def getMovies(self): tmdb = TMDb() tmdb.api_key = '1dc5bcb73c0781470cb348d5e02a05a5' tmdb.language = 'en' tmdb.debug = False movie = Movie() self.movie = movie self.popular = movie.popular() self.now = movie.now_playing() self.top = movie.top_rated() discover = Discover() self.movie_discovered = discover.discover_movies( {'sort_by': 'vote_average.desc'}) lists = [self.top, self.now, self.popular, self.movie_discovered] self.all_movies = [] for li in lists: for m in li: exist = False for r in self.all_movies: if r.id == m.id: exist = True if (not exist): self.all_movies.append(m)
def top_rated(request): if request.method == 'GET': movie = Movie() latest = movie.top_rated() results = transformer.transform(latest) return Response.ok(results) else: return Response.badRequest(message="invalid request")
class TMDBWrapper: def __init__(self, language: str): self.tmdb = TMDb() self.tmdb.api_key = config.MOVIE_DB_API_KEY # '26e13c6a960c2e640f5e1867b9c52a46' self.tmdb.language = language or settings.LANGUAGE_CODE self.movie = Movie() self.discover = Discover() self.genre = Genre() def set_language(self, language: str): self.tmdb.language = language @modify_result(return_movies) def popular(self, page: int = 1): return self.movie.popular(page) @modify_result(return_movies) def top_rated(self, page: int = 1): return self.movie.top_rated(page) @modify_result(return_movies) def upcoming(self, page: int = 1, region: str = 'UA'): return self.movie._get_obj( self.movie._call( self.movie._urls["upcoming"], urlencode({ # "region": region, "page": str(page) }))) @modify_result(return_movies) def now_playing(self, page: int = 1): return self.movie.now_playing(page) @modify_result(return_movies) def search_movies(self, query: str, page: int = 1, **kwargs): return self.movie.search(term=query, page=page) @modify_result(return_movies) def discover_movies(self, params: Dict, **kwargs): return self.discover.discover_movies(params=params) def get_movies_genres(self): return self.genre.movie_list()
class TMDbTests(unittest.TestCase): def setUp(self): self.tmdb = TMDb() self.tmdb.api_key = os.environ['TMDB_API_KEY'] self.tmdb.language = 'en' self.tmdb.debug = True self.tmdb.wait_on_rate_limit = True self.movie = Movie() self.discover = Discover() self.tv = TV() self.person = Person() self.collection = Collection() self.company = Company() self.season = Season() def test_get_movie(self): movie = self.movie.details(111) self.assertIsNotNone(movie) self.assertEqual(movie.title, 'Scarface') self.assertEqual(movie.id, 111) self.assertTrue(hasattr(movie, 'title')) self.assertTrue(hasattr(movie, 'overview')) self.assertTrue(hasattr(movie, 'id')) def test_get_movie_reviews(self): search = self.movie.search("Mad Max") self.assertTrue(len(search) > 0) first = search[0] reviews = self.movie.reviews(first.id) self.assertTrue(len(reviews) > 0) for review in reviews: self.assertTrue(hasattr(review, 'id')) self.assertTrue(hasattr(review, 'content')) def test_get_movie_lists(self): lists = self.movie.lists(111) self.assertTrue(len(lists) > 0) self.assertTrue(hasattr(lists[0], 'description')) self.assertTrue(hasattr(lists[0], 'name')) def test_get_movie_videos(self): videos = self.movie.videos(111) self.assertTrue(len(videos) > 0) self.assertTrue(hasattr(videos[0], 'id')) def test_get_movie_recommendations(self): recs = self.movie.recommendations(111) self.assertTrue(len(recs) > 0) self.assertTrue(hasattr(recs[0], 'id')) def test_discover_movies(self): discover = self.discover.discover_movies({ 'primary_release_year': '2015', 'with_genres': '28', 'page': '1', 'vote_average.gte': '8' }) self.assertTrue(len(discover) > 0) self.assertTrue(hasattr(discover[0], 'id')) movie = discover[0] has_genre = False for genre_id in movie.genre_ids: if genre_id == 28: has_genre = True self.assertTrue(has_genre) def test_discover_tv_shows(self): discover = self.discover.discover_tv_shows({ 'with_genres': '16', 'vote_average.gte': '8', 'page': '1' }) self.assertTrue(len(discover) > 0) self.assertTrue(hasattr(discover[0], 'id')) movie = discover[0] has_genre = False for genre_id in movie.genre_ids: if genre_id == 16: has_genre = True self.assertTrue(has_genre) def test_get_latest_movie(self): videos = self.movie.latest() self.assertIsNotNone(videos) self.assertTrue(hasattr(videos, 'id')) def test_now_playing(self): now_playing = self.movie.now_playing() self.assertTrue(len(now_playing) > 0) self.assertTrue(hasattr(now_playing[0], 'id')) def test_top_rated(self): top_rated = self.movie.top_rated() self.assertTrue(len(top_rated) > 0) self.assertTrue(hasattr(top_rated[0], 'id')) def test_upcoming(self): upcoming = self.movie.upcoming() self.assertTrue(len(upcoming) > 0) self.assertTrue(hasattr(upcoming[0], 'id')) def test_popular(self): popular = self.movie.popular() self.assertTrue(len(popular) > 0) self.assertTrue(hasattr(popular[0], 'id')) def test_search(self): search = self.movie.search('Mad Max') self.assertTrue(len(search) > 0) self.assertTrue(hasattr(search[0], 'id')) def test_similar(self): similar = self.movie.similar(111) self.assertTrue(len(similar) > 0) self.assertTrue(hasattr(similar[0], 'id')) def test_get_tv_show(self): show = self.tv.details(12) self.assertIsNotNone(show) self.assertTrue(hasattr(show, 'id')) def test_get_latest_tv_show(self): latest_tv = self.tv.latest() self.assertIsNotNone(latest_tv) self.assertTrue(hasattr(latest_tv, 'id')) def test_search_tv(self): search_tv = self.tv.search('Sunny') self.assertTrue(len(search_tv) > 0) self.assertTrue(hasattr(search_tv[0], 'id')) def test_popular_shows(self): popular = self.tv.popular() self.assertTrue(len(popular) > 0) self.assertTrue(hasattr(popular[0], 'id')) def test_top_rated_shows(self): top_rated = self.tv.top_rated() self.assertTrue(len(top_rated) > 0) self.assertTrue(hasattr(top_rated[0], 'id')) def test_get_person(self): person = self.person.details(234) self.assertIsNotNone(person) self.assertTrue(hasattr(person, 'id')) def test_search_person(self): search_person = self.person.search('Bryan') self.assertTrue(len(search_person) > 0) self.assertTrue(hasattr(search_person[0], 'id')) def test_collection_details(self): c = Collection() details = c.details(10) self.assertEqual(details.name, 'Star Wars Collection') self.assertEqual(details.id, 10) self.assertTrue(hasattr(details, 'overview')) self.assertTrue(hasattr(details, 'poster_path')) def test_collection_images(self): c = Collection() images = c.images(10) self.assertTrue(hasattr(images, 'backdrops')) self.assertTrue(hasattr(images, 'posters')) def test_popular_people(self): popular = self.person.popular() self.assertTrue(len(popular) > 0) first = popular[0] self.assertTrue(hasattr(first, 'name')) self.assertTrue(hasattr(first, 'known_for')) def test_latest_person(self): latest_person = self.person.latest() self.assertIsNotNone(latest_person) self.assertTrue(hasattr(latest_person, 'name')) self.assertTrue(hasattr(latest_person, 'id')) def test_person_images(self): images = self.person.images(11) self.assertIsNotNone(images) self.assertTrue(hasattr(images, 'profiles')) self.assertTrue(hasattr(images, 'id')) def test_company_details(self): c = self.company.details(1) self.assertTrue(hasattr(c, 'name')) self.assertEqual(c.name, 'Lucasfilm') def test_company_movies(self): company = self.company.movies(1) self.assertTrue(len(company) > 0) first = company[0] self.assertTrue(hasattr(first, 'title')) self.assertTrue(hasattr(first, 'overview')) def test_config(self): config = Configuration() info = config.info() self.assertIsNotNone(info) self.assertTrue(hasattr(info, 'images')) def test_genres(self): genres = Genre() movie_genres = genres.movie_list() self.assertIsNotNone(movie_genres) tv_genres = genres.tv_list() self.assertIsNotNone(tv_genres) def test_season(self): s = self.season.details(1418, 1) self.assertIsNotNone(s) self.assertEqual(s.name, 'Season 1') self.assertEqual(s.id, 3738) self.assertTrue(hasattr(s, 'episodes')) self.assertTrue(hasattr(s, 'overview')) self.assertTrue(hasattr(s, 'id')) def test_get_season_changes(self): s = self.season.changes(1418, 1) self.assertIsNotNone(s) def test_get_season_external_ids(self): s = self.season.external_ids(1418, 1) self.assertIsNotNone(s) self.assertIsNotNone(s['tvdb_id']) def test_get_season_videos(self): s = self.season.videos(1418, 1) def test_get_season_images(self): s = self.season.images(1418, 1) for l in s: self.assertIsNotNone(l.width) self.assertIsNotNone(l.height) def test_get_season_credits(self): s = self.season.credits(1418, 1) for c in s: self.assertIsNotNone(c.name) self.assertIsNotNone(c.character) def test_get_movie_by_external_id(self): ex = self.movie.external(external_id="tt8155288", external_source="imdb_id") res = ex['movie_results'][0] self.assertTrue(res['title'] == "Happy Death Day 2U")
class TMDbTests(unittest.TestCase): def setUp(self): self.tmdb = TMDb() self.tmdb.api_key = os.environ["TMDB_API_KEY"] self.tmdb.language = "en" self.tmdb.debug = True self.tmdb.wait_on_rate_limit = True self.movie = Movie() self.discover = Discover() self.tv = TV() self.person = Person() self.collection = Collection() self.company = Company() self.season = Season() self.list = List() def test_get_tv_keywords(self): keywords = self.tv.keywords(1396) self.assertGreater(len(keywords), 0) def test_get_tv_reviews(self): reviews = self.tv.reviews(1396) self.assertGreater(len(reviews), 0) def test_get_movie_repr(self): search = self.movie.search("Mad Max") for results in search: print(results) def test_get_tv_show_repr(self): search_tv = self.tv.search("Breaking Bad") for results in search_tv: print(results) def test_get_movie(self): movie = self.movie.details(111) self.assertIsNotNone(movie) self.assertEqual(movie.title, "Scarface") self.assertEqual(movie.id, 111) self.assertTrue(hasattr(movie, "title")) self.assertTrue(hasattr(movie, "overview")) self.assertTrue(hasattr(movie, "id")) def test_get_movie_reviews(self): search = self.movie.search("Mad Max") self.assertTrue(len(search) > 0) first = search[0] reviews = self.movie.reviews(first.id) self.assertTrue(len(reviews) > 0) for review in reviews: self.assertTrue(hasattr(review, "id")) self.assertTrue(hasattr(review, "content")) def test_get_movie_lists(self): lists = self.movie.lists(111) self.assertTrue(len(lists) > 0) self.assertTrue(hasattr(lists[0], "description")) self.assertTrue(hasattr(lists[0], "name")) def test_get_movie_credits(self): credits = self.movie.credits(111) print(credits) self.assertIsNotNone(credits) def test_get_movie_images(self): images = self.movie.images(111) print(images) self.assertIsNotNone(images) def test_get_movie_videos(self): videos = self.movie.videos(111) self.assertTrue(len(videos) > 0) self.assertTrue(hasattr(videos[0], "id")) def test_get_movie_recommendations(self): recs = self.movie.recommendations(111) self.assertTrue(len(recs) > 0) self.assertTrue(hasattr(recs[0], "id")) def test_discover_movies(self): discover = self.discover.discover_movies({ "primary_release_year": "2015", "with_genres": "28", "page": "1", "vote_average.gte": "8", }) self.assertTrue(len(discover) > 0) self.assertTrue(hasattr(discover[0], "id")) movie = discover[0] has_genre = False for genre_id in movie.genre_ids: if genre_id == 28: has_genre = True self.assertTrue(has_genre) def test_discover_tv_shows(self): discover = self.discover.discover_tv_shows({ "with_genres": "16", "vote_average.gte": "8", "page": "1" }) self.assertTrue(len(discover) > 0) self.assertTrue(hasattr(discover[0], "id")) movie = discover[0] has_genre = False for genre_id in movie.genre_ids: if genre_id == 16: has_genre = True self.assertTrue(has_genre) def test_get_latest_movie(self): videos = self.movie.latest() self.assertIsNotNone(videos) self.assertTrue(hasattr(videos, "id")) def test_now_playing(self): now_playing = self.movie.now_playing() self.assertTrue(len(now_playing) > 0) self.assertTrue(hasattr(now_playing[0], "id")) def test_top_rated(self): top_rated = self.movie.top_rated() self.assertTrue(len(top_rated) > 0) self.assertTrue(hasattr(top_rated[0], "id")) def test_upcoming(self): upcoming = self.movie.upcoming() self.assertTrue(len(upcoming) > 0) self.assertTrue(hasattr(upcoming[0], "id")) def test_popular(self): popular = self.movie.popular() self.assertTrue(len(popular) > 0) self.assertTrue(hasattr(popular[0], "id")) def test_search(self): search = self.movie.search("Mad Max") self.assertTrue(len(search) > 0) self.assertTrue(hasattr(search[0], "id")) def test_similar(self): similar = self.movie.similar(111) self.assertTrue(len(similar) > 0) self.assertTrue(hasattr(similar[0], "id")) def test_get_tv_show(self): show = self.tv.details(12) self.assertIsNotNone(show) self.assertTrue(hasattr(show, "id")) def test_on_the_air(self): show = self.tv.on_the_air() self.assertTrue(len(show) > 0) def test_airing_today(self): show = self.tv.on_the_air() self.assertTrue(len(show) > 0) def test_tv_videos(self): show = self.tv.videos(1396) self.assertTrue(len(show) > 0) def test_tv_recommendations(self): show = self.tv.recommendations(1396) self.assertTrue(len(show) > 0) def test_external_ids(self): show = self.tv.external_ids(1776) self.assertEqual(show["imdb_id"], "tt0488262") def test_get_latest_tv_show(self): latest_tv = self.tv.latest() self.assertIsNotNone(latest_tv) self.assertTrue(hasattr(latest_tv, "id")) def test_search_tv(self): search_tv = self.tv.search("Sunny") self.assertTrue(len(search_tv) > 0) self.assertTrue(hasattr(search_tv[0], "id")) def test_popular_shows(self): popular = self.tv.popular() self.assertTrue(len(popular) > 0) self.assertTrue(hasattr(popular[0], "id")) def test_top_rated_shows(self): top_rated = self.tv.top_rated() self.assertTrue(len(top_rated) > 0) self.assertTrue(hasattr(top_rated[0], "id")) def test_get_person(self): person = self.person.details(234) self.assertIsNotNone(person) self.assertTrue(hasattr(person, "id")) def test_search_person(self): search_person = self.person.search("Bryan") self.assertTrue(len(search_person) > 0) self.assertTrue(hasattr(search_person[0], "id")) def test_collection_details(self): c = Collection() details = c.details(10) self.assertEqual(details.name, "Star Wars Collection") self.assertEqual(details.id, 10) self.assertTrue(hasattr(details, "overview")) self.assertTrue(hasattr(details, "poster_path")) def test_collection_images(self): c = Collection() images = c.images(10) self.assertTrue(hasattr(images, "backdrops")) self.assertTrue(hasattr(images, "posters")) def test_popular_people(self): popular = self.person.popular() self.assertTrue(len(popular) > 0) first = popular[0] self.assertTrue(hasattr(first, "name")) self.assertTrue(hasattr(first, "known_for")) def test_latest_person(self): latest_person = self.person.latest() self.assertIsNotNone(latest_person) self.assertTrue(hasattr(latest_person, "name")) self.assertTrue(hasattr(latest_person, "id")) def test_person_images(self): images = self.person.images(11) self.assertIsNotNone(images) self.assertTrue(hasattr(images, "profiles")) self.assertTrue(hasattr(images, "id")) def test_company_details(self): c = self.company.details(1) self.assertTrue(hasattr(c, "name")) self.assertEqual(c.name, "Lucasfilm Ltd.") def test_company_movies(self): company = self.company.movies(1) self.assertTrue(len(company) > 0) first = company[0] self.assertTrue(hasattr(first, "title")) self.assertTrue(hasattr(first, "overview")) def test_config(self): config = Configuration() info = config.info() self.assertIsNotNone(info) self.assertTrue(hasattr(info, "images")) def test_genres(self): genres = Genre() movie_genres = genres.movie_list() self.assertIsNotNone(movie_genres) tv_genres = genres.tv_list() self.assertIsNotNone(tv_genres) def test_season(self): s = self.season.details(1418, 1) self.assertIsNotNone(s) self.assertEqual(s.name, "Season 1") self.assertEqual(s.id, 3738) self.assertTrue(hasattr(s, "episodes")) self.assertTrue(hasattr(s, "overview")) self.assertTrue(hasattr(s, "id")) def test_get_season_changes(self): s = self.season.changes(1418) self.assertIsNotNone(s) def test_get_season_external_ids(self): s = self.season.external_ids(1418, 1) self.assertIsNotNone(s) self.assertIsNotNone(s["tvdb_id"]) def test_get_season_videos(self): s = self.season.videos(1418, 1) def test_get_season_images(self): s = self.season.images(1418, 1) for l in s: self.assertIsNotNone(l.width) self.assertIsNotNone(l.height) def test_get_season_credits(self): s = self.season.credits(1418, 1) for c in s: self.assertIsNotNone(c.name) self.assertIsNotNone(c.character) def test_get_movie_by_external_id(self): ex = self.movie.external(external_id="tt8155288", external_source="imdb_id") res = ex["movie_results"][0] self.assertTrue(res["title"] == "Happy Death Day 2U") def test_get_list(self): list = self.list.details(list_id="112870") self.assertTrue(len(list) > 10) self.assertTrue(hasattr(list[0], "id")) self.assertTrue(hasattr(list[0], "title")) def test_get_certifications(self): certifications = Certification() movie_certifications = certifications.movie_list() self.assertIsNotNone(movie_certifications) tv_certifications = certifications.tv_list() self.assertIsNotNone(tv_certifications)
def tmdb_get_movies(config_path, plex, plex_map, data, method): t_movs = [] t_movie = Movie() t_movie.api_key = config_tools.TMDB( config_path).apikey # Set TMDb api key for Movie if t_movie.api_key == "None": raise KeyError("Invalid TMDb API Key") count = 0 if method == "tmdb_discover": attrs = data.copy() discover = Discover() discover.api_key = t_movie.api_key discover.discover_movies(attrs) total_pages = int(os.environ["total_pages"]) total_results = int(os.environ["total_results"]) limit = int(attrs.pop('limit')) amount = total_results if limit == 0 or total_results < limit else limit print("| Processing {}: {} movies".format(method, amount)) for attr, value in attrs.items(): print("| {}: {}".format(attr, value)) for x in range(total_pages): attrs["page"] = x + 1 tmdb_movies = discover.discover_movies(attrs) for tmovie in tmdb_movies: count += 1 t_movs.append(tmovie.id) if count == amount: break if count == amount: break elif method in [ "tmdb_popular", "tmdb_top_rated", "tmdb_now_playing", "tmdb_trending_daily", "tmdb_trending_weekly" ]: trending = Trending() trending.api_key = t_movie.api_key for x in range(int(int(data) / 20) + 1): if method == "tmdb_popular": tmdb_movies = t_movie.popular(x + 1) elif method == "tmdb_top_rated": tmdb_movies = t_movie.top_rated(x + 1) elif method == "tmdb_now_playing": tmdb_movies = t_movie.now_playing(x + 1) elif method == "tmdb_trending_daily": tmdb_movies = trending.movie_day(x + 1) elif method == "tmdb_trending_weekly": tmdb_movies = trending.movie_week(x + 1) for tmovie in tmdb_movies: count += 1 t_movs.append(tmovie.id) if count == data: break if count == data: break print("| Processing {}: {} Items".format(method, data)) else: tmdb_id = int(data) if method == "tmdb_list": tmdb = List() tmdb.api_key = t_movie.api_key try: t_col = tmdb.details(tmdb_id) tmdb_name = str(t_col) for tmovie in t_col: if tmovie.media_type == "movie": t_movs.append(tmovie.id) except: raise ValueError( "| Config Error: TMDb List: {} not found".format(tmdb_id)) elif method == "tmdb_company": tmdb = Company() tmdb.api_key = t_movie.api_key tmdb_name = str(tmdb.details(tmdb_id)) company_movies = tmdb.movies(tmdb_id) for tmovie in company_movies: t_movs.append(tmovie.id) else: tmdb = Collection() tmdb.api_key = t_movie.api_key t_col = tmdb.details(tmdb_id) tmdb_name = str(t_col) try: for tmovie in t_col.parts: t_movs.append(tmovie['id']) except AttributeError: try: t_movie.details(tmdb_id).imdb_id tmdb_name = str(t_movie.details(tmdb_id)) t_movs.append(tmdb_id) except: raise ValueError( "| Config Error: TMDb ID: {} not found".format( tmdb_id)) print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name)) matched = [] missing = [] for mid in t_movs: mid = str(mid) if mid in plex_map: matched.append(plex.Server.fetchItem(plex_map[mid])) else: missing.append(mid) return matched, missing
class MovieRepository: def __init__(self): self.__tmdb = TMDb() self.__tmdb.api_key = os.getenv('MOVIE_API_KEY') self.__tmdb.language = 'en' self.__tmdb.debug = True self.__movie = ApiMovies() self.__db_engine = db.create_engine(os.getenv('DB_ENGINE')) self.__db_connection = self.__db_engine.connect() self.__db_metadata = db.MetaData() self.__followed_movies = db.Table("followed_movies", self.__db_metadata, autoload=True, autoload_with=self.__db_engine) self.__watched_movies = db.Table("watched_movies", self.__db_metadata, autoload=True, autoload_with=self.__db_engine) def add(self, movie: Movie): pass def delete(self, movie: Movie): pass def update(self, movie: Movie): pass def getById(self, movie_id: int, user_id: UserId = None): movie_from_api = self.__movie.details(movie_id) # There are cases where the api returns an object without properties # We need to return None in those cases too if not movie_from_api or not hasattr(movie_from_api, 'id'): return None return self.__getMovieFromApiResult(movie_from_api, user_id) def getPopularMovies(self, user_id: UserId = None): movies_from_api = self.__movie.popular() if not movies_from_api: return None movies = [] for movie_from_api in movies_from_api: movies.append(self.__getMovieFromApiResult(movie_from_api, user_id)) return movies def getTopRated(self, user_id: UserId = None): movies_from_api = self.__movie.top_rated() if not movies_from_api: return None movies = [] for movie_from_api in movies_from_api: movies.append(self.__getMovieFromApiResult(movie_from_api, user_id)) return movies def getByTitle(self, title: str, user_id: UserId = None): movies_from_api = self.__movie.search(title) if not movies_from_api: return None movies = [] for movie_from_api in movies_from_api: movies.append(self.__getMovieFromApiResult(movie_from_api, user_id)) return movies def getSimilarById(self, movie_id: int, user_id: UserId = None): # When the movie_id is a 404 in the api tmdbv3api returns an error # So we have to force the 404 in that case try: movies_from_api = self.__movie.similar(movie_id) except Exception as e: return None if not movies_from_api: return None movies = [] for movie_from_api in movies_from_api: movies.append(self.__getMovieFromApiResult(movie_from_api, user_id)) return movies def get_following_movies(self, user_id: UserId): query = db.select([ self.__followed_movies.columns.movie_id ]).where(self.__followed_movies.columns.user_id == user_id.value) result_proxy = self.__db_connection.execute(query) result_set = result_proxy.fetchall() following_movies_ids = self.__getMovieIdsFromResult(result_set) movies = [] for following_movie_id in following_movies_ids: movies.append(self.getById(following_movie_id, user_id)) return movies def get_watched_movies(self, user_id: UserId): query = db.select([ self.__watched_movies.columns.movie_id ]).where(self.__watched_movies.columns.user_id == user_id.value) result_proxy = self.__db_connection.execute(query) result_set = result_proxy.fetchall() watched_movies_ids = self.__getMovieIdsFromResult(result_set) movies = [] for watched_movie_id in watched_movies_ids: movies.append(self.getById(watched_movie_id, user_id)) return movies def follow_movie(self, user_id: UserId, movie_id: int): if self.__is_following(movie_id, user_id): return False query = db.insert(self.__followed_movies).values(user_id=user_id.value, movie_id=movie_id) resultProxy = self.__db_connection.execute(query) def unfollow_movie(self, user_id: UserId, movie_id: int): if not self.__is_following(movie_id, user_id): return False query = db.delete(self.__followed_movies).where( and_(self.__followed_movies.columns.user_id == user_id.value, self.__followed_movies.columns.movie_id == movie_id)) resultProxy = self.__db_connection.execute(query) def watch_movie(self, user_id: UserId, movie_id: int): if self.__has_watched(movie_id, user_id): return False query = db.insert(self.__watched_movies).values(user_id=user_id.value, movie_id=movie_id) resultProxy = self.__db_connection.execute(query) def unwatch_movie(self, user_id: UserId, movie_id: int): if not self.__has_watched(movie_id, user_id): return False query = db.delete(self.__watched_movies).where( and_(self.__followed_movies.columns.user_id == user_id.value, self.__followed_movies.columns.movie_id == movie_id)) resultProxy = self.__db_connection.execute(query) def __getMovieIdsFromResult(self, result: tuple): movie_ids = [] for movie_id_result in result: movie_id = movie_id_result[0] movie_ids.append(movie_id) return movie_ids def __getMovieFromApiResult(self, result: Movie, user_id: UserId = None): following = False watched = False if user_id: following = self.__is_following(result.id, user_id) watched = self.__has_watched(result.id, user_id) poster = "" if result.poster_path: poster = (POSTER_URL + result.poster_path) genres = [] if hasattr(result, "genres"): genres = result.genres return Movie(movie_id=result.id, title=result.title, poster_url=poster, rating=result.vote_average, genres=genres, overview=result.overview, following=following, watched=watched) def __is_following(self, movie_id: int, user_id: UserId): query = db.select([self.__followed_movies]).where( and_(self.__followed_movies.columns.user_id == user_id.value, self.__followed_movies.columns.movie_id == movie_id)) resultProxy = self.__db_connection.execute(query) resultSet = resultProxy.fetchall() if not resultSet: return False return True def __has_watched(self, movie_id: int, user_id: UserId): query = db.select([self.__watched_movies]).where( and_(self.__watched_movies.columns.user_id == user_id.value, self.__watched_movies.columns.movie_id == movie_id)) resultProxy = self.__db_connection.execute(query) resultSet = resultProxy.fetchall() if not resultSet: return False return True
class MovieTests(unittest.TestCase): def setUp(self): self.tmdb = TMDb() self.tmdb.api_key = os.environ['TMDB_API_KEY'] self.tmdb.language = "en" self.tmdb.debug = True self.tmdb.wait_on_rate_limit = True self.tmdb.cache = False self.movie = Movie() def test_get_movie_repr(self): search = self.movie.search("Mad Max") self.assertGreater(len(search), 0) for result in search: self.assertNotEqual(str(result), "TMDB Obj") def test_get_movie_details(self): movie = self.movie.details(111) self.assertIsNotNone(movie) self.assertEqual(movie.id, 111) self.assertTrue(hasattr(movie, 'title')) self.assertTrue(hasattr(movie, 'overview')) self.assertTrue(hasattr(movie, 'release_dates')) def test_get_movie_alternative_titles(self): alternative_titles = self.movie.alternative_titles(111) self.assertEqual(alternative_titles.id, 111) self.assertGreater(len(alternative_titles.titles), 0) for title in alternative_titles.titles: self.assertIn('iso_3166_1', title) self.assertIn('title', title) self.assertIn('type', title) def test_get_movie_changes(self): changes = self.movie.changes(111, start_date="2016-08-29", end_date="2016-09-10") self.assertIsNotNone(changes) changes = self.movie.changes(111, start_date="2016-08-29") self.assertIsNotNone(changes) changes = self.movie.changes(111, end_date="2016-09-10") self.assertIsNotNone(changes) changes = self.movie.changes(111, page=2) self.assertIsNotNone(changes) def test_get_movie_credits(self): credits = self.movie.credits(111) self.assertEqual(credits.id, 111) self.assertTrue(hasattr(credits, "cast")) self.assertTrue(hasattr(credits, "crew")) def test_get_movie_external_ids(self): external_ids = self.movie.external_ids(111) self.assertIn("imdb_id", external_ids) self.assertIn("facebook_id", external_ids) self.assertIn("instagram_id", external_ids) self.assertIn("twitter_id", external_ids) self.assertIn("id", external_ids) def test_get_movie_images(self): images = self.movie.images(111, include_image_language="en,null") self.assertEqual(images.id, 111) self.assertGreater(len(images.backdrops), 0) self.assertGreater(len(images.posters), 0) for image in images.backdrops: self.assertIn("file_path", image) for image in images.posters: self.assertIn("file_path", image) def test_get_movie_keywords(self): keywords = self.movie.keywords(111) for keyword in keywords.keywords: self.assertIn("id", keyword) self.assertIn("name", keyword) def test_get_movie_lists(self): lists = self.movie.lists(111) self.assertGreater(len(lists), 0) for list in lists: self.assertTrue(hasattr(list, "description")) self.assertTrue(hasattr(list, "name")) def test_get_movie_recommendations(self): recommendations = self.movie.recommendations(111) self.assertGreater(len(recommendations), 0) for movie in recommendations: self.assertTrue(hasattr(movie, "id")) def test_get_movie_release_dates(self): release_dates = self.movie.release_dates(111) self.assertIsNotNone(release_dates) self.assertEqual(release_dates.id, 111) def test_get_movie_reviews(self): reviews = self.movie.reviews(111) self.assertGreater(len(reviews), 0) for review in reviews: self.assertTrue(hasattr(review, "id")) self.assertTrue(hasattr(review, "content")) def test_get_movie_videos(self): videos = self.movie.videos(111) self.assertGreater(len(videos), 0) for video in videos: self.assertTrue(hasattr(video, "id")) def test_get_movie_latest(self): latest = self.movie.latest() self.assertIsNotNone(latest) self.assertTrue(hasattr(latest, "id")) def test_get_movie_now_playing(self): now_playing = self.movie.now_playing() self.assertGreater(len(now_playing), 0) for movie in now_playing: self.assertTrue(hasattr(movie, "id")) def test_get_movie_top_rated(self): top_rated = self.movie.top_rated() self.assertGreater(len(top_rated), 0) for movie in top_rated: self.assertTrue(hasattr(movie, "id")) def test_get_movie_upcoming(self): upcoming = self.movie.upcoming() self.assertGreater(len(upcoming), 0) for movie in upcoming: self.assertTrue(hasattr(movie, "id")) def test_get_movie_popular(self): popular = self.movie.popular() self.assertGreater(len(popular), 0) for movie in popular: self.assertTrue(hasattr(movie, "id")) def test_get_movie_search(self): search = self.movie.search("Mad Max") self.assertGreater(len(search), 0) for movie in search: self.assertTrue(hasattr(movie, "id")) def test_get_movie_similar(self): similar = self.movie.similar(111) self.assertGreater(len(similar), 0) for movie in similar: self.assertTrue(hasattr(movie, "id")) def test_get_movie_external(self): external = self.movie.external(external_id="tt8155288", external_source="imdb_id") self.assertGreater(len(external), 0) for movie in external["movie_results"]: self.assertIn("id", movie) external_ids = self.movie.external_ids(movie["id"]) self.assertEqual(external_ids["imdb_id"], "tt8155288")
def tmdb_get_movies(config_path, plex, data, method): t_movs = [] t_movie = Movie() t_movie.api_key = config_tools.TMDB(config_path).apikey # Set TMDb api key for Movie if t_movie.api_key == "None": raise KeyError("Invalid TMDb API Key") count = 0 if method == "tmdb_discover": discover = Discover() discover.api_key = t_movie.api_key discover.discover_movies(data) total_pages = int(os.environ["total_pages"]) total_results = int(os.environ["total_results"]) limit = int(data.pop('limit')) amount = total_results if total_results < limit else limit print("| Processing {}: {} items".format(method, amount)) for attr, value in data.items(): print("| {}: {}".format(attr, value)) for x in range(total_pages): data["page"] = x + 1 tmdb_movies = discover.discover_movies(data) for tmovie in tmdb_movies: count += 1 t_movs.append(tmovie.id) if count == amount: break if count == amount: break elif method in ["tmdb_popular", "tmdb_top_rated", "tmdb_now_playing", "tmdb_trending_daily", "tmdb_trending_weekly"]: #trending = Trending() #TURNON:Trending #trending.api_key = t_movie.api_key #TURNON:Trending for x in range(int(data / 20) + 1): if method == "tmdb_popular": tmdb_movies = t_movie.popular(x + 1) elif method == "tmdb_top_rated": tmdb_movies = t_movie.top_rated(x + 1) elif method == "tmdb_now_playing": tmdb_movies = t_movie.now_playing(x + 1) #elif method == "tmdb_trending_daily": #TURNON:Trending # tmdb_movies = trending.movie_day(x + 1) #TURNON:Trending #elif method == "tmdb_trending_weekly": #TURNON:Trending # tmdb_movies = trending.movie_week(x + 1) #TURNON:Trending for tmovie in tmdb_movies: count += 1 t_movs.append(tmovie.id) if count == data: break if count == data: break print("| Processing {}: {} Items".format(method, data)) else: tmdb_id = int(data) if method == "tmdb_list": tmdb = List() tmdb.api_key = t_movie.api_key try: t_col = tmdb.details(tmdb_id) tmdb_name = str(t_col) for tmovie in t_col: if tmovie.media_type == "movie": t_movs.append(tmovie.id) except: raise ValueError("| Config Error: TMDb List: {} not found".format(tmdb_id)) elif method == "tmdb_company": tmdb = Company() tmdb.api_key = t_movie.api_key tmdb_name = str(tmdb.details(tmdb_id)) company_movies = tmdb.movies(tmdb_id) for tmovie in company_movies: t_movs.append(tmovie.id) else: tmdb = Collection() tmdb.api_key = t_movie.api_key t_col = tmdb.details(tmdb_id) tmdb_name = str(t_col) try: for tmovie in t_col.parts: t_movs.append(tmovie['id']) except AttributeError: try: t_movie.details(tmdb_id).imdb_id tmdb_name = str(t_movie.details(tmdb_id)) t_movs.append(tmdb_id) except: raise ValueError("| Config Error: TMDb ID: {} not found".format(tmdb_id)) print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name)) # Create dictionary of movies and their guid # GUIDs reference from which source Plex has pulled the metadata p_m_map = {} p_movies = plex.Library.all() for m in p_movies: guid = m.guid if "themoviedb://" in guid: guid = guid.split('themoviedb://')[1].split('?')[0] elif "imdb://" in guid: guid = guid.split('imdb://')[1].split('?')[0] elif "plex://" in guid: guid = guid.split('plex://')[1].split('?')[0] else: guid = "None" p_m_map[m] = guid matched = [] missing = [] plex_tools.create_cache(config_path) # We want to search for a match first to limit TMDb API calls # Too many rapid calls can cause a momentary block # If needed in future maybe add a delay after x calls to let the limit reset for mid in t_movs: # For each TMBd ID in TMBd Collection match = False for m in p_m_map: # For each movie in Plex item = m agent_type = urlparse(m.guid).scheme.split('.')[-1] # Plex movie agent if agent_type == 'plex': # Check cache for tmdb_id tmdb_id = plex_tools.query_cache(config_path, item.guid, 'tmdb_id') imdb_id = plex_tools.query_cache(config_path, item.guid, 'imdb_id') if not tmdb_id: imdb_id, tmdb_id = plex_tools.alt_id_lookup(plex, item) print("| Cache | + | {} | {} | {} | {}".format(item.guid, imdb_id, tmdb_id, item.title)) plex_tools.update_cache(config_path, item.guid, imdb_id=imdb_id, tmdb_id=tmdb_id) if int(tmdb_id) == int(mid): match = True break elif agent_type == 'themoviedb': if int(p_m_map[m]) == int(mid): match = True break elif agent_type == 'imdb': imdb_id = t_movie.details(mid).imdb_id for m in p_m_map: if "tt" in p_m_map[m]: if p_m_map[m] == imdb_id: match = True break if match: matched.append(m) else: # Duplicate TMDb call? missing.append(t_movie.details(mid).imdb_id) return matched, missing
insert_cast(j) connection = pymysql.connect( host='rm-d7oxcn1pw78ncu9952o.mysql.eu-west-1.rds.aliyuncs.com', user='******', password='******', db='kiwi_test') cur = connection.cursor() cur.execute("USE kiwi_test") tmdb = TMDb() movie = Movie() for page in range(1, 500): m = movie.top_rated(page) for i in m: if i['id'] < 460000: break k = i['id'] step = 1 movie_list = tm.import_movie(k, k + step) # 460000 for j in movie_list: j.vote_count = 75 insert_movie(j) mg_list = tm.import_movie_genre(k, k + step) for j in mg_list: insert_movie_genre(j) cast_list = tm.import_cast(k, k + step) for j in cast_list: