Coverage for downtify/hand_replaced.py: 98%
42 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Files whose audio an admin replaced by hand, kept from being overwritten.
3**Replace audio** (a version picked on YouTube, a SoundCloud link, or an
4audio file uploaded from the admin's own computer) puts the right audio
5in a library file. With **Download again if the file exists** on, the
6next download of the same song - from another monitored playlist, an
7artist watch, a playlist download - would write over it with whatever
8the automatic match finds, which is how a wrong version comes back
9(issue #582).
11So each replacement is remembered here, by library path, and the
12downloader leaves those files alone: a download that would land on one
13counts as "already downloaded" instead (see
14``Downloader._hand_replaced_at``). Library upgrade's audio replacement
15skips them too. The admin can lift it from the Replace audio dialog.
17A file swapped on disk, outside Downtify, is added here too the first
18time a download would land on it (``Downloader._replaced_on_disk``).
19"""
21from __future__ import annotations
23import time
24from pathlib import Path
25from typing import Any, Optional
27from .db.config import Dialect
28from .db.core import Database, as_database
30#: Where the new audio came from. ``disk``: the file was swapped outside
31#: Downtify (noticed by ``downtify/download_sources.py``: its audio is no
32#: longer what Downtify wrote).
33SOURCES = ('youtube', 'soundcloud', 'file', 'disk')
36def _key(file: str) -> str:
37 return str(file or '').replace('\\', '/').strip('/')
40class HandReplacedFiles:
41 """Library files (as stored: relative to the downloads folder, or
42 ``slskd/...``) whose audio was replaced by hand."""
44 def __init__(self, path_or_db: str | Path | Database) -> None:
45 self.db = as_database(path_or_db, 'library')
46 self._path = None if self.db.path is None else str(self.db.path)
47 # The Postgres schema is created by migrations; only SQLite needs DDL.
48 if self.db.dialect is Dialect.SQLITE:
49 with self._connect() as conn:
50 conn.execute("""
51 CREATE TABLE IF NOT EXISTS hand_replaced_files (
52 file TEXT PRIMARY KEY,
53 source TEXT NOT NULL,
54 replaced_at REAL NOT NULL
55 )
56 """)
58 def _connect(self):
59 return self.db.connect()
61 def mark(self, file: str, source: str) -> None:
62 """Remember that *file*'s audio was just replaced from *source*."""
64 if source not in SOURCES:
65 raise ValueError(f'unknown source {source!r}')
66 with self._connect() as conn:
67 conn.execute(
68 """INSERT INTO hand_replaced_files (file, source, replaced_at)
69 VALUES (?, ?, ?)
70 ON CONFLICT(file) DO UPDATE SET
71 source = excluded.source,
72 replaced_at = excluded.replaced_at""",
73 (_key(file), source, time.time()),
74 )
76 def get(self, file: str) -> Optional[dict[str, Any]]:
77 """``{file, source, replaced_at}`` for a protected file, else
78 ``None``."""
80 with self._connect() as conn:
81 row = conn.execute(
82 'SELECT file, source, replaced_at FROM hand_replaced_files '
83 'WHERE file = ?',
84 (_key(file),),
85 ).fetchone()
86 return dict(row) if row else None
88 def protected(self, file: str) -> bool:
89 return self.get(file) is not None
91 def forget(self, file: str) -> bool:
92 """Let downloads overwrite *file* again. Whether it was kept."""
94 with self._connect() as conn:
95 cursor = conn.execute(
96 'DELETE FROM hand_replaced_files WHERE file = ?',
97 (_key(file),),
98 )
99 return cursor.rowcount > 0
101 def rename(self, old: str, new: str) -> None:
102 """*old* is now *new* (a merge or a move kept the replacement)."""
104 if _key(old) == _key(new):
105 return
106 with self._connect() as conn:
107 # SQLite's ``UPDATE OR REPLACE``, spelled portably.
108 conn.execute(
109 'DELETE FROM hand_replaced_files WHERE file = ? AND '
110 'EXISTS (SELECT 1 FROM hand_replaced_files WHERE file = ?)',
111 (_key(new), _key(old)),
112 )
113 conn.execute(
114 'UPDATE hand_replaced_files SET file = ? WHERE file = ?',
115 (_key(new), _key(old)),
116 )
118 def count(self) -> int:
119 with self._connect() as conn:
120 return int(
121 conn.execute(
122 'SELECT COUNT(*) FROM hand_replaced_files'
123 ).fetchone()[0]
124 )