python-plexapi/plexapi/library.py

546 lines
25 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2017-01-02 22:38:19 +00:00
2017-02-03 03:23:46 +00:00
import logging
from plexapi import X_PLEX_CONTAINER_SIZE, log, utils
2016-12-15 23:06:12 +00:00
from plexapi.compat import unquote
2017-01-03 22:58:35 +00:00
from plexapi.media import MediaTag, Genre, Role, Director
from plexapi.exceptions import BadRequest, NotFound
from plexapi.media import MediaTag
2014-12-29 03:21:58 +00:00
class Library(object):
2017-01-26 04:21:13 +00:00
""" Represents a PlexServer library. This contains all sections of media defined
in your Plex server including video, shows and audio.
Attributes:
identifier (str): Unknown ('com.plexapp.plugins.library').
mediaTagVersion (str): Unknown (/system/bundle/media/flags/)
server (:class:`~plexapi.server.PlexServer`): PlexServer this client is connected to.
title1 (str): 'Plex Library' (not sure how useful this is).
title2 (str): Second title (this is blank on my setup).
"""
2015-06-08 16:41:47 +00:00
2014-12-29 03:21:58 +00:00
def __init__(self, server, data):
self.identifier = data.attrib.get('identifier')
self.mediaTagVersion = data.attrib.get('mediaTagVersion')
self.server = server
2014-12-29 03:21:58 +00:00
self.title1 = data.attrib.get('title1')
self.title2 = data.attrib.get('title2')
2017-02-02 03:53:05 +00:00
self._sectionsByID = {} # cached Section UUIDs
2014-12-29 03:21:58 +00:00
def __repr__(self):
return '<Library:%s>' % self.title1.encode('utf8')
def sections(self):
2017-01-26 04:21:13 +00:00
""" Returns a list of all media sections in this library. Library sections may be any of
:class:`~plexapi.library.MovieSection`, :class:`~plexapi.library.ShowSection`,
:class:`~plexapi.library.MusicSection`, :class:`~plexapi.library.PhotoSection`.
"""
2014-12-29 03:21:58 +00:00
items = []
SECTION_TYPES = {
MovieSection.TYPE: MovieSection,
ShowSection.TYPE: ShowSection,
MusicSection.TYPE: MusicSection,
2016-04-10 03:59:47 +00:00
PhotoSection.TYPE: PhotoSection,
}
2014-12-29 03:21:58 +00:00
path = '/library/sections'
for elem in self.server.query(path):
stype = elem.attrib['type']
if stype in SECTION_TYPES:
cls = SECTION_TYPES[stype]
section = cls(self.server, elem, path)
self._sectionsByID[section.key] = section
items.append(section)
2014-12-29 03:21:58 +00:00
return items
def section(self, title=None):
2017-01-31 04:48:21 +00:00
""" Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
2017-01-26 04:21:13 +00:00
Parameters:
title (str): Title of the section to return.
Raises:
:class:`~plexapi.exceptions.NotFound`: Invalid library section title.
"""
2014-12-29 03:21:58 +00:00
for item in self.sections():
if item.title == title:
return item
raise NotFound('Invalid library section: %s' % title)
2016-12-15 23:06:12 +00:00
def sectionByID(self, sectionID):
2017-01-31 04:48:21 +00:00
""" Returns the :class:`~plexapi.library.LibrarySection` that matches the specified sectionID.
2017-01-31 00:02:22 +00:00
2017-01-26 04:21:13 +00:00
Parameters:
sectionID (int): ID of the section to return.
"""
if not self._sectionsByID or sectionID not in self._sectionsByID:
self.sections()
return self._sectionsByID[sectionID]
2014-12-29 03:21:58 +00:00
def all(self):
2017-01-26 04:21:13 +00:00
""" Returns a list of all media from all library sections.
This may be a very large dataset to retrieve.
"""
return [item for section in self.sections() for item in section.all()]
2014-12-29 03:21:58 +00:00
def onDeck(self):
2017-01-26 04:21:13 +00:00
""" Returns a list of all media items on deck. """
return utils.listItems(self.server, '/library/onDeck')
2014-12-29 03:21:58 +00:00
def recentlyAdded(self):
2017-01-26 04:21:13 +00:00
""" Returns a list of all media items recently added. """
return utils.listItems(self.server, '/library/recentlyAdded')
2014-12-29 03:21:58 +00:00
2017-01-09 14:21:54 +00:00
def get(self, title): # this should use hub search when its merged
2017-01-31 00:02:22 +00:00
""" Return the first item from all items with the specified title.
2017-01-26 04:21:13 +00:00
Parameters:
title (str): Title of the item to return.
"""
2017-01-09 14:21:54 +00:00
for i in self.all():
if i.title.lower() == title.lower():
return i
2014-12-29 03:21:58 +00:00
def getByKey(self, key):
2017-01-31 00:02:22 +00:00
""" Return the first item from all items with the specified key.
2017-01-26 04:21:13 +00:00
Parameters:
key (str): Key of the item to return.
"""
return utils.findKey(self.server, key)
2016-12-15 23:06:12 +00:00
def search(self, title=None, libtype=None, **kwargs):
2017-01-26 04:21:13 +00:00
""" Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
2016-12-15 23:06:12 +00:00
Example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other items
2017-01-26 04:21:13 +00:00
such as actor=<id> seem to work, but require you already know the id of the actor.
TLDR: This is untested but seems to work. Use library section search when you can.
"""
args = {}
2016-12-15 23:06:12 +00:00
if title:
args['title'] = title
if libtype:
args['type'] = utils.searchType(libtype)
for attr, value in kwargs.items():
args[attr] = value
query = '/library/all%s' % utils.joinArgs(args)
return utils.listItems(self.server, query)
2016-12-15 23:06:12 +00:00
2014-12-29 03:21:58 +00:00
def cleanBundles(self):
2017-01-26 04:21:13 +00:00
""" Poster images and other metadata for items in your library are kept in "bundle"
packages. When you remove items from your library, these bundles aren't immediately
removed. Removing these old bundles can reduce the size of your install. By default, your
server will automatically clean up old bundles once a week as part of Scheduled Tasks.
"""
2017-02-02 03:53:05 +00:00
# TODO: Should this check the response for success or the correct mediaprefix?
2014-12-29 03:21:58 +00:00
self.server.query('/library/clean/bundles')
def emptyTrash(self):
2017-01-26 04:21:13 +00:00
""" If a library has items in the Library Trash, use this option to empty the Trash. """
2014-12-29 03:21:58 +00:00
for section in self.sections():
section.emptyTrash()
def optimize(self):
2017-01-26 04:21:13 +00:00
""" The Optimize option cleans up the server database from unused or fragmented data.
For example, if you have deleted or added an entire library or many items in a
library, you may like to optimize the database.
"""
2014-12-29 03:21:58 +00:00
self.server.query('/library/optimize')
def refresh(self):
2017-01-26 04:21:13 +00:00
""" Refresh the metadata for the entire library. This will fetch fresh metadata for
all contents in the library, including items that already have metadata.
"""
2014-12-29 03:21:58 +00:00
self.server.query('/library/sections/all/refresh')
2017-01-03 22:58:35 +00:00
def __len__(self):
return len(self.sections())
2014-12-29 03:21:58 +00:00
class LibrarySection(object):
2017-01-26 04:21:13 +00:00
""" Base class for a single library section.
Parameters:
2017-01-26 05:25:13 +00:00
server (:class:`~plexapi.server.PlexServer`): PlexServer object this library section is from.
data (ElementTree): Response from PlexServer used to build this object (optional).
2017-01-26 04:21:13 +00:00
initpath (str): Relative path requested when retrieving specified `data` (optional).
Attributes:
server (:class:`~plexapi.server.PlexServer`): Server this client is connected to.
initpath (str): Path requested when building this object.
agent (str): Unknown (com.plexapp.agents.imdb, etc)
allowSync (bool): True if you allow syncing content from this section.
art (str): Wallpaper artwork used to respresent this section.
composite (str): Composit image used to represent this section.
createdAt (datetime): Datetime this library section was created.
filters (str): Unknown
key (str): Key (or ID) of this library section.
language (str): Language represented in this section (en, xn, etc).
locations (str): Paths on disk where section content is stored.
refreshing (str): True if this section is currently being refreshed.
scanner (str): Internal scanner used to find media (Plex Movie Scanner, Plex Premium Music Scanner, etc.)
thumb (str): Thumbnail image used to represent this section.
title (str): Title of this section.
type (str): Type of content section represents (movie, artist, photo, show).
updatedAt (datetime): Datetime this library section was last updated.
uuid (str): Unique id for this section (32258d7c-3e6c-4ac5-98ad-bad7a3b78c63)
"""
ALLOWED_FILTERS = ()
ALLOWED_SORT = ()
BOOLEAN_FILTERS = ('unwatched', 'duplicate')
2014-12-29 03:21:58 +00:00
def __init__(self, server, data, initpath):
self.server = server
self.initpath = initpath
self.agent = data.attrib.get('agent')
self.allowSync = utils.cast(bool, data.attrib.get('allowSync'))
self.art = data.attrib.get('art')
self.composite = data.attrib.get('composite')
self.createdAt = utils.toDatetime(data.attrib.get('createdAt'))
self.filters = data.attrib.get('filters')
2014-12-29 03:21:58 +00:00
self.key = data.attrib.get('key')
self.language = data.attrib.get('language')
self.locations = utils.findLocations(data)
self.refreshing = utils.cast(bool, data.attrib.get('refreshing'))
self.scanner = data.attrib.get('scanner')
self.thumb = data.attrib.get('thumb')
self.title = data.attrib.get('title')
self.type = data.attrib.get('type')
self.updatedAt = utils.toDatetime(data.attrib.get('updatedAt'))
self.uuid = data.attrib.get('uuid')
2014-12-29 03:21:58 +00:00
def __repr__(self):
2016-12-15 23:06:12 +00:00
title = self.title.replace(' ', '.')[0:20]
2014-12-29 03:21:58 +00:00
return '<%s:%s>' % (self.__class__.__name__, title.encode('utf8'))
2016-12-15 23:06:12 +00:00
2014-12-29 03:21:58 +00:00
def get(self, title):
2017-01-26 04:21:13 +00:00
""" Returns the media item with the specified title.
Parameters:
title (str): Title of the item to return.
"""
2014-12-29 03:21:58 +00:00
path = '/library/sections/%s/all' % self.key
return utils.findItem(self.server, path, title)
2014-12-29 03:21:58 +00:00
def all(self):
2017-01-26 04:21:13 +00:00
""" Returns a list of media from this library section. """
return utils.listItems(self.server, '/library/sections/%s/all' % self.key)
2016-12-15 23:06:12 +00:00
def onDeck(self):
2017-01-26 04:21:13 +00:00
""" Returns a list of media items on deck from this library section. """
return utils.listItems(self.server, '/library/sections/%s/onDeck' % self.key)
def recentlyAdded(self, maxresults=50):
2017-01-26 04:21:13 +00:00
""" Returns a list of media items recently added from this library section.
2017-01-31 00:02:22 +00:00
2017-01-26 04:21:13 +00:00
Parameters:
maxresults (int): Max number of items to return (default 50).
"""
return self.search(sort='addedAt:desc', maxresults=maxresults)
2016-12-15 23:06:12 +00:00
def analyze(self):
2017-01-26 04:21:13 +00:00
""" Run an analysis on all of the items in this library section. """
2017-01-31 00:02:22 +00:00
self.server.query('/library/sections/%s/analyze' % self.key, method=self.server.session.put)
def emptyTrash(self):
2017-01-26 04:21:13 +00:00
""" If a section has items in the Trash, use this option to empty the Trash. """
self.server.query('/library/sections/%s/emptyTrash' % self.key)
def refresh(self):
2017-01-26 04:21:13 +00:00
""" Refresh the metadata for this library section. This will fetch fresh metadata for
all contents in the section, including items that already have metadata.
"""
self.server.query('/library/sections/%s/refresh' % self.key)
2016-12-15 23:06:12 +00:00
def listChoices(self, category, libtype=None, **kwargs):
2017-01-26 04:21:13 +00:00
""" Returns a list of :class:`~plexapi.library.FilterChoice` objects for the
specified category and libtype. kwargs can be any of the same kwargs in
:func:`plexapi.library.LibraySection.search()` to help narrow down the choices
to only those that matter in your current context.
Parameters:
category (str): Category to list choices for (genre, contentRating, etc).
libtype (int): Library type of item filter.
**kwargs (dict): Additional kwargs to narrow down the choices.
Raises:
:class:`~plexapi.exceptions.BadRequest`: Cannot include kwarg equal to specified category.
2014-12-29 03:21:58 +00:00
"""
if category in kwargs:
2017-01-26 04:21:13 +00:00
raise BadRequest('Cannot include kwarg equal to specified category: %s' % category)
2014-12-29 03:21:58 +00:00
args = {}
for subcategory, value in kwargs.items():
args[category] = self._cleanSearchFilter(subcategory, value)
2016-12-15 23:06:12 +00:00
if libtype is not None:
args['type'] = utils.searchType(libtype)
2017-01-26 04:21:13 +00:00
query = '/library/sections/%s/%s%s' % (self.key, category, utils.joinArgs(args))
return utils.listItems(self.server, query, bytag=True)
2014-12-29 03:21:58 +00:00
def search(self, title=None, sort=None, maxresults=999999, libtype=None, **kwargs):
""" Search the library. If there are many results, they will be fetched from the server
in batches of X_PLEX_CONTAINER_SIZE amounts. If you're only looking for the first <num>
results, it would be wise to set the maxresults option to that amount so this functions
doesn't iterate over all results on the server.
2016-12-15 23:06:12 +00:00
2017-01-26 04:21:13 +00:00
Parameters:
title (str): General string query to search for (optional).
sort (str): column:dir; column can be any of {addedAt, originallyAvailableAt, lastViewedAt,
titleSort, rating, mediaHeight, duration}. dir can be asc or desc (optional).
maxresults (int): Only return the specified number of results (optional).
libtype (str): Filter results to a spcifiec libtype (movie, show, episode, artist, album, track; optional).
**kwargs (dict): Any of the available filters for the current library section. Partial string
2016-12-15 23:06:12 +00:00
matches allowed. Multiple matches OR together. All inputs will be compared with the
available options and a warning logged if the option does not appear valid.
2017-01-26 04:21:13 +00:00
* unwatched: Display or hide unwatched content (True, False). [all]
* duplicate: Display or hide duplicate items (True, False). [movie]
* actor: List of actors to search ([actor_or_id, ...]). [movie]
* collection: List of collections to search within ([collection_or_id, ...]). [all]
* contentRating: List of content ratings to search within ([rating_or_key, ...]). [movie,tv]
* country: List of countries to search within ([country_or_key, ...]). [movie,music]
* decade: List of decades to search within ([yyy0, ...]). [movie]
* director: List of directors to search ([director_or_id, ...]). [movie]
* genre: List Genres to search within ([genere_or_id, ...]). [all]
* network: List of TV networks to search within ([resolution_or_key, ...]). [tv]
* resolution: List of video resolutions to search within ([resolution_or_key, ...]). [movie]
* studio: List of studios to search within ([studio_or_key, ...]). [music]
* year: List of years to search within ([yyyy, ...]). [all]
"""
# Cleanup the core arguments
args = {}
for category, value in kwargs.items():
args[category] = self._cleanSearchFilter(category, value, libtype)
2016-12-15 23:06:12 +00:00
if title is not None:
args['title'] = title
if sort is not None:
args['sort'] = self._cleanSearchSort(sort)
if libtype is not None:
args['type'] = utils.searchType(libtype)
# Iterate over the results
results, subresults = [], '_init'
args['X-Plex-Container-Start'] = 0
args['X-Plex-Container-Size'] = min(X_PLEX_CONTAINER_SIZE, maxresults)
while subresults and maxresults > len(results):
2016-12-15 23:06:12 +00:00
query = '/library/sections/%s/all%s' % (
self.key, utils.joinArgs(args))
subresults = utils.listItems(self.server, query)
2016-12-15 23:06:12 +00:00
results += subresults[:maxresults - len(results)]
args['X-Plex-Container-Start'] += args['X-Plex-Container-Size']
return results
2014-12-29 03:21:58 +00:00
def _cleanSearchFilter(self, category, value, libtype=None):
# check a few things before we begin
if category not in self.ALLOWED_FILTERS:
raise BadRequest('Unknown filter category: %s' % category)
if category in self.BOOLEAN_FILTERS:
return '1' if value else '0'
if not isinstance(value, (list, tuple)):
value = [value]
# convert list of values to list of keys or ids
result = set()
choices = self.listChoices(category, libtype)
2016-12-15 23:06:12 +00:00
lookup = {c.title.lower(): unquote(unquote(c.key)) for c in choices}
allowed = set(c.key for c in choices)
for item in value:
item = str(item.id if isinstance(item, MediaTag) else item).lower()
# find most logical choice(s) to use in url
2016-12-15 23:06:12 +00:00
if item in allowed:
result.add(item)
continue
if item in lookup:
result.add(lookup[item])
continue
matches = [k for t, k in lookup.items() if item in t]
if matches:
map(result.add, matches)
continue
# nothing matched; use raw item value
2017-01-26 04:21:13 +00:00
log.warning('Filter value not listed, using raw item value: %s' % item)
result.add(item)
return ','.join(result)
2016-12-15 23:06:12 +00:00
def _cleanSearchSort(self, sort):
sort = '%s:asc' % sort if ':' not in sort else sort
scol, sdir = sort.lower().split(':')
2016-12-15 23:06:12 +00:00
lookup = {s.lower(): s for s in self.ALLOWED_SORT}
if scol not in lookup:
raise BadRequest('Unknown sort column: %s' % scol)
if sdir not in ('asc', 'desc'):
raise BadRequest('Unknown sort dir: %s' % sdir)
return '%s:%s' % (lookup[scol], sdir)
2014-12-29 03:21:58 +00:00
class MovieSection(LibrarySection):
2017-01-26 04:21:13 +00:00
""" Represents a :class:`~plexapi.library.LibrarySection` section containing movies.
2017-01-31 00:02:22 +00:00
2017-01-26 04:21:13 +00:00
Attributes:
ALLOWED_FILTERS (list<str>): List of allowed search filters. ('unwatched',
'duplicate', 'year', 'decade', 'genre', 'contentRating', 'collection',
'director', 'actor', 'country', 'studio', 'resolution')
ALLOWED_SORT (list<str>): List of allowed sorting keys. ('addedAt',
'originallyAvailableAt', 'lastViewedAt', 'titleSort', 'rating',
'mediaHeight', 'duration')
TYPE (str): 'movie'
"""
ALLOWED_FILTERS = ('unwatched', 'duplicate', 'year', 'decade', 'genre', 'contentRating',
2017-02-02 03:53:05 +00:00
'collection', 'director', 'actor', 'country', 'studio', 'resolution')
ALLOWED_SORT = ('addedAt', 'originallyAvailableAt', 'lastViewedAt', 'titleSort', 'rating',
2017-02-02 03:53:05 +00:00
'mediaHeight', 'duration')
2014-12-29 03:21:58 +00:00
TYPE = 'movie'
class ShowSection(LibrarySection):
2017-01-26 04:21:13 +00:00
""" Represents a :class:`~plexapi.library.LibrarySection` section containing tv shows.
2017-01-31 00:02:22 +00:00
2017-01-26 04:21:13 +00:00
Attributes:
ALLOWED_FILTERS (list<str>): List of allowed search filters. ('unwatched',
'year', 'genre', 'contentRating', 'network', 'collection')
ALLOWED_SORT (list<str>): List of allowed sorting keys. ('addedAt', 'lastViewedAt',
'originallyAvailableAt', 'titleSort', 'rating', 'unwatched')
TYPE (str): 'show'
"""
ALLOWED_FILTERS = ('unwatched', 'year', 'genre', 'contentRating', 'network', 'collection')
ALLOWED_SORT = ('addedAt', 'lastViewedAt', 'originallyAvailableAt', 'titleSort',
2017-02-02 03:53:05 +00:00
'rating', 'unwatched')
2014-12-29 03:21:58 +00:00
TYPE = 'show'
2015-06-08 16:41:47 +00:00
def searchShows(self, **kwargs):
2017-01-26 04:21:13 +00:00
""" Search for a show. See :func:`~plexapi.library.LibrarySection.search()` for usage. """
return self.search(libtype='show', **kwargs)
2014-12-29 03:21:58 +00:00
def searchEpisodes(self, **kwargs):
2017-01-26 04:21:13 +00:00
""" Search for an episode. See :func:`~plexapi.library.LibrarySection.search()` for usage. """
return self.search(libtype='episode', **kwargs)
2014-12-29 03:21:58 +00:00
def recentlyAdded(self, libtype='episode', maxresults=50):
2017-01-26 04:21:13 +00:00
""" Returns a list of recently added episodes from this library section.
2017-01-31 00:02:22 +00:00
2017-01-26 04:21:13 +00:00
Parameters:
maxresults (int): Max number of items to return (default 50).
"""
return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults)
2014-12-29 03:21:58 +00:00
class MusicSection(LibrarySection):
2017-01-26 04:21:13 +00:00
""" Represents a :class:`~plexapi.library.LibrarySection` section containing music artists.
2017-01-31 00:02:22 +00:00
2017-01-26 04:21:13 +00:00
Attributes:
ALLOWED_FILTERS (list<str>): List of allowed search filters. ('genre',
'country', 'collection')
ALLOWED_SORT (list<str>): List of allowed sorting keys. ('addedAt',
'lastViewedAt', 'viewCount', 'titleSort')
TYPE (str): 'artist'
"""
ALLOWED_FILTERS = ('genre', 'country', 'collection')
ALLOWED_SORT = ('addedAt', 'lastViewedAt', 'viewCount', 'titleSort')
TYPE = 'artist'
2016-12-15 23:06:12 +00:00
def albums(self):
2017-01-26 04:21:13 +00:00
""" Returns a list of :class:`~plexapi.audio.Album` objects in this section. """
return utils.listItems(self.server, '/library/sections/%s/albums' % self.key)
2016-04-10 03:59:47 +00:00
def searchArtists(self, **kwargs):
2017-01-26 04:21:13 +00:00
""" Search for an artist. See :func:`~plexapi.library.LibrarySection.search()` for usage. """
return self.search(libtype='artist', **kwargs)
2016-04-10 03:59:47 +00:00
def searchAlbums(self, **kwargs):
2017-01-26 04:21:13 +00:00
""" Search for an album. See :func:`~plexapi.library.LibrarySection.search()` for usage. """
return self.search(libtype='album', **kwargs)
2016-12-15 23:06:12 +00:00
def searchTracks(self, **kwargs):
2017-01-26 04:21:13 +00:00
""" Search for a track. See :func:`~plexapi.library.LibrarySection.search()` for usage. """
return self.search(libtype='track', **kwargs)
2016-04-10 03:59:47 +00:00
class PhotoSection(LibrarySection):
2017-01-26 04:21:13 +00:00
""" Represents a :class:`~plexapi.library.LibrarySection` section containing photos.
2017-01-31 00:02:22 +00:00
2017-01-26 04:21:13 +00:00
Attributes:
ALLOWED_FILTERS (list<str>): List of allowed search filters. <NONE>
ALLOWED_SORT (list<str>): List of allowed sorting keys. <NONE>
TYPE (str): 'photo'
"""
2017-01-31 00:02:22 +00:00
ALLOWED_FILTERS = ('all', 'iso', 'make', 'lens', 'aperture', 'exposure')
2016-04-10 03:59:47 +00:00
ALLOWED_SORT = ()
TYPE = 'photo'
2016-12-15 23:06:12 +00:00
2017-01-31 00:02:22 +00:00
def searchAlbums(self, title, **kwargs): # lets use this for now.
2017-01-26 04:21:13 +00:00
""" Search for an album. See :func:`~plexapi.library.LibrarySection.search()` for usage. """
2017-01-31 00:02:22 +00:00
albums = utils.listItems(self.server, '/library/sections/%s/all?type=14' % self.key)
return [i for i in albums if i.title.lower() == title.lower()]
2016-12-15 23:06:12 +00:00
2017-01-31 00:02:22 +00:00
def searchPhotos(self, title, **kwargs):
2017-01-26 04:21:13 +00:00
""" Search for a photo. See :func:`~plexapi.library.LibrarySection.search()` for usage. """
2017-01-31 00:02:22 +00:00
photos = utils.listItems(self.server, '/library/sections/%s/all?type=13' % self.key)
return [i for i in photos if i.title.lower() == title.lower()]
2016-04-10 03:59:47 +00:00
2017-01-03 22:58:35 +00:00
@utils.register_libtype
class Hub(object):
TYPE = 'Hub'
def __init__(self, server, data, initpath):
self.server = server
self.initpath = initpath
self.type = data.attrib.get('type')
self.hubIdentifier = data.attrib.get('hubIdentifier')
self.title = data.attrib.get('title')
self._items = []
self.size = utils.cast(int, data.attrib.get('title'), 0)
if self.type == 'genre':
self._items = [Genre(self.server, elem) for elem in data]
elif self.type == 'director':
self._items = [Director(self.server, elem) for elem in data]
elif self.type == 'actor':
self._items = [Role(self.server, elem) for elem in data]
else:
for elem in data:
try:
self._items.append(utils.buildItem(self.server, elem, '/hubs'))
except Exception as e:
logging.exception('Failed %s to build %s' % (self.type, self.title))
def __repr__(self):
return '<Hub:%s>' % self.title.encode('utf8')
def __len__(self):
return self.size
def all(self):
return self._items
@utils.register_libtype
class FilterChoice(object):
2017-01-26 04:21:13 +00:00
""" Represents a single filter choice. These objects are gathered when using filters
while searching for library items and is the object returned in the result set of
:func:`~plexapi.library.LibrarySection.listChoices()`.
Attributes:
server (:class:`~plexapi.server.PlexServer`): PlexServer this client is connected to.
initpath (str): Relative path requested when retrieving specified `data` (optional).
fastKey (str): API path to quickly list all items in this filter
(/library/sections/<section>/all?genre=<key>)
key (str): Short key (id) of this filter option (used ad <key> in fastKey above).
2017-01-31 00:02:22 +00:00
thumb (str): Thumbnail used to represent this filter option.
2017-01-26 04:21:13 +00:00
title (str): Human readable name for this filter option.
type (str): Filter type (genre, contentRating, etc).
"""
TYPE = 'Directory'
def __init__(self, server, data, initpath):
self.server = server
self.initpath = initpath
self.fastKey = data.attrib.get('fastKey')
self.key = data.attrib.get('key')
self.thumb = data.attrib.get('thumb')
self.title = data.attrib.get('title')
self.type = data.attrib.get('type')
def __repr__(self):
2016-12-15 23:06:12 +00:00
title = self.title.replace(' ', '.')[0:20]
return '<%s:%s:%s>' % (self.__class__.__name__, self.key, title)