Ejemplo n.º 1
0
 def test(self, notify_lib):
     if notifiers.test_notifier(notify_lib):
         send_websocket_notification('Test notification (%s) sent.' % notify_lib)
     else:
         send_websocket_notification('Test notification (%s) failed! Please check the log file!' % notify_lib,
                                     type='error')
     return {}
Ejemplo n.º 2
0
def post_process_no_subtitle(wanted_item_index):
    log.info('Post processing without subtitle')

    # Get wanted queue lock
    if not get_wanted_queue_lock():
        return False

    # Get wanted item
    wanted_item = autosubliminal.WANTEDQUEUE[int(wanted_item_index)]

    # Post process only (no need to check for individual or not because we are forcing post processing)
    processed = PostProcessor(wanted_item).run()

    # Remove wanted item if processed
    if processed:
        autosubliminal.WANTEDQUEUE.pop(int(wanted_item_index))
        log.debug('Removed item from the wanted queue at index %s', int(wanted_item_index))
        WantedItemsDb().delete_wanted_item(wanted_item)
        log.debug('Removed %s from wanted_items database', wanted_item.videopath)
    else:
        send_websocket_notification('Unable to handle post processing! Please check the log file!', type='error')

    # Release wanted queue lock
    release_wanted_queue_lock()

    return processed
Ejemplo n.º 3
0
    def run(self, force_run):
        paths = autosubliminal.LIBRARYPATHS
        log.info('Starting round of library scanning at %r', paths)

        # Show info message (only when run was forced manually)
        if force_run:
            send_websocket_notification('Scanning library...')

        # Check if a path exists to scan
        if not one_path_exists(paths):
            log.error('None of the configured library paths (%r) exists, aborting...', paths)
            return

        # Clear failed shows/movies before starting a full scan
        FailedShowsDb().flush_failed_shows()
        FailedMoviesDb().flush_failed_movies()

        # Walk through paths and store info in db
        path_scanner = LibraryPathScanner()
        for path in paths:
            try:
                path_scanner.scan_path(path)
            except Exception:
                log.exception('Could not scan the path (%s), skipping it', path)

        # Send library page reload event
        send_websocket_event(PAGE_RELOAD, data={'name': 'library'})

        log.info('Finished round of library scanning')
Ejemplo n.º 4
0
    def put(self, imdb_id):
        """Save the settings for a movie."""
        input_json = cherrypy.request.json

        if all(k in input_json for k in ('wanted_languages', 'refine',
                                         'hearing_impaired', 'utf8_encoding')):
            wanted_languages = input_json['wanted_languages']
            refine = get_boolean(input_json['refine'])
            hearing_impaired = get_boolean(input_json['hearing_impaired'])
            utf8_encoding = get_boolean(input_json['utf8_encoding'])

            # Update settings
            db = MovieSettingsDb()
            movie_settings = db.get_movie_settings(imdb_id)
            movie_settings.wanted_languages = wanted_languages
            movie_settings.refine = refine
            movie_settings.hearing_impaired = hearing_impaired
            movie_settings.utf8_encoding = utf8_encoding
            db.update_movie_settings(movie_settings)

            # Delete wanted items for the movie so the new settings will be used in the next disk scan
            WantedItemsDb().delete_wanted_items_for_movie(imdb_id)

            # Send notification
            send_websocket_notification(
                'Settings will be applied on next disk scan.')

            return self._no_content()

        return self._bad_request('Missing data')
Ejemplo n.º 5
0
    def run(self):
        """
        Save the subtitle with further handling
        """

        log.info('Running sub downloader')

        # Save the subtitle
        if self.save():
            name = display_item_name(self._download_item)

            # Mark as downloaded
            self.mark_downloaded()

            # Post process
            processed = self.post_process()
            if not processed:
                send_websocket_notification(
                    'Unable to handle post processing for \'%s\'! Please check the log file!'
                    % name,
                    type='error')

            # Show success message
            language = self._download_item.downlang
            name = display_item_name(self._download_item)
            provider = self._download_item.provider
            send_websocket_notification(
                'Downloaded \'%s\' subtitle for \'%s\' from \'%s\'.' %
                (language, name, provider),
                type='success')
