-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
615 lines (560 loc) · 25.7 KB
/
Copy pathapp.py
File metadata and controls
615 lines (560 loc) · 25.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
import os
import sys
import ssl
import json
import secrets
import requests
import concurrent.futures
import threading
import re
import xml.etree.ElementTree as ET
import time
from urllib.parse import quote_plus
from flask import Flask, render_template, jsonify, Response, request, redirect, url_for, session, render_template_string
from plexapi.server import PlexServer
from tvdb_v4_official import TVDB
from datetime import datetime
from functools import wraps
from dotenv import load_dotenv
# ---------------------------------------------------------------------
# CONFIGURATION — all settings load from your private .env file.
# Copy ".env.example" to ".env" and fill it in. Your .env is never
# uploaded to GitHub.
# ---------------------------------------------------------------------
load_dotenv()
# App login (protects the web UI). REQUIRED.
AUTH_USERNAME = os.getenv("AUTH_USERNAME", "admin").strip()
AUTH_PASSWORD = os.getenv("AUTH_PASSWORD", "").strip()
# Flask session secret. If you don't set one, a random key is generated
# each start (which simply means you'll have to log in again after a restart).
SECRET_KEY = os.getenv("SECRET_KEY", "").strip() or secrets.token_hex(32)
# --- Plex (REQUIRED) ---
PLEX_URL = os.getenv("PLEX_URL", "").strip()
PLEX_TOKEN = os.getenv("PLEX_TOKEN", "").strip()
# --- TheTVDB API (REQUIRED for TV missing-episode detection) ---
TVDB_API_KEY = os.getenv("TVDB_API_KEY", "").strip()
# --- Sonarr (OPTIONAL — enables the "Sonarr Get" buttons) ---
SONARR_URL = os.getenv("SONARR_URL", "http://localhost:8989/api/v3").strip()
SONARR_API_KEY = os.getenv("SONARR_API_KEY", "").strip()
# --- qBittorrent Web UI (OPTIONAL — enables "Send to qBit") ---
QBIT_URL = os.getenv("QBIT_URL", "http://localhost:8080").strip()
QBIT_USER = os.getenv("QBIT_USER", "admin").strip()
QBIT_PASS = os.getenv("QBIT_PASS", "").strip()
# --- Nyaa (anime torrent index — OPTIONAL, no key needed) ---
NYAA_BASE_URL = os.getenv("NYAA_BASE_URL", "https://nyaa.si/").strip()
NYAA_NS = {'nyaa': 'https://nyaa.si/xmlns/nyaa'}
# --- Server ---
WEB_PORT = int(os.getenv("WEB_PORT", "5090"))
HOST = os.getenv("HOST", "0.0.0.0")
DEBUG = os.getenv("FLASK_DEBUG", "false").strip().lower() in ("1", "true", "yes", "on")
# Validate the settings the app can't run without.
_required = {"PLEX_URL": PLEX_URL, "PLEX_TOKEN": PLEX_TOKEN,
"TVDB_API_KEY": TVDB_API_KEY, "AUTH_PASSWORD": AUTH_PASSWORD}
_missing = [name for name, val in _required.items() if not val]
if _missing:
print("❌ Missing required settings in your .env file: " + ", ".join(_missing))
print(" Copy '.env.example' to '.env' and fill those in, then start again.")
sys.exit(1)
app = Flask(__name__)
app.secret_key = SECRET_KEY
ssl._create_default_https_context = ssl._create_unverified_context
cache = {"data": {}}
lang_cache = {"data": {}}
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if not session.get('logged_in'):
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated
def get_plex():
return PlexServer(PLEX_URL, PLEX_TOKEN)
def resolve_items(section, coll_name):
"""Return the list of items for a library, honoring a collection filter.
Looks the collection up by exact title so filtering is deterministic."""
if coll_name and coll_name != 'All':
target = next((c for c in section.collections() if c.title == coll_name), None)
return target.items() if target else []
return section.all()
# --- Background scan manager -----------------------------------------
# Scans run in a daemon thread so they keep going even if the user
# navigates away. State + results live server-side and are restored on
# page load. A generation counter supersedes an old scan when SCAN is hit.
scans = {
"dash": {"status": "idle", "current": 0, "total": 0, "results": [], "error": None, "gen": 0},
"lang": {"status": "idle", "current": 0, "total": 0, "results": [], "error": None, "gen": 0},
}
scan_lock = threading.Lock()
def start_scan(key, target, args):
st = scans[key]
with scan_lock:
st["gen"] += 1
gen = st["gen"]
st["status"] = "running"
st["current"] = 0
st["total"] = 0
st["results"] = []
st["error"] = None
threading.Thread(target=target, args=(gen,) + tuple(args), daemon=True).start()
return gen
def update_episode_timestamp(rating_key, season, episode, action_type):
show = cache["data"].get(str(rating_key))
if show:
for ep in show['episodes']:
if int(ep['season']) == int(season) and int(ep['number']) == int(episode):
ep['last_action'] = f"{action_type} on {datetime.now().strftime('%m/%d %H:%M')}"
return True
return False
def update_season_timestamps(rating_key, season, action_type):
show = cache["data"].get(str(rating_key))
if show:
ts = f"{action_type} on {datetime.now().strftime('%m/%d %H:%M')}"
for ep in show['episodes']:
if int(ep['season']) == int(season) and not ep['exists']:
ep['last_action'] = ts
return True
return False
# --- ROUTES ---
@app.route('/proxy/image')
@requires_auth
def proxy_image():
img_path = request.args.get('path')
if not img_path: return "No path", 400
proxied_url = f"{PLEX_URL}{img_path}"
try:
img_res = requests.get(proxied_url, params={'X-Plex-Token': PLEX_TOKEN}, stream=True, timeout=10)
return Response(img_res.content, mimetype=img_res.headers.get('Content-Type', 'image/jpeg'))
except: return "Error", 500
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != AUTH_USERNAME or request.form['password'] != AUTH_PASSWORD:
error = 'Invalid Credentials.'
else:
session['logged_in'] = True
return redirect(url_for('index'))
return render_template_string('''
<body style="background:#020617;color:white;display:flex;justify-content:center;align-items:center;height:100vh;font-family:-apple-system,sans-serif;margin:0;">
<form method="post" style="background:#0f172a;padding:2.5rem;border-radius:24px;width:100%;max-width:340px;border:1px solid #1e293b;">
<h1 style="text-align:center;color:#38bdf8;margin-bottom:2rem;font-weight:900;">TV MISSING</h1>
{% if error %}<p style="color:#f43f5e;text-align:center;font-weight:bold;">{{error}}</p>{% endif %}
<input type="text" name="username" placeholder="Username" required style="width:100%;margin-bottom:15px;padding:16px;background:#020617;color:white;border:1px solid #334155;border-radius:12px;font-size:16px;">
<input type="password" name="password" placeholder="Password" required style="width:100%;margin-bottom:20px;padding:16px;background:#020617;color:white;border:1px solid #334155;border-radius:12px;font-size:16px;">
<button type="submit" style="width:100%;padding:16px;background:#38bdf8;border:none;font-weight:900;color:#020617;border-radius:12px;font-size:16px;">SIGN IN</button>
</form>
</body>''', error=error)
@app.route('/')
@requires_auth
def index():
return render_template('index.html')
@app.route('/api/structure')
@requires_auth
def get_structure():
plex = get_plex()
return jsonify([{"name": s.title, "collections": [c.title for c in s.collections()]} for s in plex.library.sections() if s.type == 'show'])
@app.route('/api/stream')
@requires_auth
def stream():
lib_name, coll_name = request.args.get('library'), request.args.get('collection')
def generate():
global cache
today = datetime.now().strftime("%Y-%m-%d")
plex = get_plex()
tvdb = TVDB(TVDB_API_KEY)
library = plex.library.section(lib_name)
items = library.all() if coll_name == 'All' else library.collection(coll_name).items()
total_shows = len(items)
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
future_to_show = {executor.submit(process_single_show, s, tvdb, today): i for i, s in enumerate(items)}
for future in concurrent.futures.as_completed(future_to_show):
res = future.result()
if "skip" in res: continue
if res["id"] in cache["data"]:
old_eps = { (e['season'], e['number']): e.get('last_action') for e in cache["data"][res["id"]]['episodes'] }
for new_ep in res['episodes']:
new_ep['last_action'] = old_eps.get((new_ep['season'], new_ep['number']))
cache["data"][res["id"]] = res
yield f"data: {json.dumps({**res, 'current': future_to_show[future]+1, 'total': total_shows})}\n\n"
yield "event: finished\ndata: done\n\n"
return Response(generate(), mimetype='text/event-stream')
@app.route('/show/<rating_key>')
@requires_auth
def show_detail(rating_key):
show_data = cache["data"].get(str(rating_key))
if not show_data: return "Scan required.", 404
return render_template('detail.html', show=show_data)
@app.route('/api/sonarr/search', methods=['POST'])
@requires_auth
def sonarr_search():
data = request.json
headers = {'X-Api-Key': SONARR_API_KEY}
try:
series_res = requests.get(f"{SONARR_URL}/series", headers=headers).json()
target = re.sub(r'[^a-z0-9]', '', data['show_title'].lower())
series = next((s for s in series_res if re.sub(r'[^a-z0-9]', '', s['title'].lower()) == target), None)
if not series: return jsonify({"error": "Show not in Sonarr"}), 404
if data.get('episode'):
ep_res = requests.get(f"{SONARR_URL}/episode", params={'seriesId': series['id'], 'seasonNumber': data['season']}, headers=headers).json()
ep = next((e for e in ep_res if e['episodeNumber'] == int(data['episode'])), None)
if ep:
requests.post(f"{SONARR_URL}/command", json={"name": "EpisodeSearch", "episodeIds": [ep['id']]}, headers=headers)
update_episode_timestamp(data['rating_key'], data['season'], data['episode'], "Sonarr Get")
else:
requests.post(f"{SONARR_URL}/command", json={"name": "SeasonSearch", "seriesId": series['id'], "seasonNumber": int(data['season'])}, headers=headers)
update_season_timestamps(data['rating_key'], data['season'], "Sonarr Season Get")
return jsonify({"success": True})
except Exception as e: return jsonify({"error": str(e)}), 500
@app.route('/api/manual_get', methods=['POST'])
@requires_auth
def manual_get():
data = request.json
if data.get('episode'):
success = update_episode_timestamp(data['rating_key'], data['season'], data['episode'], "Manual Get")
else:
success = update_season_timestamps(data['rating_key'], data['season'], "Manual Season Get")
if success: return jsonify({"success": True})
return jsonify({"error": "Show not found in cache"}), 404
def process_single_show(show, tvdb, today):
try:
show.reload()
tvdb_id = next((guid.id.split('://')[1] for guid in show.guids if 'tvdb' in guid.id), None)
if not tvdb_id: return {"skip": True, "id": str(show.ratingKey)}
tvdb_data = tvdb.get_series_episodes(tvdb_id, lang="eng")
proxy_thumb = f"/proxy/image?path={quote_plus(show.thumb)}"
# Added 'addedAt' to support dashboard sorting
show_obj = {
"id": str(show.ratingKey),
"title": show.title,
"thumb": proxy_thumb,
"addedAt": str(show.addedAt.isoformat()),
"has_gaps": False,
"missing_count": 0,
"episodes": []
}
plex_episodes = set((int(getattr(e, 'parentIndex', 0)), int(e.index)) for e in show.episodes())
for ep in tvdb_data.get('episodes', []):
s, n, d = ep.get('seasonNumber'), ep.get('number'), ep.get('aired')
if not d or d > today or s == 0: continue
exists = (s, n) in plex_episodes
if not exists: show_obj["has_gaps"], show_obj["missing_count"] = True, show_obj["missing_count"] + 1
show_obj["episodes"].append({"exists": exists, "season": s, "number": n, "name": ep.get('name'), "last_action": None})
return show_obj
except: return {"skip": True, "id": str(show.ratingKey)}
# =====================================================================
# ================== LANGUAGE GAPS TAB ===============================
# =====================================================================
def get_track_langs(item):
"""Return (audio_codes, sub_codes) as sets of lowercase ISO-639 codes.
Unknown/untagged tracks are recorded as 'und'."""
audio, subs = set(), set()
try:
item.reload()
except Exception:
pass
for media in (getattr(item, 'media', None) or []):
for part in (getattr(media, 'parts', None) or []):
for stream in (getattr(part, 'streams', None) or []):
code = (getattr(stream, 'languageCode', None) or 'und').lower()
st = getattr(stream, 'streamType', None)
if st == 2:
audio.add(code)
elif st == 3:
subs.add(code)
return audio, subs
def file_matches(audio, subs, f):
"""f = dict with lists audio_exclude, sub_exclude, audio_require, sub_require
and bool ignore_und. A file is flagged when it satisfies ALL the criteria.
With ignore_und, an untagged ('und') track is treated as possibly being the
language in question, so it disqualifies an 'exclude' match (benefit of the
doubt that it's really English)."""
ignore_und = f.get('ignore_und')
for l in f['audio_exclude']:
if l in audio: return False
if ignore_und and f['audio_exclude'] and 'und' in audio:
return False
for l in f['sub_exclude']:
if l in subs: return False
if ignore_und and f['sub_exclude'] and 'und' in subs:
return False
for l in f['audio_require']:
if l not in audio: return False
for l in f['sub_require']:
if l not in subs: return False
return True
def parse_lang_filters(args):
def split(key):
return [x.strip().lower() for x in args.get(key, '').split(',') if x.strip()]
return {
'audio_exclude': split('audio_exclude'),
'sub_exclude': split('sub_exclude'),
'audio_require': split('audio_require'),
'sub_require': split('sub_require'),
'ignore_und': args.get('ignore_und') in ('1', 'true', 'True', 'on'),
}
def process_show_lang(show, f):
try:
show.reload()
proxy_thumb = f"/proxy/image?path={quote_plus(show.thumb)}"
obj = {
"id": str(show.ratingKey), "title": show.title, "thumb": proxy_thumb,
"addedAt": str(show.addedAt.isoformat()), "type": "show",
"flagged": [], "flagged_count": 0
}
for ep in show.episodes():
a, s = get_track_langs(ep)
if file_matches(a, s, f):
obj["flagged"].append({
"ratingKey": str(ep.ratingKey),
"season": int(getattr(ep, 'parentIndex', 0) or 0),
"number": int(getattr(ep, 'index', 0) or 0),
"name": ep.title,
"audio": sorted(a), "subs": sorted(s), "last_action": None
})
obj["flagged"].sort(key=lambda e: (e["season"], e["number"]))
obj["flagged_count"] = len(obj["flagged"])
return obj if obj["flagged_count"] else {"skip": True}
except Exception:
return {"skip": True}
def process_movie_lang(movie, f):
try:
a, s = get_track_langs(movie)
if not file_matches(a, s, f):
return {"skip": True}
proxy_thumb = f"/proxy/image?path={quote_plus(movie.thumb)}"
return {
"id": str(movie.ratingKey), "title": movie.title, "thumb": proxy_thumb,
"addedAt": str(movie.addedAt.isoformat()), "type": "movie",
"flagged_count": 1,
"flagged": [{
"ratingKey": str(movie.ratingKey),
"season": 0, "number": 0, "name": movie.title,
"audio": sorted(a), "subs": sorted(s), "last_action": None
}]
}
except Exception:
return {"skip": True}
@app.route('/languages')
@requires_auth
def languages():
return render_template('languages.html')
@app.route('/api/all_libraries')
@requires_auth
def all_libraries():
plex = get_plex()
out = []
for s in plex.library.sections():
if s.type in ('show', 'movie'):
try:
colls = [c.title for c in s.collections()]
except Exception:
colls = []
out.append({"name": s.title, "type": s.type, "collections": colls})
return jsonify(out)
# --- Language scan: background runner + start/state endpoints --------
def run_lang_scan(gen, lib_name, coll_name, f):
st = scans["lang"]
try:
plex = get_plex()
section = plex.library.section(lib_name)
items = resolve_items(section, coll_name)
st["total"] = len(items)
worker = process_show_lang if section.type == 'show' else process_movie_lang
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
futures = [executor.submit(worker, it, f) for it in items]
for future in concurrent.futures.as_completed(futures):
if st["gen"] != gen:
return # superseded by a newer scan
st["current"] += 1
res = future.result()
if res and not res.get("skip"):
lang_cache["data"][res["id"]] = res
st["results"].append(res)
except Exception as e:
if st["gen"] == gen:
st["error"] = str(e)
if st["gen"] == gen:
st["status"] = "done"
@app.route('/api/lang_scan/start', methods=['POST'])
@requires_auth
def lang_scan_start():
d = request.json or {}
f = parse_lang_filters(d)
lang_cache["data"] = {}
start_scan("lang", run_lang_scan, (d.get('library'), d.get('collection', 'All'), f))
return jsonify({"ok": True})
@app.route('/api/lang_scan/state')
@requires_auth
def lang_scan_state():
st = scans["lang"]
slim = [{
"id": r["id"], "title": r["title"], "thumb": r["thumb"],
"addedAt": r["addedAt"], "type": r["type"], "flagged_count": r["flagged_count"]
} for r in st["results"] if r["flagged_count"] > 0]
return jsonify({"status": st["status"], "current": st["current"],
"total": st["total"], "error": st["error"], "results": slim})
# --- Dashboard (TV gaps) scan: background runner + start/state --------
def run_dash_scan(gen, lib_name, coll_name):
st = scans["dash"]
try:
today = datetime.now().strftime("%Y-%m-%d")
plex = get_plex()
tvdb = TVDB(TVDB_API_KEY)
library = plex.library.section(lib_name)
items = resolve_items(library, coll_name)
st["total"] = len(items)
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(process_single_show, s, tvdb, today) for s in items]
for future in concurrent.futures.as_completed(futures):
if st["gen"] != gen:
return
st["current"] += 1
res = future.result()
if "skip" in res:
continue
if res["id"] in cache["data"]:
old = {(e['season'], e['number']): e.get('last_action') for e in cache["data"][res["id"]]['episodes']}
for ne in res['episodes']:
ne['last_action'] = old.get((ne['season'], ne['number']))
cache["data"][res["id"]] = res
st["results"].append(res)
except Exception as e:
if st["gen"] == gen:
st["error"] = str(e)
if st["gen"] == gen:
st["status"] = "done"
@app.route('/api/dash_scan/start', methods=['POST'])
@requires_auth
def dash_scan_start():
d = request.json or {}
start_scan("dash", run_dash_scan, (d.get('library'), d.get('collection', 'All')))
return jsonify({"ok": True})
@app.route('/api/dash_scan/state')
@requires_auth
def dash_scan_state():
st = scans["dash"]
slim = [{
"id": r["id"], "title": r["title"], "thumb": r["thumb"], "addedAt": r["addedAt"],
"has_gaps": r["has_gaps"], "missing_count": r["missing_count"]
} for r in st["results"]]
return jsonify({"status": st["status"], "current": st["current"],
"total": st["total"], "error": st["error"], "results": slim})
@app.route('/lang_show/<rating_key>')
@requires_auth
def lang_show_detail(rating_key):
show_data = lang_cache["data"].get(str(rating_key))
if not show_data:
return "Scan required.", 404
return render_template('lang_detail.html', show=show_data)
@app.route('/api/nyaa_search')
@requires_auth
def nyaa_search():
query = request.args.get('q', '')
sort_key = request.args.get('sort', 'seeders')
filter_type = request.args.get('f', '0')
page = request.args.get('p', '1')
results = []
if query:
search_url = (f"{NYAA_BASE_URL}?page=rss&q={quote_plus(query)}&c=1_2&f={filter_type}"
f"&s={sort_key}&o=desc&p={page}&_={int(time.time())}")
try:
r = requests.get(search_url, timeout=12)
root = ET.fromstring(r.content)
for item in root.findall('./channel/item'):
raw_size = item.find('nyaa:size', NYAA_NS).text
desc = item.find('description').text or ""
magnet = ""
if 'magnet:?' in desc:
magnet = desc.split(' - ')[0].strip()
results.append({
'title': item.find('title').text,
'link': item.find('link').text,
'guid': item.find('guid').text,
'magnet': magnet,
'size': raw_size,
'seeders': int(item.find('nyaa:seeders', NYAA_NS).text or 0)
})
if sort_key == 'seeders':
results.sort(key=lambda x: x['seeders'], reverse=True)
except Exception as e:
return jsonify({"error": str(e)}), 500
return jsonify(results)
@app.route('/api/nyaa_download')
@requires_auth
def nyaa_download():
torrent_url = request.args.get('url')
name = request.args.get('name', 'anime')
safe_name = "".join([c for c in name if c.isalnum() or c in (' ', '.', '-', '_')]).strip()
if not safe_name.lower().endswith(".torrent"):
safe_name += ".torrent"
try:
r = requests.get(torrent_url, stream=True, timeout=20)
return Response(r.iter_content(chunk_size=4096), headers={
"Content-Disposition": f'attachment; filename="{safe_name}"',
"Content-Type": "application/x-bittorrent"
})
except Exception:
return "Failed", 500
@app.route('/api/qbit_add', methods=['POST'])
@requires_auth
def qbit_add():
data = request.json or {}
link = data.get('magnet') or data.get('url')
if not link:
return jsonify({"error": "No magnet or url"}), 400
try:
s = requests.Session()
login = s.post(f"{QBIT_URL}/api/v2/auth/login",
data={'username': QBIT_USER, 'password': QBIT_PASS},
headers={'Referer': QBIT_URL}, timeout=10)
if login.text.strip() != 'Ok.':
return jsonify({"error": "qBittorrent login failed"}), 401
add = s.post(f"{QBIT_URL}/api/v2/torrents/add",
data={'urls': link}, headers={'Referer': QBIT_URL}, timeout=20)
if add.status_code == 200 and add.text.strip() in ('Ok.', ''):
# stamp the cache so the detail page shows it was handled
update_lang_action(data.get('rating_key'), data.get('season'), data.get('episode'), "Sent to qBit")
return jsonify({"success": True})
return jsonify({"error": f"qBittorrent error: {add.text[:200]}"}), 500
except Exception as e:
return jsonify({"error": str(e)}), 500
def update_lang_action(rating_key, season, episode, action_type):
show = lang_cache["data"].get(str(rating_key))
if not show:
return False
ts = f"{action_type} on {datetime.now().strftime('%m/%d %H:%M')}"
for ep in show['flagged']:
if episode is None or (int(ep['season']) == int(season) and int(ep['number']) == int(episode)):
ep['last_action'] = ts
return True
def remove_flagged(show_rating_key, ep_rating_key):
show = lang_cache["data"].get(str(show_rating_key))
if not show:
return
show['flagged'] = [e for e in show['flagged'] if str(e.get('ratingKey')) != str(ep_rating_key)]
show['flagged_count'] = len(show['flagged'])
@app.route('/api/plex_delete', methods=['POST'])
@requires_auth
def plex_delete():
"""Delete an episode/movie (and its file) from Plex. Requires 'Allow media
deletion' to be enabled in the Plex server settings."""
data = request.json or {}
ep_rk = data.get('episode_rating_key')
show_rk = data.get('show_rating_key')
if not ep_rk:
return jsonify({"error": "No rating key"}), 400
try:
plex = get_plex()
item = plex.fetchItem(int(ep_rk))
item.delete()
remove_flagged(show_rk, ep_rk)
return jsonify({"success": True})
except Exception as e:
msg = str(e)
if 'allowMediaDeletion' in msg or '401' in msg or '403' in msg:
msg = "Plex refused deletion. Enable 'Allow media deletion' in Plex settings."
return jsonify({"error": msg}), 500
if __name__ == '__main__':
print(f"🎬 Plex Missing starting on http://localhost:{WEB_PORT}")
print(f" Log in with the username/password from your .env file.")
app.run(host=HOST, port=WEB_PORT, debug=DEBUG, threaded=True)