示例#1
0
 def test_tv_seasons_account_states(self):
     series_id = TV_SEASON_ID
     season_number = TV_SEASON_NUMBER
     name = TV_SEASON_NAME
     tv_seasons = tmdb.TV_Seasons(series_id, season_number)
     response = tv_seasons.account_states()
     self.assertTrue(hasattr(tv_seasons, 'results'))
示例#2
0
    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
示例#3
0
 def test_tv_seasons_info(self):
     series_id = TV_SEASON_ID
     season_number = TV_SEASON_NUMBER
     name = TV_SEASON_NAME
     tv_seasons = tmdb.TV_Seasons(series_id, season_number)
     response = tv_seasons.info()
     self.assertEqual(tv_seasons.name, name)
示例#4
0
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
示例#5
0
def get_season_image(identificator, imagetype, language):
    """ returns the url of a season image"""

    try:
        season_cache = CACHE['images']['season'][identificator['tmdb']][identificator['season']]
    except KeyError:
        season_cache = None

    if season_cache:
        return season_cache.get(imagetype)

    season = tmdbsimple.TV_Seasons(
        identificator['tmdb'],
        identificator['season']
    ).images(
        language=language,
        #include_image_language="null" #bug in tmdb
    )

    images = {}
    if season['posters']:
        images['poster'] = CONFIG['base_url'] + \
                           CONFIG['poster_size'] + \
                           season['posters'][0]['file_path']

    tmdb = identificator['tmdb']
    season = identificator['season']
    if tmdb not in CACHE['images']['season']:
        CACHE['images']['season'][tmdb] = {}

    CACHE['images']['season'][tmdb][season] = images
    return images.get(imagetype)
示例#6
0
def AddSeasons(movie, newmovie):
    for i in movie.seasons:
        if i['air_date']:
            season = Season.objects.create(name=i['name'],
                                           episodecount=i['episode_count'],
                                           movie=newmovie,
                                           position=i['season_number'],
                                           tmdbid=i['id'])

            if len(i['overview']) > 0:
                season.disctiption = i['overview']

            AddPoster(season, i['poster_path'])

            TVseason = tmdb.TV_Seasons(movie.id, i['season_number'])
            TVseason.info(language="ru-RU")
            AddEpisodes(TVseason, season.id)

            try:
                if datetime.strptime(TVseason.episodes[-1]['air_date'],
                                     "%Y-%m-%d") > datetime.today():
                    season.status_id = 2
                else:
                    season.status_id = 3
            except:
                season.status_id = 2

            try:
                if datetime.strptime(i['air_date'],
                                     "%Y-%m-%d") > datetime.today():
                    season.status_id = 1
            except TypeError:
                season.status_id = 1
            season.save()
示例#7
0
 def test_tv_seasons_external_ids(self):
     series_id = TV_SEASON_ID
     season_number = TV_SEASON_NUMBER
     tvdb_id = TV_SEASON_TVDB_ID
     tv_seasons = tmdb.TV_Seasons(series_id, season_number)
     response = tv_seasons.external_ids()
     self.assertEqual(tv_seasons.tvdb_id, tvdb_id)
示例#8
0
def randomEp(id, dic, title):
    season = random.randint(1, len(dic))
    ep = random.randint(1, dic['Season {}'.format(season)])
    episodes = tmdb.TV_Seasons(id, season).info()['episodes']
    print('{}: Season {}, Episode {}, {}'.format(title, season, ep,
                                                 episodes[ep - 1]['name']))
    #Prints a 'b' in front of overview for some reason. Not part of the overview string
    print(episodes[ep - 1]['overview'].encode('utf-8'))
示例#9
0
def update_upcoming_episodes_dates():
    today_date = datetime.today().date()

    seasons_to_check = Episode.objects.select_related('tmdb_season') \
        .filter(Q(tmdb_release_date__gte=today_date) | Q(tmdb_release_date=None)) \
        .exclude(tmdb_season__tmdb_season_number=0) \
        .values('tmdb_season__tmdb_id', 'tmdb_season__tmdb_show__tmdb_id', 'tmdb_season__tmdb_season_number') \
        .distinct()

    for season in seasons_to_check:
        show_id = season['tmdb_season__tmdb_show__tmdb_id']
        season_number = season['tmdb_season__tmdb_season_number']
        tmdb_season_id = season['tmdb_season__tmdb_id']
        key = get_tmdb_season_key(show_id, season_number)
        try:
            tmdb_season = tmdb.TV_Seasons(
                show_id, season_number).info(language=LANGUAGE)
        except HTTPError:
            continue
        cache.set(key, tmdb_season, CACHE_TIMEOUT)

        episodes = tmdb_season.get('episodes')
        existed_episodes = Episode.objects.filter(
            tmdb_id__in=[episode.get('id') for episode in episodes])
        episodes_to_create = []

        for episode in episodes:
            exists = False

            for existed_episode in existed_episodes:
                if episode['id'] == existed_episode.tmdb_id:
                    exists = True

                    new_fields = {
                        'tmdb_id':
                        episode.get('id'),
                        'tmdb_episode_number':
                        episode.get('episode_number'),
                        'tmdb_season_id':
                        tmdb_season_id,
                        'tmdb_name':
                        episode.get('name'),
                        'tmdb_release_date':
                        episode.get('air_date')
                        if episode.get('air_date') != "" else None
                    }
                    update_fields_if_needed(existed_episode, new_fields)
                    break

            if not exists:
                episodes_to_create.append(
                    Episode(tmdb_id=episode.get('id'),
                            tmdb_episode_number=episode.get('episode_number'),
                            tmdb_season_id=tmdb_season_id,
                            tmdb_name=episode.get('name')))

            print(episode['name'], episode['id'])
        Episode.objects.bulk_create(episodes_to_create)