Ejemplo n.º 6
0
    def run(self):
        """
        Save the subtitle with further handling
        """

        log.info('Running sub downloader')

        # Save the subtitle
        if self.save():
            name = display_item_name(self._download_item)

            # Mark as downloaded
            self.mark_downloaded()

            # Post process
            processed = self.post_process()
            if not processed:
                send_websocket_notification(
                    'Unable to handle post processing for \'%s\'! Please check the log file!' % name, type='error')

            # Show success message
            language = self._download_item.downlang
            name = display_item_name(self._download_item)
            provider = self._download_item.provider
            send_websocket_notification(
                'Downloaded \'%s\' subtitle for \'%s\' from \'%s\'.' % (language, name, provider), type='success')
Ejemplo n.º 7
0
    def put(self, imdb_id):
        """Save the settings for a movie."""
        input_json = cherrypy.request.json

        if all(k in input_json for k in ('wanted_languages', 'refine', 'hearing_impaired', 'utf8_encoding')):
            wanted_languages = input_json['wanted_languages']
            refine = get_boolean(input_json['refine'])
            hearing_impaired = get_boolean(input_json['hearing_impaired'])
            utf8_encoding = get_boolean(input_json['utf8_encoding'])

            # Update settings
            db = MovieSettingsDb()
            movie_settings = db.get_movie_settings(imdb_id)
            movie_settings.wanted_languages = wanted_languages
            movie_settings.refine = refine
            movie_settings.hearing_impaired = hearing_impaired
            movie_settings.utf8_encoding = utf8_encoding
            db.update_movie_settings(movie_settings)

            # Delete wanted items for the movie so the new settings will be used in the next disk scan
            WantedItemsDb().delete_wanted_items_for_movie(imdb_id)

            # Send notification
            send_websocket_notification('Settings will be applied on next disk scan.')

            return self._no_content()

        return self._bad_request('Missing data')
Ejemplo n.º 8
0
    def flush_library(self):
        if not autosubliminal.SCANLIBRARY.running:
            ShowDetailsDb().flush_shows(episodes=True, subtitles=True)
            MovieDetailsDb().flush_movies(subtitles=True)
            send_websocket_notification('Flushed library database.')
        else:
            send_websocket_notification('Cannot flush library database when library scanner is running!',
                                        type='notice')

        redirect('/library')
Ejemplo n.º 9
0
 def test(self, notify_lib):
     if notifiers.test_notifier(notify_lib):
         send_websocket_notification('Test notification (%s) sent.' %
                                     notify_lib)
     else:
         send_websocket_notification(
             'Test notification (%s) failed! Please check the log file!'
             % notify_lib,
             type='error')
     return {}
Ejemplo n.º 10
0
 def update_version(self):
     if self.update_allowed:
         try:
             # Do a git clean before and after the update to remove all untracked files
             self.clean()
             self.repo.remote(name='origin').pull()
             self.clean()
             log.info('Updated to the latest version')
             send_websocket_notification('Updated to the latest version.')
         except Exception:
             log.exception('Could not update version')
Ejemplo n.º 11
0
 def update_version(self):
     if self.update_allowed:
         try:
             # Do a git clean before and after the update to remove all untracked files
             self.clean()
             self.repo.remote(name='origin').pull()
             self.clean()
             log.info('Updated to the latest version')
             send_websocket_notification('Updated to the latest version.')
         except Exception:
             log.exception('Could not update version')
Ejemplo n.º 12
0
 def flush_wanted_items(self):
     if get_wanted_queue_lock():
         # Flush db and wanted queue
         WantedItemsDb().flush_wanted_items()
         autosubliminal.WANTEDQUEUE = []
         release_wanted_queue_lock()
         send_websocket_notification(
             'Flushed wanted items database. Please launch \'Scan Disk\' from the \'System\' menu.')
     else:
         send_websocket_notification('Cannot flush wanted items database when wanted queue is in use!',
                                     type='notice')
     redirect('/home')
Ejemplo n.º 13
0
def test_send_websocket_notification(monkeypatch):
    monkeypatch.setattr('autosubliminal.WEBSOCKETMESSAGEQUEUE', [])
    message = {
        'type': 'NOTIFICATION',
        'notification': {
            'message': 'test',
            'type': 'info',
            'sticky': False
        }
    }
    send_websocket_notification('test')
    assert len(autosubliminal.WEBSOCKETMESSAGEQUEUE) == 1
    assert autosubliminal.WEBSOCKETMESSAGEQUEUE.pop(0) == message
