Esempio n. 1
0
    def photoalbum(self):
        """Summary

        Returns:
            TYPE: Description
        """
        return utils.listItems(self.server, self.parentKey)[0]
Esempio n. 2
0
    def listChoices(self, category, libtype=None, **kwargs):
        """ 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.
        """
        if category in kwargs:
            raise BadRequest(
                'Cannot include kwarg equal to specified category: %s' %
                category)
        args = {}
        for subcategory, value in kwargs.items():
            args[category] = self._cleanSearchFilter(subcategory, value)
        if libtype is not None:
            args['type'] = utils.searchType(libtype)
        query = '/library/sections/%s/%s%s' % (self.key, category,
                                               utils.joinArgs(args))
        return utils.listItems(self.server, query, bytag=True)
Esempio n. 3
0
 def items(self, *args, **kwargs):
     """ Return the list of items within this tag. This function is only applicable
         in search results from PlexServer :func:`~plexapi.server.PlexServer.search()`.
     """
     if not self.key:
         raise BadRequest('Key is not defined for this tag: %s' % self.tag)
     return listItems(self.server, self.key)
Esempio n. 4
0
    def search(self, query, mediatype=None, limit=None):
        """ Returns a list of media items or filter categories from the resulting
            `Hub Search <https://www.plex.tv/blog/seek-plex-shall-find-leveling-web-app/>`_
            against all items in your Plex library. This searches genres, actors, directors,
            playlists, as well as all the obvious media titles. It performs spell-checking
            against your search terms (because KUROSAWA is hard to spell). It also provides
            contextual search results. So for example, if you search for 'Pernice', it’ll
            return 'Pernice Brothers' as the artist result, but we’ll also go ahead and
            return your most-listened to albums and tracks from the artist. If you type
            'Arnold' you’ll get a result for the actor, but also the most recently added
            movies he’s in.

            Parameters:
                query (str): Query to use when searching your library.
                mediatype (str): Optionally limit your search to the specified media type.
                limit (int): Optionally limit to the specified number of results per Hub.
        """
        results = []
        params = {'query': query}
        if mediatype:
            params['section'] = utils.SEARCHTYPES[mediatype]
        if limit:
            params['limit'] = limit
        url = '/hubs/search?%s' % urlencode(params)
        for hub in utils.listItems(self, url, bytag=True):
            results += hub.items
        return results
Esempio n. 5
0
    def episodes(self, watched=None):
        """Returs a list of Episode

           Args:
                watched (bool): Defaults to None. Exclude watched episodes
        """
        leavesKey = '/library/metadata/%s/allLeaves' % self.ratingKey
        return utils.listItems(self.server, leavesKey, watched=watched)
Esempio n. 6
0
    def photos(self):
        """Summary

        Returns:
            TYPE: Description
        """
        path = '/library/metadata/%s/children' % self.ratingKey
        return utils.listItems(self.server, path, Photo.TYPE)
Esempio n. 7
0
    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.

            Args:
                title (string, optional): General string query to search for.
                sort (string): column:dir; column can be any of {addedAt, originallyAvailableAt, lastViewedAt,
                      titleSort, rating, mediaHeight, duration}. dir can be asc or desc.
                maxresults (int): Only return the specified number of results
                libtype (string): Filter results to a spcifiec libtype {movie, show, episode, artist, album, track}
                kwargs: Any of the available filters for the current library section. Partial string
                        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.

                        '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)
        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):
            query = '/library/sections/%s/all%s' % (self.key,
                                                    utils.joinArgs(args))
            subresults = utils.listItems(self.server, query)
            results += subresults[:maxresults - len(results)]
            args['X-Plex-Container-Start'] += args['X-Plex-Container-Size']
        return results
Esempio n. 8
0
    def getMedia(self):
        """Summary

        Returns:
            TYPE: Description
        """
        server = self.server().connect()
        items = utils.listItems(server, '/sync/items/%s' % self.id)
        return items
Esempio n. 9
0
    def tracks(self, watched=None):
        """Return all tracks to this album.

        Args:
            watched(None, False, True): Default to None.

        Returns:
            List: of Track
        """
        path = '%s/children' % self.key
        return utils.listItems(self.server, path, watched=watched)
Esempio n. 10
0
 def listChoices(self, category, libtype=None, **kwargs):
     """ List choices for the specified filter category. kwargs can be any of the same
         kwargs in self.search() to help narrow down the choices to only those that
         matter in your current context.
     """
     if category in kwargs:
         raise BadRequest('Cannot include kwarg equal to specified category: %s' % category)
     args = {}
     for subcategory, value in kwargs.items():
         args[category] = self._cleanSearchFilter(subcategory, value)
     if libtype is not None: args['type'] = utils.searchType(libtype)
     query = '/library/sections/%s/%s%s' % (self.key, category, utils.joinArgs(args))
     return utils.listItems(self.server, query, bytag=True)
