You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

200 lines
7.3 KiB

from couchpotato import get_session
14 years ago
from couchpotato.core.event import addEvent, fireEventAsync, fireEvent
13 years ago
from couchpotato.core.helpers.encoding import toUnicode, simplifyString
14 years ago
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
14 years ago
log = CPLog(__name__)
class LibraryPlugin(Plugin):
default_dict = {'titles': {}, 'files':{}}
14 years ago
def __init__(self):
addEvent('library.add', self.add)
14 years ago
addEvent('library.update', self.update)
13 years ago
addEvent('library.update_release_date', self.updateReleaseDate)
def add(self, attrs = {}, update_after = True):
# movies don't yet contain these, so lets make sure to set defaults
type = attrs.get('type', 'movie')
primary_provider = attrs.get('primary_provider', 'imdb')
14 years ago
db = get_session()
parent_identifier = attrs.get('parent_identifier', None)
# XXX: add type (somehow? it will be show when episode id the type) so we dont get conflicts
parent = None
if parent_identifier:
#parent = db.query(Library).filter_by(identifier = attrs.get('parent_identifier')).first()
parent = db.query(Library).filter_by(primary_provider = primary_provider, identifier = attrs.get('parent_identifier')).first()
l = db.query(Library).filter_by(type = type, identifier = attrs.get('identifier')).first()
if not l:
status = fireEvent('status.get', 'needs_update', single = True)
l = Library(
type = type,
primary_provider = primary_provider,
year = attrs.get('year'),
identifier = attrs.get('identifier'),
14 years ago
plot = toUnicode(attrs.get('plot')),
tagline = toUnicode(attrs.get('tagline')),
status_id = status.get('id'),
info = {},
parent = parent,
14 years ago
)
# children = [],
14 years ago
title = LibraryTitle(
title = toUnicode(attrs.get('title')),
simple_title = self.simplifyTitle(attrs.get('title')),
)
14 years ago
l.titles.append(title)
db.add(l)
db.commit()
14 years ago
# Update library info
if update_after is not False:
handle = fireEventAsync if update_after is 'async' else fireEvent
handle('library.update', identifier = l.identifier, default_title = toUnicode(attrs.get('title', '')))
14 years ago
library_dict = l.to_dict(self.default_dict)
db.expire_all()
return library_dict
def update(self, identifier, default_title = '', force = False):
14 years ago
if self.shuttingDown():
return
14 years ago
db = get_session()
library = db.query(Library).filter_by(identifier = identifier).first()
done_status = fireEvent('status.get', 'done', single = True)
if library:
library_dict = library.to_dict(self.default_dict)
14 years ago
do_update = True
# XXX: Fix to be pretty
parent_identifier = None
if library.parent:
parent_identifier = library.parent.identifier
if library.status_id == done_status.get('id') and not force:
14 years ago
do_update = False
# XXX: do this a better way. we need to pass parent_identifier to things like episode.info
# maybe just make all .info (movie, show, season and esisode requre parent var and not use it)
elif parent_identifier:
info = fireEvent('%s.info' % library.type, merge = True, identifier = identifier, \
parent_identifier = parent_identifier)
14 years ago
else:
info = fireEvent('%s.info' % library.type, merge = True, identifier = identifier)
# Don't need those here
try: del info['in_wanted']
except: pass
try: del info['in_library']
except: pass
14 years ago
if not info or len(info) == 0:
log.error('Could not update, no movie info to work with: %s', identifier)
return False
14 years ago
# Main info
14 years ago
if do_update:
14 years ago
library.plot = toUnicode(info.get('plot', ''))
library.tagline = toUnicode(info.get('tagline', ''))
14 years ago
library.year = info.get('year', 0)
library.status_id = done_status.get('id')
library.info.update(info)
14 years ago
db.commit()
14 years ago
14 years ago
# Titles
[db.delete(title) for title in library.titles]
db.commit()
14 years ago
14 years ago
titles = info.get('titles', [])
log.debug('Adding titles: %s', titles)
counter = 0
14 years ago
for title in titles:
if not title:
continue
title = toUnicode(title)
14 years ago
t = LibraryTitle(
title = title,
simple_title = self.simplifyTitle(title),
default = (len(default_title) == 0 and counter == 0) or len(titles) == 1 or title.lower() == toUnicode(default_title.lower()) or (toUnicode(default_title) == u'' and toUnicode(titles[0]) == title)
14 years ago
)
library.titles.append(t)
counter += 1
14 years ago
db.commit()
14 years ago
# Files
images = info.get('images', [])
for image_type in ['poster']:
for image in images.get(image_type, []):
if not isinstance(image, (str, unicode)):
14 years ago
continue
file_path = fireEvent('file.download', url = image, single = True)
if file_path:
file_obj = fireEvent('file.add', path = file_path, type_tuple = ('image', image_type), single = True)
try:
file_obj = db.query(File).filter_by(id = file_obj.get('id')).one()
library.files.append(file_obj)
db.commit()
break
except:
log.debug('Failed to attach to library: %s', traceback.format_exc())
14 years ago
14 years ago
library_dict = library.to_dict(self.default_dict)
14 years ago
db.expire_all()
return library_dict
13 years ago
def updateReleaseDate(self, identifier):
db = get_session()
library = db.query(Library).filter_by(identifier = identifier).first()
if not library.info:
library_dict = self.update(identifier, force = True)
dates = library_dict.get('info', {}).get('release_date')
else:
dates = library.info.get('release_date')
if dates and dates.get('expires', 0) < time.time() or not dates:
dates = fireEvent('movie.release_date', identifier = identifier, merge = True)
library.info.update({'release_date': dates })
db.commit()
db.expire_all()
return dates
def simplifyTitle(self, title):
title = toUnicode(title)
nr_prefix = '' if title[0] in ascii_letters else '#'
title = simplifyString(title)
for prefix in ['the ']:
if prefix == title[:len(prefix)]:
title = title[len(prefix):]
break
return nr_prefix + title