-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
1568 lines (1351 loc) · 65.8 KB
/
main.py
File metadata and controls
1568 lines (1351 loc) · 65.8 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 uvicorn
import yaml
import requests
import logging
import json
import asyncio
import re
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi import FastAPI, Request, Form, Depends, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from models import (
SonarrWebhook,
RadarrWebhook,
SonarrInstance,
RadarrInstance,
PlexServer as PlexServerModel,
JellyfinServer,
EmbyServer,
)
from typing import Dict, Any, List, Optional
from contextlib import asynccontextmanager
from radarr_service import (
handle_radarr_grab,
handle_radarr_import,
handle_radarr_delete,
handle_radarr_movie_add,
)
from sonarr_service import handle_sonarr_grab, handle_sonarr_import, handle_sonarr_series_add
from utils import load_config, get_config, save_config, parse_time_string
from media_server_service import MediaServerScanner
import random
import string
from pathlib import Path
import aiohttp
import xml.etree.ElementTree as ET
from collections import defaultdict
import time
import uuid
# Application version - update this when creating new releases
VERSION = "0.0.44"
# Create a logger for this module
logger = logging.getLogger(__name__)
# Store instances at module level with proper typing
sonarr_instances: List[SonarrInstance] = []
radarr_instances: List[RadarrInstance] = []
# Add after other global variables
webhook_batches = defaultdict(list)
webhook_batch_timeout = 5 # seconds to wait for batched webhooks
webhook_batch_lock = asyncio.Lock()
# TODO: Add anime support
# ------------------------------------------------------------------------------
# Load YAML Config and Setup Logging
# ------------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
global sonarr_instances, radarr_instances # Add this line to use global variables
config = load_config()
# Setup logging based on config
log_level = getattr(logging, config.get('log_level', 'INFO').upper())
# Configure root logger with improved format
logging.basicConfig(
level=log_level,
format='%(asctime)s [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Use more descriptive level names instead of abbreviations
logging.addLevelName(logging.INFO, '\033[32mINFO\033[0m') # Green
logging.addLevelName(logging.ERROR, '\033[31mERROR\033[0m') # Red
logging.addLevelName(logging.WARNING, '\033[33mWARN\033[0m') # Yellow
logging.addLevelName(logging.DEBUG, '\033[36mDEBUG\033[0m') # Cyan
# Ensure all module loggers have the correct level
for logger_name in ['media_server_service', 'radarr_service', 'sonarr_service']:
module_logger = logging.getLogger(logger_name)
module_logger.setLevel(log_level)
# Ensure the logger has a handler
if not module_logger.handlers:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S'))
module_logger.addHandler(handler)
# Build startup messages
logger.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
logger.info("\033[1mAutosync\033[0m starting up")
logger.info(f" ├─ Version: \033[1m{VERSION}\033[0m")
logger.info(f" ├─ Server port: \033[1m3536\033[0m")
logger.info(f" └─ Log level: \033[1m{config.get('log_level', 'INFO').lower()}\033[0m")
# Convert dict instances to proper types and assign to global variables
sonarr_instances = [
SonarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "sonarr"
]
radarr_instances = [
RadarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "radarr"
]
# Get media servers
media_servers = config.get("media_servers", [])
# Group servers by type
server_types = {}
for server in media_servers:
if server.get("enabled", True):
server_type = server["type"].capitalize()
if server_type not in server_types:
server_types[server_type] = 0
server_types[server_type] += 1
# Build initialization message for instances
logger.info("Instances configuration:")
logger.info(f" ├─ Sonarr: \033[1m{len(sonarr_instances)}\033[0m instance(s)")
logger.info(f" └─ Radarr: \033[1m{len(radarr_instances)}\033[0m instance(s)")
# Build initialization message for media servers
logger.info("Media servers configuration:")
media_server_types = []
for server_type, count in server_types.items():
media_server_types.append(f"{server_type}: \033[1m{count}\033[0m")
if media_server_types:
for i, server_info in enumerate(media_server_types):
prefix = " └─ " if i == len(media_server_types) - 1 else " ├─ "
logger.info(f"{prefix}{server_info}")
else:
logger.info(" └─ No media servers configured")
# Log version information
logger.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
except Exception as e:
logger.error(f"Failed to initialize server error=\"{str(e)}\"")
raise
yield
app = FastAPI(lifespan=lifespan)
# Mount static files with HTTPS configuration
app.mount("/static", StaticFiles(directory="static", html=True), name="static")
# Setup Jinja2 templates
templates = Jinja2Templates(directory="templates")
def get_template_context(request: Request, **kwargs) -> Dict[str, Any]:
"""Create a template context with common variables."""
# Get the forwarded protocol (https if forwarded, otherwise use request scheme)
scheme = request.headers.get("X-Forwarded-Proto", request.url.scheme)
# Build base URL using the correct scheme
base_url = str(request.base_url)
if base_url.startswith("http:") and scheme == "https":
base_url = "https:" + base_url[5:]
context = {
"request": request,
"version": VERSION,
"base_url": base_url
}
context.update(kwargs)
return context
# ------------------------------------------------------------------------------
# Frontend Routes
# ------------------------------------------------------------------------------
@app.get("/")
async def index(request: Request):
"""Render the dashboard page."""
config = get_config()
# Get instances
sonarr_instances = [
SonarrInstance(**inst)
for inst in config.get("instances", [])
if inst.get("type", "").lower() == "sonarr"
]
radarr_instances = [
RadarrInstance(**inst)
for inst in config.get("instances", [])
if inst.get("type", "").lower() == "radarr"
]
# Get media servers
media_servers = config.get("media_servers", [])
return templates.TemplateResponse(
"dashboard.html",
get_template_context(
request,
sonarr_instances=sonarr_instances,
radarr_instances=radarr_instances,
media_servers=media_servers,
config=config,
messages=[]
)
)
@app.get("/instances/add")
async def add_instance_form(request: Request, type: str = "sonarr"):
"""Render the add instance form."""
if type.lower() not in ["sonarr", "radarr"]:
type = "sonarr" # Default to sonarr if invalid type
config = get_config()
return templates.TemplateResponse(
"add_instance.html",
get_template_context(request, instance_type=type.lower(), config=config, messages=[])
)
@app.post("/instances/add")
async def add_instance(
request: Request,
name: str = Form(...),
type: str = Form(...),
url: str = Form(...),
api_key: str = Form(...),
root_folder_path: str = Form(...),
quality_profile_id: int = Form(...),
language_profile_id: Optional[int] = Form(None),
season_folder: Optional[bool] = Form(False),
search_on_sync: Optional[bool] = Form(False),
enabled_events: List[str] = Form([])
):
"""Add a new instance to the configuration."""
global sonarr_instances, radarr_instances
config = get_config()
# Create instance data
instance_data = {
"name": name,
"type": type,
"url": url,
"api_key": api_key,
"root_folder_path": root_folder_path,
"quality_profile_id": quality_profile_id,
"search_on_sync": search_on_sync,
"enabled_events": enabled_events
}
# Add Sonarr-specific fields
if type.lower() == "sonarr":
instance_data["language_profile_id"] = language_profile_id or 1
instance_data["season_folder"] = season_folder
# Check if instance with same name and type already exists
for idx, inst in enumerate(config.get("instances", [])):
if inst.get("name") == name and inst.get("type") == type:
# Replace existing instance
config["instances"][idx] = instance_data
save_config(config)
# Reload instances
sonarr_instances = [
SonarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "sonarr"
]
radarr_instances = [
RadarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "radarr"
]
return RedirectResponse(url="/", status_code=303)
# Add new instance
if "instances" not in config:
config["instances"] = []
config["instances"].append(instance_data)
save_config(config)
# Reload instances
sonarr_instances = [
SonarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "sonarr"
]
radarr_instances = [
RadarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "radarr"
]
return RedirectResponse(url="/", status_code=303)
@app.get("/instances/delete/{name}/{type}")
async def delete_instance(request: Request, name: str, type: str):
"""Delete an instance from the configuration."""
global sonarr_instances, radarr_instances
config = get_config()
# Find and remove the instance
config["instances"] = [
inst for inst in config.get("instances", [])
if not (inst.get("name") == name and inst.get("type").lower() == type.lower())
]
save_config(config)
# Reload instances
sonarr_instances = [
SonarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "sonarr"
]
radarr_instances = [
RadarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "radarr"
]
return RedirectResponse(url="/", status_code=303)
@app.get("/media-servers/add")
async def add_media_server_form(request: Request):
"""Render the add media server form."""
config = get_config()
return templates.TemplateResponse(
"add_media_server.html",
get_template_context(request, config=config, messages=[])
)
@app.post("/media-servers/add")
async def add_media_server(
request: Request,
name: str = Form(...),
type: str = Form(...),
url: str = Form(...),
token: Optional[str] = Form(None),
api_key: Optional[str] = Form(None),
enabled: Optional[bool] = Form(True),
rewrite_from: Optional[List[str]] = Form([]),
rewrite_to: Optional[List[str]] = Form([])
):
"""Add a new media server to the configuration."""
config = get_config()
# Check if server with same name already exists
for server in config.get("media_servers", []):
if server.get("name") == name:
return templates.TemplateResponse(
"add_media_server.html",
get_template_context(request, messages=[{"type": "danger", "text": "A server with this name already exists"}])
)
# Create server data
server_data = {
"name": name,
"type": type,
"url": url,
"enabled": enabled
}
# Add type-specific fields
if type.lower() == "plex":
if not token:
return templates.TemplateResponse(
"add_media_server.html",
get_template_context(request, messages=[{"type": "danger", "text": "Plex token is required"}])
)
server_data["token"] = token
else:
if not api_key:
return templates.TemplateResponse(
"add_media_server.html",
get_template_context(request, messages=[{"type": "danger", "text": "API key is required"}])
)
server_data["api_key"] = api_key
# Add rewrite rules if any
if rewrite_from and rewrite_to:
server_data["rewrite"] = [
{"from_path": f, "to_path": t}
for f, t in zip(rewrite_from, rewrite_to)
if f and t # Only add rules where both from and to are provided
]
# Add server to config
if "media_servers" not in config:
config["media_servers"] = []
config["media_servers"].append(server_data)
save_config(config)
return RedirectResponse(url="/", status_code=303)
@app.get("/media-servers/delete/{name}")
async def delete_media_server(request: Request, name: str):
"""Delete a media server from the configuration."""
config = get_config()
# Find and remove the server
config["media_servers"] = [
server for server in config.get("media_servers", [])
if server.get("name") != name
]
save_config(config)
return RedirectResponse(url="/", status_code=303)
@app.get("/instances/edit/{name}/{type}")
async def edit_instance_form(request: Request, name: str, type: str):
"""Render the edit instance form."""
config = get_config()
# Find the instance
instance = None
for inst in config["instances"]:
if inst["name"] == name and inst["type"].lower() == type.lower():
instance = inst
break
if not instance:
return RedirectResponse(url="/", status_code=303)
return templates.TemplateResponse(
"edit_instance.html",
get_template_context(request, instance=instance, config=config, messages=[])
)
@app.post("/instances/edit/{name}/{type}")
async def edit_instance(
request: Request,
name: str,
type: str,
new_name: str = Form(...),
url: str = Form(...),
api_key: str = Form(...),
root_folder_path: str = Form(...),
quality_profile_id: int = Form(...),
language_profile_id: Optional[int] = Form(None),
season_folder: Optional[bool] = Form(False),
search_on_sync: Optional[bool] = Form(False),
enabled_events: List[str] = Form([]),
rewrite_from: Optional[List[str]] = Form([]),
rewrite_to: Optional[List[str]] = Form([])
):
"""Update an existing instance in the configuration."""
global sonarr_instances, radarr_instances
config = get_config()
# Create updated instance data
instance_data = {
"name": new_name,
"type": type,
"url": url,
"api_key": api_key,
"root_folder_path": root_folder_path,
"quality_profile_id": quality_profile_id,
"search_on_sync": search_on_sync,
"enabled_events": enabled_events
}
# Add Sonarr-specific fields
if type.lower() == "sonarr":
instance_data["language_profile_id"] = language_profile_id or 1
instance_data["season_folder"] = season_folder
# Add rewrite rules if any
if rewrite_from and rewrite_to:
instance_data["rewrite"] = [
{"from_path": f, "to_path": t}
for f, t in zip(rewrite_from, rewrite_to)
if f and t # Only add rules where both from and to are provided
]
# Find and update the instance
for idx, inst in enumerate(config.get("instances", [])):
if inst.get("name") == name and inst.get("type").lower() == type.lower():
config["instances"][idx] = instance_data
save_config(config)
# Reload instances
sonarr_instances = [
SonarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "sonarr"
]
radarr_instances = [
RadarrInstance(**inst)
for inst in config["instances"]
if inst["type"].lower() == "radarr"
]
break
return RedirectResponse(url="/", status_code=303)
@app.get("/media-servers/edit/{name}")
async def edit_media_server_form(request: Request, name: str):
"""Render the edit media server form."""
config = get_config()
# Find the server
server = None
for srv in config["media_servers"]:
if srv["name"] == name:
server = srv
break
if not server:
return RedirectResponse(url="/", status_code=303)
return templates.TemplateResponse(
"edit_media_server.html",
get_template_context(request, server=server, config=config, messages=[])
)
@app.post("/media-servers/edit/{name}")
async def edit_media_server(
request: Request,
name: str,
new_name: str = Form(...),
type: str = Form(...),
url: str = Form(...),
token: Optional[str] = Form(None),
api_key: Optional[str] = Form(None),
enabled: Optional[bool] = Form(True),
rewrite_from: Optional[List[str]] = Form([]),
rewrite_to: Optional[List[str]] = Form([])
):
"""Update an existing media server in the configuration."""
config = get_config()
# Create updated server data
server_data = {
"name": new_name,
"type": type,
"url": url,
"enabled": enabled
}
# Add type-specific fields
if type.lower() == "plex":
if not token:
return templates.TemplateResponse(
"edit_media_server.html",
get_template_context(request, server=server_data, messages=[{"type": "danger", "text": "Plex token is required"}])
)
server_data["token"] = token
else:
if not api_key:
return templates.TemplateResponse(
"edit_media_server.html",
get_template_context(request, server=server_data, messages=[{"type": "danger", "text": "API key is required"}])
)
server_data["api_key"] = api_key
# Add rewrite rules if any
if rewrite_from and rewrite_to:
server_data["rewrite"] = [
{"from_path": f, "to_path": t}
for f, t in zip(rewrite_from, rewrite_to)
if f and t # Only add rules where both from and to are provided
]
# Find and update the server
for idx, server in enumerate(config.get("media_servers", [])):
if server.get("name") == name:
config["media_servers"][idx] = server_data
save_config(config)
break
return RedirectResponse(url="/", status_code=303)
@app.get("/settings")
async def settings_form(request: Request):
"""Render the settings form."""
config = get_config()
return templates.TemplateResponse(
"settings.html",
get_template_context(request, config=config, messages=[])
)
@app.post("/settings")
async def update_settings(
request: Request,
log_level: str = Form(...),
sync_delay: str = Form(...),
sync_interval: str = Form(...)
):
"""Update application settings."""
config = get_config()
# Update settings
config["log_level"] = log_level
config["sync_delay"] = sync_delay
config["sync_interval"] = sync_interval
# Validate time formats
try:
parse_time_string(sync_delay)
parse_time_string(sync_interval)
except Exception as e:
return templates.TemplateResponse(
"settings.html",
get_template_context(
request,
config=config,
messages=[{"type": "danger", "text": f"Invalid time format: {str(e)}"}]
),
status_code=400
)
# Save config
if save_config(config):
# Update logging level
logging.getLogger().setLevel(getattr(logging, log_level.upper()))
# Redirect to dashboard with success message
return RedirectResponse(
url="/",
status_code=303,
headers={"HX-Trigger": json.dumps({"showMessage": {"type": "success", "text": "Settings updated successfully"}})}
)
else:
# Show error
return templates.TemplateResponse(
"settings.html",
get_template_context(
request,
config=config,
messages=[{"type": "danger", "text": "Failed to save settings"}]
),
status_code=500
)
@app.get("/manual-scan")
async def manual_scan_form(request: Request):
"""Render the manual scan page."""
config = get_config()
return templates.TemplateResponse(
"manual_scan.html",
get_template_context(request, config=config, messages=[])
)
@app.post("/test-connection")
async def test_connection(
type: str = Form(...),
url: str = Form(...),
api_key: Optional[str] = Form(None),
token: Optional[str] = Form(None)
) -> Dict[str, Any]:
"""Test connection to a Sonarr/Radarr instance or media server."""
try:
# Log the connection attempt
logger.debug(f"Testing connection to {type} at {url}")
# Add http:// if not present
if not url.startswith(('http://', 'https://')):
url = f"http://{url}"
logger.debug(f"Added http:// protocol to URL: {url}")
if type.lower() in ["sonarr", "radarr"]:
# Test Sonarr/Radarr connection
test_url = f"{url}/api/v3/system/status"
headers = {"X-Api-Key": api_key}
logger.debug(f"Attempting to connect to {test_url}")
async with aiohttp.ClientSession() as session:
try:
async with session.get(test_url, headers=headers, timeout=10, ssl=False) as response:
if response.status == 200:
data = await response.json()
logger.info(f"Successfully connected to {type} instance")
return {
"status": "success",
"message": f"Successfully connected to {type}",
"version": data.get("version", "unknown")
}
else:
error_text = await response.text()
logger.error(f"Connection failed with status {response.status}: {error_text}")
return {
"status": "error",
"message": f"Failed to connect to {type}: {error_text}"
}
except aiohttp.ClientError as e:
logger.error(f"Connection error: {str(e)}")
return {
"status": "error",
"message": f"Connection error: {str(e)}"
}
elif type.lower() in ["plex", "jellyfin", "emby"]:
# Test media server connection
if type.lower() == "plex":
test_url = f"{url}/library/sections"
headers = {"X-Plex-Token": token}
elif type.lower() == "jellyfin":
test_url = f"{url}/System/Info/Public"
headers = {"Authorization": f'MediaBrowser Token="{api_key}"'}
elif type.lower() == "emby":
test_url = f"{url}/Library/SelectableMediaFolders"
headers = {"X-MediaBrowser-Token": api_key}
logger.debug(f"Attempting to connect to {test_url}")
async with aiohttp.ClientSession() as session:
try:
async with session.get(test_url, headers=headers, timeout=10, ssl=False) as response:
if response.status == 200:
logger.info(f"Successfully connected to {type}")
return {
"status": "success",
"message": f"Successfully connected to {type}"
}
else:
error_text = await response.text()
logger.error(f"Connection failed with status {response.status}: {error_text}")
return {
"status": "error",
"message": f"Failed to connect to {type}: {error_text}"
}
except aiohttp.ClientError as e:
logger.error(f"Connection error: {str(e)}")
return {
"status": "error",
"message": f"Connection error: {str(e)}"
}
else:
logger.error(f"Unsupported type: {type}")
return {
"status": "error",
"message": f"Unsupported type: {type}"
}
except Exception as e:
logger.error(f"Connection test failed: {str(e)}")
return {
"status": "error",
"message": f"Connection test failed: {str(e)}"
}
# ------------------------------------------------------------------------------
# API Routes
# ------------------------------------------------------------------------------
@app.post("/debug-webhook")
async def debug_webhook(payload: Dict[str, Any], request: Request) -> Dict[str, Any]:
"""
Debug endpoint that simply logs and returns the received webhook payload.
"""
logger.info("========================")
logger.info("Received webhook on debug endpoint")
logger.info("Headers:")
for name, value in request.headers.items():
logger.info(f"{name}: {value}")
logger.info("Payload:")
logger.info(json.dumps(payload, indent=2))
logger.info("========================")
return {
"status": "received",
"eventType": payload.get("eventType", "unknown"),
"payload": payload,
}
async def handle_sonarr_delete(payload: Dict[str, Any], instances: List[SonarrInstance], sync_interval: float, config: Dict[str, Any]):
"""Handle series or episode deletion by syncing across instances and scanning media servers"""
series_data = payload.get("series", {})
series_id = series_data.get("tvdbId")
title = series_data.get("title", "Unknown")
path = series_data.get("path")
event_type = payload.get("eventType")
results = {
"status": "ok",
"event": event_type,
"title": title,
"tvdbId": series_id,
"deletions": [],
"scanResults": []
}
# Log the delete event
logger.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
logger.info(f"Processing Sonarr {event_type}: Title=\033[1m{title}\033[0m, TVDB=\033[1m{series_id}\033[0m")
if path:
logger.info(f" ├─ Path: \033[1m{path}\033[0m")
# Sync deletion across instances
for i, instance in enumerate(instances):
try:
# Apply sync interval between instances (but not before the first one)
if i > 0 and sync_interval > 0:
logger.info(f" ├─ Waiting {sync_interval} seconds before processing next instance")
await asyncio.sleep(sync_interval)
if event_type == "SeriesDelete":
# Delete series from instance
response = await instance.delete_series(series_id)
logger.info(f" ├─ Deleted series from \033[1m{instance.name}\033[0m")
elif event_type == "EpisodeFileDelete":
# Delete episode file from instance
episode_id = payload.get("episodeFile", {}).get("id")
response = await instance.delete_episode(episode_id)
logger.info(f" ├─ Deleted episode file from \033[1m{instance.name}\033[0m")
results["deletions"].append({
"instance": instance.name,
"status": "success"
})
except Exception as e:
error_msg = str(e)
if "message" in error_msg:
try:
error_json = json.loads(error_msg)
error_msg = error_json.get("message", error_msg)
except:
pass
logger.error(f" ├─ Failed to delete from \033[1m{instance.name}\033[0m: \033[1m{error_msg}\033[0m")
results["deletions"].append({
"instance": instance.name,
"status": "error",
"error": error_msg
})
# Log deletion results
successful_deletes = len([d for d in results["deletions"] if d["status"] == "success"])
failed_deletes = len([d for d in results["deletions"] if d["status"] == "error"])
logger.info(f" ├─ Deletion results:")
if successful_deletes > 0:
logger.info(f" │ ├─ Deleted from \033[1m{successful_deletes}\033[0m instance(s)")
if failed_deletes > 0:
logger.info(f" │ └─ Failed on \033[1m{failed_deletes}\033[0m instance(s)")
# Scan media servers if path exists
if path:
# Apply sync interval before media server scanning
if sync_interval > 0 and results["deletions"]:
logger.info(f" ├─ Waiting {sync_interval} seconds before scanning media servers")
await asyncio.sleep(sync_interval)
scanner = MediaServerScanner(config.get("media_servers", []))
# Handle different event types
if event_type == "Download":
# For downloads, use the episode file path to get season folder
episode_file = payload.get("episodeFile", {})
file_path = episode_file.get("path", "")
if file_path:
scan_path = file_path
logger.debug(f" ├─ Using episode file path for scanning: \033[1m{scan_path}\033[0m")
else:
scan_path = path
logger.debug(f" ├─ Using series path for scanning: \033[1m{scan_path}\033[0m")
elif event_type == "EpisodeFileDelete":
# For episode deletions, use the episode file path to get season folder
episode_file = payload.get("episodeFile", {})
file_path = episode_file.get("path", "")
if file_path:
scan_path = file_path
logger.debug(f" ├─ Using episode file path for scanning: \033[1m{scan_path}\033[0m")
else:
scan_path = path
logger.debug(f" ├─ Using series path for scanning: \033[1m{scan_path}\033[0m")
elif event_type == "SeriesDelete":
# For series deletions, use the series path
scan_path = path
logger.debug(f" ├─ Using series path for scanning: \033[1m{scan_path}\033[0m")
else:
# For other events, use the series path
scan_path = path
logger.debug(f" ├─ Using series path for scanning: \033[1m{scan_path}\033[0m")
scan_results = []
if scan_path:
logger.info(f" ├─ Initiating scan for path: \033[1m{scan_path}\033[0m")
scan_results = await scanner.scan_path(scan_path, is_series=True)
result = {
"status": "ok",
"message": f"Successfully scanned {len(scan_results)} media server(s)",
"scanResults": scan_results,
"scannedPath": scan_path
}
else:
result = {"status": "ignored", "reason": f"No instances configured for {event_type}"}
results["scanResults"] = scan_results
# Log scan results
successful_scans = [s for s in scan_results if s.get("status") == "success"]
failed_scans = [s for s in scan_results if s.get("status") == "error"]
logger.info(f" └─ Scan results:")
if successful_scans:
for scan in successful_scans[:-1]:
logger.info(f" ├─ Scanned \033[1m{scan['server']}\033[0m ({scan['type']})")
if successful_scans:
logger.info(f" └─ Scanned \033[1m{successful_scans[-1]['server']}\033[0m ({successful_scans[-1]['type']})")
if failed_scans:
for scan in failed_scans[:-1]:
logger.info(f" ├─ Failed on \033[1m{scan['server']}\033[0m: {scan.get('message', 'Unknown error')}")
if failed_scans:
logger.info(f" └─ Failed on \033[1m{failed_scans[-1]['server']}\033[0m: {failed_scans[-1].get('message', 'Unknown error')}")
else:
logger.info(" └─ No path provided for media server scanning")
logger.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
return result
@app.post("/webhook")
async def webhook_handler(request: Request):
"""Handle incoming webhooks from Sonarr and Radarr."""
try:
# Get webhook ID for tracking
webhook_id = str(uuid.uuid4())
logger.info(f" ├─ Received webhook: \033[1m{webhook_id}\033[0m")
# Parse webhook payload
try:
payload = await request.json()
except Exception as e:
logger.error(f" ├─ Failed to parse webhook payload: {str(e)}")
raise HTTPException(status_code=400, detail="Invalid JSON payload")
# Validate webhook payload
if not payload:
logger.error(" ├─ Empty webhook payload")
raise HTTPException(status_code=400, detail="Empty webhook payload")
# Get event type
event_type = payload.get("eventType")
if not event_type:
logger.error(" ├─ Missing eventType in webhook payload")
raise HTTPException(status_code=400, detail="Missing eventType in webhook payload")
logger.info(f" ├─ Event type: \033[1m{event_type}\033[0m")
# Get sync timing settings
config = get_config()
sync_delay = parse_time_string(config.get("sync_delay", "0"))
sync_interval = parse_time_string(config.get("sync_interval", "0"))
# Check if this is a Sonarr import webhook that should be batched
if "series" in payload and event_type == "Import":
series_data = payload.get("series", {})
series_id = series_data.get("tvdbId")
episode_file = payload.get("episodeFile", {})
season_number = episode_file.get("seasonNumber")
if series_id and season_number:
# Add to batch
async with webhook_batch_lock:
webhook_batches[(series_id, season_number)].append(payload)
# Schedule batch processing with a delay
asyncio.create_task(asyncio.sleep(webhook_batch_timeout))
asyncio.create_task(process_batched_webhooks(series_id, season_number, webhook_id))
# Return immediately to acknowledge receipt
return {"status": "ok", "message": "Webhook received and queued for batch processing"}
# For non-batched webhooks, process immediately
result = await process_webhook(payload, event_type, webhook_id, sync_delay, sync_interval)
# Log webhook completion
logger.info(f" └─ Webhook processed: \033[1m{webhook_id}\033[0m")
return result
except HTTPException:
raise
except Exception as e:
logger.error(f" ├─ Webhook handler error: {str(e)}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
async def process_batched_webhooks(series_id: str, season_number: int, webhook_id: str):
"""Process a batch of webhooks for the same series and season."""
async with webhook_batch_lock:
batch = webhook_batches.get((series_id, season_number), [])
if not batch:
return
# Get the most recent webhook payload
latest_webhook = batch[-1]
event_type = latest_webhook.get("eventType")
# Get sync timing settings
config = get_config()