windarr 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
windarr/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """windarr: keep every user's TV a few episodes ahead in Sonarr, within the room on their own volume."""
2
+
3
+ __version__ = "0.1.1"
windarr/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
windarr/apps.py ADDED
@@ -0,0 +1,211 @@
1
+ """Sonarr, Radarr, Seerr, Jellyfin: connecting to them, and the data a run gathers from them."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import time
7
+ from . import settings, util, clients, downloads
8
+
9
+
10
+ def default_server(servers, name="Sonarr/Radarr"):
11
+ """Seerr's default non-4K server entry for an app; None when Seerr has no server for it at all.
12
+ Servers but none of them the default non-4K one is an error: otherwise everything for that app
13
+ (and what the windows held back in it) would be dropped without a word."""
14
+ if not servers:
15
+ return None
16
+ c = next((s for s in servers if s.get("isDefault") and not s.get("is4k")), None)
17
+ if c is None:
18
+ raise util.SetupProblem({f"seerr:{name.lower()}:default-server":
19
+ f"Seerr has {name} servers but none is the default non-4K one (Settings > Services)"})
20
+ return c
21
+
22
+
23
+ def make_apis():
24
+ # Sonarr/Radarr connection details and the API keys come from Seerr's settings (on macOS,
25
+ # launchd jobs can be blocked from reading other apps' folders in ~/Library/Application Support)
26
+ with open(settings.SEERR_SETTINGS) as f:
27
+ seerr = json.load(f)
28
+
29
+ def arr(name, servers):
30
+ c = default_server(servers, name)
31
+ if c is None:
32
+ return None # not set up in Seerr: the other one does on its own
33
+ base = f"{'https' if c.get('useSsl') else 'http'}://{c['hostname']}:{c['port']}{c.get('baseUrl') or ''}/api/v3"
34
+ return util.Api(name, base, {"X-Api-Key": c["apiKey"]})
35
+
36
+ sonarr, radarr = arr("Sonarr", seerr.get("sonarr")), arr("Radarr", seerr.get("radarr"))
37
+ if sonarr is None and radarr is None:
38
+ raise util.SetupProblem({"seerr:no-server": "Seerr has no Sonarr or Radarr server (Settings > Services): "
39
+ "windarr needs at least one"})
40
+ adapters, adapter_problems = clients.build(settings.CLIENT_OPTIONS)
41
+ return {
42
+ "sonarr": sonarr, # None without Sonarr (movies only)
43
+ "radarr": radarr, # None without Radarr (TV only)
44
+ "seerr": util.Api("Seerr", f"{settings.SEERR_URL}/api/v1", {"X-Api-Key": seerr["main"]["apiKey"]}),
45
+ "clients": adapters, # implementation name -> adapter (run() picks the ones in use)
46
+ "client_problems": adapter_problems, # installed adapters that can't be used (run() reports them)
47
+ "jf": util.Api("Jellyfin", settings.JELLYFIN_URL, # Jellyfin reads the first header, Emby the second
48
+ {"Authorization": f'MediaBrowser Token="{seerr["jellyfin"]["apiKey"]}"',
49
+ "X-Emby-Token": seerr["jellyfin"]["apiKey"]}),
50
+ "cfg": seerr,
51
+ }
52
+
53
+
54
+ def gather(A, st):
55
+ S, R = A.get("sonarr"), A.get("radarr") # (either may be missing, not both: make_apis)
56
+ d = {
57
+ "series": S.get("/series") if S else [],
58
+ "tags": {t["label"]: t["id"] for t in S.get("/tag")} if S else {},
59
+ "queue": S.get("/queue", pageSize=5000, includeUnknownSeriesItems="true")["records"] if S else [],
60
+ "roots": root_folders(S, R),
61
+ "rqueue": R.get("/queue", pageSize=5000, includeMovie="true",
62
+ includeUnknownMovieItems="true")["records"] if R else [],
63
+ "movies": R.get("/movie") if R else [],
64
+ "rtags": {t["label"]: t["id"] for t in R.get("/tag")} if R else {},
65
+ "requests": util.paged(A["seerr"], "/request", sort="modified", filter="all"),
66
+ "played": {},
67
+ }
68
+ # TV requests in Seerr (approved or completed) per series: (requester, created, seasons, owner
69
+ # of the folder Seerr stored with it)
70
+ d["tv_requests"] = {}
71
+ for r in d["requests"]:
72
+ tvdb = (r.get("media") or {}).get("tvdbId")
73
+ if r.get("type") == "tv" and r.get("status") in (2, 5) and tvdb and not r.get("is4k"):
74
+ d["tv_requests"].setdefault(tvdb, []).append(
75
+ (util.requester(r), util.parse_ts(r.get("createdAt")), {x["seasonNumber"] for x in r.get("seasons") or []},
76
+ util.owner_of(r.get("rootFolder"))))
77
+ uids = st.get("jf_uids") or {}
78
+ for label, cfg in settings.USERS.items():
79
+ if label not in d["tags"]:
80
+ continue
81
+ name = cfg["jellyfin_user"]
82
+
83
+ def played_items():
84
+ return A["jf"].get(f"/Users/{uids[name]}/Items", Recursive="true", IncludeItemTypes="Episode",
85
+ IsPlayed="true", Fields="Path", EnableImages="false")["Items"]
86
+
87
+ def fetch_uids():
88
+ new = {u["Name"]: u["Id"] for u in A["jf"].get("/Users")}
89
+ if name not in new:
90
+ raise RuntimeError(f"Jellyfin user {name!r} not found")
91
+ return new
92
+ cached = name in uids
93
+ if not cached:
94
+ uids = fetch_uids()
95
+ try:
96
+ items = played_items()
97
+ except RuntimeError:
98
+ if not cached:
99
+ raise
100
+ uids = fetch_uids() # the saved id may be stale (user deleted and recreated: HTTP 404)
101
+ items = played_items()
102
+ d["played"][label] = sorted(util.nfc(i["Path"]) for i in items if i.get("Path"))
103
+ st["jf_uids"] = uids
104
+ # torrents on the users' volumes, finished or not: a ghost download finishing (Sonarr's queue
105
+ # doesn't show it) must trigger a full run too
106
+ vols = tuple(c["volume"] for c in settings.USERS.values())
107
+ ts = downloads.torrents(A, d)
108
+ d["torrents_fp"] = None if ts is None else sorted(
109
+ [t["hash"], t.get("progress", 0) >= 1] for t in ts if (t.get("content_path") or "").startswith(vols))
110
+ # remember played files: once Media Cleaner deletes one, Jellyfin no longer lists it, and a
111
+ # vanished file only counts as watched if its user played it (re-stamped at most daily, so the
112
+ # state file doesn't change every run)
113
+ now = time.time()
114
+ memory = st.setdefault("played_seen", {})
115
+ for label, paths in d["played"].items():
116
+ mem, cur = memory.setdefault(label, {}), set(paths)
117
+ for p in cur:
118
+ if now - mem.get(p, 0) > 86400:
119
+ mem[p] = int(now)
120
+ for p in [p for p, ts in mem.items() if p not in cur and now - ts > settings.PLAYED_MEMORY]:
121
+ mem.pop(p)
122
+ return d
123
+
124
+
125
+ def root_folders(S, R):
126
+ """The volumes' free space: Sonarr's root folders, and Radarr's for volumes (the users', the
127
+ shared one) none of Sonarr's is on (Radarr scans its root folders on every call: not asked
128
+ when it isn't needed)."""
129
+ roots = list(S.get("/rootfolder")) if S else []
130
+ vols = [c["volume"] for c in settings.USERS.values()] + ([settings.SHARED_VOLUME] if settings.SHARED_VOLUME else [])
131
+ missing = [v for v in vols if not any((r.get("path") or "").startswith(v) and r.get("freeSpace") is not None
132
+ for r in roots)]
133
+ if R and missing:
134
+ roots = roots + [r for r in R.get("/rootfolder") if (r.get("path") or "").startswith(tuple(missing))]
135
+ return roots
136
+
137
+
138
+ def fingerprint(d):
139
+ vols = tuple(c["volume"] for c in settings.USERS.values())
140
+
141
+ def gb(x):
142
+ return round((x or 0) / 1e9)
143
+
144
+ fp = {
145
+ "series": [[s["id"], s["tags"], s["monitored"], s["path"],
146
+ [[x["seasonNumber"], x["monitored"]] +
147
+ [(x.get("statistics") or {}).get(k, 0) for k in
148
+ ("episodeCount", "episodeFileCount", "totalEpisodeCount", "sizeOnDisk")]
149
+ for x in s.get("seasons", [])]] for s in d["series"]],
150
+ "queue": [[q["id"], q.get("episodeId"), q.get("status"), q.get("trackedDownloadState"), gb(q.get("sizeleft"))]
151
+ for q in d["queue"]],
152
+ "rqueue": [[q["id"], gb(q.get("sizeleft"))] for q in d["rqueue"]
153
+ if ((q.get("movie") or {}).get("path") or "").startswith(vols)],
154
+ "movies": [[m["id"], m.get("tags"), m.get("monitored"), m.get("hasFile"), m.get("isAvailable"),
155
+ gb(m.get("sizeOnDisk"))] for m in d["movies"] if (m.get("path") or "").startswith(vols)],
156
+ "roots": [[r["path"], gb(r.get("freeSpace"))] for r in d["roots"] if r["path"].startswith(vols)],
157
+ "played": d["played"],
158
+ "torrents": d.get("torrents_fp"),
159
+ "requests": [[r["id"], r.get("status"), r.get("updatedAt")] for r in d["requests"]],
160
+ }
161
+ return hashlib.sha256(json.dumps(fp, sort_keys=True).encode()).hexdigest()
162
+
163
+
164
+ def seerr_media(A, d):
165
+ """Seerr's media list, fetched once per run (callers that delete entries update the cache)."""
166
+ if "_seerr_media" not in d:
167
+ d["_seerr_media"] = util.paged(A["seerr"], "/media", filter="all")
168
+ return d["_seerr_media"]
169
+
170
+
171
+ def episodes(A, d, sid, fresh=False):
172
+ """Sonarr's episodes (with their files) of a series, fetched once per run. A step that changes
173
+ monitoring before a later step reads it updates these in place (undo_rewatch_monitoring).
174
+ fresh=True: a second copy, fetched when first asked for: the run's list can be minutes old by
175
+ then (an upgrade imported since makes an old path look deleted). Nothing updates that copy in
176
+ place: read its monitored flags only before changing them."""
177
+ cache = d.setdefault("_eps_fresh" if fresh else "_eps", {})
178
+ if sid not in cache:
179
+ cache[sid] = A["sonarr"].get("/episode", seriesId=sid, includeEpisodeFile="true")
180
+ return cache[sid]
181
+
182
+
183
+ def file_on_disk(f):
184
+ """A Sonarr/Radarr file record whose file is really there: they notice a deleted one only at
185
+ their next rescan."""
186
+ return bool(f) and os.path.exists(f.get("path") or "")
187
+
188
+
189
+ def ep_on_disk(e):
190
+ return bool(e.get("hasFile")) and file_on_disk(e.get("episodeFile"))
191
+
192
+
193
+ def movie_on_disk(m):
194
+ return bool(m.get("hasFile")) and file_on_disk(m.get("movieFile"))
195
+
196
+
197
+ def eps_on_disk(A, d, sid):
198
+ """Ids of a series' episodes with a file on disk, as of when first asked for in the run (the
199
+ window's own deletions come after every caller: ghosts, cleanup)."""
200
+ cache = d.setdefault("_eps_on_disk", {})
201
+ if sid not in cache:
202
+ cache[sid] = {e["id"] for e in episodes(A, d, sid) if ep_on_disk(e)}
203
+ return cache[sid]
204
+
205
+
206
+ def ep_map(A, d, sid):
207
+ """A series' episodes by id (the run's list, see episodes())."""
208
+ cache = d.setdefault("_ep_map", {})
209
+ if sid not in cache:
210
+ cache[sid] = {e["id"]: e for e in episodes(A, d, sid)}
211
+ return cache[sid]
windarr/checks.py ADDED
@@ -0,0 +1,153 @@
1
+ """The setup check (settings in the other apps windarr relies on) and the shared-volume push."""
2
+
3
+ import os
4
+ import time
5
+ from . import settings, util, apps
6
+
7
+
8
+ def check_setup(A, st, dry):
9
+ """The settings in other apps windarr relies on: a wrong one breaks things quietly, so run()
10
+ stops before fetching or changing anything (SetupProblem: main() pushes once per distinct set of
11
+ problems). Checked hourly, and on every run while something is wrong (the fix is picked up right
12
+ away). Returns {key: one-line message}: empty when fine or not due. When it can't finish (an app
13
+ unreachable or answering with an error): with no known problem, an outage is left to the steps
14
+ that follow; otherwise (an outage while a problem is known, or any other error) it's raised: run()
15
+ stops on it, or alerts it after the run when nothing was wrong.
16
+ Any download client Sonarr/Radarr support will do; each user needs one (tagged for them, or an
17
+ untagged one); a client with an adapter (CLIENTS) has its folders checked ahead of time
18
+ (misplaced_downloads looks at every download in the queues).
19
+ st["clients_in_use"]: the implementations Sonarr/Radarr use (run() picks the adapters from it),
20
+ st["torrents_in_use"]: whether one of them is a torrent client; st["arr_categories"]: the
21
+ categories their torrent clients with an adapter download into (and move imported torrents
22
+ to), the only torrents cleanup_downloads and resume_errored touch."""
23
+ now = time.time()
24
+ last = st.get("setup_problems") or {}
25
+ if not dry and not last and now - st.get("setup_checked", 0) < settings.SETUP_CHECK_EVERY \
26
+ and all(k in st for k in ("arr_categories", "clients_in_use", "torrent_clients_without_adapter",
27
+ "adapters_in_use")):
28
+ return {}
29
+ problems, arr_cats, used, torrents_used, unchecked = {}, set(), set(), False, set()
30
+ no_adapter = set() # "app:client name" of torrent clients without an adapter
31
+ covered = [] # (app, client, its category field) of torrent clients an adapter covers
32
+ covering = {"torrent": set(), "usenet": set()} # the adapters that cover a client in use
33
+ for adapter in A["clients"].values():
34
+ adapter.begin_check()
35
+ try:
36
+ for app, noun, catfield in (("sonarr", "Episodes", "tvCategory"), ("radarr", "Movies", "movieCategory")):
37
+ if A.get(app) is None:
38
+ continue
39
+ name = app.capitalize()
40
+ mm = A[app].get("/config/mediamanagement")
41
+ if not mm.get("copyUsingHardlinks"):
42
+ problems[f"{app}:hardlinks"] = (f"{name}: 'Use Hardlinks instead of Copy' is off (Settings > "
43
+ f"Media Management): imports become copies")
44
+ if not mm.get(f"autoUnmonitorPreviouslyDownloaded{noun}"):
45
+ problems[f"{app}:unmonitor"] = (f"{name}: 'Unmonitor Deleted {noun}' is off (Settings > Media "
46
+ f"Management): watched ones get downloaded again")
47
+ if not A[app].get("/config/downloadclient").get("enableCompletedDownloadHandling"):
48
+ problems[f"{app}:cdh"] = (f"{name}: 'Completed Download Handling' is off (Settings > Download "
49
+ f"Clients): nothing gets imported")
50
+ dl_clients = [c for c in A[app].get("/downloadclient") if c.get("enable")]
51
+ for c in dl_clients:
52
+ used.add(c.get("implementation"))
53
+ torrents_used |= c.get("protocol") == "torrent"
54
+ adapter = A["clients"].get(c.get("implementation"))
55
+ if adapter is not None and adapter.kind == c.get("protocol") and adapter.covers(c):
56
+ covering[adapter.kind].add(c.get("implementation"))
57
+ if adapter.kind == "torrent":
58
+ covered.append((app, c, catfield)) # (if its adapter is the one used: below)
59
+ elif c.get("protocol") == "torrent":
60
+ no_adapter.add(f"{app}:{c.get('name')}")
61
+ roots = [r.get("path") or "" for r in A[app].get("/rootfolder")]
62
+ tags = {t.get("label"): t.get("id") for t in A[app].get("/tag")}
63
+ for label, cfg in settings.USERS.items():
64
+ vol = cfg["volume"]
65
+ if label not in tags:
66
+ continue
67
+ if not any(r.startswith(vol) for r in roots):
68
+ problems[f"{app}:{label}:root"] = f"{name}: no root folder on {vol}"
69
+ # the clients for a user's titles, per protocol as Sonarr/Radarr pick them: those
70
+ # tagged for the user, else that protocol's untagged ones
71
+ mine = []
72
+ for proto in {c.get("protocol") for c in dl_clients}:
73
+ same = [c for c in dl_clients if c.get("protocol") == proto]
74
+ mine += [c for c in same if tags[label] in (c.get("tags") or [])] or \
75
+ [c for c in same if not c.get("tags")]
76
+ if not mine:
77
+ problems[f"{app}:{label}:client"] = (f"{name}: no enabled download client tagged '{label}' "
78
+ f"(or untagged, for a user with none of their own)")
79
+ for c in mine:
80
+ cat = util.client_fields(c).get(catfield) or ""
81
+ adapter = A["clients"].get(c.get("implementation"))
82
+ if adapter is None or adapter.kind != c.get("protocol") or not adapter.covers(c):
83
+ unchecked.add(c.get("name") or c.get("implementation") or "?") # (its folders can't be read here)
84
+ else:
85
+ adapter.check(label, cfg, cat, problems)
86
+ if A.get("sonarr") and not apps.default_server(A["cfg"]["sonarr"]).get("preventSearch"):
87
+ problems["seerr:search"] = ("Seerr: 'Enable Automatic Search' is on for Sonarr (Settings > Services): "
88
+ "requests get searched all at once")
89
+ for label, cfg in settings.USERS.items():
90
+ try:
91
+ who = A["seerr"].get(f"/user/{cfg['seerr_id']}").get("jellyfinUsername")
92
+ except RuntimeError as e:
93
+ if "HTTP 404" not in str(e):
94
+ raise # Seerr answered with an error: can't tell, not "missing"
95
+ who = None
96
+ if who != cfg["jellyfin_user"]:
97
+ problems[f"seerr:user:{label}"] = (f"Seerr user {cfg['seerr_id']} is {who or 'missing'}, not "
98
+ f"{cfg['jellyfin_user']} ([users.{label}] seerr_id in the config)")
99
+ except util.Outage:
100
+ if last:
101
+ raise # can't tell if it's fixed: the run stops as an outage (its own alert)
102
+ return {} # reported as an outage by the steps that follow
103
+ # one adapter per kind is used: the first (built-ins first) that covers a client in use. Another
104
+ # torrent adapter's clients count as clients without one (their re-grabs are pushed instead)
105
+ in_use = {kind: next((impl for impl, a in A["clients"].items() if a.kind == kind and impl in covering[kind]), None)
106
+ for kind in ("torrent", "usenet")}
107
+ for app, c, catfield in covered:
108
+ if c.get("implementation") != in_use["torrent"]:
109
+ no_adapter.add(f"{app}:{c.get('name')}")
110
+ continue
111
+ fields = util.client_fields(c)
112
+ imported = catfield.replace("Category", "ImportedCategory") # post-import category
113
+ arr_cats |= {v for v in (fields.get(catfield), fields.get(imported)) if v}
114
+ sab = A["clients"].get("Sabnzbd")
115
+ sab_unreadable = bool(settings.SAB_INI and sab and sab.read and sab.dirs is None)
116
+ if sab_unreadable and not st.get("setup_sab_unreadable"):
117
+ util.log(f"(SABnzbd's config {settings.SAB_INI} can't be read here: its category folders aren't checked)", dry)
118
+ if unchecked and st.get("setup_unchecked") != sorted(unchecked):
119
+ util.log(f"(download client(s) {', '.join(sorted(unchecked))}: their folders can't be checked here; make sure "
120
+ f"each user's downloads land on their volume)", dry)
121
+ st["setup_unchecked"] = sorted(unchecked)
122
+ st["arr_categories"] = sorted(arr_cats) # (in a dry run too: its cleanup preview needs them)
123
+ st["clients_in_use"], st["torrents_in_use"] = sorted(x for x in used if x), torrents_used
124
+ st["torrent_clients_without_adapter"] = sorted(no_adapter)
125
+ st["adapters_in_use"] = in_use # (clients.client_adapters)
126
+ st.pop("qbit_in_use", None) # (its forerunner)
127
+ if not dry:
128
+ st["setup_sab_unreadable"] = sab_unreadable
129
+ st["setup_checked"] = now
130
+ st["setup_problems"] = problems
131
+ return problems
132
+
133
+
134
+ def check_shared_space(d, st, dry):
135
+ """[shared_volume] in the config: e.g. a drive whose APFS volumes (the users', and whatever else
136
+ is on it) all draw on the same free space; quotas are ceilings, nothing is reserved. Push once
137
+ when its free space drops below LOW_SPACE_ALERT, and re-arm once it's back above LOW_SPACE_CLEAR."""
138
+ if not settings.SHARED_VOLUME:
139
+ return
140
+ roots = [r for r in d["roots"] if r["path"].startswith(settings.SHARED_VOLUME) and r.get("freeSpace") is not None]
141
+ if not roots:
142
+ return
143
+ free = roots[0]["freeSpace"]
144
+ if free < settings.LOW_SPACE_ALERT and not st.get("low_space_alerted"):
145
+ name = os.path.basename(settings.SHARED_VOLUME.rstrip("/"))
146
+ msg = (f"{name} has {free / 1e9:.0f} GB free. Every volume on that drive draws from the same free "
147
+ f"space, so none can grow once it's gone.")
148
+ util.log(msg, dry)
149
+ if not dry:
150
+ util.notify(f"windarr: {name} is running low", msg)
151
+ st["low_space_alerted"] = True
152
+ elif free > settings.LOW_SPACE_CLEAR and st.get("low_space_alerted"):
153
+ st.pop("low_space_alerted", None)