How to use the flexget.plugin.PluginError function in FlexGet

To help you get started, we’ve selected a few FlexGet examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Flexget / Flexget / flexget / plugins / metainfo / imdb_lookup.py View on Github external
# search and store to cache
        if 'title' in entry:
            log.verbose('Parsing imdb for `%s`' % entry['title'])
        else:
            log.verbose('Parsing imdb for `%s`' % entry['imdb_id'])
        try:
            movie = self._parse_new_movie(entry['imdb_url'], session)
        except UnicodeDecodeError:
            log.error('Unable to determine encoding for %s. Installing chardet library may help.' %
                      entry['imdb_url'])
            # store cache so this will not be tried again
            movie = Movie()
            movie.url = entry['imdb_url']
            session.add(movie)
            session.commit()
            raise plugin.PluginError('UnicodeDecodeError')
        except ValueError as e:
            # TODO: might be a little too broad catch, what was this for anyway? ;P
            if manager.options.debug:
                log.exception(e)
            raise plugin.PluginError('Invalid parameter: %s' % entry['imdb_url'], log)

        for att in ['title', 'score', 'votes', 'meta_score', 'year', 'genres', 'languages', 'actors', 'directors', 'writers',
                    'mpaa_rating']:
            log.trace('movie.%s: %s' % (att, getattr(movie, att)))

        # Update the entry fields
        entry.update_using_map(self.field_map, movie)
