-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1791 lines (1497 loc) · 65.5 KB
/
app.py
File metadata and controls
1791 lines (1497 loc) · 65.5 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 random
import re
import requests
import urllib.parse
import jwt
import datetime
import secrets
import hashlib
from functools import wraps
from flask import Flask, render_template, request, send_file, jsonify, send_from_directory
from plexapi.server import PlexServer
import wikipediaapi
from io import BytesIO
app = Flask(__name__)
# JWT Secret Key - MUST be set via environment variable in production
# Generate a secure random key if not provided (will change on restart - not ideal for production)
_default_secret = os.getenv("JWT_SECRET_KEY")
if not _default_secret or _default_secret == "your-secret-key-change-in-production":
_default_secret = secrets.token_hex(32) # 256-bit random key
print("⚠️ WARNING: Using auto-generated JWT_SECRET_KEY. Set JWT_SECRET_KEY env var for production!")
JWT_SECRET_KEY = _default_secret
# Enable sessions for caching
app.secret_key = os.getenv("FLASK_SECRET_KEY", secrets.token_hex(32))
# Backend API configuration
BACKEND_API_URL = os.getenv("BACKEND_API_URL", "https://plex-like.satrawi.com")
# Plex config from environment
PLEX_URL = os.getenv("PLEX_URL")
PLEX_TOKEN = os.getenv("PLEX_TOKEN")
LIBRARY_NAME = os.getenv("PLEX_LIBRARY", "Movies")
wiki_wiki = wikipediaapi.Wikipedia(
user_agent='PlexMovieSuggester/1.0 (example@mail.com)', # Replace with your contact info
language='en'
)
def verify_plex_token(plex_token, plex_url=None):
"""Verify if the provided Plex token is valid"""
try:
url = plex_url or PLEX_URL
if not url:
return False
plex = PlexServer(url, plex_token)
# Try to access server info to verify token
plex.machineIdentifier
return True
except Exception:
return False
def generate_jwt_token(plex_token):
"""Generate JWT token for authenticated user"""
# Hash the plex_token instead of storing it directly (more secure)
plex_token_hash = hashlib.sha256(plex_token.encode()).hexdigest()[:16]
payload = {
'plex_token': plex_token, # Still needed for API calls
'plex_hash': plex_token_hash, # For verification without exposing full token
'iss': 'plex-suggester', # Issuer claim
'aud': 'plex-suggester-api', # Audience claim
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30),
'iat': datetime.datetime.utcnow(),
'nbf': datetime.datetime.utcnow(), # Not valid before
}
return jwt.encode(payload, JWT_SECRET_KEY, algorithm='HS256')
def get_backend_jwt_token(plex_token):
"""Get JWT token from backend service using Plex token"""
try:
response = requests.post(
f"{BACKEND_API_URL}/auth/plex",
json={"plex_token": plex_token},
timeout=10
)
if response.status_code == 200:
data = response.json()
return data.get('token')
return None
except Exception as e:
print(f"Failed to get backend JWT token: {e}")
return None
def require_jwt_auth(f):
"""Decorator to require JWT authentication for API endpoints"""
@wraps(f)
def decorated_function(*args, **kwargs):
# Get Authorization header
auth_header = request.headers.get('Authorization', '')
if not auth_header.startswith('Bearer '):
return jsonify({'error': 'Authorization header with Bearer token required'}), 401
try:
# Extract token
token = auth_header.split(' ')[1]
# PROPERLY verify JWT signature and expiration
payload = verify_jwt_token(token)
if payload is None:
return jsonify({'error': 'Invalid or expired token'}), 401
# Add plex_token to request context for use in the endpoint
request.plex_token = payload.get('plex_token')
# Pass through to the actual function
return f(*args, **kwargs)
except jwt.ExpiredSignatureError:
return jsonify({'error': 'Token has expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'error': 'Invalid token'}), 401
except Exception as e:
return jsonify({'error': 'Authentication failed'}), 401
return decorated_function
def make_backend_request(method, endpoint, headers=None, json_data=None, params=None):
"""Make authenticated request to backend API"""
url = f"{BACKEND_API_URL}{endpoint}"
try:
response = requests.request(
method=method,
url=url,
headers=headers or {},
json=json_data,
params=params,
timeout=10
)
return response
except Exception as e:
print(f"Backend request failed: {e}")
return None
def verify_jwt_token(token):
"""Verify and decode JWT token with full validation"""
try:
payload = jwt.decode(
token,
JWT_SECRET_KEY,
algorithms=['HS256'],
options={
'require': ['exp', 'iat', 'iss', 'aud'], # Require these claims
'verify_exp': True,
'verify_iat': True,
'verify_nbf': True,
},
issuer='plex-suggester',
audience='plex-suggester-api'
)
return payload
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None
except Exception:
return None
def token_required(f):
"""Decorator to require JWT authentication"""
@wraps(f)
def decorated(*args, **kwargs):
token = None
auth_header = request.headers.get('Authorization')
if auth_header:
try:
token = auth_header.split(" ")[1] # Bearer <token>
except IndexError:
return jsonify({'message': 'Token format is invalid'}), 401
if not token:
return jsonify({'message': 'Token is missing'}), 401
payload = verify_jwt_token(token)
if payload is None:
return jsonify({'message': 'Token is invalid or expired'}), 401
# Add plex_token to request context
request.plex_token = payload['plex_token']
return f(*args, **kwargs)
return decorated
def get_wikipedia_actor_image(actor_name):
"""Fetch actor image from Wikipedia API"""
try:
# Properly encode the actor name for URL
encoded_name = urllib.parse.quote(actor_name.replace(' ', '_'))
url = f"https://en.wikipedia.org/w/api.php?action=query&titles={encoded_name}&prop=pageimages&format=json&pithumbsize=200"
headers = {
"User-Agent": "PlexSuggester/1.0 (https://github.com/plex-suggester; contact@example.com)"
}
resp = requests.get(url, headers=headers, timeout=5)
if resp.status_code != 200:
return None
data = resp.json()
pages = data.get("query", {}).get("pages", {})
for pageid, pagedata in pages.items():
thumbnail = pagedata.get("thumbnail", {})
if thumbnail:
return thumbnail.get("source")
except Exception:
pass
return None
def get_tmdb_actor_image(actor_name):
"""Fetch actor image from TMDB API (free, no key needed for search)"""
try:
# Use TMDB search which works without API key for basic info
search_url = f"https://api.themoviedb.org/3/search/person?query={urllib.parse.quote(actor_name)}"
# Try without API key first - may work for cached/public results
headers = {"User-Agent": "Mozilla/5.0"}
# Alternative: Use a free image search
# Search Wikipedia with the actor name + "actor" for better results
wiki_search_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(actor_name + ' actor')}&format=json"
resp = requests.get(wiki_search_url, headers={"User-Agent": "PlexSuggester/1.0"}, timeout=5)
if resp.status_code == 200:
data = resp.json()
search_results = data.get("query", {}).get("search", [])
if search_results:
# Get the first result's title and fetch its image
title = search_results[0].get("title", "")
if title:
return get_wikipedia_actor_image(title)
except Exception:
pass
return None
def get_imdb_actor_image(actor_name):
"""
Try to fetch actor image from IMDB via DuckDuckGo image search as a workaround.
Returns image URL or None.
"""
try:
# Use DuckDuckGo image search as a simple, free workaround (not official IMDB API)
search_url = f"https://duckduckgo.com/?q={actor_name}+imdb&iax=images&ia=images"
headers = {"User-Agent": "Mozilla/5.0"}
html = requests.get(search_url, headers=headers, timeout=3).text
# Find first image URL in the HTML (very basic, not robust)
match = re.search(r'"image":"(https://[^"]+?)"', html)
if match:
return match.group(1).replace("\\/", "/")
except Exception:
pass
return None
def get_anilist_actor_image(actor_name):
"""
Try to fetch anime voice actor image from AniList GraphQL API.
Returns image URL or None.
"""
try:
query = '''
query ($search: String) {
Staff(search: $search) {
image {
large
medium
}
}
}
'''
variables = {"search": actor_name}
url = "https://graphql.anilist.co"
response = requests.post(url, json={"query": query, "variables": variables}, timeout=3)
data = response.json()
image = (
data.get("data", {})
.get("Staff", {})
.get("image", {})
.get("large")
)
return image
except Exception:
return None
def get_plex_libraries(plex_token=None):
# Use provided token or fallback to environment variable
token = plex_token or PLEX_TOKEN
if not PLEX_URL or not token:
return []
try:
plex = PlexServer(PLEX_URL, token)
# Include all video types (movie, show, etc.)
return [
{"title": section.title, "type": section.type}
for section in plex.library.sections()
if section.type in ("movie", "show", "anime", "other", "artist")
]
except Exception:
return []
def get_random_movie_lightweight(library_name=None, plex_token=None):
"""Optimized version for match rooms - only gets essential data"""
# Use provided token or fallback to environment variable
token = plex_token or PLEX_TOKEN
if not PLEX_URL or not token:
return "⚠️ Please set PLEX_URL and PLEX_TOKEN environment variables.", None
try:
plex = PlexServer(PLEX_URL, token)
lib_name = library_name or LIBRARY_NAME
section = plex.library.section(lib_name)
# Suggest a random unwatched movie or show
if section.type == "movie":
items = section.search(unwatched=True)
elif section.type in ("show", "anime"):
# FAST: Use Plex's unwatched filter - returns shows with unwatched episodes
items = section.search(unwatched=True)
if not items:
items = section.search() # Fallback to all shows
else:
items = section.search(unwatched=True)
if not items:
return "✅ No unwatched items found!", None
item = random.choice(items)
# Only get essential data - no expensive operations
# Poster URL with token or fallback
if getattr(item, "thumb", None):
# Use proxy route instead of direct Plex URL
item.poster_url = f"/poster{item.thumb}"
else:
item.poster_url = "https://avatars.githubusercontent.com/u/72304665?v=4"
# Watch on Plex URL
try:
item.watch_url = f"{PLEX_URL}/web/index.html#!/server/{plex.machineIdentifier}/details?key=/library/metadata/{item.ratingKey}"
except Exception:
item.watch_url = None
return None, item
except Exception as e:
return f"❌ Error getting random movie: {str(e)}", None
def get_random_movie_fast(library_name=None, plex_token=None):
"""Fast version - only Plex data, no external API calls"""
token = plex_token or PLEX_TOKEN
if not PLEX_URL or not token:
return "⚠️ Please set PLEX_URL and PLEX_TOKEN environment variables.", None
try:
plex = PlexServer(PLEX_URL, token)
server_id = plex.machineIdentifier
lib_name = library_name or LIBRARY_NAME
section = plex.library.section(lib_name)
if section.type == "movie":
items = section.search(unwatched=True)
elif section.type in ("show", "anime"):
# FAST: Use Plex's unwatched filter - returns shows with unwatched episodes
items = section.search(unwatched=True)
if not items:
items = section.search() # Fallback to all shows
else:
items = section.search(unwatched=True)
if not items:
return "✅ No unwatched items found!", None
item = random.choice(items)
# Poster URL - use proxy route
if getattr(item, "thumb", None):
item.poster_url = f"/poster{item.thumb}"
else:
item.poster_url = "https://via.placeholder.com/250x375/333/e5a00d?text=No+Poster"
# Fast cast - store names, images will be lazy-loaded via AJAX
cast = []
for actor in getattr(item, "roles", [])[:5]:
if getattr(actor, "thumb", None):
# Use Plex thumb if available
actor_thumb = f"/poster{actor.thumb}"
else:
# Placeholder - will be replaced by lazy-loaded image
actor_thumb = None
cast.append({
"name": actor.tag,
"thumb": actor_thumb
})
item.cast = cast
# Skip external trailer lookup - will be loaded via AJAX
item.external_trailer_url = None
item.trailer_url = None
# Watch on Plex URL
item.watch_url = f"{PLEX_URL}/web/index.html#!/server/{server_id}/details?key={item.key}"
# Fallbacks
if not getattr(item, "summary", None):
item.summary = "No summary available."
if not getattr(item, "year", None):
item.year = ""
if not getattr(item, "title", None):
item.title = "Untitled"
# Get genres directly from Plex
item.genres = [g.tag for g in getattr(item, 'genres', [])][:4] if hasattr(item, 'genres') else []
# Get duration
duration = getattr(item, 'duration', None)
if duration:
minutes = duration // 60000
item.duration_formatted = f"{minutes // 60}h {minutes % 60}m" if minutes >= 60 else f"{minutes}m"
else:
item.duration_formatted = None
return None, item
except Exception as e:
return f"❌ Error: {e}", None
def get_random_movie(library_name=None, plex_token=None):
# Use provided token or fallback to environment variable
token = plex_token or PLEX_TOKEN
if not PLEX_URL or not token:
return "⚠️ Please set PLEX_URL and PLEX_TOKEN environment variables.", None
try:
plex = PlexServer(PLEX_URL, token)
server_id = plex.machineIdentifier
lib_name = library_name or LIBRARY_NAME
section = plex.library.section(lib_name)
# Suggest a random unwatched movie or show
if section.type == "movie":
items = section.search(unwatched=True)
elif section.type in ("show", "anime"):
# FAST: Use Plex's unwatched filter - returns shows with unwatched episodes
items = section.search(unwatched=True)
if not items:
items = section.search() # Fallback to all shows
else:
items = section.search(unwatched=True)
if not items:
return "✅ No unwatched items found!", None
item = random.choice(items)
# Poster URL with token or fallback
if getattr(item, "thumb", None):
# Use proxy route instead of direct Plex URL
item.poster_url = f"/poster{item.thumb}"
else:
item.poster_url = "https://avatars.githubusercontent.com/u/72304665?v=4"
# Top 5 cast with images (Plex thumb, then IMDB, then Wikipedia, else always placeholder)
cast = []
for actor in getattr(item, "roles", [])[:5]:
# 1. Try Plex thumb
if getattr(actor, "thumb", None):
actor_thumb = f"{PLEX_URL}{actor.thumb}?X-Plex-Token={token}"
else:
# 2. Try IMDB (via DuckDuckGo image search)
actor_thumb = get_imdb_actor_image(actor.tag)
# 3. Try AniList (for anime/voice actors)
if not actor_thumb:
actor_thumb = get_anilist_actor_image(actor.tag)
# 4. Try Wikipedia
if not actor_thumb:
actor_thumb = get_wikipedia_actor_image(actor.tag)
# 5. Fallback to placeholder if all else fails
if not actor_thumb:
actor_thumb = "https://avatars.githubusercontent.com/u/72304665?v=4"
cast.append({
"name": actor.tag,
"thumb": actor_thumb
})
item.cast = cast
# External Trailer URL (YouTube/TMDB)
try:
item.external_trailer_url = get_external_trailer_url(item.title, getattr(item, 'year', None))
except Exception:
item.external_trailer_url = None
# Plex Trailer URL (if available) - keeping for compatibility
try:
trailer = next((e for e in getattr(item, "extras", lambda: [])() if 'trailer' in e.type.lower()), None)
item.trailer_url = trailer.url if trailer else None
except Exception:
item.trailer_url = None
# Watch on Plex URL
item.watch_url = f"{PLEX_URL}/web/index.html#!/server/{server_id}/details?key={item.key}"
# Add summary fallback
if not getattr(item, "summary", None):
item.summary = "No summary available."
# Add year fallback
if not getattr(item, "year", None):
item.year = ""
# Add title fallback
if not getattr(item, "title", None):
item.title = "Untitled"
# Add genres (first 4)
item.genres = [g.tag for g in getattr(item, 'genres', [])][:4]
# Add duration formatted
duration_ms = getattr(item, 'duration', None)
if duration_ms:
total_minutes = duration_ms // 60000
hours = total_minutes // 60
minutes = total_minutes % 60
if hours > 0:
item.duration_formatted = f"{hours}h {minutes}m"
else:
item.duration_formatted = f"{minutes}m"
else:
item.duration_formatted = None
return None, item
except Exception as e:
return f"❌ Error: {e}", None
def get_external_trailer_url(title, year=None):
"""
Try to fetch external trailer URL from YouTube or TMDB.
Returns trailer URL or None.
"""
try:
# Clean title for search
search_title = title.replace(":", "").replace("-", " ")
if year:
search_query = f"{search_title} {year} trailer"
else:
search_query = f"{search_title} trailer"
# Try YouTube search via DuckDuckGo (simple approach)
query = urllib.parse.quote_plus(search_query + " site:youtube.com")
search_url = f"https://duckduckgo.com/html/?q={query}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(search_url, headers=headers, timeout=5)
html = response.text
# Look for YouTube URLs in the response
youtube_pattern = r'https://www\.youtube\.com/watch\?v=([a-zA-Z0-9_-]+)'
matches = re.findall(youtube_pattern, html)
if matches:
# Return the first YouTube URL found
return f"https://www.youtube.com/watch?v={matches[0]}"
except Exception:
pass
# Fallback: try a simple YouTube search URL
try:
if year:
search_term = f"{title} {year} official trailer"
else:
search_term = f"{title} official trailer"
search_term = urllib.parse.quote_plus(search_term)
return f"https://www.youtube.com/results?search_query={search_term}"
except Exception:
pass
return None
@app.route("/auth/plex", methods=["POST"])
def plex_auth():
"""Authenticate with Plex token and return JWT"""
try:
data = request.get_json()
if not data or 'plex_token' not in data:
return jsonify({'error': 'Plex token is required'}), 400
plex_token = data['plex_token']
# Verify the Plex token
if not verify_plex_token(plex_token):
return jsonify({'error': 'Invalid Plex token'}), 401
# Generate JWT token
jwt_token = generate_jwt_token(plex_token)
return jsonify({
'token': jwt_token,
'message': 'Authentication successful'
})
except Exception as e:
return jsonify({'error': f'Authentication failed: {str(e)}'}), 500
@app.route("/api/libraries", methods=["GET"])
@token_required
def api_libraries():
"""Get Plex libraries for authenticated user"""
try:
libraries = get_plex_libraries(request.plex_token)
return jsonify({'libraries': libraries})
except Exception as e:
return jsonify({'error': f'Failed to fetch libraries: {str(e)}'}), 500
@app.route("/api/suggest", methods=["GET"])
@token_required
def api_suggest():
"""Get random movie suggestion for authenticated user"""
try:
library_name = request.args.get("library")
error, movie = get_random_movie(library_name, request.plex_token)
if error:
return jsonify({'error': error}), 400
# Convert movie object to dictionary for JSON response
movie_data = {
'title': getattr(movie, 'title', ''),
'year': getattr(movie, 'year', ''),
'summary': getattr(movie, 'summary', ''),
'poster_url': getattr(movie, 'poster_url', ''),
'watch_url': getattr(movie, 'watch_url', ''),
'trailer_url': getattr(movie, 'trailer_url', ''),
'external_trailer_url': getattr(movie, 'external_trailer_url', ''),
'cast': getattr(movie, 'cast', []),
'genres': getattr(movie, 'genres', []),
'duration_formatted': getattr(movie, 'duration_formatted', None)
}
return jsonify({'movie': movie_data})
except Exception as e:
return jsonify({'error': f'Failed to get suggestion: {str(e)}'}), 500
# ==================== MOVIE MATCH API ENDPOINTS (LOCAL) ====================
# Local implementation without external backend dependency
import string
from database import get_db_connection, init_db
# Initialize database on startup
try:
init_db()
except Exception as e:
print(f"Warning: Could not initialize database: {e}")
def generate_room_code():
"""Generate a 6-character room code"""
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
def generate_room_id():
"""Generate a unique room ID"""
return secrets.token_hex(8)
@app.route("/api/match/create", methods=["POST"])
def create_match_room_local():
"""Create a new movie matching room (uses backend API for global rooms)"""
try:
data = request.get_json()
room_name = data.get('room_name', 'Movie Night')
username = data.get('username', 'Anonymous')
library_filter = data.get('library', 'Movies')
min_participants = data.get('min_participants', 2)
# Create room via backend API
response = requests.post(
f"{BACKEND_API_URL}/api/match/rooms",
json={
'name': room_name,
'username': username,
'library': library_filter,
'min_participants': min_participants
},
timeout=10
)
if response.status_code != 200:
error_msg = response.json().get('error', 'Failed to create room')
return jsonify({'error': error_msg}), response.status_code
result = response.json()
room_id = result.get('room_id')
room_code = result.get('room_code')
# Get movies for the room using environment PLEX_TOKEN
plex_token = os.environ.get('PLEX_TOKEN')
movies = get_movies_for_match_room(library_filter, plex_token) if plex_token else []
return jsonify({
'room_id': room_id,
'room_code': room_code,
'room_name': room_name,
'user_id': result.get('user_id'),
'movies': movies
})
except requests.exceptions.RequestException as e:
return jsonify({'error': f'Backend unavailable: {str(e)}'}), 503
except Exception as e:
return jsonify({'error': f'Failed to create room: {str(e)}'}), 500
@app.route("/api/match/join", methods=["POST"])
def join_match_room_local():
"""Join a movie matching room by code (uses backend API for global rooms)"""
try:
data = request.get_json()
room_code = data.get('room_code', '').upper()
username = data.get('username', 'Anonymous')
if not room_code:
return jsonify({'error': 'Room code required'}), 400
# Join room via backend API
response = requests.post(
f"{BACKEND_API_URL}/api/match/join",
json={
'room_code': room_code,
'username': username
},
timeout=10
)
if response.status_code != 200:
error_msg = response.json().get('error', 'Failed to join room')
return jsonify({'error': error_msg}), response.status_code
result = response.json()
library_filter = result.get('library_filter', 'Movies')
# Get movies for the room using environment PLEX_TOKEN
plex_token = os.environ.get('PLEX_TOKEN')
movies = get_movies_for_match_room(library_filter, plex_token) if plex_token else []
return jsonify({
'room_id': result.get('room_id'),
'room_code': room_code,
'room_name': result.get('room_name'),
'user_id': result.get('user_id'),
'movies': movies
})
except requests.exceptions.RequestException as e:
return jsonify({'error': f'Backend unavailable: {str(e)}'}), 503
except Exception as e:
return jsonify({'error': f'Failed to join room: {str(e)}'}), 500
@app.route("/api/match/join-by-id", methods=["POST"])
def join_match_room_by_id():
"""Join a movie matching room by ID (uses backend API for global rooms)"""
try:
data = request.get_json()
room_id = data.get('room_id', '')
username = data.get('username', 'Anonymous')
if not room_id:
return jsonify({'error': 'Room ID required'}), 400
# Join room via backend API
response = requests.post(
f"{BACKEND_API_URL}/api/match/join-by-id",
json={
'room_id': room_id,
'username': username
},
timeout=10
)
if response.status_code != 200:
error_msg = response.json().get('error', 'Failed to join room')
return jsonify({'error': error_msg}), response.status_code
result = response.json()
library_filter = result.get('library_filter', 'Movies')
# Get movies for the room using environment PLEX_TOKEN
plex_token = os.environ.get('PLEX_TOKEN')
movies = get_movies_for_match_room(library_filter, plex_token) if plex_token else []
return jsonify({
'room_id': room_id,
'room_code': result.get('room_code'),
'room_name': result.get('room_name'),
'user_id': result.get('user_id'),
'movies': movies
})
except requests.exceptions.RequestException as e:
return jsonify({'error': f'Backend unavailable: {str(e)}'}), 503
except Exception as e:
return jsonify({'error': f'Failed to join room: {str(e)}'}), 500
@app.route("/api/match/rejoin", methods=["POST"])
def rejoin_match_room():
"""Rejoin a room from saved session (uses backend API for global rooms)"""
try:
data = request.get_json()
room_id = data.get('room_id', '')
username = data.get('username', 'Anonymous')
if not room_id:
return jsonify({'error': 'Room ID required'}), 400
# Rejoin via backend API
response = requests.post(
f"{BACKEND_API_URL}/api/match/rejoin",
json={
'room_id': room_id,
'username': username
},
timeout=10
)
if response.status_code != 200:
error_msg = response.json().get('error', response.json().get('detail', 'Room not found or expired'))
return jsonify({'error': error_msg}), response.status_code
result = response.json()
library_filter = result.get('library_filter', 'Movies')
# Get movies for the room using environment PLEX_TOKEN
plex_token = os.environ.get('PLEX_TOKEN')
movies = get_movies_for_match_room(library_filter, plex_token) if plex_token else []
return jsonify({
'room_id': room_id,
'room_code': result.get('room_code'),
'room_name': result.get('room_name'),
'movies': movies,
'seen_movies': result.get('seen_movies', []),
'current_index': result.get('current_index', 0)
})
except requests.exceptions.RequestException as e:
return jsonify({'error': f'Backend unavailable: {str(e)}'}), 503
except Exception as e:
return jsonify({'error': f'Failed to rejoin room: {str(e)}'}), 500
@app.route("/api/match/rooms", methods=["GET"])
def list_match_rooms_local():
"""List all active movie matching rooms (uses backend API for global rooms)"""
try:
# Get rooms from backend API
response = requests.get(
f"{BACKEND_API_URL}/api/match/rooms",
timeout=10
)
if response.status_code != 200:
return jsonify({'rooms': []}), 200
return jsonify(response.json())
except requests.exceptions.RequestException as e:
return jsonify({'rooms': [], 'error': f'Backend unavailable: {str(e)}'}), 200
except Exception as e:
return jsonify({'error': f'Failed to list rooms: {str(e)}'}), 500
@app.route("/api/match/state/<room_id>", methods=["GET"])
def get_match_room_state(room_id):
"""Get current state of a match room (uses backend API for global rooms)"""
try:
user = request.args.get('user', '')
# Get room state from backend API
response = requests.get(
f"{BACKEND_API_URL}/api/match/state/{room_id}",
params={'user': user},
timeout=10
)
if response.status_code != 200:
error_msg = response.json().get('detail', 'Room not found or expired')
return jsonify({'error': error_msg}), response.status_code
return jsonify(response.json())
except requests.exceptions.RequestException as e:
return jsonify({'error': f'Backend unavailable: {str(e)}'}), 503
except Exception as e:
return jsonify({'error': f'Failed to get room state: {str(e)}'}), 500
@app.route("/api/match/swipe", methods=["POST"])
def record_swipe_local():
"""Record a swipe on a movie (uses backend API for global rooms)"""
try:
data = request.get_json()
room_id = data.get('room_id')
username = data.get('username')
movie_id = data.get('movie_id')
movie_title = data.get('movie_title', '')
movie_year = data.get('movie_year')
action = data.get('action', 'pass') # 'like', 'pass', or 'super'
if not all([room_id, username, movie_id]):
return jsonify({'error': 'Missing required fields'}), 400
# Record swipe via backend API
response = requests.post(
f"{BACKEND_API_URL}/api/match/swipe",
json={
'room_id': room_id,
'username': username,
'movie_id': movie_id,
'movie_title': movie_title,
'movie_year': movie_year,
'action': action
},
timeout=10
)
if response.status_code != 200:
error_msg = response.json().get('detail', 'Failed to record swipe')
return jsonify({'error': error_msg}), response.status_code
return jsonify(response.json())
except requests.exceptions.RequestException as e:
return jsonify({'error': f'Backend unavailable: {str(e)}'}), 503
except Exception as e:
return jsonify({'error': f'Failed to record swipe: {str(e)}'}), 500
def get_movies_for_match_room(library_filter, plex_token):
"""Get movies from Plex for a match room"""
try:
# Use the token provided or fall back to env
token = plex_token or PLEX_TOKEN
if not token:
return []
plex = PlexServer(PLEX_URL, token)
# Try to find matching library
library = None
for section in plex.library.sections():
if section.title.lower() == library_filter.lower():
library = section
break
if not library:
# Fall back to first movie library
for section in plex.library.sections():
if section.type == 'movie':
library = section
break
if not library:
return []
# Get unwatched movies using fast filter
movies = library.search(unwatched=True, limit=200)
# Convert to simple dict format
movie_list = []
for movie in movies[:100]: # Limit to 100
poster_url = ''
if hasattr(movie, 'thumb') and movie.thumb:
poster_url = f"{PLEX_URL}{movie.thumb}?X-Plex-Token={token}"
# Get genres
genres = []
if hasattr(movie, 'genres'):
genres = [g.tag for g in movie.genres][:4]
movie_list.append({
'id': str(movie.ratingKey),
'title': movie.title,
'year': getattr(movie, 'year', ''),
'summary': getattr(movie, 'summary', '')[:300],
'poster': poster_url,
'genres': genres
})
random.shuffle(movie_list)
return movie_list
except Exception as e:
print(f"Error getting movies for match: {e}")
return []
# ==================== LEGACY MATCH API ENDPOINTS ====================
# Keep these for backwards compatibility but they proxy to local implementation
@app.route("/api/match/rooms", methods=["POST"])
@token_required
def create_match_room():
"""Create a new movie matching room using backend service"""
try:
data = request.get_json()
room_name = data.get('name', 'Movie Night')
library_filter = data.get('library', 'Movies')