def _is_tv_anime(tmdb_id): """Cacheable part of is_tv_anime()""" api_results = tmdb.TV(tmdb_id).keywords() # Check if the content contains Keyword: Anime if is_key_value_in_list("name", "anime", api_results["results"]): log.handler( str(tmdb_id) + " is anime.", log.INFO, _logger, ) return True # Check if fallback method is enabled if ANIME_CHECK_FALLBACK: tv_info = tmdb.TV(tmdb_id).info() # Check if genere is Animation and Country is Japan if (is_key_value_in_list("name", "Animation", tv_info["genres"]) and "JP" in tv_info["origin_country"]): log.handler( str(tmdb_id) + " is anime, based on fallback detection.", log.INFO, _logger, ) return True log.handler( str(tmdb_id) + " is not anime.", log.INFO, _logger, ) return False
def index(request): """ view function returns template that displays popular and upcoming movies """ popular_movies_tmdb = tmdb.Movies('popular') popular_movies = popular_movies_tmdb.info()['results'] upcoming_movies_tmdb = tmdb.Movies('upcoming') upcoming_movies = upcoming_movies_tmdb.info()['results'] popular_shows_tmdb = tmdb.TV('popular') popular_shows = popular_shows_tmdb.info()['results'] current_shows_tmdb = tmdb.TV('airing_today') current_shows = current_shows_tmdb.info()['results'] top_shows_tmdb = tmdb.TV('top_rated') top_shows = top_shows_tmdb.info()['results'] return render( request, 'movies.html', { "popular": popular_movies, 'upcoming': upcoming_movies, 'shows': popular_shows, "current": current_shows, 'top': top_shows })
def add_show(): if auth.user_id != 1: return redirect(URL("default", "index")) response.title = T("Add TV Show") show = None if session.language_for_search != None: language = session.language_for_search else: language = "es" if request.vars.tmdbid != None: show_es = tmdb.TV(request.vars.tmdbid) r = show_es.info(language=language) show = tmdb.TV(request.vars.tmdbid) r = show.info() credits = show.credits()["cast"] str_credits = u"" for i in credits: str_credits = str_credits + u"{0} ({1}), ".format(i["name"], i["character"]) str_created = u"" for i in show.created_by: str_created = str_created + u"{0}, ".format(i["name"], ) str_gender = u"" for i in show_es.genres: str_gender = str_gender + u"{0}, ".format(i["name"], ) titles = show.alternative_titles()["results"] # response.write(show) img = show.poster_path _get_image(img) if len(str_created) != 0: str_created = str_created[:-2] if len(str_credits) != 0: str_credits = str_credits[:-2] if len(str_gender) != 0: str_gender = str_gender[:-2] form = SQLFORM(db.tv_show, upload=URL("download")) form.vars.language = db(db.languages.code == language).select().first().id if show != None: # for i in titles: # if i["iso_3166_1"] == language.upper(): form.vars.show_title = i["title"]; break # else: form.vars.show_title = show_es.name form.vars.release_date = show.first_air_date form.vars.movie_db_id = show_es.id form.vars.rating = show_es.vote_average form.vars.rating_count = show_es.vote_count form.vars.overview = show_es.overview form.vars.number_of_seasons = show_es.number_of_seasons form.vars.number_of_episodes = show_es.number_of_episodes form.vars.episode_run_time = u"-".join([str(i) for i in show.episode_run_time]) + T(" Minutes") form.vars.credits = str_credits form.vars.created_by = str_created form.vars.genre = str_gender form.vars.imdb_id = show.external_ids()["imdb_id"] form.vars.image = img[1:] if form.process().accepted: return redirect(URL("default", "index")) return dict(form=form, share=False)
def query_top_shows(self, total=1000): tv = tmdb.TV() pop_shows = [] results = [] # 20 results per page in API for i in range(1, total // 20 + 1): pop_shows += tv.popular(page=i)['results'] for show in pop_shows: temp = tmdb.TV(show['id']) results.append(temp.info()) return results
def series(request): query = str(request.GET.get('query', '')) airing_today_series_tmdb = tmdb.TV('airing_today') airing_today_series = airing_today_series_tmdb.info()['results'] on_the_air_series_tmdb = tmdb.TV('on_the_air') on_the_air_series = on_the_air_series_tmdb.info()['results'] popular_series_tmdb = tmdb.TV('popular') popular_series = popular_series_tmdb.info()['results'] top_rated_series_tmdb = tmdb.TV('top_rated') top_rated_series = top_rated_series_tmdb.info()['results'] return render(request, "series_page.html", {'airing_today_series':airing_today_series ,'popular_series':popular_series, 'top_rated_series':top_rated_series,'on_the_air_series': on_the_air_series})
def serial_credits(serial_id): tv = tmdb.TV(serial_id).credits() credits_list = { 'cast': tv['cast'], 'crew': tv['crew'], } return credits_list
def serial_info(serial_id): tv = tmdb.TV(serial_id).info() info = { 'info': tv, 'name': tv['name'], 'poster_path': tv['poster_path'], 'in_production': tv['in_production'], 'seasons': tv['seasons'], 'created_by': tv['created_by'], } if tv['first_air_date']: info['first_air_date'] = tv['first_air_date'] else: info['first_air_date'] = 'N/A' if tv['last_episode_to_air']: info['last_season_number'] = tv['last_episode_to_air']['season_number'] info['last_episode_number'] = tv['last_episode_to_air'][ 'episode_number'] info['last_date'] = tv['last_episode_to_air']['air_date'] info['last_name'] = tv['last_episode_to_air']['name'] info['last_overview'] = tv['last_episode_to_air']['overview'] if tv['next_episode_to_air']: info['next_season_number'] = tv['next_episode_to_air']['season_number'] info['next_episode_number'] = tv['next_episode_to_air'][ 'episode_number'] info['next_date'] = tv['next_episode_to_air']['air_date'] info['next_name'] = tv['next_episode_to_air']['name'] info['next_overview'] = tv['next_episode_to_air']['overview'] return info
def get_tv_show_infos(title=None, year=None, tmdb_id=None): """ Return NFO fields and link for a TV show. Args: title (str): TV show title. year (int or str): TV show start year. tmdb_id (str): The Movie Database ID. Returns: tuple: Fields, The Movie Database URL, The Movie Database ID, original language """ if not tmdb_id: tmdb_id = search_tv_show(title, year) serie = tmdb.TV(tmdb_id) infos = serie.info(language=LANGUAGE) nfo_fields = { "title": infos["name"], "originaltitle": infos["original_name"], "plot": infos["overview"], "outline": infos["overview"], "premiered": infos["first_air_date"], "studio": _response_names_only(infos["production_companies"]), "genre": _response_names_only(infos["genres"]), } return ( nfo_fields, f"https://www.themoviedb.org/tv/{tmdb_id}", tmdb_id, infos["original_language"], )
def index(request): """ Render the home page for the website and if the user is signed in then display any upcoming shows that they may have """ upcoming = [] if request.user.is_authenticated: for favorite in request.user.favorites.filter(is_favorite=True).all(): if favorite.moviedb.upcoming_data is not None and favorite.moviedb.upcoming_data != "": upcoming_json = json.loads(favorite.moviedb.upcoming_data) if 'air_date' in upcoming_json: upcoming_json['air_date'] = datetime.strptime( upcoming_json['air_date'], "%Y-%m-%d") upcoming.append({ "data": json.loads(favorite.moviedb.data), "type": favorite.moviedb.type, "upcoming": upcoming_json }) # fetch the most popular movies and tv shows from tmdb movies = tmdb.Movies().popular() tvshows = tmdb.TV().popular() return render( request, "social/index.html", { "upcoming": upcoming, "movies": movies['results'][:12], "tvshows": tvshows['results'][:12] })
def get_episodes(api_key, query, season): tmdb.API_KEY = api_key search = tmdb.Search().tv(query=query) for i, s in enumerate(search["results"]): print( f"{i}." + " " + s["name"], s["original_name"], s["first_air_date"], sep=" - ", ) if not search["results"]: exit(f"Cant find anything for your query: {query}") choice = click.prompt("Enter number corresponding to TV show", type=click.IntRange(min=0, max=i)) id = search["results"][choice]["id"] seasons = tmdb.TV(id=id).info()["number_of_seasons"] if season > seasons: print( "You ask for a season that doesn't exist, this TV show only has", seasons, "season" if seasons == 1 else "seasons", ) exit() tv_season = tmdb.TV_Seasons(tv_id=id, season_number=season).info() episodes = [episode["name"] for episode in tv_season["episodes"]] return episodes
def tvdbInfo(guessData, tvdbid=None): tmdb.API_KEY = tmdb_api_key season = guessData["season"] episode = guessData["episodeNumber"] if not tvdbid: search = tmdb.Search() series = guessData["series"] fullseries = series if 'year' in guessData: fullseries = series + " (" + str(guessData["year"]) + ")" response = search.tv(query=fullseries.encode('ascii', errors='ignore')) if len(search.results) == 0: response = search.tv(query=series.encode('ascii', errors='ignore')) result = search.results[0] tvdbid = result['id'] else: seriesquery = tmdb.TV(tvdbid) showdata = seriesquery.info() series = showdata['name'] try: print("Matched TV episode as %s (TMDB ID:%d) S%02dE%02d" % (series.encode(sys.stdout.encoding, errors='ignore'), int(tvdbid), int(season), int(episode))) except Exception as e: print("Matched TV episode") print(e) return 3, tvdbid, season, episode
def get_recommendations(self, id, media_type): """ Get recommendations about movie or show Args: ID of the (Movie/Show), Media_type (Movie/Show) Return: List represntation of results with title/name and image """ recommendation_list = [] if media_type == "movie": movie = tmdb.Movies(id) response = movie.recommendations() else: show = tmdb.TV(id) response = show.recommendations() for recommendation in response['results']: temp = {} temp['id'] = recommendation['id'] try: temp['title'] = recommendation['title'] except: temp['title'] = recommendation['name'] self.handle_exceptions(temp, 'img', recommendation, 'poster_path') self.handle_exceptions(temp, 'overview', recommendation, 'overview') recommendation_list.append(temp) return recommendation_list
def find_tv(self, tv_show_id): ''' Finds tv show by id :param tv_show_id: :return: ''' return tmdb.TV(tv_show_id)
def get_tvshow_image(identificator, imagetype, language): """ returns the url of a tvshow image """ try: tvshow_cache = CACHE['images']['tvshow'][identificator['tmdb']] except KeyError: tvshow_cache = None if tvshow_cache: return tvshow_cache.get(imagetype) tvshow = tmdbsimple.TV(identificator['tmdb']).info( language=language, include_image_language="null", append_to_response='images' ) images = {} if tvshow['images']['posters']: images['poster'] = CONFIG['base_url'] + \ CONFIG['poster_size'] + \ tvshow['images']['posters'][0]['file_path'] if tvshow['images']['backdrops']: images['background'] = CONFIG['base_url'] + \ CONFIG['background_size'] + \ tvshow['images']['backdrops'][0]['file_path'] CACHE['images']['tvshow'][identificator['tmdb']] = images return images.get(imagetype)
def info(cls, code): try: ret = {} entity = EntityFtv(cls.site_name, code) tmdb = tmdbsimple.TV(code[2:]) entity.code_list.append(['tmdb_id', code[2:]]) cls.info_basic(tmdb, entity) cls.info_content_ratings(tmdb, entity) cls.info_credits(tmdb, entity) for season in entity.seasons: season_no = season.season_no season = tmdbsimple.TV_Seasons(code[2:], season_no) cls.info_credits(season, entity, crew=False) cls.info_external_ids(tmdb, entity) entity = entity.as_dict() cls._process_image(tmdb, entity['art']) entity['actor'] = list( sorted(entity['actor'], key=lambda k: k['order'])) ret['ret'] = 'success' ret['data'] = entity #entity.as_dict() #tmdb_dict except Exception as exception: logger.error('Exception:%s', exception) logger.error(traceback.format_exc()) ret['ret'] = 'exception' ret['data'] = str(exception) return ret
def insert_info(self, id, media_type): """ Get information regarding movie or show. Args: ID of the (Movie/Show), Media_type (Movie/Show) Returns: List representation of result """ result = {} result['id'] = id result['type'] = media_type if media_type == "movie": movie = tmdb.Movies(id) response = movie.info() result['title'] = response['title'] self.handle_exceptions(result, 'image', response, 'poster_path') else: tv = tmdb.TV(id) response = tv.info() result['title'] = response['name'] self.handle_exceptions(result, 'image', response, 'poster_path') lst = [] lst.append(result) return lst
def command(self, connection, event, extra, dbconn): tmdb.API_KEY = self.settings["tmdb_api_key"] id = -1 res = tmdb.Search().tv(query=self.pargs.show) if res["total_results"] > 0: id = res["results"][0]["id"] txt = "No such movie." if id != -1: movie = tmdb.TV(id) movie_info = movie.info() txt = "\x02%s\x02" % movie_info["name"] if movie_info["name"] != movie_info["original_name"]: txt += " (%s)" % movie_info["original_name"] if movie_info["first_air_date"]: txt += " | \x02First Aired:\x02 %s" % movie_info[ "first_air_date"] if movie_info["number_of_seasons"]: txt += " | \x02Nr. of Seasons:\x02 %d" % movie_info[ "number_of_seasons"] if movie_info["vote_count"] > 0: txt += " | \x02Rating:\x02 %.1f/10" % movie_info["vote_average"] if movie_info["homepage"]: txt += " | \x02Homepage:\x02 %s" % movie_info["homepage"] txt += "\n" + plugins.split(movie_info["overview"]) return txt
def send_notification(): profiles = Profile.objects.filter(telegram_id__isnull=False) for profile in profiles: user = User.objects.get(profile=profile) tv = tmdb.TV() serial_list = Serial.objects.filter(owner=user) air_today = tv.airing_today()['results'] air_today_id_list = [tv['id'] for tv in air_today] my_serials_on_air = [ serial for serial in serial_list if serial.serial_id in air_today_id_list ] text_message = '<u>My Serials On Air:</u>\n\n' if my_serials_on_air: for serial in my_serials_on_air: tv = serial_info(serial.serial_id) text = "<b>{} ({})</b>\n".format(tv['name'], tv['first_air_date'][:4]) text_message += text if tv.get('next_overview'): text = "<i>Episode: {} {}</i>\n{}\n\n".format( tv['next_episode_number'], tv['next_name'], tv['next_overview']) text_message += text try: bot.send_message(profile.telegram_id, text_message, parse_mode='HTML') except telebot.apihelper.ApiException: pass
def execute(self, connection, event, extra, dbconn): tmdb.API_KEY = self.settings["tmdb_api_key"] try: pargs = self.parser.parse_args(extra["args"]) if self.parser.help_requested: return self.parser.format_help().strip() except Exception as e: return u"Error: %s" % str(e) id = -1 res = tmdb.Search().tv(query=pargs.show) if res["total_results"] > 0: id = res["results"][0]["id"] txt = "No such movie." if id != -1: movie = tmdb.TV(id) movie_info = movie.info() txt = "\x02%s\x02" % movie_info["name"] if movie_info["name"] != movie_info["original_name"]: txt += " (%s)" % movie_info["original_name"] if movie_info["first_air_date"]: txt += " | \x02First Aired:\x02 %s" % movie_info["first_air_date"] if movie_info["number_of_seasons"]: txt += " | \x02Nr. of Seasons:\x02 %d" % movie_info["number_of_seasons"] if movie_info["vote_count"] > 0: txt += " | \x02Rating:\x02 %.1f/10" % movie_info["vote_average"] if movie_info["homepage"]: txt += " | \x02Homepage:\x02 %s" % movie_info["homepage"] txt += "\n" + plugins.split(movie_info["overview"]) return txt
def get_shows_data(show_ids): """Fetches show data using a wrapper for the TMDB API. Compiles a list of show instances which will be rendered dynamically.""" print("Fetching show data...") poster_base = "https://image.tmdb.org/t/p/w300{picture_id}" url_base = "https://themoviedb.org/tv/{id}" shows = [] # Request data per API id in list for id in show_ids: show = tmdb.TV(id) show.info() # context while waiting print("Getting data for {}".format(show.name)) # get poster image src poster_url = poster_base.format(picture_id=show.poster_path) # make secondary request for trailer videos videos_res = show.videos() videos = videos_res["results"] video_id = None if not len(videos) else videos[0]["key"] url = url_base.format(id=show.id) shows.append( media.Show(show.name, poster_url, show.overview.encode("ascii", "ignore"), video_id, url, [genre["name"] for genre in show.genres], show.vote_average, show.vote_count)) return shows
def refine_translations(id, isTv): vf_zh = '' vf_en = '' if isTv: tv = tmdb.TV(id=id) trans_ret = tv.translations() else: movie = tmdb.Movies(id=id) # TODO: this info is better to use info_ret = movie.info() if check: print(info_ret) if movie.original_language == 'en' and movie.original_title: vf_en = movie.original_title if movie.original_language in ['zh', 'cn'] and movie.original_title: vf_zh = movie.original_title trans_ret = movie.translations() if trans_ret: for item in trans_ret['translations']: if item['iso_3166_1'] == 'CN' and item[ 'iso_639_1'] == 'zh' and not vf_zh: vf_zh = item['data']['name'] if isTv else item['data']['title'] elif item['iso_3166_1'] == 'US' and item[ 'iso_639_1'] == 'en' and not vf_en: vf_en = item['data']['name'] if isTv else item['data']['title'] print(f"find vf_en {vf_en}") else: continue else: logging.warning(f"fail in refine translation: {id} (TV={isTv})") if not vf_en and not isTv: vf_en = movie.title return vf_zh, vf_en
def tmdbTv(tvseries, types): #Tv series/episodes check from TMDb if tvseries in types: try: n = int(types[types.index(tvseries)-1]) except:n=0 if n == 3: try: tvseries = types[types.index(tvseries)+1] except:pass elif n == 2: return(tmdbMovie(tvseries,types)) elif n == 4: try: return(tmdbMovie(types[types.index(tvseries)+1],types)) except: pass response = search.tv(query = tvseries) oneTv = [] for s in search.results: ide = tm.TV(s["id"]) try: res = ide.info() except HTTPError: print("Api is broken") if res["name"].lower() == tvseries.lower(): oneTv.append([res["id"], res["name"], res["episode_run_time"],res["first_air_date"],[x["name"] for x in res["genres"]]]) return(oneTv)
def get_cast(tmdb_id, imdb_id): imdb_movie = ImdbMovie.objects.get(id=imdb_id) if imdb_movie.title_type.name == TITLE_TYPE_SERIES: tv = tmdb.TV(id=tmdb_id) return tv.credits().get(c.API_RESPONSE_CAST) elif imdb_movie.title_type.name in [TITLE_TYPE_MOVIE, TITLE_TYPE_SHORT]: movies = tmdb.Movies(id=tmdb_id) return movies.credits().get(c.API_RESPONSE_CAST)
def get_tv_id(name): tv = md.TV() search = md.Search() response = search.tv(query = name) lst = [] for s in search.results: lst.append(s) return lst[0]['id']
def series(self, tv_id: int()): result = tmdb.TV(tv_id) tv_info = result.info() tv_credits = result.credits() cast = list() for actor in tv_credits['cast']: cast.append( Cast(id=actor['id'], name=actor['name'], character=actor['character'], profile_path=actor['profile_path'])) crew = list() for c in tv_credits['crew']: crew.append( Crew(id=c['id'], name=c['name'], profile_path=c['profile_path'], job=c['job'], department=c['department'])) credits = Credits(cast=cast, crew=crew) prod_companies = list() for company in tv_info['networks']: prod_companies.append( ProductionCompanies(id=company['id'], name=company['name'], logo_path=company['logo_path'], origin_country=company['origin_country'])) show_creaters = list() for creaters in tv_info['created_by']: show_creaters.append( Person(id=creaters['id'], name=creaters['name'], profile_path=creaters['profile_path'], gender=creaters['gender'])) episode_runtime = [run for run in tv_info['episode_run_time']] tv = TVSeries(id=tv_info['id'], name=tv_info['name'], original_name=tv_info['original_name'], original_language=tv_info['original_language'], overview=tv_info['overview'], in_production=tv_info['in_production'], first_air_date=tv_info['first_air_date'], last_air_date=tv_info['last_air_date'], homepage=tv_info['homepage'], number_of_episodes=tv_info['number_of_episodes'], number_of_seasons=tv_info['number_of_seasons'], episode_runtime=episode_runtime, created_by=show_creaters, backdrop_path=tv_info['backdrop_path'], poster_path=tv_info['poster_path'], networks=prod_companies, credits=credits) return tv
def popular(request): popular_list = tmdb.TV().popular()['results'] for elem in popular_list: tv = serial_info(elem['id']) elem['in_production'] = tv['in_production'] elem['year'] = tv['first_air_date'][:4] elem['in_list'] = user_serials_check(request.user, elem['id']) result = {'popular_list': popular_list} return render(request, 'serial/popular.html', result)
def on_air_today(request): air_today_list = tmdb.TV().airing_today()['results'] for elem in air_today_list: tv = serial_info(elem['id']) elem['in_production'] = tv['in_production'] elem['year'] = tv['first_air_date'][:4] elem['in_list'] = user_serials_check(request.user, elem['id']) result = {'air_today_list': air_today_list} return render(request, 'serial/on_air_today.html', result)
def get_show(tmdb_id): returned_from_cache = True key = get_tmdb_show_key(tmdb_id) tmdb_show = cache.get(key, None) if tmdb_show is None: tmdb_show = tmdb.TV(tmdb_id).info(language=LANGUAGE) cache.set(key, tmdb_show, CACHE_TIMEOUT) returned_from_cache = False return tmdb_show, returned_from_cache
def get_by_tmdb_id(self, tmdb_id, content_type, obtain_extras=True): """Obtains a movie or series given a TMDB ID. Args: id: An Integer or String containing the TMDB ID. content_type: String containing "movie" or "tv". """ # Searches for content based on TMDB ID try: # Obtain extras if needed if obtain_extras: extras = "reviews,keywords,videos,credits,images" else: extras = None # Obtain a movie by ID if content_type == "movie": return self._set_content_attributes( content_type, cache.handler( "get movie by tmdb id", page_key=tmdb_id, function=tmdb.Movies(tmdb_id).info, cache_duration=GET_BY_TMDB_ID_CACHE_TIMEOUT, kwargs={"append_to_response": extras}, ), ) # Obtain a TV show by ID if content_type == "tv": return self._set_content_attributes( content_type, cache.handler( "get tv by tmdb id", page_key=tmdb_id, function=tmdb.TV(tmdb_id).info, cache_duration=GET_BY_TMDB_ID_CACHE_TIMEOUT, kwargs={"append_to_response": extras}, ), ) # Content Type was invalid log.handler( "Invalid content_type " + str(content_type) + " in get_by_id().", log.WARNING, _logger, ) except: log.handler( "Failed to obtain content by ID!", log.ERROR, _logger, ) return None
def get_tvshow_metadata(identificator, metadatatype, language): """ returns tvshow metadata """ try: tvshow_cache = CACHE['metadata']['tvshow'][identificator['tmdb']] except KeyError: tvshow_cache = None # use value from cache if cache exists if tvshow_cache: return tvshow_cache[metadatatype] tvshow = tmdbsimple.TV(identificator['tmdb']).info( language=language, include_image_language="null", append_to_response='credits,content_ratings,images' ) metadata = { 'showtitle': tvshow.get('name'), 'premiered': tvshow.get('first_air_date'), 'plot': tvshow.get('overview'), 'rating': tvshow.get('vote_average'), 'votes': tvshow.get('vote_count'), } metadata['certification'] = None for certification in tvshow['content_ratings']['results']: if certification['iso_3166_1'] == CONFIG['certification_country']: metadata['certification'] = str(certification['rating']) metadata['creators'] = [] for creator in tvshow['created_by']: metadata['creators'].append(creator['name']) metadata['studios'] = [] for studio in tvshow['production_companies']: metadata['studios'].append(studio['name']) metadata['networks'] = [] for network in tvshow['networks']: metadata['networks'].append(network['name']) metadata['genres'] = [] for genre in tvshow['genres']: metadata['genres'].append(genre['name']) metadata['actors'] = [] for actor in tvshow['credits']['cast']: metadata['actors'].append( {'name': actor['name'], 'role': actor['character']} ) CACHE['metadata']['tvshow'][identificator['tmdb']] = metadata return metadata[metadatatype]