-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.py
More file actions
4130 lines (3498 loc) · 160 KB
/
app.py
File metadata and controls
4130 lines (3498 loc) · 160 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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# app.py - Quart (async) version
from quart import Quart, request, render_template, Response, jsonify, send_file, g
import httpx
import json
import copy
import html
import argparse
import os
import posixpath
import time
import hashlib
import collections
import math
import shutil
import uuid
import sqlite3
import ipaddress
from difflib import SequenceMatcher
from datetime import datetime, timedelta
from dotenv import load_dotenv, dotenv_values
from httpx import Limits, Timeout, AsyncHTTPTransport
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from urllib.parse import unquote, urlparse
import re
from pathlib import Path
import logging # for hypercorn logging
import sys # for stderr logging
from static.language_dict import language_dict
import asyncio
try:
from rapidfuzz import fuzz
except ImportError:
fuzz = None
RAPIDFUZZ_AVAILABLE = fuzz is not None
from clients import get_torrent_client, get_client_display_name, get_available_clients
from hashing import calculate_torrent_hash_from_url, calculate_torrent_hash_from_bytes
# --- SCHEDULER AND STATE SETUP ---
app = Quart(__name__)
UPSTREAM_CLIENT: httpx.AsyncClient | None = None
torrent_client = None
# --- Monitoring & Caching Globals ---
monitoring_state = {}
monitor_task = None
torrent_status_cache = {}
CACHE_TTL = 2.0
pending_mid_resolutions = {} # Maps MID -> {"added_at": timestamp, "metadata": {...}}
# --- SSE Globals ---
connected_websockets = set()
# --- RATE LIMITING HELPER ---
class LeakyBucket:
"""
Enforces a rate limit of `limit` requests per `period` seconds.
"""
def __init__(self, limit, period):
self.limit = limit
self.period = period
self.tokens = limit
self.last_update = time.monotonic()
self.lock = asyncio.Lock()
async def acquire(self):
async with self.lock:
now = time.monotonic()
elapsed = now - self.last_update
self.last_update = now
# Refill tokens
new_tokens = elapsed * (self.limit / self.period)
self.tokens = min(self.limit, self.tokens + new_tokens)
if self.tokens >= 1:
self.tokens -= 1
return True
# Calculate wait time if empty
wait_time = (1 - self.tokens) * (self.period / self.limit)
return wait_time
# 120 requests per 60 seconds (Shared limit)
mam_autosuggest_limiter = LeakyBucket(120, 60.0)
AUTOSUGGEST_RESPONSE_CACHE_TTL_SECONDS = 7 * 24 * 60 * 60.0
AUTOSUGGEST_RESPONSE_CACHE_MAX_ENTRIES = 1000
autosuggest_cache_db_conn = None
autosuggest_cache_db_lock = asyncio.Lock()
AUTOSUGGEST_CACHE_DB_PATH = None
RESULT_DISPLAY_FIELDS = [
"date_uploaded",
"file_type",
"file_size",
"snatches",
"seeders",
"category",
"language",
"narrator",
"series",
]
LANGUAGE_BY_ID = {str(value): name for name, value in language_dict.items()}
DEFAULT_SEARCH_FILTER_DEFAULTS = {
"searchType": "all",
"search_scope": "torrents",
"hide_downloaded": False,
"search_in_title": True,
"search_in_author": True,
"search_in_series": True,
"search_in_narrator": False,
"search_in_description": False,
"search_in_tags": False,
"search_in_filenames": False,
"language_ids": [str(language_dict.get("English", 1))],
"main_cat": [],
"category_ids": [],
"flags_mode": "0",
"flag_ids": [],
"start_date": "",
"end_date": "",
"min_size": "",
"max_size": "",
"size_unit": "1048576",
"min_seeders": "",
"max_seeders": "",
"min_leechers": "",
"max_leechers": "",
"min_snatched": "",
"max_snatched": "",
}
LEGACY_CONFIG_ALIASES = {
"LOCAL_TORRENT_DOWNLOAD_PATH": ("TORRENT_DOWNLOAD_PATH",),
}
def normalize_result_display_fields(value, fallback):
allowed = set(RESULT_DISPLAY_FIELDS)
if isinstance(value, list):
items = [str(item).strip() for item in value if str(item).strip()]
return [item for item in items if item in allowed]
if isinstance(value, str):
items = [item.strip() for item in value.split(",") if item.strip()]
return [item for item in items if item in allowed] if items else fallback
return fallback
def coerce_bool(val, default: bool) -> bool:
# Already a bool? Keep it.
if isinstance(val, bool):
return val
# None / empty string => use default (don’t silently flip off)
if val is None:
return default
if isinstance(val, str) and val.strip() == "":
return default
# Int-like values
if isinstance(val, (int, float)) and not isinstance(val, bool):
if val == 1:
return True
if val == 0:
return False
return default
# String values
s = str(val).strip().lower()
true_set = {"true", "1", "t", "yes", "y", "on"}
false_set = {"false", "0", "f", "no", "n", "off"}
if s in true_set:
return True
if s in false_set:
return False
# Unknown value => default
return default
def normalize_string_list(value):
if isinstance(value, list):
items = [str(item).strip() for item in value]
elif isinstance(value, str):
stripped = value.strip()
items = [stripped] if stripped else []
else:
items = []
unique = []
seen = set()
for item in items:
if not item:
continue
if item in seen:
continue
seen.add(item)
unique.append(item)
return unique
def normalize_info_hash(value) -> str:
return str(value or "").strip().lower()
def normalize_monitoring_state_keys():
normalized_state = {}
for raw_hash, state in list(monitoring_state.items()):
normalized_hash = normalize_info_hash(raw_hash)
if not normalized_hash:
continue
existing = normalized_state.get(normalized_hash, {})
merged = dict(existing)
merged.update(state or {})
normalized_state[normalized_hash] = merged
monitoring_state.clear()
monitoring_state.update(normalized_state)
def make_autosuggest_cache_key(raw_query, query_candidates, lang_ids, main_cats, selected_fields, suggestion_limit):
payload = {
"schema": 2,
"q": normalize_spaces(raw_query).lower(),
"candidates": [str(item) for item in (query_candidates or [])],
"lang_ids": sorted({str(item) for item in (lang_ids or [])}),
"main_cats": sorted({str(item) for item in (main_cats or [])}),
"fields": [str(item) for item in (selected_fields or [])],
"limit": int(suggestion_limit),
}
return json.dumps(payload, sort_keys=True, separators=(",", ":"))
async def get_cached_autosuggest_response(cache_key):
if not await ensure_autosuggest_cache_db():
return None
now = time.time()
async with autosuggest_cache_db_lock:
conn = autosuggest_cache_db_conn
if conn is None:
return None
row = conn.execute(
"SELECT payload, expires_at FROM autosuggest_cache WHERE cache_key = ?",
(cache_key,),
).fetchone()
if not row:
return None
payload_text, expires_at = row
if float(expires_at) <= now:
conn.execute("DELETE FROM autosuggest_cache WHERE cache_key = ?", (cache_key,))
conn.commit()
return None
conn.execute(
"UPDATE autosuggest_cache SET updated_at = ? WHERE cache_key = ?",
(now, cache_key),
)
conn.commit()
try:
payload = json.loads(payload_text)
except (TypeError, json.JSONDecodeError):
async with autosuggest_cache_db_lock:
conn = autosuggest_cache_db_conn
if conn is not None:
conn.execute("DELETE FROM autosuggest_cache WHERE cache_key = ?", (cache_key,))
conn.commit()
return None
return payload if isinstance(payload, list) else None
async def set_cached_autosuggest_response(cache_key, payload):
if not await ensure_autosuggest_cache_db():
return
async with autosuggest_cache_db_lock:
conn = autosuggest_cache_db_conn
if conn is None:
return
if not isinstance(payload, list) or len(payload) == 0:
conn.execute("DELETE FROM autosuggest_cache WHERE cache_key = ?", (cache_key,))
conn.commit()
return
now = time.time()
expires_at = now + AUTOSUGGEST_RESPONSE_CACHE_TTL_SECONDS
payload_text = json.dumps(payload, separators=(",", ":"))
conn.execute(
"""
INSERT INTO autosuggest_cache (cache_key, payload, expires_at, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(cache_key) DO UPDATE SET
payload = excluded.payload,
expires_at = excluded.expires_at,
updated_at = excluded.updated_at
""",
(cache_key, payload_text, expires_at, now),
)
prune_autosuggest_cache_db_locked(conn, now)
conn.commit()
def prune_autosuggest_cache_db_locked(conn, now_epoch):
conn.execute("DELETE FROM autosuggest_cache WHERE expires_at <= ?", (now_epoch,))
row = conn.execute("SELECT COUNT(*) FROM autosuggest_cache").fetchone()
total = int(row[0]) if row else 0
overflow = total - AUTOSUGGEST_RESPONSE_CACHE_MAX_ENTRIES
if overflow > 0:
conn.execute(
"""
DELETE FROM autosuggest_cache
WHERE cache_key IN (
SELECT cache_key FROM autosuggest_cache
ORDER BY updated_at ASC
LIMIT ?
)
""",
(overflow,),
)
async def ensure_autosuggest_cache_db():
global autosuggest_cache_db_conn
async with autosuggest_cache_db_lock:
if autosuggest_cache_db_conn is not None:
return True
db_path = AUTOSUGGEST_CACHE_DB_PATH
if db_path is None:
return False
try:
db_path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(db_path), check_same_thread=False)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS autosuggest_cache (
cache_key TEXT PRIMARY KEY,
payload TEXT NOT NULL,
expires_at REAL NOT NULL,
updated_at REAL NOT NULL
)
"""
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_autosuggest_cache_expires_at ON autosuggest_cache(expires_at)"
)
prune_autosuggest_cache_db_locked(conn, time.time())
conn.commit()
autosuggest_cache_db_conn = conn
return True
except Exception as e:
app.logger.error(f"Failed to initialize autosuggest sqlite cache: {e}")
autosuggest_cache_db_conn = None
return False
async def close_autosuggest_cache_db():
global autosuggest_cache_db_conn
async with autosuggest_cache_db_lock:
if autosuggest_cache_db_conn is None:
return
autosuggest_cache_db_conn.close()
autosuggest_cache_db_conn = None
def normalize_search_filter_defaults(value):
defaults = copy.deepcopy(DEFAULT_SEARCH_FILTER_DEFAULTS)
if not isinstance(value, dict):
return defaults
bool_fields = [
"hide_downloaded",
"search_in_title",
"search_in_author",
"search_in_series",
"search_in_narrator",
"search_in_description",
"search_in_tags",
"search_in_filenames",
]
for field in bool_fields:
defaults[field] = coerce_bool(value.get(field), defaults[field])
for field in ["searchType", "search_scope"]:
raw = value.get(field, defaults[field])
text = str(raw).strip()
defaults[field] = text if text else defaults[field]
main_cats = normalize_string_list(value.get("main_cat", defaults["main_cat"]))
if "all" in main_cats:
main_cats = ["all"]
defaults["main_cat"] = main_cats
defaults["language_ids"] = normalize_string_list(value.get("language_ids", defaults["language_ids"]))
defaults["category_ids"] = normalize_string_list(value.get("category_ids", defaults["category_ids"]))
defaults["flag_ids"] = normalize_string_list(value.get("flag_ids", defaults["flag_ids"]))
flags_mode = str(value.get("flags_mode", defaults["flags_mode"])).strip()
defaults["flags_mode"] = flags_mode if flags_mode in {"0", "1"} else defaults["flags_mode"]
text_fields = [
"start_date",
"end_date",
"min_size",
"max_size",
"size_unit",
"min_seeders",
"max_seeders",
"min_leechers",
"max_leechers",
"min_snatched",
"max_snatched",
]
for field in text_fields:
raw = value.get(field, defaults[field])
defaults[field] = str(raw).strip() if raw is not None else defaults[field]
if not defaults["size_unit"]:
defaults["size_unit"] = DEFAULT_SEARCH_FILTER_DEFAULTS["size_unit"]
return defaults
AUTO_ORGANIZE_MEDIA_TYPES = [
{"id": "13", "label": "Audiobooks"},
{"id": "14", "label": "E-Books"},
{"id": "15", "label": "Musicology"},
{"id": "16", "label": "Radio"},
]
ALLOWED_AUTO_ORGANIZE_MAIN_CATS = {item["id"] for item in AUTO_ORGANIZE_MEDIA_TYPES}
def normalize_destination_paths(value, fallback_path):
fallback_root = str(fallback_path or "").strip()
if not fallback_root:
fallback_root = "/downloads/organized"
entries = []
if isinstance(value, list):
for item in value:
if isinstance(item, dict):
raw_path = item.get("path") or item.get("root_path") or item.get("destination")
raw_default = item.get("default_main_cat") or item.get("default_for") or item.get("media_type") or ""
raw_torrent_category = (
item.get("default_torrent_category")
or item.get("default_client_category")
or item.get("torrent_category")
or item.get("client_category")
or ""
)
elif isinstance(item, str):
raw_path = item
raw_default = ""
raw_torrent_category = ""
else:
continue
path = str(raw_path or "").strip()
if not path:
continue
default_main_cat = str(raw_default or "").strip()
if default_main_cat not in ALLOWED_AUTO_ORGANIZE_MAIN_CATS:
default_main_cat = ""
default_torrent_category = str(raw_torrent_category or "").strip()
entries.append({
"path": path,
"default_main_cat": default_main_cat,
"default_torrent_category": default_torrent_category,
})
elif isinstance(value, str):
path = value.strip()
if path:
entries.append({"path": path, "default_main_cat": "", "default_torrent_category": ""})
if not entries:
entries = [{"path": fallback_root, "default_main_cat": "", "default_torrent_category": ""}]
seen_defaults = set()
for entry in entries:
default_main_cat = entry.get("default_main_cat", "")
if not default_main_cat:
continue
if default_main_cat in seen_defaults:
entry["default_main_cat"] = ""
continue
seen_defaults.add(default_main_cat)
return entries
def normalize_type_specific_torrent_categories(value, fallback_destination_paths=None):
entries = []
if isinstance(value, list):
for item in value:
if not isinstance(item, dict):
continue
raw_default = item.get("default_main_cat") or item.get("default_for") or item.get("media_type") or ""
raw_torrent_category = (
item.get("default_torrent_category")
or item.get("default_client_category")
or item.get("torrent_category")
or item.get("client_category")
or ""
)
default_main_cat = str(raw_default or "").strip()
if default_main_cat not in ALLOWED_AUTO_ORGANIZE_MAIN_CATS:
continue
default_torrent_category = str(raw_torrent_category or "").strip()
if not default_torrent_category:
continue
entries.append({
"default_main_cat": default_main_cat,
"default_torrent_category": default_torrent_category,
})
if not entries and isinstance(fallback_destination_paths, list):
for item in fallback_destination_paths:
if not isinstance(item, dict):
continue
default_main_cat = str(item.get("default_main_cat") or "").strip()
if default_main_cat not in ALLOWED_AUTO_ORGANIZE_MAIN_CATS:
continue
default_torrent_category = str(item.get("default_torrent_category") or "").strip()
if not default_torrent_category:
continue
entries.append({
"default_main_cat": default_main_cat,
"default_torrent_category": default_torrent_category,
})
normalized = []
seen_defaults = set()
for entry in entries:
default_main_cat = entry["default_main_cat"]
if default_main_cat in seen_defaults:
continue
seen_defaults.add(default_main_cat)
normalized.append(entry)
return normalized
def apply_default_destination_path(default_path, destination_paths):
default_root = str(default_path or "").strip() or FALLBACK_CONFIG["ORGANIZED_PATH"]
normalized = normalize_destination_paths(destination_paths, default_root)
extras = []
for entry in normalized:
path = str(entry.get("path") or "").strip()
default_main_cat = str(entry.get("default_main_cat") or "").strip()
has_type_specific_mapping = bool(default_main_cat)
if not path:
continue
if path == default_root and not has_type_specific_mapping:
continue
extras.append({
"path": path,
"default_main_cat": default_main_cat,
"default_torrent_category": "",
})
combined = [{"path": default_root, "default_main_cat": "", "default_torrent_category": ""}] + extras
return default_root, combined
@app.before_serving
async def startup():
# 1. Load the configuration FIRST
await load_new_app_config()
if await ensure_autosuggest_cache_db():
app.logger.debug(f"Autosuggest sqlite cache ready at {AUTOSUGGEST_CACHE_DB_PATH}")
else:
app.logger.warning("Autosuggest sqlite cache unavailable; autosuggest cache disabled")
if not RAPIDFUZZ_AVAILABLE:
app.logger.warning(
"rapidfuzz is not installed; autosuggest fuzzy scoring is using difflib fallback. "
"Install requirements to enable rapidfuzz-based matching."
)
# 2. Use app.config (instead of initial_config) to check settings
if app.config.get("ENABLE_FILESYSTEM_THUMBNAIL_CACHE", True):
app.logger.debug("Cache cleanup task started")
app.add_background_task(cleanup_cache_task)
if app.config.get("AUTO_ORGANIZE_ON_SCHEDULE"):
hours = int(app.config.get("AUTO_ORGANIZE_INTERVAL_HOURS", 1))
misfire_grace_seconds = max(1, int(hours * 3600 * 0.8))
scheduler.add_job(
check_for_unorganized_torrents,
'interval',
hours=hours,
id='organize_safety_net_job',
replace_existing=True,
misfire_grace_time=misfire_grace_seconds,
)
if (app.config.get("AUTO_BUY_UPLOAD_ON_RATIO")
or app.config.get("AUTO_BUY_UPLOAD_ON_BUFFER")
or app.config.get("AUTO_BUY_UPLOAD_ON_BONUS")):
interval_hours = int(app.config.get("AUTO_BUY_UPLOAD_CHECK_INTERVAL_HOURS", 6))
misfire_grace_seconds = max(1, int(interval_hours * 3600 * 0.8))
scheduler.add_job(
check_and_buy_upload,
'interval',
hours=interval_hours,
id='upload_check_job',
replace_existing=True,
misfire_grace_time=misfire_grace_seconds,
)
scheduler.add_job(check_and_buy_upload, 'date', run_date=datetime.now() + timedelta(seconds=15), id='initial_upload_check_job')
if app.config.get("ENABLE_DYNAMIC_IP_UPDATE"):
interval_hours = int(app.config.get("DYNAMIC_IP_UPDATE_INTERVAL_HOURS", 3))
misfire_grace_seconds = max(1, int(interval_hours * 3600 * 0.8))
scheduler.add_job(
check_and_update_ip,
'interval',
hours=interval_hours,
id='ip_check_job',
replace_existing=True,
misfire_grace_time=misfire_grace_seconds,
)
scheduler.add_job(check_and_update_ip, 'date', run_date=datetime.now() + timedelta(seconds=5), id='initial_ip_check_job')
if app.config.get("AUTO_BUY_VIP"):
interval_hours = int(app.config.get("AUTO_BUY_VIP_INTERVAL_HOURS", 24))
misfire_grace_seconds = max(1, int(interval_hours * 3600 * 0.8))
scheduler.add_job(
auto_buy_vip,
'interval',
hours=interval_hours,
id='vip_buy_job',
replace_existing=True,
misfire_grace_time=misfire_grace_seconds,
)
scheduler.add_job(auto_buy_vip, 'date', run_date=datetime.now() + timedelta(seconds=10), id='initial_vip_buy_job')
app.logger.info("AUTO_BUY_VIP started")
if not scheduler.running:
scheduler.start()
app.logger.debug("AsyncIOScheduler started")
global UPSTREAM_CLIENT
transport = AsyncHTTPTransport(http2=True, retries=2)
limits = Limits(max_connections=200, max_keepalive_connections=50, keepalive_expiry=120.0)
timeout = Timeout(connect=5.0, read=15.0, write=15.0, pool=None)
UPSTREAM_CLIENT = httpx.AsyncClient(transport=transport, limits=limits, timeout=timeout)
app.logger.debug("Shared httpx AsyncClient initialized")
# --- Initialize Active Monitoring on Startup ---
metadata = load_database()
pending = [h for h, m in metadata.items() if m.get('status') == 'pending']
if pending:
app.logger.info(f"Startup: Found {len(pending)} pending torrents. Starting active monitoring.")
current_time = time.time()
for h in pending:
normalized_hash = normalize_info_hash(h)
if normalized_hash:
monitoring_state[normalized_hash] = {"added_at": current_time - 20}
start_monitoring_loop()
@app.after_serving
async def shutdown():
if scheduler.running:
scheduler.shutdown()
app.logger.info("AsyncIOScheduler shutdown")
global UPSTREAM_CLIENT
if UPSTREAM_CLIENT is not None:
await UPSTREAM_CLIENT.aclose()
UPSTREAM_CLIENT = None
app.logger.info("Shared httpx AsyncClient closed")
await close_autosuggest_cache_db()
global monitor_task
if monitor_task:
monitor_task.cancel()
# --- LOGGING CONFIGURATION (NOISY LIBS SILENCED) ---
def parse_log_level(value, default=logging.DEBUG):
"""Parse a string/int log level with fallback."""
if isinstance(value, int):
return value
if not value:
return default
level = getattr(logging, str(value).upper(), None)
return level if isinstance(level, int) else default
def parse_bool_env(value, default=False):
"""Parse boolean environment values like true/false/1/0/on/off."""
if value is None:
return default
normalized = str(value).strip().lower()
if normalized in {"1", "true", "yes", "on"}:
return True
if normalized in {"0", "false", "no", "off"}:
return False
return default
APP_LOG_LEVEL = parse_log_level(os.getenv("APP_LOG_LEVEL", "INFO"), logging.INFO)
LOG_HTTP_REQUESTS = parse_bool_env(os.getenv("LOG_HTTP_REQUESTS"), False)
LOG_HTTP_REQUESTS_INCLUDE_STATIC = parse_bool_env(os.getenv("LOG_HTTP_REQUESTS_INCLUDE_STATIC"), False)
LOG_HTTP_REQUESTS_INCLUDE_EVENTS = parse_bool_env(os.getenv("LOG_HTTP_REQUESTS_INCLUDE_EVENTS"), False)
HTTP_LOG_REDACT_QUERY_KEYS = {"q", "query", "url", "torrent_url", "download_link"}
HTTP_LOG_MAX_QUERY_LENGTH = 240
HTTP_LOG_QUIET_PATHS = {"/events"}
HTTP_LOG_STATIC_PREFIXES = ("/static/",)
def _client_ip_from_headers():
forwarded = request.headers.get("X-Forwarded-For", "")
if forwarded:
return forwarded.split(",")[0].strip()
return request.headers.get("X-Real-IP") or request.remote_addr or "-"
def _sanitize_query_args():
if not request.args:
return ""
parts = []
for key in sorted(request.args.keys()):
key_lower = key.lower()
values = request.args.getlist(key)
cleaned_values = []
for raw in values:
value = str(raw).replace("\n", " ").replace("\r", " ")
if key_lower in HTTP_LOG_REDACT_QUERY_KEYS:
cleaned_values.append(f"<redacted:{len(value)}>")
else:
cleaned_values.append(value if len(value) <= 80 else f"{value[:77]}...")
if not cleaned_values:
continue
if len(cleaned_values) == 1:
parts.append(f"{key}={cleaned_values[0]}")
else:
parts.append(f"{key}=[{','.join(cleaned_values)}]")
joined = ", ".join(parts)
if len(joined) > HTTP_LOG_MAX_QUERY_LENGTH:
joined = f"{joined[:HTTP_LOG_MAX_QUERY_LENGTH]}..."
return joined
def _should_skip_http_log(path):
if path in HTTP_LOG_QUIET_PATHS and not LOG_HTTP_REQUESTS_INCLUDE_EVENTS:
return True
if path.startswith(HTTP_LOG_STATIC_PREFIXES) and not LOG_HTTP_REQUESTS_INCLUDE_STATIC:
return True
if path in {"/favicon.ico", "/robots.txt"} and not LOG_HTTP_REQUESTS_INCLUDE_STATIC:
return True
return False
@app.before_request
async def _track_request_start():
g.request_started_at = time.monotonic()
incoming_request_id = (request.headers.get("X-Request-ID") or "").strip()
g.request_id = incoming_request_id[:64] if incoming_request_id else uuid.uuid4().hex[:12]
@app.after_request
async def _log_http_request(response):
request_id = getattr(g, "request_id", uuid.uuid4().hex[:12])
response.headers["X-Request-ID"] = request_id
if not LOG_HTTP_REQUESTS:
return response
path = request.path or "/"
if _should_skip_http_log(path):
return response
started = getattr(g, "request_started_at", None)
duration_ms = (time.monotonic() - started) * 1000 if started else 0.0
status_code = int(response.status_code)
log_msg = (
f"[HTTP] req={request_id} ip={_client_ip_from_headers()} "
f"{request.method} {path} status={status_code} duration_ms={duration_ms:.1f}"
)
query_summary = _sanitize_query_args()
if query_summary:
log_msg += f" query={query_summary}"
if status_code >= 500:
app.logger.error(log_msg)
elif status_code >= 400:
app.logger.warning(log_msg)
else:
app.logger.info(log_msg)
return response
# Configure root logger
logging.basicConfig(
level=APP_LOG_LEVEL,
format='[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
stream=sys.stderr
)
# Silence noisy libraries
logging.getLogger("httpcore").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("hpack").setLevel(logging.WARNING)
logging.getLogger("apscheduler").setLevel(logging.WARNING)
logging.getLogger("tzlocal").setLevel(logging.WARNING)
logging.getLogger("hypercorn.access").setLevel(logging.INFO)
if __name__ != '__main__':
logger = logging.getLogger('hypercorn.error')
app.logger.handlers = logger.handlers
app.logger.setLevel(APP_LOG_LEVEL)
else:
app.logger.setLevel(APP_LOG_LEVEL)
scheduler = AsyncIOScheduler()
load_dotenv()
DEFAULT_RELATIVE_PATH_TEMPLATE = os.getenv("DEFAULT_RELATIVE_PATH_TEMPLATE", "{Author}/{Title}")
# --- VERSIONING HELPER ---
def get_app_version():
"""Reads the version from version.txt in the root directory."""
try:
version_file = Path("version.txt")
if version_file.exists():
with open(version_file, "r") as f:
return f.read().strip()
except Exception as e:
app.logger.warning(f"Could not read version.txt: {e}")
return "dev" # Default fallback
# Inject APP_VERSION into all templates
@app.context_processor
def inject_version():
return dict(APP_VERSION=get_app_version())
# Define fallback values
FALLBACK_CONFIG = {
"QUART_SECRET_KEY": os.urandom(24).hex(),
"MAM_API_URL": "https://www.myanonamouse.net",
"TORRENT_CLIENT_TYPE": "qbittorrent",
"TORRENT_CLIENT_URL": "http://localhost:8080",
"TORRENT_CLIENT_USERNAME": "admin",
"TORRENT_CLIENT_PASSWORD": "",
"TORRENT_CLIENT_CATEGORY": "",
"RTORRENT_DIGEST_AUTH": False,
"MAM_ID": "",
"DATA_PATH": "./data",
"ORGANIZED_PATH": "/downloads/organized",
"DESTINATION_PATHS": [
{"path": "/downloads/organized", "default_main_cat": "", "default_torrent_category": ""}
],
"TYPE_SPECIFIC_TORRENT_CATEGORIES": [],
"LOCAL_TORRENT_DOWNLOAD_PATH": "/downloads/torrents",
"REMOTE_TORRENT_DOWNLOAD_PATH": "",
"REL_PATH_TEMPLATE": DEFAULT_RELATIVE_PATH_TEMPLATE,
"AUTO_ORGANIZE_ON_ADD": False,
"AUTO_ORGANIZE_ON_SCHEDULE": False,
"AUTO_ORGANIZE_INTERVAL_HOURS": 1,
"AUTO_ORGANIZE_USE_COPY": False,
"HAPTICS_ENABLED": True,
"ENABLE_DYNAMIC_IP_UPDATE": False,
"DYNAMIC_IP_UPDATE_INTERVAL_HOURS": 3,
"AUTO_BUY_VIP": False,
"AUTO_BUY_VIP_INTERVAL_HOURS": 24,
"AUTO_BUY_UPLOAD_ON_RATIO": False,
"AUTO_BUY_UPLOAD_RATIO_THRESHOLD": 1.5,
"AUTO_BUY_UPLOAD_RATIO_AMOUNT": 50,
"AUTO_BUY_UPLOAD_ON_BUFFER": False,
"AUTO_BUY_UPLOAD_BUFFER_THRESHOLD": 10,
"AUTO_BUY_UPLOAD_BUFFER_AMOUNT": 50,
"AUTO_BUY_UPLOAD_ON_BONUS": False,
"AUTO_BUY_UPLOAD_BONUS_THRESHOLD": 5000,
"AUTO_BUY_UPLOAD_BONUS_AMOUNT": 50,
"AUTO_BUY_UPLOAD_CHECK_INTERVAL_HOURS": 6,
"BLOCK_DOWNLOAD_ON_LOW_BUFFER": True,
"AUTO_BUY_PERSONAL_FL_ON_DOWNLOAD": False,
"ENABLE_FILESYSTEM_THUMBNAIL_CACHE": True,
"THUMBNAIL_CACHE_MAX_SIZE_MB": 500,
"MAX_SEARCH_RESULTS": 50,
"MAX_AUTOCOMPLETE_RESULTS": 20,
"RESULTS_DISPLAY_FIELDS": ["narrator", "series", "file_size", "file_type", "seeders"],
"SEARCH_FILTER_DEFAULTS": copy.deepcopy(DEFAULT_SEARCH_FILTER_DEFAULTS),
}
# Set up data directory and paths
DATA_PATH = Path(os.getenv("DATA_PATH", FALLBACK_CONFIG["DATA_PATH"])).resolve()
DATA_PATH.mkdir(parents=True, exist_ok=True)
AUTOSUGGEST_CACHE_DB_PATH = DATA_PATH / "autosuggest_cache.sqlite3"
UPLOAD_OPTIONS_FILE = Path("./static/upload_options.json")
UPLOAD_CREDIT_COST_PER_GB = 500
UPLOAD_CREDIT_MIN_GB = 50
UPLOAD_CREDIT_MAX_GB = 200
UPLOAD_CREDIT_CHUNK_SIZES = (100, 50)
VIP_COST_PER_WEEK = 1250
VIP_MAX_WEEKS = 12.85
VIP_MIN_WEEKS = 1
CONFIG_FILE = DATA_PATH / "config.json"
DATABASE_FILE = DATA_PATH / "database.json"
IP_STATE_FILE = DATA_PATH / "ip_state.json"
ENV_FILE = Path(".env")
# --- Setup:thumbnail cache ---
THUMB_CACHE_DIR = DATA_PATH / "cache/thumbnails"
# These will be set from config
ORGANIZED_PATH = None
LOCAL_TORRENT_DOWNLOAD_PATH = None
REMOTE_TORRENT_DOWNLOAD_PATH = None
def apply_legacy_config_aliases(target: dict, source):
for canonical_key, aliases in LEGACY_CONFIG_ALIASES.items():
canonical_value = source.get(canonical_key)
if canonical_value not in (None, ""):
target[canonical_key] = canonical_value
continue
for alias in aliases:
legacy_value = source.get(alias)
if legacy_value not in (None, ""):
target[canonical_key] = legacy_value
break
def get_local_torrent_download_path(config: dict) -> str:
value = (
config.get("LOCAL_TORRENT_DOWNLOAD_PATH")
or config.get("TORRENT_DOWNLOAD_PATH")
or FALLBACK_CONFIG["LOCAL_TORRENT_DOWNLOAD_PATH"]
)
return str(value).strip()
def get_remote_torrent_download_path(config: dict) -> str:
return str(config.get("REMOTE_TORRENT_DOWNLOAD_PATH") or "").strip()
def _is_relative_to_remote_base(remote_path: str, remote_base: str) -> str | None:
normalized_remote_path = posixpath.normpath(str(remote_path or "").strip())
normalized_remote_base = posixpath.normpath(str(remote_base or "").strip())
if not normalized_remote_path or not normalized_remote_base:
return None
rel_path = posixpath.relpath(normalized_remote_path, normalized_remote_base)
if rel_path in {".", ""}:
return ""
if rel_path == ".." or rel_path.startswith("../"):
return None
return rel_path
def resolve_local_save_path(config: dict, remote_save_path: str | None) -> Path | None:
local_base = get_local_torrent_download_path(config)
remote_base = get_remote_torrent_download_path(config)
raw_save_path = str(remote_save_path or "").strip()
if raw_save_path: