Repository navigation
Expand file tree
/
Copy pathplexmatch.py
More file actions
883 lines (803 loc) · 35.7 KB
/
Copy pathplexmatch.py
File metadata and controls
883 lines (803 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
plexmatch.py - Gleicht eine Plex-Filmbibliothek gegen eine Liste (MDBList / IMDb /
CSV / Freitext) ab und markiert Vorhandene, Fehlende und nur-in-Plex-Filme.
Nur Python-Standardbibliothek. Start: python3 plexmatch.py
Danach im Browser: http://<host>:8099
Author: ezek1el3000
Lizenz: MIT
Repo: https://github.com/ezek1el/plexmatch
"""
import argparse
import csv
import io
import json
import os
import re
import ssl
import sys
import threading
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
VERSION = "1.2.2"
CONFIG_PATH = os.environ.get(
"PLEXMATCH_CONFIG",
os.path.join(os.path.expanduser("~"), ".plexmatch.json"),
)
TT_RE = re.compile(r"tt\d{6,10}")
YEAR_IN_PARENS = re.compile(r"[\(\[](\d{4})[\)\]]\s*$")
ARTICLES = ("the ", "a ", "an ", "der ", "die ", "das ", "le ", "la ", "les ",
"el ", "il ", "l ")
SSL_CTX = ssl.create_default_context()
SSL_CTX.check_hostname = False
SSL_CTX.verify_mode = ssl.CERT_NONE
# --------------------------------------------------------------------------
# Helpers
# --------------------------------------------------------------------------
def norm_title(value):
"""Titel auf vergleichbare Form bringen."""
s = unicodedata.normalize("NFKD", value or "")
s = "".join(c for c in s if not unicodedata.combining(c))
s = s.lower()
s = s.replace("&", " and ").replace("+", " and ")
s = re.sub(r"\b(part|teil)\b", " ", s)
s = re.sub(r"[^a-z0-9]+", " ", s).strip()
for art in ARTICLES:
if s.startswith(art):
s = s[len(art):]
break
return re.sub(r"\s+", " ", s).strip()
def to_year(value):
"""Jahreszahl aus '2021', '2021-05-03', 2021 usw. ziehen."""
try:
return int(str(value).strip()[:4])
except (TypeError, ValueError):
return None
def to_int(value):
"""Vollstaendige Ganzzahl parsen - NICHT auf vier Stellen kuerzen."""
try:
return int(str(value).strip())
except (TypeError, ValueError):
return None
def http_get(url, headers=None, timeout=30):
req = urllib.request.Request(url, headers=headers or {})
with urllib.request.urlopen(req, timeout=timeout, context=SSL_CTX) as resp:
raw = resp.read()
return raw.decode("utf-8", "replace")
def plex_get(base_url, token, path, params=None):
params = dict(params or {})
params["X-Plex-Token"] = token
url = base_url.rstrip("/") + path + "?" + urllib.parse.urlencode(params)
body = http_get(url, headers={
"Accept": "application/json",
"X-Plex-Product": "plexmatch",
"X-Plex-Client-Identifier": "plexmatch-" + VERSION,
})
return json.loads(body)
def plex_sections(base_url, token):
data = plex_get(base_url, token, "/library/sections")
out = []
for d in data.get("MediaContainer", {}).get("Directory", []):
out.append({
"key": d.get("key"),
"title": d.get("title"),
"type": d.get("type"),
"agent": d.get("agent"),
})
return out
def plex_items(base_url, token, section_key, section_type="movie",
page_size=400, progress=None):
"""Alle Filme bzw. Serien einer Sektion holen (paginiert)."""
plex_type = 2 if section_type == "show" else 1
items, start = [], 0
while True:
data = plex_get(base_url, token, "/library/sections/%s/all" % section_key, {
"type": plex_type,
"includeGuids": 1,
"X-Plex-Container-Start": start,
"X-Plex-Container-Size": page_size,
})
mc = data.get("MediaContainer", {})
batch = mc.get("Metadata", []) or []
for m in batch:
ids = set(TT_RE.findall(m.get("guid", "") or ""))
for g in m.get("Guid", []) or []:
ids.update(TT_RE.findall(g.get("id", "") or ""))
items.append({
"title": m.get("title", ""),
"year": to_year(m.get("year")),
"imdb": sorted(ids)[0] if ids else None,
"ratingKey": m.get("ratingKey"),
"addedAt": m.get("addedAt"),
})
total = to_int(mc.get("totalSize")) or to_int(mc.get("size")) or len(items)
if progress:
progress(len(items), total)
start += page_size
if not batch or len(items) >= total:
break
return items
# --------------------------------------------------------------------------
# Listen-Parser
# --------------------------------------------------------------------------
def _entry(imdb=None, title="", year=None, raw="", mediatype=None):
return {"imdb": imdb, "title": title.strip(), "year": year,
"raw": raw.strip(), "mediatype": mediatype}
def parse_json_list(data):
if isinstance(data, dict):
for key in ("items", "movies", "results", "data", "entries"):
if isinstance(data.get(key), list):
data = data[key]
break
else:
data = [data]
out = []
for row in data:
if isinstance(row, str):
out.extend(parse_lines(row))
continue
if not isinstance(row, dict):
continue
imdb = None
for k in ("imdb_id", "imdbid", "imdb", "id", "const"):
v = row.get(k)
if isinstance(v, str) and TT_RE.fullmatch(v.strip()):
imdb = v.strip()
break
title = row.get("title") or row.get("name") or row.get("originalTitle") or ""
year = to_year(row.get("release_year") or row.get("year")
or row.get("releaseYear") or (row.get("released") or "")[:4])
mt = row.get("mediatype") or row.get("media_type") or row.get("type")
if isinstance(mt, str):
mt = mt.strip().lower()
if mt in ("tv", "series", "tvshow"):
mt = "show"
elif mt not in ("movie", "show"):
mt = None
else:
mt = None
if imdb or title:
out.append(_entry(imdb, str(title), year, str(title), mt))
return out
def parse_csv_list(text):
sample = text[:4000]
try:
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
except csv.Error:
dialect = csv.excel
reader = csv.DictReader(io.StringIO(text), dialect=dialect)
if not reader.fieldnames:
return []
cols = {(f or "").strip().lower(): f for f in reader.fieldnames}
def pick(*names):
for n in names:
if n in cols:
return cols[n]
return None
c_imdb = pick("const", "imdb_id", "imdbid", "imdb", "tconst", "id")
c_title = pick("title", "name", "primarytitle", "original title", "originaltitle")
c_year = pick("year", "release_year", "startyear", "released", "release date")
if not (c_imdb or c_title):
return []
out = []
for row in reader:
imdb = None
if c_imdb:
m = TT_RE.search(str(row.get(c_imdb) or ""))
imdb = m.group(0) if m else None
title = str(row.get(c_title) or "").strip() if c_title else ""
year = to_year(row.get(c_year)) if c_year else None
if imdb or title:
out.append(_entry(imdb, title, year, title or imdb))
return out
def parse_lines(text):
out = []
for line in text.splitlines():
line = line.strip().lstrip("\ufeff")
if not line or line.startswith("#"):
continue
m = TT_RE.search(line)
imdb = m.group(0) if m else None
rest = line
if imdb:
rest = (line[:m.start()] + " " + line[m.end():])
rest = rest.strip(" \t-|,;:")
year = None
ym = YEAR_IN_PARENS.search(rest)
if ym:
year = to_year(ym.group(1))
rest = rest[:ym.start()].strip()
else:
parts = re.split(r"[;\t|]", rest)
if len(parts) >= 2 and to_year(parts[-1]) and len(parts[-1].strip()) == 4:
year = to_year(parts[-1])
rest = ";".join(parts[:-1]).strip()
rest = re.sub(r"^https?://\S*imdb\S*$", "", rest).strip()
if imdb or rest:
out.append(_entry(imdb, rest, year, line))
return out
def parse_list(text):
"""Erkennt JSON / CSV / Freitext automatisch."""
text = (text or "").strip()
if not text:
return []
if text[0] in "[{":
try:
return parse_json_list(json.loads(text))
except (ValueError, TypeError):
pass
head = text[:400].lower()
if head.startswith(("<!doctype", "<html", "<?xml")) or "<head" in head:
return parse_html_ids(text)
first = text.splitlines()[0].lower()
if any(d in first for d in (",", ";", "\t")) and any(
k in first for k in ("title", "const", "imdb", "year", "name")):
rows = parse_csv_list(text)
if rows:
return rows
rows = parse_lines(text)
if not rows and "imdb.com/title/" in text:
return parse_html_ids(text)
return rows
def normalize_list_url(url):
"""mdblist.com/lists/user/name -> .../json/ (Slash am Ende ist Pflicht)."""
u = url.strip()
if "mdblist.com/lists/" in u:
base = u.split("?")[0].rstrip("/")
if base.endswith("/json"):
return base + "/"
if not base.endswith(("/items", "/json/")):
return base + "/json/"
return u
HTML_IMDB_RE = re.compile(r"imdb\.com/title/(tt\d{6,10})")
def parse_html_ids(text):
"""Notnagel: aus einer HTML-Seite alle IMDb-IDs in Reihenfolge ziehen."""
ids = HTML_IMDB_RE.findall(text) or TT_RE.findall(text)
seen, out = set(), []
for i in ids:
if i not in seen:
seen.add(i)
out.append(_entry(i, "", None, i))
return out
# --------------------------------------------------------------------------
# Abgleich
# --------------------------------------------------------------------------
def compare(library, entries, year_tolerance=1):
by_imdb, by_key, by_title = {}, {}, {}
for it in library:
if it["imdb"]:
by_imdb.setdefault(it["imdb"], it)
nt = norm_title(it["title"])
if nt:
by_title.setdefault(nt, []).append(it)
if it["year"]:
by_key.setdefault((nt, it["year"]), it)
matched_keys, results = set(), []
for e in entries:
hit, how = None, None
if e["imdb"] and e["imdb"] in by_imdb:
hit, how = by_imdb[e["imdb"]], "imdb"
if hit is None:
nt = norm_title(e["title"])
if nt:
if e["year"]:
for delta in range(0, year_tolerance + 1):
for y in {e["year"] - delta, e["year"] + delta}:
if (nt, y) in by_key:
hit = by_key[(nt, y)]
how = "titel+jahr" if delta == 0 else "titel+jahr~"
break
if hit:
break
if hit is None and nt in by_title:
cand = by_title[nt]
if len(cand) == 1 and not e["year"]:
hit, how = cand[0], "titel"
elif cand:
hit, how = cand[0], "titel?"
if hit is not None:
matched_keys.add(hit["ratingKey"])
status = "fehlt"
if how in ("imdb", "titel+jahr", "titel+jahr~", "titel"):
status = "vorhanden"
elif how:
status = "unsicher" # titel? = mehrdeutig oder Jahr weicht ab
results.append({
"status": status,
"match": how,
"title": e["title"] or (e["imdb"] or ""),
"year": e["year"],
"imdb": e["imdb"],
"plexTitle": hit["title"] if hit else None,
"plexYear": hit["year"] if hit else None,
"ratingKey": hit["ratingKey"] if hit else None,
})
plex_only = [{
"title": it["title"], "year": it["year"], "imdb": it["imdb"],
"ratingKey": it["ratingKey"],
} for it in library if it["ratingKey"] not in matched_keys]
plex_only.sort(key=lambda x: (norm_title(x["title"]), x["year"] or 0))
return results, plex_only
# --------------------------------------------------------------------------
# Config
# --------------------------------------------------------------------------
def load_config():
try:
with open(CONFIG_PATH, "r", encoding="utf-8") as fh:
return json.load(fh)
except (OSError, ValueError):
return {}
def save_config(cfg):
tmp = CONFIG_PATH + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(cfg, fh, indent=2)
os.replace(tmp, CONFIG_PATH)
try:
os.chmod(CONFIG_PATH, 0o600)
except OSError:
pass
# --------------------------------------------------------------------------
# HTTP-Server
# --------------------------------------------------------------------------
class Handler(BaseHTTPRequestHandler):
server_version = "plexmatch/" + VERSION
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *args):
if os.environ.get("PLEXMATCH_DEBUG"):
sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % args))
# -- utils --------------------------------------------------------
def _send(self, code, body, ctype="application/json; charset=utf-8"):
if isinstance(body, str):
body = body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def _json(self, obj, code=200):
self._send(code, json.dumps(obj, ensure_ascii=False), )
def _err(self, exc, code=502):
msg = str(exc)
if isinstance(exc, urllib.error.HTTPError):
msg = "HTTP %s vom Plex-Server (Token oder URL prüfen)" % exc.code
elif isinstance(exc, urllib.error.URLError):
msg = "Keine Verbindung: %s" % exc.reason
self._json({"error": msg}, code)
def _body(self):
length = to_int(self.headers.get("Content-Length")) or 0
if not length:
return {}
chunks, remaining = [], length
while remaining > 0:
chunk = self.rfile.read(min(remaining, 65536))
if not chunk:
break
chunks.append(chunk)
remaining -= len(chunk)
raw = b"".join(chunks)
if len(raw) != length:
raise ValueError("Body unvollstaendig: %d von %d Byte empfangen"
% (len(raw), length))
return json.loads(raw.decode("utf-8", "replace") or "{}")
# -- routes -------------------------------------------------------
def do_GET(self):
path = urllib.parse.urlparse(self.path).path
if path in ("/", "/index.html"):
return self._send(200, PAGE.replace("__VERSION__", VERSION),
"text/html; charset=utf-8")
if path == "/api/config":
cfg = load_config()
if not cfg.get("saveToken"):
cfg.pop("token", None)
return self._json(cfg)
return self._json({"error": "not found"}, 404)
def do_POST(self):
path = urllib.parse.urlparse(self.path).path
try:
data = self._body()
except ValueError as exc:
return self._json({"error": "Ungültiger Request: %s" % exc}, 400)
try:
if path == "/api/sections":
secs = plex_sections(data.get("plexUrl", ""), data.get("token", ""))
usable = [s for s in secs if s["type"] in ("movie", "show")]
return self._json({"sections": usable, "all": secs})
if path == "/api/fetchlist":
url = normalize_list_url(data.get("url", ""))
if not url.lower().startswith(("http://", "https://")):
return self._json({"error": "URL muss mit http:// oder https:// beginnen"}, 400)
text = http_get(url, headers={
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/125.0 Safari/537.36"),
"Accept": "application/json, text/html, text/plain, */*"})
return self._json({"text": text, "url": url,
"entries": len(parse_list(text))})
if path == "/api/compare":
sec_type = (data.get("sectionType") or "movie").lower()
movies = plex_items(data.get("plexUrl", ""), data.get("token", ""),
data.get("section", ""), sec_type)
entries = parse_list(data.get("listText", ""))
if not entries:
return self._json({"error": "Liste konnte nicht gelesen werden "
"(0 Einträge erkannt)"}, 400)
results, plex_only = compare(movies, entries,
to_int(data.get("yearTolerance")) or 0)
stats = {
"list": len(entries),
"plex": len(movies),
"present": sum(1 for r in results if r["status"] == "vorhanden"),
"unsure": sum(1 for r in results if r["status"] == "unsicher"),
"missing": sum(1 for r in results if r["status"] == "fehlt"),
"plexOnly": len(plex_only),
"noGuid": sum(1 for m in movies if not m["imdb"]),
"typeMismatch": sum(1 for e in entries
if e.get("mediatype")
and e["mediatype"] != sec_type),
"sectionType": sec_type,
}
return self._json({"results": results, "plexOnly": plex_only,
"stats": stats})
if path == "/api/config":
cfg = {
"plexUrl": data.get("plexUrl", ""),
"section": data.get("section", ""),
"listUrl": data.get("listUrl", ""),
"saveToken": bool(data.get("saveToken")),
"yearTolerance": to_int(data.get("yearTolerance")) or 0,
}
if cfg["saveToken"]:
cfg["token"] = data.get("token", "")
save_config(cfg)
return self._json({"ok": True, "path": CONFIG_PATH})
except Exception as exc: # noqa: BLE001 - Fehler an GUI weiterreichen
return self._err(exc)
return self._json({"error": "not found"}, 404)
# --------------------------------------------------------------------------
# GUI
# --------------------------------------------------------------------------
PAGE = r"""<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>plexmatch __VERSION__ - Bibliothek vs. Liste</title>
<style>
:root{
--bg:#1c1d21; --panel:#212226; --line:#2e3036; --line2:#3a3d45;
--ink:#d6d8dd; --dim:#83878f; --accent:#1d9ac7;
--ok:#4caf6d; --miss:#e0554b; --maybe:#d9a441;
--mono:"JetBrains Mono",ui-monospace,"DejaVu Sans Mono",Menlo,Consolas,monospace;
}
*{box-sizing:border-box}
html,body{margin:0;padding:0;background:var(--bg);color:var(--ink);
font-family:var(--mono);font-size:13px;line-height:1.45}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
.wrap{max-width:1180px;margin:0 auto;padding:18px 16px 60px}
header{display:flex;align-items:baseline;gap:12px;border-bottom:1px solid var(--line);
padding-bottom:10px;margin-bottom:16px;flex-wrap:wrap}
header h1{font-size:15px;margin:0;letter-spacing:.14em;text-transform:uppercase;font-weight:600}
header h1 b{color:var(--accent);font-weight:600}
header .sub{color:var(--dim);font-size:11px}
fieldset{border:1px solid var(--line);background:var(--panel);border-radius:3px;
padding:12px 14px 14px;margin:0 0 14px}
legend{color:var(--dim);font-size:10px;letter-spacing:.18em;text-transform:uppercase;padding:0 6px}
label{display:block;color:var(--dim);font-size:10px;letter-spacing:.12em;
text-transform:uppercase;margin:0 0 4px}
input,select,textarea,button{font-family:var(--mono);font-size:13px;color:var(--ink);
background:#191a1e;border:1px solid var(--line2);border-radius:2px;padding:7px 9px;width:100%}
textarea{min-height:150px;resize:vertical;line-height:1.5}
input:focus,select,textarea:focus,button:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
.grid{display:grid;gap:10px}
.g3{grid-template-columns:2fr 2fr 1.4fr}
.g2{grid-template-columns:3fr 1fr}
@media(max-width:760px){.g3,.g2{grid-template-columns:1fr}}
button{cursor:pointer;background:#26282d;border-color:var(--line2);width:auto;padding:7px 14px;
letter-spacing:.06em}
button:hover{border-color:var(--accent);color:#fff}
button.primary{background:var(--accent);border-color:var(--accent);color:#08191f;font-weight:700}
button.primary:hover{background:#33b0dd;color:#08191f}
button:disabled{opacity:.45;cursor:not-allowed}
.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:10px}
.chk{display:flex;align-items:center;gap:6px;color:var(--dim);font-size:11px}
.chk input{width:auto}
.hint{color:var(--dim);font-size:11px;margin-top:6px}
#msg{display:none;margin:0 0 14px;padding:9px 12px;border-radius:2px;border-left:3px solid;
background:var(--panel);white-space:pre-wrap}
#msg.err{border-color:var(--miss);color:#ffb3ad}
#msg.info{border-color:var(--accent);color:var(--ink)}
#msg.ok{border-color:var(--ok);color:#b7e6c6}
.stats{display:grid;grid-template-columns:repeat(6,1fr);gap:1px;background:var(--line);
border:1px solid var(--line);margin-bottom:14px}
@media(max-width:760px){.stats{grid-template-columns:repeat(3,1fr)}}
.stat{background:var(--panel);padding:10px 12px}
.stat b{display:block;font-size:20px;font-weight:600;letter-spacing:-.02em}
.stat span{color:var(--dim);font-size:10px;letter-spacing:.12em;text-transform:uppercase}
.stat.ok b{color:var(--ok)} .stat.miss b{color:var(--miss)} .stat.maybe b{color:var(--maybe)}
.tabs{display:flex;gap:0;border-bottom:1px solid var(--line);margin-bottom:0;flex-wrap:wrap}
.tab{background:none;border:none;border-bottom:2px solid transparent;border-radius:0;
color:var(--dim);padding:8px 14px}
.tab:hover{color:var(--ink)}
.tab.on{color:var(--ink);border-bottom-color:var(--accent)}
.tools{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px 0}
.tools input[type=search]{max-width:260px}
table{width:100%;border-collapse:collapse}
th{position:sticky;top:0;background:var(--bg);text-align:left;color:var(--dim);font-size:10px;
letter-spacing:.14em;text-transform:uppercase;font-weight:500;padding:7px 8px;
border-bottom:1px solid var(--line2)}
td{padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}
tbody tr:hover{background:#25262b}
td.num{color:var(--dim);text-align:right;width:52px}
td.yr{color:var(--dim);width:60px}
.tag{display:inline-block;min-width:78px;text-align:center;padding:1px 6px;border-radius:2px;
font-size:10px;letter-spacing:.1em;text-transform:uppercase;border:1px solid}
.tag.vorhanden{color:var(--ok);border-color:#2d5a3c;background:#16241b}
.tag.fehlt{color:var(--miss);border-color:#5c2b27;background:#261715}
.tag.unsicher{color:var(--maybe);border-color:#5c4a22;background:#262015}
.tag.plex{color:var(--accent);border-color:#1b4a5c;background:#132229}
.via{color:var(--dim);font-size:10px}
.empty{color:var(--dim);padding:26px 8px;text-align:center}
footer{color:var(--dim);font-size:10px;margin-top:26px;border-top:1px solid var(--line);padding-top:10px}
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>plex<b>match</b></h1>
<span class="sub">v__VERSION__ - Bibliothek gegen Liste abgleichen</span>
</header>
<div id="msg"></div>
<fieldset>
<legend>Plex</legend>
<div class="grid g3">
<div><label for="plexUrl">Server-URL</label>
<input id="plexUrl" placeholder="http://192.168.88.10:32400"></div>
<div><label for="token">X-Plex-Token</label>
<input id="token" type="password" placeholder="Token aus Plex-Web (XML anzeigen)"></div>
<div><label for="section">Bibliothek</label>
<select id="section"><option value="">- Bibliotheken laden -</option></select></div>
</div>
<div class="row">
<button id="btnSections">Bibliotheken laden</button>
<span class="chk"><input type="checkbox" id="saveToken"><label for="saveToken"
style="margin:0;text-transform:none;letter-spacing:0;font-size:11px">Token lokal speichern</label></span>
<span class="chk"><input type="checkbox" id="yearTol"><label for="yearTol"
style="margin:0;text-transform:none;letter-spacing:0;font-size:11px">Jahr +/-1 tolerieren</label></span>
</div>
</fieldset>
<fieldset>
<legend>Liste</legend>
<div class="grid g2">
<div><label for="listUrl">Listen-URL (MDBList, Trakt-JSON, rohe Textdatei)</label>
<input id="listUrl" placeholder="https://mdblist.com/lists/benutzer/listenname"></div>
<div><label for="btnFetch"> </label>
<button id="btnFetch" style="width:100%">URL laden</button></div>
</div>
<div style="margin-top:10px">
<label for="listText">Listeninhalt (JSON, CSV oder eine Zeile pro Film)</label>
<textarea id="listText" placeholder="tt0111161 Der Pate (1972) Dune;2021 - oder IMDb-CSV-Export / MDBList-JSON hier einfügen -"></textarea>
</div>
<div class="row">
<input type="file" id="file" accept=".csv,.json,.txt,.tsv" style="width:auto;padding:5px">
<button id="btnClear">Leeren</button>
<span class="hint" id="listInfo"></span>
</div>
</fieldset>
<div class="row" style="margin:0 0 16px">
<button id="btnRun" class="primary">Abgleich starten</button>
<button id="btnSave">Einstellungen speichern</button>
</div>
<div id="out" hidden>
<div class="stats" id="stats"></div>
<div class="tabs" id="tabs"></div>
<div class="tools">
<input type="search" id="q" placeholder="Filtern ...">
<button id="expCsv">CSV exportieren</button>
<button id="expIds">IMDb-IDs exportieren</button>
<button id="expTitles">Titel exportieren</button>
<span class="hint" id="shown"></span>
</div>
<table><thead><tr>
<th class="num">#</th><th style="width:110px">Status</th><th>Titel</th>
<th class="yr">Jahr</th><th style="width:110px">IMDb</th><th>Treffer in Plex</th>
</tr></thead><tbody id="tbody"></tbody></table>
</div>
<footer>plexmatch - laeuft lokal, keine Daten verlassen dein Netz. Token liegt in ~/.plexmatch.json (chmod 600).</footer>
</div>
<script>
const $ = s => document.querySelector(s);
let DATA = null, TAB = 'fehlt';
function msg(text, kind){
const m = $('#msg');
if(!text){ m.style.display='none'; return; }
m.className = kind || 'info'; m.textContent = text; m.style.display='block';
}
async function api(path, payload){
const r = await fetch(path, {method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify(payload||{})});
const j = await r.json().catch(()=>({error:'Antwort nicht lesbar'}));
if(!r.ok || j.error) throw new Error(j.error || ('HTTP '+r.status));
return j;
}
function cfg(){
const opt = $('#section').selectedOptions[0];
return {plexUrl:$('#plexUrl').value.trim(), token:$('#token').value.trim(),
section:$('#section').value,
sectionType:(opt && opt.dataset.type) ? opt.dataset.type : 'movie',
listUrl:$('#listUrl').value.trim(),
listText:$('#listText').value, saveToken:$('#saveToken').checked,
yearTolerance: $('#yearTol').checked ? 1 : 0};
}
function busy(on){ document.querySelectorAll('button').forEach(b=>b.disabled=on); }
fetch('/api/config').then(r=>r.json()).then(c=>{
$('#plexUrl').value = c.plexUrl || '';
$('#token').value = c.token || '';
$('#listUrl').value = c.listUrl || '';
$('#saveToken').checked = !!c.saveToken;
$('#yearTol').checked = !!c.yearTolerance;
if(c.section){ const o=document.createElement('option');
o.value=c.section; o.textContent='Sektion '+c.section+' (gespeichert)';
$('#section').appendChild(o); $('#section').value=c.section; }
}).catch(()=>{});
$('#btnSections').onclick = async () => {
busy(true); msg('Lade Bibliotheken ...');
try{
const j = await api('/api/sections', cfg());
const sel = $('#section'); const keep = sel.value; sel.innerHTML='';
(j.sections||[]).forEach(s=>{ const o=document.createElement('option');
o.value=s.key; o.dataset.type=s.type;
o.textContent=s.title+' ['+(s.type==='show'?'Serien':'Filme')+', key '+s.key+']';
sel.appendChild(o); });
const skipped = (j.all||[]).filter(s => s.type!=='movie' && s.type!=='show');
const note = skipped.length ? ' Nicht unterstuetzt (kein IMDb-Abgleich moeglich): '
+ skipped.map(s=>s.title+' ['+s.type+']').join(', ') + '.' : '';
if(!sel.options.length){
msg('Keine Film- oder Serien-Bibliothek gefunden.'+note, 'err');
} else {
if([...sel.options].some(o=>o.value===keep)) sel.value=keep;
msg(sel.options.length+' von '+(j.all||[]).length+' Bibliotheken nutzbar.'+note, 'ok');
}
}catch(e){ msg(e.message, 'err'); } finally{ busy(false); }
};
$('#btnFetch').onclick = async () => {
const url = $('#listUrl').value.trim();
if(!url){ msg('Keine Listen-URL angegeben.', 'err'); return; }
busy(true); msg('Lade Liste ...');
try{
const j = await api('/api/fetchlist', {url});
$('#listText').value = j.text;
$('#listText').dispatchEvent(new Event('input'));
if(!j.entries){
msg('Von '+j.url+' geladen, aber 0 Filme erkannt. Liste oeffentlich? Sonst JSON/CSV manuell einfuegen.', 'err');
} else {
msg(j.entries+' Filme erkannt (Quelle: '+j.url+').', 'ok');
}
}catch(e){ msg(e.message, 'err'); } finally{ busy(false); }
};
$('#file').onchange = e => {
const f = e.target.files[0]; if(!f) return;
const r = new FileReader();
r.onload = () => { $('#listText').value = r.result;
msg('Datei geladen: '+f.name, 'ok'); };
r.readAsText(f);
};
$('#btnClear').onclick = () => { $('#listText').value=''; $('#listInfo').textContent=''; };
$('#listText').oninput = () => {
const n = $('#listText').value.split('\n').filter(x=>x.trim()).length;
$('#listInfo').textContent = n ? n.toLocaleString('de-DE')+' Zeilen im Feld' : '';
};
$('#btnSave').onclick = async () => {
try{ const j = await api('/api/config', cfg());
msg('Gespeichert: '+j.path, 'ok'); }
catch(e){ msg(e.message, 'err'); }
};
$('#btnRun').onclick = async () => {
const c = cfg();
if(!c.plexUrl || !c.token || !c.section){ msg('Server-URL, Token und Bibliothek werden benoetigt.', 'err'); return; }
if(!c.listText.trim()){ msg('Die Liste ist leer.', 'err'); return; }
busy(true); msg('Lese Plex-Bibliothek und gleiche ab - bei 11.000 Filmen dauert das ~10-30 s ...');
try{
DATA = await api('/api/compare', c);
render(); msg('', null);
}catch(e){ msg(e.message, 'err'); } finally{ busy(false); }
};
function render(){
const s = DATA.stats;
$('#stats').innerHTML = [
['Liste', s.list, ''], ['Vorhanden', s.present, 'ok'], ['Fehlt', s.missing, 'miss'],
['Unsicher', s.unsure, 'maybe'], ['Nur in Plex', s.plexOnly, ''], ['Plex gesamt', s.plex, '']
].map(([l,v,k]) => '<div class="stat '+k+'"><b>'+v.toLocaleString('de-DE')+'</b><span>'+l+'</span></div>').join('');
$('#tabs').innerHTML = [
['fehlt','Fehlt ('+s.missing+')'], ['vorhanden','Vorhanden ('+s.present+')'],
['unsicher','Unsicher ('+s.unsure+')'], ['alle','Alle ('+s.list+')'],
['plexonly','Nur in Plex ('+s.plexOnly+')']
].map(([k,l]) => '<button class="tab'+(k===TAB?' on':'')+'" data-tab="'+k+'">'+l+'</button>').join('');
$('#tabs').querySelectorAll('.tab').forEach(b => b.onclick = () => {
TAB = b.dataset.tab; render();
});
$('#out').hidden = false;
const warn = [];
if(s.typeMismatch) warn.push(s.typeMismatch+' Listeneintraege sind '
+(s.sectionType==='movie'?'Serien':'Filme')+', die gewaehlte Bibliothek enthaelt '
+(s.sectionType==='movie'?'Filme':'Serien')+' - passende Bibliothek waehlen.');
if(s.noGuid) warn.push(s.noGuid+' Plex-Eintraege ohne IMDb-ID, dort greift nur Titel+Jahr.');
if(warn.length) msg(warn.join('\n'), s.typeMismatch ? 'err' : 'info');
paint();
}
function rows(){
const q = $('#q').value.trim().toLowerCase();
let list;
if(TAB === 'plexonly') list = DATA.plexOnly.map(r => ({...r, status:'plexonly'}));
else if(TAB === 'alle') list = DATA.results;
else list = DATA.results.filter(r => r.status === TAB);
if(q) list = list.filter(r => ((r.title||'')+' '+(r.imdb||'')+' '+(r.plexTitle||'')).toLowerCase().includes(q));
return list;
}
function esc(s){ return (s==null?'':String(s)).replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c])); }
function paint(){
const list = rows();
$('#shown').textContent = list.length.toLocaleString('de-DE')+' Eintraege';
if(!list.length){ $('#tbody').innerHTML = '<tr><td colspan="6" class="empty">Nichts in dieser Ansicht.</td></tr>'; return; }
const frag = list.slice(0, 3000).map((r,i) => {
const tag = r.status==='plexonly' ? '<span class="tag plex">nur Plex</span>'
: '<span class="tag '+r.status+'">'+r.status+'</span>';
const imdb = r.imdb ? '<a href="https://www.imdb.com/title/'+r.imdb+'/" target="_blank" rel="noopener">'+r.imdb+'</a>' : '<span class="via">-</span>';
const hit = r.plexTitle ? esc(r.plexTitle)+(r.plexYear?' <span class="via">('+r.plexYear+')</span>':'')+' <span class="via">via '+esc(r.match)+'</span>' : '<span class="via">-</span>';
return '<tr><td class="num">'+(i+1)+'</td><td>'+tag+'</td><td>'+esc(r.title)+'</td>'
+ '<td class="yr">'+(r.year||'')+'</td><td>'+imdb+'</td><td>'+hit+'</td></tr>';
}).join('');
$('#tbody').innerHTML = frag + (list.length>3000 ? '<tr><td colspan="6" class="empty">... auf 3000 Zeilen begrenzt, Export enthaelt alles.</td></tr>' : '');
}
$('#q').oninput = paint;
function dl(name, text){
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([text], {type:'text/plain;charset=utf-8'}));
a.download = name; a.click(); URL.revokeObjectURL(a.href);
}
const stamp = () => new Date().toISOString().slice(0,10);
$('#expCsv').onclick = () => {
const q = v => '"'+String(v==null?'':v).replace(/"/g,'""')+'"';
const body = rows().map(r => [r.status, r.title, r.year, r.imdb, r.plexTitle, r.plexYear, r.match].map(q).join(',')).join('\n');
dl('plexmatch-'+TAB+'-'+stamp()+'.csv', 'status,titel,jahr,imdb,plex_titel,plex_jahr,match\n'+body);
};
$('#expIds').onclick = () => {
const ids = rows().map(r => r.imdb).filter(Boolean);
if(!ids.length){ msg('Keine IMDb-IDs in dieser Ansicht.', 'err'); return; }
dl('plexmatch-'+TAB+'-imdb-'+stamp()+'.txt', ids.join('\n'));
};
$('#expTitles').onclick = () => {
dl('plexmatch-'+TAB+'-titel-'+stamp()+'.txt',
rows().map(r => r.title + (r.year ? ' ('+r.year+')' : '')).join('\n'));
};
</script>
</body></html>
"""
# --------------------------------------------------------------------------
def main():
ap = argparse.ArgumentParser(description="Plex-Bibliothek gegen Liste abgleichen")
ap.add_argument("--host", default="0.0.0.0")
ap.add_argument("--port", type=int, default=8099)
ap.add_argument("--open", action="store_true", help="Browser automatisch oeffnen")
args = ap.parse_args()
srv = ThreadingHTTPServer((args.host, args.port), Handler)
url = "http://127.0.0.1:%d/" % args.port
print("plexmatch %s laeuft auf http://%s:%d/ (Strg+C beendet)"
% (VERSION, args.host, args.port))
print("Config: %s" % CONFIG_PATH)
if args.open:
threading.Timer(0.6, lambda: webbrowser.open(url)).start()
try:
srv.serve_forever()
except KeyboardInterrupt:
print("\nbeendet.")
finally:
srv.server_close()
if __name__ == "__main__":
main()