Exemplo n.º 1
0
    def submit(self, entries, remove=False):
        """Submits movies or episodes to trakt api."""
        found = {}
        for entry in entries:
            if self.config['type'] in [
                    'auto', 'shows', 'seasons', 'episodes'
            ] and entry.get('series_name') is not None:
                show_name, show_year = split_title_year(entry['series_name'])
                show = {'title': show_name, 'ids': get_entry_ids(entry)}
                if show_year:
                    show['year'] = show_year
                if self.config['type'] in [
                        'auto', 'seasons', 'episodes'
                ] and entry.get('series_season') is not None:
                    season = {'number': entry['series_season']}
                    if self.config['type'] in [
                            'auto', 'episodes'
                    ] and entry.get('series_episode') is not None:
                        season['episodes'] = [{
                            'number': entry['series_episode']
                        }]
                    show['seasons'] = [season]
                if self.config['type'] in ['seasons', 'episodes'
                                           ] and 'seasons' not in show:
                    log.debug('Not submitting `%s`, no season found.' %
                              entry['title'])
                    continue
                if self.config['type'] == 'episodes' and 'episodes' not in show:
                    log.debug('Not submitting `%s`, no episode number found.' %
                              entry['title'])
                    continue
                found.setdefault('shows', []).append(show)
            elif self.config['type'] in ['auto', 'movies']:
                movie = {'ids': get_entry_ids(entry)}
                if not movie['ids']:
                    if entry.get('movie_name') is not None:
                        movie['title'] = entry.get('movie_name') or entry.get(
                            'imdb_name')
                        movie['year'] = entry.get('movie_year') or entry.get(
                            'imdb_year')
                    else:
                        log.debug(
                            'Not submitting `%s`, no movie name or id found.' %
                            entry['title'])
                        continue
                found.setdefault('movies', []).append(movie)

        if not (found.get('shows') or found.get('movies')):
            log.debug('Nothing to submit to trakt.')
            return

        if self.config['list'] in ['collection', 'watchlist', 'watched']:
            args = ('sync', 'history' if self.config['list'] == 'watched' else
                    self.config['list'])
        else:
            args = ('users', self.config['username'], 'lists',
                    make_list_slug(self.config['list']), 'items')
        if remove:
            args += ('remove', )
        url = get_api_url(args)

        log.debug('Submitting data to trakt.tv (%s): %s' % (url, found))
        try:
            result = self.session.post(url,
                                       data=json.dumps(found),
                                       raise_status=False)
        except RequestException as e:
            log.error('Error submitting data to trakt.tv: %s' % e)
            return
        if 200 <= result.status_code < 300:
            action = 'deleted' if remove else 'added'
            res = result.json()
            # Default to 0 for all categories, even if trakt response didn't include them
            for cat in ('movies', 'shows', 'episodes', 'seasons'):
                res[action].setdefault(cat, 0)
            log.info(
                'Successfully {0} to/from list {1}: {movies} movie(s), {shows} show(s), {episodes} episode(s), '
                '{seasons} season(s).'.format(action, self.config['list'],
                                              **res[action]))
            for k, r in res['not_found'].iteritems():
                if r:
                    log.debug('not found %s: %s' % (k, r))
            # TODO: Improve messages about existing and unknown results
            # Mark the results expired if we added or removed anything
            if sum(res[action].values()) > 0:
                self.invalidate_cache()
        elif result.status_code == 404:
            log.error('List does not appear to exist on trakt: %s' %
                      self.config['list'])
        elif result.status_code == 401:
            log.error(
                'Authentication error: have you authorized Flexget on Trakt.tv?'
            )
            log.debug('trakt response: ' + result.text)
        else:
            log.error('Unknown error submitting data to trakt.tv: %s' %
                      result.text)