Ejemplo n.º 14
0
    def save_and_restart_if_needed(section=None):
        # Save to the configfile
        restart = config.write_config(section)

        # Check if restart is needed
        if restart:
            return {'restart': True}

        else:
            # For some reason the config needs to be read again, otherwise all pages get an error
            config.read_config()
            send_websocket_notification('Config saved.')
            return {}
Ejemplo n.º 15
0
 def delete_video(self, wanted_item_index, confirmed=False, cleanup=False):
     if not confirmed:
         wanted_item = autosubliminal.WANTEDQUEUE[int(wanted_item_index)]
         video = wanted_item.videopath
         return PageTemplate('/home/home-deletevideo.mako').render(wanted_item_index=wanted_item_index, video=video)
     else:
         # Delete video
         deleted = subchecker.delete_video(wanted_item_index, cleanup)
         if deleted:
             send_websocket_notification('Video deleted from filesystem.')
         else:
             send_websocket_notification('Video could not be deleted! Please check the log file!', type='error')
         redirect('/home')
Ejemplo n.º 16
0
    def save_and_restart_if_needed(section=None):
        # Save to the configfile
        restart = config.write_config(section)

        # Check if restart is needed
        if restart:
            return {'restart': True}

        else:
            # For some reason the config needs to be read again, otherwise all pages get an error
            config.read_config()
            send_websocket_notification('Config saved.')
            return {}
Ejemplo n.º 17
0
 def delete_video(self, wanted_item_index, confirmed=False, cleanup=False):
     if not confirmed:
         wanted_item = autosubliminal.WANTEDQUEUE[int(wanted_item_index)]
         video = wanted_item.videopath
         return PageTemplate('/home/home-deletevideo.mako').render(
             wanted_item_index=wanted_item_index, video=video)
     else:
         # Delete video
         deleted = subchecker.delete_video(wanted_item_index, cleanup)
         if deleted:
             send_websocket_notification('Video deleted from filesystem.')
         else:
             send_websocket_notification(
                 'Video could not be deleted! Please check the log file!',
                 type='error')
         redirect('/home')
Ejemplo n.º 18
0
    def run(self, force_run):
        paths = autosubliminal.VIDEOPATHS
        log.info('Starting round of local disk checking at %r', paths)

        # Show info message (only when run was forced manually)
        if force_run:
            send_websocket_notification('Scanning disk...')

        # Check if a path exists to scan
        if not one_path_exists(paths):
            log.error(
                'None of the configured video paths (%r) exists, aborting...',
                paths)
            return

        # Walk through paths to search for wanted items
        new_wanted_items = []
        old_wanted_items = self.wanted_db.get_wanted_items()
        for path in paths:
            try:
                new_wanted_items.extend(self._scan_path(path))
            except Exception:
                log.exception(
                    'Could not scan the video path (%s), skipping it', path)

        # Cleanup wanted items that have been removed from disk manually but are still stored in the db
        log.debug(
            'Checking for non existing wanted items in wanted_items database')
        for item in old_wanted_items:
            if item not in new_wanted_items:
                self.wanted_db.delete_wanted_item(item)
                log.debug('Deleted non existing wanted item: %s',
                          item.videopath)

        # Populate WANTEDQUEUE with all items from wanted_items database
        log.info('Listing videos with missing subtitles:')
        autosubliminal.WANTEDQUEUE = []
        for item in self.wanted_db.get_wanted_items():
            log.info('%s %s', item.videopath, item.languages)
            autosubliminal.WANTEDQUEUE.append(item)

        # Send home page reload event
        send_websocket_event(PAGE_RELOAD, data={'name': 'home'})

        log.info('Finished round of local disk checking')
Ejemplo n.º 19
0
    def update_wanted_item(self, wanted_item_index, **kwargs):
        if get_wanted_queue_lock():
            # Get wanted item and update all keys that are passed
            wanted_item = autosubliminal.WANTEDQUEUE[int(wanted_item_index)]
            for key in kwargs:
                wanted_item.set_attr(key, kwargs[key])

            # Release wanted queue lock
            release_wanted_queue_lock()

            # Only return updatable fields
            # These values will be shown in the view through jquery, so apply the display_value() on it!
            return {
                'displaytitle':
                display_item_title(wanted_item),
                'title':
                display_value(wanted_item.title),
                'year':
                display_value(wanted_item.year),
                'season':
                display_value(wanted_item.season),
                'episode':
                display_value(wanted_item.episode),
                'source':
                display_value(wanted_item.source,
                              default_value='N/A',
                              uppercase=True),
                'quality':
                display_value(wanted_item.quality,
                              default_value='N/A',
                              uppercase=True),
                'codec':
                display_value(wanted_item.codec,
                              default_value='N/A',
                              uppercase=True),
                'releasegrp':
                display_value(wanted_item.releasegrp,
                              default_value='N/A',
                              uppercase=True)
            }

        # Show notification if wanted queue is in use
        send_websocket_notification(
            'Cannot update wanted item when wanted queue is in use!',
            type='notice')
Ejemplo n.º 20
0
 def skip_movie(self, wanted_item_index, title, year):
     if not wanted_item_index:
         raise cherrypy.HTTPError(400, 'No wanted_item index supplied')
     if not title:
         raise cherrypy.HTTPError(400, 'No title supplied')
     movie = title
     if year:
         movie += ' (' + year + ')'
     # Check if already skipped
     movie_sanitized = sanitize(movie)
     for x in autosubliminal.SKIPMOVIE:
         if movie_sanitized == sanitize(x):
             send_websocket_notification('Already skipped movie %s.' %
                                         movie)
             redirect('/home')
     # Skip movie
     if subchecker.skip_movie(wanted_item_index):
         config.write_config_property('skipmovie', movie, '00')
         config.apply_skipmovie()
         send_websocket_notification('Skipped movie %s.' % movie)
     else:
         send_websocket_notification(
             'Could not skip movie! Please check the log file!',
             type='error')
     redirect('/home')
Ejemplo n.º 21
0
    def run(self, force_run):
        paths = autosubliminal.VIDEOPATHS
        log.info('Starting round of local disk checking at %r', paths)

        # Show info message (only when run was forced manually)
        if force_run:
            send_websocket_notification('Scanning disk...')

        # Check if a path exists to scan
        if not one_path_exists(paths):
            log.error('None of the configured video paths (%r) exists, aborting...', paths)
            return

        # Walk through paths to search for wanted items
        new_wanted_items = []
        old_wanted_items = self.wanted_db.get_wanted_items()
        for path in paths:
            try:
                new_wanted_items.extend(self._scan_path(path))
            except Exception:
                log.exception('Could not scan the video path (%s), skipping it', path)

        # Cleanup wanted items that have been removed from disk manually but are still stored in the db
        log.debug('Checking for non existing wanted items in wanted_items database')
        for item in old_wanted_items:
            if item not in new_wanted_items:
                self.wanted_db.delete_wanted_item(item)
                log.debug('Deleted non existing wanted item: %s', item.videopath)

        # Populate WANTEDQUEUE with all items from wanted_items database
        log.info('Listing videos with missing subtitles:')
        autosubliminal.WANTEDQUEUE = []
        for item in self.wanted_db.get_wanted_items():
            log.info('%s %s', item.videopath, item.languages)
            autosubliminal.WANTEDQUEUE.append(item)

        # Send home page reload event
        send_websocket_event(PAGE_RELOAD, data={'name': 'home'})

        log.info('Finished round of local disk checking')
Ejemplo n.º 22
0
    def reset_wanted_item(self, wanted_item_index, **kwargs):
        if get_wanted_queue_lock():
            # Get wanted item and reset values
            wanted_item = autosubliminal.WANTEDQUEUE[int(wanted_item_index)]
            wanted_item_db = WantedItemsDb().get_wanted_item(
                wanted_item.videopath)
            wanted_item_db.copy_to(wanted_item)

            # Release wanted queue lock
            release_wanted_queue_lock()

            # Only return updatable fields
            # These values represent the original values, so apply default display_value() on it!
            return {
                'displaytitle':
                display_item_title(wanted_item),
                'title':
                display_value(wanted_item.title),
                'year':
                display_value(wanted_item.year),
                'season':
                display_value(wanted_item.season),
                'episode':
                display_value(wanted_item.episode),
                'source':
                display_value(wanted_item.source, default_value='N/A'),
                'quality':
                display_value(wanted_item.quality, default_value='N/A'),
                'codec':
                display_value(wanted_item.codec, default_value='N/A'),
                'releasegrp':
                display_value(wanted_item.releasegrp, default_value='N/A')
            }

        # Show notification if wanted queue is in use
        send_websocket_notification(
            'Cannot reset wanted item when wanted queue is in use!',
            type='notice')
Ejemplo n.º 23
0
    def check_version(self, force_run=False):
        # Reset update_allowed flag
        self.update_allowed = False

        # Local git version
        log.debug('Local branch: %s', self.current_git_branch)
        log.debug('Local commit: %s', self.current_git_commit)
        if self.repo.is_dirty():
            log.warning('Local branch is dirty')

        # Remote git version
        try:
            remote_url = self.repo.remote(name='origin').url
            remote_fetch_info = self.repo.remote().fetch(refspec=self.current_git_branch)[0]
            remote_commit = remote_fetch_info.commit
            log.debug('Remote url: %s', remote_url)
            log.debug('Remote commit: %s', remote_commit)
        except Exception:
            log.exception('Could not get remote git version')
            return False

        # Get number of commits ahead and behind (option --count not supported git < 1.7.2)
        try:
            ahead, behind = self.repo.git.execute('git rev-list --count --left-right HEAD...@{upstream}').split('\t')
            self.num_commits_ahead = int(ahead)
            self.num_commits_behind = int(behind)
        except Exception:
            # Count it ourselves when option --count is not supported
            try:
                output = self.repo.git.execute('git rev-list --left-right HEAD...@{upstream}')
                self.num_commits_ahead = int(output.count('<'))
                self.num_commits_behind = int(output.count('>'))
            except Exception:
                log.exception('Could not get the difference in commits between local and remote branch')
                return False
        log.debug('Number of commits ahead: %s', self.num_commits_ahead)
        log.debug('Number of commits behind: %s', self.num_commits_behind)

        if self.num_commits_ahead > 0:
            log.info('Unknown version found')
            send_websocket_notification(
                'Unknown version found! Check <a href=' + autosubliminal.GITHUBURL +
                '/releases>Github</a> and reinstall!', type='error', sticky=True)
        elif self.num_commits_behind > 0:
            log.info('New version found')
            send_websocket_notification(
                'New version found. <a href=' + autosubliminal.WEBROOT + '/system/updateVersion>Update</a>!',
                type='notice', sticky=True)
            self.update_allowed = True
        else:
            log.info('Version up to date')
            # Show info message (only when run was forced manually)
            if force_run:
                send_websocket_notification('You are running the latest version.')

        return True
Ejemplo n.º 24
0
    def skip_show(self, wanted_item_index, title, season=None):
        if not season:
            return PageTemplate('/home/home-skipshow.mako').render(
                wanted_item_index=wanted_item_index, title=title)
        else:
            if not wanted_item_index:
                raise cherrypy.HTTPError(400, 'No wanted_item index supplied')
            if not title:
                raise cherrypy.HTTPError(400, 'No show supplied')
            # Check if season is a number to be sure
            if not season == '00':
                season = text_type(int(season))
            config_season = season
            # Check if already skipped
            title_sanitized = sanitize(title)
            for x in autosubliminal.SKIPSHOW:
                if title_sanitized == sanitize(x):
                    for s in autosubliminal.SKIPSHOW[x].split(','):
                        if s == season or s == '00':
                            send_websocket_notification(
                                'Already skipped show %s season %s.' %
                                (title, season))
                            redirect('/home')
                    # Not skipped yet, skip all or append season the seasons to skip
                    if season == '00':
                        config_season = '00'
                    else:
                        seasons = autosubliminal.SKIPSHOW[x].split(',')
                        seasons.append(season)
                        config_season = ','.join(sorted(seasons))
            # Skip show
            if subchecker.skip_show(wanted_item_index, season):
                config.write_config_property('skipshow', title, config_season)
                config.apply_skipshow()
                if season == '00':
                    send_websocket_notification(
                        'Skipped show %s all seasons.' % title)
                else:
                    send_websocket_notification('Skipped show %s season %s.' %
                                                (title, season))
            else:
                send_websocket_notification(
                    'Could not skip show! Please check the log file!',
                    type='error')

            redirect('/home')
Ejemplo n.º 25
0
    def reset_wanted_item(self, wanted_item_index, **kwargs):
        if get_wanted_queue_lock():
            # Get wanted item and reset values
            wanted_item = autosubliminal.WANTEDQUEUE[int(wanted_item_index)]
            wanted_item_db = WantedItemsDb().get_wanted_item(wanted_item.videopath)
            wanted_item_db.copy_to(wanted_item)

            # Release wanted queue lock
            release_wanted_queue_lock()

            # Only return updatable fields
            # These values represent the original values, so apply default display_value() on it!
            return {'displaytitle': display_item_title(wanted_item),
                    'title': display_value(wanted_item.title),
                    'year': display_value(wanted_item.year),
                    'season': display_value(wanted_item.season),
                    'episode': display_value(wanted_item.episode),
                    'source': display_value(wanted_item.source, default_value='N/A'),
                    'quality': display_value(wanted_item.quality, default_value='N/A'),
                    'codec': display_value(wanted_item.codec, default_value='N/A'),
                    'releasegrp': display_value(wanted_item.releasegrp, default_value='N/A')}

        # Show notification if wanted queue is in use
        send_websocket_notification('Cannot reset wanted item when wanted queue is in use!', type='notice')
Ejemplo n.º 26
0
    def update_wanted_item(self, wanted_item_index, **kwargs):
        if get_wanted_queue_lock():
            # Get wanted item and update all keys that are passed
            wanted_item = autosubliminal.WANTEDQUEUE[int(wanted_item_index)]
            for key in kwargs:
                wanted_item.set_attr(key, kwargs[key])

            # Release wanted queue lock
            release_wanted_queue_lock()

            # Only return updatable fields
            # These values will be shown in the view through jquery, so apply the display_value() on it!
            return {'displaytitle': display_item_title(wanted_item),
                    'title': display_value(wanted_item.title),
                    'year': display_value(wanted_item.year),
                    'season': display_value(wanted_item.season),
                    'episode': display_value(wanted_item.episode),
                    'source': display_value(wanted_item.source, default_value='N/A', uppercase=True),
                    'quality': display_value(wanted_item.quality, default_value='N/A', uppercase=True),
                    'codec': display_value(wanted_item.codec, default_value='N/A', uppercase=True),
                    'releasegrp': display_value(wanted_item.releasegrp, default_value='N/A', uppercase=True)}

        # Show notification if wanted queue is in use
        send_websocket_notification('Cannot update wanted item when wanted queue is in use!', type='notice')
Ejemplo n.º 27
0
    def check_version(self, force_run=False):
        # Reset update_allowed flag
        self.update_allowed = False

        # Local version
        local_version = self.current_strict_version
        log.debug('Local version: %s', local_version)

        # Remote github version
        try:
            response = connect_url(autosubliminal.VERSIONURL)
        except Exception:
            log.exception('Could not get remote version from %s',
                          autosubliminal.VERSIONURL)
            return False
        try:
            match = re.search(VERSION_PATTERN,
                              response.text,
                              flags=re.MULTILINE)
            remote_version = version.StrictVersion(match.group(1))
            log.debug('Remote version: %r', remote_version)
        except Exception:
            log.exception('Could not parse version from %s',
                          autosubliminal.VERSIONURL)
            return False

        # Compare versions
        if local_version > remote_version:
            log.info('Unknown version found')
            send_websocket_notification('Unknown version found! '
                                        'Check <a href=' +
                                        autosubliminal.GITHUBURL +
                                        '/releases>Github</a> and reinstall!',
                                        type='error',
                                        sticky=True)
        elif local_version < remote_version:
            log.info('New version found')
            send_websocket_notification('New version found. '
                                        'Check <a href=' +
                                        autosubliminal.GITHUBURL +
                                        '/releases>Github</a> and update!',
                                        type='notice',
                                        sticky=True)
        else:
            log.info('Version up to date')
            # Show info message (only when run was forced manually)
            if force_run:
                send_websocket_notification(
                    'You are running the latest version.')

        return True
Ejemplo n.º 28
0
    def skip_show(self, wanted_item_index, title, season=None):
        if not season:
            return PageTemplate('/home/home-skipshow.mako').render(wanted_item_index=wanted_item_index, title=title)
        else:
            if not wanted_item_index:
                raise cherrypy.HTTPError(400, 'No wanted_item index supplied')
            if not title:
                raise cherrypy.HTTPError(400, 'No show supplied')
            # Check if season is a number to be sure
            if not season == '00':
                season = text_type(int(season))
            config_season = season
            # Check if already skipped
            title_sanitized = sanitize(title)
            for x in autosubliminal.SKIPSHOW:
                if title_sanitized == sanitize(x):
                    for s in autosubliminal.SKIPSHOW[x].split(','):
                        if s == season or s == '00':
                            send_websocket_notification('Already skipped show %s season %s.' % (title, season))
                            redirect('/home')
                    # Not skipped yet, skip all or append season the seasons to skip
                    if season == '00':
                        config_season = '00'
                    else:
                        seasons = autosubliminal.SKIPSHOW[x].split(',')
                        seasons.append(season)
                        config_season = ','.join(sorted(seasons))
            # Skip show
            if subchecker.skip_show(wanted_item_index, season):
                config.write_config_property('skipshow', title, config_season)
                config.apply_skipshow()
                if season == '00':
                    send_websocket_notification('Skipped show %s all seasons.' % title)
                else:
                    send_websocket_notification('Skipped show %s season %s.' % (title, season))
            else:
                send_websocket_notification('Could not skip show! Please check the log file!', type='error')

            redirect('/home')
Ejemplo n.º 29
0
    def check_version(self, force_run=False):
        # Reset update_allowed flag
        self.update_allowed = False

        # Local version
        local_version = self.current_strict_version
        log.debug('Local version: %s', local_version)

        # Remote github version
        try:
            response = connect_url(autosubliminal.VERSIONURL)
        except Exception:
            log.exception('Could not get remote version from %s', autosubliminal.VERSIONURL)
            return False
        try:
            match = re.search(VERSION_PATTERN, response.text, flags=re.MULTILINE)
            remote_version = version.StrictVersion(match.group(1))
            log.debug('Remote version: %r', remote_version)
        except Exception:
            log.exception('Could not parse version from %s', autosubliminal.VERSIONURL)
            return False

        # Compare versions
        if local_version > remote_version:
            log.info('Unknown version found')
            send_websocket_notification(
                'Unknown version found! '
                'Check <a href=' + autosubliminal.GITHUBURL + '/releases>Github</a> and reinstall!',
                type='error', sticky=True)
        elif local_version < remote_version:
            log.info('New version found')
            send_websocket_notification(
                'New version found. '
                'Check <a href=' + autosubliminal.GITHUBURL + '/releases>Github</a> and update!',
                type='notice', sticky=True)
        else:
            log.info('Version up to date')
            # Show info message (only when run was forced manually)
            if force_run:
                send_websocket_notification('You are running the latest version.')

        return True
Ejemplo n.º 30
0
 def skip_movie(self, wanted_item_index, title, year):
     if not wanted_item_index:
         raise cherrypy.HTTPError(400, 'No wanted_item index supplied')
     if not title:
         raise cherrypy.HTTPError(400, 'No title supplied')
     movie = title
     if year:
         movie += ' (' + year + ')'
     # Check if already skipped
     movie_sanitized = sanitize(movie)
     for x in autosubliminal.SKIPMOVIE:
         if movie_sanitized == sanitize(x):
             send_websocket_notification('Already skipped movie %s.' % movie)
             redirect('/home')
     # Skip movie
     if subchecker.skip_movie(wanted_item_index):
         config.write_config_property('skipmovie', movie, '00')
         config.apply_skipmovie()
         send_websocket_notification('Skipped movie %s.' % movie)
     else:
         send_websocket_notification('Could not skip movie! Please check the log file!', type='error')
     redirect('/home')
Ejemplo n.º 31
0
 def flush_cache(self):
     TvdbIdCacheDb().flush_tvdb_ids()
     ImdbIdCacheDb().flush_imdb_ids()
     send_websocket_notification('Flushed id cache database.')
     redirect('/home')
