def instance(self): if self._instance is None: self._instance = TVEpisode(self.show, self.season, number=self.number, **self.ids) return self._instance
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 _build(self, data): """Build the calendar""" self._calendar = [] for item in data: show_data = item.pop('show') episode_data = { **item.pop('episode'), 'airs_at': airs_date(item.get('first_aired')) } show = TVShow( show_data.pop('title'), slug="sodiafagiaugaiugh", **{ **show_data, # 'seasons': [] }) episode = TVEpisode(show.title, episode_data.pop('season'), episode_data.pop('number'), slug=show.slug, **episode_data) for season in show.seasons: if season.season != episode.season: continue season._episodes = [episode] show._seasons = [season] self._calendar.append(show) break self._calendar = sorted(self._calendar, key=lambda x: x.seasons[0].episodes[0].airs_at)
def getTraktEpisodeInfo(showName, seasonNumber, episodeNumber, cache, seriesWhitelist, seriesMismatched): print showName, seasonNumber, episodeNumber if (showName.lower() in cache): showTvDbId = cache[showName.lower()]['tvdb'] showName = cache[showName.lower()]['title'] elif (showName in seriesMismatched): showRes = showName showName = seriesMismatched[showName] showTvDbId = TVShow('"' + showName + '"').tvdb cache = updateCache(cache, showRes, showName, showTvDbId) elif (showName in seriesWhitelist): showTvDbId = seriesWhitelist[showName] else: showName = showName.replace("(", "").replace(")", "").replace(":", "") showRes = TVShow.search('"' + showName + '"') for showFound in showRes: if showName.lower() == showFound.title.lower(): cache = updateCache(cache, showName, showFound.title, showFound.tvdb) showName = showFound.title showTvDbId = showFound.tvdb break else: # Cannot find exact show name in trakt.tv search results so use 1st entry cache = updateCache(cache, showName, showRes[0].title, showRes[0].tvdb) showName = showRes[0].title showTvDbId = showRes[0].tvdb print showName, showTvDbId, seasonNumber, episodeNumber episode = TVEpisode(showName, seasonNumber, episodeNumber) #print episode.show, showTvDbId, seasonNumber, episodeNumber, episode.title, episode.tvdb return (showName, showTvDbId, seasonNumber, episodeNumber, episode.title, episode.tvdb)
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 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 test_oneliners(): e1 = TVEpisode('Game of Thrones', season=1, number=1) functions = [ e1.add_to_library, e1.add_to_collection, e1.add_to_watchlist, e1.mark_as_seen, e1.mark_as_unseen, e1.remove_from_library, e1.remove_from_collection, e1.remove_from_watchlist ] for fn in functions: r = fn() assert r is None
def _build(self, data): """Build the calendar""" self._calendar = [] for episode in data: show = episode.get('show', {}).get('title') season = episode.get('episode', {}).get('season') ep = episode.get('episode', {}).get('number') e_data = { 'airs_at': airs_date(episode.get('first_aired')), 'ids': episode.get('episode').get('ids'), 'title': episode.get('episode', {}).get('title') } self._calendar.append(TVEpisode(show, season, ep, **e_data)) self._calendar = sorted(self._calendar, key=lambda x: x.airs_at)
def postNewEpisodesToTrakt(newEpisodes): HEADERS = { 'Content-Type': 'application/json', 'trakt-api-version': '2', 'trakt-api-key': CLIENT_ID } HEADERS['Authorization'] = 'Bearer {}'.format(trakt.api_key) for episode in newEpisodes: title = episode[0] season = episode[2] episode_num = episode[3] to_post = TVEpisode(title, season, episode_num) trakt_id = to_post.to_json() trakt_id.update(progress=100, app_version="1.0", date="2015-03-07") encodedData = json.dumps(trakt_id) request = Request('https://api-v2launch.trakt.tv/scrobble/stop', data=encodedData, headers=HEADERS) resp = urlopen(request).getcode() if (resp == 201): print str(title) + " " + str(season) + " " + str( episode_num) + " Successfully scrobbled" else: print 'Error: ' + str(resp)
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 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 _build(self, data): """Build the calendar""" self._calendar = [] for cal_item in data: show_data = cal_item.get('show', {}) episode = cal_item.get('episode', {}) first_aired = cal_item.get('first_aired') season = episode.get('season') ep_num = episode.get('number') extract_ids(show_data) show_data.update(show_data) e_data = { 'airs_at': airs_date(first_aired), 'ids': episode.get('ids'), 'title': show_data.get('title'), 'show_data': TVShow(**show_data) } self._calendar.append( TVEpisode(show_data['trakt'], season, ep_num, **e_data) ) self._calendar = sorted(self._calendar, key=lambda x: x.airs_at)
def test_episode_scrobble(): e1 = TVEpisode('Game of Thrones', season=1, number=1) scrobbler = e1.scrobble(50.0, '1.0.0', '2015-02-07') assert isinstance(scrobbler, Scrobbler)
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_episode_comment(): e1 = TVEpisode('Game of Thrones', season=1, number=1) r = e1.comment('Test Comment') assert r is None
def test_episode_ids(): e1 = TVEpisode('Game of Thrones', season=1, number=1) assert isinstance(e1.ids, dict) assert e1.trakt == e1.ids['ids']['trakt'] assert e1.imdb == e1.ids['ids']['imdb'] assert e1.tmdb == e1.ids['ids']['tmdb']
def test_rate_episode(): e1 = TVEpisode('Game of Thrones', season=1, number=1) e1.rate(10)
def test_episode_images(): e1 = TVEpisode('Game of Thrones', season=1, number=1) for _ in range(2): assert isinstance(e1.images, dict)
def test_episode_aired_dates(): e1 = TVEpisode('Game of Thrones', season=1, number=1) assert e1.first_aired_date == airs_date('2011-04-18T01:00:00.000Z') assert e1.first_aired_end_time == airs_date('2011-04-18T01:58:00.000Z')
def test_episode_ratings(): e1 = TVEpisode('Game of Thrones', season=1, number=1) assert isinstance(e1.ratings, dict)
def test_episode_search_with_year(): results = TVEpisode.search('batman', year=1987) assert isinstance(results, list) assert len(results) == 10 assert all(isinstance(m, TVEpisode) for m in results)
def test_get_episode(): e1 = TVEpisode('Game of Thrones', season=1, number=1) assert e1.season == 1 assert e1.number == 1 assert e1.get_description() == e1.overview
def test_episode_search(): results = TVEpisode.search('batman') assert isinstance(results, list) assert all(isinstance(m, TVEpisode) for m in results)
def test_episode_magic_methods(): e1 = TVEpisode('Game of Thrones', season=1, number=1) assert str(e1) == '<TVEpisode>: %s S%dE%d %s' % (e1.show, e1.season, e1.number, e1.title) assert str(e1) == repr(e1)
def test_episode_watching_now(): e1 = TVEpisode('Game of Thrones', season=1, number=1) assert all([isinstance(u, User) for u in e1.watching_now])
def test_episode_comments(): e1 = TVEpisode('Game of Thrones', season=1, number=1) assert all([isinstance(c, Comment) for c in e1.comments])