Exemplo n.º 1
0
    def test_configuration_info(self):
        change_keys = CHANGE_KEYS
        config = tmdb.Configuration()
        response = config.info()
        self.assertEqual(config.change_keys, change_keys)

        # Also test that bad API_KEY results in exception
        # Restore key for sequential tests
        api_key_save = tmdb.API_KEY
        tmdb.API_KEY = 0
        config = tmdb.Configuration()
        self.assertRaises(tmdb.APIKeyError, config.info)
        tmdb.API_KEY = api_key_save
Exemplo n.º 2
0
    def _retrieve_show_image_urls_from_tmdb(self, show, img_type):
        types = {'poster': 'poster_path',
                 'banner': None,
                 'fanart': 'backdrop_path',
                 'poster_thumb': 'poster_path',
                 'banner_thumb': None}

        # get TMDB configuration info
        tmdbsimple.API_KEY = sickbeard.TMDB_API_KEY
        config = tmdbsimple.Configuration()
        response = config.info()
        base_url = response['images']['base_url']
        sizes = response['images']['poster_sizes']

        def size_str_to_int(x):
            return float("inf") if x == 'original' else int(x[1:])

        max_size = max(sizes, key=size_str_to_int)

        try:
            search = tmdbsimple.Search()
            for show_name in allPossibleShowNames(show):
                for result in search.collection(query=show_name)['results'] + search.tv(query=show_name)['results']:
                    if types[img_type] and getattr(result, types[img_type]):
                        return "{0}{1}{2}".format(base_url, max_size, result[types[img_type]])

        except Exception:
            pass

        logger.log("Could not find any " + img_type + " images on TMDB for " + show.name, logger.INFO)
Exemplo n.º 3
0
    def get_context_data(self, **kwargs):
        context = {'page_type': 'myrating_page'}
        myratings = []
        try:
            data_entries = MovieRatings.objects.filter(user=self.request.user)

            for entry in data_entries:
                movie = tmdb.Movies(int(entry.movie_id))
                config = tmdb.Configuration().info()
                POSTER_SIZE = 1
                myratings.insert(0, (movie.info(), entry.rating,
                                     config['images']['base_url'] + config['images']['poster_sizes'][POSTER_SIZE]))

            if self.request.user.is_authenticated:
                if not myratings:
                    context['status'] = 'failure'
                else:
                    context['status'] = 'success'
                    context['results'] = myratings

            return context

        except (requests.exceptions.HTTPError, tmdb.APIKeyError)as e:
            context = {}
            print ("API ERROR")
            context["status"] = 'failure'
            return context
Exemplo n.º 4
0
def viewRatings(request):
    context = {'page_type': 'myrating_page'}
    myratings = []
    if request.method == 'POST':
        response = dict(
            errors=list(),
        )
        tmdb.API_KEY = settings.TMDB_API_KEY

        data_entries = MovieRatings.objects.filter(user=request.user)

        for entry in data_entries:
            movie = tmdb.Movies(int(entry.movie_id))
            config = tmdb.Configuration().info()
            POSTER_SIZE = 1
            myratings.insert(0, (movie.info(), entry.rating, config['images']['base_url'] + config['images']['poster_sizes'][POSTER_SIZE]))

        if request.user.is_authenticated:
            if not myratings:
                context['status'] = 'failure'

            else:
                context['status'] = 'success'
                context['results'] = myratings

        return render(request, 'myratings.html', context)

    else:
        raise Http404("No Movie Selected")
