-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
2894 lines (2371 loc) · 114 KB
/
app.py
File metadata and controls
2894 lines (2371 loc) · 114 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
import os
import sys
import json
import queue
from flask import Flask, render_template, jsonify, request, redirect, url_for, flash, session, abort, send_file, make_response
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from flask_wtf.csrf import CSRFProtect
from dotenv import load_dotenv
from models import init_db, get_session, Settings, User, Movie, HolidayChannel, MovieOverride
from plex_api import PlexAPI
from scheduler import ScheduleGenerator
from auth import PlexOAuth, create_or_update_plex_user
from user_management import user_mgmt_bp, validate_invite_code, mark_invite_used
import livetv
import utils
import logging
from datetime import datetime, timedelta
from urllib.parse import urlparse, urljoin
import requests
from io import BytesIO
from collections import OrderedDict
load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Bounded LRU cache for images (max 300 posters ~150MB)
class BoundedImageCache:
def __init__(self, max_size=300):
self.cache = OrderedDict()
self.max_size = max_size
def get(self, key):
if key in self.cache:
# Move to end (most recently used)
self.cache.move_to_end(key)
return self.cache[key]
return None
def set(self, key, value):
if key in self.cache:
# Update existing and move to end
self.cache.move_to_end(key)
self.cache[key] = value
# Evict oldest if over limit
if len(self.cache) > self.max_size:
oldest = next(iter(self.cache))
logger.info(f"Evicting oldest cached poster: {oldest}")
del self.cache[oldest]
def __contains__(self, key):
return key in self.cache
image_cache = BoundedImageCache(max_size=300)
def time_to_minutes(time_str):
"""Convert HH:MM time string to minutes from midnight"""
try:
hours, minutes = map(int, time_str.split(':'))
return hours * 60 + minutes
except:
return 0
def get_current_minutes():
"""Get current time in minutes from midnight"""
now = datetime.now()
return now.hour * 60 + now.minute
def is_safe_url(target):
"""Validate redirect URL is safe (relative to current host)"""
if not target:
return False
ref_url = urlparse(request.host_url)
test_url = urlparse(urljoin(request.host_url, target))
return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc
app = Flask(__name__, template_folder='pages')
session_secret = os.getenv('SESSION_SECRET')
if not session_secret or session_secret == 'dev-secret-key-change-in-production':
if os.getenv('FLASK_ENV') == 'production':
logger.error("CRITICAL: SESSION_SECRET not set in production! Application will not start.")
sys.exit(1)
else:
logger.warning("WARNING: Using default SESSION_SECRET. Set SESSION_SECRET environment variable for production!")
session_secret = 'dev-secret-key-change-in-production'
app.secret_key = session_secret
app.config['SESSION_COOKIE_SECURE'] = os.getenv('FLASK_ENV') == 'production'
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['REMEMBER_COOKIE_SECURE'] = os.getenv('FLASK_ENV') == 'production'
app.config['REMEMBER_COOKIE_HTTPONLY'] = True
app.config['REMEMBER_COOKIE_SAMESITE'] = 'Lax'
app.config['REMEMBER_COOKIE_DURATION'] = timedelta(days=365)
app.config['WTF_CSRF_TIME_LIMIT'] = None
csrf = CSRFProtect(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
app.register_blueprint(user_mgmt_bp)
@login_manager.user_loader
def load_user(user_id):
db_session = get_session()
return db_session.query(User).filter_by(id=int(user_id)).first()
db_session = None
plex_api = None
scheduler = None
def run_migrations():
"""Run database migrations for new columns and tables"""
import sqlite3
from models import get_db_path
logger.info("Running database migrations...")
db_path = get_db_path()
logger.info(f"Using database: {db_path}")
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Add channel numbers to settings table if it doesn't exist
try:
cursor.execute("ALTER TABLE settings ADD COLUMN enable_channel_numbers BOOLEAN DEFAULT 1")
logger.info("Added column: enable_channel_numbers to settings")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower() or "no such table" in str(e).lower():
pass
else:
logger.warning(f"Error adding enable_channel_numbers: {e}")
# Add brightness control to settings table if it doesn't exist
try:
cursor.execute("ALTER TABLE settings ADD COLUMN current_glow_brightness INTEGER DEFAULT 100")
logger.info("Added column: current_glow_brightness to settings")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower() or "no such table" in str(e).lower():
pass
else:
logger.warning(f"Error adding current_glow_brightness: {e}")
# Add TMDB API key to settings table if it doesn't exist
try:
cursor.execute("ALTER TABLE settings ADD COLUMN tmdb_api_key VARCHAR")
logger.info("Added column: tmdb_api_key to settings")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower() or "no such table" in str(e).lower():
pass
else:
logger.warning(f"Error adding tmdb_api_key: {e}")
# Add selected movie libraries to settings table if it doesn't exist
try:
cursor.execute("ALTER TABLE settings ADD COLUMN selected_movie_libraries TEXT")
logger.info("Added column: selected_movie_libraries to settings")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower() or "no such table" in str(e).lower():
pass
else:
logger.warning(f"Error adding selected_movie_libraries: {e}")
# Add Plex machine identifier to settings table if it doesn't exist
try:
cursor.execute("ALTER TABLE settings ADD COLUMN plex_machine_identifier VARCHAR")
logger.info("Added column: plex_machine_identifier to settings")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower() or "no such table" in str(e).lower():
pass
else:
logger.warning(f"Error adding plex_machine_identifier: {e}")
# Add Live TV enabled flag to settings table if it doesn't exist
try:
cursor.execute("ALTER TABLE settings ADD COLUMN live_tv_enabled BOOLEAN DEFAULT 0")
logger.info("Added column: live_tv_enabled to settings")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower() or "no such table" in str(e).lower():
pass
else:
logger.warning(f"Error adding live_tv_enabled: {e}")
# Add user preference columns to users table if they don't exist
user_columns = [
('enable_crt_mode', 'BOOLEAN DEFAULT 0'),
('enable_film_grain', 'BOOLEAN DEFAULT 0'),
('playback_mode', 'VARCHAR DEFAULT "web_player"'),
('enable_time_offset', 'BOOLEAN DEFAULT 1'),
('visible_channels', 'TEXT'),
('plex_client', 'VARCHAR'),
('current_glow_brightness', 'INTEGER DEFAULT 100'),
('using_default_password', 'BOOLEAN DEFAULT 0')
]
for column_name, column_def in user_columns:
try:
cursor.execute(f"ALTER TABLE users ADD COLUMN {column_name} {column_def}")
logger.info(f"Added user column: {column_name}")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower() or "no such table" in str(e).lower():
pass
else:
logger.warning(f"Error adding user {column_name}: {e}")
# Add movie metadata columns
movie_columns = [
('audience_rating', 'REAL'),
('content_rating', 'VARCHAR'),
('cast', 'VARCHAR'),
('art_url', 'VARCHAR'),
('library_name', 'VARCHAR')
]
for column_name, column_def in movie_columns:
try:
cursor.execute(f"ALTER TABLE movies ADD COLUMN {column_name} {column_def}")
logger.info(f"Added movie column: {column_name}")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower() or "no such table" in str(e).lower():
pass
else:
logger.warning(f"Error adding movie {column_name}: {e}")
# Create watch_history table if not exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS watch_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
movie_id INTEGER,
plex_id VARCHAR NOT NULL,
movie_title VARCHAR NOT NULL,
movie_genre VARCHAR,
watched_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
duration_watched INTEGER,
playback_position INTEGER DEFAULT 0,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (movie_id) REFERENCES movies(id)
)
''')
# Add playback_position to existing watch_history table
try:
cursor.execute("ALTER TABLE watch_history ADD COLUMN playback_position INTEGER DEFAULT 0")
logger.info("Added column: playback_position to watch_history")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e).lower() or "no such table" in str(e).lower():
pass
else:
logger.warning(f"Error adding playback_position: {e}")
# Create channel_favorites table if not exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS channel_favorites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
channel_name VARCHAR NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
UNIQUE(user_id, channel_name)
)
''')
# Create movie_favorites table if not exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS movie_favorites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
movie_id INTEGER NOT NULL,
plex_id VARCHAR NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (movie_id) REFERENCES movies(id),
UNIQUE(user_id, movie_id)
)
''')
conn.commit()
conn.close()
logger.info("Database migrations complete")
def create_default_accounts():
"""Create default demo accounts for first-time users"""
db_session = get_session()
# Create admin account if it doesn't exist
admin_user = db_session.query(User).filter_by(username='admin').first()
if not admin_user:
admin_user = User(
username='admin',
email='admin@popcorn.local',
is_admin=True,
using_default_password=True
)
admin_user.set_password('admin')
db_session.add(admin_user)
logger.info("Created default admin account (username: admin, password: admin)")
# Create demo account if it doesn't exist
demo_user = db_session.query(User).filter_by(username='demo').first()
if not demo_user:
demo_user = User(
username='demo',
email='demo@popcorn.local',
is_admin=False,
using_default_password=True
)
demo_user.set_password('demo')
db_session.add(demo_user)
logger.info("Created default demo account (username: demo, password: demo)")
db_session.commit()
def initialize_app():
global db_session, plex_api, scheduler
logger.info("Initializing Popcorn app...")
# Check if data volume is properly mounted
from models import is_volume_properly_mounted
is_mounted, warning_msg = is_volume_properly_mounted()
app.config['VOLUME_MOUNTED'] = is_mounted
app.config['VOLUME_WARNING'] = warning_msg
if not is_mounted and warning_msg:
logger.error("=" * 80)
logger.error(warning_msg)
logger.error("Add volume mapping when running container:")
logger.error(" docker run -v /path/on/host:/data ...")
logger.error("=" * 80)
# Run migrations before initializing database
run_migrations()
db_session = init_db()
logger.info("Database initialized")
# Create default accounts for demo/evaluation purposes
create_default_accounts()
try:
settings_obj = db_session.query(Settings).first()
plex_api = PlexAPI(db_settings=settings_obj)
logger.info("Plex API connected")
# Auto-populate settings from environment variables if not already set
# This ensures Plex OAuth login works when using env vars for configuration
if settings_obj:
settings_updated = False
# Save plex_url and plex_token if they came from environment variables
if not settings_obj.plex_url and plex_api.base_url:
settings_obj.plex_url = plex_api.base_url
settings_updated = True
logger.info(f"Auto-saved PLEX_URL from environment: {plex_api.base_url}")
if not settings_obj.plex_token and plex_api.token:
settings_obj.plex_token = plex_api.token
settings_updated = True
logger.info("Auto-saved PLEX_TOKEN from environment")
# Auto-save machine identifier for Plex OAuth login
if not settings_obj.plex_machine_identifier:
try:
machine_id = plex_api.plex.machineIdentifier
if machine_id:
settings_obj.plex_machine_identifier = machine_id
settings_updated = True
logger.info(f"Auto-saved Plex machine identifier: {machine_id}")
except Exception as e:
logger.warning(f"Could not get Plex machine identifier: {e}")
if settings_updated:
db_session.commit()
logger.info("Settings auto-populated from environment variables")
else:
# Create Settings row if it doesn't exist and we have a working Plex connection
try:
machine_id = plex_api.plex.machineIdentifier
settings_obj = Settings(
shuffle_frequency='weekly',
plex_url=plex_api.base_url,
plex_token=plex_api.token,
plex_machine_identifier=machine_id
)
db_session.add(settings_obj)
db_session.commit()
logger.info(f"Created Settings from environment variables (machine ID: {machine_id})")
except Exception as e:
logger.warning(f"Could not create Settings from env vars: {e}")
except Exception as e:
logger.warning(f"Plex API not available: {e}")
plex_api = None
scheduler = ScheduleGenerator()
logger.info("Scheduler initialized")
sync_movies()
scheduler.generate_all_schedules(force=True)
def sync_movies():
if not plex_api:
logger.warning("Plex API not available, skipping movie sync")
return
logger.info("Syncing movies from Plex...")
# Get selected libraries from settings
from models import Movie
session = get_session()
settings = session.query(Settings).first()
selected_libraries = None
auto_selected = False
if settings and settings.selected_movie_libraries:
# Parse comma-separated library names
selected_libraries = [lib.strip() for lib in settings.selected_movie_libraries.split(',') if lib.strip()]
logger.info(f"Syncing from selected libraries: {selected_libraries}")
else:
logger.info("No library filter set, syncing from all movie libraries")
auto_selected = True
# Fetch movies with library filter
movie_data = plex_api.fetch_movies(selected_libraries=selected_libraries)
# Auto-save library selection on first sync
if auto_selected and settings:
try:
available_libraries = plex_api.get_movie_libraries()
if available_libraries:
settings.selected_movie_libraries = ','.join(available_libraries)
session.commit()
logger.info(f"Auto-selected all {len(available_libraries)} movie libraries on first sync: {available_libraries}")
except Exception as e:
logger.error(f"Error auto-selecting libraries: {e}")
existing_combinations = {(m.plex_id, m.genre) for m in session.query(Movie).all()}
new_count = 0
update_count = 0
for data in movie_data:
if data['duration'] <= 0:
logger.warning(f"Skipping movie '{data['title']}' with invalid duration: {data['duration']}")
continue
for genre in data['genres']:
if (data['plex_id'], genre) not in existing_combinations:
movie = Movie(
title=data['title'],
genre=genre,
duration=max(data['duration'], 1),
plex_id=data['plex_id'],
year=data['year'],
rating=data['rating'],
content_rating=data.get('content_rating'),
audience_rating=data.get('audience_rating'),
summary=data['summary'],
poster_url=data.get('poster_url'),
art_url=data.get('art_url'),
cast=data.get('cast'),
library_name=data.get('library_name')
)
session.add(movie)
new_count += 1
else:
existing_movie = session.query(Movie).filter_by(plex_id=data['plex_id'], genre=genre).first()
if existing_movie:
changed = False
if existing_movie.poster_url != data.get('poster_url'):
existing_movie.poster_url = data.get('poster_url')
changed = True
if existing_movie.audience_rating != data.get('audience_rating'):
existing_movie.audience_rating = data.get('audience_rating')
changed = True
if existing_movie.content_rating != data.get('content_rating'):
existing_movie.content_rating = data.get('content_rating')
changed = True
if existing_movie.cast != data.get('cast'):
existing_movie.cast = data.get('cast')
changed = True
if existing_movie.art_url != data.get('art_url'):
existing_movie.art_url = data.get('art_url')
changed = True
if existing_movie.library_name != data.get('library_name'):
existing_movie.library_name = data.get('library_name')
changed = True
if changed:
update_count += 1
session.commit()
logger.info(f"Added {new_count} new movie entries to database")
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('guide'))
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
db_session = get_session()
user = db_session.query(User).filter_by(username=username).first()
if user and user.check_password(password):
user.last_login = datetime.utcnow()
db_session.commit()
login_user(user, remember=True)
next_page = request.args.get('next')
if next_page and is_safe_url(next_page):
return redirect(next_page)
return redirect(url_for('guide'))
flash('Invalid username or password', 'error')
return render_template('login.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('guide'))
invite_code = request.args.get('invite', '')
if request.method == 'POST':
username = request.form.get('username')
email = request.form.get('email')
password = request.form.get('password')
confirm_password = request.form.get('confirm_password')
setup_token = request.form.get('setup_token', '')
invite_code = request.form.get('invite_code', '')
if password != confirm_password:
flash('Passwords do not match', 'error')
return render_template('login.html', show_register=True, invite_code=invite_code)
db_session = get_session()
is_first_user = db_session.query(User).count() == 0
invited_by_user_id = None
if is_first_user:
required_token = os.getenv('ADMIN_SETUP_TOKEN')
if not required_token:
flash('Admin setup is not configured. Please contact the administrator.', 'error')
return render_template('login.html', show_register=True)
if setup_token != required_token:
flash('Invalid setup token. The first user registration requires the admin setup token.', 'error')
return render_template('login.html', show_register=True)
else:
if not invite_code:
flash('An invitation code is required to register.', 'error')
return render_template('login.html', show_register=True)
is_valid, result = validate_invite_code(invite_code)
if not is_valid:
flash(result, 'error')
return render_template('login.html', show_register=True, invite_code=invite_code)
invitation = result
invited_by_user_id = invitation.created_by
if db_session.query(User).filter_by(username=username).first():
flash('Username already exists', 'error')
return render_template('login.html', show_register=True, invite_code=invite_code)
if email and db_session.query(User).filter_by(email=email).first():
flash('Email already registered', 'error')
return render_template('login.html', show_register=True, invite_code=invite_code)
user = User(
username=username,
email=email,
is_admin=is_first_user,
invited_by=invited_by_user_id
)
user.set_password(password)
db_session.add(user)
db_session.commit()
if invite_code and not is_first_user:
mark_invite_used(invite_code, user.id)
login_user(user, remember=True)
flash('Account created successfully!', 'success')
return redirect(url_for('guide'))
db_session = get_session()
is_first_user = db_session.query(User).count() == 0
return render_template('login.html', show_register=True, is_first_user=is_first_user, invite_code=invite_code)
@app.route('/auth/plex')
def plex_auth():
db_session = get_session()
is_first_user = db_session.query(User).count() == 0
if is_first_user:
required_token = os.getenv('ADMIN_SETUP_TOKEN')
if not required_token:
flash('Admin setup is not configured. Please register a local account first.', 'error')
return redirect(url_for('login'))
flash('The first admin account must be created using local registration with the setup token.', 'info')
return redirect(url_for('register'))
plex_oauth = PlexOAuth()
redirect_uri = url_for('plex_callback', _external=True)
auth_data = plex_oauth.get_auth_url(redirect_uri)
if not auth_data:
flash('Failed to connect to Plex', 'error')
return redirect(url_for('login'))
session['plex_pin_id'] = auth_data['pin_id']
return jsonify({
'success': True,
'auth_url': auth_data['auth_url'],
'pin_id': auth_data['pin_id']
})
@app.route('/auth/plex/check/<pin_id>')
@csrf.exempt
def check_plex_pin(pin_id):
plex_oauth = PlexOAuth()
auth_token = plex_oauth.check_pin(pin_id)
if not auth_token:
return jsonify({'success': False, 'status': 'pending'})
user_info = plex_oauth.get_user_info(auth_token)
if not user_info:
return jsonify({'success': False, 'status': 'error', 'message': 'Failed to get user information'})
db_session = get_session()
# Get configured Plex server machine identifier from settings
settings = db_session.query(Settings).first()
if not settings or not settings.plex_machine_identifier:
return jsonify({
'success': False,
'status': 'error',
'message': 'Plex server not configured. Contact administrator.'
})
# Verify user has access using machine identifier matching
# This works for both internal and external users
user_servers = plex_oauth.get_user_servers(auth_token)
admin_machine_id = settings.plex_machine_identifier
user_server_ids = [server['machineIdentifier'] for server in user_servers]
has_access = admin_machine_id in user_server_ids
if not has_access:
logger.warning(f"User {user_info['username']} does not have access to server {admin_machine_id}")
logger.info(f"User has access to servers: {user_server_ids}")
return jsonify({
'success': False,
'status': 'no_library_access',
'message': 'You do not have access to this Plex server. Please ask the administrator to share the server with your Plex account.'
})
logger.info(f"User {user_info['username']} verified with access to server {admin_machine_id}")
# Smart merge logic: plex_id → email → create new
user = None
# 1. Check if plex_id already exists (existing Plex user)
user = db_session.query(User).filter_by(plex_id=user_info['plex_id']).first()
if user:
# Update existing Plex-linked account
user.plex_token = auth_token
user.plex_username = user_info.get('username')
user.display_name = user_info.get('display_name')
user.avatar_url = user_info.get('avatar_url')
if user_info.get('email'):
user.email = user_info['email']
user.updated_at = datetime.utcnow()
user.last_login = datetime.utcnow()
db_session.commit()
logger.info(f"Updated existing Plex user: {user.username}")
# 2. Check if email matches existing local account (merge scenario)
elif user_info.get('email'):
user = db_session.query(User).filter_by(email=user_info['email']).first()
if user:
# Link Plex to existing local account
user.plex_id = user_info['plex_id']
user.plex_token = auth_token
user.plex_username = user_info.get('username')
user.display_name = user_info.get('display_name')
user.avatar_url = user_info.get('avatar_url')
user.updated_at = datetime.utcnow()
user.last_login = datetime.utcnow()
db_session.commit()
logger.info(f"Linked Plex account to existing user by email: {user.username}")
# 3. Create new account (new Plex user with library access)
if not user:
username = user_info.get('username') or user_info.get('email', '').split('@')[0] or f"plex_user_{user_info['plex_id']}"
# Ensure unique username
base_username = username
counter = 1
while db_session.query(User).filter_by(username=username).first():
username = f"{base_username}_{counter}"
counter += 1
user = User(
username=username,
email=user_info.get('email'),
plex_id=user_info['plex_id'],
plex_token=auth_token,
plex_username=user_info.get('username'),
display_name=user_info.get('display_name') or username,
avatar_url=user_info.get('avatar_url'),
is_admin=False,
is_active=True,
last_login=datetime.utcnow()
)
db_session.add(user)
db_session.commit()
logger.info(f"Created new Plex user with library access: {user.username}")
login_user(user, remember=True)
session.pop('plex_pin_id', None)
return jsonify({'success': True, 'status': 'authorized', 'user': user.display_name})
@app.route('/auth/plex/callback')
@csrf.exempt
def plex_callback():
return render_template('plex_callback.html')
@app.route('/logout', methods=['POST'])
@login_required
def logout():
logout_user()
session.pop('_flashes', None)
flash('You have been logged out', 'info')
return redirect(url_for('login'))
@app.route('/discover.json')
def hdhr_discover():
"""HDHomeRun device discovery endpoint for Plex auto-detection"""
if not livetv.is_live_tv_enabled():
return jsonify({"error": "Live TV is not enabled"}), 404
return jsonify(livetv.get_discover_data())
@app.route('/lineup_status.json')
def hdhr_lineup_status():
"""HDHomeRun lineup status endpoint"""
if not livetv.is_live_tv_enabled():
return jsonify({"error": "Live TV is not enabled"}), 404
return jsonify(livetv.get_lineup_status())
@app.route('/lineup.json')
def hdhr_lineup():
"""HDHomeRun channel lineup endpoint"""
if not livetv.is_live_tv_enabled():
return jsonify({"error": "Live TV is not enabled"}), 404
return jsonify(livetv.get_lineup(scheduler))
@app.route('/iptv/playlist.m3u')
def iptv_playlist():
"""M3U playlist endpoint for IPTV clients"""
if not livetv.is_live_tv_enabled():
return "Live TV is not enabled", 404
m3u_content = livetv.generate_m3u_playlist(scheduler)
response = make_response(m3u_content)
response.headers['Content-Type'] = 'audio/x-mpegurl'
response.headers['Content-Disposition'] = 'inline; filename=popcorn.m3u'
return response
@app.route('/iptv/xmltv.xml')
def iptv_xmltv():
"""XMLTV EPG (Electronic Program Guide) endpoint"""
if not livetv.is_live_tv_enabled():
return "Live TV is not enabled", 404
xmltv_content = livetv.generate_xmltv_epg(scheduler)
response = make_response(xmltv_content)
response.headers['Content-Type'] = 'text/xml; charset=utf-8'
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
return response
@app.route('/livetv/stream/<int:channel_num>')
def livetv_stream(channel_num):
"""
Stream a live TV channel in MPEG-TS format.
This endpoint is called by Plex and other IPTV clients.
"""
if not livetv.is_live_tv_enabled():
return "Live TV is not enabled", 404
if not plex_api:
return "Plex is not configured", 500
try:
# Stream the channel using FFmpeg
return app.response_class(
livetv.stream_channel(channel_num, plex_api),
mimetype='video/mp2t',
headers={
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
}
)
except ValueError as e:
logger.error(f"Channel streaming error: {e}")
return str(e), 404
except RuntimeError as e:
logger.error(f"FFmpeg error: {e}")
return str(e), 500
except Exception as e:
logger.error(f"Unexpected streaming error: {e}")
return "Internal server error", 500
@app.route('/livetv/help')
def livetv_help():
"""Help page for Live TV setup and configuration"""
base_url = request.url_root
# Get device ID from discover data
discover_data = livetv.get_discover_data()
device_id = discover_data['DeviceID']
# Read and render the help page template
with open('pages/livetv_help.html', 'r') as f:
template = f.read()
# Simple template rendering (replace variables)
template = template.replace('{{ device_id }}', device_id)
template = template.replace('{{ base_url }}', base_url)
template = template.replace('{{ xmltv_url }}', f"{base_url}iptv/xmltv.xml")
template = template.replace('{{ lineup_url }}', f"{base_url}lineup.json")
template = template.replace('{{ url_for(\'settings\') }}', '/settings')
template = template.replace('{{ url_for(\'index\') }}', '/')
response = make_response(template)
response.headers['Content-Type'] = 'text/html'
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
return response
@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
from theme_service import ThemeService
from watch_history_service import WatchHistoryService
import json
themes = ThemeService.get_all_themes_for_user(current_user.id)
if request.method == 'POST':
theme = request.form.get('theme')
if theme and theme in themes:
db_session = get_session()
user = db_session.query(User).get(current_user.id)
user.theme = theme
db_session.commit()
flash(f'Theme changed to {themes[theme]["name"]}!', 'success')
return redirect(url_for('profile'))
user_theme = current_user.theme if current_user.theme else 'plex'
theme_colors = themes.get(user_theme, themes.get('plex', {})).get('colors', {})
watch_stats = WatchHistoryService.get_user_stats(current_user.id)
# Get all available channels dynamically from actual channels in the database
# This includes genre channels from all movies (including French/non-English tags)
# and holiday channels that are currently active
all_channels = []
if scheduler:
all_channels = sorted(scheduler.get_all_channels())
# Get user's visible channels (default to all if not set)
visible_channels = []
if current_user.visible_channels:
try:
visible_channels = json.loads(current_user.visible_channels)
except:
visible_channels = all_channels
else:
visible_channels = all_channels
# Get admin max brightness setting
db_session_local = get_session()
settings_obj = db_session_local.query(Settings).first()
admin_max_brightness = settings_obj.current_glow_brightness if settings_obj and settings_obj.current_glow_brightness else 100
return render_template('profile.html',
themes=themes,
theme_colors=theme_colors,
watch_stats=watch_stats,
all_channels=all_channels,
visible_channels=visible_channels,
admin_max_brightness=admin_max_brightness)
@app.route('/profile/preferences', methods=['POST'])
@login_required
def update_preferences():
db_session = get_session()
user = db_session.query(User).get(current_user.id)
settings_obj = db_session.query(Settings).first()
user.enable_crt_mode = 'enable_crt_mode' in request.form
user.enable_film_grain = 'enable_film_grain' in request.form
user.enable_time_offset = 'enable_time_offset' in request.form
user.playback_mode = request.form.get('playback_mode', 'web_player')
user.plex_client = request.form.get('plex_client', '').strip() or None
# Handle user brightness with validation against admin max
brightness = request.form.get('current_glow_brightness')
if brightness is not None:
try:
brightness_val = int(brightness)
# Get admin max brightness
admin_max = settings_obj.current_glow_brightness if settings_obj and settings_obj.current_glow_brightness else 100
# Constrain user brightness to admin max
if 0 <= brightness_val <= admin_max:
user.current_glow_brightness = brightness_val
else:
user.current_glow_brightness = min(brightness_val, admin_max)
except ValueError:
pass
db_session.commit()
flash('Viewing preferences saved successfully!', 'success')
return redirect(url_for('profile'))
@app.route('/profile/channels', methods=['POST'])
@login_required
def update_channel_visibility():
import json
from channel_numbers import CHANNEL_NUMBERS
db_session = get_session()
user = db_session.query(User).get(current_user.id)
# Get all channels that were checked
visible_channels = request.form.getlist('visible_channels')
# If no channels selected, show all channels (default)
if not visible_channels:
visible_channels = list(CHANNEL_NUMBERS.keys())
# Save as JSON
user.visible_channels = json.dumps(visible_channels)
db_session.commit()
flash(f'Channel preferences saved! {len(visible_channels)} channels visible.', 'success')
return redirect(url_for('profile'))
@app.route('/profile/password', methods=['POST'])
@login_required
def change_password():
current_password = request.form.get('current_password')
new_password = request.form.get('new_password')
confirm_password = request.form.get('confirm_password')
if not all([current_password, new_password, confirm_password]):
flash('All password fields are required.', 'error')
return redirect(url_for('profile'))
db_session = get_session()
user = db_session.query(User).get(current_user.id)
if not user.check_password(current_password):
flash('Current password is incorrect.', 'error')
return redirect(url_for('profile'))
if new_password != confirm_password:
flash('New passwords do not match.', 'error')
return redirect(url_for('profile'))
if len(new_password) < 4:
flash('New password must be at least 4 characters long.', 'error')
return redirect(url_for('profile'))
user.set_password(new_password)
user.using_default_password = False
db_session.commit()
flash('Password changed successfully! Security warning removed.', 'success')