github Flexget / Flexget / flexget / components / sites / sites / torrentz.py View on Github external
for domain in ['eu', 'is']:
                # urllib.quote will crash if the unicode string has non ascii characters, so encode in utf-8 beforehand
                url = 'http://torrentz2.%s/%s?f=%s' % (domain, feed, quote(query.encode('utf-8')))
                log.debug('requesting: %s' % url)
                try:
                    r = task.requests.get(url)
                    break
                except requests.ConnectionError as err:
                    # The different domains all resolve to the same ip, so only try more if it was a dns error
                    log.warning('torrentz.%s connection failed. Error: %s' % (domain, err))
                    continue
                except requests.RequestException as err:
                    raise plugin.PluginError('Error getting torrentz search results: %s' % err)

            else:
                raise plugin.PluginError('Error getting torrentz search results')

            if not r.content.strip():
                raise plugin.PluginError(
                    'No data from %s. Maybe torrentz is blocking the FlexGet User-Agent' % url
                )

            rss = feedparser.parse(r.content)

            if rss.get('bozo_exception'):
                raise plugin.PluginError('Got bozo_exception (bad rss feed)')

            for item in rss.entries:
                m = re.search(
                    r'Size: ([\d]+) Mb Seeds: ([,\d]+) Peers: ([,\d]+) Hash: ([a-f0-9]+)',
                    item.description,
                    re.IGNORECASE,
github Flexget / Flexget / flexget / components / trakt / db.py View on Github external
end_time = time.time() + expires_in
        console('Waiting...', end='')
        # stop polling after expires_in seconds
        while time.time() < end_time:
            time.sleep(interval)
            polling_request = requests.post(
                get_api_url('oauth/device/token'), data=data, raise_status=False
            )
            if polling_request.status_code == 200:  # success
                return polling_request.json()
            elif polling_request.status_code == 400:  # pending -- waiting for user
                console('...', end='')
            elif polling_request.status_code == 404:  # not found -- invalid device_code
                raise plugin.PluginError('Invalid device code. Open an issue on Github.')
            elif polling_request.status_code == 409:  # already used -- user already approved
                raise plugin.PluginError('User code has already been approved.')
            elif polling_request.status_code == 410:  # expired -- restart process
                break
            elif polling_request.status_code == 418:  # denied -- user denied code
                raise plugin.PluginError('User code has been denied.')
            elif polling_request.status_code == 429:  # polling too fast
                logger.warning('Polling too quickly. Upping the interval. No action required.')
                interval += 1
        raise plugin.PluginError('User code has expired. Please try again.')
    except requests.RequestException as e:
        raise plugin.PluginError('Device authorization with Trakt.tv failed: {0}'.format(e))
github Flexget / Flexget / flexget / components / trakt / trakt_list.py View on Github external
def get_list_endpoint(self, remove=False, submit=False):
        if (
            not submit
            and self.config['list'] == 'collection'
            and self.config['type'] == 'episodes'
        ):
            # API restriction as they don't have an endpoint for collected episodes yet
            if self.config['list'] == 'collection':
                raise plugin.PluginError('`type` cannot be `episodes` for collection list.')
            if self.config.get('account'):
                return ('sync', 'history', 'episodes')
            else:
                raise plugin.PluginError(
                    'A trakt `account` needs to be configured to get the episode history.'
                )

        if self.config['list'] in ['collection', 'watchlist', 'watched', 'ratings']:
            if self.config.get('account'):
                endpoint = (
                    'sync',
                    'history' if self.config['list'] == 'watched' else self.config['list'],
                )
                if not submit:
                    endpoint += (self.config['type'],)
            else:
                endpoint = (
                    'users',
                    self.config['username'],
                    self.config['list'],
github Flexget / Flexget / flexget / components / notify / notifiers / telegram.py View on Github external
def _get_chat_ids_n_update_db(self, session):
        """
        :type session: sqlalchemy.orm.Session
        :rtype: list[ChatIdEntry]

        """
        usernames = self._usernames[:]
        fullnames = self._fullnames[:]
        groups = self._groups[:]
        chat_ids, has_new_chat_ids = self._get_chat_ids(session, usernames, fullnames, groups)
        self.log.debug('chat_ids=%s', chat_ids)

        if not chat_ids:
            raise PluginError(
                'no chat id found, try manually sending the bot any message to initialize the chat'
            )
        else:
            if usernames:
                self.log.warning('no chat id found for usernames: %s', usernames)
            if fullnames:
                self.log.warning('no chat id found for fullnames: %s', fullnames)
            if groups:
                self.log.warning('no chat id found for groups: %s', groups)
            if has_new_chat_ids:
                self._update_db(session, chat_ids)

        return chat_ids
github Flexget / Flexget / flexget / plugins / input / parameterize.py View on Github external
def _parameterize(element, entry):
    if isinstance(element, dict):
        return dict((k, _parameterize(v, entry)) for k, v in element.items())
    if isinstance(element, list):
        return [_parameterize(v, entry) for v in element]
    if isinstance(element, str) and ('{{' in element or '{%' in element):
        try:
            return render_from_entry(element, entry, native=True)
        except (RenderError, TypeError) as e:
            raise plugin.PluginError('Error parameterizing `%s`: %s' % (element, e), logger=log)
    return element
github Flexget / Flexget / flexget / components / sites / sites / filelist.py View on Github external
log.debug('Attempting to retrieve FileList.ro cookie')
            response = requests.post(
                url,
                data={
                    'username': username,
                    'password': password,
                    'login': 'Log in',
                    'unlock': '1',
                },
                timeout=30,
            )
        except RequestException as e:
            raise plugin.PluginError('FileList.ro login failed: %s' % e)

        if 'https://filelist.ro/my.php' != response.url:
            raise plugin.PluginError(
                'FileList.ro login failed: Your username or password was incorrect.'
            )

        with Session() as session:
            expires = None
            for c in requests.cookies:
                if c.name == 'pass':
                    expires = c.expires
            if expires:
                expires = datetime.datetime.fromtimestamp(expires)
            log.debug('Saving or updating FileList.ro cookie in db')
            cookie = FileListCookie(
                username=username.lower(), cookie=dict(requests.cookies), expires=expires
            )
            session.merge(cookie)
            return cookie.cookie
github Flexget / Flexget / flexget / components / series / configure_series.py View on Github external
def on_task_prepare(self, task, config):

        series = {}
        for input_name, input_config in config.get('from', {}).items():
            input_plugin = plugin.get_plugin_by_name(input_name)
            method = input_plugin.phase_handlers['input']
            try:
                result = method(task, input_config)
            except PluginError as e:
                log.warning('Error during input plugin %s: %s' % (input_name, e))
                continue
            if not result:
                log.warning('Input %s did not return anything' % input_name)
                continue

            for entry in result:
                s = series.setdefault(entry['title'], {})
                if entry.get('tvdb_id'):
                    s['set'] = {'tvdb_id': entry['tvdb_id']}

                # Allow configure_series to set anything available to series
                for key, schema in self.settings_schema['properties'].items():
                    if 'configure_series_' + key in entry:
                        errors = process_config(
                            entry['configure_series_' + key], schema, set_defaults=False
github Flexget / Flexget / flexget / plugins / clients / deluge.py View on Github external
def on_connect_fail(self, result):
        """Pauses the reactor, returns PluginError. Gets called when connection to deluge daemon fails."""
        log.debug('Connect to deluge daemon failed, result: %s' % result)
        reactor.callLater(0, reactor.pause, plugin.PluginError('Could not connect to deluge daemon', log))
github Flexget / Flexget / flexget / plugins / services / myepisodes.py View on Github external
myepisodes_id = None
        baseurl = 'http://www.myepisodes.com/search/'
        search_value = self._generate_search_value(entry)

        payload = {'tvshow': search_value, 'action': 'Search'}

        try:
            response = self.http_session.post(baseurl, data=payload)
            regex = r'"/epsbyshow\/([0-9]*)\/.*">' + search_value + ''
            match_obj = re.search(regex, response.text, re.MULTILINE | re.IGNORECASE)
            if match_obj:
                myepisodes_id = match_obj.group(1)
                self._save_id(search_value, myepisodes_id)

        except requests.RequestException as e:
            raise plugin.PluginError('Error searching for myepisodes id: %s' % e)

        return myepisodes_id