<commit_before>from __future__ import unicode_literals, division, absolute_import
import logging
from urlparse import urljoin

from requests import RequestException

from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.trakt import API_URL, get_session, make_list_slug, get_api_url

log = logging.getLogger('trakt_emit')


class TraktEmit(object):
    """
    Creates an entry for the latest or the next item in your watched or collected
    episodes in your trakt account.

    Syntax:

    trakt_emit:
      username: <value>
      position: <last|next>
      context: <collect|collected|watch|watched>
      list: <value>

    Options username, password and api_key are required.

    """

    schema = {
        'type': 'object',
        'properties': {
            'username': {'type': 'string'},
            'password': {'type': 'string'},
            'position': {'type': 'string', 'enum': ['last', 'next'], 'default': 'next'},
            'context': {'type': 'string', 'enum': ['watched', 'collected'], 'default': 'watched'},
            'list': {'type': 'string'}
        },
        'required': ['username'],
        'additionalProperties': False
    }

    def on_task_input(self, task, config):
        session = get_session(config['username'], config.get('password'))
        listed_series = {}
        if config.get('list'):
            url = urljoin(API_URL, 'users/%s/' % config['username'])
            if config['list'] in ['collection', 'watchlist', 'watched']:
                url = urljoin(url, '%s/shows' % config['list'])
            else:
                url = urljoin(url, 'lists/%s/items' % make_list_slug(config['list']))
            try:
                data = session.get(url).json()
            except RequestException as e:
                raise plugin.PluginError('Unable to get trakt list `%s`: %s' % (config['list'], e))
            if not data:
                log.warning('The list "%s" is empty.' % config['list'])
                return
            for item in data:
                if getattr(data, 'show'):
                    if item['show'] is not None:
                        if not item['show']['title']:
                            # Seems we can get entries with a blank show title sometimes
                            log.warning('Found trakt list show with no series name.')
                            continue
                        trakt_id = item['show']['ids']['trakt']
                        listed_series[trakt_id] = {
                            'series_name': item['show']['title'],
                            'trakt_id': trakt_id,
                            'tvdb_id': item['show']['ids']['tvdb']}
                    else:
                        log.error('Trakt input returned invalid Data for trakt list')
        context = config['context']
        if context == 'collected':
            context = 'collection'
        entries = []
        for trakt_id, fields in listed_series.iteritems():
            url = get_api_url('shows', trakt_id, 'progress', context)
            try:
                data = session.get(url).json()
            except RequestException as e:
                raise plugin.PluginError('TODO: error message')
            if config['position'] == 'next' and data.get('next_episode'):
                # If the next episode is already in the trakt database, we'll get it here
                eps = data['next_episode']['season']
                epn = data['next_episode']['number']
            else:
                # If we need last ep, or next_episode was not provided, search for last ep
                for seas in reversed(data['seasons']):
                    # Find the first season with collected/watched episodes
                    if seas['completed'] > 0:<commit_msg>Fixed typo<commit_after>from __future__ import unicode_literals, division, absolute_import
import logging
from urlparse import urljoin

from requests import RequestException

from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.trakt import API_URL, get_session, make_list_slug, get_api_url

log = logging.getLogger('trakt_emit')


class TraktEmit(object):
    """
    Creates an entry for the latest or the next item in your watched or collected
    episodes in your trakt account.

    Syntax:

    trakt_emit:
      username: <value>
      position: <last|next>
      context: <collect|collected|watch|watched>
      list: <value>

    Options username, password and api_key are required.

    """

    schema = {
        'type': 'object',
        'properties': {
            'username': {'type': 'string'},
            'password': {'type': 'string'},
            'position': {'type': 'string', 'enum': ['last', 'next'], 'default': 'next'},
            'context': {'type': 'string', 'enum': ['watched', 'collected'], 'default': 'watched'},
            'list': {'type': 'string'}
        },
        'required': ['username'],
        'additionalProperties': False
    }

    def on_task_input(self, task, config):
        session = get_session(config['username'], config.get('password'))
        listed_series = {}
        if config.get('list'):
            url = urljoin(API_URL, 'users/%s/' % config['username'])
            if config['list'] in ['collection', 'watchlist', 'watched']:
                url = urljoin(url, '%s/shows' % config['list'])
            else:
                url = urljoin(url, 'lists/%s/items' % make_list_slug(config['list']))
            try:
                data = session.get(url).json()
            except RequestException as e:
                raise plugin.PluginError('Unable to get trakt list `%s`: %s' % (config['list'], e))
            if not data:
                log.warning('The list "%s" is empty.' % config['list'])
                return
            for item in data:
                if getattr(item, 'show'):
                    if item['show'] is not None:
                        if not item['show']['title']:
                            # Seems we can get entries with a blank show title sometimes
                            log.warning('Found trakt list show with no series name.')
                            continue
                        trakt_id = item['show']['ids']['trakt']
                        listed_series[trakt_id] = {
                            'series_name': item['show']['title'],
                            'trakt_id': trakt_id,
                            'tvdb_id': item['show']['ids']['tvdb']}
                    else:
                        log.error('Trakt input returned invalid Data for trakt list')
        context = config['context']
        if context == 'collected':
            context = 'collection'
        entries = []
        for trakt_id, fields in listed_series.iteritems():
            url = get_api_url('shows', trakt_id, 'progress', context)
            try:
                data = session.get(url).json()
            except RequestException as e:
                raise plugin.PluginError('TODO: error message')
            if config['position'] == 'next' and data.get('next_episode'):
                # If the next episode is already in the trakt database, we'll get it here
                eps = data['next_episode']['season']
                epn = data['next_episode']['number']
            else:
                # If we need last ep, or next_episode was not provided, search for last ep
                for seas in reversed(data['seasons']):
                    # Find the first season with collected/watched episodes
                    if seas['completed'] > 0:
{'fraction_non_alphanumeric': 0.12377338741331938, 'fraction_numerical': 0.00026167735182519954, 'mean_word_length': 1.8954545454545455, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '110200', 'n_tokens_mistral': 2029, 'n_tokens_neox': 1954, 'n_words': 598}