Esempio n. 11
0
    def episodes(self, watched=None):
        """Returs a list of Episode

           Args:
                watched (bool): Defaults to None. Exclude watched episodes

           Returns:
                list: of Episode


        """
        childrenKey = '/library/metadata/%s/children' % self.ratingKey
        return utils.listItems(self.server, childrenKey, watched=watched)
Esempio n. 12
0
 def search(self, title=None, libtype=None, **kwargs):
     """ 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. For example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other items
         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 = {}
     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)
Esempio n. 13
0
    def search(self, query, mediatype=None):
        """Searching within a library section is much more powerful.

        Args:
            query (str): Search str
            mediatype (str, optional): Limit your search to a media type.

        Returns:
            List
        """
        items = utils.listItems(self, '/search?query=%s' % quote(query))
        if mediatype:
            return [item for item in items if item.type == mediatype]
        return items
Esempio n. 14
0
 def search(self, title=None, libtype=None, **kwargs):
     """ 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. For example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other items
         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 = {}
     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)
Esempio n. 15
0
 def listChoices(self, category, libtype=None, **kwargs):
     """ List choices for the specified filter category. kwargs can be any of the same
         kwargs in self.search() to help narrow down the choices to only those that
         matter in your current context.
     """
     if category in kwargs:
         raise BadRequest(
             'Cannot include kwarg equal to specified category: %s' %
             category)
     args = {}
     for subcategory, value in kwargs.items():
         args[category] = self._cleanSearchFilter(subcategory, value)
     if libtype is not None: args['type'] = utils.searchType(libtype)
     query = '/library/sections/%s/%s%s' % (self.key, category,
                                            utils.joinArgs(args))
     return utils.listItems(self.server, query, bytag=True)
Esempio n. 16
0
    def browse(self, uri):
        logger.debug('browse: %s', str(uri))
        if not uri:
            return []
        if uri == self.root_directory.uri:
            return self._root
        parts = uri.split(':')

        # albums
        if uri == 'plex:album':
            logger.debug('self._browse_albums()')
            return [self._item_ref(item, 'album') for item in
                    plexutils.listItems(self.plex, '/library/sections/4/albums')]

        # a single album
        # uri == 'plex:album:album_id'
        if len(parts) == 3 and parts[1] == 'album':
            logger.debug('self._browse_album(uri)')
            album_id = parts[2]
            return [self._item_ref(item, 'track') for item in
                    plexutils.listItems(self.plex,
                                         '/library/metadata/{}/children'.format(album_id))]

        # artists
        if uri == 'plex:artist':
            logger.debug('self._browse_artists()')
            return [self._item_ref(item, 'artist') for item in
                    plexutils.listItems(self.plex, '/library/sections/4/all')]

        # a single artist
        # uri == 'plex:artist:artist_id'
        if len(parts) == 3 and parts[1] == 'artist':
            logger.debug('self._browse_artist(uri)')
            artist_id = parts[2]
            # get albums and tracks
            ret = []
            for item in plexutils.listItems(self.plex,
                                             '/library/metadata/{}/children'.format(artist_id)):
                ret.append(self._item_ref(item, 'album'))
            for item in plexutils.listItems(self.plex,
                                             '/library/metadata/{}/allLeaves'.format(artist_id)):
                ret.append(self._item_ref(item, 'track'))
            return ret

        # all tracks of a single artist
        # uri == 'plex:artist:artist_id:all'
        if len(parts) == 4 and parts[1] == 'artist' and parts[3] == 'all':
            logger.debug('self._browse_artist_all_tracks(uri)')
            artist_id = parts[2]
            return [self._item_ref(item, 'track') for item in
                    plexutils.listItems(self.plex, '/library/metadata/{}/allLeaves'.format(artist_id))]

        logger.debug('Unknown uri for browse request: %s', uri)

        return []
Esempio n. 17
0
 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.
         title: General string query to search for.
         sort: column:dir; column can be any of {addedAt, originallyAvailableAt, lastViewedAt,
           titleSort, rating, mediaHeight, duration}. dir can be asc or desc.
         maxresults: Only return the specified number of results
         libtype: Filter results to a spcifiec libtype {movie, show, episode, artist, album, track}
         kwargs: Any of the available filters for the current library section. Partial string
           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.
             '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)
     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):
         query = '/library/sections/%s/all%s' % (self.key, utils.joinArgs(args))
         subresults = utils.listItems(self.server, query)
         results += subresults[:maxresults-len(results)]
         args['X-Plex-Container-Start'] += args['X-Plex-Container-Size']
     return results
