Exemple #1
0
    def post(self):
        radarr_id = int(request.args.get('radarrid'))
        provider = request.form.get('provider')
        subs_id = request.form.get('subs_id')
        language = request.form.get('language')
        # TODO
        forced = False
        hi = False

        data = TableMovies.select(TableMovies.path).where(TableMovies.radarrId == radarr_id).dicts().get()

        media_path = data['path']
        subtitles_path = request.form.get('subtitles_path')

        blacklist_log_movie(radarr_id=radarr_id,
                            provider=provider,
                            subs_id=subs_id,
                            language=language)
        delete_subtitles(media_type='movie',
                         language=language,
                         forced=forced,
                         hi=hi,
                         media_path=path_mappings.path_replace_movie(media_path),
                         subtitles_path=subtitles_path,
                         radarr_id=radarr_id)
        movies_download_subtitles(radarr_id)
        event_stream(type='movie-history')
        return '', 200
Exemple #2
0
    def patch(self):
        radarrid = request.form.get('radarrid')
        action = request.form.get('action')
        if action == "scan-disk":
            movies_scan_subtitles(radarrid)
            return '', 204
        elif action == "search-missing":
            movies_download_subtitles(radarrid)
            return '', 204
        elif action == "search-wanted":
            wanted_search_missing_subtitles_movies()
            return '', 204

        return '', 400
Exemple #3
0
    def post(self):
        json_webhook = request.form.get('payload')
        parsed_json_webhook = json.loads(json_webhook)

        event = parsed_json_webhook['event']
        if event not in ['media.play']:
            return '', 204

        media_type = parsed_json_webhook['Metadata']['type']

        if media_type == 'episode':
            season = parsed_json_webhook['Metadata']['parentIndex']
            episode = parsed_json_webhook['Metadata']['index']
        else:
            season = episode = None

        ids = []
        for item in parsed_json_webhook['Metadata']['Guid']:
            splitted_id = item['id'].split('://')
            if len(splitted_id) == 2:
                ids.append({splitted_id[0]: splitted_id[1]})
        if not ids:
            return '', 404

        if media_type == 'episode':
            try:
                episode_imdb_id = [x['imdb'] for x in ids if 'imdb' in x][0]
                r = requests.get(
                    'https://imdb.com/title/{}'.format(episode_imdb_id),
                    headers={"User-Agent": os.environ["SZ_USER_AGENT"]})
                soup = bso(r.content, "html.parser")
                series_imdb_id = soup.find(
                    'a',
                    {'class': re.compile(r'SeriesParentLink__ParentTextLink')
                     })['href'].split('/')[2]
            except:
                return '', 404
            else:
                sonarrEpisodeId = TableEpisodes.select(TableEpisodes.sonarrEpisodeId) \
                    .join(TableShows, on=(TableEpisodes.sonarrSeriesId == TableShows.sonarrSeriesId)) \
                    .where(TableShows.imdbId == series_imdb_id,
                           TableEpisodes.season == season,
                           TableEpisodes.episode == episode) \
                    .dicts() \
                    .get()

                if sonarrEpisodeId:
                    episode_download_subtitles(
                        no=sonarrEpisodeId['sonarrEpisodeId'],
                        send_progress=True)
        else:
            try:
                movie_imdb_id = [x['imdb'] for x in ids if 'imdb' in x][0]
            except:
                return '', 404
            else:
                radarrId = TableMovies.select(TableMovies.radarrId)\
                    .where(TableMovies.imdbId == movie_imdb_id)\
                    .dicts()\
                    .get()
                if radarrId:
                    movies_download_subtitles(no=radarrId['radarrId'])

        return '', 200
Exemple #4
0
def update_movies():
    logging.debug('BAZARR Starting movie sync from Radarr.')
    apikey_radarr = settings.radarr.apikey

    radarr_version = get_radarr_version()
    movie_default_enabled = settings.general.getboolean(
        'movie_default_enabled')

    if movie_default_enabled is True:
        movie_default_language = settings.general.movie_default_language
        movie_default_hi = settings.general.movie_default_hi
        movie_default_forced = settings.general.movie_default_forced
    else:
        movie_default_language = '[]'
        movie_default_hi = 'False'
        movie_default_forced = 'False'

    if apikey_radarr is None:
        pass
    else:
        audio_profiles = get_profile_list()
        tagsDict = get_tags()

        # Get movies data from radarr
        if radarr_version.startswith('0'):
            url_radarr_api_movies = url_radarr(
            ) + "/api/movie?apikey=" + apikey_radarr
        else:
            url_radarr_api_movies = url_radarr(
            ) + "/api/v3/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):
                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 = str(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

                            alternativeTitles = None
                            if radarr_version.startswith('0'):
                                if 'alternativeTitles' in movie:
                                    alternativeTitles = str([
                                        item['title']
                                        for item in movie['alternativeTitles']
                                    ])
                            else:
                                if 'alternateTitles' in movie:
                                    alternativeTitles = str([
                                        item['title']
                                        for item in movie['alternateTitles']
                                    ])

                            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 = str(
                                        movie['movieFile']['quality']
                                        ['quality']['resolution']) + 'p'
                                except:
                                    resolution = None

                            if 'mediaInfo' in movie['movieFile']:
                                videoFormat = videoCodecID = videoProfile = videoCodecLibrary = None
                                if radarr_version.startswith('0'):
                                    if 'videoFormat' in movie['movieFile'][
                                            'mediaInfo']:
                                        videoFormat = movie['movieFile'][
                                            'mediaInfo']['videoFormat']
                                else:
                                    if 'videoCodec' in movie['movieFile'][
                                            'mediaInfo']:
                                        videoFormat = movie['movieFile'][
                                            'mediaInfo']['videoCodec']
                                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,
                                    videoCodecLibrary)

                                audioFormat = audioCodecID = audioProfile = audioAdditionalFeatures = None
                                if radarr_version.startswith('0'):
                                    if 'audioFormat' in movie['movieFile'][
                                            'mediaInfo']:
                                        audioFormat = movie['movieFile'][
                                            'mediaInfo']['audioFormat']
                                else:
                                    if 'audioCodec' in movie['movieFile'][
                                            'mediaInfo']:
                                        audioFormat = movie['movieFile'][
                                            'mediaInfo']['audioCodec']
                                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

                            audio_language = None
                            if radarr_version.startswith('0'):
                                if 'mediaInfo' in movie['movieFile']:
                                    if 'audioLanguages' in movie['movieFile'][
                                            'mediaInfo']:
                                        audio_language_list = movie[
                                            'movieFile']['mediaInfo'][
                                                'audioLanguages'].split('/')
                                        if len(audio_language_list):
                                            audio_language = audio_language_list[
                                                0].strip()
                                if not audio_language:
                                    audio_language = profile_id_to_language(
                                        movie['qualityProfileId'],
                                        audio_profiles)
                            else:
                                if 'languages' in movie['movieFile'] and len(
                                        movie['movieFile']['languages']):
                                    for item in movie['movieFile'][
                                            'languages']:
                                        if isinstance(item, dict):
                                            if 'name' in item:
                                                audio_language = item['name']
                                                break

                            tags = [
                                d['label'] for d in tagsDict
                                if d['id'] in movie['tags']
                            ]

                            # Add movies in radarr to current movies list
                            current_movies_radarr.append(str(movie['tmdbId']))

                            if str(movie['tmdbId']) in current_movies_db_list:
                                movies_to_update.append({
                                    'radarrId':
                                    int(movie["id"]),
                                    'title':
                                    movie["title"],
                                    'path':
                                    movie["path"] + separator +
                                    movie['movieFile']['relativePath'],
                                    'tmdbId':
                                    str(movie["tmdbId"]),
                                    'poster':
                                    poster,
                                    'fanart':
                                    fanart,
                                    'audio_language':
                                    audio_language,
                                    'sceneName':
                                    sceneName,
                                    'monitored':
                                    str(bool(movie['monitored'])),
                                    'year':
                                    str(movie['year']),
                                    'sortTitle':
                                    movie['sortTitle'],
                                    'alternativeTitles':
                                    alternativeTitles,
                                    'format':
                                    format,
                                    'resolution':
                                    resolution,
                                    'video_codec':
                                    videoCodec,
                                    'audio_codec':
                                    audioCodec,
                                    'overview':
                                    overview,
                                    'imdbId':
                                    imdbId,
                                    'movie_file_id':
                                    int(movie['movieFile']['id']),
                                    'tags':
                                    str(tags)
                                })
                            else:
                                movies_to_add.append({
                                    'radarrId':
                                    int(movie["id"]),
                                    'title':
                                    movie["title"],
                                    'path':
                                    movie["path"] + separator +
                                    movie['movieFile']['relativePath'],
                                    'tmdbId':
                                    str(movie["tmdbId"]),
                                    'languages':
                                    movie_default_language,
                                    'subtitles':
                                    '[]',
                                    'hearing_impaired':
                                    movie_default_hi,
                                    'overview':
                                    overview,
                                    'poster':
                                    poster,
                                    'fanart':
                                    fanart,
                                    'audio_language':
                                    audio_language,
                                    'sceneName':
                                    sceneName,
                                    'monitored':
                                    str(bool(movie['monitored'])),
                                    'sortTitle':
                                    movie['sortTitle'],
                                    'year':
                                    str(movie['year']),
                                    'alternativeTitles':
                                    alternativeTitles,
                                    'format':
                                    format,
                                    'resolution':
                                    resolution,
                                    'video_codec':
                                    videoCodec,
                                    'audio_codec':
                                    audioCodec,
                                    'imdbId':
                                    imdbId,
                                    'forced':
                                    movie_default_forced,
                                    'movie_file_id':
                                    int(movie['movieFile']['id']),
                                    'tags':
                                    str(tags)
                                })
                        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, tags 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 tmdbId = ?''',
                    query.values + (updated_movie['tmdbId'], ))
                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_mappings.path_replace_movie(added_movie['path']))

            # Store subtitles for added or modified movies
            for i, altered_movie in enumerate(altered_movies, 1):
                store_subtitles_movie(
                    altered_movie[1],
                    path_mappings.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:
                    data = database.execute(
                        "SELECT * FROM table_movies WHERE radarrId = ?" +
                        get_exclusion_clause('movie'), (altered_movie[2], ),
                        only_one=True)
                    if data:
                        movies_download_subtitles(data['radarrId'])
                    else:
                        logging.debug(
                            "BAZARR skipping download for this movie as it is excluded."
                        )
            else:
                logging.debug(
                    "BAZARR More than 5 movies were added during this sync then we wont search for subtitles."
                )
Exemple #5
0
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.')
Exemple #6
0
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 = TableMovies.select(TableMovies.tmdb_id,
                                                   TableMovies.path,
                                                   TableMovies.radarr_id)

            current_movies_db_list = [x.tmdb_id 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({
                                    'radarr_id':
                                    movie["id"],
                                    'title':
                                    unicode(movie["title"]),
                                    'path':
                                    unicode(
                                        movie["path"] + separator +
                                        movie['movieFile']['relativePath']),
                                    'tmdb_id':
                                    unicode(movie["tmdbId"]),
                                    'poster':
                                    unicode(poster),
                                    'fanart':
                                    unicode(fanart),
                                    'audio_language':
                                    unicode(
                                        profile_id_to_language(
                                            movie['qualityProfileId'],
                                            audio_profiles)),
                                    'scene_name':
                                    sceneName,
                                    'monitored':
                                    unicode(bool(movie['monitored'])),
                                    'year':
                                    unicode(movie['year']),
                                    'sort_title':
                                    unicode(movie['sortTitle']),
                                    'alternative_titles':
                                    unicode(alternativeTitles),
                                    'format':
                                    unicode(format),
                                    'resolution':
                                    unicode(resolution),
                                    'video_codec':
                                    unicode(videoCodec),
                                    'audio_codec':
                                    unicode(audioCodec),
                                    'overview':
                                    unicode(overview),
                                    'imdb_id':
                                    unicode(imdbId),
                                    'movie_file_id':
                                    movie['movieFile']['id']
                                })
                            else:
                                if movie_default_enabled is True:
                                    movies_to_add.append({
                                        'radarr_id':
                                        movie["id"],
                                        'title':
                                        movie["title"],
                                        'path':
                                        movie["path"] + separator +
                                        movie['movieFile']['relativePath'],
                                        'tmdb_id':
                                        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),
                                        'scene_name':
                                        sceneName,
                                        'monitored':
                                        unicode(bool(movie['monitored'])),
                                        'sort_title':
                                        movie['sortTitle'],
                                        'year':
                                        movie['year'],
                                        'alternative_titles':
                                        alternativeTitles,
                                        'format':
                                        format,
                                        'resolution':
                                        resolution,
                                        'video_codec':
                                        videoCodec,
                                        'audio_codec':
                                        audioCodec,
                                        'imdb_id':
                                        imdbId,
                                        'forced':
                                        movie_default_forced,
                                        'movie_file_id':
                                        movie['movieFile']['id']
                                    })
                                else:
                                    movies_to_add.append({
                                        'radarr_id':
                                        movie["id"],
                                        'title':
                                        movie["title"],
                                        'path':
                                        movie["path"] + separator +
                                        movie['movieFile']['relativePath'],
                                        'tmdb_id':
                                        movie["tmdbId"],
                                        'overview':
                                        overview,
                                        'poster':
                                        poster,
                                        'fanart':
                                        fanart,
                                        'audio_language':
                                        profile_id_to_language(
                                            movie['qualityProfileId'],
                                            audio_profiles),
                                        'scene_name':
                                        sceneName,
                                        'monitored':
                                        unicode(bool(movie['monitored'])),
                                        'sort_title':
                                        movie['sortTitle'],
                                        'year':
                                        movie['year'],
                                        'alternative_titles':
                                        alternativeTitles,
                                        'format':
                                        format,
                                        'resolution':
                                        resolution,
                                        'video_codec':
                                        videoCodec,
                                        'audio_codec':
                                        audioCodec,
                                        'imdb_id':
                                        imdbId,
                                        'movie_file_id':
                                        movie['movieFile']['id']
                                    })
                        else:
                            logging.error(
                                'BAZARR Radarr returned a movie without a file path: '
                                + movie["path"] + separator +
                                movie['movieFile']['relativePath'])

            # Update or insert movies in DB
            movies_in_db_list = []
            movies_in_db = TableMovies.select(
                TableMovies.radarr_id, TableMovies.title, TableMovies.path,
                TableMovies.tmdb_id, TableMovies.overview, TableMovies.poster,
                TableMovies.fanart, TableMovies.audio_language,
                TableMovies.scene_name, TableMovies.monitored,
                TableMovies.sort_title, TableMovies.year,
                TableMovies.alternative_titles, TableMovies.format,
                TableMovies.resolution, TableMovies.video_codec,
                TableMovies.audio_codec, TableMovies.imdb_id,
                TableMovies.movie_file_id).dicts()

            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:
                TableMovies.update(updated_movie).where(
                    TableMovies.radarr_id ==
                    updated_movie['radarr_id']).execute()
                altered_movies.append([
                    updated_movie['tmdb_id'], updated_movie['path'],
                    updated_movie['radarr_id']
                ])

            # Insert new movies in DB
            for added_movie in movies_to_add:
                TableMovies.insert(added_movie).on_conflict_ignore().execute()
                altered_movies.append([
                    added_movie['tmdb_id'], added_movie['path'],
                    added_movie['radarr_id']
                ])

            # Remove old movies from DB
            removed_movies = list(
                set(current_movies_db_list) - set(current_movies_radarr))

            for removed_movie in removed_movies:
                TableMovies.delete().where(
                    TableMovies.tmdb_id == removed_movie).execute()

            # 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]))
                list_missing_subtitles_movies(altered_movie[2])

            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:
                    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."
                )
Exemple #7
0
def update_one_movie(movie_id, action):
    logging.debug('BAZARR syncing this specific movie from Radarr: {}'.format(movie_id))

    # Check if there's a row in database for this movie ID
    try:
        existing_movie = TableMovies.select(TableMovies.path)\
            .where(TableMovies.radarrId == movie_id)\
            .dicts()\
            .get()
    except DoesNotExist:
        existing_movie = None

    # Remove movie from DB
    if action == 'deleted':
        if existing_movie:
            TableMovies.delete().where(TableMovies.radarrId == movie_id).execute()
            event_stream(type='movie', action='delete', payload=int(movie_id))
            logging.debug('BAZARR deleted this movie from the database:{}'.format(path_mappings.path_replace_movie(
                existing_movie['path'])))
        return

    movie_default_enabled = settings.general.getboolean('movie_default_enabled')

    if movie_default_enabled is True:
        movie_default_profile = settings.general.movie_default_profile
        if movie_default_profile == '':
            movie_default_profile = None
    else:
        movie_default_profile = None

    audio_profiles = get_profile_list()
    tagsDict = get_tags()

    try:
        # Get movie data from radarr api
        movie = None
        movie_data = get_movies_from_radarr_api(url=url_radarr(), apikey_radarr=settings.radarr.apikey,
                                                radarr_id=movie_id)
        if not movie_data:
            return
        else:
            if action == 'updated' and existing_movie:
                movie = movieParser(movie_data, action='update', tags_dict=tagsDict, 
                                    movie_default_profile=movie_default_profile, audio_profiles=audio_profiles)
            elif action == 'updated' and not existing_movie:
                movie = movieParser(movie_data, action='insert', tags_dict=tagsDict, 
                                    movie_default_profile=movie_default_profile, audio_profiles=audio_profiles)
    except Exception:
        logging.debug('BAZARR cannot get movie returned by SignalR feed from Radarr API.')
        return

    # Drop useless events
    if not movie and not existing_movie:
        return

    # Remove movie from DB
    if not movie and existing_movie:
        TableMovies.delete().where(TableMovies.radarrId == movie_id).execute()
        event_stream(type='movie', action='delete', payload=int(movie_id))
        logging.debug('BAZARR deleted this movie from the database:{}'.format(path_mappings.path_replace_movie(
            existing_movie['path'])))
        return

    # Update existing movie in DB
    elif movie and existing_movie:
        TableMovies.update(movie).where(TableMovies.radarrId == movie['radarrId']).execute()
        event_stream(type='movie', action='update', payload=int(movie_id))
        logging.debug('BAZARR updated this movie into the database:{}'.format(path_mappings.path_replace_movie(
            movie['path'])))

    # Insert new movie in DB
    elif movie and not existing_movie:
        TableMovies.insert(movie).on_conflict(action='IGNORE').execute()
        event_stream(type='movie', action='update', payload=int(movie_id))
        logging.debug('BAZARR inserted this movie into the database:{}'.format(path_mappings.path_replace_movie(
            movie['path'])))

    # Storing existing subtitles
    logging.debug('BAZARR storing subtitles for this movie: {}'.format(path_mappings.path_replace_movie(
            movie['path'])))
    store_subtitles_movie(movie['path'], path_mappings.path_replace_movie(movie['path']))

    # Downloading missing subtitles
    logging.debug('BAZARR downloading missing subtitles for this movie: {}'.format(path_mappings.path_replace_movie(
        movie['path'])))
    movies_download_subtitles(movie_id)