示例#10
0
def get_season(show_tmdb_id, season_number):
    returned_from_cache = True
    key = get_tmdb_season_key(show_tmdb_id, season_number)
    tmdb_season = cache.get(key, None)
    if tmdb_season is None:
        tmdb_season = tmdb.TV_Seasons(show_tmdb_id, season_number).info(language=LANGUAGE)
        cache.set(key, tmdb_season, CACHE_TIMEOUT)
        returned_from_cache = False
    return tmdb_season, returned_from_cache
示例#11
0
def episode_list_extraction(show_id, season, secret_key):
    """

    :param show_id:
    :param season:
    :return:
    """
    db.API_KEY = secret_key
    season_info = db.TV_Seasons(show_id, season).info()
    episode_names = [
        "{0:02d} {1}".format(i + 1, x["name"])
        for i, x in enumerate(season_info["episodes"])
    ]
    return episode_names
示例#12
0
def add_season():
	if auth.user_id != 1: return redirect(URL("default", "index"))
	id = request.vars.show
	show = db(db.tv_show.id == id).select().first()
	if show == None:
		return redirect(URL("default", "index"))
	response.title = T("Add season")
	form = SQLFORM.factory(Field("season", "integer"))
	if form.validate():
		season_en = tmdb.TV_Seasons(show.movie_db_id, season_number=form.vars.season)
		info_en = season_en.info()
		season_es = tmdb.TV_Seasons(show.movie_db_id, season_number=form.vars.season)
		info_es = season_es.info(language="es")
		for i in range(0, len(info_es["episodes"])):
			for z in info_es["episodes"][i].keys():
				if type(info_es["episodes"][i][z]) == str and len(info_es["episodes"][i][z]) == 0: info_es["episodes"][i][z] = info_en["episodes"][i][z]
		s = db.tv_season.insert(show=show, name=info_es["name"], season_number=info_es["season_number"], first_aired=info_es["air_date"], movie_db_id=info_es["id"], overview=info_es["overview"], image=info_es["poster_path"][1:])
		_get_image(info_es["poster_path"][1:])
		for i in info_es["episodes"]:
			db.tv_episode.insert(show=show, name=i["name"], episode_number=i["episode_number"], season_number=s, first_aired=i["air_date"], movie_db_id=i["id"], rating=i["vote_average"], rating_count=i["vote_count"], overview=i["overview"], image=i["still_path"][1:])
			_get_image(i["still_path"][1:])
		return redirect(URL("default", "show", vars=dict(show=show.id)))
	return dict(form=form, share=False)
示例#13
0
def getAiredEpisodesTMDB(myshow):
    """
    Getting Aired Episodes by date from TMDB
    """
    def getReleaseDate(e, es):
        """
        Getting Release date - if not present, find next episode that has release date, and subtract no. of episode * 7 days backwards #TODO: Improve?
        If can't find any date, return future date.
        """
        index = es.index(e) + 1
        while True:
            if index < es.__len__():
                if es[index].release_date is not None:
                    dtObj = DT.strptime(es[index].release_date, "%Y-%m-%d")
                    cor_dtObj = dtObj - datetime.timedelta(days=7 * index)
                    return DT.strftime(cor_dtObj, "%Y-%m-%d")
                else:
                    index += 1
            else:
                print "Cannot find release date in all the episodes"
                return u'2100-01-01'

    aired = OrderedDict()
    _seasons = tmdb.TV(myshow.tmdb).info()['seasons']
    _seasons = [
        cell for cell in _seasons
        if (cell['season_number'] != 0 and cell['season_number'] is not None)
    ]
    for i in range(0, _seasons.__len__()):
        if _seasons[i]['episode_count'] == 0: continue
        _episodes = tmdb.TV_Seasons(
            myshow.tmdb, _seasons[i]['season_number']).info()['episodes']
        s = mySeason(i + 1)
        for epi in _episodes:
            if epi['air_date'] is None:
                _rdate = getReleaseDate(epi, _episodes)
            else:
                _rdate = epi['air_date']
            try:
                rdate = DT.strptime(_rdate, "%Y-%m-%d")
            except:
                rdate = DT.strptime(u'2100-01-01', "%Y-%m-%d")
            if today >= rdate:
                s.addEpisode(epi['episode_number'])
            else:
                break
        if s.episodes != []:
            aired[s.season] = s
    return aired
