# 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 def fetch_from_tmdb(self, path, parameters, data): apikey = "?api_key=%s" % self.apikey url = (self.baseurl + path + apikey + parameters) % data json_url = urllib.urlopen(url) data = json.loads(json_url.read()) return data def get_tmdbid(self, imdbid): print("getting tmdbid for imdbid %s" % imdbid) data = self.fetch_from_tmdb('find/%s', '&external_source=imdb_id', imdbid) try: tmdbid = data['movie_results'][0]['id'] print("tmdbid is %d" % tmdbid) except: tmdbid = 0 print("tmdbid could not be found") return tmdbid def get_recommendations(self, movieid, choice): print("getting %s for %d" % (choice, movieid)) data = self.fetch_from_tmdb('movie/%d/%s', '&language=%s', (movieid, choice, self.language)) results = [] for result in data['results']: results.append({'title': result['title'], 'movieid': result['id']}) return results def get_movie_trailers(self, movieid): print("getting trailers for %d" % movieid) data = self.fetch_from_tmdb('movie/%d', '&language=%s&append_to_response=videos', (movieid, 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: next results.append({'title': result['name'], 'type': result['type'], 'location': location}) return results def get_trailers(self, recommendations, cliptype, count): results = [] for recommendation in recommendations[:10]: all_trailers = self.get_movie_trailers(recommendation['movieid']) trailers = [] for trailer in all_trailers: if trailer['type'] == cliptype: trailers.append(trailer) if len(trailers) > 0: random.shuffle(trailers) trailer = trailers[0] results.append(trailer) if len(results) == count: break return results