Ejemplo n.º 32
0
    def run(self, force_run):
        log.info('Starting round of subtitle checking')

        # Wait for internet connection
        wait_for_internet_connection()

        # Show info message (only when run was forced manually)
        if force_run:
            send_websocket_notification('Checking subtitles...')

        to_delete_wanted_queue = []

        # Setup provider pool
        provider_pool = _get_provider_pool()
        if provider_pool:
            log.info('Searching subtitles with providers: %s', ', '.join(provider_pool.providers))

            # Process all items in wanted queue
            db = WantedItemsDb()
            for index, wanted_item in enumerate(autosubliminal.WANTEDQUEUE):
                log.info('Searching subtitles for video: %s', wanted_item.videopath)

                # Check if the search is currently active for the wanted_item
                if not wanted_item.is_search_active:
                    log.info('Search not active in this run for video: %s', wanted_item.videopath)
                    continue

                # Scan wanted_item for video, skip when no video could be determined
                video = _scan_wanted_item_for_video(wanted_item)
                if not video:
                    continue

                # Clear discarded providers for each new wanted_item
                provider_pool.discarded_providers.clear()

                # Check subtitles for each language
                languages = wanted_item.languages
                for lang in languages[:]:
                    # Search the best subtitle with the minimal score
                    try:
                        subtitles, language, single = _search_subtitles(video, lang, True, provider_pool)
                    except Exception:
                        log.exception('Error while searching subtitles for video %r', wanted_item.videopath)
                        continue

                    # Subtitle is found for the video
                    if subtitles:
                        # Handle download
                        download_item = _construct_download_item(wanted_item, subtitles, language, single)
                        SubDownloader(download_item).run()

                        # Remove downloaded language from wanted languages
                        languages.remove(lang)

                        # Update wanted item if there are still wanted languages
                        if len(languages) > 0:
                            db.update_wanted_item(wanted_item)

                        # Mark wanted item as deleted if there are no more wanted languages
                        else:
                            to_delete_wanted_queue.append(index)

            # Cleanup wanted item(s)
            i = len(to_delete_wanted_queue) - 1
            while i >= 0:
                wanted_item_to_delete = autosubliminal.WANTEDQUEUE.pop(to_delete_wanted_queue[i])
                log.debug('Removed item from the wanted queue at index %s', to_delete_wanted_queue[i])
                db.delete_wanted_item(wanted_item_to_delete)
                log.debug('Removed %s from wanted_items database', wanted_item_to_delete.videopath)
                i -= 1

        else:
            log.info('No subliminal providers configured, skipping')

        # Send home page reload event
        send_websocket_event(PAGE_RELOAD, data={'name': 'home'})

        log.info('Finished round of subtitle checking')
Ejemplo n.º 33
0
    def check_version(self, force_run=False):
        # Reset update_allowed flag
        self.update_allowed = False

        # Local git version
        log.debug('Local branch: %s', self.current_git_branch)
        log.debug('Local commit: %s', self.current_git_commit)
        if self.repo.is_dirty():
            log.warning('Local branch is dirty')

        # Remote git version
        try:
            remote_url = self.repo.remote(name='origin').url
            remote_fetch_info = self.repo.remote().fetch(
                refspec=self.current_git_branch)[0]
            remote_commit = remote_fetch_info.commit
            log.debug('Remote url: %s', remote_url)
            log.debug('Remote commit: %s', remote_commit)
        except Exception:
            log.exception('Could not get remote git version')
            return False

        # Get number of commits ahead and behind (option --count not supported git < 1.7.2)
        try:
            ahead, behind = self.repo.git.execute(
                'git rev-list --count --left-right HEAD...@{upstream}').split(
                    '\t')
            self.num_commits_ahead = int(ahead)
            self.num_commits_behind = int(behind)
        except Exception:
            # Count it ourselves when option --count is not supported
            try:
                output = self.repo.git.execute(
                    'git rev-list --left-right HEAD...@{upstream}')
                self.num_commits_ahead = int(output.count('<'))
                self.num_commits_behind = int(output.count('>'))
            except Exception:
                log.exception(
                    'Could not get the difference in commits between local and remote branch'
                )
                return False
        log.debug('Number of commits ahead: %s', self.num_commits_ahead)
        log.debug('Number of commits behind: %s', self.num_commits_behind)

        if self.num_commits_ahead > 0:
            log.info('Unknown version found')
            send_websocket_notification(
                'Unknown version found! Check <a href=' +
                autosubliminal.GITHUBURL +
                '/releases>Github</a> and reinstall!',
                type='error',
                sticky=True)
        elif self.num_commits_behind > 0:
            log.info('New version found')
            send_websocket_notification('New version found. <a href=' +
                                        autosubliminal.WEBROOT +
                                        '/system/updateVersion>Update</a>!',
                                        type='notice',
                                        sticky=True)
            self.update_allowed = True
        else:
            log.info('Version up to date')
            # Show info message (only when run was forced manually)
            if force_run:
                send_websocket_notification(
                    'You are running the latest version.')

        return True
Ejemplo n.º 34
0
 def flush_last_downloads(self):
     LastDownloadsDb().flush_last_downloads()
     send_websocket_notification('Flushed last downloads database.')
     redirect('/home')