Exemplo n.º 5
0
    def _retrieve_show_images_from_tmdb(show, img_type):
        types = {
            'poster': 'poster_path',
            'banner': None,
            'fanart': 'backdrop_path',
            'poster_thumb': 'poster_path',
            'banner_thumb': None
        }

        def _request(self, method, path, params=None, payload=None):
            url = self._get_complete_url(path)
            params = self._get_params(params)

            requests.packages.urllib3.disable_warnings()
            response = requests.request(
                method,
                url,
                params=params,
                data=json.dumps(payload) if payload else payload,
                verify=False)

            #response.raise_for_status()
            response.encoding = 'utf-8'
            return response.json()

        from tmdbsimple.base import TMDB
        TMDB._request = _request

        # get TMDB configuration info
        tmdb.API_KEY = sickrage.srCore.srConfig.TMDB_API_KEY
        response = tmdb.Configuration().info()
        base_url = response['images']['base_url']
        sizes = response['images']['poster_sizes']

        def size_str_to_int(x):
            return float("inf") if x == 'original' else int(x[1:])

        max_size = max(sizes, key=size_str_to_int)

        sickrage.srCore.srLogger.debug("Searching for any " + img_type +
                                       " images on TMDB for " + show.name)

        try:
            search = tmdb.Search()
            from sickrage.core.helpers.show_names import allPossibleShowNames
            for show_name in set(allPossibleShowNames(show)):
                for result in search.collection(
                        query=show_name)['results'] + search.tv(
                            query=show_name)['results']:
                    if types[img_type] and getattr(result, types[img_type]):
                        return "{0}{1}{2}".format(base_url, max_size,
                                                  result[types[img_type]])
        except:
            pass

        sickrage.srCore.srLogger.debug("Could not find any " + img_type +
                                       " images on TMDB for " + show.name)
Exemplo n.º 6
0
class Movie():
    """
    This class provides a way to store movie related information.
    Utilizes the tmdbsimple library, a wrapper for The Movie Database (TMDb) API v3    
    """
    # obtain configuration info from TMDb to generate poster URLs
    conf = tmdb.Configuration()
    reponse = conf.info()

    # object for querying the database
    search = tmdb.Search()

    # class variables
    YOUTUBE_BASE_URL = 'https://www.youtube.com/watch?v='
    POSTER_SECURE_BASE_URL = conf.images['secure_base_url']
    POSTER_SIZE = 'w342'

    def __init__(self, title):
        self.movie = tmdb.Movies(self.get_movie_id(title))
        self.title = self.get_movie_title(title)
        self.poster_image_url = self.POSTER_SECURE_BASE_URL + \
            self.POSTER_SIZE + self.get_poster_path()
        self.trailer_youtube_url = self.YOUTUBE_BASE_URL + self.get_youtube_key()

    def get_movie_id(self, title):
        '''
        Returns the movie ID for a given title query
        If title is an ID itself, function simply returns the ID
        '''
        if type(title) is int:
            return title
        else:
            reponse = self.search.movie(query=title)
            return self.search.results[0]['id']

    def get_movie_title(self,title):
        '''
        Returns the movie title from the database for a given title query
        If title is an ID itself, function returns title from info()
        '''
        if type(title) is int:
            response = self.movie.info()
            return self.movie.title
        else:
            return self.search.results[0]['title']

    def get_youtube_key(self):
        '''Returns the YouTube key for the movie trailer'''
        response = self.movie.videos()
        return self.movie.results[0]['key']

    def get_poster_path(self):
        '''Returns the poster path for the movie poster'''
        response = self.movie.images()
        return self.movie.posters[0]['file_path']
 def populate_movies_info(self, movie_index):
     movie = tmdb.Movies(movie_index)
     movie.info()
     title = movie.title
     # use the first poster in the list of posters returned
     poster_image_file_path = movie.images()["posters"][0]["file_path"]
     base_url = tmdb.Configuration().info()["images"]["base_url"]
     poster_image_url = base_url + poster_image_size + poster_image_file_path  # NOQA
     # use the first link in the list of trailer links returned
     youtube_video_key = movie.videos()["results"][0]["key"]
     trailer_youtube_url = youtube_base_url + youtube_video_key
     return Movies(title, trailer_youtube_url, poster_image_url)
