Debian Codegraph @

jellyfin_apiclient_python/api.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 For API info see:
4 https://api.jellyfin.org/
5 """
6 from typing import List
7 from datetime import datetime
8 from urllib.parse import quote
9 import requests
10 import json
11 import logging
12
13 LOG = logging.getLogger('JELLYFIN.' + __name__)
14
15
16 def jellyfin_url(client, handler):
17 base_url = client.config.data['auth.server'].rstrip('/')
18 return f"{base_url}/{handler.lstrip('/')}"
19
20
21 def basic_info():
22 return "Etag"
23
24
25 def info():
26 return (
27 "Path,Genres,SortName,Studios,Writer,Taglines,LocalTrailerCount,"
28 "OfficialRating,CumulativeRunTimeTicks,ItemCounts,"
29 "Metascore,AirTime,DateCreated,People,Overview,"
30 "CriticRating,CriticRatingSummary,Etag,ShortOverview,ProductionLocations,"
31 "Tags,ProviderIds,ParentId,RemoteTrailers,SpecialEpisodeNumbers,"
32 "MediaSources,VoteCount,RecursiveItemCount,PrimaryImageAspectRatio"
33 )
34
35
36 def music_info():
37 return (
38 "Etag,Genres,SortName,Studios,Writer,"
39 "OfficialRating,CumulativeRunTimeTicks,Metascore,"
40 "AirTime,DateCreated,MediaStreams,People,ProviderIds,Overview,ItemCounts"
41 )
42
43
44 class InternalAPIMixin:
45 """
46 A mixin class containing a common set of internal calls the other mixin
47 classes will use.
48 """
49
50 def _http(self, action, url, request={}):
51 request.update({'type': action, 'handler': url})
52
53 return self.client.request(request)
54
55 def _http_url(self, action, url, request={}, include_apikey=True):
56 request.update({"type": action, "handler": url})
57
58 return self.client.request_url(request, include_apikey=include_apikey)
59
60 def _http_stream(self, action, url, dest_file, request={}):
61 request.update({'type': action, 'handler': url})
62
63 self.client.request(request, dest_file=dest_file)
64
65 def _get(self, handler, params=None):
66 return self._http("GET", handler, {'params': params})
67
68 def _get_url(self, handler, params=None, include_apikey=True):
69 return self._http_url("GET", handler, {"params": params},
70 include_apikey=include_apikey)
71
72 def _post(self, handler, json=None, params=None, data=None, headers=None):
73 return self._http("POST", handler, {'params': params, 'json': json,
74 'data': data, 'headers': headers})
75
76 def _delete(self, handler, params=None):
77 return self._http("DELETE", handler, {'params': params})
78
79 def _get_stream(self, handler, dest_file, params=None):
80 self._http_stream("GET", handler, dest_file, {'params': params})
81
82
83 class BiggerAPIMixin:
84 """
85 Bigger section of the Jellyfin api
86 """
87
88 def try_server(self):
89 return self._get("System/Info/Public")
90
91 def command(self, id, command, params=None, json=None):
92 return self._post(
93 "Sessions/%s/Command" % id,
94 json={"Name": command, "Arguments": json},
95 params=params,
96 )
97
98 def remote(self, id, command, params=None, json=None):
99 handler = (
100 "Sessions/%s/Playing/%s" % (id, command)
101 if command
102 else "Sessions/%s/Playing" % id
103 )
104 return self._post(
105 handler,
106 json=json,
107 params=params,
108 )
109
110 def sessions(self, handler="", action="GET", params=None, json=None,
111 timeout=None, retry=None):
112 """Session endpoints.
113
114 ``timeout`` and ``retry`` bound this one call instead of using the
115 client-wide defaults (30s, 5 retries). A caller polling for liveness —
116 a health check — wants a request that fails fast, since the defaults
117 can wedge its thread for minutes against an unresponsive server.
118 """
119 request = {'params': params}
120 if timeout is not None:
121 request['timeout'] = timeout
122 if retry is not None:
123 request['retry'] = retry
124 if action == "POST":
125 request['json'] = json
126 return self._http("POST", "Sessions%s" % handler, request)
127 elif action == "DELETE":
128 return self._http("DELETE", "Sessions%s" % handler, request)
129 else:
130 return self._http("GET", "Sessions%s" % handler, request)
131
132 def users(self, handler="", action="GET", params=None, json=None):
133 if action == "POST":
134 return self._post("Users/{UserId}%s" % handler, json, params)
135 elif action == "DELETE":
136 return self._delete("Users/{UserId}%s" % handler, params)
137 else:
138 return self._get("Users/{UserId}%s" % handler, params)
139
140 def media_folders(self, params=None):
141 return self._get("Library/MediaFolders/", params)
142
143 def virtual_folders(self, action="GET", params=None, json=None):
144 if action == "POST":
145 return self._post("Library/VirtualFolders", json, params)
146 elif action == "DELETE":
147 return self._delete("Library/VirtualFolders", params)
148 else:
149 return self._get("Library/VirtualFolders", params)
150
151 def physical_paths(self, params=None):
152 return self._get("Library/PhysicalPaths/", params)
153
154 def folder_contents(self, abspath="/", params=None, json=None):
155 params = {} if params is None else params.copy()
156 params['path'] = abspath
157 params['includeFiles'] = params.get('includeFiles', True)
158 params['includeDirectories'] = params.get('includeDirectories', True)
159 return self._get("Environment/DirectoryContents", params)
160
161 def refresh_library(self):
162 """
163 Starts a library scan.
164 """
165 return self._post("Library/Refresh")
166
167 def add_media_library(self, name, collectionType, paths, refreshLibrary=True):
168 """
169 Create a new media library.
170
171 Args:
172 name (str): name of the new library
173
174 collectionType (str): one of "movies" "tvshows" "music" "musicvideos"
175 "homevideos" "boxsets" "books" "mixed"
176
177 paths (List[str]):
178 paths on the server to use in the media library
179
180 References:
181 .. [AddVirtualFolder] https://api.jellyfin.org/#tag/LibraryStructure/operation/AddVirtualFolder
182 """
183 params = {
184 'name': name,
185 'collectionType': collectionType,
186 'paths': paths,
187 'refreshLibrary': refreshLibrary,
188
189 }
190 return self.virtual_folders('POST', params=params)
191
192 def items(self, handler="", action="GET", params=None, json=None, data=None, headers=None):
193 if action == "POST":
194 return self._post("Items%s" % handler, json, params, data, headers)
195 elif action == "DELETE":
196 return self._delete("Items%s" % handler, params)
197 else:
198 return self._get("Items%s" % handler, params)
199
200 def user_items(self, handler="", params=None):
201 return self.users("/Items%s" % handler, params=params)
202
203 def get_playlist_items(self, playlist_id, fields=None, start_index=None,
204 limit=None):
205 """Items of a playlist in playlist order (GET Playlists/{id}/Items).
206
207 Unlike a ``ParentId`` query, this preserves the user's playlist ordering
208 and returns each entry's ``PlaylistItemId``. ``UserId`` is filled from
209 the session so per-user data (played/resume) comes back.
210 """
211 params = {"UserId": "{UserId}"}
212 if fields is not None:
213 params["Fields"] = fields
214 if start_index is not None:
215 params["StartIndex"] = start_index
216 if limit is not None:
217 params["Limit"] = limit
218 return self._get("Playlists/%s/Items" % playlist_id, params)
219
220 def shows(self, handler, params):
221 return self._get("Shows%s" % handler, params)
222
223 def videos(self, handler):
224 return self._get("Videos%s" % handler)
225
226 def media_segments(self, handler, params=None):
227 return self._get("MediaSegments%s" % handler, params)
228
229 def artwork(self, item_id, art, max_width, ext="jpg", index=None,
230 include_apikey=True):
231 params = {"MaxWidth": max_width, "format": ext}
232 handler = ("Items/%s/Images/%s" % (item_id, art) if index is None
233 else "items/%s/images/%s/%s" % (item_id, art, index)
234 )
235
236 return self._get_url(handler, params,
237 include_apikey=include_apikey)
238
239 def audio_url(self, item_id, container=None, audio_codec=None,
240 max_streaming_bitrate=140000000, include_apikey=True):
241 params = {
242 "UserId": "{UserId}",
243 "DeviceId": "{DeviceId}",
244 "MaxStreamingBitrate": max_streaming_bitrate,
245 }
246
247 if container:
248 params["Container"] = container
249
250 if audio_codec:
251 params["AudioCodec"] = audio_codec
252
253 return self._get_url("Audio/%s/universal" % item_id, params,
254 include_apikey=include_apikey)
255
256 def video_url(self, item_id, media_source_id=None, include_apikey=True):
257 params = {
258 "static": "true",
259 "DeviceId": "{DeviceId}"
260 }
261 if media_source_id is not None:
262 params["MediaSourceId"] = media_source_id
263
264 return self._get_url("Videos/%s/stream" % item_id, params,
265 include_apikey=include_apikey)
266
267 def download_url(self, item_id, include_apikey=True):
268 params = {}
269 return self._get_url("Items/%s/Download" % item_id, params,
270 include_apikey=include_apikey)
271
272 def image_url(self, item_id, image_type="Primary", index=None, tag=None,
273 max_width=None, fill_width=None, fill_height=None,
274 quality=90, include_apikey=True):
275 """Build an image URL for an item.
276
277 Pass ``fill_width``/``fill_height`` to crop to an exact box, or
278 ``max_width`` to scale within a width. ``index`` selects a numbered
279 image (e.g. ``Backdrop`` index ``0``).
280 """
281 handler = "Items/%s/Images/%s" % (item_id, image_type)
282 if index is not None:
283 handler = "%s/%s" % (handler, index)
284 params = {}
285 if quality is not None:
286 params["quality"] = quality
287 if fill_width is not None and fill_height is not None:
288 params["fillWidth"] = int(fill_width)
289 params["fillHeight"] = int(fill_height)
290 elif max_width is not None:
291 params["maxWidth"] = int(max_width)
292 if tag is not None:
293 params["tag"] = tag
294 return self._get_url(handler, params,
295 include_apikey=include_apikey)
296
297 def subtitle_url(self, item_id, media_source_id, index, fmt, fmt_index=0,
298 include_apikey=True):
299 """Build the external-subtitle sidecar stream URL for one stream."""
300 return self._get_url(
301 "Videos/%s/%s/Subtitles/%s/%s/Stream.%s"
302 % (item_id, media_source_id, index, fmt_index, fmt), {},
303 include_apikey=include_apikey)
304
305 def trickplay_tile_url(self, item_id, width, index, media_source_id=None,
306 include_apikey=True):
307 """Build the URL for a single trickplay (scrubbing preview) tile."""
308 params = {}
309 if media_source_id is not None:
310 params["MediaSourceId"] = media_source_id
311 return self._get_url(
312 "Videos/%s/Trickplay/%s/%s.jpg" % (item_id, width, index), params,
313 include_apikey=include_apikey)
314
315
316 class GranularAPIMixin:
317 """
318 Mixin class containing Jellyfin API granular user-level calls
319 """
320
321 def get_users(self):
322 return self._get("Users")
323
324 def get_public_users(self):
325 return self._get("Users/Public")
326
327 def get_user(self, user_id=None):
328 return self.users() if user_id is None else self._get("Users/%s" % user_id)
329
330 def get_user_settings(self, client="emby"):
331 return self._get("DisplayPreferences/usersettings", params={
332 "userId": "{UserId}",
333 "client": client
334 })
335
336 def new_user(self, name, pw):
337 return self._post("Users/New", {
338 "name": name,
339 "Password": pw
340 })
341
342 def delete_user(self, userID):
343 return self._delete(f"Users/{userID}")
344
345 def get_views(self):
346 return self.users("/Views")
347
348 def get_media_folders(self, fields=None):
349 params = None
350 if fields is not None:
351 params = {'fields': fields}
352 return self.users("/Items", params=params)
353
354 def get_item(self, item_id, fields=None):
355 """
356 Lookup metadata for an item.
357
358 Args:
359 item_id (str): item uuid to lookup metadata for
360 fields (str): comma-separated Fields to request; defaults to the
361 standard ``info()`` field set.
362
363 Returns:
364 Dict[str, Any]: metadata keys and values for the queried item.
365 """
366 return self.users("/Items/%s" % item_id, params={
367 'Fields': fields if fields is not None else info()
368 })
369
370 def get_items(self, item_ids, fields=None):
371 """
372 Lookup metadata for multiple items.
373
374 The server does not preserve the requested order, and it drops ids it
375 cannot resolve, so callers that care about order should re-index the
376 result by ``Id``. Very long id lists are best sent in batches — they
377 travel in the query string, which servers and proxies cap (HTTP 414).
378
379 Args:
380 item_ids (List[str]): item uuids to lookup metadata for
381
382 fields (str): comma-separated Fields to request; defaults to the
383 standard ``info()`` field set.
384
385 Returns:
386 Dict[str, Any]: A result dictionary where the info from each
387 item is stored in the "Items" list.
388 """
389 return self.users("/Items", params={
390 'Ids': ','.join(str(x) for x in item_ids),
391 'Fields': info() if fields is None else fields
392 })
393
394 def update_item(self, item_id, data):
395 """
396 Updates the metadata for an item.
397
398 Requires a user with elevated permissions [UpdateItem]_.
399
400 Args:
401 item_id (str): item uuid to update metadata for
402
403 data (Dict): the new information to add to this item.
404 Note: any specified items are completely overwritten.
405
406 References:
407 .. [UpdateItem] https://api.jellyfin.org/#tag/ItemUpdate/operation/UpdateItem
408 """
409 # Force us to get the entire original item, we need to pass
410 # all information, otherwise all info is overwritten
411 body = self.get_item(item_id)
412 body.update(data)
413 assert body['Id'] == item_id
414 return self.items('/' + item_id, action='POST', params=None, json=body)
415
416 def get_sessions(self):
417 return self.sessions(params={'ControllableByUserId': "{UserId}"})
418
419 def get_device(self, device_id):
420 return self.sessions(params={'DeviceId': device_id})
421
422 def post_session(self, session_id, url, params=None, data=None):
423 return self.sessions("/%s/%s" % (session_id, url), "POST", params, data)
424
425 def get_images(self, item_id):
426 return self.items("/%s/Images" % item_id)
427
428 def get_suggestion(self, media="Movie,Episode", limit=1):
429 return self.users("/Suggestions", params={
430 'Type': media,
431 'Limit': limit
432 })
433
434 def get_recently_added(self, media=None, parent_id=None, limit=20,
435 fields=None, enable_image_types=None,
436 image_type_limit=None,
437 enable_total_record_count=None):
438 """Recently added items (GET Users/{UserId}/Items/Latest).
439
440 Answers a bare list of items, not the usual ``{"Items": [...]}``
441 envelope.
442
443 ``fields`` defaults to the broad ``info()`` set for backward
444 compatibility; pass a lean list when building a home-screen row, since
445 the default pulls MediaSources, People and Studios for every item.
446 ``enable_total_record_count=False`` skips the server's separate
447 ``COUNT(*)``, which a fixed-size row never reads.
448 """
449 params = {
450 'Limit': limit,
451 'UserId': "{UserId}",
452 'IncludeItemTypes': media,
453 'ParentId': parent_id,
454 'Fields': info() if fields is None else fields,
455 }
456 if enable_image_types is not None:
457 params['EnableImageTypes'] = enable_image_types
458 if image_type_limit is not None:
459 params['ImageTypeLimit'] = image_type_limit
460 if enable_total_record_count is not None:
461 params['EnableTotalRecordCount'] = enable_total_record_count
462 return self.user_items("/Latest", params)
463
464 def get_next(self, index=None, limit=1, series_id=None, fields=None,
465 enable_image_types=None, image_type_limit=None):
466 """Next Up (GET /Shows/NextUp).
467
468 ``image_type_limit`` caps how many tags of each type come back per
469 item. Without it a series with twenty backdrops sends twenty tags
470 for a card that will use one; jellyfin-web sends 1 here.
471 """
472 params = {
473 'Limit': limit,
474 'UserId': "{UserId}",
475 'StartIndex': None if index is None else int(index)
476 }
477 if series_id is not None:
478 params['SeriesId'] = series_id
479 if fields is not None:
480 params['Fields'] = fields
481 if enable_image_types is not None:
482 params['EnableImageTypes'] = enable_image_types
483 if image_type_limit is not None:
484 params['ImageTypeLimit'] = image_type_limit
485 return self.shows("/NextUp", params)
486
487 def get_adjacent_episodes(self, show_id, item_id):
488 return self.shows("/%s/Episodes" % show_id, {
489 'UserId': "{UserId}",
490 'AdjacentTo': item_id,
491 'Fields': "Overview"
492 })
493
494 def get_season(self, show_id, season_id):
495 return self.shows("/%s/Episodes" % show_id, {
496 'UserId': "{UserId}",
497 'SeasonId': season_id
498 })
499
500 def get_episodes(self, series_id, season_id=None, start_item_id=None,
501 fields=None, limit=None):
502 """Episodes for a series, optionally scoped to one season or starting
503 at a given episode (``start_item_id`` crosses season boundaries)."""
504 params = {'UserId': "{UserId}"}
505 if season_id is not None:
506 params['SeasonId'] = season_id
507 if start_item_id is not None:
508 params['StartItemId'] = start_item_id
509 if fields is not None:
510 params['Fields'] = fields
511 if limit is not None:
512 params['Limit'] = limit
513 return self.shows("/%s/Episodes" % series_id, params)
514
515 def get_studios(self, parent_id=None, include_item_types=None,
516 sort_by="SortName", sort_order="Ascending",
517 fields=None, start_index=None, limit=None):
518 """Studios / networks under a library (GET /Studios).
519
520 The by-name counterpart to ``get_genres``: it answers with Studio
521 items carrying their own ids and artwork, which is what a studios
522 screen draws and what ``StudioIds`` on an item query then filters by.
523 """
524 params = {
525 "ParentId": parent_id,
526 "UserId": "{UserId}",
527 "SortBy": sort_by,
528 "SortOrder": sort_order,
529 "Recursive": True,
530 "Fields": fields if fields is not None else "PrimaryImageAspectRatio",
531 }
532 if include_item_types is not None:
533 params["IncludeItemTypes"] = include_item_types
534 if start_index is not None:
535 params["StartIndex"] = start_index
536 if limit is not None:
537 params["Limit"] = limit
538 return self._get("Studios", params)
539
540 def get_genres(self, parent_id=None, include_item_types=None):
541 params = {
542 'ParentId': parent_id,
543 'UserId': "{UserId}",
544 'Fields': info(),
545 }
546 if include_item_types is not None:
547 # e.g. "MusicAlbum" for a music library's genre list.
548 params['IncludeItemTypes'] = include_item_types
549 return self._get("Genres", params)
550
551 def _artist_query(self, handler, params, parent_id, sort_by, sort_order,
552 start_index, limit, fields, image_type_limit,
553 enable_image_types, search_term):
554 p = {
555 "UserId": "{UserId}",
556 "ParentId": parent_id,
557 "SortBy": sort_by,
558 "SortOrder": sort_order,
559 "StartIndex": start_index,
560 "Limit": limit,
561 "Fields": fields,
562 "ImageTypeLimit": image_type_limit,
563 "EnableImageTypes": enable_image_types,
564 "SearchTerm": search_term,
565 }
566 p = {k: v for k, v in p.items() if v is not None}
567 if params:
568 p.update(params)
569 return self._get(handler, p)
570
571 def get_artists(self, params=None, parent_id=None, sort_by=None,
572 sort_order=None, start_index=None, limit=None, fields=None,
573 image_type_limit=None, enable_image_types=None,
574 search_term=None):
575 """Artists (GET /Artists) — includes track-level / featured artists.
576 Pass ``parent_id`` to scope to a library, plus the usual paging and
577 sort arguments. ``params`` is merged in last for anything this
578 signature does not name. UserId is added so per-user data comes back."""
579 return self._artist_query(
580 "Artists", params, parent_id, sort_by, sort_order, start_index,
581 limit, fields, image_type_limit, enable_image_types, search_term)
582
583 def get_album_artists(self, params=None, parent_id=None, sort_by=None,
584 sort_order=None, start_index=None, limit=None,
585 fields=None, image_type_limit=None,
586 enable_image_types=None, search_term=None):
587 """Album artists (GET /Artists/AlbumArtists) — artists credited on an
588 album, the more useful artist list. Same arguments as get_artists."""
589 return self._artist_query(
590 "Artists/AlbumArtists", params, parent_id, sort_by, sort_order,
591 start_index, limit, fields, image_type_limit, enable_image_types,
592 search_term)
593
594 def get_instant_mix(self, item_id, limit=200, fields=None):
595 """A radio-style auto queue seeded from an item (GET
596 /Items/{id}/InstantMix); works for a song, album, artist, or genre.
597
598 ``fields`` defaults to the ``music_info()`` set for backwards
599 compatibility, but that set is expensive here in a way it is not on a
600 single item: ``MediaStreams``, ``People`` and ``ItemCounts`` are all
601 per-item lookups, and this endpoint returns up to ``limit`` (200)
602 items, so the server does hundreds of extra queries before it answers.
603 jellyfin-web asks for no fields at all here. Pass ``fields=""`` to do
604 the same, or a lean set of your own.
605 """
606 params = {
607 "UserId": "{UserId}",
608 "Limit": limit,
609 }
610 fields = music_info() if fields is None else fields
611 if fields:
612 params["Fields"] = fields
613 return self._get("Items/%s/InstantMix" % item_id, params)
614
615 def get_recommendation(self, parent_id=None, limit=20):
616 return self._get("Movies/Recommendations", {
617 'ParentId': parent_id,
618 'UserId': "{UserId}",
619 'Fields': info(),
620 'Limit': limit
621 })
622
623 def get_items_by_letter(self, parent_id=None, media=None, letter=None):
624 return self.user_items(params={
625 'ParentId': parent_id,
626 'NameStartsWith': letter,
627 'Fields': info(),
628 'Recursive': True,
629 'IncludeItemTypes': media
630 })
631
632 def search_media_items(self, term=None, year=None, media=None, limit=20, parent_id=None):
633 """
634 Description:
635 Search for media using terms, production year(s) and media type
636
637 Args:
638 term (str):
639 year (int):
640 media (str):
641 limit (int):
642 parent_id (str):
643
644 Returns:
645 dict
646
647 Example:
648 >>> result = client.jellyfin.search_media_items(term='The Lion King', year=1994, media='Movie', limit=1)
649 >>> result['Items']
650 [
651 {
652 'Name': 'The Lion King',
653 ...
654 'ProductionYear': 1994
655 ...
656 'Type': 'Movie'
657 }
658 ]
659 """
660 return self.user_items(params={
661 'searchTerm': term,
662 'years': year,
663 'Recursive': True,
664 'IncludeItemTypes': media,
665 'Limit': limit,
666 'parentId': parent_id,
667 })
668
669 def get_user_items(self, parent_id=None, include_item_types=None,
670 media_types=None, recursive=None, sort_by=None,
671 sort_order=None, start_index=None, limit=None,
672 fields=None, filters=None, ids=None, genres=None,
673 genre_ids=None, years=None, person_ids=None,
674 artist_ids=None, album_artist_ids=None,
675 search_term=None, is_favorite=None,
676 name_starts_with=None, name_less_than=None,
677 image_type_limit=None, enable_image_types=None,
678 enable_images=None, enable_user_data=None,
679 enable_total_record_count=None, params=None):
680 """The general item query (GET Users/{UserId}/Items).
681
682 This is the endpoint behind every library grid: pass ``parent_id`` to
683 scope to a folder or library, ``recursive=True`` to search below it,
684 and the usual sort/page/filter arguments. Arguments left at ``None``
685 are not sent, so the server's own defaults apply.
686
687 ``filters`` takes Jellyfin's ``Filters`` enum as a comma-separated
688 string (``"IsUnplayed"``, ``"IsResumable"``, ``"IsFavorite"``, …).
689 ``params`` is merged in last, for query parameters this signature does
690 not name.
691
692 Prefer the narrower helpers where one exists (``get_resume_items``,
693 ``get_album_tracks``, ``get_artist_albums``, ``get_playlists``,
694 ``get_random_items``, ``search_media_items``) — they document intent
695 and pick the right sort.
696
697 References:
698 .. [GetItems] https://api.jellyfin.org/#tag/Items/operation/GetItems
699 """
700 query = {
701 'ParentId': parent_id,
702 'IncludeItemTypes': include_item_types,
703 'MediaTypes': media_types,
704 'Recursive': recursive,
705 'SortBy': sort_by,
706 'SortOrder': sort_order,
707 'StartIndex': start_index,
708 'Limit': limit,
709 'Fields': fields,
710 'Filters': filters,
711 'Ids': ','.join(str(x) for x in ids) if ids is not None else None,
712 'Genres': genres,
713 'GenreIds': genre_ids,
714 'Years': years,
715 'PersonIds': person_ids,
716 'ArtistIds': artist_ids,
717 'AlbumArtistIds': album_artist_ids,
718 'SearchTerm': search_term,
719 'IsFavorite': is_favorite,
720 'NameStartsWith': name_starts_with,
721 'NameLessThan': name_less_than,
722 'ImageTypeLimit': image_type_limit,
723 'EnableImageTypes': enable_image_types,
724 'EnableImages': enable_images,
725 'EnableUserData': enable_user_data,
726 'EnableTotalRecordCount': enable_total_record_count,
727 }
728 query = {k: v for k, v in query.items() if v is not None}
729 if params:
730 query.update(params)
731 return self.user_items(params=query)
732
733 def get_resume_items(self, limit=20, parent_id=None,
734 include_item_types=None, media_types=None,
735 fields=None, image_type_limit=None,
736 enable_image_types=None,
737 enable_total_record_count=None):
738 """Items the user can resume, most recently played first — the
739 "Continue Watching" row.
740
741 Pass ``media_types="Audio"`` for the audio equivalent ("Continue
742 Listening"); it catches Audio and AudioBook without enumerating types.
743
744 Leaving ``parent_id`` unset is meaningful: the server applies the
745 user's "Display in home screen sections" library exclusions only to
746 queries that carry no ``ParentId``.
747 """
748 return self.get_user_items(
749 parent_id=parent_id, include_item_types=include_item_types,
750 media_types=media_types, recursive=True, filters="IsResumable",
751 sort_by="DatePlayed", sort_order="Descending", limit=limit,
752 fields=fields, image_type_limit=image_type_limit,
753 enable_image_types=enable_image_types,
754 enable_total_record_count=enable_total_record_count)
755
756 def get_random_items(self, parent_id=None, include_item_types=None,
757 limit=100, fields=None, image_types=None,
758 max_official_rating=None, enable_images=None,
759 enable_total_record_count=None, media_types=None):
760 """A random sample of items, shuffled by the server (``SortBy=Random``)
761 so it spans the whole library rather than one loaded page.
762
763 ``image_types`` restricts the result to items that *have* that image
764 (e.g. ``"Backdrop"`` when picking artwork), which is not the same as
765 ``enable_image_types``.
766
767 ``media_types`` (``"Video,Audio"``) filters on what an item *is to a
768 player*, which for "give me something to queue" is usually a better
769 axis than ``include_item_types``: that one matches the concrete
770 entity the library scanner chose, so the answer depends on which
771 resolver ran (a clip in a Home Videos library is a ``Video``, the
772 same file in a movies library a ``Movie``).
773 """
774 return self.get_user_items(
775 parent_id=parent_id, include_item_types=include_item_types,
776 media_types=media_types,
777 recursive=True, sort_by="Random", limit=limit, fields=fields,
778 enable_images=enable_images,
779 enable_total_record_count=enable_total_record_count,
780 params={k: v for k, v in (
781 ('ImageTypes', image_types),
782 ('MaxOfficialRating', max_official_rating),
783 ) if v is not None})
784
785 def get_items_by_person(self, person_id, include_item_types="Movie,Series",
786 sort_by="SortName", sort_order="Ascending",
787 start_index=None, limit=None, fields=None,
788 image_type_limit=None, enable_image_types=None):
789 """A person's filmography — everything they are credited on."""
790 return self.get_user_items(
791 person_ids=person_id, include_item_types=include_item_types,
792 recursive=True, sort_by=sort_by, sort_order=sort_order,
793 start_index=start_index, limit=limit, fields=fields,
794 image_type_limit=image_type_limit,
795 enable_image_types=enable_image_types)
796
797 def get_album_tracks(self, album_id, fields=None):
798 """An album's tracks in disc/track order.
799
800 Sorted by ``ParentIndexNumber`` (disc) before ``IndexNumber`` (track),
801 which is what keeps a multi-disc album in album order rather than
802 interleaving the discs.
803 """
804 return self.get_user_items(
805 parent_id=album_id, fields=fields, sort_order="Ascending",
806 sort_by="ParentIndexNumber,IndexNumber,SortName")
807
808 def get_artist_albums(self, artist_id, fields=None, limit=None,
809 image_type_limit=None, enable_image_types=None):
810 """Albums credited to an album artist, newest first.
811
812 Uses ``AlbumArtistIds``, not ``ArtistIds``: the latter also matches
813 albums the artist merely guests on a track of.
814 """
815 return self.get_user_items(
816 album_artist_ids=artist_id, include_item_types="MusicAlbum",
817 recursive=True, sort_by="PremiereDate,ProductionYear,SortName",
818 sort_order="Descending", limit=limit, fields=fields,
819 image_type_limit=image_type_limit,
820 enable_image_types=enable_image_types)
821
822 def get_artist_songs(self, artist_id, limit=None, fields=None):
823 """Every track an artist appears on, in album order.
824
825 Uses ``ArtistIds`` (not ``AlbumArtistIds``) so featured appearances
826 are included — this backs "play everything by X".
827 """
828 return self.get_user_items(
829 artist_ids=artist_id, include_item_types="Audio", recursive=True,
830 sort_by="AlbumArtist,Album,ParentIndexNumber,IndexNumber,SortName",
831 limit=limit, fields=fields)
832
833 def get_genre_songs(self, genre_id, parent_id=None, limit=None,
834 fields=None):
835 """Every track in a genre, optionally scoped to one music library."""
836 return self.get_user_items(
837 genre_ids=genre_id, parent_id=parent_id,
838 include_item_types="Audio", recursive=True,
839 sort_by="AlbumArtist,Album,ParentIndexNumber,IndexNumber,SortName",
840 limit=limit, fields=fields)
841
842 def get_endpoint_info(self):
843 """Where the server thinks this connection came from (GET
844 System/Endpoint) — ``{"IsLocal": bool, "IsInNetwork": bool}``.
845
846 ``IsInNetwork`` is judged against the admin-configured LAN subnets, so
847 it is the server's own answer to "is this client remote?", which a
848 client cannot always work out for itself (notably over IPv6, where
849 home networks use globally-routable addresses).
850
851 References:
852 .. [GetEndpointInfo] https://api.jellyfin.org/#tag/System/operation/GetEndpointInfo
853 """
854 return self._get("System/Endpoint")
855
856 def update_user_settings(self, data, client="emby"):
857 """Write back the display preferences read by ``get_user_settings``
858 (POST DisplayPreferences/usersettings).
859
860 There is no partial-update path on this API: the server replaces the
861 whole document, so pass a DTO you read with ``get_user_settings`` and
862 mutated, or you will drop settings other clients wrote.
863
864 ``client`` must match the namespace the settings were read from — the
865 official web client uses ``"emby"``, and any other string addresses a
866 different, empty preference set.
867
868 References:
869 .. [UpdateDisplayPreferences] https://api.jellyfin.org/#tag/DisplayPreferences/operation/UpdateDisplayPreferences
870 """
871 return self._post("DisplayPreferences/usersettings", json=data,
872 params={"userId": "{UserId}", "client": client})
873
874 def get_channels(self, limit=None, start_index=None, fields=None,
875 enable_images=True, enable_user_data=True,
876 image_type_limit=None, enable_image_types=None,
877 add_current_program=None, is_favorite=None,
878 sort_by=None, sort_order=None,
879 enable_favorite_sorting=None, is_movie=None,
880 is_series=None, is_news=None, is_kids=None,
881 is_sports=None):
882 """Live TV channels (GET LiveTv/Channels).
883
884 The no-argument call is unbounded, which is only safe for small tuner
885 line-ups: an M3U/IPTV source with thousands of channels answers with
886 all of them, with images and user data. Pass ``limit``/``start_index``
887 to page. Unlike the item endpoints there is no way to skip the total
888 record count — this controller always computes and returns it.
889
890 ``add_current_program`` (server default: true) attaches each channel's
891 currently-airing program, which is what lets a channel list show "what
892 is on now" without a second request to ``get_programs``.
893
894 ``enable_favorite_sorting`` floats favourited channels to the top;
895 ``sort_by="DatePlayed"`` orders by when the user last watched each
896 one. Both are what the official guide's channel-order setting drives.
897
898 The ``is_*`` category flags do NOT combine the way they look like
899 they should. ``is_sports``/``is_news``/``is_kids`` become a tag
900 filter and OR among themselves, but ``is_movie`` is a separate
901 column predicate and ANDs with them — so ``is_movie=True,
902 is_news=True`` asks for a movie that is also tagged News and matches
903 nothing. Passing none of them means "every channel", which is the
904 only way to express it: passing all four is an intersection, not a
905 union. The same is true of ``get_programs``.
906
907 References:
908 .. [GetLiveTvChannels] https://api.jellyfin.org/#tag/LiveTv/operation/GetLiveTvChannels
909 """
910 params = {
911 'UserId': "{UserId}",
912 'EnableImages': enable_images,
913 'EnableUserData': enable_user_data,
914 'Limit': limit,
915 'StartIndex': start_index,
916 'Fields': fields,
917 'ImageTypeLimit': image_type_limit,
918 'EnableImageTypes': enable_image_types,
919 'AddCurrentProgram': add_current_program,
920 'IsFavorite': is_favorite,
921 'SortBy': sort_by,
922 'SortOrder': sort_order,
923 'EnableFavoriteSorting': enable_favorite_sorting,
924 'IsMovie': is_movie,
925 'IsSeries': is_series,
926 'IsNews': is_news,
927 'IsKids': is_kids,
928 'IsSports': is_sports,
929 }
930 return self._get("LiveTv/Channels",
931 {k: v for k, v in params.items() if v is not None})
932
933 def get_programs(self, channel_ids=None, library_series_id=None,
934 min_start_date=None, max_start_date=None,
935 min_end_date=None, max_end_date=None, is_airing=None,
936 is_movie=None, is_series=None, is_news=None,
937 is_kids=None, is_sports=None, genres=None,
938 sort_by=None, sort_order=None, start_index=None,
939 limit=None, fields=None, image_type_limit=None,
940 enable_image_types=None, enable_user_data=None,
941 enable_total_record_count=None,
942 has_aired=None):
943 """Guide entries (GET LiveTv/Programs).
944
945 ``channel_ids`` accepts a list or a comma-separated string, matching
946 the server's comma-delimited binder. ``genres`` does NOT: that one
947 binds pipe-delimited (``value.Split('|')``), so join it with ``|`` or
948 the whole string arrives as a single bogus genre.
949
950 ``has_aired=False`` is what an "upcoming" list asks for; ``is_airing``
951 is the narrower "on right now". They are separate filters, not two
952 spellings of one — the official clients' Programs screen pairs
953 ``has_aired=False`` with the category flags for its upcoming rows.
954
955 The date bounds are how a guide grid asks for one time window. They
956 must be ISO 8601 carrying ``Z`` or an explicit offset — the server
957 binds them with ``AdjustToUniversal``, and an offset-less string
958 (including what ``str(datetime)`` produces) is accepted without being
959 shifted, silently querying the wrong window.
960
961 This is the GET form, so the whole query travels in the request line;
962 past roughly 150-200 channel ids that exceeds the default request-line
963 limit in Kestrel and common reverse proxies (414/431). Page the
964 channel set, as the official guide does. The server also offers a POST
965 form for large line-ups, which is not implemented here.
966
967 Request ``fields="ChannelInfo"`` to get ``ChannelName`` and
968 ``ChannelNumber`` on each program. The channel's **logo** is a
969 separate field: ``AddInfoToProgramDto`` sets
970 ``ChannelPrimaryImageTag`` only under ``ChannelImage``, so ask for
971 ``fields="ChannelInfo,ChannelImage"`` — as the official clients do.
972 That matters more than it sounds, because guide data often carries
973 no artwork of its own and the channel logo is then the only image
974 available at all.
975
976 References:
977 .. [GetLiveTvPrograms] https://api.jellyfin.org/#tag/LiveTv/operation/GetLiveTvPrograms
978 """
979 if channel_ids is not None and not isinstance(channel_ids, str):
980 channel_ids = ','.join(str(x) for x in channel_ids)
981 params = {
982 'UserId': "{UserId}",
983 'ChannelIds': channel_ids,
984 'LibrarySeriesId': library_series_id,
985 'MinStartDate': min_start_date,
986 'MaxStartDate': max_start_date,
987 'MinEndDate': min_end_date,
988 'MaxEndDate': max_end_date,
989 'IsAiring': is_airing,
990 'HasAired': has_aired,
991 'IsMovie': is_movie,
992 'IsSeries': is_series,
993 'IsNews': is_news,
994 'IsKids': is_kids,
995 'IsSports': is_sports,
996 'Genres': genres,
997 'SortBy': sort_by,
998 'SortOrder': sort_order,
999 'StartIndex': start_index,
1000 'Limit': limit,
1001 'Fields': fields,
1002 'ImageTypeLimit': image_type_limit,
1003 'EnableImageTypes': enable_image_types,
1004 'EnableUserData': enable_user_data,
1005 'EnableTotalRecordCount': enable_total_record_count,
1006 }
1007 return self._get("LiveTv/Programs",
1008 {k: v for k, v in params.items() if v is not None})
1009
1010 def get_recommended_programs(self, is_airing=None, has_aired=None,
1011 is_series=None, is_movie=None, is_news=None,
1012 is_kids=None, is_sports=None, genre_ids=None,
1013 limit=None, fields=None,
1014 image_type_limit=None,
1015 enable_image_types=None,
1016 enable_user_data=None,
1017 enable_total_record_count=None):
1018 """The server's recommended guide entries (GET
1019 LiveTv/Programs/Recommended).
1020
1021 ``is_airing=True`` is the "On Now" strip the official clients show on
1022 the home screen. As with ``get_programs``, pass
1023 ``fields="…,ChannelInfo,ChannelImage"`` or most entries will have no
1024 artwork — the logo needs the second of those, see there.
1025
1026 References:
1027 .. [GetRecommendedPrograms] https://api.jellyfin.org/#tag/LiveTv/operation/GetRecommendedPrograms
1028 """
1029 params = {
1030 'UserId': "{UserId}",
1031 'IsAiring': is_airing,
1032 'HasAired': has_aired,
1033 'IsSeries': is_series,
1034 'IsMovie': is_movie,
1035 'IsNews': is_news,
1036 'IsKids': is_kids,
1037 'IsSports': is_sports,
1038 'GenreIds': genre_ids,
1039 'Limit': limit,
1040 'Fields': fields,
1041 'ImageTypeLimit': image_type_limit,
1042 'EnableImageTypes': enable_image_types,
1043 'EnableUserData': enable_user_data,
1044 'EnableTotalRecordCount': enable_total_record_count,
1045 }
1046 return self._get("LiveTv/Programs/Recommended",
1047 {k: v for k, v in params.items() if v is not None})
1048
1049 def get_live_tv_program(self, program_id):
1050 """One guide entry, with its recording state (GET
1051 LiveTv/Programs/{id}).
1052
1053 The ``TimerId``/``SeriesTimerId``/``Status`` fields this carries are
1054 what a program page needs to decide whether its Record button reads
1055 "Record" or "Cancel Recording" — the list endpoints omit them unless
1056 user data is enabled, and even then are a snapshot from before the
1057 user pressed anything.
1058
1059 References:
1060 .. [GetProgram] https://api.jellyfin.org/#tag/LiveTv/operation/GetProgram
1061 """
1062 return self._get("LiveTv/Programs/%s" % program_id,
1063 {'UserId': "{UserId}"})
1064
1065 def get_live_tv_guide_info(self):
1066 """The guide's available date range (GET LiveTv/GuideInfo).
1067
1068 ``StartDate``/``EndDate`` bound how far the date picker may go; a
1069 guide that offers days the provider has no data for just shows empty
1070 rows.
1071
1072 References:
1073 .. [GetGuideInfo] https://api.jellyfin.org/#tag/LiveTv/operation/GetGuideInfo
1074 """
1075 return self._get("LiveTv/GuideInfo")
1076
1077 def get_live_tv_recordings(self, series_timer_id=None, is_in_progress=None,
1078 status=None, start_index=None, limit=None,
1079 fields=None, enable_images=None,
1080 image_type_limit=None, enable_image_types=None,
1081 enable_user_data=None,
1082 enable_total_record_count=None):
1083 """Completed and in-progress recordings (GET LiveTv/Recordings).
1084
1085 ``is_in_progress=True`` is the "recording right now" list; the
1086 unfiltered call is the recordings library. Recordings are ordinary
1087 items once written, so they play through the normal item path.
1088
1089 References:
1090 .. [GetRecordings] https://api.jellyfin.org/#tag/LiveTv/operation/GetRecordings
1091 """
1092 params = {
1093 'UserId': "{UserId}",
1094 'SeriesTimerId': series_timer_id,
1095 'IsInProgress': is_in_progress,
1096 'Status': status,
1097 'StartIndex': start_index,
1098 'Limit': limit,
1099 'Fields': fields,
1100 'EnableImages': enable_images,
1101 'ImageTypeLimit': image_type_limit,
1102 'EnableImageTypes': enable_image_types,
1103 'EnableUserData': enable_user_data,
1104 'EnableTotalRecordCount': enable_total_record_count,
1105 }
1106 return self._get("LiveTv/Recordings",
1107 {k: v for k, v in params.items() if v is not None})
1108
1109 def get_recording_folders(self):
1110 """The virtual folders recordings are filed under (GET
1111 LiveTv/Recordings/Folders) — one per recording group the server
1112 keeps, which is what the Recordings screen browses into.
1113
1114 References:
1115 .. [GetRecordingFolders] https://api.jellyfin.org/#tag/LiveTv/operation/GetRecordingFolders
1116 """
1117 return self._get("LiveTv/Recordings/Folders",
1118 {'UserId': "{UserId}"})
1119
1120 def get_live_tv_timers(self, channel_id=None, series_timer_id=None,
1121 is_active=None, is_scheduled=None):
1122 """Scheduled single recordings (GET LiveTv/Timers).
1123
1124 ``is_active=False, is_scheduled=True`` is the "Upcoming Recordings"
1125 list; ``is_active=True`` is what is recording now. The DTOs are
1126 ``Timer`` objects, not items — they carry ``ProgramId``, the channel
1127 and the start/end times, and are addressed by their own ``Id``.
1128
1129 References:
1130 .. [GetTimers] https://api.jellyfin.org/#tag/LiveTv/operation/GetTimers
1131 """
1132 params = {
1133 'ChannelId': channel_id,
1134 'SeriesTimerId': series_timer_id,
1135 'IsActive': is_active,
1136 'IsScheduled': is_scheduled,
1137 }
1138 return self._get("LiveTv/Timers",
1139 {k: v for k, v in params.items() if v is not None})
1140
1141 def get_live_tv_timer(self, timer_id):
1142 """One timer, for the recording editor (GET LiveTv/Timers/{id})."""
1143 return self._get("LiveTv/Timers/%s" % timer_id)
1144
1145 def get_new_timer_defaults(self, program_id=None):
1146 """A pre-filled timer for ``program_id`` (GET LiveTv/Timers/Defaults).
1147
1148 This is how a recording is created: ask the server for the defaults
1149 (padding, keep-until, and the program's own channel and times), then
1150 POST the result back — creating one from a hand-built DTO skips the
1151 server's own configuration.
1152
1153 Called without ``program_id`` it returns the bare defaults, which is
1154 what the series-timer editor shows for a new series rule.
1155
1156 References:
1157 .. [GetDefaultTimer] https://api.jellyfin.org/#tag/LiveTv/operation/GetDefaultTimer
1158 """
1159 params = {'programId': program_id} if program_id else None
1160 return self._get("LiveTv/Timers/Defaults", params)
1161
1162 def create_live_tv_timer(self, timer):
1163 """Schedule a single recording from a ``get_new_timer_defaults``
1164 payload (POST LiveTv/Timers)."""
1165 return self._post("LiveTv/Timers", json=timer)
1166
1167 def update_live_tv_timer(self, timer_id, timer):
1168 """Rewrite a timer (POST LiveTv/Timers/{id}). The whole DTO is
1169 replaced, so send one you read back from ``get_live_tv_timer``."""
1170 return self._post("LiveTv/Timers/%s" % timer_id, json=timer)
1171
1172 def cancel_live_tv_timer(self, timer_id):
1173 """Cancel a scheduled recording, or stop one in progress (DELETE
1174 LiveTv/Timers/{id})."""
1175 return self._delete("LiveTv/Timers/%s" % timer_id)
1176
1177 def get_live_tv_series_timers(self, sort_by=None, sort_order=None):
1178 """Series recording rules (GET LiveTv/SeriesTimers).
1179
1180 References:
1181 .. [GetSeriesTimers] https://api.jellyfin.org/#tag/LiveTv/operation/GetSeriesTimers
1182 """
1183 params = {'SortBy': sort_by, 'SortOrder': sort_order}
1184 return self._get("LiveTv/SeriesTimers",
1185 {k: v for k, v in params.items() if v is not None})
1186
1187 def get_live_tv_series_timer(self, timer_id):
1188 """One series rule, for the series editor (GET
1189 LiveTv/SeriesTimers/{id})."""
1190 return self._get("LiveTv/SeriesTimers/%s" % timer_id)
1191
1192 def create_live_tv_series_timer(self, timer):
1193 """Record every showing of a program (POST LiveTv/SeriesTimers).
1194
1195 Takes the same ``get_new_timer_defaults`` payload the single-recording
1196 path uses; the server derives the series rule from the program it was
1197 seeded with.
1198 """
1199 return self._post("LiveTv/SeriesTimers", json=timer)
1200
1201 def update_live_tv_series_timer(self, timer_id, timer):
1202 """Rewrite a series rule (POST LiveTv/SeriesTimers/{id})."""
1203 return self._post("LiveTv/SeriesTimers/%s" % timer_id, json=timer)
1204
1205 def cancel_live_tv_series_timer(self, timer_id):
1206 """Stop recording a series (DELETE LiveTv/SeriesTimers/{id})."""
1207 return self._delete("LiveTv/SeriesTimers/%s" % timer_id)
1208
1209 def get_intros(self, item_id):
1210 return self.user_items("/%s/Intros" % item_id)
1211
1212 def get_additional_parts(self, item_id):
1213 return self.videos("/%s/AdditionalParts" % item_id)
1214
1215 def get_media_segments(self, item_id, include_segment_types=None):
1216 """Media segments (intros, outros, previews, …) for an item.
1217
1218 ``include_segment_types`` takes a list of segment type names; the
1219 server repeats the parameter per type. Segments come from a plugin, so
1220 an item can legitimately have none.
1221 """
1222 params = None
1223 if include_segment_types is not None:
1224 if isinstance(include_segment_types, str):
1225 include_segment_types = [include_segment_types]
1226 params = {'includeSegmentTypes': list(include_segment_types)}
1227 return self.media_segments("/%s" % item_id, params)
1228
1229 def delete_item(self, item_id):
1230 return self.items("/%s" % item_id, "DELETE")
1231
1232 def get_local_trailers(self, item_id):
1233 return self.user_items("/%s/LocalTrailers" % item_id)
1234
1235 def get_similar(self, item_id, limit=12, fields=None):
1236 """Items similar to the given one (GET Items/{id}/Similar) — the
1237 "More Like This" row in the official clients.
1238
1239 References:
1240 .. [GetSimilarItems] https://api.jellyfin.org/#tag/Library/operation/GetSimilarItems
1241 """
1242 params = {"UserId": "{UserId}", "Limit": limit}
1243 if fields is not None:
1244 params["Fields"] = fields
1245 return self.items("/%s/Similar" % item_id, params=params)
1246
1247 def get_filters(self, parent_id=None, include_item_types=None):
1248 """Distinct filter values (genres, tags, official ratings, years)
1249 available under a folder (GET Items/Filters) — used to build filter
1250 pickers without scanning the whole library client-side.
1251
1252 References:
1253 .. [GetQueryFiltersLegacy] https://api.jellyfin.org/#tag/Filter/operation/GetQueryFiltersLegacy
1254 """
1255 params = {"UserId": "{UserId}"}
1256 if parent_id is not None:
1257 params["ParentId"] = parent_id
1258 if include_item_types is not None:
1259 params["IncludeItemTypes"] = include_item_types
1260 return self.items("/Filters", params=params)
1261
1262 def get_persons(self, search_term=None, limit=20, fields=None):
1263 """Search people (GET Persons) — actors/directors for people search.
1264
1265 References:
1266 .. [GetPersons] https://api.jellyfin.org/#tag/Persons/operation/GetPersons
1267 """
1268 params = {"UserId": "{UserId}", "Limit": limit}
1269 if search_term is not None:
1270 params["SearchTerm"] = search_term
1271 if fields is not None:
1272 params["Fields"] = fields
1273 return self._get("Persons", params)
1274
1275 def get_transcode_settings(self):
1276 return self._get('System/Configuration/encoding')
1277
1278 def get_ancestors(self, item_id):
1279 return self.items("/%s/Ancestors" % item_id, params={
1280 'UserId': "{UserId}"
1281 })
1282
1283 def get_items_theme_video(self, parent_id):
1284 return self.users("/Items", params={
1285 'HasThemeVideo': True,
1286 'ParentId': parent_id
1287 })
1288
1289 def get_themes(self, item_id):
1290 return self.items("/%s/ThemeMedia" % item_id, params={
1291 'UserId': "{UserId}",
1292 'InheritFromParent': True
1293 })
1294
1295 def get_items_theme_song(self, parent_id):
1296 return self.users("/Items", params={
1297 'HasThemeSong': True,
1298 'ParentId': parent_id
1299 })
1300
1301 def get_plugins(self):
1302 return self._get("Plugins")
1303
1304 def check_companion_installed(self):
1305 try:
1306 self._get("/Jellyfin.Plugin.KodiSyncQueue/GetServerDateTime")
1307 return True
1308 except Exception:
1309 return False
1310
1311 def get_seasons(self, show_id):
1312 return self.shows("/%s/Seasons" % show_id, params={
1313 'UserId': "{UserId}",
1314 'EnableImages': True,
1315 'Fields': info()
1316 })
1317
1318 def get_date_modified(self, date, parent_id, media=None):
1319 return self.users("/Items", params={
1320 'ParentId': parent_id,
1321 'Recursive': False,
1322 'IsMissing': False,
1323 'IsVirtualUnaired': False,
1324 'IncludeItemTypes': media or None,
1325 'MinDateLastSaved': date,
1326 'Fields': info()
1327 })
1328
1329 def get_userdata_date_modified(self, date, parent_id, media=None):
1330 return self.users("/Items", params={
1331 'ParentId': parent_id,
1332 'Recursive': True,
1333 'IsMissing': False,
1334 'IsVirtualUnaired': False,
1335 'IncludeItemTypes': media or None,
1336 'MinDateLastSavedForUser': date,
1337 'Fields': info()
1338 })
1339
1340 def get_userdata_for_item(self, item_id):
1341 return self._get(
1342 f"UserItems/{item_id}/UserData", params={"UserId": "{UserId}"}
1343 )
1344
1345 def update_userdata_for_item(self, item_id, data):
1346 """
1347 Updates the userdata for an item.
1348
1349 Args:
1350 item_id (str): item uuid to update userdata for
1351
1352 data (dict): the information to add to the current user's
1353 userdata for the item. Any fields in data overwrite the
1354 equivalent fields in UserData, other UserData fields are
1355 left untouched.
1356
1357 References:
1358 .. [UpdateItemUserData] https://api.jellyfin.org/#tag/Items/operation/UpdateItemUserData
1359 """
1360 return self._post(f"UserItems/{item_id}/UserData", params={"UserId": "{UserId}"}, json=data)
1361
1362
1363 def refresh_item(self, item_id, recursive=True, image_refresh='FullRefresh', metadata_refresh='FullRefresh', replace_images=False, replace_metadata=True, preset=None):
1364 """
1365 Description:
1366
1367 - Refreshes media items on server. Pass a single item or pass multiple as a list.
1368 - Use of presets lets you run a refresh similar to Jellyfin's Web UI.
1369 - preset='missing' searches for missing metadata, while preset='replace' replaces all metadata.
1370 - You may also configure the refresh manually by passing a value for each parameter.
1371
1372 Args:
1373 item_id (str | List[str]): one or more items to refresh
1374 recursive (bool):
1375 image_refresh (str): 'Default' or 'ValidationOnly' or 'FullRefresh'
1376 image_refresh (str): 'Default' or 'ValidationOnly' or 'FullRefresh'
1377 replace_images (bool):
1378 replace_metadata (bool)
1379 preset (str): 'missing' or 'replace'
1380
1381 Examples:
1382 >>> client.jellyfin.refresh_item('123456abcd', preset='missing')
1383 -
1384 >>> client.jellyfin.refresh_item(['123456abcd', 'abcd123456'])
1385 """
1386
1387 # Presets modeled after Jellyfin's Web UI
1388 if preset:
1389 if preset.lower() == 'missing':
1390 recursive = True
1391 image_refresh = 'FullRefresh'
1392 metadata_refresh = 'FullRefresh'
1393 replace_images = False
1394 replace_metadata = False
1395 elif preset.lower() == 'replace':
1396 recursive = True
1397 image_refresh = 'FullRefresh'
1398 metadata_refresh = 'FullRefresh'
1399 replace_images = True
1400 replace_metadata = True
1401
1402 params = {
1403 'Recursive': recursive,
1404 'ImageRefreshMode': image_refresh,
1405 'MetadataRefreshMode': metadata_refresh,
1406 'ReplaceAllImages': replace_images,
1407 'ReplaceAllMetadata': replace_metadata
1408 }
1409
1410 # If item_id is a list, loop through each item and refresh it
1411 if isinstance(item_id, list):
1412 results = []
1413 for i in item_id:
1414 result = self.items("/%s/Refresh" % i, "POST", params=params)
1415 results.append(result)
1416 return results
1417 else:
1418 # If item_id is a single string, just refresh that item
1419 return self.items("/%s/Refresh" % item_id, "POST", params=params)
1420
1421 def favorite(self, item_id, option=True):
1422 return self.users("/FavoriteItems/%s" % item_id, "POST" if option else "DELETE")
1423
1424 def get_system_info(self):
1425 """Returns configuration for legacy reasons, not System/Info, use get_system_info_new for that"""
1426 return self._get("System/Configuration")
1427
1428 def get_system_info_new(self):
1429 """Actual System/Info API call"""
1430 return self._get("System/Info")
1431
1432 def get_system_configuration(self):
1433 return self._get("System/Configuration")
1434
1435 def get_server_logs(self):
1436 """
1437 Returns:
1438 List[Dict] - list of information about available log files
1439
1440 References:
1441 .. [GetServerLogs] https://api.jellyfin.org/#tag/System/operation/GetServerLogs
1442 """
1443 return self._get("System/Logs")
1444
1445 def get_log_entries(self, startIndex=None, limit=None, minDate=None, hasUserId=None):
1446 """
1447 Returns a list of recent log entries
1448
1449 Returns:
1450 Dict: with main key "Items"
1451 """
1452 params = {}
1453 if limit is not None:
1454 params['limit'] = limit
1455 if startIndex is not None:
1456 params['startIndex'] = startIndex
1457 if minDate is not None:
1458 params['minDate'] = minDate
1459 if hasUserId is not None:
1460 params['hasUserId'] = hasUserId
1461 return self._get("System/ActivityLog/Entries", params=params)
1462
1463 def post_capabilities(self, data):
1464 return self.sessions("/Capabilities/Full", "POST", json=data)
1465
1466 def session_add_user(self, session_id, user_id, option=True):
1467 return self.sessions("/%s/Users/%s" % (session_id, user_id), "POST" if option else "DELETE")
1468
1469 def session_playing(self, data):
1470 return self.sessions("/Playing", "POST", json=data)
1471
1472 def session_progress(self, data):
1473 return self.sessions("/Playing/Progress", "POST", json=data)
1474
1475 def session_stop(self, data):
1476 return self.sessions("/Playing/Stopped", "POST", json=data)
1477
1478 def remote_pause(self, id):
1479 return self.remote(id, "Pause")
1480
1481 def remote_playpause(self, id):
1482 return self.remote(id, "PlayPause")
1483
1484 def remote_seek(self, id, ticks, params={}, json={}):
1485 """
1486 Seek to a specific position in the specified session.
1487
1488 Args:
1489 id (int): The session id to control
1490 ticks (int): The position (in ticks) to seek to
1491 """
1492 return self.remote(
1493 id, "Seek", params={"seekPositionTicks": ticks, **params}, json=json
1494 )
1495
1496 def remote_stop(self, id):
1497 return self.remote(id, "Stop")
1498
1499 def remote_unpause(self, id):
1500 return self.remote(id, "Unpause")
1501
1502 def remote_play_media(
1503 self, id: str, item_ids: List[str], command: str = "PlayNow", params={}, json={}
1504 ):
1505 """Instruct the session to play some media
1506
1507 Args:
1508 id (str): The session id to control
1509 item_ids (List[str]): A list of items to play
1510 command (str): When to play. (*PlayNow*, PlayNext, PlayLast, PlayInstantMix, PlayShuffle)
1511 """
1512 return self.remote(
1513 id,
1514 None,
1515 json=json,
1516 params={"playCommand": command, "itemIds": item_ids, **params},
1517 )
1518
1519 def remote_set_volume(self, id: str, volume: int, json={}):
1520 """
1521 Set the volume on the sessions.
1522
1523 Args:
1524 id (int): The session id to control
1525 volume (int): The volume normalized from 0 to 100
1526 """
1527 return self.command(id, "SetVolume", json={"Volume": volume, **json})
1528
1529 def remote_mute(self, id):
1530 return self.command(id, "Mute")
1531
1532 def remote_unmute(self, id):
1533 return self.command(id, "Unmute")
1534
1535 def item_played(self, item_id, watched, date=None):
1536 params = {}
1537 if watched and date is not None:
1538 params["datePlayed"] = date
1539 return self.users("/PlayedItems/%s" % item_id, "POST" if watched else "DELETE", params=params)
1540
1541 def get_sync_queue(self, date, filters=None):
1542 return self._get("Jellyfin.Plugin.KodiSyncQueue/{UserId}/GetItems", params={
1543 'LastUpdateDT': date,
1544 'filter': filters or None
1545 })
1546
1547 def get_server_time(self):
1548 return self._get("Jellyfin.Plugin.KodiSyncQueue/GetServerDateTime")
1549
1550 def get_play_info(self, item_id, profile=None, aid=None, sid=None, start_time_ticks=None, is_playback=True, media_source_id=None):
1551 args = {
1552 'UserId': "{UserId}",
1553 'AutoOpenLiveStream': is_playback,
1554 'IsPlayback': is_playback
1555 }
1556 if profile is not None:
1557 args['DeviceProfile'] = profile
1558 if sid:
1559 args['SubtitleStreamIndex'] = sid
1560 if aid:
1561 args['AudioStreamIndex'] = aid
1562 if start_time_ticks:
1563 args['StartTimeTicks'] = start_time_ticks
1564 if media_source_id:
1565 args['MediaSourceId'] = media_source_id
1566
1567 return self.items("/%s/PlaybackInfo" % item_id, "POST", json=args)
1568
1569 def get_live_stream(self, item_id, play_id, token, profile):
1570 return self._post("LiveStreams/Open", json={
1571 'UserId': "{UserId}",
1572 'DeviceProfile': profile,
1573 'OpenToken': token,
1574 'PlaySessionId': play_id,
1575 'ItemId': item_id
1576 })
1577
1578 def close_live_stream(self, live_id):
1579 """Release a live stream and the tuner behind it.
1580
1581 The id goes in the query string because that is where the server binds
1582 it (``CloseLiveStream([FromQuery, Required] string liveStreamId)``);
1583 sent as a JSON body it fails model validation with a 400 and the
1584 stream is never closed. Nothing reaps a leaked stream — it is freed
1585 only by this call, a stop report carrying the ``LiveStreamId``, a
1586 session disconnect, or a server restart — so on a single-tuner box a
1587 leak means no more live TV until the server comes back.
1588 """
1589 return self._post("LiveStreams/Close",
1590 params={'liveStreamId': live_id})
1591
1592 def close_transcode(self, device_id, play_session_id):
1593 return self._delete("Videos/ActiveEncodings", params={
1594 'DeviceId': device_id,
1595 'PlaySessionId': play_session_id,
1596 })
1597
1598 def get_audio_stream(self, dest_file, item_id, play_id, container, max_streaming_bitrate=140000000, audio_codec=None):
1599 self._get_stream("Audio/%s/universal" % item_id, dest_file, params={
1600 'UserId': "{UserId}",
1601 'DeviceId': "{DeviceId}",
1602 'PlaySessionId': play_id,
1603 'Container': container,
1604 'AudioCodec': audio_codec,
1605 "MaxStreamingBitrate": max_streaming_bitrate,
1606 })
1607
1608 def get_chapter_image(self, dest_file, item_id, index, tag=None,
1609 max_width=None, quality=None):
1610 """Download one chapter thumbnail into ``dest_file``.
1611
1612 ``index`` is the chapter's position in the item's ``Chapters`` list;
1613 ``tag`` is that chapter's ``ImageTag`` and is what makes the URL
1614 cacheable. Chapters without an ``ImageTag`` have no image — asking for
1615 one is a 404.
1616
1617 Use ``image_url(item_id, "Chapter", index=…, tag=…)`` instead when a
1618 URL is wanted rather than the bytes.
1619 """
1620 params = {'tag': tag, 'maxWidth': max_width, 'quality': quality}
1621 self._get_stream(
1622 "Items/%s/Images/Chapter/%s" % (item_id, index), dest_file,
1623 {k: v for k, v in params.items() if v is not None})
1624
1625 def get_trickplay_tile(self, dest_file, item_id, width, index,
1626 media_source_id=None):
1627 """Download one trickplay (scrubbing preview) tile sheet into
1628 ``dest_file``.
1629
1630 ``width`` selects which generated resolution to read and must be one
1631 the server actually produced — the item's ``Trickplay`` manifest lists
1632 them (request the ``Trickplay`` field to get it).
1633
1634 See ``trickplay_tile_url`` for the URL-building equivalent.
1635 """
1636 params = {}
1637 if media_source_id is not None:
1638 params['MediaSourceId'] = media_source_id
1639 self._get_stream(
1640 "Videos/%s/Trickplay/%s/%s.jpg" % (item_id, width, index),
1641 dest_file, params)
1642
1643 def get_default_headers(self):
1644 return self.client._get_default_headers(content_type="application/x-www-form-urlencoded; charset=UTF-8")
1645
1646 def send_request(self, url, path, method="get", timeout=None, headers=None, data=None, session=None):
1647 request_method = getattr(session or requests, method.lower())
1648 url = "%s/%s" % (url, path)
1649 request_settings = {
1650 "timeout": timeout or self.default_timeout,
1651 "headers": headers or self.get_default_headers(),
1652 "data": data
1653 }
1654
1655 # Changed to use non-Kodi specific setting.
1656 if self.config.data.get('auth.ssl') is False:
1657 request_settings["verify"] = False
1658
1659 LOG.info("Sending %s request to %s" % (method, path))
1660 LOG.debug(request_settings['timeout'])
1661 LOG.debug(request_settings['headers'])
1662
1663 return request_method(url, **request_settings)
1664
1665 def login(self, server_url, username, password="", session=None):
1666 path = "Users/AuthenticateByName"
1667 authData = {
1668 "username": username,
1669 "Pw": password
1670 }
1671
1672 headers = self.get_default_headers()
1673 headers.update({'Content-type': "application/json"})
1674
1675 try:
1676 LOG.info("Trying to login to %s/%s as %s" % (server_url, path, username))
1677 response = self.send_request(server_url, path, method="post", headers=headers,
1678 data=json.dumps(authData), timeout=(5, 30), session=session)
1679
1680 if response.status_code == 200:
1681 return response.json()
1682 else:
1683 LOG.error("Failed to login to server with status code: " + str(response.status_code))
1684 LOG.error("Server Response:\n" + str(response.content))
1685 LOG.debug(headers)
1686
1687 return {}
1688 except Exception as e: # Find exceptions for likely cases i.e, server timeout, etc
1689 LOG.error(e)
1690
1691 return {}
1692
1693 def quick_connect_enabled(self, server_url, session=None):
1694 """Return whether Quick Connect is enabled on the server."""
1695 try:
1696 response = self.send_request(
1697 server_url, "QuickConnect/Enabled", session=session
1698 )
1699 if response.status_code == 200:
1700 return bool(response.json())
1701 LOG.error(
1702 "Failed to query Quick Connect status: " + str(response.status_code)
1703 )
1704 except Exception as e:
1705 LOG.error(e)
1706
1707 return False
1708
1709 def quick_connect_initiate(self, server_url, session=None):
1710 """Start a Quick Connect request, returning a dict with Secret and Code."""
1711 headers = self.get_default_headers()
1712
1713 try:
1714 response = self.send_request(
1715 server_url, "QuickConnect/Initiate", method="post",
1716 headers=headers, timeout=(5, 30), session=session
1717 )
1718 if response.status_code == 200:
1719 return response.json()
1720 LOG.error(
1721 "Failed to initiate Quick Connect: " + str(response.status_code)
1722 )
1723 except Exception as e:
1724 LOG.error(e)
1725
1726 return {}
1727
1728 def quick_connect_state(self, server_url, secret, session=None):
1729 """Return the current state of a Quick Connect request as a dict.
1730
1731 The returned dict's ``Authenticated`` field indicates whether the user
1732 has approved the request yet.
1733 """
1734 path = "QuickConnect/Connect?secret=" + quote(secret, safe="")
1735
1736 try:
1737 response = self.send_request(server_url, path, session=session)
1738 if response.status_code == 200:
1739 return response.json()
1740 LOG.error(
1741 "Failed to query Quick Connect state: " + str(response.status_code)
1742 )
1743 except Exception as e:
1744 LOG.error(e)
1745
1746 return {}
1747
1748 def login_with_quick_connect(self, server_url, secret, session=None):
1749 """Exchange an authorized Quick Connect secret for an AuthenticationResult.
1750
1751 Returns the same payload shape as ``login()`` (AccessToken, User, ...)
1752 on success, or an empty dict on failure.
1753 """
1754 path = "Users/AuthenticateWithQuickConnect"
1755 authData = {"Secret": secret}
1756
1757 headers = self.get_default_headers()
1758 headers.update({'Content-type': "application/json"})
1759
1760 try:
1761 response = self.send_request(
1762 server_url, path, method="post", headers=headers,
1763 data=json.dumps(authData), timeout=(5, 30), session=session
1764 )
1765 if response.status_code == 200:
1766 return response.json()
1767 LOG.error(
1768 "Failed to authenticate with Quick Connect, status code: "
1769 + str(response.status_code)
1770 )
1771 LOG.error("Server Response:\n" + str(response.content))
1772 except Exception as e:
1773 LOG.error(e)
1774
1775 return {}
1776
1777 def validate_authentication_token(self, server, session=None):
1778 headers = self.get_default_headers()
1779 comma = "," if "app.device_name" in self.config.data else ""
1780 headers["Authorization"] += f"{comma} Token=\"{server['AccessToken']}\""
1781
1782 response = self.send_request(server['address'], "system/info", headers=headers, session=session)
1783 return response.json() if response.status_code == 200 else {}
1784
1785 def get_public_info(self, server_address, session=None):
1786 response = self.send_request(server_address, "system/info/public", session=session)
1787 return response.json() if response.status_code == 200 else {}
1788
1789 def check_redirect(self, server_address, session=None):
1790 ''' Checks if the server is redirecting traffic to a new URL and
1791 returns the URL the server prefers to use
1792 '''
1793 response = self.send_request(server_address, "system/info/public", session=session)
1794 url = response.url.replace('/system/info/public', '')
1795 return url
1796
1797
1798 class SyncPlayAPIMixin:
1799 """
1800 Mixin class containing Jellyfin API calls related to Syncplay
1801 """
1802
1803 def _parse_precise_time(self, time):
1804 # We have to remove the Z and the least significant digit.
1805 return datetime.strptime(time[:-2], "%Y-%m-%dT%H:%M:%S.%f")
1806
1807 def utc_time(self):
1808 # Measure time as close to the call as is possible.
1809 server_address = self.config.data.get("auth.server")
1810 session = self.client.session
1811
1812 response = self.send_request(server_address, "GetUTCTime", session=session)
1813 response_received = datetime.utcnow()
1814 request_sent = response_received - response.elapsed
1815
1816 response_obj = response.json()
1817 request_received = self._parse_precise_time(response_obj["RequestReceptionTime"])
1818 response_sent = self._parse_precise_time(response_obj["ResponseTransmissionTime"])
1819
1820 return {
1821 "request_sent": request_sent,
1822 "request_received": request_received,
1823 "response_sent": response_sent,
1824 "response_received": response_received
1825 }
1826
1827 def get_sync_play(self, item_id=None):
1828 params = {}
1829 if item_id is not None:
1830 params["FilterItemId"] = item_id
1831 return self._get("SyncPlay/List", params)
1832
1833 def join_sync_play(self, group_id):
1834 return self._post("SyncPlay/Join", {
1835 "GroupId": group_id
1836 })
1837
1838 def leave_sync_play(self):
1839 return self._post("SyncPlay/Leave")
1840
1841 def play_sync_play(self):
1842 """deprecated (<= 10.7.0)"""
1843 return self._post("SyncPlay/Play")
1844
1845 def pause_sync_play(self):
1846 return self._post("SyncPlay/Pause")
1847
1848 def unpause_sync_play(self):
1849 """10.7.0+ only"""
1850 return self._post("SyncPlay/Unpause")
1851
1852 def seek_sync_play(self, position_ticks):
1853 return self._post("SyncPlay/Seek", {
1854 "PositionTicks": position_ticks
1855 })
1856
1857 def buffering_sync_play(self, when, position_ticks, is_playing, item_id):
1858 return self._post("SyncPlay/Buffering", {
1859 "When": when.isoformat() + "Z",
1860 "PositionTicks": position_ticks,
1861 "IsPlaying": is_playing,
1862 "PlaylistItemId": item_id
1863 })
1864
1865 def ready_sync_play(self, when, position_ticks, is_playing, item_id):
1866 """10.7.0+ only"""
1867 return self._post("SyncPlay/Ready", {
1868 "When": when.isoformat() + "Z",
1869 "PositionTicks": position_ticks,
1870 "IsPlaying": is_playing,
1871 "PlaylistItemId": item_id
1872 })
1873
1874 def reset_queue_sync_play(self, queue_item_ids, position=0, position_ticks=0):
1875 """10.7.0+ only"""
1876 return self._post("SyncPlay/SetNewQueue", {
1877 "PlayingQueue": queue_item_ids,
1878 "PlayingItemPosition": position,
1879 "StartPositionTicks": position_ticks
1880 })
1881
1882 def ignore_sync_play(self, should_ignore):
1883 """10.7.0+ only"""
1884 return self._post("SyncPlay/SetIgnoreWait", {
1885 "IgnoreWait": should_ignore
1886 })
1887
1888 def next_sync_play(self, item_id):
1889 """10.7.0+ only"""
1890 return self._post("SyncPlay/NextItem", {
1891 "PlaylistItemId": item_id
1892 })
1893
1894 def prev_sync_play(self, item_id):
1895 """10.7.0+ only"""
1896 return self._post("SyncPlay/PreviousItem", {
1897 "PlaylistItemId": item_id
1898 })
1899
1900 def set_item_sync_play(self, item_id):
1901 """10.7.0+ only"""
1902 return self._post("SyncPlay/SetPlaylistItem", {
1903 "PlaylistItemId": item_id
1904 })
1905
1906 def ping_sync_play(self, ping):
1907 return self._post("SyncPlay/Ping", {
1908 "Ping": ping
1909 })
1910
1911 def new_sync_play(self):
1912 """deprecated (< 10.7.0)"""
1913 return self._post("SyncPlay/New")
1914
1915 def new_sync_play_v2(self, group_name):
1916 """10.7.0+ only"""
1917 return self._post("SyncPlay/New", {
1918 "GroupName": group_name
1919 })
1920
1921
1922 class ExperimentalAPIMixin:
1923 """
1924 This is a location for testing proposed additions to the API Client.
1925 """
1926
1927 def identify(self, item_id, name=None, provider_ids=None, year=None, replaceAllImages=True):
1928 """
1929 Applies search criteria to an item and refreshes metadata.
1930
1931 This method requires an authenticated user with elevated permissions
1932 [RequiresElevation]_.
1933
1934 Args:
1935 item_id (str): item uuid to identify and update metadata for.
1936
1937 name (str):
1938 name for the identified item
1939 provider_ids (dict):
1940 maps providers to the content id. (E.g. {"Imdb": "tt1254207"})
1941 Valid keys will depend on available providers. Common ones are:
1942 "Tvdb" and "Imdb".
1943 year (int):
1944 production year for the identified idem
1945 replaceAllImages(bool):
1946 whether all images should be replaced by default
1947
1948 References:
1949 .. [ApplySearchCriteria] https://api.jellyfin.org/#tag/ItemLookup/operation/ApplySearchCriteria
1950 """
1951
1952 data = {
1953 'Name': name,
1954 'ProviderIds': provider_ids,
1955 'ProductionYear': year
1956 }
1957 params = {
1958 'replaceAllImages': replaceAllImages
1959 }
1960
1961 return self._post(
1962 f'Items/RemoteSearch/Apply/{item_id}', params=params, json=data
1963 )
1964
1965
1966 def get_now_playing(self, session_id):
1967 """
1968 Simplified API to get now playing information for a session including the
1969 play state.
1970
1971 References:
1972 https://github.com/jellyfin/jellyfin/issues/9665
1973 """
1974 resp = self.sessions(params={
1975 'Id': session_id,
1976 'fields': ['PlayState']
1977 })
1978 found = None
1979 for item in resp:
1980 if item['Id'] == session_id:
1981 found = item
1982 if not found:
1983 raise KeyError(f'No session_id={session_id}')
1984 play_state = found['PlayState']
1985 now_playing = found.get('NowPlayingItem', None)
1986 if now_playing is None:
1987 # handle case if nothing is playing
1988 now_playing = {'Name': None}
1989 now_playing['PlayState'] = play_state
1990 return now_playing
1991
1992 @staticmethod
1993 def _coerce_image_bytes(image_data) -> bytes:
1994 """
1995 Transform data into a common b64 representation with associated mime
1996 type
1997 """
1998 import os
1999 import base64
2000 import mimetypes
2001
2002 image_bytes = None
2003
2004 # It doesn't seem to matter which image mimetype we choose
2005 mimetype = 'image/jpeg'
2006
2007 if isinstance(image_data, (str, os.PathLike)):
2008 file_path = image_data
2009
2010 mimetype, encoding = mimetypes.guess_type(file_path)
2011
2012 with open(file_path, 'rb') as f:
2013 raw_data = f.read()
2014 img_bytes1 = base64.b64encode(raw_data)
2015
2016 image_bytes = img_bytes1
2017 elif isinstance(image_data, bytes):
2018 image_bytes = image_data
2019
2020 if image_bytes is None:
2021 raise Exception("unable to construct image bytes")
2022
2023 return image_bytes, mimetype
2024
2025 def set_item_image(self, item_id, image_data, image_type='Primary',
2026 mimetype='auto'):
2027 """
2028 Args:
2029 item_id (str): item to set the image of
2030
2031 image_data (str | PathLike | bytes):
2032 A path to an image on disk or raw bytes of an image.
2033
2034 image_type (str): A valid image type. I.e. one of
2035 'Primary', 'Art', 'Backdrop', 'Banner', 'Logo', 'Thumb',
2036 'Disc', 'Box', 'Screenshot', 'Menu', 'Chapter', 'BoxRear',
2037 'Profile'.
2038
2039 mimetype (str): if "auto", attempt to infer the mimetype.
2040 falls back to image/jpeg if unable. Otherwise this is used.
2041
2042 References:
2043 .. [SetItemImageByIndex] https://api.jellyfin.org/#tag/Image/operation/SetItemImageByIndex
2044 """
2045 from jellyfin_apiclient_python.constants import ImageType
2046
2047 image_bytes, auto_mimetype = self._coerce_image_bytes(image_data)
2048
2049 if mimetype == 'auto':
2050 mimetype = auto_mimetype
2051
2052 if image_type not in ImageType:
2053 raise KeyError(f'image_type must be one of: {ImageType}')
2054
2055 data = image_bytes.decode()
2056
2057 # Overriding headers are important for this call
2058 headers = {
2059 'Accept': '*/*',
2060 'Content-type': mimetype,
2061 }
2062 resp = self.items(f'/{item_id}/Images/{image_type}', action='POST',
2063 data=data, headers=headers)
2064 return resp
2065
2066 def set_user_image(self, user_id, image_data, mimetype='auto'):
2067 """
2068 Args:
2069 item_id (str): user id to set the image for
2070
2071 image_data (str | PathLike | bytes):
2072 A path to an image on disk or raw bytes of an image.
2073
2074 mimetype (str): if "auto", attempt to infer the mimetype.
2075 falls back to image/jpeg if unable. Otherwise this is used.
2076
2077 References:
2078 .. [PostUserImage] https://api.jellyfin.org/#tag/Image/operation/PostUserImage
2079 """
2080 image_bytes, auto_mimetype = self._coerce_image_bytes(image_data)
2081
2082 if mimetype == 'auto':
2083 mimetype = auto_mimetype
2084
2085 data = image_bytes.decode()
2086 # Overriding headers are important for this call
2087 headers = {
2088 'Accept': '*/*',
2089 'Content-type': mimetype,
2090 }
2091 resp = self._post("/UserImage", params={'user_id': user_id}, data=data,
2092 headers=headers)
2093 return resp
2094
2095
2096 class PlaylistAPIMixin:
2097 """
2098 Methods for creating and editing playlists.
2099
2100 Note: removal and reordering address playlist ENTRIES by their
2101 ``PlaylistItemId`` (as returned by ``get_playlist_items``), not by the
2102 underlying item id — the same item can appear in a playlist twice.
2103 """
2104
2105 def get_playlists(self, limit=None, fields=None, start_index=None,
2106 sort_by="SortName", sort_order="Ascending"):
2107 """The user's playlists, as ordinary items.
2108
2109 Jellyfin lets a playlist's declared ``MediaType`` diverge from what it
2110 actually holds, so this deliberately does not filter by media type —
2111 inspect the contents (``get_playlist_items``) to classify one.
2112 """
2113 return self.get_user_items(
2114 include_item_types="Playlist", recursive=True, sort_by=sort_by,
2115 sort_order=sort_order, start_index=start_index, limit=limit,
2116 fields=fields)
2117
2118 def new_playlist(self, name, item_ids=None, media_type="Video",
2119 is_public=None):
2120 """
2121 Create a new playlist.
2122
2123 Args:
2124 name (str):
2125 Name of the playlist to create.
2126
2127 item_ids (List[str] | None):
2128 Item ids to seed the playlist with.
2129
2130 media_type (str | None):
2131 The playlist media type ("Video" or "Audio").
2132
2133 is_public (bool | None):
2134 Whether the playlist is visible to all users. When None the
2135 server default is used (currently public); pass ``False`` for a
2136 playlist private to its owner.
2137
2138 Returns:
2139 Dict:
2140 with one entry: "Id", the id of the new playlist.
2141
2142 References:
2143 .. [CreatePlaylist] https://api.jellyfin.org/#tag/Playlists/operation/CreatePlaylist
2144 """
2145 json = {
2146 "Name": name,
2147 "UserId": "{UserId}",
2148 }
2149 if media_type is not None:
2150 json["MediaType"] = media_type
2151 if item_ids is not None:
2152 json["Ids"] = list(item_ids)
2153 if is_public is not None:
2154 json["IsPublic"] = bool(is_public)
2155 return self._post("Playlists", json)
2156
2157 def get_playlist(self, playlist_id):
2158 """
2159 Fetch a playlist's metadata (visibility and shares).
2160
2161 Args:
2162 playlist_id (str):
2163 Id of the playlist.
2164
2165 Returns:
2166 Dict:
2167 A ``PlaylistDto`` — notably ``OpenAccess`` (bool; True means
2168 visible to all users) and ``Shares``.
2169
2170 References:
2171 .. [GetPlaylist] https://api.jellyfin.org/#tag/Playlists/operation/GetPlaylist
2172 """
2173 return self._get("Playlists/%s" % playlist_id)
2174
2175 def update_playlist(self, playlist_id, name=None, item_ids=None,
2176 users=None, is_public=None):
2177 """
2178 Update a playlist's name, item order, shares, or visibility. Only the
2179 arguments you pass are changed; the server leaves omitted fields alone,
2180 so this is safe for a rename-only or visibility-only edit.
2181
2182 Args:
2183 playlist_id (str):
2184 Id of the playlist to update.
2185
2186 name (str | None):
2187 New name, or None to leave unchanged.
2188
2189 item_ids (List[str] | None):
2190 Full ordered item id list to replace the contents, or None to
2191 leave the contents unchanged.
2192
2193 users (List[Dict] | None):
2194 ``PlaylistUserPermissions`` entries to replace the share list,
2195 or None to leave shares unchanged.
2196
2197 is_public (bool | None):
2198 New visibility (True = all users, False = owner only), or None
2199 to leave unchanged.
2200
2201 References:
2202 .. [UpdatePlaylist] https://api.jellyfin.org/#tag/Playlists/operation/UpdatePlaylist
2203 """
2204 json = {}
2205 if name is not None:
2206 json["Name"] = name
2207 if item_ids is not None:
2208 json["Ids"] = list(item_ids)
2209 if users is not None:
2210 json["Users"] = list(users)
2211 if is_public is not None:
2212 json["IsPublic"] = bool(is_public)
2213 return self._post("Playlists/%s" % playlist_id, json)
2214
2215 def add_playlist_items(self, playlist_id, item_ids):
2216 """
2217 Append items to a playlist. Folder-ish ids (a series, a season) are
2218 expanded to their children by the server.
2219
2220 Args:
2221 playlist_id (str):
2222 Id of the playlist to add items to.
2223
2224 item_ids (List[str]):
2225 Item ids to append.
2226
2227 References:
2228 .. [AddItemToPlaylist] https://api.jellyfin.org/#tag/Playlists/operation/AddItemToPlaylist
2229 """
2230 params = {
2231 "Ids": ",".join(item_ids),
2232 "UserId": "{UserId}",
2233 }
2234 return self._post("Playlists/%s/Items" % playlist_id, None, params)
2235
2236 def remove_playlist_items(self, playlist_id, entry_ids):
2237 """
2238 Remove entries from a playlist.
2239
2240 Args:
2241 playlist_id (str):
2242 Id of the playlist to remove entries from.
2243
2244 entry_ids (List[str]):
2245 ``PlaylistItemId`` values of the entries to remove (NOT the
2246 item ids; see ``get_playlist_items``).
2247
2248 References:
2249 .. [RemoveItemFromPlaylist] https://api.jellyfin.org/#tag/Playlists/operation/RemoveItemFromPlaylist
2250 """
2251 params = {"EntryIds": ",".join(entry_ids)}
2252 return self._delete("Playlists/%s/Items" % playlist_id, params)
2253
2254 def move_playlist_item(self, playlist_id, entry_id, new_index):
2255 """
2256 Move one playlist entry to a new position.
2257
2258 Args:
2259 playlist_id (str):
2260 Id of the playlist being reordered.
2261
2262 entry_id (str):
2263 ``PlaylistItemId`` of the entry to move.
2264
2265 new_index (int):
2266 Target position within the playlist.
2267
2268 References:
2269 .. [MoveItem] https://api.jellyfin.org/#tag/Playlists/operation/MoveItem
2270 """
2271 return self._post("Playlists/%s/Items/%s/Move/%s"
2272 % (playlist_id, entry_id, int(new_index)))
2273
2274
2275 class CollectionAPIMixin:
2276 """
2277 Methods for creating and modifying collections.
2278
2279 Note: there does not seem to be an API endpoint for removing a collection.
2280 """
2281
2282 def get_collection_folders(self, term=None):
2283 """
2284 Queries for top-level default collections
2285
2286 I.e. Movies, Music, Shows, Collections, Playlists, etc...
2287
2288 Returns:
2289 Dict: pagenated result with key "Items"
2290 """
2291 from jellyfin_apiclient_python.constants import ItemType
2292 # For whatever reason, including search term in the query does nothing.
2293 # Furthermore, recursive has to base False, and the basic Music,
2294 # Collections, Movies, Playlists folders are always returned.
2295 result = self.user_items(params={
2296 'recursive': False,
2297 # 'searchTerm': term,
2298 'includeItemTypes': [ItemType.COLLECTION_FOLDER],
2299 })
2300 items = result['Items']
2301 if term is not None:
2302 # manual filter
2303 name_lower = term.lower()
2304 items = [item for item in items if name_lower in item['Name'].lower()]
2305 result['Items'] = items
2306 return result
2307
2308 def get_collections(self, term=None, limit=None, start_index=None,
2309 sort_by=None, sort_order=None, fields=None,
2310 image_type_limit=None, enable_image_types=None):
2311 """
2312 Queries for user-created collections
2313
2314 Args:
2315 term (str): query string to match
2316
2317 limit (int): maximum collections to return; without it the server
2318 answers with every collection the user can see.
2319
2320 start_index (int): paging offset, used with ``limit``.
2321
2322 sort_by (str): e.g. ``"SortName"``. Left unset, the order is
2323 whatever the server returns.
2324
2325 sort_order (str): ``"Ascending"`` or ``"Descending"``.
2326
2327 fields (str): comma-separated Fields to request.
2328
2329 Returns:
2330 Dict: pagenated result with key "Items"
2331 """
2332 from jellyfin_apiclient_python.constants import ItemType
2333 params = {
2334 'recursive': True,
2335 'searchTerm': term,
2336 'includeItemTypes': [ItemType.BOX_SET],
2337 'Limit': limit,
2338 'StartIndex': start_index,
2339 'SortBy': sort_by,
2340 'SortOrder': sort_order,
2341 'Fields': fields,
2342 'ImageTypeLimit': image_type_limit,
2343 'EnableImageTypes': enable_image_types,
2344 }
2345 result = self.user_items(
2346 params={k: v for k, v in params.items() if v is not None})
2347 return result
2348
2349 def delete_collection(self, item_id=None, name=None):
2350 """
2351 Delete a collection by name or ID.
2352
2353 This is mostly a wraper around delete_item, but with additional safety
2354 checks that ensure the item you are deleting is a collection.
2355 """
2356 if bool(name) ^ bool(item_id):
2357 raise ValueError('Exactly one of item_id or name must be given')
2358
2359 results = self.user_items(params={'searchTerm': name, 'recursive': True})
2360 items = results['Items']
2361
2362 if name is not None:
2363 # Filter to a case insensitive exact name match
2364 lower_name = name.lower()
2365 items = [item for item in items if item['Name'].lower() == lower_name]
2366
2367 if len(items) == 0:
2368 raise Exception('No items matched the given input')
2369 assert len(items) == 1, 'filtered to length 0 or 1'
2370 item = items[0]
2371
2372 # It looks like what the UI calls collections are called box sets in
2373 # the backend. there is a collection type, but these seem to be for
2374 # special groups like Music / Movies that should likely not be deleted.
2375 collection_types = {'BoxSet'}
2376
2377 if item['Type'] not in collection_types:
2378 raise ValueError('Given item={item} is not a collection')
2379
2380 return self.delete_item(item['Id'])
2381
2382 def new_collection(self, name, item_ids=None, parent_id=None, is_locked=False):
2383 """
2384 Create a new collection, or search for a collection with a given name.
2385
2386 Args:
2387 name (str):
2388 Name of the collection to create or lookup
2389
2390 item_ids (List[str] | None):
2391 List of item ids to initialize the collection with.
2392
2393 parent_id (str | None):
2394 Create the collection within a specific folder.
2395
2396 is_locked (str | None):
2397 Whether or not to lock the new collection.
2398
2399 Returns:
2400 Dict:
2401 with one entry: "Id", which contains the id of the new or found
2402 collection.
2403
2404 References:
2405 .. [CreateCollection] https://api.jellyfin.org/#tag/Collection/operation/CreateCollection
2406 """
2407 params = {}
2408 params['name'] = name
2409 params['isLocked'] = is_locked
2410 json = {}
2411 if parent_id is not None:
2412 params['parentId'] = parent_id
2413 if item_ids is not None:
2414 params['ids'] = item_ids
2415 return self._post("Collections", json, params)
2416
2417 def add_collection_items(self, collection_id, item_ids):
2418 """
2419 Adds items to a collection.
2420
2421 Args:
2422 collection_id (str):
2423 Id of the collection to add items to.
2424
2425 item_ids (List[str]):
2426 List of item ids to add to the collection.
2427
2428 References:
2429 .. [AddToCollection] https://api.jellyfin.org/#tag/Collection/operation/AddToCollection
2430 """
2431 params = {}
2432 json = {}
2433 params['ids'] = ','.join(item_ids)
2434 return self._post(f"Collections/{collection_id}/Items", json, params)
2435
2436 def remove_collection_items(self, collection_id, item_ids=None):
2437 """
2438 Removes items from a collection.
2439
2440 Args:
2441 collection_id (str):
2442 Id of the collection to remove items from.
2443
2444 item_ids (List[str]):
2445 List of item ids to remove from the collection.
2446
2447 References:
2448 .. [RemoveFromCollection] https://api.jellyfin.org/#tag/Collection/operation/RemoveFromCollection
2449 """
2450 params = {}
2451 params['ids'] = ','.join(item_ids)
2452 # _delete takes (handler, params); a stray positional json argument
2453 # here used to make every call raise TypeError.
2454 return self._delete(f"Collections/{collection_id}/Items", params)
2455
2456
2457 class BackupAPIMixin:
2458 """
2459 Methods for creating, restoring and listing system backups
2460
2461 10.11.0+ only
2462
2463 Note: backup manifests are dictionary objects with the following structure:
2464
2465 {
2466 "ServerVersion": "string",
2467 "BackupEngineVersion": "string",
2468 "DateCreated": "2019-08-24T14:15:22Z",
2469 "Path": "string",
2470 "Options": {
2471 "Metadata": true,
2472 "Trickplay": true,
2473 "Subtitles": true,
2474 "Database": true
2475 }
2476 }
2477
2478 """
2479
2480 def create_backup(
2481 self,
2482 include_metadata: bool = False,
2483 include_subtitles: bool = False,
2484 include_trickplay: bool = False,
2485 ):
2486 """
2487 Creates a new backup including the database and any of the optional
2488 elements requested. If metadata is included, this can be a time-consuming
2489 operation.
2490
2491 Args:
2492 include_metadata (bool)
2493 Whether or not to include metadata in the backup
2494
2495 include_subtitles (bool)
2496 Whether or not to include subtitles in the backup
2497
2498 include_trickplay (bool)
2499 Whether or not to include trickplay information in the backup
2500
2501 Returns:
2502 The manifest of the backup if it was created, an empty directory
2503 otherwise.
2504
2505 """
2506 params = {
2507 "database": True,
2508 "metadata": include_metadata,
2509 "subtitles": include_subtitles,
2510 "trickplay": include_trickplay,
2511 }
2512 return self._post("Backup/Create", params)
2513
2514 def get_backup_manifest(self, path: str):
2515 """
2516 Gets the manifest of a backup at the path passed
2517
2518 Args:
2519 path (str):
2520 Location of the backup
2521
2522 Returns:
2523 The backup's manifest, if the backup exists, an empty dictionary
2524 otherwise.
2525
2526 References:
2527 .. [BackupManifest] https://api.jellyfin.org/#tag/Backup/operation/GetBackup
2528 """
2529 params = {"path": path}
2530 return self._get("Backup/Manifest", params)
2531
2532 def get_backups(self):
2533 """
2534 Gets a list of all currently present backups in the backup directory.
2535
2536 Args:
2537 None
2538
2539 Returns:
2540 List of manifests for the backup that exist, one per backup.
2541
2542 References:
2543 .. [Backup] https://api.jellyfin.org/#tag/Backup/operation/ListBackups
2544 """
2545 return self._get("Backup")
2546
2547 def restore_backup(self, backup_name: str):
2548 """
2549 Starts the process of restoring a backup with the name passed.
2550
2551 Args:
2552 backup_name (str)
2553 The name of the backup archive, which must exist in the
2554 backups directory for the restore process to start
2555
2556 Returns:
2557 True if the restore process started, False otherwise
2558
2559 """
2560 params = {"ArchiveFileName": backup_name}
2561 try:
2562 # This post call returns a 204 to indicate that the restore has
2563 # been requested, but the client ingests the non-error code
2564 # and the _post() call returns nothing.
2565 self._post("Backup/Restore", params)
2566 return True
2567
2568 except Exception as e:
2569 LOG.error(e)
2570
2571 return False
2572
2573
2574 class API(
2575 InternalAPIMixin,
2576 BiggerAPIMixin,
2577 GranularAPIMixin,
2578 SyncPlayAPIMixin,
2579 ExperimentalAPIMixin,
2580 PlaylistAPIMixin,
2581 CollectionAPIMixin,
2582 BackupAPIMixin,
2583 ):
2584 """
2585 The Jellyfin Python API client containing all api calls to the server.
2586
2587 This class implements a subset of the [JellyfinWebAPI]_.
2588
2589 References:
2590 .. [JellyfinWebAPI] https://api.jellyfin.org/
2591
2592 Example:
2593 >>> from jellyfin_apiclient_python import JellyfinClient
2594 >>> client = JellyfinClient()
2595 >>> #
2596 >>> client.config.app(
2597 >>> name='your_brilliant_app',
2598 >>> version='0.0.1',
2599 >>> device_name='machine_name',
2600 >>> device_id='unique_id')
2601 >>> client.config.data["auth.ssl"] = True
2602 >>> #
2603 >>> your_jellyfin_url = 'http://127.0.0.1:8096' # Use your jellyfin IP / port
2604 >>> your_jellyfin_username = 'jellyfin' # Use your jellyfin userid
2605 >>> your_jellyfin_password = '' # Use your user's password
2606 >>> #
2607 >>> client.auth.connect_to_address(your_jellyfin_url)
2608 >>> client.auth.login(
2609 >>> server_url=your_jellyfin_url,
2610 >>> username=your_jellyfin_username,
2611 >>> password=your_jellyfin_password
2612 >>> )
2613 >>> #
2614 >>> # Test basic calls
2615 >>> system_info = client.jellyfin.get_system_info()
2616 >>> print(system_info)
2617 >>> media_folders = client.jellyfin.get_media_folders()
2618 >>> print(media_folders)
2619 """
2620
2621 def __init__(self, client, *args, **kwargs):
2622 """
2623 Args:
2624 client (jellyfin_apiclient_python.client.JellyfinClient): the client object
2625 *args: unused
2626 **kwargs: unused
2627 """
2628 self.client = client
2629 self.config = client.config
2630 self.default_timeout = 5