def path_replace_movie(self, values_dict): if type(values_dict) is list: for item in values_dict: item['path'] = path_replace_movie(item['path']) elif type(values_dict) is dict: values_dict['path'] = path_replace_movie(values_dict['path']) else: return path_replace(values_dict)
def movies_scan_subtitles(no): movies = TableMovies.select( TableMovies.path).where(TableMovies.radarr_id == no) for movie in movies: store_subtitles_movie(path_replace_movie(movie.path)) list_missing_subtitles_movies(no)
def movies_download_subtitles(no): conn_db = sqlite3.connect(os.path.join(config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() movie = c_db.execute("SELECT path, missing_subtitles, radarrId, sceneName, hearing_impaired FROM table_movies WHERE radarrId = ?", (no,)).fetchone() c_db.close() providers_list = get_providers() providers_auth = get_providers_auth() for language in ast.literal_eval(movie[1]): if language is not None: message = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(language)), movie[4], providers_list, providers_auth, str(movie[3]), 'movie') if message is not None: store_subtitles_movie(path_replace_movie(movie[0])) history_log_movie(1, no, message) send_notifications_movie(no, message) list_missing_subtitles_movies(no)
def movies_full_scan_subtitles(): conn_db = sqlite3.connect(os.path.join(config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() movies = c_db.execute("SELECT path FROM table_movies").fetchall() c_db.close() for movie in movies: store_subtitles_movie(path_replace_movie(movie[0])) gc.collect()
def movies_download_subtitles(no): conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() movie = c_db.execute( "SELECT path, missing_subtitles, radarrId, sceneName, hearing_impaired, title FROM table_movies WHERE radarrId = ?", (no, )).fetchone() c_db.close() providers_list = get_providers() providers_auth = get_providers_auth() count_movie = len(ast.literal_eval(movie[1])) for i, language in enumerate(ast.literal_eval(movie[1]), 1): if language is not None: notifications.write(msg='Searching for movies subtitles', queue='get_subtitle', item=i, length=count_movie) result = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(language)), movie[4], providers_list, providers_auth, str(movie[3]), movie[5], 'movie') if result is not None: message = result[0] path = result[1] language_code = result[2] provider = result[3] score = result[4] store_subtitles_movie(path_replace_movie(movie[0])) history_log_movie(1, no, message, path, language_code, provider, score) send_notifications_movie(no, message) list_missing_subtitles_movies(no) if count_movie: notifications.write(msg='Searching completed. Please reload the page.', type='success', duration='permanent', button='refresh', queue='get_subtitle')
def movies_scan_subtitles(no): conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() movies = c_db.execute("SELECT path FROM table_movies WHERE radarrId = ?", (no,)).fetchall() c_db.close() for movie in movies: store_subtitles_movie(path_replace_movie(movie[0])) list_missing_subtitles_movies(no)
def movies_full_scan_subtitles(): movies = TableMovies.select(TableMovies.path) count_movies = movies.count() for i, movie in enumerate(movies, 1): notifications.write(msg='Updating all movies subtitles from disk...', queue='list_subtitles_movies', item=i, length=count_movies) store_subtitles_movie(path_replace_movie(movie.path)) gc.collect()
def movies_full_scan_subtitles(): movies = database.execute("SELECT path FROM table_movies") count_movies = len(movies) for i, movie in enumerate(movies, 1): notifications.write(msg='Updating all movies subtitles from disk...', queue='list_subtitles_movies', item=i, length=count_movies) store_subtitles_movie(movie['path'], path_replace_movie(movie['path'])) gc.collect()
def wanted_download_subtitles_movie(path): conn_db = sqlite3.connect(os.path.join(config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() movies_details = c_db.execute("SELECT path, missing_subtitles, radarrId, radarrId, hearing_impaired, sceneName, failedAttempts FROM table_movies WHERE path = ? AND missing_subtitles != '[]'", (path_replace_reverse_movie(path),)).fetchall() c_db.close() providers_list = get_providers() providers_auth = get_providers_auth() for movie in movies_details: attempt = movie[6] if type(attempt) == unicode: attempt = ast.literal_eval(attempt) for language in ast.literal_eval(movie[1]): if attempt is None: attempt = [] attempt.append([language, time.time()]) else: att = zip(*attempt)[0] if language not in att: attempt.append([language, time.time()]) conn_db = sqlite3.connect(os.path.join(config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() c_db.execute('UPDATE table_movies SET failedAttempts = ? WHERE radarrId = ?', (unicode(attempt), movie[2])) conn_db.commit() c_db.close() for i in range(len(attempt)): if attempt[i][0] == language: if search_active(attempt[i][1]) is True: q4ws.append('Searching ' + str(language_from_alpha2(language)) + ' subtitles for this file: ' + path) message = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(language)), movie[4], providers_list, providers_auth, str(movie[5]), 'movie') if message is not None: store_subtitles_movie(path_replace_movie(movie[0])) list_missing_subtitles_movies(movie[3]) history_log_movie(1, movie[3], message) send_notifications_movie(movie[3], message) else: logging.info('BAZARR Search is not active for movie ' + movie[0] + ' Language: ' + attempt[i][0])
def movies_full_scan_subtitles(): conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() movies = c_db.execute("SELECT path FROM table_movies").fetchall() c_db.close() count_movies = len(movies) for i, movie in enumerate(movies, 1): notifications.write(msg='Updating all movies subtitles from disk...', queue='list_subtitles_movies', item=i, length=count_movies) store_subtitles_movie(path_replace_movie(movie[0])) gc.collect()
def update_movies(): logging.debug('BAZARR Starting movie sync from Radarr.') apikey_radarr = settings.radarr.apikey movie_default_enabled = settings.general.getboolean( 'movie_default_enabled') movie_default_language = settings.general.movie_default_language movie_default_hi = settings.general.movie_default_hi movie_default_forced = settings.general.movie_default_forced if apikey_radarr is None: pass else: audio_profiles = get_profile_list() # Get movies data from radarr url_radarr_api_movies = url_radarr( ) + "/api/movie?apikey=" + apikey_radarr try: r = requests.get(url_radarr_api_movies, timeout=60, verify=False) r.raise_for_status() except requests.exceptions.HTTPError as errh: logging.exception( "BAZARR Error trying to get movies from Radarr. Http error.") return except requests.exceptions.ConnectionError as errc: logging.exception( "BAZARR Error trying to get movies from Radarr. Connection Error." ) return except requests.exceptions.Timeout as errt: logging.exception( "BAZARR Error trying to get movies from Radarr. Timeout Error." ) return except requests.exceptions.RequestException as err: logging.exception("BAZARR Error trying to get movies from Radarr.") return else: # Get current movies in DB current_movies_db = database.execute( "SELECT tmdbId, path, radarrId FROM table_movies") current_movies_db_list = [x['tmdbId'] for x in current_movies_db] current_movies_radarr = [] movies_to_update = [] movies_to_add = [] altered_movies = [] moviesIdListLength = len(r.json()) for i, movie in enumerate(r.json(), 1): notifications.write(msg="Getting movies data from Radarr...", queue='get_movies', item=i, length=moviesIdListLength) if movie['hasFile'] is True: if 'movieFile' in movie: # Detect file separator if movie['path'][0] == "/": separator = "/" else: separator = "\\" if movie["path"] != None and movie['movieFile'][ 'relativePath'] != None: try: overview = unicode(movie['overview']) except: overview = "" try: poster_big = movie['images'][0]['url'] poster = os.path.splitext( poster_big)[0] + '-500' + os.path.splitext( poster_big)[1] except: poster = "" try: fanart = movie['images'][1]['url'] except: fanart = "" if 'sceneName' in movie['movieFile']: sceneName = movie['movieFile']['sceneName'] else: sceneName = None if 'alternativeTitles' in movie: alternativeTitles = str([ item['title'] for item in movie['alternativeTitles'] ]) else: alternativeTitles = None if 'imdbId' in movie: imdbId = movie['imdbId'] else: imdbId = None try: format, resolution = movie['movieFile'][ 'quality']['quality']['name'].split('-') except: format = movie['movieFile']['quality'][ 'quality']['name'] try: resolution = movie['movieFile']['quality'][ 'quality']['resolution'].lstrip( 'r').lower() except: resolution = None if 'mediaInfo' in movie['movieFile']: videoFormat = videoCodecID = videoProfile = videoCodecLibrary = None if 'videoFormat' in movie['movieFile'][ 'mediaInfo']: videoFormat = movie['movieFile'][ 'mediaInfo']['videoFormat'] if 'videoCodecID' in movie['movieFile'][ 'mediaInfo']: videoCodecID = movie['movieFile'][ 'mediaInfo']['videoCodecID'] if 'videoProfile' in movie['movieFile'][ 'mediaInfo']: videoProfile = movie['movieFile'][ 'mediaInfo']['videoProfile'] if 'videoCodecLibrary' in movie['movieFile'][ 'mediaInfo']: videoCodecLibrary = movie['movieFile'][ 'mediaInfo']['videoCodecLibrary'] videoCodec = RadarrFormatVideoCodec( videoFormat, videoCodecID, videoProfile, videoCodecLibrary) audioFormat = audioCodecID = audioProfile = audioAdditionalFeatures = None if 'audioFormat' in movie['movieFile'][ 'mediaInfo']: audioFormat = movie['movieFile'][ 'mediaInfo']['audioFormat'] if 'audioCodecID' in movie['movieFile'][ 'mediaInfo']: audioCodecID = movie['movieFile'][ 'mediaInfo']['audioCodecID'] if 'audioProfile' in movie['movieFile'][ 'mediaInfo']: audioProfile = movie['movieFile'][ 'mediaInfo']['audioProfile'] if 'audioAdditionalFeatures' in movie[ 'movieFile']['mediaInfo']: audioAdditionalFeatures = movie[ 'movieFile']['mediaInfo'][ 'audioAdditionalFeatures'] audioCodec = RadarrFormatAudioCodec( audioFormat, audioCodecID, audioProfile, audioAdditionalFeatures) else: videoCodec = None audioCodec = None # Add movies in radarr to current movies list current_movies_radarr.append( unicode(movie['tmdbId'])) if unicode( movie['tmdbId']) in current_movies_db_list: movies_to_update.append({ 'radarrId': movie["id"], 'title': unicode(movie["title"]), 'path': unicode( movie["path"] + separator + movie['movieFile']['relativePath']), 'tmdbId': unicode(movie["tmdbId"]), 'poster': unicode(poster), 'fanart': unicode(fanart), 'audio_language': unicode( profile_id_to_language( movie['qualityProfileId'], audio_profiles)), 'sceneName': sceneName, 'monitored': unicode(bool(movie['monitored'])), 'year': unicode(movie['year']), 'sortTitle': unicode(movie['sortTitle']), 'alternativeTitles': unicode(alternativeTitles), 'format': unicode(format), 'resolution': unicode(resolution), 'video_codec': unicode(videoCodec), 'audio_codec': unicode(audioCodec), 'overview': unicode(overview), 'imdbId': unicode(imdbId), 'movie_file_id': movie['movieFile']['id'] }) else: if movie_default_enabled is True: movies_to_add.append({ 'radarrId': movie["id"], 'title': movie["title"], 'path': movie["path"] + separator + movie['movieFile']['relativePath'], 'tmdbId': movie["tmdbId"], 'languages': movie_default_language, 'subtitles': '[]', 'hearing_impaired': movie_default_hi, 'overview': overview, 'poster': poster, 'fanart': fanart, 'audio_language': profile_id_to_language( movie['qualityProfileId'], audio_profiles), 'sceneName': sceneName, 'monitored': unicode(bool(movie['monitored'])), 'sortTitle': movie['sortTitle'], 'year': movie['year'], 'alternativeTitles': alternativeTitles, 'format': format, 'resolution': resolution, 'video_codec': videoCodec, 'audio_codec': audioCodec, 'imdbId': imdbId, 'forced': movie_default_forced, 'movie_file_id': movie['movieFile']['id'] }) else: movies_to_add.append({ 'radarrId': movie["id"], 'title': movie["title"], 'path': movie["path"] + separator + movie['movieFile']['relativePath'], 'tmdbId': movie["tmdbId"], 'languages': None, 'subtitles': '[]', 'hearing_impaired': None, 'overview': overview, 'poster': poster, 'fanart': fanart, 'audio_language': profile_id_to_language( movie['qualityProfileId'], audio_profiles), 'sceneName': sceneName, 'monitored': unicode(bool(movie['monitored'])), 'sortTitle': movie['sortTitle'], 'year': movie['year'], 'alternativeTitles': alternativeTitles, 'format': format, 'resolution': resolution, 'video_codec': videoCodec, 'audio_codec': audioCodec, 'imdbId': imdbId, 'forced': None, 'movie_file_id': movie['movieFile']['id'] }) else: logging.error( 'BAZARR Radarr returned a movie without a file path: ' + movie["path"] + separator + movie['movieFile']['relativePath']) # Remove old movies from DB removed_movies = list( set(current_movies_db_list) - set(current_movies_radarr)) for removed_movie in removed_movies: database.execute("DELETE FROM table_movies WHERE tmdbId=?", (removed_movie, )) # Update movies in DB movies_in_db_list = [] movies_in_db = database.execute( "SELECT radarrId, title, path, tmdbId, overview, poster, fanart, " "audio_language, sceneName, monitored, sortTitle, year, " "alternativeTitles, format, resolution, video_codec, audio_codec, imdbId," "movie_file_id FROM table_movies") for item in movies_in_db: movies_in_db_list.append(item) movies_to_update_list = [ i for i in movies_to_update if i not in movies_in_db_list ] for updated_movie in movies_to_update_list: query = dict_converter.convert(updated_movie) database.execute( '''UPDATE table_movies SET ''' + query.keys_update + ''' WHERE radarrId = ?''', query.values + (updated_movie['radarrId'], )) altered_movies.append([ updated_movie['tmdbId'], updated_movie['path'], updated_movie['radarrId'], updated_movie['monitored'] ]) # Insert new movies in DB for added_movie in movies_to_add: query = dict_converter.convert(added_movie) result = database.execute( '''INSERT OR IGNORE INTO table_movies(''' + query.keys_insert + ''') VALUES(''' + query.question_marks + ''')''', query.values) if result > 0: altered_movies.append([ added_movie['tmdbId'], added_movie['path'], added_movie['radarrId'], added_movie['monitored'] ]) else: logging.debug( 'BAZARR unable to insert this movie into the database:', path_replace_movie(added_movie['path'])) # Store subtitles for added or modified movies for i, altered_movie in enumerate(altered_movies, 1): notifications.write( msg='Indexing movies embedded subtitles...', queue='get_movies', item=i, length=len(altered_movies)) store_subtitles_movie(path_replace_movie(altered_movie[1])) logging.debug( 'BAZARR All movies synced from Radarr into database.') # Search for desired subtitles if no more than 5 movies have been added. if len(altered_movies) <= 5: logging.debug( "BAZARR No more than 5 movies were added during this sync then we'll search for subtitles." ) for altered_movie in altered_movies: if settings.radarr.getboolean('only_monitored'): if altered_movie[3] == 'True': movies_download_subtitles(altered_movie[2]) else: movies_download_subtitles(altered_movie[2]) else: logging.debug( "BAZARR More than 5 movies were added during this sync then we wont search for subtitles." )
def update_movies(): logging.debug('BAZARR Starting movie sync from Radarr.') apikey_radarr = settings.radarr.apikey movie_default_enabled = settings.general.getboolean( 'movie_default_enabled') movie_default_language = settings.general.movie_default_language movie_default_hi = settings.general.movie_default_hi movie_default_forced = settings.general.movie_default_forced if apikey_radarr is None: pass else: get_profile_list() # Get movies data from radarr url_radarr_api_movies = url_radarr + "/api/movie?apikey=" + apikey_radarr try: r = requests.get(url_radarr_api_movies, timeout=60, verify=False) r.raise_for_status() except requests.exceptions.HTTPError as errh: logging.exception( "BAZARR Error trying to get movies from Radarr. Http error.") except requests.exceptions.ConnectionError as errc: logging.exception( "BAZARR Error trying to get movies from Radarr. Connection Error." ) except requests.exceptions.Timeout as errt: logging.exception( "BAZARR Error trying to get movies from Radarr. Timeout Error." ) except requests.exceptions.RequestException as err: logging.exception("BAZARR Error trying to get movies from Radarr.") else: # Get current movies in DB db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) c = db.cursor() current_movies_db = c.execute( 'SELECT tmdbId, path, radarrId FROM table_movies').fetchall() db.close() current_movies_db_list = [x[0] for x in current_movies_db] current_movies_radarr = [] movies_to_update = [] movies_to_add = [] moviesIdListLength = len(r.json()) for i, movie in enumerate(r.json(), 1): notifications.write(msg="Getting movies data from Radarr...", queue='get_movies', item=i, length=moviesIdListLength) if movie['hasFile'] is True: if 'movieFile' in movie: if movie["path"] != None and movie['movieFile'][ 'relativePath'] != None: try: overview = unicode(movie['overview']) except: overview = "" try: poster_big = movie['images'][0]['url'] poster = os.path.splitext( poster_big)[0] + '-500' + os.path.splitext( poster_big)[1] except: poster = "" try: fanart = movie['images'][1]['url'] except: fanart = "" if 'sceneName' in movie['movieFile']: sceneName = movie['movieFile']['sceneName'] else: sceneName = None if movie['alternativeTitles'] != None: alternativeTitles = str([ item['title'] for item in movie['alternativeTitles'] ]) if 'imdbId' in movie: imdbId = movie['imdbId'] else: imdbId = None try: format, resolution = movie['movieFile'][ 'quality']['quality']['name'].split('-') except: format = movie['movieFile']['quality'][ 'quality']['name'] try: resolution = movie['movieFile']['quality'][ 'quality']['resolution'].lstrip( 'r').lower() except: resolution = None if 'mediaInfo' in movie['movieFile']: videoFormat = videoCodecID = videoProfile = videoCodecLibrary = None if 'videoFormat' in movie['movieFile'][ 'mediaInfo']: videoFormat = movie['movieFile'][ 'mediaInfo']['videoFormat'] if 'videoCodecID' in movie['movieFile'][ 'mediaInfo']: videoCodecID = movie['movieFile'][ 'mediaInfo']['videoCodecID'] if 'videoProfile' in movie['movieFile'][ 'mediaInfo']: videoProfile = movie['movieFile'][ 'mediaInfo']['videoProfile'] if 'videoCodecLibrary' in movie['movieFile'][ 'mediaInfo']: videoCodecLibrary = movie['movieFile'][ 'mediaInfo']['videoCodecLibrary'] videoCodec = RadarrFormatVideoCodec( videoFormat, videoCodecID, videoProfile, videoCodecLibrary) audioFormat = audioCodecID = audioProfile = audioAdditionalFeatures = None if 'audioFormat' in movie['movieFile'][ 'mediaInfo']: audioFormat = movie['movieFile'][ 'mediaInfo']['audioFormat'] if 'audioCodecID' in movie['movieFile'][ 'mediaInfo']: audioCodecID = movie['movieFile'][ 'mediaInfo']['audioCodecID'] if 'audioProfile' in movie['movieFile'][ 'mediaInfo']: audioProfile = movie['movieFile'][ 'mediaInfo']['audioProfile'] if 'audioAdditionalFeatures' in movie[ 'movieFile']['mediaInfo']: audioAdditionalFeatures = movie[ 'movieFile']['mediaInfo'][ 'audioAdditionalFeatures'] audioCodec = RadarrFormatAudioCodec( audioFormat, audioCodecID, audioProfile, audioAdditionalFeatures) else: videoCodec = None audioCodec = None # Add movies in radarr to current movies list current_movies_radarr.append( unicode(movie['tmdbId'])) # Detect file separator if movie['path'][0] == "/": separator = "/" else: separator = "\\" if unicode( movie['tmdbId']) in current_movies_db_list: movies_to_update.append( (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie["id"], overview, poster, fanart, profile_id_to_language( movie['qualityProfileId']), sceneName, unicode(bool(movie['monitored'])), movie['sortTitle'], movie['year'], alternativeTitles, format, resolution, videoCodec, audioCodec, imdbId, movie["tmdbId"])) else: if movie_default_enabled is True: movies_to_add.append( (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie_default_language, '[]', movie_default_hi, movie["id"], overview, poster, fanart, profile_id_to_language( movie['qualityProfileId']), sceneName, unicode(bool(movie['monitored'])), movie['sortTitle'], movie['year'], alternativeTitles, format, resolution, videoCodec, audioCodec, imdbId, movie_default_forced)) else: movies_to_add.append( (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie["tmdbId"], movie["tmdbId"], movie["id"], overview, poster, fanart, profile_id_to_language( movie['qualityProfileId']), sceneName, unicode(bool(movie['monitored'])), movie['sortTitle'], movie['year'], alternativeTitles, format, resolution, videoCodec, audioCodec, imdbId, movie["tmdbId"])) else: logging.error( 'BAZARR Radarr returned a movie without a file path: ' + movie["path"] + separator + movie['movieFile']['relativePath']) # Update or insert movies in DB db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) c = db.cursor() updated_result = c.executemany( '''UPDATE table_movies SET title = ?, path = ?, tmdbId = ?, radarrId = ?, overview = ?, poster = ?, fanart = ?, `audio_language` = ?, sceneName = ?, monitored = ?, sortTitle = ?, year = ?, alternativeTitles = ?, format = ?, resolution = ?, video_codec = ?, audio_codec = ?, imdbId = ? WHERE tmdbid = ?''', movies_to_update) db.commit() if movie_default_enabled is True: added_result = c.executemany( '''INSERT OR IGNORE INTO table_movies(title, path, tmdbId, languages, subtitles,`hearing_impaired`, radarrId, overview, poster, fanart, `audio_language`, sceneName, monitored, sortTitle, year, alternativeTitles, format, resolution, video_codec, audio_codec, imdbId, forced) VALUES (?,?,?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', movies_to_add) db.commit() else: added_result = c.executemany( '''INSERT OR IGNORE INTO table_movies(title, path, tmdbId, languages, subtitles,`hearing_impaired`, radarrId, overview, poster, fanart, `audio_language`, sceneName, monitored, sortTitle, year, alternativeTitles, format, resolution, video_codec, audio_codec, imdbId, forced) VALUES (?,?,?,(SELECT languages FROM table_movies WHERE tmdbId = ?), '[]',(SELECT `hearing_impaired` FROM table_movies WHERE tmdbId = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT `forced` FROM table_movies WHERE tmdbId = ?))''', movies_to_add) db.commit() removed_movies = list( set(current_movies_db_list) - set(current_movies_radarr)) for removed_movie in removed_movies: c.execute('DELETE FROM table_movies WHERE tmdbId = ?', (removed_movie, )) db.commit() # Get movies list after INSERT and UPDATE movies_now_in_db = c.execute( 'SELECT tmdbId, path, radarrId FROM table_movies').fetchall() # Close database connection db.close() # Get only movies added or modified and store subtitles for them altered_movies = set(movies_now_in_db).difference( set(current_movies_db)) for altered_movie in altered_movies: store_subtitles_movie(path_replace_movie(altered_movie[1])) list_missing_subtitles_movies(altered_movie[2]) # Search for desired subtitles if no more than 5 movies have been added. if len(altered_movies) <= 5: logging.debug( "BAZARR No more than 5 movies were added during this sync then we'll search for subtitles." ) for altered_movie in altered_movies: movies_download_subtitles(altered_movie[2]) else: logging.debug( "BAZARR More than 5 movies were added during this sync then we wont search for subtitles." ) logging.debug('BAZARR All movies synced from Radarr into database.')
def update_movies(): q4ws.append("Update movies list from Radarr is running...") logging.debug('BAZARR Starting movie sync from Radarr.') apikey_radarr = settings.radarr.apikey movie_default_enabled = settings.general.getboolean( 'movie_default_enabled') movie_default_language = settings.general.movie_default_language movie_default_hi = settings.general.movie_default_hi if apikey_radarr is None: pass else: get_profile_list() # Get movies data from radarr url_radarr_api_movies = url_radarr + "/api/movie?apikey=" + apikey_radarr try: r = requests.get(url_radarr_api_movies, timeout=15, verify=False) r.raise_for_status() except requests.exceptions.HTTPError as errh: logging.exception( "BAZARR Error trying to get movies from Radarr. Http error.") except requests.exceptions.ConnectionError as errc: logging.exception( "BAZARR Error trying to get movies from Radarr. Connection Error." ) except requests.exceptions.Timeout as errt: logging.exception( "BAZARR Error trying to get movies from Radarr. Timeout Error." ) except requests.exceptions.RequestException as err: logging.exception("BAZARR Error trying to get movies from Radarr.") else: # Get current movies in DB db = sqlite3.connect(os.path.join(config_dir, 'db', 'bazarr.db'), timeout=30) c = db.cursor() current_movies_db = c.execute( 'SELECT tmdbId, path FROM table_movies').fetchall() db.close() current_movies_db_list = [x[0] for x in current_movies_db] current_movies_radarr = [] movies_to_update = [] movies_to_add = [] for movie in r.json(): q4ws.append("Getting data for this movie: " + movie['title']) if movie['hasFile'] is True: if 'movieFile' in movie: if movie["path"] != None and movie['movieFile'][ 'relativePath'] != None: try: overview = unicode(movie['overview']) except: overview = "" try: poster_big = movie['images'][0]['url'] poster = os.path.splitext( poster_big)[0] + '-500' + os.path.splitext( poster_big)[1] except: poster = "" try: fanart = movie['images'][1]['url'] except: fanart = "" if 'sceneName' in movie['movieFile']: sceneName = movie['movieFile']['sceneName'] else: sceneName = None # Add movies in radarr to current movies list current_movies_radarr.append( unicode(movie['tmdbId'])) # Detect file separator if movie['path'][0] == "/": separator = "/" else: separator = "\\" if unicode( movie['tmdbId']) in current_movies_db_list: movies_to_update.append( (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie["id"], overview, poster, fanart, profile_id_to_language( movie['qualityProfileId']), sceneName, unicode(bool(movie['monitored'])), movie['sortTitle'], movie["tmdbId"])) else: if movie_default_enabled is True: movies_to_add.append( (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie_default_language, '[]', movie_default_hi, movie["id"], overview, poster, fanart, profile_id_to_language( movie['qualityProfileId']), sceneName, unicode(bool(movie['monitored'])), movie['sortTitle'])) else: movies_to_add.append( (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie["tmdbId"], movie["tmdbId"], movie["id"], overview, poster, fanart, profile_id_to_language( movie['qualityProfileId']), sceneName, unicode(bool(movie['monitored'])), movie['sortTitle'])) else: logging.error( 'BAZARR Radarr returned a movie without a file path: ' + movie["path"] + separator + movie['movieFile']['relativePath']) # Update or insert movies in DB db = sqlite3.connect(os.path.join(config_dir, 'db', 'bazarr.db'), timeout=30) c = db.cursor() updated_result = c.executemany( '''UPDATE table_movies SET title = ?, path = ?, tmdbId = ?, radarrId = ?, overview = ?, poster = ?, fanart = ?, `audio_language` = ?, sceneName = ?, monitored = ?, sortTitle= ? WHERE tmdbid = ?''', movies_to_update) db.commit() if movie_default_enabled is True: added_result = c.executemany( '''INSERT OR IGNORE INTO table_movies(title, path, tmdbId, languages, subtitles,`hearing_impaired`, radarrId, overview, poster, fanart, `audio_language`, sceneName, monitored, sortTitle) VALUES (?,?,?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', movies_to_add) db.commit() else: added_result = c.executemany( '''INSERT OR IGNORE INTO table_movies(title, path, tmdbId, languages, subtitles,`hearing_impaired`, radarrId, overview, poster, fanart, `audio_language`, sceneName, monitored, sortTitle) VALUES (?,?,?,(SELECT languages FROM table_movies WHERE tmdbId = ?), '[]',(SELECT `hearing_impaired` FROM table_movies WHERE tmdbId = ?), ?, ?, ?, ?, ?, ?, ?, ?)''', movies_to_add) db.commit() removed_movies = list( set(current_movies_db_list) - set(current_movies_radarr)) for removed_movie in removed_movies: c.execute('DELETE FROM table_movies WHERE tmdbId = ?', (removed_movie, )) db.commit() # Get movies list after INSERT and UPDATE movies_now_in_db = c.execute( 'SELECT tmdbId, path FROM table_movies').fetchall() # Close database connection db.close() # Get only movies added or modified and store subtitles for them altered_movies = set(movies_now_in_db).difference( set(current_movies_db)) for altered_movie in altered_movies: store_subtitles_movie(path_replace_movie(altered_movie[1])) logging.debug('BAZARR All movies synced from Radarr into database.') list_missing_subtitles_movies() logging.debug('BAZARR All movie missing subtitles updated in database.') q4ws.append("Update movies list from Radarr is ended.")
def upgrade_subtitles(): days_to_upgrade_subs = settings.general.days_to_upgrade_subs minimum_timestamp = ( (datetime.now() - timedelta(days=int(days_to_upgrade_subs))) - datetime(1970, 1, 1)).total_seconds() if settings.general.getboolean('upgrade_manual'): query_actions = [1, 2, 3] else: query_actions = [1, 3] db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) c = db.cursor() episodes_list = c.execute( """SELECT table_history.video_path, table_history.language, table_history.score, table_shows.hearing_impaired, table_episodes.scene_name, table_episodes.title, table_episodes.sonarrSeriesId, table_episodes.sonarrEpisodeId, MAX(table_history.timestamp), table_shows.languages FROM table_history INNER JOIN table_shows on table_shows.sonarrSeriesId = table_history.sonarrSeriesId INNER JOIN table_episodes on table_episodes.sonarrEpisodeId = table_history.sonarrEpisodeId WHERE action IN (""" + ','.join(map(str, query_actions)) + """) AND timestamp > ? AND score is not null GROUP BY table_history.video_path, table_history.language""", (minimum_timestamp, )).fetchall() movies_list = c.execute( """SELECT table_history_movie.video_path, table_history_movie.language, table_history_movie.score, table_movies.hearing_impaired, table_movies.sceneName, table_movies.title, table_movies.radarrId, MAX(table_history_movie.timestamp), table_movies.languages FROM table_history_movie INNER JOIN table_movies on table_movies.radarrId = table_history_movie.radarrId WHERE action IN (""" + ','.join(map(str, query_actions)) + """) AND timestamp > ? AND score is not null GROUP BY table_history_movie.video_path, table_history_movie.language""", (minimum_timestamp, )).fetchall() db.close() episodes_to_upgrade = [] for episode in episodes_list: if os.path.exists(path_replace(episode[0])) and int(episode[2]) < 360: episodes_to_upgrade.append(episode) movies_to_upgrade = [] for movie in movies_list: if os.path.exists(path_replace_movie( movie[0])) and int(movie[2]) < 120: movies_to_upgrade.append(movie) providers_list = get_providers() providers_auth = get_providers_auth() count_episode_to_upgrade = len(episodes_to_upgrade) count_movie_to_upgrade = len(movies_to_upgrade) for i, episode in enumerate(episodes_to_upgrade, 1): if episode[1] in ast.literal_eval(str(episode[9])): notifications.write(msg='Upgrading series subtitles : ' + str(i) + '/' + str(count_episode_to_upgrade), queue='get_subtitle', duration='long') result = download_subtitle(path_replace(episode[0]), str(alpha3_from_alpha2(episode[1])), episode[3], providers_list, providers_auth, str(episode[4]), episode[5], 'series', forced_minimum_score=int(episode[2]), is_upgrade=True) if result is not None: message = result[0] path = result[1] language_code = result[2] provider = result[3] score = result[4] store_subtitles(path_replace(episode[0])) history_log(3, episode[6], episode[7], message, path, language_code, provider, score) send_notifications(episode[6], episode[7], message) for i, movie in enumerate(movies_to_upgrade, 1): if movie[1] in ast.literal_eval(str(movie[8])): notifications.write(msg='Upgrading movie subtitles : ' + str(i) + '/' + str(count_movie_to_upgrade), queue='get_subtitle', duration='long') result = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(movie[1])), movie[3], providers_list, providers_auth, str(movie[4]), movie[5], 'movie', forced_minimum_score=int(movie[2]), is_upgrade=True) if result is not None: message = result[0] path = result[1] language_code = result[2] provider = result[3] score = result[4] store_subtitles_movie(path_replace_movie(movie[0])) history_log_movie(3, movie[6], message, path, language_code, provider, score) send_notifications_movie(movie[6], message)
def store_subtitles_movie(file): logging.debug('BAZARR started subtitles indexing for this file: ' + file) actual_subtitles = [] if os.path.exists(file): # notifications.write(msg='Analyzing this file for subtitles: ' + file, queue='list_subtitles') if settings.general.getboolean('use_embedded_subs'): logging.debug("BAZARR is trying to index embedded subtitles.") try: subtitle_languages = embedded_subs_reader.list_languages(file) for subtitle_language in subtitle_languages: try: if alpha2_from_alpha3(subtitle_language) is not None: lang = str(alpha2_from_alpha3(subtitle_language)) logging.debug( "BAZARR embedded subtitles detected: " + lang) actual_subtitles.append([lang, None]) except: logging.debug( "BAZARR unable to index this unrecognized language: " + subtitle_language) pass except Exception as e: logging.exception( "BAZARR error when trying to analyze this %s file: %s" % (os.path.splitext(file)[1], file)) pass dest_folder = get_subtitle_destination_folder() or '' subliminal_patch.core.CUSTOM_PATHS = [dest_folder ] if dest_folder else [] brazilian_portuguese = [".pt-br", ".pob", "pb"] try: subtitles = search_external_subtitles( file, languages=get_language_set(), only_one=settings.general.getboolean('single_language')) except Exception as e: logging.exception("BAZARR unable to index external subtitles.") pass else: for subtitle, language in subtitles.iteritems(): if str(os.path.splitext(subtitle)[0]).lower().endswith( tuple(brazilian_portuguese)) is True: logging.debug("BAZARR external subtitles detected: " + "pb") actual_subtitles.append([ str("pb"), path_replace_reverse_movie( os.path.join(os.path.dirname(file), dest_folder, subtitle)) ]) elif str(language) != 'und': logging.debug("BAZARR external subtitles detected: " + str(language)) actual_subtitles.append([ str(language), path_replace_reverse_movie( os.path.join(os.path.dirname(file), dest_folder, subtitle)) ]) else: if os.path.splitext(subtitle)[1] != ".sub": logging.debug( "BAZARR falling back to file content analysis to detect language." ) with open( path_replace_movie( os.path.join(os.path.dirname(file), dest_folder, subtitle)), 'r') as f: text = list(islice(f, 100)) text = ' '.join(text) encoding = UnicodeDammit(text) try: text = text.decode(encoding.original_encoding) detected_language = langdetect.detect(text) except Exception as e: logging.exception( 'BAZARR Error trying to detect language for this subtitles file: ' + path_replace( os.path.join(os.path.dirname(file), subtitle)) + ' You should try to delete this subtitles file manually and ask Bazarr to download it again.' ) else: if len(detected_language) > 0: logging.debug( "BAZARR external subtitles detected and analysis guessed this language: " + str(detected_language)) actual_subtitles.append([ str(detected_language), path_replace_reverse_movie( os.path.join( os.path.dirname(file), dest_folder, subtitle)) ]) conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() logging.debug("BAZARR storing those languages to DB: " + str(actual_subtitles)) c_db.execute("UPDATE table_movies SET subtitles = ? WHERE path = ?", (str(actual_subtitles), path_replace_reverse_movie(file))) conn_db.commit() c_db.close() else: logging.debug( "BAZARR this file doesn't seems to exist or isn't accessible.") logging.debug('BAZARR ended subtitles indexing for this file: ' + file) return actual_subtitles
def path_substitution_movie(path): return path_replace_movie(path)
def store_subtitles_movie(file): logging.debug('BAZARR started subtitles indexing for this file: ' + file) actual_subtitles = [] if os.path.exists(file): q4ws.append('Analyzing this file for subtitles: ' + file) if os.path.splitext(file)[1] == '.mkv': logging.debug("BAZARR is trying to index embedded subtitles.") try: with open(file, 'rb') as f: mkv = enzyme.MKV(f) for subtitle_track in mkv.subtitle_tracks: try: if alpha2_from_alpha3(subtitle_track.language) is not None: lang = str(alpha2_from_alpha3(subtitle_track.language)) logging.debug("BAZARR embedded subtitles detected: " + lang) actual_subtitles.append([lang, None]) except: logging.debug("BAZARR unable to index this unrecognized language: " + subtitle_track.language) pass except Exception as e: logging.exception("BAZARR error when trying to analyze this mkv file: " + file) pass else: logging.debug("BAZARR This file isn't an .mkv file.") brazilian_portuguese = [".pt-br", ".pob", "pb"] try: subtitles = core.search_external_subtitles(file) except Exception as e: logging.exception("BAZARR unable to index external subtitles.") pass else: for subtitle, language in subtitles.iteritems(): if str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(brazilian_portuguese)) is True: logging.debug("BAZARR external subtitles detected: " + "pb") actual_subtitles.append([str("pb"), path_replace_reverse_movie(os.path.join(os.path.dirname(file), subtitle))]) elif str(language) != 'und': logging.debug("BAZARR external subtitles detected: " + str(language)) actual_subtitles.append([str(language), path_replace_reverse_movie(os.path.join(os.path.dirname(file), subtitle))]) else: if os.path.splitext(subtitle)[1] != ".sub": logging.debug("BAZARR falling back to file content analysis to detect language.") with open(path_replace_movie(os.path.join(os.path.dirname(file), subtitle)), 'r') as f: text = list(islice(f, 100)) text = ' '.join(text) encoding = UnicodeDammit(text) try: text = text.decode(encoding.original_encoding) detected_language = langdetect.detect(text) except Exception as e: logging.exception('BAZARR Error trying to detect language for this subtitles file: ' + path_replace(os.path.join(os.path.dirname(file), subtitle)) + ' You should try to delete this subtitles file manually and ask Bazarr to download it again.') else: if len(detected_language) > 0: logging.debug("BAZARR external subtitles detected and analysis guessed this language: " + str(detected_language)) actual_subtitles.append([str(detected_language), path_replace_reverse_movie(os.path.join(os.path.dirname(file), subtitle))]) conn_db = sqlite3.connect(os.path.join(config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() logging.debug("BAZARR storing those languages to DB: " + str(actual_subtitles)) c_db.execute("UPDATE table_movies SET subtitles = ? WHERE path = ?", (str(actual_subtitles), path_replace_reverse_movie(file))) conn_db.commit() c_db.close() else: logging.debug("BAZARR this file doesn't seems to exist or isn't accessible.") logging.debug('BAZARR ended subtitles indexing for this file: ' + file) return actual_subtitles
def movies_scan_subtitles(no): movies = database.execute("SELECT path FROM table_movies WHERE radarrId=?", (no, )) for movie in movies: store_subtitles_movie(movie['path'], path_replace_movie(movie['path']))