Coverage for downtify/playlist_shares.py: 100%

161 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Who besides its owner may see a playlist, and who may edit its songs. 

2 

3Every playlist is private to its owner (and admins) until the owner 

4shares it: with named users (``shared``) or with everyone on the server 

5(``public``). A viewer can play it, follow a public one so it stays in 

6their sidebar, and save a copy. Some of the named users of a Library 

7playlist can also be its editors: they add and remove its songs, while 

8renaming, sharing and deleting stay with the owner. The owner is whoever 

9the playlist catalog or the Library-playlist owners table says (see 

10``downtify.playlist_catalog``); this module only records the sharing, by 

11casefolded playlist name like those tables. 

12""" 

13 

14from __future__ import annotations 

15 

16from collections.abc import Iterable 

17from contextlib import AbstractContextManager 

18from dataclasses import dataclass, field 

19from pathlib import Path 

20from typing import Optional 

21 

22from .db.config import Dialect 

23from .db.core import Connection, Database, as_database 

24from .db.dialect import column_names 

25 

26PRIVATE = 'private' 

27SHARED = 'shared' 

28PUBLIC = 'public' 

29VISIBILITIES = (PRIVATE, SHARED, PUBLIC) 

30 

31#: The tables keyed by playlist name, in the order they are rewritten. 

32_TABLES = ( 

33 'playlist_shares', 

34 'playlist_share_users', 

35 'playlist_follows', 

36 'playlist_editors', 

37 'playlist_favorites', 

38) 

39 

40#: Primary key of each table in ``_TABLES`` (used by ``restore``). 

41_PRIMARY_KEYS = { 

42 'playlist_shares': ('name_key',), 

43 'playlist_share_users': ('name_key', 'user_id'), 

44 'playlist_follows': ('user_id', 'name_key'), 

45 'playlist_editors': ('name_key', 'user_id'), 

46 'playlist_favorites': ('user_id', 'name_key'), 

47} 

48 

49#: The column besides ``name_key`` that makes up each table's key, if any. 

50_OTHER_KEY = { 

51 'playlist_shares': None, 

52 'playlist_share_users': 'user_id', 

53 'playlist_follows': 'user_id', 

54 'playlist_editors': 'user_id', 

55 'playlist_favorites': 'user_id', 

56} 

57 

58 

59def share_key(name: str) -> str: 

60 return str(name or '').strip().casefold() 

61 

62 

63@dataclass(frozen=True) 

64class ShareView: 

65 """What one user is shown of other people's playlists.""" 

66 

67 #: Casefolded names of every public playlist. 

68 public: frozenset[str] = frozenset() 

69 #: ``{name: seen}`` for playlists shared with this user by name. 

70 to_me: dict[str, bool] = field(default_factory=dict) 

71 #: Public playlists this user follows. 

72 followed: frozenset[str] = frozenset() 

73 

74 

75class PlaylistShares: 

76 """Visibility, the share list, editors and follows, in the library 

77 database.""" 

78 

79 def __init__(self, path_or_db: str | Path | Database) -> None: 

80 self.db = as_database(path_or_db, 'library') 

81 if isinstance(path_or_db, Database): 

82 self._path = str(self.db.path) if self.db.path else None 

83 else: 

84 self._path = str(path_or_db) 

85 self._init_db() 

86 

87 def _connect(self) -> AbstractContextManager[Connection]: 

88 return self.db.connect() 

89 

90 def _init_db(self) -> None: 

91 # On PostgreSQL the library migrations already created the schema. 

92 if self.db.dialect is not Dialect.SQLITE: 

93 return 

94 with self._connect() as conn: 

95 conn.execute(""" 

96 CREATE TABLE IF NOT EXISTS playlist_shares ( 

97 name_key TEXT PRIMARY KEY, 

98 visibility TEXT NOT NULL DEFAULT 'private' 

99 ) 

100 """) 

101 conn.execute(""" 

102 CREATE TABLE IF NOT EXISTS playlist_share_users ( 

103 name_key TEXT NOT NULL, 

104 user_id INTEGER NOT NULL, 

105 seen INTEGER NOT NULL DEFAULT 0, 

106 PRIMARY KEY (name_key, user_id) 

107 ) 

108 """) 

109 conn.execute(""" 

110 CREATE TABLE IF NOT EXISTS playlist_follows ( 

111 user_id INTEGER NOT NULL, 

112 name_key TEXT NOT NULL, 

113 PRIMARY KEY (user_id, name_key) 

114 ) 

115 """) 

