def __init__(self, show, season, episode, original=None, language='en', logger=None, tmdbid=False): tmdb.API_KEY = tmdb_api_key if logger: self.log = logger else: self.log = logging.getLogger(__name__) if not tmdbid: self.log.info( "ID supplied is not a TMDB ID, attempting to convert") find = tmdb.Find(show) response = find.info(external_source='tvdb_id') try: new = find.tv_results[0]['id'] self.log.info("Replacing TVDB ID %s with TMDB ID %s" % (show, new)) show = find.tv_results[0]['id'] except: self.log.exception("Unable to convert TVDB to TMDB") for i in range(3): try: seriesquery = tmdb.TV(show) seasonquery = tmdb.TV_Seasons(show, season) episodequery = tmdb.TV_Episodes(show, season, episode) self.show = show self.showid = show self.season = season self.episode = episode self.rating = None self.HD = None self.original = original # Gather information from theTVDB self.showdata = seriesquery.info() self.seasondata = seasonquery.info() self.episodedata = episodequery.info() self.credit = episodequery.credits() self.show = self.showdata['name'] self.genre = self.showdata['genres'] self.network = self.showdata['networks'] # self.contentrating = self.showdata['rating'] self.title = self.episodedata['name'] self.description = self.episodedata['overview'] self.airdate = self.episodedata['air_date'] # Generate XML tags for Actors/Writers/Directors self.xml = self.xmlTags() break except Exception as e: self.log.exception( "Failed to connect to TVDB, trying again in 20 seconds.") time.sleep(20)
def __init__(self, mediatype, tmdbid=None, imdbid=None, tvdbid=None, season=None, episode=None, original=None, language=None, logger=None): tmdb.API_KEY = tmdb_api_key self.log = logger or logging.getLogger(__name__) self.log.debug("Input IDs:") self.log.debug("TMDBID: %s" % tmdbid) self.log.debug("IMDBID: %s" % imdbid) self.log.debug("TVDBID: %s" % tvdbid) self.tmdbid = self.resolveTmdbID(mediatype, tmdbid=tmdbid, tvdbid=tvdbid, imdbid=imdbid) self.log.debug("Using TMDB ID: %s" % self.tmdbid) if not self.tmdbid: self.log.error("Unable to resolve a valid TMDBID.") raise TMDBIDError self.mediatype = mediatype self.language = getAlpha2BCode(language, default='en') self.log.debug("Tagging language determined to be %s." % language) self.original = original if self.mediatype == MediaType.Movie: query = tmdb.Movies(self.tmdbid) self.moviedata = query.info(language=self.language) self.externalids = query.external_ids(language=self.language) self.credit = query.credits() try: releases = query.release_dates() release = next(x for x in releases['results'] if x['iso_3166_1'] == 'US') rating = release['release_dates'][0]['certification'] self.rating = self.getRating(rating) except KeyboardInterrupt: raise except: self.log.error("Unable to retrieve rating.") self.rating = None self.title = self.moviedata['title'] self.genre = self.moviedata['genres'] self.tagline = self.moviedata['tagline'] self.description = self.moviedata['overview'] self.date = self.moviedata['release_date'] self.imdbid = self.externalids.get('imdb_id') or imdbid elif self.mediatype == MediaType.TV: self.season = int(season) self.episode = int(episode) seriesquery = tmdb.TV(self.tmdbid) seasonquery = tmdb.TV_Seasons(self.tmdbid, season) episodequery = tmdb.TV_Episodes(self.tmdbid, season, episode) self.showdata = seriesquery.info(language=self.language) self.seasondata = seasonquery.info(language=self.language) self.episodedata = episodequery.info(language=self.language) self.credit = episodequery.credits() self.externalids = seriesquery.external_ids(language=self.language) try: content_ratings = seriesquery.content_ratings() rating = next(x for x in content_ratings['results'] if x['iso_3166_1'] == 'US')['rating'] self.rating = self.getRating(rating) except KeyboardInterrupt: raise except: self.log.error("Unable to retrieve rating.") self.rating = None self.showname = self.showdata['name'] self.genre = self.showdata['genres'] self.network = self.showdata['networks'] self.title = self.episodedata['name'] or "Episode %d" % (episode) self.description = self.episodedata['overview'] self.date = self.episodedata['air_date'] self.imdbid = self.externalids.get('imdb_id') or imdbid self.tvdbid = self.externalids.get('tvdb_id') or tvdbid
def get_episode_metadata(identificator, metadatatype, language): """ returns episode metadata """ try: episode_cache = CACHE['metadata']['episode'][identificator['tmdb']][identificator['season']][identificator['episode']] except KeyError: episode_cache = None # use value from cache if cache exists if episode_cache: return episode_cache[metadatatype] try: episode = tmdbsimple.TV_Episodes( identificator['tmdb'], identificator['season'], identificator['episode'] ).info(language=language) except requests.exceptions.HTTPError: raise error.NotEnoughData("Problem with accessing TMDb") metadata = { 'showtitle': get_tvshow_metadata(identificator, 'showtitle', language), 'title': episode.get('name'), 'premiered': episode.get('air_date'), 'show_premiered': get_tvshow_metadata(identificator, 'premiered', language), 'plot': episode.get('overview'), 'rating': episode.get('vote_average'), 'votes': episode.get('vote_count'), 'studios': get_tvshow_metadata(identificator, 'studios', language), 'networks': get_tvshow_metadata(identificator, 'networks', language), 'certification': get_tvshow_metadata(identificator, 'certification', language), } metadata['directors'] = [] metadata['scriptwriters'] = [] if 'crew' in episode: for crewmember in episode['crew']: if crewmember['job'] == 'Director': metadata['directors'].append(crewmember['name']) elif crewmember['job'] == 'Writer': metadata['scriptwriters'].append(crewmember['name']) metadata['actors'] = get_tvshow_metadata(identificator, 'actors', language) if 'guest_stars' in episode: for guest_star in episode['guest_stars']: if guest_star['character']: metadata['actors'].append( {'name': guest_star['name'], 'role': guest_star['character']}) # write metadata to cache tmdb = identificator['tmdb'] episode = identificator['episode'] season = identificator['season'] if tmdb not in CACHE['metadata']['episode']: CACHE['metadata']['episode'][tmdb] = {} if season not in CACHE['metadata']['episode'][tmdb]: CACHE['metadata']['episode'][tmdb][season] = {} CACHE['metadata']['episode'][tmdb][season][episode] = metadata return metadata[metadatatype]
def __init__(self, **kwargs): super(Movie_db, self).__init__(**kwargs) # parameters self.api_key = kwargs.get('api_key', None) self.language = kwargs.get('language', 'en-us') self.action = kwargs.get('action', None) self.region = kwargs.get('region', None) self.movie = kwargs.get('movie', None) self.movie_extra = kwargs.get('movie_extra', None) self.tv = kwargs.get('tv', None) self.tv_extra = kwargs.get('tv_extra', None) self.tv_season = kwargs.get('tv_season', None) self.tv_episode = kwargs.get('tv_episode', None) self.people = kwargs.get('people', None) logger.debug("Movie Db launch for action %s", self.action) # check parameters if self._is_parameters_ok(): tmdb.API_KEY = self.api_key if self.action == MOVIEDB_ACTIONS[0]: # MOVIE if self._is_movie_parameters_ok(): logger.debug("Searching for movies %s for language %s", self.movie, self.language) result = dict() result["query"] = self.movie search = tmdb.Search() search_response = search.movie(query=self.movie, language=self.language) first_movie = next(iter(search_response["results"]), None) if first_movie is None: logger.debug("No movie matches the query") else: logger.debug("Movie db first result : %s with id %s", first_movie['title'], first_movie['id']) movie = tmdb.Movies(first_movie['id']) result['movie'] = movie.info(language=self.language, append_to_response=self.movie_extra) self.say(result) if self.action == MOVIEDB_ACTIONS[1]: # PEOPLE if self.is_people_parameters_ok(): logger.debug("Searching for people with query %s for language %s", self.people, self.language) search = tmdb.Search() response = search.person(query=self.people, language=self.language) first_people = search.results[0] logger.debug("Movie db first result for people : %s", first_people) if first_people is None: logger.debug("No people matches the query") self.say(None) else: people = tmdb.People(first_people['id']) peopleResponse = people.info(language=self.language) peopleResponse['known_for'] = first_people['known_for'] self.say(peopleResponse) if self.action == MOVIEDB_ACTIONS[2]: # POPULAR logger.debug("Searching for popular movies for language %s", self.language) movies = tmdb.Movies() popular_response = movies.popular(language=self.language) self.say(popular_response) if self.action == MOVIEDB_ACTIONS[3]: # TOP_RATED logger.debug("Searching for top rated movies for language %s", self.language) movies = tmdb.Movies() top_rated_response = movies.top_rated(language=self.language) self.say(top_rated_response) if self.action == MOVIEDB_ACTIONS[4]: # UPCOMING logger.debug("Searching for upcoming movies for language %s", self.language) movies = tmdb.Movies() upcoming = movies.upcoming(language=self.language, region=self.region) self.say(upcoming) if self.action == MOVIEDB_ACTIONS[5]: # NOW_PLAYING logger.debug("Searching for now playing movies for language %s", self.language) movies = tmdb.Movies() now_playing_response = movies.now_playing(language=self.language, region=self.region) self.say(now_playing_response) if self.action == MOVIEDB_ACTIONS[6]: # TV if self._is_tv_parameters_ok(): logger.debug("Searching for tv show %s for language %s", self.tv, self.language) result = dict() result["query"] = self.tv search = tmdb.Search() search_response = search.tv(query=self.tv, language=self.language) first_tv = next(iter(search_response["results"]), None) if first_tv is None: logger.debug("No tv matches the query") else: logger.debug("Movie db first result : %s with id %s", first_tv['name'], first_tv['id']) tv = tmdb.TV(first_tv['id']) result['tv'] = tv.info(language=self.language, append_to_response=self.tv_extra) self.say(result) if self.action == MOVIEDB_ACTIONS[7]: # TV_POPULAR logger.debug("Searching for popular TV Shows for language %s", self.language) tv = tmdb.TV() popular_response = tv.popular(language=self.language) self.say(popular_response) if self.action == MOVIEDB_ACTIONS[8]: # TV_TOP_RATED logger.debug("Searching for top rated TV Shows for language %s", self.language) tv = tmdb.TV() top_rated_response = tv.top_rated(language=self.language) self.say(top_rated_response) if self.action == MOVIEDB_ACTIONS[9]: # TV_LATEST logger.debug("Searching for latest TV Shows for language %s", self.language) tv = tmdb.TV() latest = tv.latest(language=self.language) self.say(latest) if self.action == MOVIEDB_ACTIONS[10]: # TV_SEASON if self._is_tv_season_parameters_ok(): logger.debug("Searching for Season %s of TV Show %s for language %s", self.tv_season, self.tv, self.language) search = tmdb.Search() search_response = search.tv(query=self.tv, language=self.language) result = dict() result["query"] = dict() result["query"]["tv"] = self.tv result["query"]["season"] = self.tv_season first_tv = next(iter(search_response["results"]), None) result["tv"] = first_tv if first_tv is None: logger.debug("No tv matches the query") else: logger.debug("Movie db first result : %s with id %s", first_tv['name'], first_tv['id']) season = tmdb.TV_Seasons(first_tv['id'], self.tv_season) result["season"] = season.info(language=self.language, append_to_response=self.tv_extra) self.say(result) if self.action == MOVIEDB_ACTIONS[11]: # TV_EPISODE if self._is_tv_episode_parameters_ok(): logger.debug("Searching for Episode %s of season %s of TV Show %s for language %s", self.tv_episode, self.tv_season, self.tv, self.language) search = tmdb.Search() search_response = search.tv(query=self.tv, language=self.language) result = dict() result["query"] = dict() result["query"]["tv"] = self.tv result["query"]["season"] = self.tv_season result["query"]["episode"] = self.tv_episode first_tv = next(iter(search_response["results"]), None) result["tv"] = first_tv if first_tv is None: logger.debug("No tv matches the query") else: logger.debug("Movie db first result : %s with id %s", first_tv['name'], first_tv['id']) episode = tmdb.TV_Episodes(first_tv['id'], self.tv_season, self.tv_episode) result["episode"] = episode.info(language=self.language, append_to_response=self.tv_extra) self.say(result)
cursor.execute(sql, (tv.networks[0].get("name"), tv.id)) sql = "INSERT INTO media(critic_rating,release_date,synopsis,year,contentid) VALUES (%s, %s, %s, %s,%s)" cursor.execute( sql, (0, tv.first_air_date, tv.overview[:255], year, tv.id)) for season in tv.seasons: time.sleep(10) print(season) sql = "INSERT INTO tvseries_seasons (tvseries_contentid,seasons_season_id) VALUES(%s,%s)" cursor.execute(sql, (tv.id, season.get("id"))) sql = "INSERT INTO season (synopsis,tv_id,season_id) VALUES(%s,%s,%s)" cursor.execute( sql, (season.get("overview")[:255], tv.id, season.get("id"))) i = 1 while (i <= season.get("episode_count")): episode = tmdb.TV_Episodes(tv_id, season.get("season_number"), i) episode.info() print("episode number " + str(episode.episode_number) + ": " + episode.overview) sql = "INSERT INTO episode (season_id,episode_num,synopsis) VALUES(%s,%s,%s)" cursor.execute( sql, (episode.season_number, i, episode.overview[:255])) sql = "INSERT INTO season_episodes(season_season_id,episodes_season_id) VALUES(%s,%s)" cursor.execute(sql, (season.get("id"), episode.id)) i += 1 db.commit() finally: db.close()
def populate(): for each in pop_list: a = each while a == each: try: show = tmdb.TV(a) response = show.info() tv_show_name = response['name'] tv_show_id = response['id'] tv_show_synopsis = response['overview'] tv_show_poster = response['poster_path'] tv_show_avg_rating = response['vote_average'] tv_show_date = response['first_air_date'] #print(tv_show_year) strip_date = datetime.strptime(tv_show_date, '%Y-%m-%d') strip_year = strip_date.year tv_show_year = int(strip_year) finallist = [] genrelist = response['genres'] tv_show_genre_id = {} for each in genrelist: finallist.append(each['name']) tv_show_genre_id[each['name']] = each['id'] tv_show_genre = finallist add_show(tv_show_name, tv_show_id, tv_show_synopsis, tv_show_poster, tv_show_avg_rating, tv_show_year, tv_show_genre, tv_show_genre_id) a = -1 except: a = -1 for each in pop_list: a = each b = 1 while a == each: try: show = tmdb.TV(a) show_response = show.info() season = tmdb.TV_Seasons(a, b) response = season.info() tv_season_id = response['id'] tv_season_number = response['season_number'] tv_show_id = show_response['id'] add_season(tv_show_id, tv_season_id, tv_season_number) b = b + 1 except: a = -1 b = 1 for each in pop_list: a = each b = 1 c = 1 check = 1 while a == each: try: show = tmdb.TV(a) #print('Show taken') show_response = show.info() season = tmdb.TV_Seasons(a, b) #print('Season taken') season_response = season.info() tv_season_id = season_response['id'] episode = tmdb.TV_Episodes(a, b, c) #print('Episode taken') response = episode.info() tv_episode_id = response['id'] #print(tv_episode_id) tv_episode_number = response['episode_number'] #print(tv_episode_number) tv_show_id = show_response['id'] #print(tv_show_id) tv_episode_airdate = response['air_date'] #print(tv_episode_airdate) tv_episode_synopsis = response['overview'] #print(tv_episode_synopsis) tv_episode_name = response['name'] #print(tv_episode_name) #tv_episode_avg_rating = response['vote_average'] #print(tv_episode_avg_rating) tv_season_num = response['season_number'] #print(tv_season_num) add_episode(tv_season_id, tv_show_id, tv_episode_id, tv_season_num, tv_episode_name, tv_episode_number, tv_episode_airdate, tv_episode_synopsis) c = c + 1 check = 1 #time.sleep(1) except: #print("except") b = b + 1 c = 1 if check == 0: a = -1 b = 1 else: check = 0
def resolve_episode_ids(series, season, episode, year=None, imdbid=None): # To store the IDs found ids = {} # Initialize a TMDB search object tmdb_search = tmdbsimple.Search() ################################################################## # TVDB tvdb = tvdb_api.Tvdb(language='en', ) tvdb_series = None try: # Try getting the series directly, but check the year if available # as sometimes series have the same name but are from different years tvdb_series = tvdb[series] if (imdbid is None or tvdb_series['imdbId'] != imdbid) and \ year is not None and tvdb_series['firstAired'] and \ year != int(tvdb_series['firstAired'].split('-')[0]): # It is not the expected year, we thus need to perform a search tvdb_series = None tvdb_search = tvdb.search(series) for s in tvdb_search: if imdbid is None or s['imdbId'] != imdbid: if not s['seriesName'].startswith(series): LOGGER.debug('TVDB: Discarding result because of the ' 'name not beginning with the expected ' 'series name: {}'.format(s)) continue if int(s['firstAired'].split('-')[0]) != year: LOGGER.debug('TVDB: Discarding result because of the ' 'year not matching: {}'.format(s)) continue tvdb_series = tvdb[s['seriesName']] break tvdb_season = tvdb_series[season] tvdb_episode = tvdb_season[episode] ids['tvdb'] = tvdb_episode['id'] except Exception as e: LOGGER.debug(e) LOGGER.warning('Unable to find series {}, season {}, ' 'episode {} on TheTVDB'.format(series, season, episode)) ################################################################## # TMDB params = {'query': series} if year is not None: params['first_air_date_year'] = year try: tmdb_search.tv(**params) except Exception as e: LOGGER.debug(e) tmdb_search.results = [] for s in tmdb_search.results: if s['name'] != series and \ (tvdb_series is None or (s['name'] != tvdb_series['seriesName'] and s['name'] not in tvdb_series['aliases'])): LOGGER.debug('TMDB: Discarding result because of the name ' 'not matching with the expected series ' 'name: {}'.format(s)) continue # Try to get the episode information tmdb_episode = tmdbsimple.TV_Episodes(s['id'], season, episode) try: tmdb_external_ids = tmdb_episode.external_ids() except Exception as e: continue # If we have the tvdb information, check that we got the right # id... else, it is probably not the episode we are looking # for! if 'tvdb' in ids and \ tmdb_external_ids.get('tvdb_id') is not None and \ ids['tvdb'] != tmdb_external_ids['tvdb_id']: LOGGER.debug('TMDB: Discarding result because of the TVDB id not ' 'matching with the one found on the TVDB ' 'side: {}'.format(s)) continue ids['tmdb'] = tmdb_external_ids['id'] break return ids
def get_episode_info(show_id, season_number, episode_number): episode = tmdb.TV_Episodes(show_id, season_number, episode_number) response = episode.info() return response