Skip to content
Merged
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ FIRST_RUN=true
# Ask GitHub (anonymously, at most hourly) whether a newer build exists;
# admins then see "Update available" under the sidebar. Sends no library data.
UPDATE_CHECK=true
# The nightly DB backup (data/backups) keeps users' Plex tokens out and is
# 0600 like the database; true makes it 0640, readable by the app's group
# (a NAS user in that group copying backups off a share).
BACKUP_GROUP_READABLE=false
# Also keep one snapshot of the caches and the vector store with the nightly
# backup (~2 GB on a large library; they are rebuilt from their sources).
BACKUP_CACHES=false

# ── Security (required) ────────────────────────────────────────────────────
# Long random string; the setup wizard generates one for you.
Expand Down
24 changes: 23 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,29 @@ Condensed release history, newest first.

## Unreleased

Nothing yet.
**One song played is one play.** Plex gives every copy of a track in the library (the album, the
remaster, a compilation) the same "last played" second while its history holds one play, and a song
stored from the library listing and from the history landed twice when the two stamps lay more than
90 seconds apart (a song's two ends; the rule was made for video). Per song and second one copy is
kept now (the one with genres), a song's same-play window is its length, and a one-time repair takes
the copies out of what was stored: on the owner's server 8,577 rows of about 400,000, Spotify plays
and video untouched. The taste profile had counted them.

**Backups carry no tokens, and the cache snapshot is opt-in.** The nightly DB backup blanks the
users' Plex tokens in its copy (overwriting their bytes); a restore asks each member to sign in once,
the way Plex keeps its token out of its own database backups. Backups stay 0600 like the database;
`BACKUP_GROUP_READABLE=true` makes them 0640 for a NAS user in the app's group, and the start-up pass
no longer undoes that. The cache and vector-store snapshot from 1.2.0 is off by default now
(`BACKUP_CACHES=true` keeps it); switched off, the snapshot already written is removed. Like the
other self-hosted apps, the backup holds what cannot be rebuilt: the database.

**LAN apps keep to their own address, port included.** The setup's logo fetch and the arr
discovery follow a redirect only on the app's own scheme, host and port (one NAS, an app per port).
SoulSync's logo shows again: its icon link carries a `?v=` query, which the address check refused.

**From the bots:** the setup wizard moves focus to the new step's heading, the arr discovery checks
each redirect hop, and the Wrap-Up's comebacks find a title's last earlier play through the title
indexes.

---

Expand Down
4 changes: 3 additions & 1 deletion docs/screenshots/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ python scripts/demo/build_demo.py --source <the live install's data folder>
as the database, and the nightly cache snapshot (`backups/caches`: the
enrichment cache, music index, lyrics, anime maps and the vector store),
both made with SQLite's backup API, so the demo has today's library and
today's schema. A running install's own files are never copied: they
today's schema. The source install needs `BACKUP_CACHES=true` in its
`.env` (the snapshot is off by default) and, to copy backups off a share,
`BACKUP_GROUP_READABLE=true`. A running install's own files are never copied: they
are open, and a share refuses them. Each copied database is checked.
3. **Its own `.env`:** a fresh JWT secret; from your `.env` only the model
names, Ollama, the metadata keys, and Radarr/Sonarr (read only, for the
Expand Down
8 changes: 6 additions & 2 deletions scripts/demo/build_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
backup API and integrity-checked) becomes the demo's database, so the demo
always has today's library and today's schema, never an old copy that is
missing columns. CURATARR_DEMO_SOURCE may hold it instead of --source.
The source install needs BACKUP_CACHES=true (the cache snapshot) and, to
read its backups over a share as a member of the app's group,
BACKUP_GROUP_READABLE=true in its .env.

Stages, in order (--stages picks some):

Expand Down Expand Up @@ -188,8 +191,9 @@ def stage_fetch(base: Path, source: str) -> None:
# cannot be copied safely (a share refuses them outright).
snap = src / "backups" / "caches"
if not (snap / "cache").is_dir():
sys.exit(f"no cache snapshot in {snap} - it is written with the nightly DB backup; run it now "
"as the admin: Activity -> Scheduled -> DB backup -> Run now")
sys.exit(f"no cache snapshot in {snap}: set BACKUP_CACHES=true (and BACKUP_GROUP_READABLE=true "
"to copy backups off a share) in the source install's .env, then run the backup as the "
"admin: Activity -> Scheduled -> DB backup -> Run now")
for sub in ("cache", "chromadb"):
if (snap / sub).is_dir():
say(f"fetch: {sub}/ from the cache snapshot ...")
Expand Down
9 changes: 9 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,15 @@ def _blank_url_falls_back_to_default(cls, v, info):
# Ask GitHub (anonymously, hourly) whether a newer build is published;
# admins then see "Update available" under the sidebar (services/update_check.py).
UPDATE_CHECK: bool = True
# The nightly DB backup (data/backups) holds no tokens: users' Plex tokens
# are blanked in the copy. Its files are 0600 like the live database;
# true makes them 0640, readable by the app's group - for a NAS user in
# that group who copies them off a share (scripts/demo/build_demo.py).
BACKUP_GROUP_READABLE: bool = False
# Also keep ONE snapshot of the caches and the vector store next to the
# DB backup (backups/caches, ~2 GB on a large library). They are rebuilt
# from their sources; only the demo builder reads them.
BACKUP_CACHES: bool = False

# ── API surface hardening ────────────────────────────────────────────────
# Pass 97: Swagger / ReDoc are off by default. Curatarr binds to
Expand Down
54 changes: 51 additions & 3 deletions src/database/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,10 @@ def checkpoint_and_dispose() -> None:
# plays imported from Plex's history without a length count as played (2026-10-25).
# 3 = episodes marked as played one after another (seconds apart, no play event)
# are source "marked" too (2026-10-30).
SCHEMA_VERSION = 3
# 4 = music read whole from Plex once: copies of one song at one second are one
# play, and a play stored twice from the listing and the history is one
# (2026-11-15).
SCHEMA_VERSION = 4


def _migrate_columns() -> None:
Expand Down Expand Up @@ -527,6 +530,39 @@ def _migrate_columns() -> None:
" AND player IS NULL AND media_type IN ('movie', 'show', 'anime'))"
" SELECT a.id FROM v a JOIN v b ON b.user_id = a.user_id AND b.t = a.t"
" AND b.p != a.p AND b.s BETWEEN a.s - 60 AND a.s + 60)")
if schema_was < 4 and "watch_history" in tables:
# The first read of a music library stored every COPY of a
# song Plex marked at the play's second (the album, the
# remaster, a compilation): 962 rows on the owner's server,
# 628 of them parked as "marked" by the three-in-a-second
# rule. One per song and second stays - the one with genres,
# a play (not "marked") - the others go.
conn.exec_driver_sql(
"CREATE TEMP TABLE _copies AS SELECT id, "
" ROW_NUMBER() OVER (g ORDER BY COALESCE(genres, '') = '', source IS NOT NULL, id) AS rn, "
" COUNT(*) OVER g AS n, source " # g unordered: the whole group, not a running count
" FROM watch_history WHERE media_type = 'music' "
" AND (source IS NULL OR source = 'marked') "
" WINDOW g AS (PARTITION BY user_id, LOWER(COALESCE(series_title, '')), "
" LOWER(title), viewed_at)")
conn.exec_driver_sql(
"UPDATE watch_history SET source = NULL WHERE id IN "
"(SELECT id FROM _copies WHERE rn = 1 AND n > 1 AND source = 'marked')")
conn.exec_driver_sql(
"DELETE FROM watch_history WHERE id IN (SELECT id FROM _copies WHERE rn > 1)")
conn.exec_driver_sql("DROP TABLE _copies")
# One play stored twice: the listing stamps a song at one end,
# the history at the other (147 s apart for a 4-minute track),
# and the 90-second rule took them for two. A second row of the
# same song inside the first one's length is that same play.
conn.exec_driver_sql(
"DELETE FROM watch_history WHERE id IN ("
" WITH v AS (SELECT id, user_id, plex_item_id AS p,"
" CAST(strftime('%s', viewed_at) AS INTEGER) AS s,"
" COALESCE(duration_ms, 0) / 1000 AS d"
" FROM watch_history WHERE media_type = 'music' AND source IS NULL)"
" SELECT b.id FROM v a JOIN v b ON b.user_id = a.user_id AND b.p = a.p"
" AND b.s > a.s AND b.s - a.s < MAX(90, a.d))")
# Record the schema generation this boot brought the file to. A
# future one-shot backfill keys on it (``if user_version < N``)
# rather than on whether its column happened to be added just now.
Expand Down Expand Up @@ -694,8 +730,18 @@ def _rebuild_from_model(conn, table) -> None:
conn.exec_driver_sql(f'DROP TABLE "{aside}"')