116 conn.execute(""" 

117 CREATE TABLE IF NOT EXISTS playlist_editors ( 

118 name_key TEXT NOT NULL, 

119 user_id INTEGER NOT NULL, 

120 PRIMARY KEY (name_key, user_id) 

121 ) 

122 """) 

123 conn.execute(""" 

124 CREATE TABLE IF NOT EXISTS playlist_display_names ( 

125 identity TEXT PRIMARY KEY, 

126 display_name TEXT NOT NULL 

127 ) 

128 """) 

129 conn.execute(""" 

130 CREATE TABLE IF NOT EXISTS playlist_favorites ( 

131 user_id INTEGER NOT NULL, 

132 name_key TEXT NOT NULL, 

133 PRIMARY KEY (user_id, name_key) 

134 ) 

135 """) 

136 

137 def favorites(self, user_id: int) -> frozenset[str]: 

138 """Favorites are personal preferences, never permission grants.""" 

139 with self._connect() as conn: 

140 return frozenset( 

141 str(row['name_key']) 

142 for row in conn.execute( 

143 'SELECT name_key FROM playlist_favorites WHERE user_id = ?', 

144 (int(user_id),), 

145 ) 

146 ) 

147 

148 def set_favorite(self, user_id: int, name: str, favorite: bool) -> None: 

149 key = share_key(name) 

150 if not key or not user_id: 

151 raise ValueError('A user and playlist are required') 

152 with self._connect() as conn: 

153 if favorite: 

154 conn.execute( 

155 'INSERT INTO playlist_favorites ' 

156 '(user_id, name_key) VALUES (?, ?) ' 

157 'ON CONFLICT DO NOTHING', 

158 (int(user_id), key), 

159 ) 

160 else: 

161 conn.execute( 

162 'DELETE FROM playlist_favorites WHERE user_id = ? ' 

163 'AND name_key = ?', 

164 (int(user_id), key), 

165 ) 

166 

167 def display_names(self) -> dict[str, str]: 

168 with self._connect() as conn: 

169 return { 

170 str(row['identity']): str(row['display_name']) 

171 for row in conn.execute('SELECT * FROM playlist_display_names') 

172 } 

173 

174 def set_display_name(self, identity: str, display_name: str) -> None: 

175 with self._connect() as conn: 

176 if display_name: 

177 conn.execute( 

178 'INSERT INTO playlist_display_names (identity, display_name) ' 

179 'VALUES (?, ?) ON CONFLICT(identity) DO UPDATE SET ' 

180 'display_name = excluded.display_name', 

181 (identity, display_name), 

182 ) 

183 else: 

184 conn.execute( 

185 'DELETE FROM playlist_display_names WHERE identity = ?', 

186 (identity,), 

187 ) 

188 

189 # Reading 

190 

191 def visibility(self, name: str) -> str: 

192 with self._connect() as conn: 

193 row = conn.execute( 

194 'SELECT visibility FROM playlist_shares WHERE name_key = ?', 

195 (share_key(name),), 

196 ).fetchone() 

197 return row['visibility'] if row else PRIVATE 

198 

199 def visibility_map(self) -> dict[str, str]: 

200 """``{name key: visibility}`` for playlists that aren't private.""" 

201 

202 with self._connect() as conn: 

203 rows = conn.execute( 

204 'SELECT name_key, visibility FROM playlist_shares ' 

205 'WHERE visibility != ?', 

206 (PRIVATE,), 

207 ).fetchall() 

208 return {str(row['name_key']): str(row['visibility']) for row in rows} 

209 

210 def shared_users(self) -> dict[str, list[int]]: 

211 """``{name key: [user ids]}`` for playlists shared by name.""" 

212 

213 with self._connect() as conn: 

214 rows = conn.execute( 

215 'SELECT name_key, user_id FROM playlist_share_users ' 

216 'ORDER BY user_id' 

217 ).fetchall() 

218 shared: dict[str, list[int]] = {} 

219 for row in rows: 

220 shared.setdefault(str(row['name_key']), []).append( 

221 int(row['user_id']) 

222 ) 

223 return shared 

224 

225 def editors(self) -> dict[str, list[int]]: 

226 """``{name key: [user ids]}``: who may add and remove the songs of 

227 a playlist shared with them by name.""" 

228 

229 with self._connect() as conn: 

230 rows = conn.execute( 

231 'SELECT name_key, user_id FROM playlist_editors ' 

232 'ORDER BY user_id' 

233 ).fetchall() 

234 editors: dict[str, list[int]] = {} 

