forked from Drakonis96/plexytrack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
4577 lines (3989 loc) · 179 KB
/
Copy pathapp.py
File metadata and controls
4577 lines (3989 loc) · 179 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
#!/usr/bin/env python3
"""
PlexyTrackt – Synchronizes Plex watched history with Trakt.
• Compatible with PlexAPI ≥ 4.15
• Safe conversion of ``viewedAt`` (datetime, numeric timestamp or string)
• Handles movies without year (``year == None``) to avoid Plex 500 errors
• Replaced ``searchShows`` (removed in PlexAPI ≥ 4.14) with generic search ``libtype="show"``
"""
import os
import json
import logging
import secrets
import hashlib
import hmac
import threading
from collections import deque
from datetime import datetime, timezone
from numbers import Number
from typing import Dict, List, Optional, Set, Tuple, Union
from functools import wraps
import time
import requests
from flask import (
Flask,
render_template,
request,
redirect,
url_for,
has_request_context,
jsonify,
)
from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.security import generate_password_hash, check_password_hash
from flask import send_file, session
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.base import STATE_STOPPED
from threading import Event, Lock, Thread
from plexapi.server import PlexServer
from plexapi.myplex import MyPlexAccount
from plexapi.exceptions import BadRequest, NotFound
from getpass import getpass
# Plex moved watchlist and other account endpoints from the old
# ``metadata.provider.plex.tv`` domain to ``discover.provider.plex.tv``.
# Override the PlexAPI constant so all watchlist operations use the
# updated base URL.
MyPlexAccount.METADATA = MyPlexAccount.DISCOVER
from utils import (
to_iso_z,
normalize_year,
_parse_guid_value,
best_guid,
imdb_guid,
get_show_from_library,
find_item_by_guid,
ensure_collection,
movie_key,
guid_to_ids,
valid_guid,
trakt_movie_key,
episode_key,
trakt_episode_key,
simkl_episode_key,
)
from plex_utils import (
get_plex_history,
update_plex,
get_user_plex_history,
get_user_watch_counts,
get_owner_watch_counts,
get_managed_user_watch_counts,
get_owner_plex_history,
get_managed_user_plex_history,
load_last_plex_sync,
save_last_plex_sync,
load_state,
migrate_legacy_state,
)
from trakt_utils import (
trakt_request,
get_trakt_history,
update_trakt,
sync_collection,
sync_ratings,
sync_liked_lists,
sync_collections_to_trakt,
sync_watchlist,
fetch_trakt_history_full,
fetch_trakt_ratings,
fetch_trakt_watchlist,
apply_trakt_ratings,
restore_backup,
get_trakt_last_activities,
should_sync_category,
load_trakt_activities,
save_trakt_activities,
import_trakt_collection,
sync_personal_lists_to_plex,
sync_playback_plex_to_trakt,
sync_playback_trakt_to_plex,
sync_trakt_recommendations_to_plex,
sync_trakt_discovery_to_plex,
)
from simkl_utils import (
simkl_request,
simkl_search_ids,
simkl_movie_key,
get_simkl_history,
update_simkl,
sync_simkl_ratings,
apply_simkl_ratings,
get_simkl_last_activities,
has_simkl_category_changed,
update_saved_activities,
sync_plex_playback_to_simkl,
sync_playback_simkl_to_plex,
sync_watchlist_plex_simkl,
sync_simkl_trending_to_plex,
)
# --------------------------------------------------------------------------- #
# LOGGING
# --------------------------------------------------------------------------- #
# Log level is configurable via PLEXYTRACK_LOG_LEVEL (DEBUG/INFO/WARNING/ERROR);
# defaults to INFO. The format includes the module name so it is clear whether a
# line comes from the web app, the Trakt/Simkl clients or the Plex helpers.
_LOG_LEVEL = getattr(
logging,
os.environ.get("PLEXYTRACK_LOG_LEVEL", "INFO").strip().upper(),
logging.INFO,
)
root_logger = logging.getLogger()
root_logger.setLevel(_LOG_LEVEL)
# Reset handlers so re-importing the module never duplicates log lines.
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
_LOG_FORMATTER = logging.Formatter(
"%(asctime)s [%(levelname)-8s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
console_handler = logging.StreamHandler()
console_handler.setFormatter(_LOG_FORMATTER)
root_logger.addHandler(console_handler)
# In-memory ring buffer that mirrors the log stream so the web UI can display
# recent activity live (see the "Logs" page). The buffer size is configurable
# via PLEXYTRACK_LOG_BUFFER (number of most recent lines to keep).
try:
_LOG_BUFFER_MAXLEN = max(100, int(os.environ.get("PLEXYTRACK_LOG_BUFFER", "2000")))
except (TypeError, ValueError):
_LOG_BUFFER_MAXLEN = 2000
class RingBufferLogHandler(logging.Handler):
"""Keep the most recent log records in memory for the live Logs page.
Every stored entry carries a monotonically increasing ``id`` so the browser
can poll for only the records it has not seen yet. A lock guards the buffer
because records arrive from scheduler and sync worker threads as well as the
request threads.
"""
def __init__(self, maxlen: int):
super().__init__()
self._buffer = deque(maxlen=maxlen)
self._lock = threading.Lock()
self._counter = 0
self._error_count = 0
def emit(self, record: logging.LogRecord) -> None:
try:
message = record.getMessage()
except Exception: # noqa: BLE001 - never let logging raise
return
entry = {
"time": datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S"),
"level": record.levelname,
"logger": record.name,
"message": message,
}
with self._lock:
self._counter += 1
if record.levelno >= logging.ERROR:
self._error_count += 1
entry["id"] = self._counter
self._buffer.append(entry)
def get_since(self, since_id: int, limit: Optional[int] = None):
"""Return buffered entries with ``id`` greater than ``since_id``."""
with self._lock:
items = [e for e in self._buffer if e["id"] > since_id]
if limit is not None and len(items) > limit:
items = items[-limit:]
return items
def latest_id(self) -> int:
with self._lock:
return self._counter
def error_count(self) -> int:
"""Total number of ERROR/CRITICAL records observed so far."""
with self._lock:
return self._error_count
log_buffer_handler = RingBufferLogHandler(_LOG_BUFFER_MAXLEN)
log_buffer_handler.setFormatter(_LOG_FORMATTER)
root_logger.addHandler(log_buffer_handler)
logger = logging.getLogger(__name__)
# Keep Flask's HTTP request logger quiet; access logging is the proxy's job.
logging.getLogger("werkzeug").setLevel(logging.WARNING)
# --------------------------------------------------------------------------- #
# APPLICATION INFO
# --------------------------------------------------------------------------- #
APP_NAME = "PlexyTrack"
APP_VERSION = "v0.5.4"
USER_AGENT = f"{APP_NAME} / {APP_VERSION}"
# --------------------------------------------------------------------------- #
# FLASK + APSCHEDULER
# --------------------------------------------------------------------------- #
app = Flask(__name__)
def _env_flag(name: str, default: bool = False) -> bool:
"""Parse a boolean-ish environment variable."""
val = os.environ.get(name)
if val is None:
return default
return val.strip().lower() in ("1", "true", "yes", "on")
def _env_int(name: str, default: int) -> int:
"""Parse an integer environment variable, falling back on bad input."""
try:
raw = os.environ.get(name)
if raw is None or raw.strip() == "":
return default
return int(raw.strip())
except (TypeError, ValueError):
return default
# --------------------------------------------------------------------------- #
# SECURITY / HARDENING CONFIGURATION (env-tunable)
# --------------------------------------------------------------------------- #
# Number of trusted reverse proxies in front of the app. When >0 the real
# client IP is read from X-Forwarded-For (required for correct per-client login
# rate limiting behind Nginx/Traefik/Caddy/etc.). Default 0 means the header is
# NOT trusted, so a directly-exposed instance cannot be tricked into accepting a
# spoofed X-Forwarded-For value. Set to the exact number of proxies you run.
TRUSTED_PROXY_COUNT = _env_int("PLEXYTRACK_TRUSTED_PROXY_COUNT", 0)
# Mark session/CSRF cookies as Secure (HTTPS-only). Enable when the app is
# served over HTTPS (strongly recommended for internet-exposed deployments).
# Left off by default so plain-HTTP LAN access keeps working out of the box.
SECURE_COOKIES = _env_flag("PLEXYTRACK_SECURE_COOKIES", False)
# Optional shared secret required by the Plex webhook endpoint. When set,
# incoming webhook requests must present ?token=<secret> (or an
# X-Webhook-Token header). Unset keeps the endpoint open (backward compatible).
WEBHOOK_TOKEN = os.environ.get("PLEXYTRACK_WEBHOOK_TOKEN", "").strip()
# Password policy. Minimum length is enforced on every new/changed password.
# MAX guards the hashing routine against denial-of-service via huge inputs.
MIN_PASSWORD_LENGTH = _env_int("PLEXYTRACK_MIN_PASSWORD_LENGTH", 8)
MAX_PASSWORD_LENGTH = 1024
# Maximum accepted request-body size (MB). Protects endpoints such as
# /backup/restore (which parses an uploaded JSON file) from memory-exhaustion
# via oversized uploads; Flask returns 413 for anything larger.
MAX_CONTENT_LENGTH_MB = _env_int("PLEXYTRACK_MAX_UPLOAD_MB", 32)
# Optional comma-separated allowlist of Host header values the app answers to.
# When set, requests with any other Host are rejected — a defence against
# Host-header injection if the container is ever reachable outside the proxy.
# Unset = accept any Host (backward compatible).
ALLOWED_HOSTS = tuple(
h.strip().lower()
for h in os.environ.get("PLEXYTRACK_ALLOWED_HOSTS", "").split(",")
if h.strip()
)
# HSTS is emitted only on responses that are actually served over HTTPS
# (request.is_secure respects X-Forwarded-Proto behind the proxy), so it is safe
# to leave enabled even for plain-HTTP LAN access.
HSTS_ENABLED = _env_flag("PLEXYTRACK_HSTS", True)
HSTS_MAX_AGE = _env_int("PLEXYTRACK_HSTS_MAX_AGE", 31536000) # 1 year
# CSRF protection settings
CSRF_COOKIE_NAME = "plexytrack_csrf"
CSRF_HEADER_NAMES = ("X-CSRFToken", "X-CSRF-Token")
CSRF_FORM_FIELD = "_csrf_token"
# Endpoints that must accept unauthenticated / cross-context POSTs.
CSRF_EXEMPT_ENDPOINTS = {"login_page", "plex_webhook", "static"}
# Honor X-Forwarded headers when running behind a reverse proxy so that
# request.url_root uses the external address and scheme. ``x_for`` is set from
# the trusted-proxy count above so client IPs used for rate limiting are only
# taken from X-Forwarded-For when a proxy is actually declared.
app.wsgi_app = ProxyFix(
app.wsgi_app, x_for=TRUSTED_PROXY_COUNT, x_proto=1, x_host=1
)
# Generate a strong random secret key if not provided via env
app.secret_key = os.environ.get('FLASK_SECRET_KEY') or secrets.token_hex(32)
# Secure session cookie settings for internet-exposed deployment
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE='Lax',
SESSION_COOKIE_SECURE=SECURE_COOKIES,
PERMANENT_SESSION_LIFETIME=86400, # 24 hours
MAX_CONTENT_LENGTH=MAX_CONTENT_LENGTH_MB * 1024 * 1024,
)
@app.context_processor
def inject_version():
return {"app_version": APP_VERSION}
SYNC_INTERVAL_MINUTES = 60 # default frequency
SYNC_COLLECTION = False
SYNC_RATINGS = True
SYNC_WATCHED = True # honoured on every sync run
SYNC_LIKED_LISTS = False
SYNC_WATCHLISTS = False
SYNC_PLAYBACK = False # mirror in-progress resume points ("continue watching")
SYNC_RECOMMENDATIONS = False # materialize recommendations/trending as Plex collections
LIVE_SYNC = False
SYNC_PROVIDER = "none" # trakt | simkl | both | none
CONFIG_DIR = os.environ.get("PLEXYTRACK_CONFIG_DIR") or "/config"
STATE_DIR = os.environ.get("PLEXYTRACK_STATE_DIR") or "/state"
AUTH_FILE = os.path.join(CONFIG_DIR, "auth.json")
STATE_FILE = os.path.join(STATE_DIR, "state.json")
PROVIDER_FILE = os.path.join(CONFIG_DIR, "provider.json")
CREDENTIALS_FILE = os.path.join(CONFIG_DIR, "credentials.json")
SELECTED_USER_FILE = os.path.join(CONFIG_DIR, "selected_user.json")
SAFE_MODE = False
scheduler = BackgroundScheduler()
plex = None # will hold PlexServer instance
plex_account = None # will hold MyPlexAccount instance
_plex_connection_ok = False # Flag: True after successful connection, False on failure
_sync_lock = Lock() # Prevent concurrent sync execution
# Sync direction constants
DIRECTION_BOTH = "both"
DIRECTION_PLEX_TO_SERVICE = "plex_to_service"
DIRECTION_SERVICE_TO_PLEX = "service_to_plex"
# Default per-sync-type direction (owner only)
HISTORY_SYNC_DIRECTION = DIRECTION_BOTH
LISTS_SYNC_DIRECTION = DIRECTION_BOTH
WATCHLISTS_SYNC_DIRECTION = DIRECTION_BOTH
RATINGS_SYNC_DIRECTION = DIRECTION_BOTH
COLLECTION_SYNC_DIRECTION = DIRECTION_BOTH
# Watchlist sync behavior
WATCHLIST_CONFLICT_RESOLUTION = "last_wins" # "last_wins" | "additive_only" | "manual"
WATCHLIST_REMOVAL_ENABLED = True
# Redirect URI management – saved URIs and active selection per service
REDIRECT_URIS = {
"trakt": {"saved": [], "active": ""},
"simkl": {"saved": [], "active": ""},
}
# Global storage for session-based Plex credentials (for scheduler access)
session_plex_credentials = {
'token': None, # Authentication token obtained via web login
'baseurl': None # Normalized server base URL
}
# Event used to cancel an ongoing sync
stop_event = Event()
# --------------------------------------------------------------------------- #
# LIVE SYNC STATUS (shared with the web UI)
# --------------------------------------------------------------------------- #
# Snapshot of the most recent / current sync run, surfaced on the Sync page so
# the user can see when a run started, when it finished and what triggered it.
_sync_state_lock = Lock()
SYNC_STATE = {
"running": False,
"trigger": None, # "scheduled" | "once" | "live"
"mode": None, # "full" | "watchlist"
"started_at": None, # ISO-8601 UTC
"finished_at": None, # ISO-8601 UTC
"result": None, # "success" | "error" | "stopped"
}
def _mark_sync_start(trigger: str, mode: str = "full") -> None:
"""Record that a sync run has just begun."""
with _sync_state_lock:
SYNC_STATE["running"] = True
SYNC_STATE["trigger"] = trigger
SYNC_STATE["mode"] = mode
SYNC_STATE["started_at"] = datetime.now(timezone.utc).isoformat()
SYNC_STATE["finished_at"] = None
SYNC_STATE["result"] = None
logger.info("Sync run started (trigger=%s, mode=%s)", trigger, mode)
def _mark_sync_finish(result: str) -> None:
"""Record that the current sync run has finished."""
with _sync_state_lock:
SYNC_STATE["running"] = False
SYNC_STATE["finished_at"] = datetime.now(timezone.utc).isoformat()
SYNC_STATE["result"] = result
logger.info("Sync run finished (result=%s)", result)
def ensure_directory(path: str) -> None:
"""Create ``path`` with 0700 permissions if missing."""
if not os.path.isdir(path):
os.makedirs(path, mode=0o700, exist_ok=True)
logger.info("Created missing directory %s; continuing start-up.", path)
def verify_volume(path: str, name: str) -> None:
"""Ensure ``path`` exists and is a mounted volume."""
if not os.path.isdir(path):
raise SystemExit(
f"Required {name} directory '{path}' is missing. Bind mount a volume."
)
if not os.path.ismount(path):
raise SystemExit(
f"{name} directory '{path}' must be a mounted volume."
)
# --------------------------------------------------------------------------- #
# AUTH / SETTINGS
# --------------------------------------------------------------------------- #
SETTINGS_FILE = os.path.join(CONFIG_DIR, "settings.json")
# --------------------------------------------------------------------------- #
# USER AUTHENTICATION (PlexyTrack login)
# --------------------------------------------------------------------------- #
_login_attempts: Dict[str, list] = {} # IP → list of timestamps
_LOGIN_MAX_ATTEMPTS = 5
_LOGIN_WINDOW_SECONDS = 300 # 5 minutes
def _is_rate_limited(ip: str) -> bool:
"""Return True if the IP has exceeded the login attempt limit."""
now = time.time()
attempts = _login_attempts.get(ip, [])
# Remove old attempts outside the window
attempts = [t for t in attempts if now - t < _LOGIN_WINDOW_SECONDS]
_login_attempts[ip] = attempts
return len(attempts) >= _LOGIN_MAX_ATTEMPTS
def _record_login_attempt(ip: str) -> None:
"""Record a failed login attempt for rate limiting."""
if ip not in _login_attempts:
_login_attempts[ip] = []
_login_attempts[ip].append(time.time())
def _reset_login_attempts(ip: str) -> None:
"""Clear recorded attempts for an IP (e.g. after a successful login)."""
_login_attempts.pop(ip, None)
def _client_ip() -> str:
"""Best-effort client IP.
``request.remote_addr`` already reflects X-Forwarded-For when
``TRUSTED_PROXY_COUNT`` > 0 (see ProxyFix setup); otherwise it is the
direct peer address, which cannot be spoofed by the client.
"""
return (request.remote_addr if has_request_context() else None) or "unknown"
def _password_meets_policy(password: str) -> bool:
"""Return True when a password satisfies the current length policy."""
return MIN_PASSWORD_LENGTH <= len(password) <= MAX_PASSWORD_LENGTH
def load_credentials() -> dict:
"""Load user credentials from CREDENTIALS_FILE."""
if os.path.exists(CREDENTIALS_FILE):
try:
with open(CREDENTIALS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as exc:
logger.error("Failed to load credentials: %s", exc)
return {}
def save_credentials(data: dict) -> None:
"""Persist user credentials to CREDENTIALS_FILE."""
try:
os.makedirs(CONFIG_DIR, exist_ok=True)
with open(CREDENTIALS_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
# Restrict file permissions so only owner can read
os.chmod(CREDENTIALS_FILE, 0o600)
except Exception as exc:
logger.error("Failed to save credentials: %s", exc)
def ensure_default_credentials() -> None:
"""Create default admin/admin credentials if none exist."""
creds = load_credentials()
if not creds.get("username") or not creds.get("password_hash"):
creds = {
"username": "admin",
"password_hash": generate_password_hash(
"admin", method="pbkdf2:sha256", salt_length=16
),
# Flags the still-default admin/admin login so the app can force a
# password change on first sign-in (see login_page).
"is_default": True,
}
save_credentials(creds)
logger.info("Default credentials created (admin/admin). Change the password!")
def verify_credentials(username: str, password: str) -> bool:
"""Verify username/password against stored credentials."""
creds = load_credentials()
stored_user = creds.get("username", "")
stored_hash = creds.get("password_hash", "")
if not stored_user or not stored_hash:
return False
# Constant-time comparison for username
user_ok = hmac.compare_digest(username.lower(), stored_user.lower())
pass_ok = check_password_hash(stored_hash, password)
return user_ok and pass_ok
def login_required(f):
"""Decorator to require authentication for a route."""
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("authenticated"):
if request.is_json or request.headers.get("X-Requested-With") == "XMLHttpRequest":
return jsonify({"success": False, "error": "Authentication required"}), 401
return redirect(url_for("login_page"))
return f(*args, **kwargs)
return decorated_function
# --------------------------------------------------------------------------- #
# CSRF PROTECTION (synchronizer token, cookie-distributed)
# --------------------------------------------------------------------------- #
def get_csrf_token() -> str:
"""Return the session CSRF token, creating one if needed."""
token = session.get("_csrf_token")
if not token:
token = secrets.token_urlsafe(32)
session["_csrf_token"] = token
return token
def _extract_request_csrf() -> str:
"""Pull the CSRF token from headers, form data or a JSON body."""
for header in CSRF_HEADER_NAMES:
val = request.headers.get(header)
if val:
return val
val = request.form.get(CSRF_FORM_FIELD)
if val:
return val
if request.is_json:
data = request.get_json(silent=True) or {}
if isinstance(data, dict) and data.get(CSRF_FORM_FIELD):
return str(data.get(CSRF_FORM_FIELD))
return ""
def _wants_json_response() -> bool:
return bool(
request.is_json
or request.headers.get("X-Requested-With") == "XMLHttpRequest"
or "application/json" in request.headers.get("Accept", "")
)
# Endpoints reachable while a forced password change is pending.
_PW_CHANGE_ALLOWED_ENDPOINTS = {
"account_password_page",
"change_password",
"logout",
"security_status",
"static",
}
@app.before_request
def _security_before_request():
"""Reject bad Host headers, enforce CSRF and forced password changes."""
# ---- Host allowlist (opt-in) --------------------------------------------
if ALLOWED_HOSTS:
host = (request.host or "").rsplit(":", 1)[0].lower()
if host not in ALLOWED_HOSTS:
logger.warning(
"Rejected request with disallowed Host %r from %s",
request.host, _client_ip(),
)
return ("Bad Request", 400)
endpoint = request.endpoint or ""
authenticated = bool(session.get("authenticated"))
# Make sure an authenticated session always carries a CSRF token so the
# cookie can be published (see _publish_csrf_cookie).
if authenticated:
get_csrf_token()
# ---- CSRF validation (only for state-changing, authenticated requests) --
if request.method not in ("GET", "HEAD", "OPTIONS", "TRACE"):
if authenticated and endpoint not in CSRF_EXEMPT_ENDPOINTS:
expected = session.get("_csrf_token", "")
provided = _extract_request_csrf()
if not expected or not provided or not hmac.compare_digest(
str(provided), str(expected)
):
logger.warning(
"CSRF validation failed for %s %s from %s",
request.method, request.path, _client_ip(),
)
if _wants_json_response():
return jsonify(
{"success": False, "error": "CSRF validation failed"}
), 400
return ("CSRF validation failed", 400)
# ---- Forced password change (default admin/admin credentials) -----------
if (
authenticated
and session.get("must_change_password")
and endpoint not in _PW_CHANGE_ALLOWED_ENDPOINTS
):
if _wants_json_response():
return jsonify(
{
"success": False,
"error": "Password change required",
"redirect": url_for("account_password_page"),
}
), 403
return redirect(url_for("account_password_page"))
return None
@app.after_request
def _publish_csrf_cookie(response):
"""Expose the CSRF token to JS via a readable, same-site cookie."""
if session.get("authenticated"):
token = session.get("_csrf_token")
if token:
response.set_cookie(
CSRF_COOKIE_NAME,
token,
max_age=86400,
samesite="Lax",
secure=SECURE_COOKIES,
httponly=False,
)
return response
@app.after_request
def _security_headers(response):
"""Attach hardening headers suitable for public (reverse-proxied) exposure."""
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Permissions-Policy"] = (
"geolocation=(), microphone=(), camera=(), payment=(), usb=()"
)
response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
# Content-Security-Policy: the UI ships inline <script>/<style> and pulls
# Google Fonts, so those are allowed explicitly. frame-ancestors 'none'
# blocks clickjacking, object-src 'none' blocks plugin injection, and
# base-uri/form-action 'self' block base-tag and form-hijacking tricks.
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline'; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
"font-src 'self' https://fonts.gstatic.com; "
"img-src 'self' data: https:; "
"connect-src 'self'; "
"base-uri 'self'; "
"form-action 'self'; "
"frame-ancestors 'none'; "
"object-src 'none'"
)
# Only advertise HSTS when the response is actually over HTTPS.
if HSTS_ENABLED and request.is_secure:
response.headers["Strict-Transport-Security"] = (
f"max-age={HSTS_MAX_AGE}; includeSubDomains"
)
# Reduce framework/version disclosure.
response.headers["Server"] = "PlexyTrack"
return response
@app.errorhandler(413)
def _too_large(_exc):
"""Clean 413 instead of a stack page when a body exceeds MAX_CONTENT_LENGTH."""
if _wants_json_response():
return jsonify({"success": False, "error": "Request too large"}), 413
return ("Request too large", 413)
@app.context_processor
def inject_csrf_token():
"""Make ``csrf_token()`` available inside templates."""
return {"csrf_token": get_csrf_token}
# --------------------------------------------------------------------------- #
# PROVIDER SELECTION
# --------------------------------------------------------------------------- #
def load_provider() -> None:
"""Load selected sync provider from file."""
global SYNC_PROVIDER
if os.path.exists(PROVIDER_FILE):
try:
with open(PROVIDER_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
SYNC_PROVIDER = data.get("provider", "none")
except Exception as exc: # noqa: BLE001
logger.error("Failed to load provider: %s", exc)
def save_provider(provider: str) -> None:
"""Persist selected sync provider to file."""
global SYNC_PROVIDER
SYNC_PROVIDER = provider
try:
with open(PROVIDER_FILE, "w", encoding="utf-8") as f:
json.dump({"provider": provider}, f, indent=2)
except Exception as exc: # noqa: BLE001
logger.error("Failed to save provider: %s", exc)
# --------------------------------------------------------------------------- #
# PERSISTENT SETTINGS
# --------------------------------------------------------------------------- #
def load_settings() -> None:
"""Load sync settings from :data:`SETTINGS_FILE` if present."""
global SYNC_INTERVAL_MINUTES, SYNC_COLLECTION, SYNC_RATINGS, SYNC_WATCHED
global SYNC_LIKED_LISTS, SYNC_WATCHLISTS, SYNC_PLAYBACK, SYNC_RECOMMENDATIONS, LIVE_SYNC
global HISTORY_SYNC_DIRECTION, LISTS_SYNC_DIRECTION
global WATCHLISTS_SYNC_DIRECTION, RATINGS_SYNC_DIRECTION, COLLECTION_SYNC_DIRECTION
global WATCHLIST_CONFLICT_RESOLUTION, WATCHLIST_REMOVAL_ENABLED
global REDIRECT_URIS
if os.path.exists(SETTINGS_FILE):
try:
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
SYNC_INTERVAL_MINUTES = int(data.get("minutes", SYNC_INTERVAL_MINUTES))
SYNC_COLLECTION = data.get("collection", SYNC_COLLECTION)
SYNC_RATINGS = data.get("ratings", SYNC_RATINGS)
SYNC_WATCHED = data.get("watched", SYNC_WATCHED)
SYNC_LIKED_LISTS = data.get("liked_lists", SYNC_LIKED_LISTS)
SYNC_WATCHLISTS = data.get("watchlists", SYNC_WATCHLISTS)
SYNC_PLAYBACK = data.get("playback", SYNC_PLAYBACK)
SYNC_RECOMMENDATIONS = data.get("recommendations", SYNC_RECOMMENDATIONS)
LIVE_SYNC = data.get("live_sync", LIVE_SYNC)
HISTORY_SYNC_DIRECTION = data.get("history_direction", HISTORY_SYNC_DIRECTION)
LISTS_SYNC_DIRECTION = data.get("lists_direction", LISTS_SYNC_DIRECTION)
WATCHLISTS_SYNC_DIRECTION = data.get(
"watchlists_direction", WATCHLISTS_SYNC_DIRECTION
)
RATINGS_SYNC_DIRECTION = data.get("ratings_direction", RATINGS_SYNC_DIRECTION)
COLLECTION_SYNC_DIRECTION = data.get(
"collection_direction", COLLECTION_SYNC_DIRECTION
)
WATCHLIST_CONFLICT_RESOLUTION = data.get("watchlist_conflict_resolution", WATCHLIST_CONFLICT_RESOLUTION)
WATCHLIST_REMOVAL_ENABLED = data.get("watchlist_removal_enabled", WATCHLIST_REMOVAL_ENABLED)
# Redirect URIs
stored_uris = data.get("redirect_uris")
if stored_uris and isinstance(stored_uris, dict):
for svc in ("trakt", "simkl"):
if svc in stored_uris and isinstance(stored_uris[svc], dict):
REDIRECT_URIS[svc]["saved"] = stored_uris[svc].get("saved", [])
REDIRECT_URIS[svc]["active"] = stored_uris[svc].get("active", "")
logger.info("Loaded sync settings from %s", SETTINGS_FILE)
except Exception as exc: # noqa: BLE001
logger.error("Failed to load settings: %s", exc)
def save_settings() -> None:
"""Persist current sync settings to :data:`SETTINGS_FILE`."""
data = {
"minutes": SYNC_INTERVAL_MINUTES,
"collection": SYNC_COLLECTION,
"ratings": SYNC_RATINGS,
"watched": SYNC_WATCHED,
"liked_lists": SYNC_LIKED_LISTS,
"watchlists": SYNC_WATCHLISTS,
"playback": SYNC_PLAYBACK,
"recommendations": SYNC_RECOMMENDATIONS,
"live_sync": LIVE_SYNC,
"history_direction": HISTORY_SYNC_DIRECTION,
"lists_direction": LISTS_SYNC_DIRECTION,
"watchlists_direction": WATCHLISTS_SYNC_DIRECTION,
"ratings_direction": RATINGS_SYNC_DIRECTION,
"collection_direction": COLLECTION_SYNC_DIRECTION,
"watchlist_conflict_resolution": WATCHLIST_CONFLICT_RESOLUTION,
"watchlist_removal_enabled": WATCHLIST_REMOVAL_ENABLED,
"redirect_uris": REDIRECT_URIS,
}
try:
with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
logger.info("Saved sync settings to %s", SETTINGS_FILE)
except Exception as exc: # noqa: BLE001
logger.error("Failed to save settings: %s", exc)
# --------------------------------------------------------------------------- #
# CUSTOM EXCEPTIONS
# --------------------------------------------------------------------------- #
class TraktAccountLimitError(Exception):
"""Raised when Trakt returns HTTP 420 (account limit exceeded)."""
pass
def get_trakt_redirect_uri() -> str:
"""Return the Trakt redirect URI.
Priority: 1) active URI from settings, 2) env var, 3) request-based, 4) default.
"""
# 1. Active URI saved via the UI
active = REDIRECT_URIS.get("trakt", {}).get("active", "")
if active:
return active
# 2. Environment variable
uri = os.environ.get("TRAKT_REDIRECT_URI")
if uri:
return uri
if has_request_context():
return request.url_root.rstrip("/") + "/oauth/trakt"
return "http://localhost:5030/oauth/trakt"
def get_simkl_redirect_uri() -> str:
"""Return the Simkl redirect URI.
Priority: 1) active URI from settings, 2) env var, 3) request-based, 4) default.
"""
# 1. Active URI saved via the UI
active = REDIRECT_URIS.get("simkl", {}).get("active", "")
if active:
return active
# 2. Environment variable
uri = os.environ.get("SIMKL_REDIRECT_URI")
if uri:
return uri
if has_request_context():
return request.url_root.rstrip("/") + "/oauth/simkl"
return "http://localhost:5030/oauth/simkl"
def normalize_baseurl(url: Optional[str]) -> Optional[str]:
"""Ensure the Plex base URL includes a scheme and no trailing slash."""
if not url:
return None
url = url.strip()
if not url.startswith(("http://", "https://")):
url = "http://" + url
return url.rstrip("/")
def _build_plex_session() -> requests.Session:
"""Return a configured requests.Session for Plex connections.
Honors env PLEX_VERIFY_SSL (true/false). Defaults to False to support
connecting via https to IPs without valid certs. Disables proxy inheritance
from the environment to avoid accidental rerouting.
"""
sess = requests.Session()
verify_env = os.environ.get("PLEX_VERIFY_SSL", "false").strip().lower()
sess.verify = verify_env in ("1", "true", "yes", "on")
# Avoid environment proxies interfering with local connections
sess.trust_env = False
return sess
def get_plex_server_legacy():
"""
Legacy fallback method using token authentication.
Used when credentials are not provided.
"""
baseurl = normalize_baseurl(os.environ.get("PLEX_BASEURL"))
token = os.environ.get("PLEX_TOKEN")
if not baseurl or not token:
return None
try:
from plexapi.server import PlexServer
return PlexServer(baseurl, token, session=_build_plex_session())
except Exception as exc:
logger.error("Failed to connect to Plex using legacy token method: %s", exc)
return None
def get_plex_server():
"""Return a connected :class:`PlexServer` instance or ``None``."""
global plex, plex_account, _plex_connection_ok
if plex is None:
from flask import has_request_context, session
token = None
baseurl = None
if has_request_context():
token = session.get('plex_token')
baseurl = session.get('plex_baseurl')
if not token or not baseurl:
stored_token, stored_baseurl = get_session_credentials()
token = token or stored_token
baseurl = baseurl or stored_baseurl
if not baseurl:
baseurl = os.environ.get("PLEX_BASEURL")
baseurl = normalize_baseurl(baseurl)
if not token:
token = os.environ.get("PLEX_TOKEN")
if not token or not baseurl:
logger.error("Missing Plex token or base URL for connection")
return None
if token and baseurl:
try:
from plexapi.server import PlexServer
plex = PlexServer(baseurl, token, session=_build_plex_session())
# Create MyPlexAccount only when absolutely necessary, and cache the account ID
try:
temp_account = MyPlexAccount(token=token)
# Cache the account ID to avoid future auto-discovery calls
plex._cached_account_id = temp_account.id
plex_account = temp_account
except Exception as acc_exc:
logger.warning("Could not create MyPlexAccount: %s", acc_exc)
plex_account = None
if plex:
plex._cached_account_id = None
_plex_connection_ok = True
logger.info("Successfully connected to Plex using token and configured base URL")
return plex
except Exception as exc:
logger.warning("Token-based authentication failed: %s", exc)
plex = None
# Last resort: legacy token-based method
legacy = get_plex_server_legacy()
if legacy is not None:
plex = legacy
_plex_connection_ok = True
else:
_plex_connection_ok = False
plex_account = None
return plex
def get_plex_account():
"""Return the authenticated MyPlexAccount instance or None."""
global plex_account
# Ensure server connection is established first (which also sets up the account)
get_plex_server()
return plex_account
# --------------------------------------------------------------------------- #
# UTILITIES
# --------------------------------------------------------------------------- #
def to_iso_z(value) -> Optional[str]:
"""Convert any ``viewedAt`` variant to ISO-8601 UTC ("...Z")."""
if value is None:
return None
if isinstance(value, datetime): # datetime / pendulum / arrow
if value.tzinfo is None:
# PlexAPI creates naive datetimes in the system's local timezone