def backup_modes() -> tuple:
"""(file mode, folder mode) for what the nightly backup writes: 0600/0700
like the database, or 0640/0750 when BACKUP_GROUP_READABLE opens them to
the app's group (a NAS user copying them off a share). The backups carry
no tokens (scheduler._strip_secrets); the live database and .env stay
0600 either way."""
return (0o640, 0o750) if settings.BACKUP_GROUP_READABLE else (0o600, 0o700)


def _secure_db_files() -> None:
"""Ensure SQLite files in data/ and .env are 0600 (POSIX only)."""
"""Ensure SQLite files in data/ and .env are 0600; backups follow
backup_modes() (POSIX only)."""
import os
import stat
import logging as _logging
Expand All @@ -711,10 +757,12 @@ def _secure_db_files() -> None:
if not DATA_DIR.exists():
return

backups = (DATA_DIR / "backups").resolve()
for ext in ("*.db", "*.sqlite3", "*.sqlite3-wal", "*.sqlite3-shm", "*.db-wal", "*.db-shm"):
for p in DATA_DIR.rglob(ext):
try:
os.chmod(p, stat.S_IRUSR | stat.S_IWUSR)
in_backups = backups in p.resolve().parents
os.chmod(p, backup_modes()[0] if in_backups else stat.S_IRUSR | stat.S_IWUSR)
except FileNotFoundError:
pass # a -wal/-shm sidecar checkpointed away mid-scan
except OSError as e:
Expand Down
18 changes: 5 additions & 13 deletions src/services/arr_find.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,11 @@ def which_app(html: str) -> Optional[str]:

async def _probe(client: httpx.AsyncClient, url: str) -> Optional[str]:
# An app's login redirect is followed by hand, each hop on the asked
# host and its origin through the endpoint policy, as the wizard's logo
# fetch does: the policy judged the first address, the answer names the
# next. The origin, because the login hop carries a ?returnUrl= query.
from src.services.media_server.jellyfin_connect import _allowed
from src.services.setup_icons import _get
host = httpx.URL(url).host

async def ok(hop: str) -> bool:
try:
u = httpx.URL(hop)
except (httpx.InvalidURL, ValueError, TypeError):
return False
return u.host == host and await _allowed(str(u.copy_with(path="/", query=None, fragment=None)))
# app's origin (host AND port: one NAS, an app per port) with the
# endpoint policy judging that address, as the wizard's LAN logo fetch
# does (setup_icons._lan_ok).
from src.services.setup_icons import _get, _lan_ok
ok = _lan_ok(url)

r = await _get(client, f"{url}/", ok)
if r is None or r.status_code >= 400:
Expand Down
31 changes: 28 additions & 3 deletions src/services/cache_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
enrichment work lives beside it: the enrichment cache, the music index, the
lyrics, the anime maps (data/cache/*.db) and the vector store
(data/chromadb). Weeks of API calls and GPU time, with no restore point but
a hand-made copy. After the DB backup, this keeps ONE consistent snapshot of
a hand-made copy. With BACKUP_CACHES on (off by default: they are rebuilt
from their sources), the DB backup is followed by ONE consistent snapshot of
them in backups/caches/ (the newest only: they are large and rebuilt from
the same sources):

Expand Down Expand Up @@ -93,9 +94,32 @@ def _snapshot_chroma(src: Path, dst: Path) -> int:
return n


def _set_modes(root: Path) -> None:
"""The DB backup's modes (connection.backup_modes): 0600/0700, or
0640/0750 when BACKUP_GROUP_READABLE opens backups to the app's group."""
from src.database.connection import backup_modes
fmode, dmode = backup_modes()
try:
os.chmod(root, dmode)
for p in root.rglob("*"):
os.chmod(p, dmode if p.is_dir() else fmode)
except OSError as e:
logger.debug("[backup] could not set the cache snapshot's modes: %s", e)


async def snapshot_caches(bdir: str) -> str:
"""Write backups/caches; a one-line summary for the backup task. Never
raises: the DB backup already succeeded and stands on its own."""
"""Write backups/caches when BACKUP_CACHES is on; a one-line summary for
the backup task ("" when off). Switched off, a snapshot left from before
is removed (it is ~2 GB). Never raises: the DB backup already succeeded
and stands on its own."""
from src.config import settings
if not settings.BACKUP_CACHES:
old = Path(bdir) / DIR
if old.exists():
shutil.rmtree(old, ignore_errors=True)
logger.info("[backup] cache snapshot removed (BACKUP_CACHES is off)")
return "caches: old snapshot removed (BACKUP_CACHES off)"
return ""
from src.services.scheduler import _free_bytes
from src.vector_store.chromadb_wrapper import run_chroma
base = Path(bdir)
Expand All @@ -120,6 +144,7 @@ async def snapshot_caches(bdir: str) -> str:
bad.append(p.name)
(tmp / "cache" / p.name).unlink(missing_ok=True)
files = await run_chroma(_snapshot_chroma, chroma, tmp / "chromadb") if chroma.is_dir() else 0
_set_modes(tmp)
shutil.rmtree(old, ignore_errors=True)
if final.exists():
final.rename(old)
Expand Down
54 changes: 52 additions & 2 deletions src/services/plex_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,11 @@ def _drop_dead() -> None:
item["_anilist_id"] = gid[10:]
elif gid.startswith("mal://"):
item["_mal_id"] = gid[6:]
if category == "music":
copies = drop_music_copies(items)
if copies:
logger.info("Library %r: %d copies of songs played once (same song, same "
"second) left out", sec_title, copies)
marked = mark_bulk_marked(items)
if marked:
logger.info("Library %r: %d item(s) marked as played in Plex (one second "
Expand Down Expand Up @@ -855,7 +860,7 @@ def _template(rk: str):

if entry.get("_history_extra"):
vts = int(viewed_at_ts)
if any(abs(t - vts) <= _SAME_PLAY_S for t in near.get((user.id, rating_key), ())):
if any(abs(t - vts) <= _same_play_s(entry) for t in near.get((user.id, rating_key), ())):
skipped += 1
continue
if not entry.get("duration") or not entry.get("Genre"):
Expand Down Expand Up @@ -1338,6 +1343,44 @@ def follow_libraries(section_keys: list) -> None:
_MARKED_MIN = 3


def _song_key(artist, title) -> tuple:
return ((artist or "").strip().lower(), (title or "").strip().lower())


def drop_music_copies(items: list) -> int:
"""One song played, every copy of it marked: Plex gives each copy of a
track in the library (the album, the remaster, a compilation) the same
lastViewedAt second, while its history holds one play. The owner's
first music read stored 962 such copies (2026-11-15: "Lovely Day" three
times at 00:46:51). Keep one per song and second - the one Plex knows
a genre for - and drop the others from ``items``; returns how many."""
groups: dict = {}
for it in items:
ts = it.get("lastViewedAt")
if ts and not it.get("_in_progress"):
key = (*_song_key(it.get("grandparentTitle"), it.get("title")), int(ts))
groups.setdefault(key, []).append(it)
drop = set()
for group in groups.values():
if len(group) > 1:
keep = next((it for it in group if it.get("Genre")), group[0])
drop.update(id(it) for it in group if it is not keep)
if drop:
items[:] = [it for it in items if id(it) not in drop]
return len(drop)


def _same_play_s(entry: dict) -> int:
"""How far apart the listing's and the history's stamp of ONE play may
lie. Plex truncates seconds for video; for a song the two stamps are the
start and the end of it (147 s apart for a 4-minute track, measured on
the owner's server), so the window is the song's length."""
if entry.get("type") == "track" or entry.get("_category") == "music":
# a history event carries no length: a song's typical one
return max(_SAME_PLAY_S, int(entry.get("duration") or 360_000) // 1000)
return _SAME_PLAY_S


def mark_bulk_marked(items: list) -> int:
"""Flag the listed items whose lastViewedAt they share with at least
``_MARKED_MIN - 1`` others of the same library (``_marked``)."""
Expand Down Expand Up @@ -1398,19 +1441,26 @@ def _owner_history_entries(events: list, lib_configs: dict, listing: list,
Events older than ``backfill_before`` are marked ``_backfill``:
recovered history, not news."""
listed: dict = {}
songs: dict = {}
for e in listing:
ts = e.get("lastViewedAt") or e.get("viewedAt")
if e.get("ratingKey") and ts:
listed.setdefault(str(e["ratingKey"]), []).append((int(ts), e))
if e.get("_category") == "music":
songs.setdefault(_song_key(e.get("grandparentTitle"), e.get("title")), []).append((int(ts), e))
out: list = []
for ev in events:
base = _member_entry(dict(zip(_HISTORY_EVENT_KEYS, ev)), lib_configs, 1)
if base is None:
continue
vts = base["viewedAt"]
same = listed.get(base["ratingKey"], ())
if any(abs(t - vts) <= _SAME_PLAY_S for t, _ in same):
if any(abs(t - vts) <= _same_play_s(e) for t, e in same):
continue
if base["_category"] == "music" and any(
abs(t - vts) <= _same_play_s(e)
for t, e in songs.get(_song_key(base.get("grandparentTitle"), base.get("title")), ())):
continue # the play of another copy of this song, already listed
if same:
entry = {k: v for k, v in same[0][1].items() if k not in _LISTING_ONLY_KEYS}
entry.update(lastViewedAt=vts, viewedAt=vts)
Expand Down
Loading
Loading