# this is a small and single-purpose wrapper around the TMDB API import json import random import urllib class Tmdb: def __init__(self, apikey, language): self.baseurl = 'https://api.themoviedb.org/3/' self.apikey = apikey self.language = language # fetches data from TMDB API def fetch_from_tmdb(self, path, parameters): apikey = "?api_key=%s" % self.apikey url = self.baseurl + path + apikey + parameters json_url = urllib.urlopen(url) data = json.loads(json_url.read()) return data # finds TMDB-id for a known IMDB-id, return 0 if nothing is found def get_tmdbid(self, imdbid): print("getting tmdbid for imdbid %s" % imdbid) data = self.fetch_from_tmdb( path = 'find/%s' % imdbid, parameters = '&external_source=imdb_id' ) try: tmdbid = data['movie_results'][0]['id'] print("tmdbid is %d" % tmdbid) except: tmdbid = 0 print("tmdbid could not be found") return tmdbid # get recommendations for a movie id # choice is either "recommendations" or "similar" def get_recommendations(self, movieid, choice): print("getting %s for %d" % (choice, movieid)) data = self.fetch_from_tmdb( path = 'movie/%d/%s' % (movieid, choice), parameters = '&language=%s' % self.language ) results = [] for result in data['results']: results.append({ 'title': result['title'], 'movieid': result['id'] }) return results # get trailers, teasers, clips... for a movie id def get_movie_trailers(self, movieid): print("getting trailers for %d" % movieid) data = self.fetch_from_tmdb( path = 'movie/%d' % movieid, parameters = '&language=%s&append_to_response=videos' % self.language ) results = [] for result in data['videos']['results']: if result['site'] == 'YouTube': location = 'plugin://plugin.video.youtube/play/?video_id=%s' % result['key'] else: # skip other sites next results.append({ 'title': result['name'], 'type': result['type'], 'location': location }) return results # get a number of trailers of a certain kind for a list of recommended movies def get_trailers(self, recommendations, cliptype, count): results = [] # loop over ten out of the list of recommendations random.shuffle(recommendations) for recommendation in recommendations[:10]: all_trailers = self.get_movie_trailers(recommendation['movieid']) # filter to get only a certain kind of trailer trailers = [] for trailer in all_trailers: if trailer['type'] == cliptype: trailers.append(trailer) # get a random clip for this recommendation if len(trailers) > 0: random.shuffle(trailers) trailer = trailers[0] results.append(trailer) # quit if enough clips have been collected if len(results) == count: break return results