Better variable naming

Thanks to DxCx
This commit is contained in:
Ruud
2011-12-16 22:34:33 +01:00
parent a6f9ad6330
commit 224d1527e1
19 changed files with 96 additions and 95 deletions
+2 -2
View File
@@ -47,10 +47,10 @@ class ClientScript(Plugin):
def registerScript(self, path, position = 'head'):
self.register(path, 'script', position)
def register(self, file, type, location):
def register(self, filepath, type, location):
if not self.urls[type].get(location):
self.urls[type][location] = []
filePath = file
filePath = filepath
self.urls[type][location].append(filePath)
+2 -2
View File
@@ -18,9 +18,9 @@ class Downloader(Plugin):
def download(self, data = {}):
pass
def createFileName(self, data, file, movie):
def createFileName(self, data, filename, movie):
name = os.path.join('%s%s' % (toSafeString(data.get('name')), self.cpTag(movie)))
if data.get('type') == 'nzb' and "DOCTYPE nzb" not in file:
if data.get('type') == 'nzb' and "DOCTYPE nzb" not in filename:
return '%s.%s' % (name, 'rar')
return '%s.%s' % (name, data.get('type'))
@@ -18,19 +18,19 @@ class Blackhole(Downloader):
log.error('No directory set for blackhole %s download.' % data.get('type'))
else:
try:
file = data.get('download')(url = data.get('url'), nzb_id = data.get('id'))
filedata = data.get('download')(url = data.get('url'), nzb_id = data.get('id'))
if len(file) < 50:
if len(filedata) < 50:
log.error('No nzb available!')
return False
fullPath = os.path.join(directory, self.createFileName(data, file, movie))
fullPath = os.path.join(directory, self.createFileName(data, filedata, movie))
try:
if not os.path.isfile(fullPath):
log.info('Downloading %s to %s.' % (data.get('type'), fullPath))
with open(fullPath, 'wb') as f:
f.write(file)
f.write(filedata)
return True
else:
log.info('File %s already exists.' % fullPath)
+4 -4
View File
@@ -42,18 +42,18 @@ class NZBGet(Downloader):
try:
if isfunction(data.get('download')):
file = data.get('download')()
if not file:
filedata = data.get('download')()
if not filedata:
log.error('Failed download file: %s' % nzb_name)
return False
else:
log.info('Downloading: %s' % data.get('url'))
file = self.urlopen(data.get('url'))
filedata = self.urlopen(data.get('url'))
except:
log.error('Unable to get NZB file: %s' % traceback.format_exc())
return False
if rpc.append(nzb_name, self.conf('category'), False, standard_b64encode(file.strip())):
if rpc.append(nzb_name, self.conf('category'), False, standard_b64encode(filedata.strip())):
log.info('NZB sent successfully to NZBGet')
return True
else:
+1 -1
View File
@@ -3,7 +3,7 @@ import xml.etree.ElementTree as XMLTree
log = CPLog(__name__)
class RSS():
class RSS(object):
def getTextElements(self, xml, path):
''' Find elements and return tree'''
+3 -4
View File
@@ -67,10 +67,9 @@ def getImdb(txt):
output.close()
try:
m = re.search('(?P<id>tt[0-9{7}]+)', txt)
id = m.group('id')
if id: return id
except AttributeError:
id = re.findall('imdb\.com\/title\/tt(\d{7})', txt)[0]
return id
except IndexError:
pass
return False
+3 -3
View File
@@ -6,7 +6,7 @@ import traceback
log = CPLog(__name__)
class Loader:
class Loader(object):
plugins = {}
providers = {}
@@ -59,8 +59,8 @@ class Loader:
def addFromDir(self, type, priority, module, dir):
for file in glob.glob(os.path.join(dir, '*')):
name = os.path.basename(file)
for cur_file in glob.glob(os.path.join(dir, '*')):
name = os.path.basename(cur_file)
if os.path.isdir(os.path.join(dir, name)):
module_name = '%s.%s' % (module, name)
self.addModule(priority, type, module_name, name)
+1 -1
View File
@@ -1,7 +1,7 @@
import logging
import re
class CPLog():
class CPLog(object):
context = ''
replace_private = ['api', 'apikey', 'api_key', 'password', 'username', 'h']
@@ -28,7 +28,7 @@ GROWL_TYPE_REGISTRATION = 0
GROWL_TYPE_NOTIFICATION = 1
class GrowlRegistrationPacket:
class GrowlRegistrationPacket(object):
"""Builds a Growl Network Registration packet.
Defaults to emulating the command-line growlnotify utility."""
@@ -70,7 +70,7 @@ class GrowlRegistrationPacket:
self.data += self.checksum.digest()
return self.data
class GrowlNotificationPacket:
class GrowlNotificationPacket(object):
"""Builds a Growl Network Notification packet.
Defaults to emulating the command-line growlnotify utility."""
+8 -8
View File
@@ -57,15 +57,15 @@ class Plugin(object):
class_name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
path = 'static/' + class_name + '/'
addView(path + '<path:file>', self.showStatic, static = True)
addView(path + '<path:filename>', self.showStatic, static = True)
if add_to_head:
for f in glob.glob(os.path.join(self.plugin_path, 'static', '*')):
fireEvent('register_%s' % ('script' if getExt(f) in 'js' else 'style'), path + os.path.basename(f))
def showStatic(self, file = ''):
def showStatic(self, filename):
d = os.path.join(self.plugin_path, 'static')
return send_from_directory(d, file)
return send_from_directory(d, filename)
def createFile(self, path, content):
@@ -81,7 +81,7 @@ class Plugin(object):
def makeDir(self, path):
try:
if not os.path.isdir(path):
os.makedirs(path, Env.getPermission('folder'))
os.makedirs(path, Env.getValuePermission('folder'))
return True
except Exception, e:
log.error('Unable to create folder "%s": %s' % (path, e))
@@ -147,11 +147,11 @@ class Plugin(object):
self.needs_shutdown = value
def isRunning(self, value = None, bool = True):
def isRunning(self, value = None, boolean = True):
if value is None:
return self.running
if bool:
if boolean:
self.running.append(value)
else:
try:
@@ -161,7 +161,7 @@ class Plugin(object):
def getCache(self, cache_key, url = None):
cache = Env.get('cache').get(cache_key)
cache = Env.getValue('cache').get(cache_key)
if cache:
log.debug('Getting cache %s' % cache_key)
return cache
@@ -176,7 +176,7 @@ class Plugin(object):
def setCache(self, cache_key, value, timeout = 300):
log.debug('Setting cache %s' % cache_key)
Env.get('cache').set(cache_key, value, timeout)
Env.getValue('cache').set(cache_key, value, timeout)
return value
def isDisabled(self):
+5 -5
View File
@@ -23,19 +23,19 @@ class FileManager(Plugin):
addEvent('file.download', self.download)
addEvent('file.types', self.getTypes)
addApiView('file.cache/<path:file>', self.showImage)
addApiView('file.cache/<path:filename>', self.showImage)
def showImage(self, file = ''):
def showImage(self, filename = ''):
filename = filename.replace(cache_dir[1:] + '/', '')
cache_dir = Env.get('cache_dir')
filename = file.replace(cache_dir[1:] + '/', '')
return send_from_directory(cache_dir, filename)
def download(self, url = '', dest = None, overwrite = False):
try:
file = self.urlopen(url)
filedata = self.urlopen(url)
except:
return False
@@ -43,7 +43,7 @@ class FileManager(Plugin):
dest = os.path.join(Env.get('cache_dir'), '%s.%s' % (md5(url), getExt(url)))
if overwrite or not os.path.isfile(dest):
self.createFile(dest, file)
self.createFile(dest, filedata)
return dest
+3 -3
View File
@@ -111,10 +111,10 @@ class LibraryPlugin(Plugin):
continue
file_path = fireEvent('file.download', url = image, single = True)
file = fireEvent('file.add', path = file_path, type = ('image', type), single = True)
file_obj = fireEvent('file.add', path = file_path, type = ('image', type), single = True)
try:
file = db.query(File).filter_by(id = file.get('id')).one()
library.files.append(file)
file_obj = db.query(File).filter_by(id = file_obj.get('id')).one()
library.files.append(file_obj)
db.commit()
except:
log.debug('Failed to attach to library: %s' % traceback.format_exc())
@@ -137,7 +137,7 @@ var Profile = new Class({
var self = this;
var label = self.el.getElement('.quality_label input').get('value');
new Question('Are you sure you want to delete <strong>"'+label+'"</strong>?', 'Items using this profile, will be set to the default quality.', [{
var qObj = new Question('Are you sure you want to delete <strong>"'+label+'"</strong>?', 'Items using this profile, will be set to the default quality.', [{
'text': 'Delete "'+label+'"',
'class': 'delete',
'events': {
@@ -152,10 +152,12 @@ var Profile = new Class({
'target': self.el
},
'onComplete': function(json){
if(json.success)
if(json.success) {
qObj.close();
self.el.destroy();
else
alert(json.message)
} else {
alert(json.message);
}
}
});
}
+3 -3
View File
@@ -140,9 +140,9 @@ class QualityPlugin(Plugin):
cached = self.getCache(hash)
if cached: return cached
for file in files:
size = (os.path.getsize(file) / 1024 / 1024) if os.path.isfile(file) else 0
words = re.split('\W+', file.lower())
for cur_file in files:
size = (os.path.getsize(cur_file) / 1024 / 1024) if os.path.isfile(cur_file) else 0
words = re.split('\W+', cur_file.lower())
for quality in self.all():
+5 -5
View File
@@ -56,19 +56,19 @@ class Release(Plugin):
# Add each file type
for type in group['files']:
for file in group['files'][type]:
added_file = self.saveFile(file, type = type, include_media_info = type is 'movie')
for cur_file in group['files'][type]:
added_file = self.saveFile(cur_file, type = type, include_media_info = type is 'movie')
try:
added_file = db.query(File).filter_by(id = added_file.get('id')).one()
rel.files.append(added_file)
db.commit()
except Exception, e:
log.debug('Failed to attach "%s" to release: %s' % (file, e))
log.debug('Failed to attach "%s" to release: %s' % (cur_file, e))
db.remove()
def saveFile(self, file, type = 'unknown', include_media_info = False):
def saveFile(self, filepath, type = 'unknown', include_media_info = False):
properties = {}
@@ -77,7 +77,7 @@ class Release(Plugin):
properties = {}
# Check database and update/insert if necessary
return fireEvent('file.add', path = file, part = fireEvent('scanner.partnumber', file, single = True), type = Scanner.file_types.get(type), properties = properties, single = True)
return fireEvent('file.add', path = filepath, part = fireEvent('scanner.partnumber', file, single = True), type = Scanner.file_types.get(type), properties = properties, single = True)
def delete(self):
+12 -12
View File
@@ -119,14 +119,14 @@ class Renamer(Plugin):
multiple = len(group['files']['movie']) > 1 and not group['is_dvd']
cd = 1 if multiple else 0
for file in sorted(list(group['files'][file_type])):
for current_file in sorted(list(group['files'][file_type])):
# Original filename
replacements['original'] = os.path.basename(file)
replacements['original_folder'] = os.path.basename(os.path.dirname(file))
replacements['original'] = os.path.basename(current_file)
replacements['original_folder'] = os.path.basename(os.path.dirname(current_file))
# Extension
replacements['ext'] = getExt(file)
replacements['ext'] = getExt(current_file)
# cd #
replacements['cd'] = ' cd%d' % cd if cd else ''
@@ -205,8 +205,8 @@ class Renamer(Plugin):
# Mark movie "done" onces it found the quality with the finish check
try:
if movie.status_id == active_status.get('id'):
for type in movie.profile.types:
if type.quality_id == group['meta_data']['quality']['id'] and type.finish:
for profile_type in movie.profile.types:
if profile_type.quality_id == group['meta_data']['quality']['id'] and type.finish:
movie.status_id = done_status.get('id')
db.commit()
except Exception, e:
@@ -221,14 +221,14 @@ class Renamer(Plugin):
# This is where CP removes older, lesser quality releases
if release.quality.order > group['meta_data']['quality']['order']:
log.info('Removing lesser quality %s for %s.' % (movie.library.titles[0].title, release.quality.label))
for file in release.files:
remove_files.append(file)
for current_file in release.files:
remove_files.append(current_file)
remove_releases.append(release)
# Same quality, but still downloaded, so maybe repack/proper/unrated/directors cut etc
elif release.quality.order is group['meta_data']['quality']['order']:
log.info('Same quality release already exists for %s, with quality %s. Assuming repack.' % (movie.library.titles[0].title, release.quality.label))
for file in release.files:
remove_files.append(file)
for current_file in release.files:
remove_files.append(current_file)
remove_releases.append(release)
# Downloaded a lower quality, rename the newly downloaded files/folder to exclude them from scan
@@ -254,8 +254,8 @@ class Renamer(Plugin):
# Remove leftover files
if self.conf('cleanup') and not self.conf('move_leftover'):
log.debug('Removing leftover files')
for file in group['files']['leftover']:
remove_files.append(file)
for current_file in group['files']['leftover']:
remove_files.append(current_file)
# Rename all files marked
for src in rename_files:
+22 -22
View File
@@ -196,8 +196,8 @@ class Scanner(Plugin):
# Check if movie is fresh and maybe still unpacking, ignore files new then 1 minute
file_too_new = False
for file in group['unsorted_files']:
file_time = os.path.getmtime(file)
for cur_file in group['unsorted_files']:
file_time = os.path.getmtime(cur_file)
if file_time > time.time() - 60:
file_too_new = tryInt(time.time() - file_time)
break
@@ -265,13 +265,13 @@ class Scanner(Plugin):
data = {}
files = list(group['files']['movie'])
for file in files:
if os.path.getsize(file) < self.minimal_filesize['media']: continue # Ignore smaller files
for cur_file in files:
if os.path.getsize(cur_file) < self.minimal_filesize['media']: continue # Ignore smaller files
meta = self.getMeta(file)
meta = self.getMeta(cur_file)
try:
data['video'] = self.getCodec(file, self.codecs['video'])
data['video'] = self.getCodec(cur_file, self.codecs['video'])
data['audio'] = meta['audio stream'][0]['compression']
data['resolution_width'] = meta['video stream'][0]['image width']
data['resolution_height'] = meta['video stream'][0]['image height']
@@ -286,9 +286,9 @@ class Scanner(Plugin):
data['quality_type'] = 'HD' if data.get('resolution_width', 0) >= 1280 else 'SD'
file = re.sub('(.cp\(tt[0-9{7}]+\))', '', files[0])
data['group'] = self.getGroup(file)
data['source'] = self.getSourceMedia(file)
filename = re.sub('(.cp\(tt[0-9{7}]+\))', '', files[0])
data['group'] = self.getGroup(filename)
data['source'] = self.getSourceMedia(filename)
return data
@@ -311,8 +311,8 @@ class Scanner(Plugin):
files = group['files']
# Check for CP(imdb_id) string in the file paths
for file in files['movie']:
imdb_id = self.getCPImdb(file)
for cur_file in files['movie']:
imdb_id = self.getCPImdb(cur_file)
if imdb_id: break
# Check and see if nfo contains the imdb-id
@@ -327,8 +327,8 @@ class Scanner(Plugin):
# Check if path is already in db
if not imdb_id:
db = get_session()
for file in files['movie']:
f = db.query(File).filter_by(path = toUnicode(file)).first()
for cur_file in files['movie']:
f = db.query(File).filter_by(path = toUnicode(cur_file)).first()
try:
imdb_id = f.library[0].identifier
break
@@ -338,8 +338,8 @@ class Scanner(Plugin):
# Search based on OpenSubtitleHash
if not imdb_id and not group['is_dvd']:
for file in files['movie']:
movie = fireEvent('movie.by_hash', file = file, merge = True)
for cur_file in files['movie']:
movie = fireEvent('movie.by_hash', file = cur_file, merge = True)
if len(movie) > 0:
imdb_id = movie[0]['imdb']
@@ -437,22 +437,22 @@ class Scanner(Plugin):
return False
def keepFile(self, file):
def keepFile(self, filename):
# ignoredpaths
for i in self.ignored_in_path:
if i in file.lower():
log.debug('Ignored "%s" contains "%s".' % (file, i))
if i in filename.lower():
log.debug('Ignored "%s" contains "%s".' % (filename, i))
return False
# Sample file
if re.search('(^|[\W_])sample\d*[\W_]', file.lower()):
log.debug('Is sample file "%s".' % file)
if re.search('(^|[\W_])sample\d*[\W_]', filename.lower()):
log.debug('Is sample file "%s".' % filename)
return False
# Minimal size
if self.filesizeBetween(file, self.minimal_filesize['media']):
log.debug('File to small: %s' % file)
if self.filesizeBetween(filename, self.minimal_filesize['media']):
log.debug('File to small: %s' % filename)
return False
# All is OK
+9 -9
View File
@@ -22,24 +22,24 @@ class MetaDataBase(Plugin):
root = self.getRootName(release)
for type in ['nfo', 'thumbnail', 'fanart']:
for file_type in ['nfo', 'thumbnail', 'fanart']:
try:
# Get file path
name = getattr(self, 'get' + type.capitalize() + 'Name')(root)
name = getattr(self, 'get' + file_type.capitalize() + 'Name')(root)
if name and self.conf('meta_' + type):
if name and self.conf('meta_' + file_type):
# Get file content
content = getattr(self, 'get' + type.capitalize())(release)
content = getattr(self, 'get' + file_type.capitalize())(release)
if content:
log.debug('Creating %s file: %s' % (type, name))
log.debug('Creating %s file: %s' % (file_type, name))
if os.path.isfile(content):
shutil.copy2(content, name)
else:
self.createFile(name, content)
except Exception, e:
log.error('Unable to create %s file: %s' % (type, traceback.format_exc()))
log.error('Unable to create %s file: %s' % (file_type, traceback.format_exc()))
def getRootName(self, data):
return
@@ -62,9 +62,9 @@ class MetaDataBase(Plugin):
if type.get('identifier') == file_type:
break
for file in data['library'].get('files'):
if file.get('type_id') is type.get('id'):
return file.get('path')
for cur_file in data['library'].get('files'):
if cur_file.get('type_id') is type.get('id'):
return cur_file.get('path')
def getFanart(self, data):
return self.getThumbnail(data, file_type = 'backdrop_original')
+1 -1
View File
@@ -1,7 +1,7 @@
from couchpotato.core.loader import Loader
from couchpotato.core.settings import Settings
class Env:
class Env(object):
''' Environment variables '''
_uses_git = False