def series_lookup(session=None, only_cached=False, **lookup_params): search_params = search_params_for_series(**lookup_params) # Searching cache first series = from_cache(session=session, cache_type=TVMazeSeries, search_params=search_params) search = None # Preparing search from lookup table title = lookup_params.get('series_name') or lookup_params.get('show_name') or lookup_params.get('title') if not series and title: log.debug('did not find exact match for series {0} in cache, looking in search table'.format( search_params['name'])) search = from_lookup(session=session, title=title) if search and search.series: series = search.series log.debug('found series {0} from search table'.format(series.name)) if only_cached: if series: # If force_cache is True, return series even if it expired log.debug('forcing cache for series {0}'.format(series.name)) return series raise LookupError('Series %s not found from cache' % lookup_params) if series and not series.expired: log.debug('returning series {0} from cache'.format(series.name)) return series prepared_params = prepare_lookup_for_pytvmaze(**lookup_params) try: log.debug('trying to fetch series {0} from pytvmaze'.format(title)) pytvmaze_show = get_show(**prepared_params) except ShowNotFound as e: log.debug('could not find series {0} in pytvmaze'.format(title)) raise LookupError(e.value) except ConnectionError as e: log.warning(e) raise LookupError(e.value) # See if series already exist in cache series = session.query(TVMazeSeries).filter(TVMazeSeries.tvmaze_id == pytvmaze_show.maze_id).first() if series: log.debug('series {0} is already in cache, checking for expiration'.format(series.name)) if series.expired: series.update(pytvmaze_show, session) else: log.debug('creating new series {0} in tvmaze_series db'.format(pytvmaze_show.name)) series = TVMazeSeries(pytvmaze_show, session) session.add(series) # Check if show returned from lookup table as expired. Relevant only if search by title if title: if series and title.lower() == series.name.lower(): return series elif series and not search: log.debug('mismatch between search title {0} and series title {1}. ' 'saving in lookup table'.format(title, series.name)) add_to_lookup(session=session, title=title, series=series) elif series and search: log.debug('Updating search result in db') search.series = series return series
def command_maze(bot, user, channel, args): try: show = pytvmaze.get_show(show_name=args, embed="episodes") except pytvmaze.exceptions.ShowNotFound: bot.say(channel, "Show '%s' not found" % args) return next_episode = None next_delta = None now = datetime.now(pytz.timezone("Europe/Helsinki")) # go through the episodes in reverse order for episode in reversed(show.episodes): # episode has id and name, but no airstamp yet (not announced) if not episode.airstamp: continue delta = relativedelta(parse(episode.airstamp), now) # episode is in the past, stop searching if delta.months <= 0 and delta.days <= 0 and delta.minutes <= 0: break else: # episode is (still) in the future next_episode = episode next_delta = delta # No new episodes found if not next_episode: # ended show, find latest episode if show.status == "Ended": next_episode = show.episodes.pop() latest_delta = relativedelta(now, parse(next_episode.airstamp)) else: # Still running, ep airdate not yet known bot.say(channel, "No new episodes found for %s" % show.name) return show_id = "%s %s '%s'" % ( show.name, "%dx%02d" % (next_episode.season_number, next_episode.episode_number), next_episode.title, ) if show.status == "Ended": msg = "Latest episode of %s aired on %s (%s ago) on %s [Ended]" % ( show_id, next_episode.airdate, _ago(latest_delta), show.network["name"], ) else: msg = "Next episode of {0} airs {1} ({2})".format(show_id, next_episode.airdate, _ago(next_delta)) # Not all shows have network info for some reason if show.network: msg = "{0} on {1}".format(msg, show.network["name"]) bot.say(channel, msg.encode("UTF-8"))
def series_lookup(session=None, only_cached=False, **lookup_params): search_params = search_params_for_series(**lookup_params) # Searching cache first series = from_cache(session=session, cache_type=TVMazeSeries, search_params=search_params) search = None # Preparing search from lookup table title = lookup_params.get('series_name') or lookup_params.get('show_name') or lookup_params.get('title') if not series and title: log.debug('did not find exact match for series {0} in cache, looking in search table'.format( search_params['name'])) search = from_lookup(session=session, title=title) if search and search.series: series = search.series log.debug('found series {0} from search table'.format(series.name)) if only_cached: if series: # If force_cache is True, return series even if it expired log.debug('forcing cache for series {0}'.format(series.name)) return series raise LookupError('Series %s not found from cache' % lookup_params) if series and not series.expired: log.debug('returning series {0} from cache'.format(series.name)) return series prepared_params = prepare_lookup_for_pytvmaze(**lookup_params) try: log.debug('trying to fetch series {0} from pytvmaze'.format(title)) pytvmaze_show = get_show(**prepared_params) except ShowNotFound as e: log.debug('could not find series {0} in pytvmaze'.format(title)) raise LookupError(e) except ConnectionError as e: log.warning(e) raise LookupError(e) # See if series already exist in cache series = session.query(TVMazeSeries).filter(TVMazeSeries.tvmaze_id == pytvmaze_show.maze_id).first() if series: log.debug('series {0} is already in cache, checking for expiration'.format(series.name)) if series.expired: series.update(pytvmaze_show, session) else: log.debug('creating new series {0} in tvmaze_series db'.format(pytvmaze_show.name)) series = TVMazeSeries(pytvmaze_show, session) session.add(series) # Check if show returned from lookup table as expired if series and title.lower() == series.name.lower(): return series elif series and not search: log.debug('mismatch between series title {0} and search title {1}. ' 'saving in lookup table'.format(title, series.name)) session.add(TVMazeLookup(search_name=title, series=series)) elif series and search: log.debug('Updating search result in db') search.series = series return series
def estimate(self, entry): if not all(field in entry for field in ['series_name', 'series_season', 'series_episode']): return series_name = entry['series_name'] season = entry['series_season'] episode_number = entry['series_episode'] year_match = re.search('\(([\d]{4})\)', series_name) # Gets year from title if present if year_match: year_match = year_match.group(1) kwargs = {} kwargs['maze_id'] = entry.get('tvmaze_id') kwargs['tvdb_id'] = entry.get('tvdb_id') or entry.get( 'trakt_series_tvdb_id') kwargs['tvrage_id'] = entry.get('tvrage_id') or entry.get( 'trakt_series_tvrage_id') kwargs['show_name'] = re.sub( '\(([\d]{4})\)', '', series_name).rstrip() # Remove year from name if present kwargs['show_year'] = entry.get('trakt_series_year') or entry.get( 'year') or entry.get('imdb_year') or year_match kwargs['show_network'] = entry.get('network') or entry.get( 'trakt_series_network') kwargs['show_country'] = entry.get('country') or entry.get( 'trakt_series_country') kwargs['show_language'] = entry.get('language') log.debug('Searching TVMaze for airdate of {0} season {1} episode {2}'. format(kwargs['show_name'], season, episode_number)) for k, v in kwargs.items(): if v: log.debug('{0}: {1}'.format(k, v)) try: tvmaze_show = get_show(**kwargs) except ShowNotFound as e: log.warning('Could not found show on TVMaze: {0}'.format(e)) return try: episode = tvmaze_show[season][episode_number] except SeasonNotFound as e: log.debug( 'Show {0} does not appear to have a season {1}: {2}'.format( series_name, season, e)) return except EpisodeNotFound as e: log.debug( 'Show {0} does not appear to have a season {1} and episode {2}: {3}' .format(series_name, season, episode_number, e)) return if not episode.airdate: log.debug('empty airdate received from episode, probably TBA') return airdate = datetime.strptime(episode.airdate, '%Y-%m-%d') log.debug('received airdate: {0}'.format(airdate)) return airdate
def byId(idType, id): logger.info("Requesting info for %s key %s from TVMaze" % (idType, id)) try: if idType == "thetvdb": info = pytvmaze.get_show(tvdb_id=id) elif idType == "tvrage": info = pytvmaze.get_show(tvrage_id=id) elif idType == "tvmaze": info = pytvmaze.get_show(maze_id=id) else: logger.error("Invalid call to byId() using idType %s" % idType) return None except pytvmaze.ShowNotFound: logger.error("Unable to find show on TVMaze") return None externals = info.externals rageid = externals["tvrage"] if "tvrage" in externals.keys() else None tvdbid = externals["thetvdb"] if "thetvdb" in externals.keys() else None title = info.name poster = info.image["medium"] if "medium" in info.image.keys() else None return TvMaze(info.id, rageid, tvdbid, title, poster)
def tvmaze(self, sender, message, raw_message): ''' Fetch TV episode information from TVmaze.com ''' try: show = pytvmaze.get_show(show_name=message, embed='episodes') except pytvmaze.exceptions.ShowNotFound: return self.bot.respond('Show "%s" not found.' % message, raw_message) if not show.episodes: return self.bot.respond('No episodes found for "%s".' % show.name, raw_message) next_episode = None now = get_utc_datetime() # go through the episodes in reverse order for episode in reversed(show.episodes): # episode has id and name, but no airstamp yet (not announced) if not episode.airstamp: continue # Episode is in the past, stop searching if parse_datetime(episode.airstamp) < now: break # episode is (still) in the future next_episode = episode if not next_episode: next_episode = show.episodes.pop() msg = 'Latest episode of "{show_name}" {season:d}x{episode:02d} "{title}" aired on {date} ({relative_date})' else: msg = 'Next episode of "{show_name}" {season:d}x{episode:02d} "{title}" airs on {date} ({relative_date})' next_episode_time = parse_datetime(next_episode.airstamp) msg = msg.format( show_name=show.name, season=next_episode.season_number, episode=next_episode.episode_number, title=next_episode.title, date=next_episode_time.strftime('%Y-%m-%d'), relative_date=get_relative_time_string(next_episode_time, no_time=True) ) # Not all shows have network info for some reason if show.network: msg += ' on %s' % (show.network['name']) if show.status == 'Ended': msg += ' [ended]' self.bot.respond(msg, raw_message)
def estimate(self, entry): if not all(field in entry for field in ['series_name', 'series_season', 'series_episode']): return series_name = entry['series_name'] season = entry['series_season'] episode_number = entry['series_episode'] year_match = re.search('\(([\d]{4})\)', series_name) # Gets year from title if present if year_match: year_match = year_match.group(1) kwargs = {} kwargs['maze_id'] = entry.get('tvmaze_id') kwargs['tvdb_id'] = entry.get('tvdb_id') or entry.get('trakt_series_tvdb_id') kwargs['tvrage_id'] = entry.get('tvrage_id') or entry.get('trakt_series_tvrage_id') kwargs['show_name'] = re.sub('\(([\d]{4})\)', '', series_name).rstrip() # Remove year from name if present kwargs['show_year'] = entry.get('trakt_series_year') or entry.get('year') or entry.get( 'imdb_year') or year_match kwargs['show_network'] = entry.get('network') or entry.get('trakt_series_network') kwargs['show_country'] = entry.get('country') or entry.get('trakt_series_country') kwargs['show_language'] = entry.get('language') log.debug('Searching TVMaze for airdate of {0} season {1} episode {2}'.format(kwargs['show_name'], season, episode_number)) for k, v in kwargs.items(): if v: log.debug('{0}: {1}'.format(k, v)) try: tvmaze_show = get_show(**kwargs) except ShowNotFound as e: log.warning('Could not found show on TVMaze: {0}'.format(e)) return try: episode = tvmaze_show[season][episode_number] except SeasonNotFound as e: log.debug('Show {0} does not appear to have a season {1}: {2}'.format(series_name, season, e)) return except EpisodeNotFound as e: log.debug( 'Show {0} does not appear to have a season {1} and episode {2}: {3}'.format(series_name, season, episode_number, e)) return if not episode.airdate: log.debug('empty airdate received from episode, probably TBA') return airdate = datetime.strptime(episode.airdate, '%Y-%m-%d') log.debug('received airdate: {0}'.format(airdate)) return airdate
def search(data): """ Search TVMaze for Show Info. :param data: show data :return: show details """ year = data.get('year') country = data.get('country') clean_name = pynab.ids.clean_name(data.get('name')) log.debug('tvmaze: attempting to find "{}" online'.format(clean_name)) # code contributed by srob650 (https://github.com/srob650) showname = '' if year: showname = clean_name[:-5] if country: showname = clean_name.split(country)[0].strip() if not year or country: showname = clean_name maze_show = None try: maze_show = pytvmaze.get_show(show_name=showname, show_year=year, show_country=country) except Exception as e: log.debug('tvmaze: exception: {}'.format(e)) if maze_show: log.debug('tvmaze: returning show - {} with id - {}'.format(maze_show.name, maze_show.id)) return maze_show.id else: log.debug('tvmaze: No show found') return None
def search(data): """ Search TVMaze for Show Info. :param data: show data :return: show details """ year = data.get("year") country = data.get("country") clean_name = pynab.ids.clean_name(data.get("name")) log.debug('tvmaze: attempting to find "{}" online'.format(clean_name)) # code contributed by srob650 (https://github.com/srob650) showname = "" if year: showname = clean_name[:-5] if country: showname = clean_name.split(country)[0].strip() if not year or country: showname = clean_name maze_show = None try: maze_show = pytvmaze.get_show(show_name=showname, show_year=year, show_country=country) except Exception as e: log.debug("tvmaze: exception: {}".format(e)) if maze_show: log.debug("tvmaze: returning show - {} with id - {}".format(maze_show.name, maze_show.id)) return maze_show.id else: log.debug("tvmaze: No show found") return None
def get_tvmaze(self, tvdb_id): return pytvmaze.get_show(tvdb_id=tvdb_id)
USING http://www.tvmaze.com/ API Script to iterate through all TV Series in TVmaze DB. Using a python implementation of the TV Maze REST API. #https://github.com/srob650/pytvmaze The TVmaze DB holds information about 14803 Tv Series. ''' import pytvmaze as PTM import sys lowerLimit = 1 upperLimit = 14803 if __name__ == "__main__": for id in range(lowerLimit,upperLimit): try: show = PTM.get_show(maze_id = id,embed = 'episodes') numberOfSeasons = len(show.seasons) nameOfTheShow = show.name try: f = open('series.txt','a') s = nameOfTheShow+" has "+str(numberOfSeasons)+" seasons." f.write(s+'\n') f.close() except Exception as e: print e pass except Exception as e: f = open('series.txt','a') f.write(str(e) + '\n') f.close()