Exemplo n.º 8
0
def download_config():
    """ downloads and caches the tmdb config """

    tmdb_config = tmdbsimple.Configuration().info()
    tmdb_config['lastaccess'] = datetime.datetime.now().strftime('%Y-%m-%d')

    pathonly = os.path.dirname(CACHEFILE)
    if not os.path.exists(pathonly):
        os.makedirs(pathonly)

    with open(CACHEFILE, 'w') as cache:
        json.dump(tmdb_config, cache)
    return tmdb_config
Exemplo n.º 9
0
def sort(request):
    sort_option = 'popularity.desc'
    genre_option = ''
    page = '1'
    context = {'page_type' : 'sort_and_filter'}
    tmdb.API_KEY = settings.TMDB_API_KEY

    try:
        discover = tmdb.Discover()
        config = tmdb.Configuration().info()
        POSTER_SIZE = 2

        if request.method == 'POST':
            context['status'] = 'success'
            sort_option = request.POST['sort_by']
            genre_option = request.POST['genre']

            if request.POST.__contains__('prev_page'):
                page = request.POST.get('prev_page', '2')
                pageNumber = int(page)
                page = str(pageNumber - 1)
            elif request.POST.__contains__('next_page'):
                page = request.POST.get('next_page', '0')
                pageNumber = int(page)
                page = str(pageNumber + 1)
            else:
                page = '1'

        movie_query = discover.movie(page=page, sort_by=sort_option, with_genres=genre_option, with_release_type='2|3|4|5|6')
        # For testing purposes, you can use commented query below to get result which will only return 2 pages
        # movie_query = discover.movie(page=page, sort_by=sort_option, with_genres=genre_option, vote_count_gte='6234')

        context['results'] = movie_query['results']

        context['last_page'] = 'false'
        if int(page) == movie_query['total_pages']:
            context['last_page'] = 'true'

        if len(context['results']) == 0:
            context['status'] = 'noresult'

        context['image_path'] = config['images']['base_url'] + config['images']['poster_sizes'][POSTER_SIZE]
        context['sort_selected'] = sort_option
        context['genre_selected'] = genre_option
        context['page_num'] = page
        return render(request, 'home.html', context)

    except (requests.exceptions.HTTPError, tmdb.APIKeyError)as e:
        print("THE API IS WRONG")
        context["status"] = 'failure'
        return render(request, 'home.html', context)
Exemplo n.º 10
0
    def post(request, *args, **kwargs):
        context_instance = RequestContext(request)
        action = request.POST.get('action', '')
        if action == "rate_movie":
            # get important info
            movieID = int(request.POST['movie_id'])
            rating_given = int(request.POST['rating'])
            current_user = request.user
            updated = False
            context = {}

            if current_user.is_authenticated:
                try:
                    movie = MovieRatings.objects.get(user=current_user, movie_id=movieID)

                    if rating_given == 0:
                        movie.delete()
                    else:
                        # update rating
                        movie.rating = int(rating_given)
                        movie.save()
                    updated = True
                except MovieRatings.DoesNotExist:
                    MovieRatings.objects.create(user=current_user, movie_id=movieID, rating=rating_given)
                    updated = True

                myratings=[]

                try:
                    data_entries = MovieRatings.objects.filter(user=request.user)

                    for entry in data_entries:
                        movie = tmdb.Movies(int(entry.movie_id))
                        config = tmdb.Configuration().info()
                        POSTER_SIZE = 1
                        myratings.insert(0, (movie.info(), entry.rating,
                                             config['images']['base_url'] + config['images']['poster_sizes'][
                                                 POSTER_SIZE]))

                    if not myratings:
                        context['status'] = 'failure'
                    else:
                        context['status'] = 'success'
                        context['results'] = myratings

                except (requests.exceptions.HTTPError, tmdb.APIKeyError)as e:
                    context["status"] = 'failure'

            return render(request, 'myratings.html', context)

        return render(request, 'myratings.html', {})