235 for row in rows: 

236 editors.setdefault(str(row['name_key']), []).append( 

237 int(row['user_id']) 

238 ) 

239 return editors 

240 

241 def view_for(self, user_id: int) -> ShareView: 

242 """Public playlists, those shared with *user_id*, and the public 

243 ones they follow (a playlist that stopped being public is no 

244 longer followed).""" 

245 

246 with self._connect() as conn: 

247 public = { 

248 str(row['name_key']) 

249 for row in conn.execute( 

250 'SELECT name_key FROM playlist_shares ' 

251 'WHERE visibility = ?', 

252 (PUBLIC,), 

253 ) 

254 } 

255 shared = { 

256 str(row['name_key']): bool(row['seen']) 

257 for row in conn.execute( 

258 'SELECT u.name_key, u.seen FROM playlist_share_users u ' 

259 'JOIN playlist_shares s ON s.name_key = u.name_key ' 

260 'WHERE u.user_id = ? AND s.visibility = ?', 

261 (int(user_id), SHARED), 

262 ) 

263 } 

264 followed = { 

265 str(row['name_key']) 

266 for row in conn.execute( 

267 'SELECT name_key FROM playlist_follows WHERE user_id = ?', 

268 (int(user_id),), 

269 ) 

270 } 

271 return ShareView( 

272 frozenset(public), shared, frozenset(followed & public) 

273 ) 

274 

275 # Changing 

276 

277 def set_visibility( 

278 self, 

279 name: str, 

280 visibility: str, 

281 user_ids: Iterable[int] = (), 

282 editors: Optional[Iterable[int]] = None, 

283 ) -> None: 

284 """Make *name* ``private``, ``public`` or ``shared`` with exactly 

285 *user_ids*. Users already on the list keep whether they opened it; 

286 anyone new has not. Following only makes sense while public. 

287 

288 *editors* replaces who of *user_ids* may also edit its songs 

289 (``None`` keeps them); only users on the list can be editors, so 

290 dropping someone from it, or the playlist leaving ``shared``, ends 

291 their editing too.""" 

292 

293 key = share_key(name) 

294 if not key or visibility not in VISIBILITIES: 

295 raise ValueError('Unknown visibility') 

296 wanted = ( 

297 {int(uid) for uid in user_ids if int(uid) > 0} 

298 if visibility == SHARED 

299 else set() 

300 ) 

301 with self._connect() as conn: 

302 if visibility == PRIVATE: 

303 conn.execute( 

304 'DELETE FROM playlist_shares WHERE name_key = ?', (key,) 

305 ) 

306 else: 

307 conn.execute( 

308 'INSERT INTO playlist_shares (name_key, visibility) ' 

309 'VALUES (?, ?) ON CONFLICT(name_key) DO UPDATE SET ' 

310 'visibility = excluded.visibility', 

311 (key, visibility), 

312 ) 

313 have = { 

314 int(row['user_id']) 

315 for row in conn.execute( 

316 'SELECT user_id FROM playlist_share_users ' 

317 'WHERE name_key = ?', 

318 (key,), 

319 ) 

320 } 

321 for uid in have - wanted: 

322 conn.execute( 

323 'DELETE FROM playlist_share_users ' 

324 'WHERE name_key = ? AND user_id = ?', 

325 (key, uid), 

326 ) 

327 for uid in wanted - have: 

328 conn.execute( 

329 'INSERT INTO playlist_share_users ' 

330 '(name_key, user_id, seen) VALUES (?, ?, 0)', 

331 (key, uid), 

332 ) 

333 if editors is None: 

334 editors = [ 

335 int(row['user_id']) 

336 for row in conn.execute( 

337 'SELECT user_id FROM playlist_editors ' 

338 'WHERE name_key = ?', 

339 (key,), 

340 ) 

341 ] 

342 conn.execute( 

343 'DELETE FROM playlist_editors WHERE name_key = ?', (key,) 

344 ) 

345 conn.executemany( 

346 'INSERT INTO playlist_editors (name_key, user_id) ' 

347 'VALUES (?, ?)', 

348 [ 

349 (key, uid) 

350 for uid in sorted({int(uid) for uid in editors} & wanted) 

351 ], 

352 ) 

353 if visibility != PUBLIC: 

354 conn.execute( 

355 'DELETE FROM playlist_follows WHERE name_key = ?', (key,) 

356 ) 

357 

358 def follow(self, user_id: int, name: str, followed: bool = True) -> None: 

359 key = share_key(name) 