Esempio n. 18
0
    def lookup(self, uri):
        '''Lookup playlist with given URI in both the set of playlists and in any other playlist source.

        Returns the playlists or None if not found.


          Parameters:	uri (string) – playlist URI
          Return type:	mopidy.models.Playlist or None

        '''
        logger.debug('Playlist: lookup %r', uri)
        _rx = re.compile(r'plex:playlist:(?P<plid>\d+)').match(uri)
        if _rx is None:
            return None
        plexlist = listItems(self.plex, '/playlists/{:s}'.format(_rx.group('plid')))[0]
        PL = Playlist(uri=uri,
                      name=plexlist.title,
                      tracks=[wrap_track(_t, self.backend.plex_uri) for _t in plexlist.items()],
                      last_modified=None, # TODO: find this value
                     )
        return PL
Esempio n. 19
0
    def get_items(self, uri):
        '''Get the items in a playlist specified by uri.

        Returns a list of Ref objects referring to the playlist’s items.

        If a playlist with the given uri doesn’t exist, it returns None.


          Return type:	list of mopidy.models.Ref, or None

        '''
        logger.debug('Playlist: get_items %r', uri)
        _rx = re.compile(r'plex:playlist:(?P<plid>\d+)').match(uri)
        if _rx is None:
            return None

        def wrap_ref(item):
            return Ref.track(uri='plex:track:{}'.format(item.ratingKey), name=item.title)

        return [wrap_ref(item) for item in
                listItems(self.plex, '/playlists/{}/items'.format(_rx.group('plid')))]
Esempio n. 20
0
 def search(self, query, mediatype=None):
     """ Searching within a library section is much more powerful. """
     items = utils.listItems(self, '/search?query=%s' % quote(query))
     if mediatype:
         return [item for item in items if item.type == mediatype]
     return items
Esempio n. 21
0
 def season(self):
     return utils.listItems(self.server, self.parentKey)[0]
Esempio n. 22
0
 def episodes(self, watched=None):
     childrenKey = '/library/metadata/%s/children' % self.ratingKey
     return utils.listItems(self.server, childrenKey, watched=watched)
Esempio n. 23
0
 def seasons(self):
     path = '/library/metadata/%s/children' % self.ratingKey
     return utils.listItems(self.server, path, Season.TYPE)
Esempio n. 24
0
 def history(self):
     return utils.listItems(self, '/status/sessions/history/all')
Esempio n. 25
0
 def search(self, query, mediatype=None):
     """ Searching within a library section is much more powerful. """
     items = utils.listItems(self, '/search?query=%s' % quote(query))
     if mediatype:
         return [item for item in items if item.type == mediatype]
     return items
Esempio n. 26
0
 def playlists(self):
     # TODO: Add sort and type options?
     # /playlists/all?type=15&sort=titleSort%3Aasc&playlistType=video&smart=0
     return utils.listItems(self, '/playlists')
Esempio n. 27
0
 def tracks(self, watched=None):
     childrenKey = '/library/metadata/%s/children' % self.ratingKey
     return utils.listItems(self.server, childrenKey, watched=watched)
Esempio n. 28
0
 def playlists(self):
     return utils.listItems(self, '/playlists')
Esempio n. 29
0
 def items(self):
     path = '%s/items' % self.key
     return utils.listItems(self.server, path)
Esempio n. 30
0
 def photos(self):
     path = '/library/metadata/%s/children' % self.ratingKey
     return utils.listItems(self.server, path, Photo.TYPE)
Esempio n. 31
0
 def sessions(self):
     return utils.listItems(self, '/status/sessions')
Esempio n. 32
0
 def history(self):
     return utils.listItems(self, '/status/sessions/history/all')
Esempio n. 33
0
 def onDeck(self):
     return utils.listItems(self.server, '/library/onDeck')
Esempio n. 34
0
 def items(self):
     """Return all items in the playlist."""
     path = '%s/items' % self.key
     return utils.listItems(self.server, path)
Esempio n. 35
0
 def show(self):
     return utils.listItems(self.server, self.grandparentKey)[0]
Esempio n. 36
0
 def sessions(self):
     return utils.listItems(self, '/status/sessions')
Esempio n. 37
0
 def photoalbum(self):
     return utils.listItems(self.server, self.parentKey)[0]
Esempio n. 38
0
 def playlists(self):
     # TODO: Add sort and type options?
     # /playlists/all?type=15&sort=titleSort%3Aasc&playlistType=video&smart=0
     return utils.listItems(self, '/playlists')
Esempio n. 39
0
 def onDeck(self):
     return utils.listItems(self.server, '/library/sections/%s/onDeck' % self.key)
Esempio n. 40
0
 def episodes(self, watched=None):
     leavesKey = '/library/metadata/%s/allLeaves' % self.ratingKey
     return utils.listItems(self.server, leavesKey, watched=watched)
