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
16
from flexget.plugins.api_tvdb import lookup_series
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):
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)
33
# Create new table from the current model
34
Base.metadata.create_all(bind=session.bind)
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()
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.
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')
76
@cached('thetvdb_favorites')
79
def on_feed_input(self, feed, config, session=None):
80
account_id = str(config['account_id'])
81
# Get the cache for this user
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)
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))
91
for i in data.favorites.findAll('series', recursive=False):
93
favorite_ids.append(i.string)
94
except (urllib2.URLError, IOError, AttributeError):
96
# If there are errors getting the favorites or parsing the xml, fall back on cache
97
log.error('Error retrieving favorites from thetvdb, using cache.')
98
log.debug(traceback.format_exc())
100
# Successfully updated from tvdb, update the database
101
log.debug('Successfully updated favorites from thetvdb.com')
102
if not user_favorites:
103
user_favorites = ThetvdbFavorites(account_id, favorite_ids)
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.')
112
# Construct list of entries with our series names
114
for series_id in user_favorites.series_ids:
115
# Lookup the series name from the id
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))
121
series_name = series.seriesname
122
if config.get('strip_dates'):
123
# Remove year from end of series name if present
124
series_name = re.sub(r'\s+\(\d{4}\)$', '', series_name)
125
entries.append(Entry(series_name, ''))
128
register_plugin(InputThetvdbFavorites, 'thetvdb_favorites', api_ver=2)