-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathwebhook_listener.py
More file actions
executable file
·2592 lines (2118 loc) · 109 KB
/
Copy pathwebhook_listener.py
File metadata and controls
executable file
·2592 lines (2118 loc) · 109 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
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask import Response, send_file
import subprocess
import os
import re
import time
import logging
import json
import sonarr_utils
import radarr_utils
from datetime import datetime, timezone, timedelta
from dotenv import load_dotenv
import requests
import modified_episeerr
import threading
import feedparser
from functools import lru_cache
from logging.handlers import RotatingFileHandler
from api.jellyseerr_api import JellyseerrAPI
from jellyfin_utils import JellyfinAPI
import tmdb_utils
import plex_utils
app = Flask(__name__)
# Load environment variables
load_dotenv()
BASE_DIR = os.getcwd()
# Sonarr variables
SONARR_URL = os.getenv('SONARR_URL')
SONARR_API_KEY = os.getenv('SONARR_API_KEY')
# Radarr variables
RADARR_URL = os.getenv('RADARR_URL')
RADARR_API_KEY = os.getenv('RADARR_API_KEY')
# Jellyseerr variables
JELLYSEERR_URL = os.getenv('JELLYSEERR_URL', '')
# Import the environment variable limits
MAX_SHOWS_ITEMS = int(os.getenv('MAX_SHOWS_ITEMS', 24))
MAX_MOVIES_ITEMS = int(os.getenv('MAX_MOVIES_ITEMS', 24))
MAX_COMBINED_ITEMS = int(os.getenv('MAX_COMBINED_ITEMS', 24))
# Global variable to track pending requests from Jellyseerr
# Format: {tvdb_id: {request_id: "123", title: "Show Title"}}
jellyseerr_pending_requests = {}
# Other settings
REQUESTS_DIR = os.path.join(os.getcwd(), 'data', 'requests')
os.makedirs(REQUESTS_DIR, exist_ok=True)
LAST_PROCESSED_FILE = os.path.join(os.getcwd(), 'data', 'last_processed.json')
os.makedirs(os.path.dirname(LAST_PROCESSED_FILE), exist_ok=True)
# Initialize the Jellyseerr API client
jellyseerr_api = JellyseerrAPI()
jellyfin_api = JellyfinAPI(
jellyfin_token=os.getenv('JELLYFIN_TOKEN', ''),
jellyfin_user_id=os.getenv('JELLYFIN_USER_ID', '')
)
# Setup logging to capture all logs
log_file = os.getenv('LOG_PATH', os.path.join(os.getcwd(), 'logs', 'app.log'))
log_level = logging.INFO # Capture INFO and ERROR levels
# Create log directory if it doesn't exist
os.makedirs(os.path.dirname(log_file), exist_ok=True)
# Create a RotatingFileHandler
file_handler = RotatingFileHandler(
log_file,
maxBytes=1*1024*1024, # 1 MB max size
backupCount=2, # Keep 2 backup files
encoding='utf-8'
)
file_handler.setLevel(log_level)
file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(file_formatter)
# Configure the root logger
logging.basicConfig(
level=log_level,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[file_handler]
)
# Adding stream handler to also log to console for Docker logs to capture
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG if os.getenv('FLASK_DEBUG', 'false').lower() == 'true' else logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')
stream_handler.setFormatter(formatter)
app.logger.addHandler(stream_handler)
# Configuration management
config_path = os.path.join(app.root_path, 'config', 'config.json')
def load_config():
try:
with open(config_path, 'r') as file:
config = json.load(file)
if 'rules' not in config:
config['rules'] = {}
if 'preferences' not in config:
config['preferences'] = {
'radarr_quality_profile': 'Any',
'sonarr_quality_profile': 'Any',
'feed_preferences': DEFAULT_FEEDS # Add default feed preferences
}
elif 'feed_preferences' not in config['preferences']:
# If preferences exist but feed_preferences doesn't
config['preferences']['feed_preferences'] = DEFAULT_FEEDS
return config
except FileNotFoundError:
default_config = {
'rules': {
'full_seasons': {
'get_option': 'season',
'action_option': 'monitor',
'keep_watched': 'season',
'monitor_watched': False,
'series': []
}
},
'preferences': {
'radarr_quality_profile': 'Any',
'sonarr_quality_profile': 'Any',
'feed_preferences': DEFAULT_FEEDS
}
}
return default_config
def save_config(config):
with open(config_path, 'w') as file:
json.dump(config, file, indent=4)
def check_service_status(url):
try:
# Add a longer timeout and use a HEAD request which is lighter
response = requests.head(url, timeout=3, allow_redirects=True)
# Check for successful status codes
if response.status_code in [200, 301, 302, 303, 307, 308]:
return "Online"
except requests.exceptions.RequestException:
pass
return "Offline"
# Jellyfin Routes
@app.route('/api/jellyfin/connect', methods=['POST'])
def connect_to_jellyfin():
try:
data = request.json
jellyfin_url = data.get('jellyfin_url', '')
jellyfin_token = data.get('jellyfin_token', '')
jellyfin_user_id = data.get('jellyfin_user_id', '')
if not jellyfin_url or not jellyfin_token or not jellyfin_user_id:
return jsonify({"success": False, "message": "All Jellyfin connection parameters are required"}), 400
# Create temp JellyfinAPI instance to test connection and resolve ID if needed
temp_api = JellyfinAPI()
temp_api.jellyfin_url = jellyfin_url
temp_api.jellyfin_token = jellyfin_token
# Check if the provided user_id looks like a username (shorter than GUID)
if len(jellyfin_user_id) < 32:
# Treat as username and resolve
resolved_id = temp_api.get_user_id_by_name(jellyfin_user_id)
if resolved_id:
jellyfin_user_id = resolved_id
app.logger.info(f"Resolved username '{data.get('jellyfin_user_id')}' to ID: {jellyfin_user_id}")
else:
return jsonify({"success": False, "message": f"Could not find user with name: {jellyfin_user_id}"}), 400
# Update the global API instance
global jellyfin_api
jellyfin_api = JellyfinAPI()
jellyfin_api.jellyfin_url = jellyfin_url
jellyfin_api.jellyfin_token = jellyfin_token
jellyfin_api.jellyfin_user_id = jellyfin_user_id
# Test connection
stats = jellyfin_api.get_library_stats()
# Save to .env file
with open('.env', 'r') as f:
env_content = f.read()
# Update or add the variables
if 'JELLYFIN_URL=' in env_content:
env_content = re.sub(r'JELLYFIN_URL=.*', f'JELLYFIN_URL={jellyfin_url}', env_content)
else:
env_content += f'\nJELLYFIN_URL={jellyfin_url}'
if 'JELLYFIN_TOKEN=' in env_content:
env_content = re.sub(r'JELLYFIN_TOKEN=.*', f'JELLYFIN_TOKEN={jellyfin_token}', env_content)
else:
env_content += f'\nJELLYFIN_TOKEN={jellyfin_token}'
if 'JELLYFIN_USER_ID=' in env_content:
env_content = re.sub(r'JELLYFIN_USER_ID=.*', f'JELLYFIN_USER_ID={jellyfin_user_id}', env_content)
else:
env_content += f'\nJELLYFIN_USER_ID={jellyfin_user_id}'
with open('.env', 'w') as f:
f.write(env_content)
return jsonify({
"success": True,
"message": "Connected to Jellyfin successfully",
"stats": stats
})
except Exception as e:
app.logger.error(f"Error connecting to Jellyfin: {str(e)}")
return jsonify({"success": False, "message": str(e)}), 500
@app.route('/api/jellyfin/sync', methods=['POST'])
def sync_jellyfin_data():
"""Force a refresh of Jellyfin data."""
try:
if not jellyfin_api.jellyfin_token:
return jsonify({"success": False, "message": "Jellyfin not connected"}), 400
# We don't need to save data persistently like with Plex
# Just return success as we'll fetch fresh data on each page load
return jsonify({"success": True, "message": "Jellyfin data refreshed"})
except Exception as e:
app.logger.error(f"Error syncing Jellyfin data: {str(e)}")
return jsonify({"success": False, "message": str(e)}), 500
@app.route('/api/jellyfin/stats')
def get_jellyfin_stats():
try:
# Debug logging
app.logger.info(f"JellyfinAPI config: URL={jellyfin_api.jellyfin_url}, UserID={jellyfin_api.jellyfin_user_id}")
app.logger.info(f"Token exists: {bool(jellyfin_api.jellyfin_token)}")
if not jellyfin_api.jellyfin_token:
app.logger.error("No Jellyfin token configured")
return jsonify({"success": False, "message": "Jellyfin not connected - no token"}), 400
if not jellyfin_api.jellyfin_user_id:
app.logger.error("No Jellyfin user ID configured")
return jsonify({"success": False, "message": "Jellyfin not connected - no user ID"}), 400
# Test connection
try:
test_url = f"{jellyfin_api.jellyfin_url}/Users/{jellyfin_api.jellyfin_user_id}"
app.logger.info(f"Testing Jellyfin connection with URL: {test_url}")
response = requests.get(
test_url,
headers=jellyfin_api.get_headers(),
timeout=5
)
app.logger.info(f"Jellyfin test response: Status={response.status_code}")
if not response.ok:
app.logger.error(f"Failed to connect to Jellyfin: {response.status_code} - {response.text[:100]}")
return jsonify({
"success": False,
"message": f"Cannot connect to Jellyfin: {response.status_code}",
"stats": {
"library_stats": {"movies": 0, "tv_shows": 0},
"favorites_stats": {"movies": 0, "tv_shows": 0}
},
"lastUpdated": datetime.now().isoformat()
}), 200 # Return 200 but with error info so frontend can display it
except requests.exceptions.RequestException as e:
app.logger.error(f"Connection error to Jellyfin: {str(e)}")
return jsonify({
"success": False,
"message": f"Cannot connect to Jellyfin: {str(e)}",
"stats": {
"library_stats": {"movies": 0, "tv_shows": 0},
"favorites_stats": {"movies": 0, "tv_shows": 0}
},
"lastUpdated": datetime.now().isoformat()
}), 200 # Return 200 but with error info
# If we got here, connection is good - get stats
stats = jellyfin_api.get_formatted_stats()
# Log the stats for debugging
app.logger.info(f"Jellyfin stats retrieved: {json.dumps(stats)}")
return jsonify(stats)
except Exception as e:
app.logger.error(f"Error getting Jellyfin stats: {str(e)}", exc_info=True)
return jsonify({
"success": False,
"message": str(e),
"stats": {
"library_stats": {"movies": 0, "tv_shows": 0},
"favorites_stats": {"movies": 0, "tv_shows": 0}
},
"lastUpdated": datetime.now().isoformat()
}), 200 # Return 200 but with error info
@app.route('/api/jellyfin/favorites')
def get_jellyfin_favorites():
try:
app.logger.info("Jellyfin favorites API called")
if not jellyfin_api.jellyfin_token:
return jsonify({"success": False, "message": "Jellyfin not connected", "items": []}), 200
# Use this URL with specific parameters
url = f"{jellyfin_api.jellyfin_url}/Users/{jellyfin_api.jellyfin_user_id}/Items"
params = {
'Recursive': 'true',
'IsFavorite': 'true',
'IncludeItemTypes': 'Movie,Series', # Only include Movies and TV Series
'SortBy': 'DateCreated,SortName',
'SortOrder': 'Descending'
}
app.logger.info(f"Getting favorites from: {url} with params: {params}")
response = requests.get(
url,
headers=jellyfin_api.get_headers(),
params=params
)
app.logger.info(f"Favorites response: {response.status_code}")
if response.ok:
data = response.json()
items = data.get('Items', [])
app.logger.info(f"Found {len(items)} favorites")
# Process items
processed_items = []
for item in items:
# Determine media type
media_type = 'movie' if item.get('Type') == 'Movie' else 'tv'
processed_item = {
'Id': item.get('Id'),
'Name': item.get('Name', ''),
'Type': item.get('Type', ''),
'type': media_type,
'ProductionYear': item.get('ProductionYear'),
'Overview': item.get('Overview', ''),
'ImageTags': item.get('ImageTags', {})
}
processed_items.append(processed_item)
return jsonify({"success": True, "items": processed_items, "count": len(processed_items)})
else:
app.logger.error(f"Failed to get favorites: {response.status_code} - {response.text[:100]}")
return jsonify({"success": False, "message": f"Failed to get favorites: {response.status_code}", "items": []}), 200
except Exception as e:
app.logger.error(f"Error getting Jellyfin favorites: {str(e)}")
return jsonify({"success": False, "message": str(e), "items": []}), 200
@app.route('/api/jellyfin/recommendations')
def get_jellyfin_recommendations():
try:
app.logger.info("Jellyfin recommendations API called")
# Use TMDB data for recommendations
movies_data = tmdb_utils.get_quality_movies()
tv_data = tmdb_utils.get_quality_tv_shows()
# Format the results
movies = []
for movie in movies_data.get('results', [])[:12]:
movies.append({
'Id': movie.get('id'),
'Name': movie.get('title'),
'type': 'movie',
'ProductionYear': movie.get('release_date', '').split('-')[0] if movie.get('release_date') else '',
'Overview': movie.get('overview', ''),
'posterUrl': f"https://image.tmdb.org/t/p/w300{movie.get('poster_path')}" if movie.get('poster_path') else None
})
shows = []
for show in tv_data.get('results', [])[:12]:
shows.append({
'Id': show.get('id'),
'Name': show.get('name'),
'type': 'tv',
'ProductionYear': show.get('first_air_date', '').split('-')[0] if show.get('first_air_date') else '',
'Overview': show.get('overview', ''),
'posterUrl': f"https://image.tmdb.org/t/p/w300{show.get('poster_path')}" if show.get('poster_path') else None
})
# Combine and limit
recommendations = movies + shows
recommendations = recommendations[:24]
return jsonify({"success": True, "items": recommendations, "count": len(recommendations)})
except Exception as e:
app.logger.error(f"Error getting recommendations: {str(e)}")
return jsonify({"success": False, "message": str(e), "items": []}), 200
@app.route('/api/jellyfin/recent-additions')
def get_jellyfin_recent_additions():
try:
app.logger.info("Jellyfin recent additions API called")
if not jellyfin_api.jellyfin_token:
return jsonify({"success": False, "message": "Jellyfin not connected", "items": []}), 200
# Use the Items/Latest endpoint
url = f"{jellyfin_api.jellyfin_url}/Users/{jellyfin_api.jellyfin_user_id}/Items/Latest"
app.logger.info(f"Getting recent items from: {url}")
response = requests.get(
url,
headers=jellyfin_api.get_headers(),
params={
'Limit': 24,
'Fields': 'Overview,ProductionYear',
'IncludeItemTypes': 'Movie,Series' # Only get Movies and Series, exclude Episodes
}
)
app.logger.info(f"Recent items response: {response.status_code}")
if response.ok:
items = response.json()
app.logger.info(f"Found {len(items)} recent items")
# Process items
processed_items = []
for item in items:
# Determine media type
media_type = 'movie' if item.get('Type') == 'Movie' else 'tv'
processed_item = {
'Id': item.get('Id'),
'Name': item.get('Name', ''),
'Type': item.get('Type', ''),
'type': media_type,
'ProductionYear': item.get('ProductionYear'),
'Overview': item.get('Overview', ''),
'ImageTags': item.get('ImageTags', {})
}
processed_items.append(processed_item)
return jsonify({"success": True, "items": processed_items, "count": len(processed_items)})
else:
app.logger.error(f"Failed to get recent items: {response.status_code} - {response.text[:100]}")
return jsonify({"success": False, "message": f"Failed to get recent items: {response.status_code}", "items": []}), 200
except Exception as e:
app.logger.error(f"Error getting Jellyfin recent additions: {str(e)}")
return jsonify({"success": False, "message": str(e), "items": []}), 200
@app.route('/api/jellyfin/image/<item_id>/<image_type>')
def get_jellyfin_image(item_id, image_type):
try:
if not jellyfin_api.jellyfin_token:
return jsonify({"success": False, "message": "Jellyfin not connected"}), 400
# Get parameters
width = request.args.get('width', '300')
tag = request.args.get('tag', '')
# Build URL
image_url = f"{jellyfin_api.jellyfin_url}/Items/{item_id}/Images/{image_type}"
if tag:
image_url += f"?tag={tag}&width={width}"
else:
image_url += f"?width={width}"
# Proxy the image to avoid CORS issues
response = requests.get(image_url, headers=jellyfin_api.get_headers(), stream=True)
if response.ok:
return Response(
response.iter_content(chunk_size=1024),
content_type=response.headers['Content-Type']
)
else:
return send_file('static/placeholder-banner.png', mimetype='image/png')
except Exception as e:
app.logger.error(f"Error getting Jellyfin image: {str(e)}")
return send_file('static/placeholder-banner.png', mimetype='image/png')
@app.route('/api/plex/sync', methods=['POST'])
def sync_plex_watchlist():
"""Force a sync of the Plex watchlist."""
try:
# Read Plex token directly from .env
plex_token = os.getenv('PLEX_TOKEN', '')
if not plex_token:
return jsonify({"success": False, "message": "Plex not connected"}), 400
plex_api = plex_utils.PlexWatchlistAPI(plex_token)
success = plex_api.save_watchlist_data()
if success:
return jsonify({"success": True, "message": "Watchlist synced successfully"})
else:
return jsonify({"success": False, "message": "Failed to sync watchlist"}), 500
except Exception as e:
app.logger.error(f"Error syncing Plex watchlist: {str(e)}")
return jsonify({"success": False, "message": str(e)}), 500
@app.route('/api/plex/connect', methods=['POST'])
def connect_to_plex():
try:
plex_token = request.form.get('plex_token', '')
if not plex_token:
return jsonify({"success": False, "message": "Plex token is required"}), 400
# Test the token
plex_api = plex_utils.PlexWatchlistAPI(plex_token)
watchlist = plex_api.get_watchlist()
if 'MediaContainer' not in watchlist:
return jsonify({"success": False, "message": "Invalid Plex token"}), 400
# Save token to .env file instead of config
with open('.env', 'a') as f:
f.write(f"\nPLEX_TOKEN={plex_token}\n")
# Update config to mark Plex as connected
config = load_config()
if 'plex' not in config:
config['plex'] = {}
config['plex']['connected'] = True
config['plex']['auto_download'] = False # Default to off
config['plex']['last_sync'] = datetime.now().isoformat()
save_config(config)
# Sync watchlist
plex_api.save_watchlist_data()
return jsonify({"success": True, "message": "Connected to Plex successfully"})
except Exception as e:
app.logger.error(f"Error connecting to Plex: {str(e)}")
return jsonify({"success": False, "message": str(e)}), 500
@app.route('/api/plex/watchlist')
def get_plex_watchlist():
try:
plex_token = os.getenv('PLEX_TOKEN', '')
if not plex_token:
return jsonify({"success": False, "message": "Plex not connected"}), 400
plex_api = plex_utils.PlexWatchlistAPI(plex_token)
watchlist_data = plex_api.get_watchlist()
# Prepare categories and stats
categories = {
'tv_in_watchlist': [],
'tv_not_in_arr': [],
'movie_in_watchlist': [],
'movie_not_in_arr': []
}
# Get existing Sonarr/Radarr series
sonarr_preferences = sonarr_utils.load_preferences()
sonarr_series = sonarr_utils.get_series_list(sonarr_preferences)
sonarr_tmdb_ids = set(str(series.get('tmdbId')) for series in sonarr_series if series.get('tmdbId'))
radarr_preferences = radarr_utils.load_preferences()
radarr_movies = radarr_utils.get_movie_list(radarr_preferences)
radarr_tmdb_ids = set(str(movie.get('tmdbId')) for movie in radarr_movies if movie.get('tmdbId'))
# Check the correct structure from the API
if 'MediaContainer' in watchlist_data and 'Metadata' in watchlist_data['MediaContainer']:
items = watchlist_data['MediaContainer']['Metadata']
for item in items:
media_type = 'movie' if item.get('type') == 'movie' else 'tv'
processed_item = {
'title': item.get('title', ''),
'type': media_type,
'year': item.get('year'),
'plex_guid': item.get('guid', ''),
'thumb': item.get('thumb', '')
}
# Attempt to get TMDB ID
try:
if media_type == 'movie':
search_results = tmdb_utils.search_movies(processed_item['title'])
if search_results.get('results'):
processed_item['tmdb_id'] = search_results['results'][0]['id']
else:
search_results = tmdb_utils.search_tv_shows(processed_item['title'])
if search_results.get('results'):
processed_item['tmdb_id'] = search_results['results'][0]['id']
except Exception as e:
app.logger.error(f"Error getting TMDB ID for {processed_item['title']}: {str(e)}")
# Categorize items
tmdb_id = str(processed_item.get('tmdb_id', ''))
if media_type == 'tv':
categories['tv_in_watchlist'].append(processed_item)
if not tmdb_id or tmdb_id not in sonarr_tmdb_ids:
categories['tv_not_in_arr'].append(processed_item)
else:
categories['movie_in_watchlist'].append(processed_item)
if not tmdb_id or tmdb_id not in radarr_tmdb_ids:
categories['movie_not_in_arr'].append(processed_item)
# Get library counts
library_sections = plex_api.get_library_sections()
library_stats = {
"movies": 0,
"tv_shows": 0
}
if library_sections.get("movie"):
try:
movie_url = f"{plex_api.plex_url}/library/sections/{library_sections['movie']}/all"
movie_response = requests.get(movie_url, headers=plex_api.get_headers())
if movie_response.ok:
movie_data = movie_response.json()
library_stats["movies"] = movie_data.get("MediaContainer", {}).get("size", 0)
except Exception as e:
app.logger.error(f"Error getting movie count: {str(e)}")
if library_sections.get("tv"):
try:
tv_url = f"{plex_api.plex_url}/library/sections/{library_sections['tv']}/all"
tv_response = requests.get(tv_url, headers=plex_api.get_headers())
if tv_response.ok:
tv_data = tv_response.json()
library_stats["tv_shows"] = tv_data.get("MediaContainer", {}).get("size", 0)
except Exception as e:
app.logger.error(f"Error getting TV show count: {str(e)}")
# Prepare watchlist stats
watchlist_stats = {
"movies": len(categories['movie_in_watchlist']),
"tv_shows": len(categories['tv_in_watchlist'])
}
response_data = {
'success': True,
'watchlist': {
'categories': categories,
'last_updated': datetime.now().isoformat(),
'count': len(categories['tv_in_watchlist']) + len(categories['movie_in_watchlist']),
'stats': {
'library_stats': library_stats,
'watchlist_stats': watchlist_stats
}
}
}
return jsonify(response_data)
except Exception as e:
app.logger.error(f"Error fetching Plex watchlist: {str(e)}")
return jsonify({"success": False, "message": str(e)}), 500
def cleanup_config_rules():
"""Remove series from rules that no longer exist in Sonarr."""
try:
# Load the current configuration
config = load_config()
# Load Sonarr preferences
sonarr_preferences = sonarr_utils.load_preferences()
headers = {
'X-Api-Key': sonarr_preferences['SONARR_API_KEY'],
'Content-Type': 'application/json'
}
sonarr_url = sonarr_preferences['SONARR_URL']
# Fetch all series from Sonarr
series_response = requests.get(f"{sonarr_url}/api/v3/series", headers=headers)
if not series_response.ok:
app.logger.error("Failed to fetch series from Sonarr during config cleanup")
return
# Get set of existing series IDs as strings
existing_series_ids = set(str(series['id']) for series in series_response.json())
# Track removed series for logging
removed_series = {}
# Iterate through all rules
for rule_name, rule_details in config['rules'].items():
# Filter out series IDs that no longer exist in Sonarr
original_series = rule_details.get('series', [])
updated_series = [
series_id for series_id in original_series
if series_id in existing_series_ids
]
# Track removed series
if len(updated_series) != len(original_series):
removed_series[rule_name] = [
sid for sid in original_series
if sid not in updated_series
]
# Update the rule's series list
rule_details['series'] = updated_series
# Remove empty rules
config['rules'] = {
rule: details for rule, details in config['rules'].items()
if details.get('series')
}
# Save the updated configuration
save_config(config)
# Log removed series
for rule, series_list in removed_series.items():
app.logger.info(f"Cleaned up rule '{rule}': Removed series IDs {series_list}")
app.logger.info("Completed configuration rules cleanup")
except Exception as e:
app.logger.error(f"Error during config rules cleanup: {str(e)}", exc_info=True)
@app.route('/api/tmdb/filtered/tv')
def tmdb_filtered_tv():
"""Get filtered TV shows using TMDB API directly."""
try:
# Get quality TV shows
shows_data = tmdb_utils.get_quality_tv_shows()
# Format the data to match what your frontend expects
results = []
for show in shows_data.get('results', []):
results.append({
'id': show['id'],
'name': show['name'],
'posterUrl': f"https://image.tmdb.org/t/p/w300{show['poster_path']}" if show.get('poster_path') else '/static/placeholder-banner.png',
'overview': show.get('overview', ''),
'releaseYear': show.get('first_air_date', '').split('-')[0] if show.get('first_air_date') else '',
'genre_ids': show.get('genre_ids', [])
})
app.logger.info(f"Returning {len(results)} filtered TV shows")
return jsonify({'results': results})
except Exception as e:
app.logger.error(f"Error in tmdb_filtered_tv: {str(e)}", exc_info=True)
return jsonify({"results": [], "error": str(e)})
@app.route('/api/tmdb/filtered/movies')
def tmdb_filtered_movies():
"""Get filtered movies using TMDB API directly."""
try:
# Get quality movies
movies_data = tmdb_utils.get_quality_movies()
# Format the data to match what your frontend expects
results = []
for movie in movies_data.get('results', []):
results.append({
'id': movie['id'],
'title': movie['title'],
'posterUrl': f"https://image.tmdb.org/t/p/w300{movie['poster_path']}" if movie.get('poster_path') else '/static/placeholder-banner.png',
'overview': movie.get('overview', ''),
'releaseYear': movie.get('release_date', '').split('-')[0] if movie.get('release_date') else '',
'genre_ids': movie.get('genre_ids', [])
})
app.logger.info(f"Returning {len(results)} filtered movies")
return jsonify({'results': results})
except Exception as e:
app.logger.error(f"Error in tmdb_filtered_movies: {str(e)}", exc_info=True)
return jsonify({"results": [], "error": str(e)})
@app.route('/api/tmdb/season/<tmdb_id>/<season_number>')
def get_tmdb_season(tmdb_id, season_number):
"""Get season details from TMDB API."""
try:
season_data = tmdb_utils.get_tmdb_endpoint(f"tv/{tmdb_id}/season/{season_number}")
return jsonify(season_data)
except Exception as e:
app.logger.error(f"Error fetching season data: {str(e)}")
return jsonify({"error": str(e)}), 500
def create_pending_request(series):
"""Create a pending request for season/episode selection."""
request_id = f"season-select-{series['id']}-{int(time.time())}"
pending_request = {
"id": request_id,
"series_id": series['id'],
"title": series.get('title', 'Unknown Series'),
"tmdb_id": series.get('tmdbId'),
"tvdb_id": series.get('tvdbId'),
"needs_season_selection": True,
"source": "sonarr_webhook",
"source_name": "Sonarr Webhook",
"needs_attention": True,
"created_at": int(time.time())
}
os.makedirs(REQUESTS_DIR, exist_ok=True)
with open(os.path.join(REQUESTS_DIR, f"{request_id}.json"), 'w') as f:
json.dump(pending_request, f)
app.logger.info(f"Created pending request for {pending_request['title']}")
return pending_request
@app.route('/api/radarr/request', methods=['POST'])
def radarr_request():
"""Handle movie requests directly to Radarr."""
try:
data = request.json
tmdb_id = data.get('tmdbId')
title = data.get('title', 'Unknown')
if not tmdb_id:
return jsonify({"success": False, "message": "No TMDB ID provided"}), 400
# Load config to get preferred profile
config = load_config()
preferred_profile = config.get('preferences', {}).get('radarr_quality_profile', 'Any')
# Check if movie exists in Radarr
radarr_preferences = radarr_utils.load_preferences()
headers = {
'X-Api-Key': radarr_preferences['RADARR_API_KEY'],
'Content-Type': 'application/json'
}
radarr_url = radarr_preferences['RADARR_URL']
# Look up the movie in TMDB
response = requests.get(
f"{radarr_url}/api/v3/movie/lookup/tmdb",
headers=headers,
params={"tmdbId": tmdb_id}
)
if not response.ok:
return jsonify({"success": False, "message": f"Failed to look up movie in Radarr"}), 500
lookup_results = response.json()
# Check if movie already exists in Radarr
existing_movies = radarr_utils.get_movie_list(radarr_preferences)
movie_id = None
for existing_movie in existing_movies:
if existing_movie.get('tmdbId') == tmdb_id:
movie_id = existing_movie.get('id')
break
# If not in Radarr, add it
if not movie_id and lookup_results:
# Get the root folder path
root_folder_response = requests.get(f"{radarr_url}/api/v3/rootfolder", headers=headers)
if not root_folder_response.ok or not root_folder_response.json():
return jsonify({"success": False, "message": "Failed to get root folders from Radarr"}), 500
root_folder = root_folder_response.json()[0].get('path')
# Get quality profiles
profile_response = requests.get(f"{radarr_url}/api/v3/qualityprofile", headers=headers)
if not profile_response.ok or not profile_response.json():
return jsonify({"success": False, "message": "Failed to get quality profiles from Radarr"}), 500
# Look for the preferred profile
quality_profile_id = None
profiles = profile_response.json()
# If 'Any' is specified, use the first profile
if preferred_profile == 'Any':
if profiles:
quality_profile_id = profiles[0].get('id')
else:
# Try to find the named profile
for profile in profiles:
if profile.get('name') == preferred_profile:
quality_profile_id = profile.get('id')
break
# Fallback to first profile if preferred not found
if not quality_profile_id and profiles:
quality_profile_id = profiles[0].get('id')
if not quality_profile_id:
return jsonify({"success": False, "message": "No quality profiles available in Radarr"}), 500
# Prepare movie for adding
movie_to_add = lookup_results
movie_to_add['rootFolderPath'] = root_folder
movie_to_add['qualityProfileId'] = quality_profile_id
movie_to_add['monitored'] = True
movie_to_add['addOptions'] = {
'searchForMovie': True
}
# Add to Radarr
add_response = requests.post(
f"{radarr_url}/api/v3/movie",
headers=headers,
json=movie_to_add
)
if not add_response.ok:
return jsonify({"success": False, "message": f"Failed to add movie to Radarr: {add_response.text}"}), 500
movie_id = add_response.json().get('id')
return jsonify({"success": True, "message": f"Successfully added movie '{title}' to Radarr"})
elif movie_id:
# Movie already exists, just search for it
search_response = requests.post(
f"{radarr_url}/api/v3/command",
headers=headers,
json={"name": "MoviesSearch", "movieIds": [movie_id]}
)
if not search_response.ok:
return jsonify({"success": False, "message": f"Failed to search for movie {title}"}), 500
return jsonify({"success": True, "message": f"Successfully refreshed search for existing movie '{title}'"})
else:
return jsonify({"success": False, "message": f"Failed to lookup or add movie '{title}'"}), 500
except Exception as e:
app.logger.error(f"Error requesting movie: {str(e)}", exc_info=True)
return jsonify({"success": False, "message": str(e)}), 500
@app.route('/api/process-selected-episodes', methods=['POST'])
def process_selected_episodes_api():
"""Process selected episodes without creating a new request."""
try:
data = request.json
tmdb_id = data.get('tmdbId')
season_number = data.get('seasonNumber')
episode_numbers = data.get('episodes', [])
# Detect if this is a solo episode 1
is_first_episode_only = (
len(episode_numbers) == 1 and
episode_numbers[0] == 1
)
if not tmdb_id or not season_number or not episode_numbers:
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
cleanup_config_rules()
except Exception as e:
app.logger.error(f"Error during config rule cleanup: {str(e)}")
# Find the series in Sonarr
sonarr_preferences = sonarr_utils.load_preferences()
headers = {
'X-Api-Key': sonarr_preferences['SONARR_API_KEY'],
'Content-Type': 'application/json'
}
sonarr_url = sonarr_preferences['SONARR_URL']
# First find the TVDB ID from the TMDB ID
details = tmdb_utils.get_external_ids(tmdb_id, 'tv')
tvdb_id = details.get('tvdb_id')
if not tvdb_id:
return jsonify({"success": False, "error": "Could not find TVDB ID for this show"}), 400
# Check if series already exists in Sonarr
series_id = None