360 if not key or not user_id: 

361 return 

362 with self._connect() as conn: 

363 if followed: 

364 conn.execute( 

365 'INSERT INTO playlist_follows ' 

366 '(user_id, name_key) VALUES (?, ?) ' 

367 'ON CONFLICT DO NOTHING', 

368 (int(user_id), key), 

369 ) 

370 else: 

371 conn.execute( 

372 'DELETE FROM playlist_follows ' 

373 'WHERE user_id = ? AND name_key = ?', 

374 (int(user_id), key), 

375 ) 

376 

377 def mark_seen(self, name: str, user_id: int) -> None: 

378 with self._connect() as conn: 

379 conn.execute( 

380 'UPDATE playlist_share_users SET seen = 1 ' 

381 'WHERE name_key = ? AND user_id = ?', 

382 (share_key(name), int(user_id)), 

383 ) 

384 

385 def rename(self, name: str, new_name: str) -> None: 

386 """Carry the sharing over when its playlist is renamed.""" 

387 

388 old, new = share_key(name), share_key(new_name) 

389 if not old or not new or old == new: 

390 return 

391 with self._connect() as conn: 

392 for table in _TABLES: 

393 # Same effect as ``UPDATE OR REPLACE``: rows already under 

394 # the new name that would collide with a moved row go. 

395 other = _OTHER_KEY[table] 

396 if other is None: 

397 conn.execute( 

398 f'DELETE FROM {table} WHERE name_key = ?', (new,) 

399 ) 

400 else: 

401 conn.execute( 

402 f'DELETE FROM {table} WHERE name_key = ? ' 

403 f'AND {other} IN (SELECT {other} FROM {table} ' 

404 'WHERE name_key = ?)', 

405 (new, old), 

406 ) 

407 conn.execute( 

408 f'UPDATE {table} SET name_key = ? WHERE name_key = ?', 

409 (new, old), 

410 ) 

411 

412 def forget(self, name: str) -> None: 

413 """Drop all sharing of a playlist that is gone or detached from 

414 its owner.""" 

415 

416 key = share_key(name) 

417 with self._connect() as conn: 

418 for table in _TABLES: 

419 conn.execute(f'DELETE FROM {table} WHERE name_key = ?', (key,)) 

420 

421 def snapshot(self, name: str) -> dict[str, list[tuple]]: 

422 """Capture rows removed by :meth:`forget` for a failed create rollback.""" 

423 

424 key = share_key(name) 

425 with self._connect() as conn: 

426 return { 

427 table: [ 

428 tuple(row) 

429 for row in conn.execute( 

430 f'SELECT * FROM {table} WHERE name_key = ?', (key,) 

431 ).fetchall() 

432 ] 

433 for table in _TABLES 

434 } 

435 

436 def restore(self, name: str, snapshot: dict[str, list[tuple]]) -> None: 

437 """Restore a snapshot captured before a failed creation attempt.""" 

438 

439 with self._connect() as conn: 

440 for table in _TABLES: 

441 rows = snapshot.get(table, []) 

442 if not rows: 

443 continue 

444 columns = column_names(conn, table) 

445 marks = ', '.join('?' for _ in columns) 

446 pk = _PRIMARY_KEYS[table] 

447 changed = [col for col in columns if col not in pk] 

448 if changed: 

449 sets = ', '.join( 

450 f'{col} = excluded.{col}' for col in changed 

451 ) 

452 action = f'DO UPDATE SET {sets}' 

453 else: 

454 action = 'DO NOTHING' 

455 conn.executemany( 

456 f'INSERT INTO {table} ' 

457 f'({", ".join(columns)}) VALUES ({marks}) ' 

458 f'ON CONFLICT ({", ".join(pk)}) {action}', 

459 rows, 

460 ) 

461 

462 def remove_user(self, user_id: int) -> None: 

463 """A deleted account's follows, and being on anyone's list.""" 

464 

465 with self._connect() as conn: 

466 conn.execute( 

467 'DELETE FROM playlist_editors WHERE user_id = ?', 

468 (int(user_id),), 

469 ) 

470 conn.execute( 

471 'DELETE FROM playlist_favorites WHERE user_id = ?', 

472 (int(user_id),), 

473 ) 

474 conn.execute( 

475 'DELETE FROM playlist_follows WHERE user_id = ?', 

476 (int(user_id),), 

477 ) 

478 conn.execute( 

479 'DELETE FROM playlist_share_users WHERE user_id = ?', 

480 (int(user_id),), 

481 )