-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodels.py
More file actions
529 lines (437 loc) · 17.7 KB
/
models.py
File metadata and controls
529 lines (437 loc) · 17.7 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
from pydantic import BaseModel
from typing import List, Optional, Dict, Any, Union
from enum import Enum
import aiohttp
import xml.etree.ElementTree as ET
import logging
import json
from urllib.parse import quote
logger = logging.getLogger(__name__)
# Webhook Models (What we receive)
class Language(BaseModel):
id: int
name: str
class MediaImage(BaseModel):
coverType: str
url: str
remoteUrl: str
# Base model for common webhook fields
class WebhookBase(BaseModel):
eventType: str
applicationUrl: Optional[str] = ""
instanceName: str
class SonarrWebhookSeries(BaseModel):
id: int
title: str
path: str
tvdbId: int
type: str
year: int
titleSlug: Optional[str] = None
tvMazeId: Optional[int] = None
tmdbId: Optional[int] = None
imdbId: Optional[str] = None
genres: Optional[List[str]] = []
images: Optional[List[MediaImage]] = []
tags: List[Any] = []
originalLanguage: Optional[Language] = None
class SonarrWebhookEpisode(BaseModel):
id: int
episodeNumber: int
seasonNumber: int
title: str
overview: Optional[str] = None
airDate: Optional[str] = None
airDateUtc: Optional[str] = None
seriesId: int
tvdbId: int
class SonarrCustomFormat(BaseModel):
id: int
name: str
class SonarrReleaseInfo(BaseModel):
quality: str = None
qualityVersion: int = None
releaseTitle: str = None
indexer: str = None
size: int = None
customFormatScore: int = None
customFormats: List[str] = None
languages: List[Language] = None
class SonarrCustomFormatInfo(BaseModel):
customFormats: List[SonarrCustomFormat]
customFormatScore: int
class WebhookPayload(BaseModel):
series: SonarrWebhookSeries
episodes: List[SonarrWebhookEpisode]
eventType: str
instanceName: str
applicationUrl: str
release: Optional[SonarrReleaseInfo] = None
downloadClient: Optional[str] = None
downloadClientType: Optional[str] = None
customFormatInfo: Optional[SonarrCustomFormatInfo] = None
# Sonarr-specific webhook (reusing our existing WebhookPayload)
class SonarrWebhook(WebhookBase):
series: SonarrWebhookSeries
episodes: Optional[List[SonarrWebhookEpisode]] = None
release: Optional[SonarrReleaseInfo] = None
downloadClient: Optional[str] = None
downloadClientType: Optional[str] = None
customFormatInfo: Optional[SonarrCustomFormatInfo] = None
# Radarr-specific webhook (you'll need to define these models)
class RadarrWebhook(WebhookBase):
movie: Dict[str, Any] # Replace with proper movie model when needed
class MediaWebhook(BaseModel):
webhook: Union[SonarrWebhook, RadarrWebhook]
# Sonarr API Models (What we send)
class SonarrMonitorTypes(str, Enum):
unknown = "unknown"
all = "all"
future = "future"
missing = "missing"
existing = "existing"
firstSeason = "firstSeason"
lastSeason = "lastSeason"
latestSeason = "latestSeason"
pilot = "pilot"
recent = "recent"
monitorSpecials = "monitorSpecials"
unmonitorSpecials = "unmonitorSpecials"
none = "none"
skip = "skip"
class SonarrAddSeriesOptions(BaseModel):
ignoreEpisodesWithFiles: bool = False
ignoreEpisodesWithoutFiles: bool = False
monitor: SonarrMonitorTypes = SonarrMonitorTypes.all
searchForMissingEpisodes: bool = False
searchForCutoffUnmetEpisodes: bool = False
class Season(BaseModel):
seasonNumber: int
monitored: bool
class SonarrEpisode(BaseModel):
"""Model for Sonarr Episode Resource"""
id: int
seriesId: int
tvdbId: Optional[int] = None
episodeFileId: int
seasonNumber: int
episodeNumber: int
title: Optional[str] = None
airDate: Optional[str] = None
airDateUtc: Optional[str] = None
lastSearchTime: Optional[str] = None
runtime: Optional[int] = None
finaleType: Optional[str] = None
overview: Optional[str] = None
episodeFile: Optional[Dict[str, Any]] = None
hasFile: bool
monitored: bool
absoluteEpisodeNumber: Optional[int] = None
sceneAbsoluteEpisodeNumber: Optional[int] = None
sceneEpisodeNumber: Optional[int] = None
sceneSeasonNumber: Optional[int] = None
unverifiedSceneNumbering: bool = None
endTime: Optional[str] = None
grabDate: Optional[str] = None
series: Optional[Dict[str, Any]] = None
images: List[Dict[str, Any]] = []
class Config:
extra = "ignore" # Allow extra fields in the data
class SonarrSeries(BaseModel):
"""Model for series creation/updates in Sonarr"""
tvdbId: int
title: str
qualityProfileId: int
seasonFolder: bool
rootFolderPath: str
monitored: bool = True
seasons: List[Season]
addOptions: Optional[SonarrAddSeriesOptions] = None
seriesType: str = "standard"
class PathRewrite(BaseModel):
"""Model for path rewriting configuration"""
from_path: str
to_path: str
class Config:
json_schema_extra = {
"example": {
"from_path": "/mnt/plex",
"to_path": "/mnt/remote/plex"
}
}
class MediaServerBase(BaseModel):
"""Base model for media server configurations"""
name: str
type: str
url: str
enabled: bool = True
rewrite: Optional[List[PathRewrite]] = []
@property
def base_url(self) -> str:
"""Return the base URL with protocol"""
if not self.url.startswith(('http://', 'https://')):
url = f"http://{self.url}"
logger.debug(f"Added http:// protocol to URL: {url}")
return url
return self.url
async def _make_request(self, method: str, endpoint: str, **kwargs) -> Any:
"""Make an HTTP request with proper URL handling"""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
async with aiohttp.ClientSession() as session:
async with session.request(method, url, headers=self.headers, **kwargs) as response:
if response.status not in [200, 201, 204]:
error_text = await response.text()
raise Exception(f"Request failed with status {response.status}: {error_text}")
if response.status == 204:
return {"status": "success"}
try:
return await response.json()
except:
return await response.text()
class PlexServer(MediaServerBase):
token: str
type: str = "plex"
def get(self, key: str, default: Any = None) -> Any:
"""Get a value from the server configuration"""
return getattr(self, key, default)
@property
def headers(self) -> Dict[str, str]:
"""Return headers for API requests"""
return {
"X-Plex-Token": self.token,
"Accept": "application/xml" # Force XML response
}
async def scan_path(self, path: str) -> Dict[str, Any]:
"""Scan a specific path in Plex"""
# First get library sections
sections_text = await self._make_request("GET", "library/sections")
root = ET.fromstring(sections_text)
# Find matching section for the path
section_id = None
for directory in root.findall(".//Directory"):
for location in directory.findall(".//Location"):
if path.startswith(location.get("path", "")):
section_id = directory.get("key")
break
if section_id:
break
if not section_id:
raise ValueError(f"No matching library section found for path: {path}")
# URL encode the path
encoded_path = quote(path)
# Trigger scan for the section with the specific path
await self._make_request("POST", f"library/sections/{section_id}/refresh?path={encoded_path}")
return {"status": "success", "message": "Scan initiated"}
class JellyfinServer(MediaServerBase):
api_key: str
type: str = "jellyfin"
def get(self, key: str, default: Any = None) -> Any:
"""Get a value from the server configuration"""
return getattr(self, key, default)
@property
def headers(self) -> Dict[str, str]:
"""Return headers for API requests"""
return {"X-MediaBrowser-Token": self.api_key}
async def scan_path(self, path: str) -> Dict[str, Any]:
"""Scan a specific path in Jellyfin"""
# URL encode the path
encoded_path = quote(path)
await self._make_request("POST", f"Library/Refresh?path={encoded_path}")
return {"status": "success", "message": "Scan initiated"}
class EmbyServer(MediaServerBase):
api_key: str
type: str = "emby"
def get(self, key: str, default: Any = None) -> Any:
"""Get a value from the server configuration"""
return getattr(self, key, default)
@property
def headers(self) -> Dict[str, str]:
"""Return headers for API requests"""
return {"X-Emby-Token": self.api_key}
async def scan_path(self, path: str) -> Dict[str, Any]:
"""Scan a specific path in Emby"""
# URL encode the path
encoded_path = quote(path)
await self._make_request("POST", f"Library/Refresh?path={encoded_path}")
return {"status": "success", "message": "Scan initiated"}
MediaServer = Union[PlexServer, JellyfinServer, EmbyServer]
class SonarrInstance(BaseModel):
"""Configuration model for Sonarr instances"""
name: str
type: str = "sonarr"
url: str
api_key: str
root_folder_path: str
quality_profile_id: int
language_profile_id: int = 1
season_folder: bool = True
search_on_sync: bool = False
enabled_events: List[str] = []
rewrite: Optional[List[Dict[str, str]]] = None
@property
def is_sonarr(self) -> bool:
return self.type.lower() == "sonarr"
@property
def base_url(self) -> str:
"""Return the base URL with protocol"""
if not self.url.startswith(('http://', 'https://')):
return f"http://{self.url}"
return self.url
@property
def headers(self) -> Dict[str, str]:
"""Return headers for API requests"""
return {"X-Api-Key": self.api_key}
async def get_series_by_tvdb_id(self, tvdb_id: int) -> Optional[Dict[str, Any]]:
"""Get a series by TVDB ID"""
url = f"{self.base_url}/api/v3/series?tvdbId={tvdb_id}"
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.headers) as response:
if response.status != 200:
raise Exception(f"Failed to get series: {await response.text()}")
series = await response.json()
return series[0] if series else None
async def delete_series(self, tvdb_id: int) -> Dict[str, Any]:
"""Delete a series by TVDB ID"""
# First get the series ID from TVDB ID
series = await self.get_series_by_tvdb_id(tvdb_id)
if not series:
raise ValueError(f"Series with TVDB ID {tvdb_id} not found")
url = f"{self.base_url}/api/v3/series/{series['id']}"
async with aiohttp.ClientSession() as session:
async with session.delete(url, headers=self.headers) as response:
if response.status != 200:
raise Exception(f"Failed to delete series: {await response.text()}")
# Sonarr's DELETE endpoint doesn't return JSON
return {"status": "success", "message": "Series deleted successfully"}
async def delete_episode(self, episode_id: int) -> Dict[str, Any]:
"""Delete an episode file"""
url = f"{self.base_url}/api/v3/episodeFile/{episode_id}"
async with aiohttp.ClientSession() as session:
async with session.delete(url, headers=self.headers) as response:
if response.status != 200:
raise Exception(f"Failed to delete episode: {await response.text()}")
return await response.json()
async def refresh_series(self, series_id: int) -> Dict[str, Any]:
"""Refresh series metadata and scan files"""
url = f"{self.base_url}/api/v3/command"
data = {
"name": "RefreshSeries",
"seriesId": series_id
}
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=self.headers, json=data) as response:
if response.status != 201:
raise Exception(f"Failed to refresh series: {await response.text()}")
return await response.json()
async def import_series(self, tvdb_id: int, path: str) -> Dict[str, Any]:
"""Import a series by refreshing and rescanning"""
# First get the series ID from TVDB ID
series = await self.get_series_by_tvdb_id(tvdb_id)
if not series:
raise ValueError(f"Series with TVDB ID {tvdb_id} not found")
series_id = series["id"]
# First refresh the series
await self.refresh_series(series_id)
# Then trigger a rescan
url = f"{self.base_url}/api/v3/command"
data = {
"name": "RescanSeries",
"seriesId": series_id
}
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=self.headers, json=data) as response:
if response.status != 201:
raise Exception(f"Failed to rescan series: {await response.text()}")
return await response.json()
class RadarrInstance(BaseModel):
"""Configuration model for Radarr instances"""
name: str
type: str = "radarr"
url: str
api_key: str
root_folder_path: str
quality_profile_id: int
search_on_sync: bool = False
enabled_events: List[str] = []
rewrite: Optional[List[Dict[str, str]]] = None
@property
def is_radarr(self) -> bool:
return self.type.lower() == "radarr"
@property
def base_url(self) -> str:
"""Return the base URL with protocol"""
if not self.url.startswith(('http://', 'https://')):
return f"http://{self.url}"
return self.url
@property
def headers(self) -> Dict[str, str]:
"""Return headers for API requests"""
return {"X-Api-Key": self.api_key}
async def get_movie_by_tmdb_id(self, tmdb_id: int) -> Dict[str, Any]:
"""Get a movie by TMDB ID"""
url = f"{self.base_url}/api/v3/movie?tmdbId={tmdb_id}"
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.headers) as response:
if response.status != 200:
raise Exception(f"Failed to get movie: {await response.text()}")
movies = await response.json()
return movies[0] if movies else None
async def delete_movie(self, tmdb_id: int) -> Dict[str, Any]:
"""Delete a movie by TMDB ID"""
# First get the movie ID from TMDB ID
movie = await self.get_movie_by_tmdb_id(tmdb_id)
if not movie:
raise ValueError(f"Movie with TMDB ID {tmdb_id} not found")
url = f"{self.base_url}/api/v3/movie/{movie['id']}"
async with aiohttp.ClientSession() as session:
async with session.delete(url, headers=self.headers) as response:
if response.status != 200:
raise Exception(f"Failed to delete movie: {await response.text()}")
# Radarr's delete endpoint doesn't return any JSON response
return {"status": "success"}
async def delete_movie_file(self, movie_file_id: int) -> Dict[str, Any]:
"""Delete a movie file"""
url = f"{self.base_url}/api/v3/movieFile/{movie_file_id}"
async with aiohttp.ClientSession() as session:
async with session.delete(url, headers=self.headers) as response:
if response.status != 200:
error_text = await response.text()
try:
error_json = json.loads(error_text)
error_message = error_json.get("message", error_text)
except:
error_message = error_text
raise Exception(f"Failed to delete movie file: {error_message}")
return await response.json()
async def refresh_movie(self, movie_id: int) -> Dict[str, Any]:
"""Refresh movie metadata and scan files"""
url = f"{self.base_url}/api/v3/command"
data = {
"name": "RefreshMovie",
"movieId": movie_id
}
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=self.headers, json=data) as response:
if response.status != 201:
raise Exception(f"Failed to refresh movie: {await response.text()}")
return await response.json()
async def import_movie(self, tmdb_id: int, path: str) -> Dict[str, Any]:
"""Import a movie by refreshing and rescanning"""
# First get the movie ID from TMDB ID
movie = await self.get_movie_by_tmdb_id(tmdb_id)
if not movie:
raise ValueError(f"Movie with TMDB ID {tmdb_id} not found")
movie_id = movie["id"]
# First refresh the movie
await self.refresh_movie(movie_id)
# Then trigger a rescan
url = f"{self.base_url}/api/v3/command"
data = {
"name": "RescanMovie",
"movieId": movie_id
}
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=self.headers, json=data) as response:
if response.status != 201:
raise Exception(f"Failed to rescan movie: {await response.text()}")
return await response.json()