Exemplo n.º 11
0
    def get_context_data(self, **kwargs):
        try:
            movies = tmdb.Movies()
            config = tmdb.Configuration().info()
            POSTER_SIZE = 2

            context = {}
            context['status'] = 'success'
            context['results'] = movies.top_rated(page = 1)['results'][:10]
            context['image_path'] = config['images']['base_url'] + config['images']['poster_sizes'][POSTER_SIZE]
            return context
        except (requests.exceptions.HTTPError, tmdb.APIKeyError )as e:
            context = {}
            print ("THE API IS WRONG")
            context["status"] = 'failure'
            return context
Exemplo n.º 12
0
def _load_base_urls(url_settings):
    urls = {}
    urls['original'] = url_settings.getSettingString('originalUrl')
    urls['preview'] = url_settings.getSettingString('previewUrl')
    last_updated = url_settings.getSettingString('lastUpdated')
    if not urls['original'] or not urls['preview'] or not last_updated or \
            float(last_updated) < _get_date_numeric(datetime.now() - timedelta(days=30)):
        conf = tmdbsimple.Configuration().info()
        if conf:
            urls['original'] = conf['images']['base_url'] + 'original'
            urls['preview'] = conf['images']['base_url'] + 'w780'
            url_settings.setSetting('originalUrl', urls['original'])
            url_settings.setSetting('previewUrl', urls['preview'])
            url_settings.setSetting('lastUpdated',
                                    str(_get_date_numeric(datetime.now())))
    return urls
Exemplo n.º 13
0
    def __init__(self, showid, id_type, season=None, episode=None, language='en'):
        # Showinfo is a dict containing the name of the show, episode, season
        super(FetcherTmdb, self).__init__(showid, id_type, season=season, episode=episode, language=language)
        tmdb.API_KEY = FetcherTmdb.api_key
        self.tmdbconfig = tmdb.Configuration().info()
        self.definition = 'original'

        if self.id_type == 'tmdb_id':
            self._fetcherid = self.showid

        if self.id_type in ['imdb_id', 'freebase_mid', 'freebase_id', 'tvdb_id', 'tvrage_id']:
            find = tmdb.Find(self.showid)

            if self.__class__.ftype == 'tv':
                self._fetcherid = find.info(external_source=self.id_type)['tv_results'][0]['id']
            elif self.__class__.ftype == 'movie':
                self._fetcherid = find.info(external_source=self.id_type)['movie_results'][0]['id']
    def __init__(self, movie_title, movie_release_date):
        """ Initialises the Movie_Details Class.

        uses the tmdbsimple library to connect to the moviedb api
        uses a key to securely connect
        sets up the connection and sets some object level
        variables to be used in the methods
        """
        self.movie_title = movie_title
        self.movie_release_date = movie_release_date
        # setup the apikey required to connect to the moviedb
        moviedb.API_KEY = '5c5354c3aa31e31a67ec9a4897882aee'
        self.config = moviedb.Configuration()
        # search for the movie in the moviedb
        self.moviedb_search = moviedb.Search()
        response = self.moviedb_search.movie(
            query=movie_title, year=movie_release_date)
Exemplo n.º 15
0
    def _retrieve_show_images_from_tmdb(show, img_type):
        types = {
            u'poster': u'poster_path',
            u'banner': None,
            u'fanart': u'backdrop_path',
            u'poster_thumb': u'poster_path',
            u'banner_thumb': None
        }

        # get TMDB configuration info
        tmdb.API_KEY = app.TMDB_API_KEY
        config = tmdb.Configuration()
        try:
            response = config.info()
        except RequestException as error:
            log.warning(u'Indexer TMDB is unavailable at this time: {reason}',
                        {u'reason': error})
            return False

        base_url = response[u'images'][u'base_url']
        sizes = response[u'images'][u'poster_sizes']

        def size_str_to_int(x):
            return float(u'inf') if x == u'original' else int(x[1:])

        max_size = max(sizes, key=size_str_to_int)

        try:
            search = tmdb.Search()
            for show_name in show.get_all_possible_names():
                for result in search.collection(
                        query=show_name)[u'results'] + search.tv(
                            query=show_name)[u'results']:
                    if types[img_type] and result.get(types[img_type]):
                        return u'{0}{1}{2}'.format(base_url, max_size,
                                                   result[types[img_type]])

        except Exception:
            pass

        log.info(u'Could not find any {type} images on TMDB for {series}', {
            u'type': img_type,
            u'series': show.name
        })
