def test_movie_to_json(): tron = Movie('Tron Legacy', year=2010) expected = {'movies': [{'title': tron.title, 'year': 2010, 'ids': {'imdb': 'tt1104001', 'slug': 'tron-legacy-2010', 'tmdb': 20526, 'trakt': 343}}]} assert tron.to_json() == expected
def get_watched(list_type=None, extended=None): """Return all movies or shows a user has watched sorted by most plays. :param list_type: Optional Filter by a specific type. Possible values: movies, shows, seasons or episodes. :param extended: Optional value for requesting extended information. """ valid_type = ('movies', 'shows', 'seasons', 'episodes') if list_type and list_type not in valid_type: raise ValueError('list_type must be one of {}'.format(valid_type)) uri = 'sync/watchlist' if list_type: uri += '/{}'.format(list_type) if list_type == 'shows' and extended: uri += '?extended={extended}'.format(extended=extended) data = yield uri results = [] for d in data: if 'movie' in d: from trakt.movies import Movie results.append(Movie(**d.pop('movie'))) elif 'show' in d: from trakt.tv import TVShow results.append(TVShow(**d.pop('show'))) yield results
def watching(self): """The :class:`TVEpisode` or :class:`Movie` this :class:`User` is currently watching. If they aren't watching anything, a blank object will be returned. Protected users won't return any data unless you are friends. """ data = yield 'users/{user}/watching'.format( user=slugify(self.username)) # if a user isn't watching anything, trakt returns a 204 if data is None or data == '': yield None media_type = data.pop('type') if media_type == 'movie': movie_data = data.pop('movie') extract_ids(movie_data) movie_data.update(data) yield Movie(**movie_data) else: # media_type == 'episode' ep_data = data.pop('episode') extract_ids(ep_data) sh_data = data.pop('show') ep_data.update(data, show=sh_data.get('title')) yield TVEpisode(**ep_data)
def get_collection(list_type=None, extended=None): """ Get all collected items in a user's collection. A collected item indicates availability to watch digitally or on physical media. :param list_type: Optional Filter by a specific type. Possible values: movies or shows. :param extended: Optional value for requesting extended information. """ valid_type = ('movies', 'shows') if list_type and list_type not in valid_type: raise ValueError('list_type must be one of {}'.format(valid_type)) uri = 'sync/watchlist' if list_type: uri += '/{}'.format(list_type) if extended: uri += '?extended={extended}'.format(extended=extended) data = yield uri results = [] for d in data: if 'movie' in d: from trakt.movies import Movie results.append(Movie(**d.pop('movie'))) elif 'show' in d: from trakt.tv import TVShow results.append(TVShow(**d.pop('show'))) yield results
def search_by_id(query, id_type='imdb', media_type=None): """Perform a search query by using a Trakt.tv ID or other external ID :param query: Your search string, which should be an ID from your source :param id_type: The source of the ID you're looking for. Must be one of 'trakt', trakt-movie', 'trakt-show', 'trakt-episode', 'trakt-person', 'imdb', 'tmdb', or 'tvdb' :param media_type: The type of media you're looking for. May be one of 'movie', 'show', 'episode', or 'person', or a comma-separated list of any combination of those. Null by default, which will return all types of media that match the ID given. """ valids = ('trakt', 'trakt-movie', 'trakt-show', 'trakt-episode', 'trakt-person', 'imdb', 'tmdb', 'tvdb') id_types = {'trakt': 'trakt', 'trakt-movie': 'trakt', 'trakt-show': 'trakt', 'trakt-episode': 'trakt', 'trakt-person': 'trakt', 'imdb': 'imdb', 'tmdb': 'tmdb', 'tvdb': 'tvdb'} if id_type not in valids: raise ValueError('search_type must be one of {}'.format(valids)) source = id_types.get(id_type) media_types = {'trakt-movie': 'movie', 'trakt-show': 'show', 'trakt-episode': 'episode', 'trakt-person': 'person'} # If there was no media_type passed in, see if we can guess based off the # ID source. None is still an option here, as that will return all possible # types for a given source. if media_type is None: media_type = media_types.get(source, None) # If media_type is still none, don't add it as a parameter to the search if media_type is None: uri = 'search/{source}/{query}'.format( query=slugify(query), source=source) else: uri = 'search/{source}/{query}?type={media_type}'.format( query=slugify(query), source=source, media_type=media_type) data = yield uri for media_item in data: extract_ids(media_item) results = [] for d in data: if 'episode' in d: from trakt.tv import TVEpisode show = d.pop('show') extract_ids(d['episode']) results.append(TVEpisode(show['title'], **d['episode'])) elif 'movie' in d: from trakt.movies import Movie results.append(Movie(**d.pop('movie'))) elif 'show' in d: from trakt.tv import TVShow results.append(TVShow(**d.pop('show'))) elif 'person' in d: from trakt.people import Person results.append(Person(**d.pop('person'))) yield results
def search_by_id(query, id_type='imdb'): """Perform a search query by using a Trakt.tv ID or other external ID :param query: Your search string :param id_type: The type of object you're looking for. Must be one of 'trakt-movie', 'trakt-show', 'trakt-episode', 'imdb', 'tmdb', 'tvdb' or 'tvrage' """ valids = ('trakt-movie', 'trakt-show', 'trakt-episode', 'imdb', 'tmdb', 'tvdb', 'tvrage') if id_type not in valids: raise ValueError('search_type must be one of {}'.format(valids)) data = yield 'search?id={query}&id_type={id_type}'.format( query=slugify(query), id_type=id_type) for media_item in data: extract_ids(media_item) results = [] for d in data: if 'episode' in d: from trakt.tv import TVEpisode show = d.pop('show') extract_ids(d['episode']) results.append(TVEpisode(show['title'], **d['episode'])) elif 'movie' in d: from trakt.movies import Movie results.append(Movie(**d.pop('movie'))) elif 'show' in d: from trakt.tv import TVShow results.append(TVShow(**d.pop('show'))) elif 'person' in d: from trakt.people import Person results.append(Person(**d.pop('person'))) yield results
def _search(self, query, context=None): """Search for a movie matching *query*""" results = Movie.search(query) movie = self._filter_results(query, results) movie._get() # fetch remainder of data from trakt if movie is not None: return self._apply_mapping(movie) return self.context
def search(query, search_type='movie', year=None): """Perform a search query against all of trakt's media types :param query: Your search string :param search_type: The type of object you're looking for. Must be one of 'movie', 'show', 'movie,show', 'episode', or 'person' """ valids = ('movie', 'show', 'episode', 'person', 'movie,show') if search_type not in valids: raise ValueError('search_type must be one of {}'.format(valids)) uri = 'search?query={query}&type={type}'.format( query=slugify(query), type=search_type) if year is not None: uri += '&year={}'.format(year) data = yield uri for media_item in data: extract_ids(media_item) # Need to do imports here to prevent circular imports with modules that # need to import Scrobblers if search_type == 'movie': from trakt.movies import Movie yield [Movie(d['score'], **d.pop('movie')) for d in data] elif search_type == 'show': from trakt.tv import TVShow yield [TVShow(d['score'], **d.pop('show')) for d in data] elif search_type == 'movie,show': from trakt.movies import Movie from trakt.tv import TVShow yield [Movie(d['score'], **d.pop('movie')) if d['type'] == 'movie' else TVShow(d['score'], **d.pop('show')) for d in data] elif search_type == 'episode': from trakt.tv import TVEpisode episodes = [] for episode in data: show = episode.pop('show') extract_ids(episode['episode']) episodes.append(TVEpisode(show.get('title', None), **episode['episode'])) yield episodes elif search_type == 'person': from trakt.people import Person yield [Person(**d.pop('person')) for d in data]
def test_utilities(): tron = Movie('Tron Legacy 2010') functions = [tron.add_to_library, tron.add_to_collection, tron.add_to_watchlist, tron.dismiss, tron.mark_as_unseen, tron.remove_from_library, tron.remove_from_collection, tron.remove_from_watchlist, tron.mark_as_seen] for fn in functions: r = fn() assert r is None
def _build(self, data): """Build the calendar of Movies""" self._calendar = [] for movie in data: m_data = movie.get('movie', {}) released = movie.get('released', None) self._calendar.append(Movie(released=released, **m_data)) self._calendar = sorted(self._calendar, key=lambda x: x.released)
def test_movie_people(): tron = Movie('Tron Legacy', year=2010) sub_groups = ['people', 'cast', 'crew'] for group in sub_groups: persons = getattr(tron, group) assert isinstance(persons, list) assert len(persons) >= 1 assert isinstance(persons[0], Person) assert all(isinstance(p, Person) for p in persons)
def test_scrobble(): """test the Scrobbler class's workflow""" guardians = Movie('Guardians of the Galaxy', year=2014) scrobbler = Scrobbler(guardians, 1.0, '1.0.0', '2015-02-01') scrobbler.start() scrobbler.update(50.0) scrobbler.pause() scrobbler.start() scrobbler.stop() scrobbler.start() scrobbler.finish()
def test_get_movie(): tron = Movie('Tron Legacy', year=2010) assert isinstance(tron, Movie) assert tron.title == 'TRON: Legacy' assert tron.year == 2010 assert tron.tagline == 'The Game Has Changed.' assert tron.runtime == 125 expected = {"trakt": 343, "slug": "tron-legacy-2010", "imdb": "tt1104001", "tmdb": 20526} assert tron.ids == {'ids': expected}
def watchlist_movies(self): """Returns all watchlist movies of :class:`User`. """ if self._movie_watchlist is None: data = yield 'users/{username}/watchlist/movies'.format( username=slugify(self.username), ) self._movie_watchlist = [] for movie in data: mov = movie.pop('movie') extract_ids(mov) self._movie_watchlist.append(Movie(**mov)) yield self._movie_watchlist yield self._movie_watchlist
def movie_collection(self): """All :class:`Movie`'s in this :class:`User`'s library collection. Collection items might include blu-rays, dvds, and digital downloads. Protected users won't return any data unless you are friends. """ if self._movie_collection is None: ext = 'users/{username}/collection/movies?extended=metadata' data = yield ext.format(username=slugify(self.username)) self._movie_collection = [] for movie in data: mov = movie.pop('movie') extract_ids(mov) self._movie_collection.append(Movie(**mov)) yield self._movie_collection
def watched_movies(self): """Watched profess for all :class:`Movie`'s in this :class:`User`'s collection. """ if self._watched_movies is None: data = yield 'users/{user}/watched/movies'.format( user=slugify(self.username)) self._watched_movies = [] for movie in data: movie_data = movie.pop('movie') extract_ids(movie_data) movie_data.update(movie) self._watched_movies.append(Movie(**movie_data)) yield self._watched_movies
def get_search_results(query, search_type=None, slugify_query=False): """Perform a search query against all of trakt's media types. :param query: Your search string :param search_type: The types of objects you're looking for. Must be specified as a list of strings containing any of 'movie', 'show', 'episode', or 'person'. :param slugify_query: A boolean indicating whether or not the provided query should be slugified or not prior to executing the query. """ # if no search type was specified, then search everything if search_type is None: search_type = ['movie', 'show', 'episode', 'person'] # If requested, slugify the query prior to running the search if slugify_query: query = slugify(query) uri = 'search/{type}?query={query}'.format( query=query, type=','.join(search_type)) data = yield uri # Need to do imports here to prevent circular imports with modules that # need to import Scrobblers results = [] for media_item in data: extract_ids(media_item) result = SearchResult(media_item['type'], media_item['score']) if media_item['type'] == 'movie': from trakt.movies import Movie result.media = Movie(**media_item.pop('movie')) elif media_item['type'] == 'show': from trakt.tv import TVShow result.media = TVShow(**media_item.pop('show')) elif media_item['type'] == 'episode': from trakt.tv import TVEpisode show = media_item.pop('show') result.media = TVEpisode(show.get('title', None), **media_item.pop('episode')) elif media_item['type'] == 'person': from trakt.people import Person result.media = Person(**media_item.pop('person')) results.append(result) yield results
def get_watchlist(list_type=None, sort=None): """ Get a watchlist. optionally with a filter for a specific item type. :param list_type: Optional Filter by a specific type. Possible values: movies, shows, seasons or episodes. :param sort: Optional sort. Only if the type is also sent. Possible values: rank, added, released or title. """ valid_type = ('movies', 'shows', 'seasons', 'episodes') valid_sort = ('rank', 'added', 'released', 'title') if list_type and list_type not in valid_type: raise ValueError('list_type must be one of {}'.format(valid_type)) if sort and sort not in valid_sort: raise ValueError('sort must be one of {}'.format(valid_sort)) uri = 'sync/watchlist' if list_type: uri += '/{}'.format(list_type) if list_type and sort: uri += '/{}'.format(sort) data = yield uri results = [] for d in data: if 'episode' in d: from trakt.tv import TVEpisode show = d.pop('show') extract_ids(d['episode']) results.append(TVEpisode(show, **d['episode'])) elif 'movie' in d: from trakt.movies import Movie results.append(Movie(**d.pop('movie'))) elif 'show' in d: from trakt.tv import TVShow results.append(TVShow(**d.pop('show'))) yield results
def get_items(self): """A list of the list items using class instances instance types: movie, show, season, episode, person """ data = yield 'users/{user}/lists/{id}/items'.format(user=slugify( self.creator), id=self.slug) for item in data: # match list item type if 'type' not in item: continue item_type = item['type'] item_data = item.pop(item_type) extract_ids(item_data) if item_type == 'movie': self._items.append( Movie(item_data['title'], item_data['year'], item_data['slug'])) elif item_type == 'show': self._items.append( TVShow(item_data['title'], item_data['slug'])) elif item_type == 'season': show_data = item.pop('show') extract_ids(show_data) season = TVSeason(show_data['title'], item_data['number'], show_data['slug']) self._items.append(season) elif item_type == 'episode': show_data = item.pop('show') extract_ids(show_data) episode = TVEpisode(show_data['title'], item_data['season'], item_data['number']) self._items.append(episode) elif item_type == 'person': self._items.append(Person(item_data['name'], item_data['slug'])) yield self._items
def do_trakt_search(self): """Search Trakt.TV for data on the movie being tagged""" self._update_progress() title = self.atoms['Name'] year = None if '(' in title and ')' in title: year = title[title.find('(')+1:title.find(')')].strip() title = ' '.join(title.split()[:-1]).strip() movie = Movie(title, year=year) self.subler.rating = movie.certification self.atoms['Genre'] = movie.genres[0].name self.atoms['Description'] = self.atoms['Long Description'] = \ movie.overview self.atoms['Release Date'] = movie.released_iso self.atoms['Name'] = movie.title if 'Artwork' not in self.atoms and 'poster' in movie.images: if self.has_artwork(movie.images['poster']): pid = str(os.getpid()) art = os.path.abspath('.albumart{}.jpg'.format(pid)) self.atoms['Artwork'] = art.replace(' ', '\\ ') self._update_progress()
def get_trakt_info(self, eiga_movie): logging.debug('search trakt for movie %s', eiga_movie['title_jp']) original_title = eiga_movie['movie_data'].get('原題'.decode('utf8'), None) year = eiga_movie['movie_data'].get('製作年'.decode('utf8'), None) logging.debug('search trakt for movie [%s](%s)', original_title, year) if original_title is None: logging.warning('original title does not exist, skip get trakt info') return None else: if year is not None: year = year[:4] try: result = Movie.search(original_title, year) if len(result) > 0: return result[0] else: return None except TypeError as e: logging.error('the movie title only contains non-ascii character, ' 'PyTrakt can not handle this: %s' % title) return None
def test_movie_comment(): tron = Movie('Tron Legacy 2010') r = tron.comment('Some comment data') assert r is None
def test_scrobbler_context_manager(): """test the Scrobbler when used as a context manager""" guardians = Movie('Guardians of the Galaxy', year=2014) with Scrobbler(guardians, 0.0, '1.0.0', '2015-02-01') as scrob: for i in range(10): scrob.update(i * 10)
def test_movie_translations(): tron = Movie('Tron Legacy', year=2010) translations = tron.get_translations(country_code='es') assert isinstance(translations, list) assert len(translations) == 3 assert isinstance(translations[0], Translation)
def test_movie_comments(): tron = Movie('Tron Legacy 2010') assert isinstance(tron.comments, list) assert len(tron.comments) == 1 assert isinstance(tron.comments[0], Comment)
def test_movie_ratings(): tron = Movie('Tron Legacy 2010') assert isinstance(tron.ratings, dict)
def test_movie_releases(): tron = Movie('Tron Legacy 2010') releases = tron.get_releases() assert isinstance(releases, list) assert len(releases) == 13 assert isinstance(releases[0], Release)
def _extract_media(self, media): from trakt.movies import Movie data = media.get(self.MEDIA_KEY) return Movie(**data)
def com_net_trakt_set_rating_movie(self, movie_name_year, media_rating): """ Set user rating on media """ media_instance = Movie(movie_name_year) media_instance.rate(media_rating)
def test_movie_related(): tron = Movie('Tron Legacy', year=2010) assert isinstance(tron.related, list) assert len(tron.related) == 10 assert isinstance(tron.related[0], Movie)
def com_net_trakt_add_movie(self, movie_name_year): """ Set add media """ media_instance = Movie(movie_name_year) media_instance.add_to_library()
def test_movie_watching(): tron = Movie('Tron Legacy 2010') watching_now = tron.watching_now assert isinstance(watching_now, list) assert len(watching_now) == 2 assert isinstance(watching_now[0], User)
def get_items(self): """A list of the list items using class instances instance types: movie, show, season, episode, person """ data = yield 'users/{user}/lists/{id}/items'.format(user=self.creator, id=self.slug) for item in data: # match list item type if 'type' not in item: continue item_type = item['type'] item_data = item.pop(item_type) extract_ids(item_data) if item_type == 'movie': movie = Movie(item_data.pop('title'), item_data.pop('year'), item_data.pop('slug'), **item_data) self._items.append(movie) elif item_type == 'show': show = TVShow(item_data.pop('title'), slug=item_data.pop('slug'), **item_data) seasons = show.seasons show._seasons = [] for season in seasons: season._episodes = [] show._seasons.append(season) self._items.append(show) elif item_type == 'season': show_data = item.pop('show') extract_ids(show_data) show = TVShow(show_data.pop('title'), slug=show_data.pop('slug'), **show_data) _season = TVSeason(show=show.title, season=item_data.pop('number'), slug=show.slug, **item_data) for season in show.seasons: if season.trakt != _season.trakt: continue season._episodes = [] show._seasons = [season] self._items.append(show) break # season._episodes = [] # show._seasons = [season] # self._items.append(show) # extract_ids(show_data) # show=TVShow(show_data['title'], show_data['slug']) # season = TVSeason( # show=show.title, # season=item_data['number'], # slug=show.slug, # **item_data # ) # self._items.append(self.__class__.ListTVSeason(show=show, season=season)) elif item_type == 'episode': show_data = item.pop('show') extract_ids(show_data) show = TVShow(show_data.pop('title'), slug=show_data.pop('slug'), **show_data) episode = TVEpisode(show=show.title, season=item_data.pop('season'), slug=show.slug, **item_data) for season in show.seasons: if season.season != episode.season: continue season._episodes = [episode] show._seasons = [season] self._items.append(show) break # show=TVShow(show_data['title'], show_data['slug']) # show._seasons = None # for season in show.seasons: # if season.season != item_data['number']: # continue # episode = TVEpisode(show.title, season.season, item_data['number'], show.slug) # self._items.append(self.__class__.ListTVEpisode(show=show, season=season, episode=episode)) # break elif item_type == 'person': self._items.append(Person(item_data['name'], item_data['slug'])) yield self._items
def test_rate_movie(): tron = Movie('Tron Legacy 2010') tron.rate(10)
def test_scrobble_movie(): tron = Movie('Tron Legacy 2010') tron.scrobble(50.0, '1.0.0', '2015-02-01')
def com_net_trakt_set_watching_movie(self, movie_name_year): """ Set watching status on media """ media_instance = Movie(movie_name_year) media_instance.watching_now()
def test_movie_to_json(): tron = Movie('Tron Legacy', year=2010) assert tron.to_json() == {'movie': {'title': tron.title}}
def test_movie_aliases(): tron = Movie('Tron Legacy', year=2010) assert isinstance(tron.aliases, list) assert len(tron.aliases) == 15
def test_movie_search(): results = Movie.search('batman') assert isinstance(results, list) assert all(isinstance(m, Movie) for m in results)
def com_net_trakt_set_seen_movie(self, movie_name_year): """ Set seen status on media """ media_instance = Movie(movie_name_year) media_instance.mark_as_seen()