-
Notifications
You must be signed in to change notification settings - Fork 0
/
imdb_trakt_sync.py
761 lines (630 loc) · 22.1 KB
/
imdb_trakt_sync.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
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
import csv
import logging
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from datetime import date, datetime, time
from pathlib import Path
from time import sleep
from typing import Any, Literal, TypedDict, cast
import click
import requests
logger = logging.getLogger("imdb-trakt-sync")
_NOW: datetime = datetime.now()
_END_OF_DAY_TIME: time = time(hour=23, minute=59, second=59)
_IMDB_MOVIE_TYPES: set[str] = {"Movie", "Short", "TV Movie", "TV Special", "Video"}
_IMDB_SHOW_TYPES: set[str] = {"TV Series", "TV Mini Series"}
_IMDB_TYPES: set[str] = _IMDB_MOVIE_TYPES | _IMDB_SHOW_TYPES
@click.group()
@click.option(
"--trakt-client-id",
required=True,
envvar="TRAKT_CLIENT_ID",
)
@click.option(
"--trakt-access-token",
required=True,
envvar="TRAKT_ACCESS_TOKEN",
)
@click.option(
"--verbose",
"-v",
is_flag=True,
help="Enable verbose logging",
envvar="ACTIONS_RUNNER_DEBUG",
)
@click.pass_context
def main(
ctx: click.Context,
trakt_client_id: str,
trakt_access_token: str,
verbose: bool,
) -> None:
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
ctx.obj = trakt_session(trakt_client_id, trakt_access_token)
@main.command()
@click.option(
"--imdb-watchlist-url",
required=True,
envvar="IMDB_WATCHLIST_URL",
)
@click.pass_obj
def sync_watchlist(session: requests.Session, imdb_watchlist_url: str) -> None:
items = fetch_imdb_watchlist(imdb_watchlist_url)
existing_media_items = list(trakt_watchlist(session))
existing_movie_imdb_ids: set[str] = _compact_set(
_trakt_mediaitem_imdb_id(item)
for item in existing_media_items
if item["type"] == "movie"
)
existing_show_imdb_ids: set[str] = _compact_set(
_trakt_mediaitem_imdb_id(item)
for item in existing_media_items
if item["type"] == "show"
)
imdb_movie_ids: set[str] = {
item.imdb_id for item in items if item.trakt_type == "movie"
}
imdb_show_ids: set[str] = {
item.imdb_id for item in items if item.trakt_type == "show"
}
add_movies: list[TraktAnyItem] = [
{"ids": {"imdb": imdb}} for imdb in imdb_movie_ids - existing_movie_imdb_ids
]
add_shows: list[TraktAnyItem] = [
{"ids": {"imdb": imdb}} for imdb in imdb_show_ids - existing_show_imdb_ids
]
remove_movies: list[TraktAnyItem] = [
{"ids": {"imdb": imdb}} for imdb in existing_movie_imdb_ids - imdb_movie_ids
]
remove_shows: list[TraktAnyItem] = [
{"ids": {"imdb": imdb}} for imdb in existing_show_imdb_ids - imdb_show_ids
]
if watching_item := trakt_watching(session):
logger.debug("Filtering out currently watching...")
add_movies = list(_block_watching_items(add_movies, watching_item))
add_shows = list(_block_watching_items(add_shows, watching_item))
remove_movies = list(_block_watching_items(remove_movies, watching_item))
remove_shows = list(_block_watching_items(remove_shows, watching_item))
trakt_update_watchlist(session, movies=add_movies, shows=add_shows)
trakt_remove_from_watchlist(session, movies=remove_movies, shows=remove_shows)
@main.command()
@click.option(
"--imdb-ratings-url",
required=True,
envvar="IMDB_RATINGS_URL",
)
@click.pass_obj
def sync_ratings(session: requests.Session, imdb_ratings_url: str) -> None:
imdb_ratings = fetch_imdb_ratings(imdb_ratings_url)
trakt_rated_at: dict[str, datetime] = {}
trakt_rated: dict[str, int] = {}
imdb_rated: dict[str, int] = {}
add_movies: list[TraktRatedItem] = []
add_shows: list[TraktRatedItem] = []
for item in trakt_ratings(session, media_type="all"):
if imdb_id := _trakt_mediaitem_imdb_id(item):
trakt_rated_at[imdb_id] = _fromisoformat(item["rated_at"])
trakt_rated[imdb_id] = item["rating"]
for imdb_rating in imdb_ratings:
imdb_rated[imdb_rating.imdb_id] = imdb_rating.rating
title_rated_at = datetime.combine(imdb_rating.rated_on, _END_OF_DAY_TIME)
title_rated_at = min(title_rated_at, _NOW)
should_rate: bool = False
if imdb_rating.imdb_id in trakt_rated:
if imdb_rating.rating != trakt_rated[imdb_rating.imdb_id]:
logger.info(
"Update rating https://www.imdb.com/title/%s/ %d -> %d @ %s",
imdb_rating.imdb_id,
trakt_rated[imdb_rating.imdb_id],
imdb_rating.rating,
title_rated_at,
)
should_rate = True
else:
logger.info(
"Add rating https://www.imdb.com/title/%s/ %d @ %s",
imdb_rating.imdb_id,
imdb_rating.rating,
title_rated_at,
)
should_rate = True
if should_rate:
rated_item: TraktRatedItem = {
"rated_at": title_rated_at.isoformat(),
"rating": imdb_rating.rating,
"ids": {"imdb": imdb_rating.imdb_id},
}
if imdb_rating.trakt_type == "movie":
add_movies.append(rated_item)
elif imdb_rating.trakt_type == "show":
add_shows.append(rated_item)
not_rated_on_imdb = set(trakt_rated.keys()) - set(imdb_rated.keys())
for imdb_id in not_rated_on_imdb:
logger.info(
"https://www.imdb.com/title/%s/ rated %d @ %s on Trakt, but not IMDb",
imdb_id,
trakt_rated[imdb_id],
trakt_rated_at[imdb_id],
)
trakt_add_ratings(session=session, movies=add_movies, shows=add_shows)
@main.command()
@click.option(
"--imdb-ratings-url",
required=True,
envvar="IMDB_RATINGS_URL",
)
@click.pass_obj
def sync_history(session: requests.Session, imdb_ratings_url: str) -> None:
existing_movie_imdb_ids: set[str] = set()
existing_episodes_imdb_ids: set[str] = set()
imdb_id_rated_at: dict[str, date] = {}
imdb_movie_ids: set[str] = set()
imdb_episode_ids: set[str] = set()
for imdb_item in fetch_imdb_ratings(imdb_ratings_url):
imdb_id_rated_at[imdb_item.imdb_id] = imdb_item.rated_on
if imdb_item.trakt_type == "movie":
imdb_movie_ids.add(imdb_item.imdb_id)
elif imdb_item.trakt_type == "episode":
imdb_episode_ids.add(imdb_item.imdb_id)
for trakt_item in trakt_history(session):
if trakt_item["type"] == "movie":
existing_movie_imdb_ids.add(trakt_item["movie"]["ids"]["imdb"])
elif trakt_item["type"] == "episode":
existing_episodes_imdb_ids.add(trakt_item["episode"]["ids"]["imdb"])
add_movies: list[TraktWatchedItem] = [
{"watched_at": imdb_id_rated_at[imdb].isoformat(), "ids": {"imdb": imdb}}
for imdb in imdb_movie_ids - existing_movie_imdb_ids
]
add_episodes: list[TraktWatchedItem] = [
{"watched_at": imdb_id_rated_at[imdb].isoformat(), "ids": {"imdb": imdb}}
for imdb in imdb_episode_ids - existing_episodes_imdb_ids
]
if watching_item := trakt_watching(session):
logger.debug("Filtering out currently watching...")
add_movies = cast(
list[TraktWatchedItem],
list(_block_watching_items(add_movies, watching_item)),
)
add_episodes = cast(
list[TraktWatchedItem],
list(_block_watching_items(add_episodes, watching_item)),
)
trakt_add_history(session, movies=add_movies, episodes=add_episodes)
@dataclass
class IMDBWatchlistItem:
imdb_id: str
trakt_type: Literal["movie", "show", "episode"]
@dataclass
class IMDBRatingItem:
imdb_id: str
rating: int
rated_on: date
trakt_type: Literal["movie", "show", "episode"]
def fetch_imdb_watchlist(url: str) -> list[IMDBWatchlistItem]:
items: list[IMDBWatchlistItem] = []
for row in csv.DictReader(_iterlines(url)):
imdb_id = row["Const"]
assert imdb_id.startswith("tt"), f"Invalid IMDb ID: {imdb_id}"
trakt_type: Literal["movie", "show", "episode"] | None = None
if row["Title Type"] in _IMDB_MOVIE_TYPES:
trakt_type = "movie"
elif row["Title Type"] in _IMDB_SHOW_TYPES:
trakt_type = "show"
assert trakt_type, f"Unknown IMDB Title Type: {row['Title Type']}"
item = IMDBWatchlistItem(imdb_id=imdb_id, trakt_type=trakt_type)
items.append(item)
return items
def fetch_imdb_ratings(url: str) -> list[IMDBRatingItem]:
items: list[IMDBRatingItem] = []
for row in csv.DictReader(_iterlines(url)):
imdb_id = row["Const"]
assert imdb_id.startswith("tt"), f"Invalid IMDb ID: {imdb_id}"
rating = int(row["Your Rating"])
rated_on: date = datetime.strptime(row["Date Rated"], "%Y-%m-%d")
trakt_type: Literal["movie", "show", "episode"] | None = None
if row["Title Type"] in _IMDB_MOVIE_TYPES:
trakt_type = "movie"
elif row["Title Type"] in _IMDB_SHOW_TYPES:
trakt_type = "show"
assert trakt_type, f"Unknown IMDB Title Type: {row['Title Type']}"
item = IMDBRatingItem(
imdb_id=imdb_id,
rating=rating,
rated_on=rated_on,
trakt_type=trakt_type,
)
items.append(item)
return items
def _iterlines(path: Path | str) -> Iterator[str]:
if isinstance(path, str) and path.startswith("http"):
logger.debug("Fetching remote '%s'", path)
response = requests.get(path)
response.raise_for_status()
yield from response.iter_lines(decode_unicode=True)
else:
logger.debug("Reading local file '%s'", path)
with open(path) as f:
yield from f
class TraktIMDBIDs(TypedDict):
imdb: str
class TraktAnyItem(TypedDict):
ids: TraktIMDBIDs
class TraktWatchlistItem(TypedDict):
rank: int
id: int
type: Literal["movie", "show", "season", "episode"]
movie: TraktAnyItem
show: TraktAnyItem
season: TraktAnyItem
episode: TraktAnyItem
class TraktRatedItem(TraktAnyItem):
rated_at: str
rating: int
class TraktWatchingItem(TypedDict):
expires_at: str
started_at: str
action: Literal["scrobble", "checkin", "watch"]
type: Literal["movie", "episode"]
movie: TraktAnyItem
episode: TraktAnyItem
show: TraktAnyItem
class TraktHistoryItem(TypedDict):
id: int
watched_at: str
action: Literal["scrobble", "checkin", "watch"]
type: Literal["movie", "episode"]
movie: TraktAnyItem
episode: TraktAnyItem
class TraktWatchedItem(TraktAnyItem):
watched_at: str
class TraktRatingItem(TypedDict):
rated_at: str
rating: int
type: Literal["movie", "show", "season", "episode"]
movie: TraktAnyItem
show: TraktAnyItem
season: TraktAnyItem
episode: TraktAnyItem
class TraktTypedContainer(TypedDict):
type: Literal["movie", "show", "season", "episode"]
movie: TraktAnyItem
show: TraktAnyItem
season: TraktAnyItem
episode: TraktAnyItem
_TRAKT_API_HEADERS = {
"Content-Type": "application/json",
"trakt-api-key": "",
"trakt-api-version": "2",
"Authorization": "Bearer [access_token]",
}
_TRAKT_WATCHLIST_URL = "https://api.trakt.tv/sync/watchlist"
_TRAKT_UPDATE_WATCHLIST_URL = "https://api.trakt.tv/sync/watchlist"
_TRAKT_REMOVE_FROM_WATCHLIST_URL = "https://api.trakt.tv/sync/watchlist/remove"
_TRAKT_RATINGS_URL = "https://api.trakt.tv/sync/ratings"
_TRAKT_HISTORY_URL = "https://api.trakt.tv/sync/history"
_TRAKT_ADD_RATINGS_URL = "https://api.trakt.tv/sync/ratings"
_TRAKT_REMOVE_RATINGS_URL = "https://api.trakt.tv/sync/ratings/remove"
def trakt_session(client_id: str, access_token: str) -> requests.Session:
session = requests.Session()
session.headers.update(_TRAKT_API_HEADERS)
session.headers["trakt-api-key"] = client_id
session.headers["Authorization"] = f"Bearer {access_token}"
return session
class TraktRatelimit(TypedDict):
name: str
period: int
limit: int
remaining: int
until: str
def trakt_request(
session: requests.Session,
method: Literal["GET", "POST", "PUT", "DELETE"],
url: str,
**kwargs: Any,
) -> requests.Response:
response = session.request(method, url, **kwargs)
response.raise_for_status()
if method != "GET":
logger.debug("Sleeping for 1 sec")
sleep(1)
return response
def trakt_request_paginated(
session: requests.Session,
method: Literal["GET"],
url: str,
limit: int,
) -> Iterator[Any]:
page = 1
while True:
response = trakt_request(
session,
method=method,
url=url,
params={
"page": str(page),
"limit": str(limit),
},
)
yield from response.json()
pagination = _trakt_pagination(response)
if pagination.page >= pagination.page_count:
break
page += 1
@dataclass
class TraktPagination:
page: int
limit: int
page_count: int
item_count: int
def _trakt_pagination(response: requests.Response) -> TraktPagination:
return TraktPagination(
page=int(response.headers["X-Pagination-Page"]),
limit=int(response.headers["X-Pagination-Limit"]),
page_count=int(response.headers["X-Pagination-Page-Count"]),
item_count=int(response.headers["X-Pagination-Item-Count"]),
)
def trakt_watchlist(session: requests.Session) -> Iterator[TraktWatchlistItem]:
yield from trakt_request_paginated(
session,
method="GET",
url=_TRAKT_WATCHLIST_URL,
limit=1000,
)
def trakt_update_watchlist(
session: requests.Session,
movies: list[TraktAnyItem] = [],
shows: list[TraktAnyItem] = [],
seasons: list[TraktAnyItem] = [],
episodes: list[TraktAnyItem] = [],
) -> None:
if not movies and not shows and not seasons and not episodes:
logger.debug("No items to update")
return
data = {
"movies": movies,
"shows": shows,
"seasons": seasons,
"episodes": episodes,
}
response = trakt_request(
session,
method="POST",
url=_TRAKT_UPDATE_WATCHLIST_URL,
json=data,
)
result = response.json()
for media_type in ["movies", "shows", "seasons", "episodes"]:
added: int = result["added"][media_type]
existing: int = result["existing"][media_type]
not_found: list[TraktAnyItem] = result["not_found"][media_type]
if added > 0:
logger.info("Added %d %s to watchlist", added, media_type)
if existing > 0:
logger.debug("%d %s already in watchlist", existing, media_type)
if not_found:
for item in not_found:
logger.warning(
"https://www.imdb.com/title/%s/ not found on Trakt",
item["ids"]["imdb"],
)
def trakt_remove_from_watchlist(
session: requests.Session,
movies: list[TraktAnyItem] = [],
shows: list[TraktAnyItem] = [],
seasons: list[TraktAnyItem] = [],
episodes: list[TraktAnyItem] = [],
) -> None:
if not movies and not shows and not seasons and not episodes:
logger.debug("No items to remove")
return
data = {
"movies": movies,
"shows": shows,
"seasons": seasons,
"episodes": episodes,
}
response = trakt_request(
session,
method="POST",
url=_TRAKT_REMOVE_FROM_WATCHLIST_URL,
json=data,
)
result = response.json()
for media_type in ["movies", "shows", "seasons", "episodes"]:
deleted: int = result["deleted"][media_type]
not_found: list[TraktAnyItem] = result["not_found"][media_type]
if deleted > 0:
logger.info("Deleted %d %s from watchlist", deleted, media_type)
if not_found:
for item in not_found:
logger.warning(
"https://www.imdb.com/title/%s/ not found on Trakt",
item["ids"]["imdb"],
)
def trakt_watching(session: requests.Session) -> TraktWatchingItem | None:
response = trakt_request(
session,
method="GET",
url="https://api.trakt.tv/users/me/watching",
)
if response.status_code == 200:
data: TraktWatchingItem = response.json()
return data
elif response.status_code == 204:
return None
else:
response.raise_for_status()
return None
def trakt_watching_imdb_id(session: requests.Session) -> str | None:
if watching := trakt_watching(session):
if watching["type"] == "movie":
return watching["movie"]["ids"]["imdb"]
elif watching["type"] == "episode":
return watching["episode"]["ids"]["imdb"]
return None
def _block_watching_items(
items: Iterable[TraktAnyItem],
watching: TraktWatchingItem | None,
) -> Iterator[TraktAnyItem]:
if watching is None:
yield from items
return
if watching["type"] == "movie":
watching_imdb_id = watching["movie"]["ids"]["imdb"]
elif watching["type"] == "episode":
watching_imdb_id = watching["episode"]["ids"]["imdb"]
else:
yield from items
return
for item in items:
if item["ids"].get("imdb") == watching_imdb_id:
logger.warning(
"https://www.imdb.com/title/%s/ is currently being watched, ignoring",
watching_imdb_id,
)
continue
else:
yield item
def trakt_ratings(
session: requests.Session,
media_type: Literal["movies", "shows", "seasons", "episodes", "all"] = "all",
) -> Iterator[TraktRatingItem]:
yield from trakt_request_paginated(
session,
method="GET",
url=f"{_TRAKT_RATINGS_URL}/{media_type}",
limit=1000,
)
def trakt_add_ratings(
session: requests.Session,
movies: list[TraktRatedItem] = [],
shows: list[TraktRatedItem] = [],
seasons: list[TraktRatedItem] = [],
episodes: list[TraktRatedItem] = [],
) -> None:
if not movies and not shows and not seasons and not episodes:
logger.debug("No items to rate")
return
data = {
"movies": movies,
"shows": shows,
"seasons": seasons,
"episodes": episodes,
}
response = trakt_request(
session,
method="POST",
url=_TRAKT_ADD_RATINGS_URL,
json=data,
)
result = response.json()
for media_type in ["movies", "shows", "seasons", "episodes"]:
added: int = result["added"][media_type]
not_found: list[TraktAnyItem] = result["not_found"][media_type]
if added > 0:
logger.info("Added %d %s to ratings", added, media_type)
if not_found:
for item in not_found:
logger.warning(
"https://www.imdb.com/title/%s/ not found on Trakt",
item["ids"]["imdb"],
)
def trakt_remove_ratings(
session: requests.Session,
movies: list[TraktRatedItem] = [],
shows: list[TraktRatedItem] = [],
seasons: list[TraktRatedItem] = [],
episodes: list[TraktRatedItem] = [],
) -> None:
if not movies and not shows and not seasons and not episodes:
logger.debug("No items to remove")
return
data = {
"movies": movies,
"shows": shows,
"seasons": seasons,
"episodes": episodes,
}
response = trakt_request(
session,
method="POST",
url=_TRAKT_REMOVE_RATINGS_URL,
json=data,
)
result = response.json()
for media_type in ["movies", "shows", "seasons", "episodes"]:
deleted: int = result["deleted"][media_type]
not_found: list[TraktAnyItem] = result["not_found"][media_type]
if deleted > 0:
logger.info("Deleted %d %s from ratings", deleted, media_type)
if not_found:
for item in not_found:
logger.warning(
"https://www.imdb.com/title/%s/ not found on Trakt",
item["ids"]["imdb"],
)
def trakt_history(
session: requests.Session,
media_type: Literal["movies", "shows", "seasons", "episodes"] | None = None,
) -> Iterator[TraktHistoryItem]:
url = _TRAKT_HISTORY_URL
if media_type:
url += f"/{media_type}"
yield from trakt_request_paginated(
session,
method="GET",
url=url,
limit=1000,
)
def trakt_add_history(
session: requests.Session,
movies: list[TraktWatchedItem] = [],
shows: list[TraktWatchedItem] = [],
seasons: list[TraktWatchedItem] = [],
episodes: list[TraktWatchedItem] = [],
) -> None:
if not movies and not shows and not seasons and not episodes:
logger.debug("No items to add")
return
data = {
"movies": movies,
"shows": shows,
"seasons": seasons,
"episodes": episodes,
}
response = trakt_request(
session,
method="POST",
url=_TRAKT_HISTORY_URL,
json=data,
)
result = response.json()
for media_type in ["movies", "episodes"]:
added: int = result["added"][media_type]
not_found: list[TraktAnyItem] = result["not_found"][media_type]
if added > 0:
logger.info("Added %d %s to ratings", added, media_type)
if not_found:
for item in not_found:
logger.warning(
"https://www.imdb.com/title/%s/ not found on Trakt",
item["ids"]["imdb"],
)
def _trakt_mediaitem_imdb_id(item: TraktTypedContainer) -> str | None:
if item["type"] == "movie":
return item["movie"]["ids"]["imdb"]
elif item["type"] == "show":
return item["show"]["ids"]["imdb"]
elif item["type"] == "season":
return item["season"]["ids"]["imdb"]
elif item["type"] == "episode":
return item["episode"]["ids"]["imdb"]
else:
raise ValueError(f"Unknown media type: {item['type']}")
def _compact_set(s: Iterable[str | None]) -> set[str]:
return {x for x in s if x is not None}
def _fromisoformat(s: str) -> datetime:
assert s.endswith("Z")
return datetime.fromisoformat(s[:-1])
if __name__ == "__main__":
main()