Esempio n. 41
0
 def tracks(self, watched=None):
     leavesKey = '/library/metadata/%s/allLeaves' % self.ratingKey
     return utils.listItems(self.server, leavesKey, watched=watched)
Esempio n. 42
0
 def season(self):
     return utils.listItems(self.server, self.parentKey)[0]
Esempio n. 43
0
 def seasons(self):
     path = '/library/metadata/%s/children' % self.ratingKey
     return utils.listItems(self.server, path, Season.TYPE)
Esempio n. 44
0
 def photos(self):
     path = '/library/metadata/%s/children' % self.ratingKey
     return utils.listItems(self.server, path, Photo.TYPE)
Esempio n. 45
0
 def episodes(self, watched=None):
     childrenKey = "/library/metadata/%s/children" % self.ratingKey
     return utils.listItems(self.server, childrenKey, watched=watched)
Esempio n. 46
0
 def all(self):
     return utils.listItems(self.server, '/library/sections/%s/all' % self.key)
Esempio n. 47
0
 def episodes(self, watched=None):
     leavesKey = "/library/metadata/%s/allLeaves" % self.ratingKey
     return utils.listItems(self.server, leavesKey, watched=watched)
Esempio n. 48
0
 def show(self):
     """Return this episodes Show"""
     return utils.listItems(self.server, self.grandparentKey)[0]
Esempio n. 49
0
 def tracks(self, watched=None):
     path = '%s/children' % self.key
     return utils.listItems(self.server, path, watched=watched)
Esempio n. 50
0
 def all(self):
     return utils.listItems(self.server, '/library/all')
Esempio n. 51
0
 def album(self):
     return utils.listItems(self.server, self.parentKey)[0]
Esempio n. 52
0
 def recentlyAdded(self):
     return utils.listItems(self.server, '/library/recentlyAdded')
Esempio n. 53
0
 def artist(self):
     return utils.listItems(self.server, self.grandparentKey)[0]
Esempio n. 54
0
    def browse(self, uri):
        logger.debug('browse: %s', str(uri))
        if not uri:
            return []
        if uri == self.root_directory.uri:
            return self._root
        parts = uri.split(':')

        sections = self.plex.library.sections()
        artists = [sec for sec in sections if sec.type == 'artist']
        # albums
        if uri == 'plex:album':
            logger.debug('self._browse_albums()')
            albums = list()
            for a in artists:
                try:
                    albums += a.albums()
                except Exception as e:
                    logger.warning(
                        'Failed to process albums for {}: {}'.format(a, e))
            # logger.info('Albums: {}'.format([a.title for a in albums]))
            logger.debug('{} albums found'.format(len(albums)))
            return [self._item_ref(item, 'album') for item in albums]

        # a single album
        # uri == 'plex:album:album_id'
        if len(parts) == 3 and parts[1] == 'album':
            logger.debug('self._browse_album(uri)')
            album_id = parts[2]
            key = '/library/metadata/{}/children'.format(album_id)
            return [
                self._item_ref(item, 'track')
                for item in self.plex.fetchItems(key)
            ]

        # artists
        if uri == 'plex:artist':
            logger.debug('self._browse_artists()')
            return [self._item_ref(item, 'artist') for item in artists]

        # a single artist
        # uri == 'plex:artist:artist_id'
        if len(parts) == 3 and parts[1] == 'artist':
            logger.debug('self._browse_artist(uri)')
            artist_id = parts[2]
            # get albums and tracks
            ret = []
            for item in plexutils.listItems(
                    self.plex,
                    '/library/metadata/{}/children'.format(artist_id)):
                ret.append(self._item_ref(item, 'album'))
            for item in plexutils.listItems(
                    self.plex,
                    '/library/metadata/{}/allLeaves'.format(artist_id)):
                ret.append(self._item_ref(item, 'track'))
            return ret

        # all tracks of a single artist
        # uri == 'plex:artist:artist_id:all'
        if len(parts) == 4 and parts[1] == 'artist' and parts[3] == 'all':
            logger.debug('self._browse_artist_all_tracks(uri)')
            artist_id = parts[2]
            return [
                self._item_ref(item, 'track') for item in plexutils.listItems(
                    self.plex, '/library/metadata/{}/allLeaves'.format(
                        artist_id))
            ]

        logger.debug('Unknown uri for browse request: %s', uri)

        return []
Esempio n. 55
0
 def albums(self):
     path = '%s/children' % self.key
     return utils.listItems(self.server, path, Album.TYPE)
Esempio n. 56
0
 def tracks(self, watched=None):
     path = '%s/allLeaves' % self.key
     return utils.listItems(self.server, path, watched=watched)
Esempio n. 57
0
 def getMedia(self):
     server = self.server().connect()
     items = utils.listItems(server, '/sync/items/%s' % self.id)
     return items