示例#14
0
def seasonInfo(id, title):
    dic = {}
    s = 1
    while True:
        try:
            season = tmdb.TV_Seasons(id, s).info()
            eps = len(season['episodes'])
            #Only adds seasons with episodes
            if eps > 0:
                dic['Season {}'.format(s)] = eps
            s += 1
        except Exception as e:
            #print (e)
            break
    randomEp(id, dic, title)
示例#15
0
    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("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 = self.checkLanguage(language)
        self.original = original

        if self.mediatype == MediaType.Movie:
            query = tmdb.Movies(self.tmdbid)
            self.moviedata = query.info(language=language)
            self.credit = query.credits()

            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']
        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=language)
            self.seasondata = seasonquery.info(language=language)
            self.episodedata = episodequery.info(language=language)
            self.credit = episodequery.credits()

            self.showname = self.showdata['name']
            self.genre = self.showdata['genres']
            self.network = self.showdata['networks']
            self.title = self.episodedata['name']
            self.description = self.episodedata['overview']
            self.airdate = self.episodedata['air_date']
示例#16
0
    def gettags(self):

        season = self.season
        episode = self.episode
        tags = Tags()
        episodedata = None
        showdata = None

        try:
            fetcher = tmdb.TV_Seasons(self.fetcherid, season)
            showdata = tmdb.TV(self.fetcherid).info(language=self.language)
            episodedata = tmdb.TV_Episodes(self.fetcherid, season, episode).info(language=self.language)
        except Exception:
            raise FetcherException

        if showdata:
            # Show parsers
            tags.season_total = showdata['number_of_seasons']
            tags.show = showdata['name']

            for net in showdata['networks']:
                if net['origin_country'] == showdata['origin_country'][0]:
                    tags.network = net['name']
                    break

            tags.genre = showdata['genres'][0]['name']

            # Season parsers
            tags.poster_url = self._getposterpath(fetcher)

            tags.episode_number = episode
            tags.season_number = season
            tags.title = episodedata['name']
            tags.date = episodedata['air_date']
            tags.ldescription = episodedata['overview']

            for member in episodedata['crew']:
                if member['job'] == 'Director':
                    tags.directors.append(member['name'])
                if member['job'] == 'Writer':
                    tags.writers.append(member['name'])

            return tags
        else:
            raise FetcherException
示例#17
0
 def info_season_api(cls, code):
     try:
         if code.startswith(cls.module_char + cls.site_char):
             code = code[2:]
         tmp = code.split('_')
         if len(tmp) != 2:
             return
         tmdb_id = tmp[0]
         season_number = tmp[1]
         tmdb = tmdbsimple.TV_Seasons(tmdb_id, season_number)
         ret = {}
         ret['info'] = tmdb.info(language='ko')
         ret['credits'] = tmdb.credits(language='en')
         ret['image'] = tmdb.images()
         ret['video'] = tmdb.videos()
         ret['external_ids'] = tmdb.external_ids()
         return ret
     except Exception as exception:
         logger.error('Exception:%s', exception)
         logger.error(traceback.format_exc())
示例#18
0
    def info_season(cls, code):
        try:
            if code.startswith(cls.module_char + cls.site_char):
                code = code[2:]
            tmp = code.split('_')
            if len(tmp) != 2:
                return
            tmdb_id = tmp[0]
            season_number = int(tmp[1])
            """
            series_info = tmdbsimple.TV(tmdb_id).info(language='ko')
            series_title = series_info['name']
            series_season_count = 0
            for tmp in series_info['seasons']:
                if tmp['episode_count'] > 0 and tmp['season_number'] > 0:
                    series_season_count += 1
            try: series_year = int(series_info['first_air_date'].split('-')[0])
            except: series_year = 1900
            """
            ret = {}
            entity = EntitySeason(
                cls.site_name,
                parent_code=cls.module_char + cls.site_char + str(tmdb_id),
                season_code=cls.module_char + cls.site_char + code,
                season_no=season_number)
            tmdb = tmdbsimple.TV_Seasons(tmdb_id, season_number)

            cls.info_season_basic(tmdb, entity)
            #cls.info_content_ratings(tmdb, entity)
            #cls.info_credits(tmdb, entity)
            #cls.info_external_ids(tmdb, entity)
            entity = entity.as_dict()
            cls._process_image(tmdb, entity['art'])
            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
