Merge pull request #2139 from nrgaway/tv_tvdb

Tv tvdb
This commit is contained in:
Joel Kåberg
2013-09-11 07:52:42 -07:00
6 changed files with 219 additions and 261 deletions
+1 -26
View File
@@ -54,12 +54,10 @@ class ShowBase(MediaBase):
addEvent('show.add', self.add) addEvent('show.add', self.add)
def search(self, q = '', **kwargs): def search(self, q = '', **kwargs):
cache_key = u'%s/%s' % (__name__, simplifyString(q)) cache_key = u'%s/%s' % (__name__, simplifyString(q))
shows = Env.get('cache').get(cache_key) shows = Env.get('cache').get(cache_key)
if not shows: if not shows:
if getImdb(q): if getImdb(q):
shows = [fireEvent('show.info', identifier = q, merge = True)] shows = [fireEvent('show.info', identifier = q, merge = True)]
else: else:
@@ -73,7 +71,6 @@ class ShowBase(MediaBase):
} }
def addView(self, **kwargs): def addView(self, **kwargs):
movie_dict = fireEvent('show.add', params=kwargs) # XXX: Temp added so we can catch a breakpoint movie_dict = fireEvent('show.add', params=kwargs) # XXX: Temp added so we can catch a breakpoint
#movie_dict = self.add(params = kwargs) #movie_dict = self.add(params = kwargs)
@@ -83,26 +80,6 @@ class ShowBase(MediaBase):
'movie': movie_dict, 'movie': movie_dict,
} }
# XXX: Remove function and reference to it!
def debug(self, identifier):
"""
XXX: This is only a hook for a breakpoint so we can test database stuff easily
REMOVE when finished
"""
from couchpotato import get_session
from couchpotato.core.event import addEvent, fireEventAsync, fireEvent
from couchpotato.core.helpers.encoding import toUnicode, simplifyString
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from couchpotato.core.settings.model import Library, LibraryTitle, File
from string import ascii_letters
import time
import traceback
db = get_session()
parent = db.query(Library).filter_by(identifier = identifier).first()
return
def add(self, params = {}, force_readd = True, search_after = True, update_library = False, status_id = None): def add(self, params = {}, force_readd = True, search_after = True, update_library = False, status_id = None):
""" """
1. Add Show 1. Add Show
@@ -125,11 +102,10 @@ class ShowBase(MediaBase):
log.debug("show.add") log.debug("show.add")
# Add show parent to db first # Add show parent to db first
parent = self.addToDatabase(params = params, type = 'show') parent = self.addToDatabase(params = params, type = 'show')
identifier = params.get('id') identifier = params.get('id')
# XXX: add seasons
# XXX: Fix so we dont have a nested list [0] (fireEvent) # XXX: Fix so we dont have a nested list [0] (fireEvent)
try: try:
seasons = fireEvent('season.info', identifier = identifier)[0] seasons = fireEvent('season.info', identifier = identifier)[0]
@@ -156,7 +132,6 @@ class ShowBase(MediaBase):
episode['parent_identifier'] = season['identifier'] episode['parent_identifier'] = season['identifier']
self.addToDatabase(params=episode, type = "episode") self.addToDatabase(params=episode, type = "episode")
#self.debug(str(identifier)) # XXX: Remove DEBUG only
return parent return parent
def addToDatabase(self, params = {}, type="show", force_readd = True, search_after = True, update_library = False, status_id = None): def addToDatabase(self, params = {}, type="show", force_readd = True, search_after = True, update_library = False, status_id = None):
@@ -81,7 +81,6 @@ class EpisodeLibraryPlugin(LibraryBase):
do_update = True do_update = True
# XXX: Fix to be pretty
parent_identifier = None parent_identifier = None
if library.parent is not None: if library.parent is not None:
parent_identifier = library.parent.identifier parent_identifier = library.parent.identifier
@@ -89,10 +88,6 @@ class EpisodeLibraryPlugin(LibraryBase):
if library.status_id == done_status.get('id') and not force: if library.status_id == done_status.get('id') and not force:
do_update = False do_update = False
#info = fireEvent('episode.info', merge = True, identifier = identifier, \
# parent_identifier = parent_identifier)
#info = fireEvent('episode.info', merge = True, identifier = parent_identifier, \
# episode_identifier = identifier)
info = fireEvent('episode.info', merge = True, season_identifier = parent_identifier, \ info = fireEvent('episode.info', merge = True, season_identifier = parent_identifier, \
episode_identifier = identifier) episode_identifier = identifier)
@@ -114,6 +109,10 @@ class EpisodeLibraryPlugin(LibraryBase):
library.status_id = done_status.get('id') library.status_id = done_status.get('id')
library.season_number = tryInt(info.get('seasonnumber', None)) library.season_number = tryInt(info.get('seasonnumber', None))
library.episode_number = tryInt(info.get('episodenumber', None)) library.episode_number = tryInt(info.get('episodenumber', None))
try:
library.last_updated = int(info.get('lastupdated'))
except:
library.last_updated = int(time.time())
library.info.update(info) library.info.update(info)
db.commit() db.commit()
@@ -163,25 +162,27 @@ class EpisodeLibraryPlugin(LibraryBase):
return library_dict return library_dict
def updateReleaseDate(self, identifier): def updateReleaseDate(self, identifier):
'''XXX: Not sure what this is for yet in relation to an episode'''
pass
#db = get_session()
#library = db.query(EpisodeLibrary).filter_by(identifier = identifier).first()
db = get_session() #if not library.info:
library = db.query(EpisodeLibrary).filter_by(identifier = identifier).first() #library_dict = self.update(identifier, force = True)
#dates = library_dict.get('info', {}).get('release_date')
#else:
#dates = library.info.get('release_date')
if not library.info: #if dates and dates.get('expires', 0) < time.time() or not dates:
library_dict = self.update(identifier, force = True) #dates = fireEvent('movie.release_date', identifier = identifier, merge = True)
dates = library_dict.get('info', {}).get('release_date') #library.info.update({'release_date': dates })
else: #db.commit()
dates = library.info.get('release_date')
if dates and dates.get('expires', 0) < time.time() or not dates: #db.expire_all()
dates = fireEvent('movie.release_date', identifier = identifier, merge = True) #return dates
library.info.update({'release_date': dates })
db.commit()
db.expire_all()
return dates
#TODO: Add to base class
def simplifyTitle(self, title): def simplifyTitle(self, title):
title = toUnicode(title) title = toUnicode(title)
@@ -81,7 +81,6 @@ class SeasonLibraryPlugin(LibraryBase):
do_update = True do_update = True
# XXX: Fix to be pretty
parent_identifier = None parent_identifier = None
if library.parent is not None: if library.parent is not None:
parent_identifier = library.parent.identifier parent_identifier = library.parent.identifier
@@ -136,23 +135,23 @@ class SeasonLibraryPlugin(LibraryBase):
db.commit() db.commit()
# Files # Files
#images = info.get('images', []) images = info.get('images', [])
#for image_type in ['poster']: for image_type in ['poster']:
#for image in images.get(image_type, []): for image in images.get(image_type, []):
#if not isinstance(image, (str, unicode)): if not isinstance(image, (str, unicode)):
#continue continue
#file_path = fireEvent('file.download', url = image, single = True) file_path = fireEvent('file.download', url = image, single = True)
#if file_path: if file_path:
#file_obj = fireEvent('file.add', path = file_path, type_tuple = ('image', image_type), single = True) file_obj = fireEvent('file.add', path = file_path, type_tuple = ('image', image_type), single = True)
#try: try:
#file_obj = db.query(File).filter_by(id = file_obj.get('id')).one() file_obj = db.query(File).filter_by(id = file_obj.get('id')).one()
#library.files.append(file_obj) library.files.append(file_obj)
#db.commit() db.commit()
#break break
#except: except:
#log.debug('Failed to attach to library: %s', traceback.format_exc()) log.debug('Failed to attach to library: %s', traceback.format_exc())
library_dict = library.to_dict(self.default_dict) library_dict = library.to_dict(self.default_dict)
@@ -160,25 +159,27 @@ class SeasonLibraryPlugin(LibraryBase):
return library_dict return library_dict
def updateReleaseDate(self, identifier): def updateReleaseDate(self, identifier):
'''XXX: Not sure what this is for yet in relation to a tvshow'''
pass
#db = get_session()
#library = db.query(SeasonLibrary).filter_by(identifier = identifier).first()
db = get_session() #if not library.info:
library = db.query(SeasonLibrary).filter_by(identifier = identifier).first() #library_dict = self.update(identifier, force = True)
#dates = library_dict.get('info', {}).get('release_date')
#else:
#dates = library.info.get('release_date')
if not library.info: #if dates and dates.get('expires', 0) < time.time() or not dates:
library_dict = self.update(identifier, force = True) #dates = fireEvent('movie.release_date', identifier = identifier, merge = True)
dates = library_dict.get('info', {}).get('release_date') #library.info.update({'release_date': dates })
else: #db.commit()
dates = library.info.get('release_date')
if dates and dates.get('expires', 0) < time.time() or not dates: #db.expire_all()
dates = fireEvent('movie.release_date', identifier = identifier, merge = True) #return dates
library.info.update({'release_date': dates })
db.commit()
db.expire_all()
return dates
#TODO: Add to base class
def simplifyTitle(self, title): def simplifyTitle(self, title):
title = toUnicode(title) title = toUnicode(title)
@@ -84,7 +84,7 @@ class ShowLibraryPlugin(LibraryBase):
except: pass except: pass
if not info or len(info) == 0: if not info or len(info) == 0:
log.error('Could not update, no movie info to work with: %s', identifier) log.error('Could not update, no show info to work with: %s', identifier)
return False return False
# Main info # Main info
@@ -93,13 +93,30 @@ class ShowLibraryPlugin(LibraryBase):
library.tagline = toUnicode(info.get('tagline', '')) library.tagline = toUnicode(info.get('tagline', ''))
library.year = info.get('year', 0) library.year = info.get('year', 0)
library.status_id = done_status.get('id') library.status_id = done_status.get('id')
#--------------------------------------------------------------------------------------------------
# XXX: TODO: implement logic to get proper values
library.airs_dayofweek = int(0)
library.airs_time = int(0)
library.last_updated = int(0)
library.show_status = toUnicode(info.get('status', '').lower()) library.show_status = toUnicode(info.get('status', '').lower())
#-------------------------------------------------------------------------------------------------- library.airs_time = info.get('airs_time', None)
# Bits
days_of_week_map = {
u'Monday': 1,
u'Tuesday': 2,
u'Wednesday': 4,
u'Thursday': 8,
u'Friday': 16,
u'Saturday': 32,
u'Sunday': 64,
u'Daily': 127,
}
try:
library.airs_dayofweek = days_of_week_map.get(info.get('airs_dayofweek'))
except:
library.airs_dayofweek = 0
try:
library.last_updated = int(info.get('lastupdated'))
except:
library.last_updated = int(time.time())
library.info.update(info) library.info.update(info)
db.commit() db.commit()
@@ -150,25 +167,27 @@ class ShowLibraryPlugin(LibraryBase):
return library_dict return library_dict
def updateReleaseDate(self, identifier): def updateReleaseDate(self, identifier):
'''XXX: Not sure what this is for yet in relation to a show'''
pass
#db = get_session()
#library = db.query(ShowLibrary).filter_by(identifier = identifier).first()
db = get_session() #if not library.info:
library = db.query(ShowLibrary).filter_by(identifier = identifier).first() #library_dict = self.update(identifier, force = True)
#dates = library_dict.get('info', {}).get('release_date')
#else:
#dates = library.info.get('release_date')
if not library.info: #if dates and dates.get('expires', 0) < time.time() or not dates:
library_dict = self.update(identifier, force = True) #dates = fireEvent('movie.release_date', identifier = identifier, merge = True)
dates = library_dict.get('info', {}).get('release_date') #library.info.update({'release_date': dates })
else: #db.commit()
dates = library.info.get('release_date')
if dates and dates.get('expires', 0) < time.time() or not dates: #db.expire_all()
dates = fireEvent('movie.release_date', identifier = identifier, merge = True) #return dates
library.info.update({'release_date': dates })
db.commit()
db.expire_all()
return dates
#TODO: Add to base class
def simplifyTitle(self, title): def simplifyTitle(self, title):
title = toUnicode(title) title = toUnicode(title)
+111 -163
View File
@@ -2,70 +2,40 @@ from couchpotato.core.event import addEvent
from couchpotato.core.helpers.encoding import simplifyString, toUnicode from couchpotato.core.helpers.encoding import simplifyString, toUnicode
from couchpotato.core.logger import CPLog from couchpotato.core.logger import CPLog
from couchpotato.core.providers.info.base import ShowProvider from couchpotato.core.providers.info.base import ShowProvider
from couchpotato.environment import Env
from tvdb_api import tvdb_api, tvdb_exceptions from tvdb_api import tvdb_api, tvdb_exceptions
from datetime import datetime from datetime import datetime
import traceback import traceback
import os
log = CPLog(__name__) log = CPLog(__name__)
# XXX: I return None in alot of functions when there is error or no value; check if I # TODO: Consider grabbing zips to put less strain on tvdb
# should be returning an empty list or dictionary # TODO: Unicode stuff (check)
# XXX: Consider grabbing zips to put less strain on tvdb # TODO: Notigy frontend on error (tvdb down at monent)
# XXX: Consider a cache; not implenented everywhere yet or at all # TODO: Expose apikey in setting so it can be changed by user
# XXX: Search by language; now ists defualt of "en"
# XXX: alternate titles do exist for show and episodes; add them
# XXX: Unicode stuff
# XXX: we have a getShow function but it it being used?
class TheTVDb(ShowProvider): class TheTVDb(ShowProvider):
def __init__(self): def __init__(self):
#addEvent('show.by_hash', self.byHash)
addEvent('show.search', self.search, priority = 1) addEvent('show.search', self.search, priority = 1)
addEvent('show.info', self.getShowInfo, priority = 1) addEvent('show.info', self.getShowInfo, priority = 1)
addEvent('season.info', self.getSeasonInfo, priority = 1) addEvent('season.info', self.getSeasonInfo, priority = 1)
addEvent('episode.info', self.getEpisodeInfo, priority = 1) addEvent('episode.info', self.getEpisodeInfo, priority = 1)
#addEvent('show.info_by_thetvdb', self.getInfoByTheTVDBId)
# XXX: Load from somewhere else self.tvdb_api_parms = {
tvdb_api_parms = { 'apikey': self.conf('api_key'),
'apikey':"7966C02F860586D2", 'banners': True,
'banners':True 'language': 'en',
'cache': os.path.join(Env.get('cache_dir'), 'thetvdb_api'),
} }
self._setup()
self.tvdb = tvdb_api.Tvdb(**tvdb_api_parms) def _setup(self):
self.tvdb = tvdb_api.Tvdb(**self.tvdb_api_parms)
self.valid_languages = self.tvdb.config['valid_languages']
#def byHash(self, file): def search(self, q, limit = 12, language='en'):
#''' Find show by hash '''
#if self.isDisabled():
#return False
#cache_key = 'tmdb.cache.%s' % simplifyString(file)
#results = self.getCache(cache_key)
#if not results:
#log.debug('Searching for show by hash: %s', file)
#try:
#raw = tmdb.searchByHashingFile(file)
#results = []
#if raw:
#try:
#results = self.parseShow(raw)
#log.info('Found: %s', results['titles'][0] + ' (' + str(results.get('year', 0)) + ')')
#self.setCache(cache_key, results)
#return results
#except SyntaxError, e:
#log.error('Failed to parse XML response: %s', e)
#return False
#except:
#log.debug('No shows known by hash for: %s', file)
#pass
#return results
def search(self, q, limit = 12):
''' Find show by name ''' Find show by name
show = { 'id': 74713, show = { 'id': 74713,
'language': 'en', 'language': 'en',
@@ -77,45 +47,39 @@ class TheTVDb(ShowProvider):
if self.isDisabled(): if self.isDisabled():
return False return False
if language != self.tvdb_api_parms['language'] and language in self.valid_languages:
self.tvdb_api_parms['language'] = language
self._setup()
search_string = simplifyString(q) search_string = simplifyString(q)
cache_key = 'thetvdb.cache.%s.%s' % (search_string, limit) cache_key = 'thetvdb.cache.%s.%s' % (search_string, limit)
results = self.getCache(cache_key) results = self.getCache(cache_key)
# TODO: cache is not returned
if not results: if not results:
log.debug('Searching for show: %s', q) log.debug('Searching for show: %s', q)
raw = None raw = None
try: try:
raw = self.tvdb.search(search_string) raw = self.tvdb.search(search_string)
except (tvdb_exceptions.tvdb_error, IOError), e: except (tvdb_exceptions.tvdb_error, IOError), e:
log.error('Failed searching TheTVDB for "%s": %s', (search_string, traceback.format_exc())) log.error('Failed searching TheTVDB for "%s": %s', (search_string, traceback.format_exc()))
return None return False
results = [] results = []
if raw: if raw:
try: try:
nr = 0 nr = 0
for show_info in raw:
for show in raw: show = self.tvdb[int(show_info['id'])]
show = self.tvdb[int(show['id'])] results.append(self._parseShow(show))
results.append(self.parseShow(show))
nr += 1 nr += 1
if nr == limit: if nr == limit:
break break
log.info('Found: %s', [result['titles'][0] + ' (' + str(result.get('year', 0)) + ')' for result in results]) log.info('Found: %s', [result['titles'][0] + ' (' + str(result.get('year', 0)) + ')' for result in results])
self.setCache(cache_key, results) self.setCache(cache_key, results)
return results return results
#except SyntaxError, e:
# log.error('Failed to parse XML response: %s', e)
# return False
except (tvdb_exceptions.tvdb_error, IOError), e: except (tvdb_exceptions.tvdb_error, IOError), e:
log.error('Failed parsing TheTVDB for "%s": %s', (show, traceback.format_exc())) log.error('Failed parsing TheTVDB for "%s": %s', (show, traceback.format_exc()))
return False return False
return results return results
def getShow(self, identifier = None): def getShow(self, identifier = None):
@@ -129,18 +93,35 @@ class TheTVDb(ShowProvider):
return show return show
def getShowInfo(self, identifier = None):
if not identifier:
return None
cache_key = 'thetvdb.cache.%s' % identifier
log.debug('Getting showInfo: %s', cache_key)
result = self.getCache(cache_key) or {}
if result:
return result
show = self.getShow(identifier=identifier)
if show:
result = self._parseShow(show)
self.setCache(cache_key, result)
return result
def getSeasonInfo(self, identifier=None, season_identifier=None): def getSeasonInfo(self, identifier=None, season_identifier=None):
"""Either return a list of all seasons or a single season by number. """Either return a list of all seasons or a single season by number.
identifier is the show 'id' identifier is the show 'id'
""" """
if not identifier: if not identifier:
return None return False
# season_identifier must contain the 'show id : season number' since there is no tvdb id # season_identifier must contain the 'show id : season number' since there is no tvdb id
# for season and we need a reference to both the show id and season number # for season and we need a reference to both the show id and season number
if season_identifier: if season_identifier:
try: season_identifier = int(season_identifier.split(':')[1]) try: season_identifier = int(season_identifier.split(':')[1])
except: return None except: return False
cache_key = 'thetvdb.cache.%s.%s' % (identifier, season_identifier) cache_key = 'thetvdb.cache.%s.%s' % (identifier, season_identifier)
log.debug('Getting SeasonInfo: %s', cache_key) log.debug('Getting SeasonInfo: %s', cache_key)
@@ -152,16 +133,16 @@ class TheTVDb(ShowProvider):
show = self.tvdb[int(identifier)] show = self.tvdb[int(identifier)]
except (tvdb_exceptions.tvdb_error, IOError), e: except (tvdb_exceptions.tvdb_error, IOError), e:
log.error('Failed parsing TheTVDB SeasonInfo for "%s" id "%s": %s', (show, identifier, traceback.format_exc())) log.error('Failed parsing TheTVDB SeasonInfo for "%s" id "%s": %s', (show, identifier, traceback.format_exc()))
return None return False
result = [] result = []
for number, season in show.items(): for number, season in show.items():
if season_identifier is not None and number == season_identifier: if season_identifier is not None and number == season_identifier:
result = self.parseSeason(show, (number, season)) result = self._parseSeason(show, (number, season))
self.setCache(cache_key, result) self.setCache(cache_key, result)
return result return result
else: else:
result.append(self.parseSeason(show, (number, season))) result.append(self._parseSeason(show, (number, season)))
self.setCache(cache_key, result) self.setCache(cache_key, result)
return result return result
@@ -171,7 +152,7 @@ class TheTVDb(ShowProvider):
If episode_identifer contains an episode number to search for If episode_identifer contains an episode number to search for
""" """
if not identifier and season_identifier is None: if not identifier and season_identifier is None:
return None return False
# season_identifier must contain the 'show id : season number' since there is no tvdb id # season_identifier must contain the 'show id : season number' since there is no tvdb id
# for season and we need a reference to both the show id and season number # for season and we need a reference to both the show id and season number
@@ -191,7 +172,7 @@ class TheTVDb(ShowProvider):
show = self.tvdb[int(identifier)] show = self.tvdb[int(identifier)]
except (tvdb_exceptions.tvdb_error, IOError), e: except (tvdb_exceptions.tvdb_error, IOError), e:
log.error('Failed parsing TheTVDB EpisodeInfo for "%s" id "%s": %s', (show, identifier, traceback.format_exc())) log.error('Failed parsing TheTVDB EpisodeInfo for "%s" id "%s": %s', (show, identifier, traceback.format_exc()))
return None return False
result = [] result = []
for number, season in show.items(): for number, season in show.items():
@@ -200,81 +181,42 @@ class TheTVDb(ShowProvider):
for episode in season.values(): for episode in season.values():
if episode_identifier is not None and episode['id'] == toUnicode(episode_identifier): if episode_identifier is not None and episode['id'] == toUnicode(episode_identifier):
result = self.parseEpisode(show, episode) result = self._parseEpisode(show, episode)
self.setCache(cache_key, result) self.setCache(cache_key, result)
return result return result
else: else:
result.append(self.parseEpisode(show, episode)) result.append(self._parseEpisode(show, episode))
self.setCache(cache_key, result) self.setCache(cache_key, result)
return result return result
def getShowInfo(self, identifier = None): def _parseShow(self, show):
if not identifier:
return None
cache_key = 'thetvdb.cache.%s' % identifier
log.debug('Getting showInfo: %s', cache_key)
result = self.getCache(cache_key) or {}
if result:
return result
show = self.getShow(identifier=identifier)
if show:
result = self.parseShow(show)
self.setCache(cache_key, result)
return result
#def getInfoByTheTVDBId(self, id = None):
#cache_key = 'thetvdb.cache.%s' % id
#result = self.getCache(cache_key)
#if not result:
#result = {}
#show = None
#try:
#log.debug('Getting info: %s', cache_key)
#show = tmdb.getShowInfo(id = id)
#except:
#pass
#if show:
#result = self.parseShow(show)
#self.setCache(cache_key, result)
#return result
def parseShow(self, show):
""" """
show[74713] = { 'actors': u'|Bryan Cranston|Aaron Paul|Dean Norris|RJ Mitte|Betsy Brandt|Anna Gunn|Laura Fraser|Jesse Plemons|Christopher Cousins|Steven Michael Quezada|Jonathan Banks|Giancarlo Esposito|Bob Odenkirk|',
'actors': u'|Bryan Cranston|Aaron Paul|Dean Norris|RJ Mitte|Betsy Brandt|Anna Gunn|Laura Fraser|Jesse Plemons|Christopher Cousins|Steven Michael Quezada|Jonathan Banks|Giancarlo Esposito|Bob Odenkirk|', 'added': None,
'added': None, 'addedby': None,
'addedby': None, 'airs_dayofweek': u'Sunday',
'airs_dayofweek': u'Sunday', 'airs_time': u'9:00 PM',
'airs_time': u'9:00 PM', 'banner': u'http://thetvdb.com/banners/graphical/81189-g13.jpg',
'banner': u'http://thetvdb.com/banners/graphical/81189-g13.jpg', 'contentrating': u'TV-MA',
'contentrating': u'TV-MA', 'fanart': u'http://thetvdb.com/banners/fanart/original/81189-28.jpg',
'fanart': u'http://thetvdb.com/banners/fanart/original/81189-28.jpg', 'firstaired': u'2008-01-20',
'firstaired': u'2008-01-20', 'genre': u'|Crime|Drama|Suspense|',
'genre': u'|Crime|Drama|Suspense|', 'id': u'81189',
'id': u'81189', 'imdb_id': u'tt0903747',
'imdb_id': u'tt0903747', 'language': u'en',
'language': u'en', 'lastupdated': u'1376620212',
'lastupdated': u'1376620212', 'network': u'AMC',
'network': u'AMC', 'networkid': None,
'networkid': None, 'overview': u"Walter White, a struggling high school chemistry teacher is diagnosed with advanced lung cancer. He turns to a life of crime, producing and selling methamphetamine accompanied by a former student, Jesse Pinkman with the aim of securing his family's financial future before he dies.",
'overview': u"Walter White, a struggling high school chemistry teacher is diagnosed with advanced lung cancer. He turns to a life of crime, producing and selling methamphetamine accompanied by a former student, Jesse Pinkman with the aim of securing his family's financial future before he dies.", 'poster': u'http://thetvdb.com/banners/posters/81189-22.jpg',
'poster': u'http://thetvdb.com/banners/posters/81189-22.jpg', 'rating': u'9.3',
'rating': u'9.3', 'ratingcount': u'473',
'ratingcount': u'473', 'runtime': u'60',
'runtime': u'60', 'seriesid': u'74713',
'seriesid': u'74713', 'seriesname': u'Breaking Bad',
'seriesname': u'Breaking Bad', 'status': u'Continuing',
'status': u'Continuing', 'zap2it_id': u'SH01009396'
'zap2it_id': u'SH01009396'}
""" """
# Make sure we have a valid show id, not '' or None # Make sure we have a valid show id, not '' or None
@@ -282,10 +224,10 @@ class TheTVDb(ShowProvider):
# return None # return None
## Images ## Images
poster = self.getImage(show, type = 'poster', size = 'cover') poster = show['poster']
backdrop = self.getImage(show, type = 'fanart', size = 'w1280') backdrop = show['fanart']
#poster_original = self.getImage(show, type = 'poster', size = 'original') #poster = self.getImage(show, type = 'poster', size = 'cover')
#backdrop_original = self.getImage(show, type = 'backdrop', size = 'original') #backdrop = self.getImage(show, type = 'fanart', size = 'w1280')
genres = [] if show['genre'] is None else show['genre'].strip('|').split('|') genres = [] if show['genre'] is None else show['genre'].strip('|').split('|')
if show['firstaired'] is not None: if show['firstaired'] is not None:
@@ -329,21 +271,34 @@ class TheTVDb(ShowProvider):
show_data = dict((k, v) for k, v in show_data.iteritems() if v) show_data = dict((k, v) for k, v in show_data.iteritems() if v)
## Add alternative names # Add alternative titles
#for alt in ['original_name', 'alternative_name']: try:
#alt_name = toUnicode(show['alt)) raw = self.tvdb.search(show['seriesname'])
#if alt_name and not alt_name in show_data['titles'] and alt_name.lower() != 'none' and alt_name != None: if raw:
#show_data['titles'].append(alt_name) for show_info in raw:
if show_info['id'] == show_data['id'] and show_info.get('aliasnames', None):
for alt_name in show_info['aliasnames'].split('|'):
show_data['titles'].append(toUnicode(alt_name))
except (tvdb_exceptions.tvdb_error, IOError), e:
log.error('Failed searching TheTVDB for "%s": %s', (show['seriesname'], traceback.format_exc()))
return show_data return show_data
def parseSeason(self, show, season_tuple): def _parseSeason(self, show, season_tuple):
""" """
contains no data contains no data
""" """
number, season = season_tuple number, season = season_tuple
title = toUnicode('%s - Season %s' % (show['seriesname'], str(number))) title = toUnicode('%s - Season %s' % (show['seriesname'], str(number)))
poster = []
try:
for id, data in show.data['_banners']['season']['season'].items():
if data.get('season', None) == str(number) and data['bannertype'] == 'season' and data['bannertype2'] == 'season':
poster.append(data.get('_bannerpath'))
break # Only really need one
except:
pass
# XXX: work on title; added defualt_title to fix an error # XXX: work on title; added defualt_title to fix an error
season_data = { season_data = {
@@ -356,7 +311,7 @@ class TheTVDb(ShowProvider):
'parent_identifier': show['id'], 'parent_identifier': show['id'],
'seasonnumber': str(number), 'seasonnumber': str(number),
'images': { 'images': {
'poster': [], 'poster': poster,
'backdrop': [], 'backdrop': [],
'poster_original': [], 'poster_original': [],
'backdrop_original': [], 'backdrop_original': [],
@@ -369,7 +324,7 @@ class TheTVDb(ShowProvider):
season_data = dict((k, v) for k, v in season_data.iteritems() if v) season_data = dict((k, v) for k, v in season_data.iteritems() if v)
return season_data return season_data
def parseEpisode(self, show, episode): def _parseEpisode(self, show, episode):
""" """
('episodenumber', u'1'), ('episodenumber', u'1'),
('thumb_added', None), ('thumb_added', None),
@@ -473,26 +428,19 @@ class TheTVDb(ShowProvider):
} }
episode_data = dict((k, v) for k, v in episode_data.iteritems() if v) episode_data = dict((k, v) for k, v in episode_data.iteritems() if v)
## Add alternative names
#for alt in ['original_name', 'alternative_name']:
#alt_name = toUnicode(episode['alt))
#if alt_name and not alt_name in episode_data['titles'] and alt_name.lower() != 'none' and alt_name != None:
#episode_data['titles'].append(alt_name)
return episode_data return episode_data
def getImage(self, show, type = 'poster', size = 'cover'): #def getImage(self, show, type = 'poster', size = 'cover'):
"""""" #""""""
# XXX: Need to implement size ## XXX: Need to implement size
image_url = '' #image_url = ''
for res, res_data in show['_banners'].get(type, {}).items(): #for res, res_data in show['_banners'].get(type, {}).items():
for bid, banner_info in res_data.items(): #for bid, banner_info in res_data.items():
image_url = banner_info.get('_bannerpath', '') #image_url = banner_info.get('_bannerpath', '')
break #break
return image_url #return image_url
def isDisabled(self): def isDisabled(self):
if self.conf('api_key') == '': if self.conf('api_key') == '':
+16 -2
View File
@@ -118,8 +118,21 @@ class ShowLibrary(Library, DictMixin):
last_updated = Field(Integer, index = True) last_updated = Field(Integer, index = True)
show_status = Field(String(10), index = True) show_status = Field(String(10), index = True)
airs_dayofweek = Field(Integer, index = True)
airs_time = Field(Integer, index = True) # XXX: Maybe we should convert this to seconds?
# airs_time u'21:00'
airs_time = Field(Unicode, index = True)
# airs_dayofweek = Field(Integer, index = True)
# u'Monday': 1,
# u'Tuesday': 2,
# u'Wednesday': 4,
# u'Thursday': 8,
# u'Friday': 16,
# u'Saturday': 32,
# u'Sunday': 64,
# u'Daily': 127,
airs_dayofweek = Field(Integer, index = True)
def getSeasons(self): def getSeasons(self):
data = OrderedDict() data = OrderedDict()
@@ -188,6 +201,7 @@ class SeasonLibrary(Library, DictMixin):
class EpisodeLibrary(Library): class EpisodeLibrary(Library):
using_options(inheritance = 'multi') using_options(inheritance = 'multi')
last_updated = Field(Integer, index = True)
season_number = Field(Integer, index = True) season_number = Field(Integer, index = True)
episode_number = Field(Integer, index = True) episode_number = Field(Integer, index = True)