-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsonarr_service.py
452 lines (385 loc) · 18.8 KB
/
sonarr_service.py
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
import logging
import time
import asyncio
from utils import http_get, http_post, http_put, get_config, parse_time_string
from typing import Dict, Any, List
from models import (
SonarrSeries,
SonarrEpisode,
SonarrAddSeriesOptions,
WebhookPayload,
SonarrMonitorTypes,
SonarrInstance,
)
from media_server_service import MediaServerScanner
from pathlib import Path
logger = logging.getLogger(__name__)
# ------------------------------------------------------------------------------
# Sonarr-Specific Functions
# ------------------------------------------------------------------------------
def get_series_by_tvdbid(base_url, api_key, tvdb_id) -> List[Dict[str, Any]]:
"""
GET /api/v3/series?tvdbId=<tvdb_id>
Returns an array of series (possibly empty).
"""
url = f"{base_url}/api/v3/series?tvdbId={tvdb_id}"
return http_get(url, api_key)
def add_series(base_url: str, api_key: str, series: SonarrSeries) -> Dict[str, Any]:
"""Add a new series to Sonarr using validated model."""
# Convert model to dict for API call
payload = series.model_dump(exclude_none=True)
url = f"{base_url}/api/v3/series"
return http_post(url, api_key, payload)
def update_episodes(
base_url: str, api_key: str, episodes: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""Update episodes in Sonarr using individual PUT requests."""
if not episodes:
return []
updated_episodes = []
for episode in episodes:
try:
# First get the current episode data
url = f"{base_url}/api/v3/episode/{episode['id']}"
current_episode = http_get(url, api_key)
# Update only the monitored status while preserving other fields
current_episode["monitored"] = True
# PUT to the individual episode endpoint
updated = http_put(url, api_key, current_episode)
updated_episodes.append(updated)
logger.info(f"Successfully updated episode {episode['id']}")
except Exception as e:
logger.error(f"Failed to update episode {episode['id']}: {str(e)}")
continue
return updated_episodes
def search_episodes(
base_url: str, api_key: str, episode_ids: List[int]
) -> Dict[str, Any]:
"""
Trigger a search for specific episodes in Sonarr.
"""
url = f"{base_url}/api/v3/command"
payload = {"name": "EpisodeSearch", "episodeIds": episode_ids}
try:
response = http_post(url, api_key, payload)
logger.info(f"Triggered search for episodeIds={episode_ids} in Sonarr.")
return response
except Exception as e:
logger.error(f"Failed to trigger search for episodes: {str(e)}")
raise
def search_series(base_url: str, api_key: str, series_id: int) -> Dict[str, Any]:
"""
Trigger a search for a specific series in Sonarr.
"""
url = f"{base_url}/api/v3/command"
payload = {"name": "SeriesSearch", "seriesId": series_id}
try:
response = http_post(url, api_key, payload)
logger.info(f"Triggered search for seriesId={series_id} in Sonarr.")
return response
except Exception as e:
logger.error(f"Failed to trigger search for seriesId={series_id}: {str(e)}")
raise
def refresh_series(base_url: str, api_key: str, series_id: int) -> Dict[str, Any]:
"""
Trigger a refresh for a specific series in Sonarr.
"""
url = f"{base_url}/api/v3/command"
payload = {"name": "RefreshSeries", "seriesId": series_id}
try:
response = http_post(url, api_key, payload)
logger.info(f"Triggered refresh for seriesId={series_id} in Sonarr.")
return response
except Exception as e:
logger.error(f"Failed to trigger refresh for seriesId={series_id}: {str(e)}")
raise
def rescan_series(base_url: str, api_key: str, series_id: int) -> Dict[str, Any]:
"""
Trigger a rescan for a specific series in Sonarr.
"""
url = f"{base_url}/api/v3/command"
payload = {"name": "RescanSeries", "seriesId": series_id}
try:
response = http_post(url, api_key, payload)
logger.info(f"Triggered rescan for seriesId={series_id} in Sonarr.")
return response
except Exception as e:
logger.error(f"Failed to trigger rescan for seriesId={series_id}: {str(e)}")
raise
async def handle_sonarr_grab(
payload: Dict[str, Any], instances: List[SonarrInstance]
) -> Dict[str, Any]:
"""Handle Sonarr grab webhook with validated data."""
try:
# Validate incoming webhook payload
webhook_data = WebhookPayload(**payload)
if webhook_data.eventType != "Grab":
logger.info(f"Ignoring non-Grab event: {webhook_data.eventType}")
return {"status": "ignored", "reason": f"Event is {webhook_data.eventType}"}
target_season = (
webhook_data.episodes[0].seasonNumber if webhook_data.episodes else None
)
episode_numbers = ", ".join(
str(ep.episodeNumber) for ep in webhook_data.episodes
)
logger.info(
"Processing Sonarr Grab: Title=%s, TVDB=%s, Season=%s, Episodes=[%s]",
webhook_data.series.title,
webhook_data.series.tvdbId,
target_season,
episode_numbers,
)
if not instances:
logger.warning("No Sonarr instances provided")
return {"status": "error", "reason": "No Sonarr instances configured"}
logger.info(f"Processing {len(instances)} Sonarr instances")
results = []
for inst in instances:
try:
logger.info(f"Processing Sonarr instance: {inst.name}")
# Check if series exists
existing = get_series_by_tvdbid(
inst.url, inst.api_key, webhook_data.series.tvdbId
)
if not existing:
logger.info(f"Series not found in {inst.name}, adding new series")
# Create series model for addition
series = SonarrSeries(
tvdbId=webhook_data.series.tvdbId,
title=webhook_data.series.title,
qualityProfileId=inst.quality_profile_id,
seasonFolder=inst.season_folder,
rootFolderPath=inst.root_folder_path,
monitored=True,
# seasons=[Season(seasonNumber=target_season, monitored=True)],
seasons=[],
addOptions=SonarrAddSeriesOptions(
ignoreEpisodesWithFiles=True,
monitor=SonarrMonitorTypes.future,
searchForMissingEpisodes=True,
searchForCutoffUnmetEpisodes=True,
),
)
# Add the series
added = add_series(inst.url, inst.api_key, series)
series_id = added["id"]
logger.info(f"Added new series (id={series_id}) to {inst.name}")
logger.info(
"Pausing for 2 seconds after adding series so episodes can be added"
)
time.sleep(2)
else:
series_id = existing[0]["id"]
logger.info(
f"Found existing series (id={series_id}) on {inst.name}"
)
# Handle episode monitoring
if webhook_data.episodes and target_season is not None:
url = f"{inst.url}/api/v3/episode?seriesId={series_id}&seasonNumber={target_season}"
season_eps = http_get(url, inst.api_key)
logger.info(
f"Retrieved {len(season_eps)} episodes for season {target_season}"
)
to_update = []
for grabbed_ep in webhook_data.episodes:
matching_eps = [
ep
for ep in season_eps
if ep["episodeNumber"] == grabbed_ep.episodeNumber
]
if matching_eps:
target_ep = matching_eps[0]
if not target_ep.get("monitored", False):
episode = SonarrEpisode(
id=target_ep["id"],
seriesId=series_id,
seasonNumber=grabbed_ep.seasonNumber,
episodeNumber=grabbed_ep.episodeNumber,
title=grabbed_ep.title,
monitored=True,
hasFile=target_ep.get("hasFile", False),
episodeFileId=target_ep.get("episodeFileId", 0),
)
to_update.append(episode)
logger.info(
f"Will monitor episode {grabbed_ep.episodeNumber}"
)
if to_update:
episodes_to_update = [
ep.model_dump(exclude_none=True) for ep in to_update
]
updated = update_episodes(
inst.url, inst.api_key, episodes_to_update
)
logger.info(f"Updated {len(updated)} episodes in {inst.name}")
# Search episodes
# time.sleep(0.5)
episode_ids = [ep["id"] for ep in updated]
search_episodes(inst.url, inst.api_key, episode_ids)
logger.info(f"Triggered search for episodes in {inst.name}")
results.append(
{
"instance": inst.name,
"episodesMonitored": len(updated),
"season": target_season,
}
)
else:
logger.info(f"No episodes need updating in {inst.name}")
results.append(
{
"instance": inst.name,
"episodesMonitored": 0,
"season": target_season,
}
)
except Exception as e:
logger.error(f"Error processing instance {inst.name}: {str(e)}")
results.append(
{"instance": inst.name, "error": str(e), "season": target_season}
)
response = {
"status": "ok",
"sonarrTitle": webhook_data.series.title,
"tvdbId": webhook_data.series.tvdbId,
"targetSeason": target_season,
"results": results,
}
logger.info(f"Completed processing with response: {response}")
return response
except Exception as e:
logger.error(f"Error processing webhook: {str(e)}")
return {"status": "error", "error": str(e)}
async def handle_sonarr_import(payload: Dict[str, Any], instances: List[SonarrInstance]) -> Dict[str, Any]:
"""Handle Sonarr import webhook with validated instances."""
try:
# Log the full payload for debugging
logger.debug(f"Received Sonarr webhook payload: {payload}")
# Check event type
event_type = payload.get("eventType", "")
# Accept both "Import" and "Download" events
if event_type not in ["Import", "Download"]:
logger.info(f"Ignoring non-Import event: {event_type}")
return {"status": "ignored", "reason": f"Sonarr event is {event_type}"}
webhook_data = WebhookPayload(**payload)
logger.info(
"Processing Sonarr Import: Title=%s, TVDB=%s, Episodes=%s",
webhook_data.series.title,
webhook_data.series.tvdbId,
[f"S{ep.seasonNumber}E{ep.episodeNumber}" for ep in webhook_data.episodes]
)
# Get all possible paths from the payload
series_path = webhook_data.series.path
episode_path = payload.get("episodeFile", {}).get("path")
logger.info(f"Series path: {series_path}")
logger.info(f"Episode file path: {episode_path}")
if not instances:
logger.warning("No Sonarr instances provided")
return {"status": "error", "reason": "No Sonarr instances configured"}
logger.info(f"Found {len(instances)} Sonarr instance(s) to process")
for inst in instances:
logger.info(f"Instance {inst.name}: URL={inst.url}, enabled_events={inst.enabled_events}")
# Get sync interval from config
config = get_config()
sync_interval = parse_time_string(config.get("sync_interval", "0"))
logger.info(f"Using sync interval of {sync_interval} seconds between operations")
results = []
for i, inst 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)
logger.info(f"Processing Sonarr instance: {inst.name}")
# Check if series exists
logger.debug(f"Checking if series exists in {inst.name} (TVDB ID: {webhook_data.series.tvdbId})")
existing = get_series_by_tvdbid(inst.url, inst.api_key, webhook_data.series.tvdbId)
logger.debug(f"Existing series check result: {existing}")
if not existing:
logger.info(f"Series not found in {inst.name}, adding new series")
# Create series model for addition
logger.debug(f"Adding series to {inst.name} with path={inst.root_folder_path}, quality_profile={inst.quality_profile_id}")
series = SonarrSeries(
tvdbId=webhook_data.series.tvdbId,
title=webhook_data.series.title,
qualityProfileId=inst.quality_profile_id,
seasonFolder=inst.season_folder,
rootFolderPath=inst.root_folder_path,
monitored=True,
seasons=[],
addOptions=SonarrAddSeriesOptions(
ignoreEpisodesWithFiles=True,
monitor=SonarrMonitorTypes.future,
searchForMissingEpisodes=True,
searchForCutoffUnmetEpisodes=True,
),
)
added = add_series(inst.url, inst.api_key, series)
series_id = added["id"]
logger.info(f"Added new series (id={series_id}) to {inst.name}")
results.append({
"instance": inst.name,
"action": "added_series",
"seriesId": series_id
})
else:
series_id = existing[0]["id"]
logger.info(f"Series already exists (id={series_id}) on {inst.name}")
# Refresh and rescan the series
logger.info(f"Refreshing series (id={series_id}) on {inst.name}")
refresh_result = refresh_series(inst.url, inst.api_key, series_id)
logger.debug(f"Refresh result: {refresh_result}")
# Apply sync interval between operations
if sync_interval > 0:
logger.info(f"Waiting {sync_interval} seconds before rescanning")
await asyncio.sleep(sync_interval)
logger.info(f"Rescanning series (id={series_id}) on {inst.name}")
rescan_result = rescan_series(inst.url, inst.api_key, series_id)
logger.debug(f"Rescan result: {rescan_result}")
results.append({
"instance": inst.name,
"action": "series_refreshed_and_rescanned",
"seriesId": series_id
})
except Exception as e:
logger.error(f"Error processing instance {inst.name}: {str(e)}", exc_info=True)
results.append({"instance": inst.name, "error": str(e)})
# Initialize scanner with media servers from config
media_servers = config.get("media_servers", [])
logger.info(f"Found {len(media_servers)} media server(s) to scan")
for server in media_servers:
logger.info(f"Media server config: name={server.get('name')}, type={server.get('type')}, enabled={server.get('enabled')}")
# Apply sync interval before media server scanning
if sync_interval > 0 and results:
logger.info(f"Waiting {sync_interval} seconds before scanning media servers")
await asyncio.sleep(sync_interval)
scanner = MediaServerScanner(media_servers)
# Try to scan using the most specific path available
scan_path = None
if series_path: # Use series path for better Plex library scanning
scan_path = series_path
logger.info(f"Using series path for scanning: {scan_path}")
elif episode_path: # Fallback to episode path if series path not available
# For TV shows, scan the season folder (one up from episode)
scan_path = str(Path(episode_path).parent)
logger.info(f"Using episode parent path for scanning: {scan_path}")
scan_results = []
if scan_path:
logger.info(f"Initiating scan for path: {scan_path}")
scan_results = await scanner.scan_path(scan_path, is_series=True)
logger.info(f"Scan results: {scan_results}")
else:
logger.warning("No valid path available to scan")
response = {
"status": "ok",
"sonarrTitle": webhook_data.series.title,
"tvdbId": webhook_data.series.tvdbId,
"results": results,
"scanResults": scan_results,
"scannedPath": scan_path
}
logger.info(f"Completed processing with response: {response}")
return response
except Exception as e:
logger.error(f"Error processing webhook: {str(e)}", exc_info=True)
return {"status": "error", "error": str(e)}