Exemplo n.º 16
0
def find_movie_ids(input):
    global tmdb_img_config
    if tmdb_img_config is None:
        tmdb_img_config = tmdbsimple.Configuration().info()["images"]
    base_url = tmdb_img_config["secure_base_url"]
    poster_size = "w92" if "w92" in tmdb_img_config["poster_sizes"] else tmdb_img_config["poster_sizes"][0]

    search = tmdbsimple.Search()
    results = search.movie(query=input)["results"]
    infos = []
    for s in results:
        title = s["title"]
        if "release_date" in s.keys() and s["release_date"] != "":
            title = "%s (%s)" % (title, arrow.get(s["release_date"]).year)
        result = {"label": title, "value": s["id"], "title": s["title"]}
        if "poster_path" in s and s["poster_path"]:
            result["poster"] = base_url + poster_size + s["poster_path"]
            infos.append(result)
    return infos
Exemplo n.º 17
0
    def _retrieve_show_image_urls_from_tmdb(show, img_type, multiple=False):
        types = {
            'poster': 'posters',
            'banner': None,
            'fanart': 'backdrops',
            'poster_thumb': 'posters',
            'banner_thumb': None
        }

        if not types[img_type]:
            return [] if multiple else ""

        # get TMDB configuration info
        tmdbsimple.API_KEY = settings.TMDB_API_KEY
        config = tmdbsimple.Configuration()
        response = config.info()
        base_url = response['images']['base_url']
        sizes = response['images']['poster_sizes']

        def size_str_to_int(x):
            return float("inf") if x == 'original' else int(x[1:])

        max_size = max(sizes, key=size_str_to_int)

        try:
            results = []
            find = tmdbsimple.Find(show.indexerid)
            found = find.info(external_source='tvdb_id')
            if found['tv_results']:
                tmdb_show = tmdbsimple.TV(found['tv_results'][0]['id'])
                images = tmdb_show.images()
                if types[img_type] in images:
                    for result in images[types[img_type]]:
                        results.append("{0}{1}{2}".format(
                            base_url, max_size, result['file_path']))
                        if not multiple:
                            return results[0]
                    return results
        except Exception as error:
            logger.debug(error)

        logger.info("Could not find any " + img_type + " images on TMDB for " +
                    show.name)
Exemplo n.º 18
0
 def test_configuration_jobs(self):
     config = tmdb.Configuration()
     config.jobs()
     self.assertTrue(hasattr(config, 'jobs'))
Exemplo n.º 19
0
import tmdbsimple as tmdb
import urllib
import os
import string

valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)

if __name__ == "__main__":

    tmdb.API_KEY = 'x'
    search = tmdb.Movies()
    base = tmdb.Configuration().info().get("images").get("secure_base_url")
    genres = tmdb.Genres().list().get("genres")
    genre_map = {}

    total_pages = 100  #Maxiumum 284 for top_rated, 983 for popular

    #Directory of downloads to be saved. It should be same in reader
    path = "Data"
    if path != "":
        if not os.path.exists(path):
            os.makedirs(path)
            os.chdir(path)

    for genre in genres:
        genre_map[genre.get('id')] = genre.get('name')

    for page in range(1, total_pages):
        print("Page: " + page)
        list = search.top_rated(page=page).get(
            'results')  #search.popular() can also be used.
Exemplo n.º 20
0
 def config(self):
     if not self.__config:
         self.__config = tmdb.Configuration().info()
     return self.__config