Exemplo n.º 2
0
    def on_task_output(self, task, config):
        """Submits accepted movies or episodes to trakt api."""
        if config.get('account') and not config.get('username'):
            config['username'] = '******'
        found = {'shows': [], 'movies': []}
        for entry in task.accepted:
            if config['type'] in ['auto', 'shows', 'seasons', 'episodes'] and entry.get('series_name') is not None:
                show = {'title': entry['series_name'], 'ids': get_entry_ids(entry)}
                if config['type'] in ['auto', 'seasons', 'episodes'] and entry.get('series_season') is not None:
                    season = {'number': entry['series_season']}
                    if config['type'] in ['auto', 'episodes'] and entry.get('series_episode') is not None:
                        season['episodes'] = [{'number': entry['series_episode']}]
                    show['seasons'] = [season]
                if config['type'] in ['seasons', 'episodes'] and 'seasons' not in show:
                    self.log.debug('Not submitting `%s`, no season found.' % entry['title'])
                    continue
                if config['type'] == 'episodes' and 'episodes' not in show:
                    self.log.debug('Not submitting `%s`, no episode number found.' % entry['title'])
                    continue
                found['shows'].append(show)
            elif config['type'] in ['auto', 'movies']:
                movie = {'ids': get_entry_ids(entry)}
                if not movie['ids']:
                    if entry.get('movie_name') is not None:
                        movie['title'] = entry.get('movie_name') or entry.get('imdb_name')
                        movie['year'] = entry.get('movie_year') or entry.get('imdb_year')
                    else:
                        self.log.debug('Not submitting `%s`, no movie name or id found.' % entry['title'])
                        continue
                found['movies'].append(movie)

        if not (found['shows'] or found['movies']):
            self.log.debug('Nothing to submit to trakt.')
            return

        if config['list'] in ['collection', 'watchlist', 'watched']:
            args = ('sync', 'history' if config['list'] == 'watched' else config['list'])
        else:
            args = ('users', config['username'], 'lists', make_list_slug(config['list']), 'items')
        if self.remove:
            args += ('remove', )
        url = get_api_url(args)

        if task.manager.options.test:
            self.log.info('Not submitting to trakt.tv because of test mode.')
            return
        session = get_session(account=config.get('account'))
        self.log.debug('Submitting data to trakt.tv (%s): %s' % (url, found))
        try:
            result = session.post(url, data=json.dumps(found), raise_status=False)
        except RequestException as e:
            self.log.error('Error submitting data to trakt.tv: %s' % e)
            return
        if 200 <= result.status_code < 300:
            action = 'added'
            if self.remove:
                action = 'deleted'
            res = result.json()
            movies = res[action].get('movies', 0)
            shows = res[action].get('shows', 0)
            eps = res[action].get('episodes', 0)
            self.log.info('Successfully %s to/from list %s: %s movie(s), %s show(s), %s episode(s).',
                          action, config['list'], movies, shows, eps)
            for k, r in res['not_found'].iteritems():
                if r:
                    self.log.debug('not found %s: %s' % (k, r))
            # TODO: Improve messages about existing and unknown results
        elif result.status_code == 404:
            self.log.error('List does not appear to exist on trakt: %s' % config['list'])
        elif result.status_code == 401:
            self.log.error('Authentication error: have you authorized Flexget on Trakt.tv?')
            self.log.debug('trakt response: ' + result.text)
        else:
            self.log.error('Unknown error submitting data to trakt.tv: %s' % result.text)
Exemplo n.º 3
0
    def submit(self, entries, remove=False):
        """Submits movies or episodes to trakt api."""
        found = {}
        for entry in entries:
            if self.config['type'] in ['auto', 'shows', 'seasons', 'episodes'] and entry.get('series_name') is not None:
                show_name, show_year = split_title_year(entry['series_name'])
                show = {'title': show_name, 'ids': get_entry_ids(entry)}
                if show_year:
                    show['year'] = show_year
                if self.config['type'] in ['auto', 'seasons', 'episodes'] and entry.get('series_season') is not None:
                    season = {'number': entry['series_season']}
                    if self.config['type'] in ['auto', 'episodes'] and entry.get('series_episode') is not None:
                        season['episodes'] = [{'number': entry['series_episode']}]
                    show['seasons'] = [season]
                if self.config['type'] in ['seasons', 'episodes'] and 'seasons' not in show:
                    log.debug('Not submitting `%s`, no season found.' % entry['title'])
                    continue
                if self.config['type'] == 'episodes' and 'episodes' not in show:
                    log.debug('Not submitting `%s`, no episode number found.' % entry['title'])
                    continue
                found.setdefault('shows', []).append(show)
            elif self.config['type'] in ['auto', 'movies']:
                movie = {'ids': get_entry_ids(entry)}
                if not movie['ids']:
                    if entry.get('movie_name') is not None:
                        movie['title'] = entry.get('movie_name') or entry.get('imdb_name')
                        movie['year'] = entry.get('movie_year') or entry.get('imdb_year')
                    else:
                        log.debug('Not submitting `%s`, no movie name or id found.' % entry['title'])
                        continue
                found.setdefault('movies', []).append(movie)

        if not (found.get('shows') or found.get('movies')):
            log.debug('Nothing to submit to trakt.')
            return

        if self.config['list'] in ['collection', 'watchlist', 'watched']:
            args = ('sync', 'history' if self.config['list'] == 'watched' else self.config['list'])
        else:
            args = ('users', self.config['username'], 'lists', make_list_slug(self.config['list']), 'items')
        if remove:
            args += ('remove',)
        url = get_api_url(args)

        log.debug('Submitting data to trakt.tv (%s): %s' % (url, found))
        try:
            result = self.session.post(url, data=json.dumps(found), raise_status=False)
        except RequestException as e:
            log.error('Error submitting data to trakt.tv: %s' % e)
            return
        if 200 <= result.status_code < 300:
            action = 'deleted' if remove else 'added'
            res = result.json()
            # Default to 0 for all categories, even if trakt response didn't include them
            for cat in ('movies', 'shows', 'episodes', 'seasons'):
                res[action].setdefault(cat, 0)
            log.info('Successfully {0} to/from list {1}: {movies} movie(s), {shows} show(s), {episodes} episode(s), '
                     '{seasons} season(s).'.format(action, self.config['list'], **res[action]))
            for k, r in res['not_found'].items():
                if r:
                    log.debug('not found %s: %s' % (k, r))
            # TODO: Improve messages about existing and unknown results
            # Mark the results expired if we added or removed anything
            if sum(res[action].values()) > 0:
                self.invalidate_cache()
        elif result.status_code == 404:
            log.error('List does not appear to exist on trakt: %s' % self.config['list'])
        elif result.status_code == 401:
            log.error('Authentication error: have you authorized Flexget on Trakt.tv?')
            log.debug('trakt response: ' + result.text)
        else:
            log.error('Unknown error submitting data to trakt.tv: %s' % result.text)