示例#19
0
def details(request, db_id):
    tv = serial_info(db_id)
    credits_list = serial_credits(db_id)
    try:
        serial_id = models.Serial.objects.get(owner=request.user,
                                              serial_id=db_id).id
    except ObjectDoesNotExist:
        serial_id = None
    seasons = tv['seasons']
    for season in seasons:
        tv_s = tmdb.TV_Seasons(db_id,
                               season['season_number']).info()['episodes']
        season['episodes'] = tv_s
    result = {
        'serial_id': serial_id,
        'seasons': seasons,
        'info': tv['info'],
        'year': tv['first_air_date'][:4],
        'cast': credits_list['cast'][:15],
        'created_by': tv['created_by'],
    }
    return render(request, "serial/details.html", result)
def insert_episodes_of_season(show_id, season_number):
    season_details = tmdb.TV_Seasons(
        show_id, season_number).info(append_to_response="credits")
    episodes = season_details['episodes']

    season_credits = season_details.get('credits', {})
    insert_actors_of_type('season', season_details['id'],
                          season_credits.get('cast', []))

    for i, episode in enumerate(episodes):
        stmt = """
            INSERT INTO episodes (id, title, episode_number, overview, season_id)
            VALUES (%(id)s, %(title)s, %(episode_number)s, %(overview)s, %(season_id)s)
            ON CONFLICT DO NOTHING;
        """
        execute_dml_statement(
            stmt, get_episode_entity(season_details["id"], episode))
        # episode_credits = tmdb.TV_Episodes(show_id, season_number, episode['episode_number']).credits()
        # insert_actors_of_type('episode', episode['id'], episode_credits.get('cast', []))
        progress_bar(i + 1,
                     len(episodes),
                     prefix='Inserting episodes:',
                     suffix=f"{season_details['name']} - {episode['name']}")
示例#21
0
def generate_random_episode():
    """Return a randomly selected episode from a list of TV shows."""
    context = {}

    if flask.request.method == "POST":
        # retrieve the list of show IDs from the data sent in the POST request
        show_ids = flask.request.get_json()
        # select a show at random
        random_id = random.choice(show_ids)

        # download information about the specific show from TMDB
        show_obj = tmdb.TV(id=random_id)
        random_season_num = random.randint(
            1,
            show_obj.info()["number_of_seasons"])
        season_obj = tmdb.TV_Seasons(random_id, random_season_num)

        # randomly select an episode from our season
        random_episode_obj = random.choice(season_obj.info()["episodes"])

        context["episode"] = random_episode_obj
        context["show"] = show_obj.info()

    return flask.jsonify(**context)
示例#22
0
 def test_tv_seasons_videos(self):
     series_id = TV_SEASON_ID
     season_number = TV_SEASON_NUMBER
     tv_seasons = tmdb.TV_Seasons(series_id, season_number)
     response = tv_seasons.videos()
     self.assertTrue(hasattr(tv_seasons, 'results'))
示例#23
0
    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("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.original = original

        if self.mediatype == MediaType.Movie:
            query = tmdb.Movies(self.tmdbid)
            self.moviedata = query.info(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:
                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']
        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()

            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:
                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']
            self.description = self.episodedata['overview']
            self.airdate = self.episodedata['air_date']
示例#24
0
def _get_tmdb_season(serie_id, season_number) -> dict:
    tmdb_season = tmdb.TV_Seasons(serie_id, season_number)
    return tmdb_season.info()
示例#25
0
 def test_tv_seasons_images(self):
     series_id = TV_SEASON_ID
     season_number = TV_SEASON_NUMBER
     tv_seasons = tmdb.TV_Seasons(series_id, season_number)
     response = tv_seasons.images()
     self.assertTrue(hasattr(tv_seasons, 'posters'))
示例#26
0
 def test_tv_seasons_credits(self):
     series_id = TV_SEASON_ID
     season_number = TV_SEASON_NUMBER
     tv_seasons = tmdb.TV_Seasons(series_id, season_number)
     response = tv_seasons.credits()
     self.assertTrue(hasattr(tv_seasons, 'crew'))
示例#27
0
 def __init__(self, show_id, season_number):
     self._data = tmdbsimple.TV_Seasons(show_id, season_number).info(
         language=get_language(), append_to_response="credits")
     self._credits = self._data.get("credits", {})
     # TODO: parse data - to_list_item is useless atm
     super(Season, self).__init__(show_id, season_number)
    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)
示例#29
0
    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)
示例#30
0
 def test_tv_seasons_account_states(self):
     series_id = TV_SEASON_ID
     season_number = TV_SEASON_NUMBER
     tv_seasons = tmdb.TV_Seasons(series_id, season_number)
     tv_seasons.account_states(session_id=SESSION_ID)
     self.assertTrue(hasattr(tv_seasons, 'results'))