Code cleanup

This commit is contained in:
Ruud
2013-09-02 21:59:06 +02:00
parent 7d32a8750d
commit 7fd14e0283
59 changed files with 171 additions and 170 deletions
+3 -1
View File
@@ -26,11 +26,13 @@ log = CPLog(__name__)
class Plugin(object):
_class_name = None
plugin_path = None
enabled_option = 'enabled'
auto_register_static = True
_needs_shutdown = False
_running = None
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20130519 Firefox/24.0'
http_last_use = {}
@@ -306,4 +308,4 @@ class Plugin(object):
return not self.isEnabled()
def isEnabled(self):
return self.conf(self.enabled_option) or self.conf(self.enabled_option) == None
return self.conf(self.enabled_option) or self.conf(self.enabled_option) is None
+1 -1
View File
@@ -12,7 +12,7 @@ if os.name == 'nt':
except:
# todo:: subclass ImportError for missing dependencies, vs. broken plugins?
raise ImportError("Missing the win32file module, which is a part of the prerequisite \
pywin32 package. You can get it from http://sourceforge.net/projects/pywin32/files/pywin32/");
pywin32 package. You can get it from http://sourceforge.net/projects/pywin32/files/pywin32/")
else:
import win32file #@UnresolvedImport
+1 -1
View File
@@ -93,7 +93,7 @@ class Dashboard(Plugin):
})
# Don't list older movies
if ((not late and ((not eta.get('dvd') and not eta.get('theater')) or (eta.get('dvd') and eta.get('dvd') > (now - 2419200)))) or \
if ((not late and (not eta.get('dvd') and not eta.get('theater') or eta.get('dvd') and eta.get('dvd') > (now - 2419200))) or
(late and (eta.get('dvd', 0) > 0 or eta.get('theater')) and eta.get('dvd') < (now - 2419200))):
movies.append(temp)
-1
View File
@@ -90,7 +90,6 @@ class Logging(Plugin):
if not os.path.isfile(path):
break
reversed_lines = []
f = open(path, 'r')
reversed_lines = toUnicode(f.read()).split('[0m\n')
reversed_lines.reverse()
+2 -2
View File
@@ -184,7 +184,7 @@ class Manage(Plugin):
fireEvent('release.add', group = group)
fireEventAsync('library.update.movie', identifier = identifier, on_complete = self.createAfterUpdate(folder, identifier))
else:
self.in_progress[folder]['to_go'] = self.in_progress[folder]['to_go'] - 1
self.in_progress[folder]['to_go'] -= 1
return addToLibrary
@@ -195,7 +195,7 @@ class Manage(Plugin):
if not self.in_progress or self.shuttingDown():
return
self.in_progress[folder]['to_go'] = self.in_progress[folder]['to_go'] - 1
self.in_progress[folder]['to_go'] -= 1
total = self.in_progress[folder]['total']
movie_dict = fireEvent('movie.get', identifier, single = True)
+1 -1
View File
@@ -155,7 +155,7 @@ class ProfilePlugin(Plugin):
def fill(self):
db = get_session();
db = get_session()
profiles = [{
'label': 'Best',
+1 -1
View File
@@ -102,7 +102,7 @@ class QualityPlugin(Plugin):
def fill(self):
db = get_session();
db = get_session()
order = 0
for q in self.qualities:
+3 -2
View File
@@ -8,6 +8,7 @@ from couchpotato.core.plugins.scanner.main import Scanner
from couchpotato.core.settings.model import File, Release as Relea, Movie
from sqlalchemy.sql.expression import and_, or_
import os
import traceback
log = CPLog(__name__)
@@ -88,8 +89,8 @@ class Release(Plugin):
added_files = db.query(File).filter(or_(*[File.id == x for x in added_files])).all()
rel.files.extend(added_files)
db.commit()
except Exception, e:
log.debug('Failed to attach "%s" to release: %s', (cur_file, e))
except:
log.debug('Failed to attach "%s" to release: %s', (added_files, traceback.format_exc()))
fireEvent('movie.restatus', movie.id)
+14 -15
View File
@@ -9,8 +9,7 @@ from couchpotato.core.plugins.base import Plugin
from couchpotato.core.settings.model import Library, File, Profile, Release, \
ReleaseInfo
from couchpotato.environment import Env
from unrar2 import RarFile, RarInfo
from unrar2.rar_exceptions import *
from unrar2 import RarFile
import errno
import fnmatch
import os
@@ -62,10 +61,10 @@ class Renamer(Plugin):
def scanView(self, **kwargs):
async = tryInt(kwargs.get('async', None))
movie_folder = kwargs.get('movie_folder', None)
downloader = kwargs.get('downloader', None)
download_id = kwargs.get('download_id', None)
async = tryInt(kwargs.get('async', 0))
movie_folder = kwargs.get('movie_folder')
downloader = kwargs.get('downloader')
download_id = kwargs.get('download_id')
download_info = {'folder': movie_folder} if movie_folder else None
if download_info:
@@ -98,7 +97,7 @@ class Renamer(Plugin):
elif self.conf('from') in self.conf('to'):
log.error('The "to" can\'t be inside of the "from" folder. You\'ll get an infinite loop.')
return
elif (movie_folder and movie_folder in [self.conf('to'), self.conf('from')]):
elif movie_folder and movie_folder in [self.conf('to'), self.conf('from')]:
log.error('The "to" and "from" folders can\'t be inside of or the same as the provided movie folder.')
return
@@ -131,8 +130,8 @@ class Renamer(Plugin):
# Unpack any archives
extr_files = None
if self.conf('unrar'):
folder, movie_folder, files, extr_files = self.extractFiles(folder = folder, movie_folder = movie_folder, files = files, \
cleanup = self.conf('cleanup') and not self.downloadIsTorrent(download_info))
folder, movie_folder, files, extr_files = self.extractFiles(folder = folder, movie_folder = movie_folder, files = files,
cleanup = self.conf('cleanup') and not self.downloadIsTorrent(download_info))
groups = fireEvent('scanner.scan', folder = folder if folder else self.conf('from'),
files = files, download_info = download_info, return_ignored = False, single = True)
@@ -347,7 +346,7 @@ class Renamer(Plugin):
profile = db.query(Profile).filter_by(core = True, label = group['meta_data']['quality']['label']).first()
fireEvent('movie.add', params = {'identifier': group['library']['identifier'], 'profile_id': profile.id}, search_after = False)
db.expire_all()
library = db.query(Library).filter_by(identifier = group['library']['identifier']).first()
library_ent = db.query(Library).filter_by(identifier = group['library']['identifier']).first()
for movie in library_ent.movies:
@@ -517,7 +516,7 @@ class Renamer(Plugin):
def tagDir(self, group, tag):
ignore_file = None
if isinstance(group, (dict)):
if isinstance(group, dict):
for movie_file in sorted(list(group['files']['movie'])):
ignore_file = '%s.%s.ignore' % (os.path.splitext(movie_file)[0], tag)
break
@@ -603,9 +602,9 @@ Remove it if you want it to be renamed (again, or at least let it try again)
return True
def doReplace(self, string, replacements, remove_multiple = False):
'''
"""
replace confignames with the real thing
'''
"""
replacements = replacements.copy()
if remove_multiple:
@@ -873,7 +872,7 @@ Remove it if you want it to be renamed (again, or at least let it try again)
#Extract all found archives
for archive in archives:
# Check if it has already been processed by CPS
if (self.hastagDir(os.path.dirname(archive['file']))):
if self.hastagDir(os.path.dirname(archive['file'])):
continue
# Find all related archive files
@@ -970,4 +969,4 @@ Remove it if you want it to be renamed (again, or at least let it try again)
files = []
folder = None
return (folder, movie_folder, files, extr_files)
return folder, movie_folder, files, extr_files
+13 -10
View File
@@ -429,7 +429,7 @@ class Scanner(Plugin):
if len(processed_movies) > 0:
log.info('Found %s movies in the folder %s', (len(processed_movies), folder))
else:
log.debug('Found no movies in the folder %s', (folder))
log.debug('Found no movies in the folder %s', folder)
return processed_movies
@@ -508,6 +508,7 @@ class Scanner(Plugin):
detected_languages = {}
# Subliminal scanner
paths = None
try:
paths = group['files']['movie']
scan_result = []
@@ -560,12 +561,14 @@ class Scanner(Plugin):
break
# Check and see if nfo contains the imdb-id
nfo_file = None
if not imdb_id:
try:
for nfo_file in files['nfo']:
for nf in files['nfo']:
imdb_id = getImdb(nfo_file)
if imdb_id:
log.debug('Found movie via nfo file: %s', nfo_file)
log.debug('Found movie via nfo file: %s', nf)
nfo_file = nf
break
except:
pass
@@ -585,11 +588,12 @@ class Scanner(Plugin):
# Check if path is already in db
if not imdb_id:
db = get_session()
for cur_file in files['movie']:
f = db.query(File).filter_by(path = toUnicode(cur_file)).first()
for cf in files['movie']:
f = db.query(File).filter_by(path = toUnicode(cf)).first()
try:
imdb_id = f.library[0].identifier
log.debug('Found movie via database: %s', cur_file)
log.debug('Found movie via database: %s', cf)
cur_file = cf
break
except:
pass
@@ -680,10 +684,9 @@ class Scanner(Plugin):
return getExt(s.lower()) in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tbn']
files = set(filter(test, files))
images = {}
# Fanart
images['backdrop'] = set(filter(lambda s: re.search('(^|[\W_])fanart|backdrop\d*[\W_]', s.lower()) and self.filesizeBetween(s, 0, 5), files))
images = {
'backdrop': set(filter(lambda s: re.search('(^|[\W_])fanart|backdrop\d*[\W_]', s.lower()) and self.filesizeBetween(s, 0, 5), files))
}
# Rest
images['rest'] = files - images['backdrop']
+1 -1
View File
@@ -17,7 +17,7 @@ class Score(Plugin):
addEvent('score.calculate', self.calculate)
def calculate(self, nzb, movie):
''' Calculate the score of a NZB, used for sorting later '''
""" Calculate the score of a NZB, used for sorting later """
# Merge global and category
preferred_words = splitString(Env.setting('preferred_words', section = 'searcher').lower())
+4 -4
View File
@@ -1,6 +1,6 @@
from couchpotato.core.event import fireEvent
from couchpotato.core.helpers.encoding import simplifyString
from couchpotato.core.helpers.variable import tryInt, splitString
from couchpotato.core.helpers.variable import tryInt
from couchpotato.environment import Env
import re
@@ -24,7 +24,7 @@ name_scores = [
def nameScore(name, year, preferred_words):
''' Calculate score for words in the NZB name '''
""" Calculate score for words in the NZB name """
score = 0
name = name.lower()
@@ -34,11 +34,11 @@ def nameScore(name, year, preferred_words):
v = value.split(':')
add = int(v.pop())
if v.pop() in name:
score = score + add
score += add
# points if the year is correct
if str(year) in name:
score = score + 5
score += 5
# Contains preferred word
nzb_words = re.split('\W+', simplifyString(name))
+1 -1
View File
@@ -75,7 +75,7 @@ class StatusPlugin(Plugin):
def get(self, identifiers):
if not isinstance(identifiers, (list)):
if not isinstance(identifiers, list):
identifiers = [identifiers]
db = get_session()
+1 -1
View File
@@ -36,7 +36,7 @@ class Subtitle(Plugin):
files = []
for file in release.files.filter(FileType.status.has(identifier = 'movie')).all():
files.append(file.path);
files.append(file.path)
# get subtitles for those files
subliminal.list_subtitles(files, cache_dir = Env.get('cache_dir'), multi = True, languages = self.getLanguages(), services = self.services)
@@ -47,6 +47,7 @@ class Suggestion(Plugin):
ignored = splitString(Env.prop('suggest_ignore', default = ''))
new_suggestions = []
if imdb:
if not remove_only:
ignored.append(imdb)