Exemplo n.º 4
0
    def on_task_output(self, task, config):
        """Submits accepted movies or episodes to trakt api."""
        if config.get('account') and not config.get('username'):
            config['username'] = '******'
        found = {'shows': [], 'movies': []}
        for entry in task.accepted:
            if 'series_name' in entry:
                show = {
                    'title': entry['series_name'],
                    'ids': get_entry_ids(entry)
                }
                if 'series_season' in entry:
                    season = {'number': entry['series_season']}
                    if 'series_episode' in entry:
                        season['episodes'] = [{
                            'number': entry['series_episode']
                        }]
                    show['seasons'] = [season]
                found['shows'].append(show)
            elif any(field in entry
                     for field in ['imdb_id', 'tmdb_id', 'movie_name']):
                movie = {'ids': get_entry_ids(entry)}
                if not movie['ids']:
                    movie['title'] = entry.get('movie_name') or entry.get(
                        'imdb_name')
                    movie['year'] = entry.get('movie_year') or entry.get(
                        'imdb_year')
                found['movies'].append(movie)

        if not (found['shows'] or found['movies']):
            self.log.debug('Nothing to submit to trakt.')
            return

        if config['list'] in ['collection', 'watchlist', 'watched']:
            args = ('sync', 'history'
                    if config['list'] == 'watched' else config['list'])
        else:
            args = ('users', config['username'], 'lists',
                    make_list_slug(config['list']), 'items')
        if self.remove:
            args += ('remove', )
        url = get_api_url(args)

        if task.manager.options.test:
            self.log.info('Not submitting to trakt.tv because of test mode.')
            return
        session = get_session(account=config.get('account'))
        self.log.debug('Submitting data to trakt.tv (%s): %s' % (url, found))
        try:
            result = session.post(url,
                                  data=json.dumps(found),
                                  raise_status=False)
        except RequestException as e:
            self.log.error('Error submitting data to trakt.tv: %s' % e)
            return
        if 200 <= result.status_code < 300:
            action = 'added'
            if self.remove:
                action = 'deleted'
            res = result.json()
            movies = res[action].get('movies', 0)
            eps = res[action].get('episodes', 0)
            self.log.info(
                'Successfully %s to/from list %s: %s movie(s), %s episode(s).'
                % (action, config['list'], movies, eps))
            for k, r in res['not_found'].iteritems():
                if r:
                    self.log.debug('not found %s: %s' % (k, r))
            # TODO: Improve messages about existing and unknown results
        elif result.status_code == 404:
            self.log.error('List does not appear to exist on trakt: %s' %
                           config['list'])
        elif result.status_code == 401:
            self.log.error(
                'Authentication error: have you authorized Flexget on Trakt.tv?'
            )
            self.log.debug('trakt response: ' + result.text)
        else:
            self.log.error('Unknown error submitting data to trakt.tv: %s' %
                           result.text)