flexget.plugins.input.thetvdb_favorites
Covered: 65 lines
Missed: 37 lines
Skipped 27 lines
Percent: 63 %
  1
import logging
  2
import urllib2
  3
import re
  4
from datetime import datetime, timedelta
  5
from BeautifulSoup import BeautifulStoneSoup
  6
from sqlalchemy import Column, Integer, Unicode, DateTime, String
  7
from flexget import schema
  8
from flexget.plugin import register_plugin, internet, DependencyError
  9
from flexget.utils.tools import urlopener
 10
from flexget.utils.database import pipe_list_synonym, with_session
 11
from flexget.utils.sqlalchemy_utils import drop_tables, table_columns
 12
from flexget.utils.cached_input import cached
 13
from flexget.entry import Entry
 15
try:
 16
    from flexget.plugins.api_tvdb import lookup_series
 17
except ImportError:
 18
    raise DependencyError(issued_by='thetvdb_favorites', missing='api_tvdb',
 19
                          message='thetvdb_lookup requires the `api_tvdb` plugin')
 21
log = logging.getLogger('thetvdb_favorites')
 22
Base = schema.versioned_base('thetvdb_favorites', 0)
 25
@schema.upgrade('thetvdb_favorites')
 26
def upgrade(ver, session):
 27
    if ver is None:
 28
        columns = table_columns('thetvdb_favorites', session)
 29
        if not 'series_ids' in columns:
 31
            log.info('Dropping old version of thetvdb_favorites table from db')
 32
            drop_tables(['thetvdb_favorites'], session)
 34
            Base.metadata.create_all(bind=session.bind)
 35
        ver = 0
 36
    return ver
 39
class ThetvdbFavorites(Base):
 41
    __tablename__ = 'thetvdb_favorites'
 43
    id = Column(Integer, primary_key=True)
 44
    account_id = Column(String, index=True)
 45
    _series_ids = Column('series_ids', Unicode)
 46
    series_ids = pipe_list_synonym('_series_ids')
 47
    updated = Column(DateTime)
 49
    def __init__(self, account_id, series_ids):
 50
        self.account_id = account_id
 51
        self.series_ids = series_ids
 52
        self.updated = datetime.now()
 54
    def __repr__(self):
 55
        return '<series_favorites(account_id=%s, series_id=%s)>' % (self.account_id, self.series_id)
 58
class InputThetvdbFavorites(object):
 59
    """Creates a list of entries for your series marked as favorites at thetvdb.com for use in import_series.
 61
    Example:
 63
    import_series:
 64
      from:
 65
        thetvdb_favorites:
 66
          account_id: 23098230
 67
    """
 69
    def validator(self):
 70
        from flexget import validator
 71
        root = validator.factory('dict')
 72
        root.accept('text', key='account_id', required=True)
 73
        root.accept('boolean', key='strip_dates')
 74
        return root
 76
    @cached('thetvdb_favorites')
 77
    @internet(log)
 78
    @with_session
 79
    def on_feed_input(self, feed, config, session=None):
 80
        account_id = str(config['account_id'])
 82
        user_favorites = session.query(ThetvdbFavorites).filter(ThetvdbFavorites.account_id == account_id).first()
 83
        if user_favorites and user_favorites.updated > datetime.now() - timedelta(minutes=10):
 84
            log.debug('Using cached thetvdb favorite series information for account ID %s' % account_id)
 85
        else:
 86
            try:
 87
                url = 'http://thetvdb.com/api/User_Favorites.php?accountid=%s' % account_id
 88
                log.debug('requesting %s' % url)
 89
                data = BeautifulStoneSoup(urlopener(url, log))
 90
                favorite_ids = []
 91
                for i in data.favorites.findAll('series', recursive=False):
 92
                    if i.string:
 93
                        favorite_ids.append(i.string)
 94
            except (urllib2.URLError, IOError, AttributeError):
 95
                import traceback
 97
                log.error('Error retrieving favorites from thetvdb, using cache.')
 98
                log.debug(traceback.format_exc())
 99
            else:
101
                log.debug('Successfully updated favorites from thetvdb.com')
102
                if not user_favorites:
103
                    user_favorites = ThetvdbFavorites(account_id, favorite_ids)
104
                else:
105
                    user_favorites.series_ids = favorite_ids
106
                    user_favorites.updated = datetime.now()
107
                session.merge(user_favorites)
108
        if not user_favorites.series_ids:
109
            log.warning('Didn\'t find any thetvdb.com favorites.')
110
            return
113
        entries = []
114
        for series_id in user_favorites.series_ids:
116
            try:
117
                series = lookup_series(tvdb_id=series_id)
118
            except LookupError, e:
119
                log.error('Error looking up %s from thetvdb: %s' % (series_id, e.message))
120
            else:
121
                series_name = series.seriesname
122
                if config.get('strip_dates'):
124
                    series_name = re.sub(r'\s+\(\d{4}\)$', '', series_name)
125
                entries.append(Entry(series_name, ''))
126
        return entries
128
register_plugin(InputThetvdbFavorites, 'thetvdb_favorites', api_ver=2)