jellyfin-utils 0.1.0__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.
@@ -0,0 +1 @@
1
+ """Jellyfin utility scripts."""
@@ -0,0 +1,5 @@
1
+ """Library-analysis commands."""
2
+
3
+ from .cli import duplicates, health, reclaim, report, requests
4
+
5
+ __all__ = ["duplicates", "health", "reclaim", "report", "requests"]
@@ -0,0 +1,323 @@
1
+ """Library-analysis commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ from collections import defaultdict
7
+ from pathlib import Path
8
+
9
+ import click
10
+ import orjson
11
+
12
+ from jellyfin_utils.client import (
13
+ LibraryItem,
14
+ build_headers,
15
+ display_name,
16
+ get_all_items,
17
+ get_users,
18
+ get_watchers_per_item,
19
+ size_gb,
20
+ )
21
+ from jellyfin_utils.jellyseerr import get_requesters_by_tmdb_id, get_requests
22
+ from jellyfin_utils.options import (
23
+ connection_options,
24
+ ignore_user_option,
25
+ jellyseerr_options,
26
+ output_option,
27
+ quiet_option,
28
+ require_jellyseerr_pair,
29
+ threshold_option,
30
+ )
31
+ from jellyfin_utils.output import OutputFormat, Report, Table, emit
32
+ from jellyfin_utils.stale.cli import find_stale
33
+ from jellyfin_utils.watched.cli import find_candidates
34
+
35
+ from .render import render_csv, render_json, render_markdown, render_text
36
+
37
+
38
+ @click.command("reclaim")
39
+ @connection_options
40
+ @jellyseerr_options
41
+ @ignore_user_option
42
+ @threshold_option
43
+ @click.option("--min-age", type=int, default=90, show_default=True, help="Minimum stale-item age in days.")
44
+ @output_option
45
+ @quiet_option
46
+ def reclaim(
47
+ base_url: str,
48
+ token: str,
49
+ ignore_user: tuple[str, ...],
50
+ threshold: int,
51
+ min_age: int,
52
+ jellyseerr_server: str | None,
53
+ jellyseerr_token: str | None,
54
+ output_format: OutputFormat,
55
+ quiet: bool,
56
+ ) -> None:
57
+ """Rank watched and stale content for cleanup review."""
58
+ require_jellyseerr_pair(jellyseerr_server, jellyseerr_token)
59
+
60
+ headers = build_headers(token)
61
+ users = get_users(base_url, headers)
62
+ ignored = set(ignore_user)
63
+ watchers = get_watchers_per_item(base_url, headers, users, ignored, max_age_days=None)
64
+ active = sum(user.get("Name") not in ignored for user in users)
65
+ items = get_all_items(base_url, headers)
66
+ requesters_by_tmdb_id = (
67
+ get_requesters_by_tmdb_id(jellyseerr_server, jellyseerr_token)
68
+ if jellyseerr_server and jellyseerr_token
69
+ else None
70
+ )
71
+ candidates = find_candidates(items, watchers, active, threshold, requesters_by_tmdb_id)
72
+ stale = find_stale(items, watchers, active, 0, min_age, dt.datetime.now(dt.UTC), requesters_by_tmdb_id)
73
+ merged: dict[str, dict] = {}
74
+ for candidate in candidates:
75
+ merged[candidate.item.item_id] = {
76
+ "reason": "widely_watched",
77
+ "item": display_name(candidate.item),
78
+ "series": candidate.item.series_name,
79
+ "id": candidate.item.item_id,
80
+ "type": candidate.item.item_type,
81
+ "path": candidate.item.path,
82
+ "size_gib": round(size_gb(candidate.item.size), 2),
83
+ "size_is_rollup": candidate.item.size_is_rollup,
84
+ "watchers": candidate.watch_count,
85
+ "requested_by": list(candidate.requested_by),
86
+ "watched_by_requester": list(candidate.watched_by_requester),
87
+ "requester_watched": candidate.requester_watched,
88
+ }
89
+ for item in stale:
90
+ entry = merged.setdefault(
91
+ item.item.item_id,
92
+ {
93
+ "reason": "stale",
94
+ "item": display_name(item.item),
95
+ "series": item.item.series_name,
96
+ "id": item.item.item_id,
97
+ "type": item.item.item_type,
98
+ "path": item.item.path,
99
+ "size_gib": round(size_gb(item.item.size), 2),
100
+ "size_is_rollup": item.item.size_is_rollup,
101
+ "watchers": item.watch_count,
102
+ "requested_by": list(item.requested_by),
103
+ "watched_by_requester": list(item.watched_by_requester),
104
+ "requester_watched": item.requester_watched,
105
+ },
106
+ )
107
+ if entry["reason"] == "widely_watched":
108
+ entry["reason"] = "widely_watched_and_stale"
109
+ results = sorted(
110
+ merged.values(), key=lambda entry: (not entry["requester_watched"], -float(entry["size_gib"]))
111
+ )
112
+ jellyseerr_enabled = requesters_by_tmdb_id is not None
113
+
114
+ match output_format:
115
+ case OutputFormat.JSON:
116
+ click.echo(render_json(results, jellyseerr_enabled=jellyseerr_enabled))
117
+ case OutputFormat.CSV:
118
+ click.echo(render_csv(results), nl=False)
119
+ case OutputFormat.MARKDOWN:
120
+ click.echo(render_markdown(results))
121
+ case _:
122
+ click.echo(render_text(results, jellyseerr_enabled=jellyseerr_enabled, quiet=quiet))
123
+
124
+
125
+ @click.command("duplicates")
126
+ @connection_options
127
+ @output_option
128
+ def duplicates(base_url: str, token: str, output_format: OutputFormat) -> None:
129
+ """Find on-disk items with the same TMDb identifier."""
130
+ items = get_all_items(base_url, build_headers(token))
131
+ grouped: dict[tuple[str, int], list[LibraryItem]] = defaultdict(list)
132
+ for item in items:
133
+ if item.path and item.tmdb_id is not None:
134
+ grouped[(item.item_type, item.tmdb_id)].append(item)
135
+ duplicate_groups = [(key, group) for key, group in grouped.items() if len(group) > 1]
136
+ emit(
137
+ Report(
138
+ title="Duplicate items",
139
+ payload={
140
+ "duplicate_groups": [
141
+ {
142
+ "type": kind,
143
+ "tmdb_id": tmdb_id,
144
+ "items": [
145
+ {
146
+ "id": item.item_id,
147
+ "name": item.name,
148
+ "year": item.production_year,
149
+ "path": item.path,
150
+ "size_gib": round(size_gb(item.size), 2),
151
+ }
152
+ for item in group
153
+ ],
154
+ }
155
+ for (kind, tmdb_id), group in duplicate_groups
156
+ ],
157
+ "count": len(duplicate_groups),
158
+ },
159
+ summary=(
160
+ ("Items scanned", len(items)),
161
+ ("Duplicate groups", len(duplicate_groups)),
162
+ ("Copies on disk", sum(len(group) for _, group in duplicate_groups)),
163
+ ),
164
+ tables=(
165
+ Table(
166
+ columns=("Type", "TMDb ID", "Title", "Year", "Size (GiB)", "ID", "Path"),
167
+ align="lrlrrll",
168
+ rows=[
169
+ (
170
+ kind,
171
+ tmdb_id,
172
+ item.name,
173
+ item.production_year,
174
+ f"{size_gb(item.size):.2f}",
175
+ item.item_id,
176
+ item.path,
177
+ )
178
+ for (kind, tmdb_id), group in duplicate_groups
179
+ for item in group
180
+ ],
181
+ empty="No duplicates found.",
182
+ ),
183
+ ),
184
+ ),
185
+ output_format,
186
+ )
187
+
188
+
189
+ @click.command("health")
190
+ @connection_options
191
+ @output_option
192
+ def health(base_url: str, token: str, output_format: OutputFormat) -> None:
193
+ """Report library records that cannot be used for storage analysis."""
194
+ items = get_all_items(base_url, build_headers(token))
195
+ missing_path = [item for item in items if not item.path]
196
+ no_size = [item for item in items if item.path and item.size == 0]
197
+ emit(
198
+ Report(
199
+ title="Library health",
200
+ payload={
201
+ "items_scanned": len(items),
202
+ "missing_path": [
203
+ {"id": item.item_id, "name": item.name, "type": item.item_type} for item in missing_path
204
+ ],
205
+ "zero_size": [{"id": item.item_id, "name": item.name, "path": item.path} for item in no_size],
206
+ },
207
+ summary=(
208
+ ("Items scanned", len(items)),
209
+ ("Missing path", len(missing_path)),
210
+ ("Zero size", len(no_size)),
211
+ ),
212
+ tables=(
213
+ Table(
214
+ title="Items with no on-disk path",
215
+ columns=("Type", "Title", "ID"),
216
+ rows=[(item.item_type, item.name, item.item_id) for item in missing_path],
217
+ empty="Every item has a path.",
218
+ ),
219
+ Table(
220
+ title="On-disk items reporting zero bytes",
221
+ columns=("Title", "ID", "Path"),
222
+ rows=[(item.name, item.item_id, item.path) for item in no_size],
223
+ empty="Every on-disk item reports a size.",
224
+ ),
225
+ ),
226
+ ),
227
+ output_format,
228
+ )
229
+
230
+
231
+ @click.command("requests")
232
+ @connection_options
233
+ @jellyseerr_options(required=True)
234
+ @output_option
235
+ def requests(
236
+ base_url: str,
237
+ token: str,
238
+ jellyseerr_server: str,
239
+ jellyseerr_token: str,
240
+ output_format: OutputFormat,
241
+ ) -> None:
242
+ """Reconcile Jellyseerr requests with media currently in Jellyfin."""
243
+ items = get_all_items(base_url, build_headers(token))
244
+ available = {item.tmdb_id for item in items if item.tmdb_id is not None and item.path}
245
+ results = [
246
+ {**request, "available_in_jellyfin": request.get("tmdb_id") in available}
247
+ for request in get_requests(jellyseerr_server, jellyseerr_token)
248
+ ]
249
+ landed = sum(bool(request["available_in_jellyfin"]) for request in results)
250
+ emit(
251
+ Report(
252
+ title="Jellyseerr requests vs. library",
253
+ payload={"requests": results, "count": len(results)},
254
+ summary=(
255
+ ("Requests", len(results)),
256
+ ("Available in Jellyfin", landed),
257
+ ("Missing from Jellyfin", len(results) - landed),
258
+ ),
259
+ tables=(
260
+ Table(
261
+ columns=("ID", "Status", "Requested by", "TMDb ID", "Media type", "In Jellyfin"),
262
+ align="rrlrll",
263
+ rows=[
264
+ (
265
+ request["id"],
266
+ request["status"],
267
+ request["requested_by"],
268
+ request["tmdb_id"],
269
+ request["media_type"],
270
+ request["available_in_jellyfin"],
271
+ )
272
+ for request in results
273
+ ],
274
+ empty="No requests found.",
275
+ ),
276
+ ),
277
+ notes=("Status is Jellyseerr's own request-status code, passed through unchanged.",),
278
+ ),
279
+ output_format,
280
+ )
281
+
282
+
283
+ @click.command("report")
284
+ @connection_options
285
+ @click.option("--snapshot", type=click.Path(path_type=Path), help="JSON file to write with this report.")
286
+ @output_option
287
+ def report(base_url: str, token: str, snapshot: Path | None, output_format: OutputFormat) -> None:
288
+ """Summarize library size and item counts, optionally saving a snapshot."""
289
+ items = get_all_items(base_url, build_headers(token))
290
+ by_type: dict[str, dict[str, int]] = defaultdict(lambda: {"items": 0, "bytes": 0})
291
+ for item in items:
292
+ by_type[item.item_type]["items"] += 1
293
+ by_type[item.item_type]["bytes"] += item.size
294
+ payload = {
295
+ "items": len(items),
296
+ # Series sizes total their episodes, which are counted individually.
297
+ "total_gib": round(sum(item.size for item in items if not item.size_is_rollup) / 1024**3, 2),
298
+ "by_type": by_type,
299
+ }
300
+ if snapshot is not None:
301
+ snapshot.parent.mkdir(parents=True, exist_ok=True)
302
+ snapshot.write_bytes(orjson.dumps(payload, option=orjson.OPT_INDENT_2))
303
+ emit(
304
+ Report(
305
+ title="Library report",
306
+ payload=payload,
307
+ summary=(("Items", payload["items"]), ("Total GiB", f"{payload['total_gib']:.2f}")),
308
+ tables=(
309
+ Table(
310
+ title="By media type",
311
+ columns=("Type", "Items", "Bytes", "Size (GiB)"),
312
+ align="lrrr",
313
+ rows=[
314
+ (kind, counts["items"], counts["bytes"], f"{counts['bytes'] / 1024**3:.2f}")
315
+ for kind, counts in sorted(by_type.items())
316
+ ],
317
+ empty="Library is empty.",
318
+ ),
319
+ ),
320
+ notes=("Series repeat the bytes already counted under Episode; Total GiB counts them once.",),
321
+ ),
322
+ output_format,
323
+ )
@@ -0,0 +1,172 @@
1
+ """Output renderers for the reclaim cleanup queue."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+
8
+ import orjson
9
+
10
+ PRIORITY_LEGEND = "* = requested in Jellyseerr and already watched by whoever requested it"
11
+ ROLLUP_LEGEND = "Series sizes total their episodes, which are listed separately and counted once."
12
+ REASON_LABELS = {
13
+ "widely_watched_and_stale": "Widely watched, and stale",
14
+ "widely_watched": "Widely watched",
15
+ "stale": "Stale",
16
+ }
17
+ REASON_ORDER = ("widely_watched_and_stale", "widely_watched", "stale")
18
+ MIN_TITLE_WIDTH = 32
19
+ MAX_TITLE_WIDTH = 52
20
+ RULE_WIDTH = 80
21
+ DETAIL_INDENT = " " * 10
22
+
23
+
24
+ def _total_gib(entries: list[dict]) -> float:
25
+ """Sum sizes, skipping series whose size is the total of episodes listed separately."""
26
+ return sum(float(entry["size_gib"]) for entry in entries if not entry["size_is_rollup"])
27
+
28
+
29
+ def _truncate(text: str, width: int) -> str:
30
+ return text if len(text) <= width else f"{text[: width - 1]}…"
31
+
32
+
33
+ def _title_width(entries: list[dict]) -> int:
34
+ longest = max((len(entry["item"]) for entry in entries), default=MIN_TITLE_WIDTH)
35
+ return min(max(longest, MIN_TITLE_WIDTH), MAX_TITLE_WIDTH)
36
+
37
+
38
+ def _format_entry_line(entry: dict, title_width: int) -> str:
39
+ marker = "*" if entry["requester_watched"] else " "
40
+ title = _truncate(entry["item"], title_width)
41
+ watchers = _plural(entry["watchers"], "watcher")
42
+ size = f"{float(entry['size_gib']):.2f} GiB"
43
+ return f"{marker} {entry['type']:<7} {title:<{title_width}} {watchers:>11} {size:>10}"
44
+
45
+
46
+ def _format_entry_detail(entry: dict) -> list[str]:
47
+ lines = []
48
+ if entry["watched_by_requester"]:
49
+ requesters = ", ".join(entry["watched_by_requester"])
50
+ lines.append(f"{DETAIL_INDENT}requested by {requesters}, who has since watched it")
51
+ elif entry["requested_by"]:
52
+ lines.append(f"{DETAIL_INDENT}requested by {', '.join(entry['requested_by'])}")
53
+ lines.append(f"{DETAIL_INDENT}{entry['path'] or '(no path on disk)'} [{entry['id']}]")
54
+ return lines
55
+
56
+
57
+ def _plural(count: int, noun: str) -> str:
58
+ return f"{count} {noun}" if count == 1 else f"{count} {noun}s"
59
+
60
+
61
+ def _group_rule(reason: str, entries: list[dict]) -> list[str]:
62
+ label = REASON_LABELS.get(reason, reason)
63
+ heading = f"── {label} · {_plural(len(entries), 'item')} · {_total_gib(entries):.2f} GiB "
64
+ return ["", heading + "─" * max(RULE_WIDTH - len(heading), 0)]
65
+
66
+
67
+ def _header_lines(entries: list[dict], *, jellyseerr_enabled: bool) -> list[str]:
68
+ total = _total_gib(entries)
69
+ lines = [f"Reclaim review · {_plural(len(entries), 'candidate')} · {total:.2f} GiB to reclaim"]
70
+ if any(entry["size_is_rollup"] for entry in entries):
71
+ lines.append(ROLLUP_LEGEND)
72
+ if jellyseerr_enabled:
73
+ lines.append(PRIORITY_LEGEND)
74
+ return lines
75
+
76
+
77
+ def render_text(entries: list[dict], *, jellyseerr_enabled: bool, quiet: bool) -> str:
78
+ """Render the cleanup queue as a grouped, human-readable report."""
79
+ title_width = _title_width(entries)
80
+
81
+ if quiet:
82
+ return "\n".join(_format_entry_line(entry, title_width) for entry in entries)
83
+
84
+ lines = _header_lines(entries, jellyseerr_enabled=jellyseerr_enabled)
85
+ if not entries:
86
+ lines.append("\nNothing to review.")
87
+ return "\n".join(lines)
88
+
89
+ for reason in REASON_ORDER:
90
+ group = [entry for entry in entries if entry["reason"] == reason]
91
+ if not group:
92
+ continue
93
+ lines.extend(_group_rule(reason, group))
94
+ for entry in group:
95
+ lines.append(_format_entry_line(entry, title_width))
96
+ lines.extend(_format_entry_detail(entry))
97
+
98
+ return "\n".join(lines)
99
+
100
+
101
+ def render_json(entries: list[dict], *, jellyseerr_enabled: bool) -> str:
102
+ """Render the cleanup queue as indented JSON."""
103
+ payload = {
104
+ "candidates": entries,
105
+ "count": len(entries),
106
+ "estimated_reclaimable_gib": round(_total_gib(entries), 2),
107
+ "jellyseerr_enabled": jellyseerr_enabled,
108
+ }
109
+ return orjson.dumps(payload, option=orjson.OPT_INDENT_2).decode()
110
+
111
+
112
+ def render_markdown(entries: list[dict]) -> str:
113
+ """Render the cleanup queue as a compact Markdown table."""
114
+ lines = [
115
+ "| Priority | Reason | Type | Series | Title | Watchers | Requested by | Requester watched | Size |",
116
+ "| --- | --- | --- | --- | --- | ---: | --- | --- | ---: |",
117
+ ]
118
+ lines.extend(
119
+ "| "
120
+ + " | ".join(
121
+ (
122
+ "Priority" if entry["requester_watched"] else "Standard",
123
+ entry["reason"],
124
+ entry["type"],
125
+ entry["series"] or "—",
126
+ entry["item"],
127
+ str(entry["watchers"]),
128
+ ", ".join(entry["requested_by"]) or "—",
129
+ ", ".join(entry["watched_by_requester"]) or "—",
130
+ f"{float(entry['size_gib']):.2f} GiB",
131
+ )
132
+ )
133
+ + " |"
134
+ for entry in entries
135
+ )
136
+ return "\n".join(lines)
137
+
138
+
139
+ def render_csv(entries: list[dict]) -> str:
140
+ """Render the cleanup queue as CSV with headers."""
141
+ buf = io.StringIO()
142
+ writer = csv.writer(buf)
143
+ writer.writerow(
144
+ [
145
+ "Reason",
146
+ "Type",
147
+ "Series",
148
+ "Name",
149
+ "Watchers",
150
+ "Requester Watched",
151
+ "Requested By",
152
+ "File Size (GiB)",
153
+ "ID",
154
+ "Path",
155
+ ]
156
+ )
157
+ for entry in entries:
158
+ writer.writerow(
159
+ [
160
+ entry["reason"],
161
+ entry["type"],
162
+ entry["series"] or "",
163
+ entry["item"],
164
+ entry["watchers"],
165
+ ", ".join(entry["watched_by_requester"]),
166
+ ", ".join(entry["requested_by"]),
167
+ f"{float(entry['size_gib']):.2f}",
168
+ entry["id"],
169
+ entry["path"],
170
+ ]
171
+ )
172
+ return buf.getvalue()
jellyfin_utils/cli.py ADDED
@@ -0,0 +1,26 @@
1
+ """Unified CLI entry point for all jellyfin-utils commands."""
2
+
3
+ import click
4
+
5
+ from jellyfin_utils.analysis import duplicates, health, reclaim, report, requests
6
+ from jellyfin_utils.server import server
7
+ from jellyfin_utils.stale.cli import main as stale
8
+ from jellyfin_utils.user.cli import user
9
+ from jellyfin_utils.watched.cli import main as watched
10
+
11
+
12
+ @click.group("jellyfin")
13
+ @click.version_option(package_name="jellyfin-utils")
14
+ def cli() -> None:
15
+ """Manage a Jellyfin media server."""
16
+
17
+
18
+ cli.add_command(watched, "watched")
19
+ cli.add_command(stale, "stale")
20
+ cli.add_command(user)
21
+ cli.add_command(reclaim)
22
+ cli.add_command(duplicates)
23
+ cli.add_command(health)
24
+ cli.add_command(requests)
25
+ cli.add_command(report)
26
+ cli.add_command(server)