Exemplo n.º 21
0
def base_url():
    return tmdbsimple.Configuration().info()['images']['secure_base_url']
Exemplo n.º 22
0
 def test_configuration_languages(self):
     config = tmdb.Configuration()
     response = config.languages()
     # First language is No Language
     self.assertEqual(response[0][ISO_639_1], NO_LANGUAGE)
Exemplo n.º 23
0
 def _get_config():
     config = tmdb.Configuration()
     response = config.info()
     return config
Exemplo n.º 24
0
def configuration():
    conf = tmdb.Configuration()
    return _query_retry(conf.info)
Exemplo n.º 25
0
# This is a sample Python script.
import tmdbsimple as tmdb

tmdb.API_KEY = '73972aa479b5ec8c31a15ff73eba8ef3'
# from flask import Flask

# app = Flask(__name__)

discover = tmdb.Discover()
genre = tmdb.Genres()
movies = discover.movie(sort_by='vote_average', vote_count_gte=1000)['results']
config = tmdb.Configuration()
print(discover.movie()['results'])
Exemplo n.º 26
0
def get_tmdb_metadata(tmdb, title):
    # extract basic metadata
    config = tmdb.Configuration().info()['images']
    search = tmdb.Search()
    res = search.movie(query=title)
    if len(res['results'])>0:
        mov_id = res['results'][0]['id'] #HACK: use the first one
        movie = tmdb.Movies(mov_id)

        # General movie info
        info = movie.info()
        keywords = movie.keywords()['keywords']

        # Characters & Director info
        credit = movie.credits()
        cast = []
        for person in credit['cast']:
            detail = tmdb.People(person['id']).info()
            actor = {
                'name': person['name'],
                'credit_order': person['order'],
                'character': person['character'],
                'birthdate': detail['birthday'],
                'gender': detail['gender'],
                'mdb_id': person['id'],
                'imdb_id': detail['imdb_id']
            }

            if person['profile_path'] is not None:
                actor['img_url'] = config['base_url'] + \
                    config['profile_sizes'][0] + person['profile_path']
            cast.append(actor)
        director = None
        for person in credit['crew']:
            if person['job']=='Director':
                director = {
                    'name': person['name']
                }
                if person['profile_path'] is not None:
                    director['img_url'] = config['base_url'] + \
                        config['profile_sizes'][0] + person['profile_path']

        record = {
            'query_title': title,
            'original_title': info['original_title'],
            'release_date': info['release_date'],
            'mdb_id': info['id'],
            'imdb_id': info['imdb_id'],
            'backdrop_path': config['base_url'] + config['backdrop_sizes'][0] + info['backdrop_path'],
            'vote_average': info['vote_average'],
            'vote_count': info['vote_count'],
            'tagline': info['tagline'],
            'runtime': info['runtime'],
            'genres': map(lambda x: x['name'], info['genres']),
            'keywords': map(lambda x: x['name'], keywords),
            'cast':cast,
            'director':director

        }
        return record
    return None
Exemplo n.º 27
0
 def test_configuration_timezones(self):
     config = tmdb.Configuration()
     response = config.timezones()
     # First country is Andorra
     self.assertEqual(response[0][ISO_3166_1], ANDORRA)
Exemplo n.º 28
0
 def test_configuration_primary_translations(self):
     config = tmdb.Configuration()
     response = config.primary_translations()
     # First primary translation is Arabic
     self.assertEqual(response[0], ARABIC)
Exemplo n.º 29
0
 def test_configuration_languages(self):
     config = tmdb.Configuration()
     response = config.languages()
     # Languages are two lowercase letters
     self.assertTrue(re.match('^[a-z]{2}$', response[0][ISO_639_1]))
Exemplo n.º 30
0
 def test_configuration_countries(self):
     config = tmdb.Configuration()
     response = config.countries()
     # Countries are two capital letters
     self.assertTrue(re.match('^[A-Z]{2}$', response[0][ISO_3166_1]))