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

from dateutil.parser import parse as dateutil_parse
from sqlalchemy import Table, Column, Integer, String, Unicode, Boolean, Date, DateTime, Time, or_
from sqlalchemy.orm import relation, object_session
from sqlalchemy.schema import ForeignKey

from flexget import db_schema
from flexget import plugin
from flexget.db_schema import upgrade
from flexget.event import event
from flexget.plugins.filter.series import normalize_series_name
from flexget.utils import json, requests
from flexget.utils.database import with_session
from flexget.utils.simple_persistence import SimplePersistence

api_key = '6c228565a45a302e49fb7d2dab066c9ab948b7be/'
search_show = 'http://api.trakt.tv/search/shows.json/'
episode_summary = 'http://api.trakt.tv/show/episode/summary.json/'
show_summary = 'http://api.trakt.tv/show/summary.json/'
Base = db_schema.versioned_base('api_trakt', 3)
log = logging.getLogger('api_trakt')
# Production Site
API_KEY = '<KEY>'
API_URL = 'https://api-v2launch.trakt.tv/'

# Stores the last time we checked for updates for shows/movies
updated = SimplePersistence('api_trakt')


def make_list_slug(name):
    """Return the slug for use in url for given list name."""
    slug = name.lower()
    # These characters are just stripped in the url
    for char in '!@#$%^*()[]{}/=?+\\|':
        slug = slug.replace(char, '')
    # These characters get replaced
    slug = slug.replace('&', 'and')
    slug = slug.replace(' ', '-')
    return slug


def get_session(username=None, password=None):
    """Creates a requests session which is authenticated to trakt."""
    session = requests.Session()
    session.headers = {
        'Content-Type': 'application/json',
        'trakt-api-version': 2,
        'trakt-api-key': API_KEY
    }
    if username:
        session.headers['trakt-user-login'] = username
    if username and password:
        auth = {'login': username, 'password': password}
        try:
            r = session.post(urljoin(API_URL, 'auth/login'), data=json.dumps(auth))
        except requests.RequestException as e:
            if e.response and e.response.status_code in [401, 403]:<commit_msg>Start adding code for trakt pin auth<commit_after>from __future__ import unicode_literals, division, absolute_import
import logging
import re
from datetime import datetime, timedelta
from urlparse import urljoin

from dateutil.parser import parse as dateutil_parse
from sqlalchemy import Table, Column, Integer, String, Unicode, Boolean, Date, DateTime, Time, or_
from sqlalchemy.orm import relation, object_session
from sqlalchemy.schema import ForeignKey

from flexget import db_schema
from flexget import plugin
from flexget.db_schema import upgrade
from flexget.event import event
from flexget.manager import Session
from flexget.plugins.filter.series import normalize_series_name
from flexget.utils import json, requests
from flexget.utils.database import with_session
from flexget.utils.simple_persistence import SimplePersistence

api_key = '6c228565a45a302e49fb7d2dab066c9ab948b7be/'
search_show = 'http://api.trakt.tv/search/shows.json/'
episode_summary = 'http://api.trakt.tv/show/episode/summary.json/'
show_summary = 'http://api.trakt.tv/show/summary.json/'
Base = db_schema.versioned_base('api_trakt', 3)
log = logging.getLogger('api_trakt')
# Production Site
CLIENT_ID = '57e188bcb9750c79ed452e1674925bc6848bd126e02bb15350211be74c6547af'
CLIENT_SECRET = '<KEY>'
API_URL = 'https://api-v2launch.trakt.tv/'

# Stores the last time we checked for updates for shows/movies
updated = SimplePersistence('api_trakt')


# Oauth account authentication
class TraktUserAuth(Base):
    __tablename__ = 'trakt_user_auth'

    account = Column(Unicode)
    access_token = Column(Unicode)
    refresh_token = Column(Unicode)
    expires = Column(DateTime)


def account_auth(token, refresh=False):
    """
    Gets authorization info from a pin or refresh token.

    :param account: Arbitrary account name to attach authorization to.
    :param unicode token: The pin or refresh token, as supplied by the trakt website.
    :param bool refresh: If True, `token` should be a refresh token rather than a pin.
    :raises RequestException: If there is a network error while authorizing.
    """
    data = {
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob'
    }
    if refresh:
        data['refresh_token'] = token
        data['grant_type'] = 'refresh_token'
    else:
        data['code'] = token
        data['grant_type'] = 'authorization_code'

    return get_session().post(get_api_url('oauth/token'), data=data).json()


def make_list_slug(name):
    """Return the slug for use in url for given list name."""
    slug = name.lower()
    # These characters are just stripped in the url
    for char in '!@#$%^*()[]{}/=?+\\|':
        slug = slug.replace(char, '')
    # These characters get replaced
    slug = slug.replace('&', 'and')
    slug = slug.replace(' ', '-')
    return slug


def get_session(username=None, password=None):
    """Creates a requests session which is authenticated to trakt."""
    session = requests.Session()
    session.headers = {
        'Content-Type': 'application/json',
        'trakt-api-version': 2,
        'trakt-api-key': CLIENT_ID
    }
    if username:
        session.headers['trakt-user-login'] = username
    if username and password:
        auth = {'login': username, 'password': password}
        try:
            r = session.post(urljoin(API_URL, 'auth/login'), data=json.dumps(auth))
        except requests.RequestException as e:
            if e.response and e.response.status_code in [401, 403]:
{'fraction_non_alphanumeric': 0.108541846419327, 'fraction_numerical': 0.019327006039689388, 'mean_word_length': 3.949615713065756, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, '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': '6932037', 'n_tokens_mistral': 1861, 'n_tokens_neox': 1756, 'n_words': 502}