diff options
author | Walter Purcaro <vuolter@gmail.com> | 2014-12-01 23:53:07 +0100 |
---|---|---|
committer | Walter Purcaro <vuolter@gmail.com> | 2014-12-01 23:53:07 +0100 |
commit | 004a80bfaad38f9400e8aebcb8f980353a232295 (patch) | |
tree | 1e786d2d14a3040767aac237982544b74a9567cb /pyload | |
parent | Fix previous merge (diff) | |
download | pyload-004a80bfaad38f9400e8aebcb8f980353a232295.tar.xz |
PEP-8, Python Zen, refactor and reduce code (thx FedeG)
Diffstat (limited to 'pyload')
91 files changed, 315 insertions, 390 deletions
diff --git a/pyload/Core.py b/pyload/Core.py index b7317cf0f..a555ba3ff 100644 --- a/pyload/Core.py +++ b/pyload/Core.py @@ -210,7 +210,7 @@ class Core(object): if not pid or os.name == "nt": return False try: os.kill(pid, 0) # 0 - default signal (does nothing) - except: + except Exception: return 0 return pid @@ -241,7 +241,7 @@ class Core(object): print "pyLoad did not respond" print "Kill signal was send to process with id %s" % pid - except: + except Exception: print "Error quitting pyLoad" @@ -275,7 +275,7 @@ class Core(object): pass except KeyboardInterrupt: print "\nSetup interrupted" - except: + except Exception: res = False print_exc() print "Setup failed" @@ -285,7 +285,7 @@ class Core(object): exit() try: signal.signal(signal.SIGQUIT, self.quit) - except: pass + except Exception: pass self.config = ConfigParser() @@ -503,7 +503,7 @@ class Core(object): subprocess.Popen(check_name, stdout=pipe, stderr=pipe) return True - except: + except Exception: if essential: self.log.info(_("Install %s") % legend) exit() @@ -529,7 +529,7 @@ class Core(object): makedirs(tmp_name) else: open(tmp_name, "w") - except: + except Exception: file_created = False else: file_created = False @@ -578,7 +578,7 @@ class Core(object): self.addonManager.coreExiting() - except: + except Exception: if self.debug: print_exc() self.log.info(_("error while shutting down")) diff --git a/pyload/InitHomeDir.py b/pyload/InitHomeDir.py index ca229fb1e..bf60e6abc 100644 --- a/pyload/InitHomeDir.py +++ b/pyload/InitHomeDir.py @@ -76,4 +76,4 @@ if not path.exists(configdir): __builtin__.configdir = configdir chdir(configdir) -#print "Using %s as working directory." % configdir +# print "Using %s as working directory." % configdir diff --git a/pyload/api/__init__.py b/pyload/api/__init__.py index e7e082ecd..365828d0a 100644 --- a/pyload/api/__init__.py +++ b/pyload/api/__init__.py @@ -31,12 +31,17 @@ from utils import compare_time, freeSpace, html_unescape, save_filename if activated: try: + from lib.thrift.protocol import TBase from remote.thriftbackend.thriftgen.pyload.ttypes import * from remote.thriftbackend.thriftgen.pyload.Pyload import Iface + BaseObject = TBase + except ImportError: - print "Thrift not imported" from pyload.api.types import * + + print "Thrift not imported" + else: from pyload.api.types import * @@ -44,34 +49,37 @@ else: # unlisted functions are for admins only permMap = {} + # decorator only called on init, never initialized, so has no effect on runtime def permission(bits): class _Dec(object): def __new__(cls, func, *args, **kwargs): permMap[func.__name__] = bits return func - return _Dec urlmatcher = re.compile(r"((https?|ftps?|xdcc|sftp):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+\-=\\\.&\[\]\|]*)", re.IGNORECASE) -class PERMS: + +class PERMS(object): ALL = 0 # requires no permission, but login ADD = 1 # can add packages - DELETE = 2 # can delete packages - STATUS = 4 # see and change server status - LIST = 16 # see queue and collector - MODIFY = 32 # moddify some attribute of downloads + DELETE = 2 # can delete packages + STATUS = 4 # see and change server status + LIST = 16 # see queue and collector + MODIFY = 32 # moddify some attribute of downloads DOWNLOAD = 64 # can download from webinterface - SETTINGS = 128 # can access settings - ACCOUNTS = 256 # can access accounts - LOGS = 512 # can see server logs + SETTINGS = 128 # can access settings + ACCOUNTS = 256 # can access accounts + LOGS = 512 # can see server logs + -class ROLE: - ADMIN = 0 #admin has all permissions implicit +class ROLE(object): + ADMIN = 0 # admin has all permissions implicit USER = 1 + def has_permission(userperms, perms): # bytewise or perms before if needed return perms == (userperms & perms) @@ -90,17 +98,16 @@ class Api(Iface): These can be configured via webinterface. Admin user have all permissions, and are the only ones who can access the methods with no specific permission. """ - EXTERNAL = Iface # let the json api know which methods are external def __init__(self, core): self.core = core def _convertPyFile(self, p): - f = FileData(p["id"], p["url"], p["name"], p["plugin"], p["size"], - p["format_size"], p["status"], p["statusmsg"], - p["package"], p["error"], p["order"]) - return f + fdata = FileData(p["id"], p["url"], p["name"], p["plugin"], p["size"], + p["format_size"], p["status"], p["statusmsg"], + p["package"], p["error"], p["order"]) + return fdata def _convertConfigFormat(self, c): sections = {} @@ -135,8 +142,7 @@ class Api(Iface): value = self.core.config[category][option] else: value = self.core.config.getPlugin(category, option) - - return str(value) if not isinstance(value, basestring) else value + return str(value) @permission(PERMS.SETTINGS) def setConfigValue(self, category, option, value, section="core"): @@ -148,13 +154,10 @@ class Api(Iface): :param section: 'plugin' or 'core """ self.core.addonManager.dispatchEvent("configChanged", category, option, value, section) - if section == "core": self.core.config[category][option] = value - - if option in ("limit_speed", "max_speed"): #not so nice to update the limit + if option in ("limit_speed", "max_speed"): # not so nice to update the limit self.core.requestFactory.updateBucket() - elif section == "plugin": self.core.config.setPlugin(category, option, value) @@ -188,7 +191,6 @@ class Api(Iface): """ return self.core.config.plugin - @permission(PERMS.STATUS) def pauseServer(self): """Pause server: Tt wont start any new downloads, but nothing gets aborted.""" @@ -227,10 +229,8 @@ class Api(Iface): self.core.files.getQueueCount(), self.core.files.getFileCount(), 0, not self.core.threadManager.pause and self.isTimeDownload(), self.core.config['reconnect']['activated'] and self.isTimeReconnect()) - for pyfile in [x.active for x in self.core.threadManager.threads if x.active and isinstance(x.active, PyFile)]: - serverStatus.speed += pyfile.getSpeed() #bytes/s - + serverStatus.speed += pyfile.getSpeed() # bytes/s return serverStatus @permission(PERMS.STATUS) @@ -266,7 +266,7 @@ class Api(Iface): if offset >= len(lines): return [] return lines[offset:] - except: + except Exception: return ['No log available'] @permission(PERMS.STATUS) @@ -299,13 +299,11 @@ class Api(Iface): for pyfile in self.core.threadManager.getActiveFiles(): if not isinstance(pyfile, PyFile): continue - data.append(DownloadInfo( pyfile.id, pyfile.name, pyfile.getSpeed(), pyfile.getETA(), pyfile.formatETA(), pyfile.getBytesLeft(), pyfile.getSize(), pyfile.formatSize(), pyfile.getPercent(), pyfile.status, pyfile.getStatusName(), pyfile.formatWait(), pyfile.waitUntil, pyfile.packageid, pyfile.package().name, pyfile.pluginname)) - return data @permission(PERMS.ADD) @@ -342,18 +340,14 @@ class Api(Iface): :return: """ urls = [] - if html: urls += [x[0] for x in urlmatcher.findall(html)] - if url: page = getURL(url) urls += [x[0] for x in urlmatcher.findall(page)] - # remove duplicates return self.checkURLs(set(urls)) - @permission(PERMS.ADD) def checkURLs(self, urls): """ Gets urls and returns pluginname mapped to list of matches urls. @@ -367,7 +361,7 @@ class Api(Iface): for url, plugintype, pluginname in data: try: plugins[plugintype][pluginname].append(url) - except: + except Exception: plugins[plugintype][pluginname] = [url] return plugins @@ -386,7 +380,6 @@ class Api(Iface): tmp = [(url, (url, OnlineStatus(url, (plugintype, pluginname), "unknown", 3, 0))) for url, plugintype, pluginname in data] data = parseNames(tmp) result = {} - for k, v in data.iteritems(): for url, status in v: status.packagename = k @@ -406,7 +399,6 @@ class Api(Iface): th = open(join(self.core.config["general"]["download_folder"], "tmp_" + container), "wb") th.write(str(data)) th.close() - return self.checkOnlineStatus(urls + [th.name]) @permission(PERMS.ADD) @@ -417,14 +409,12 @@ class Api(Iface): :return: `OnlineCheck`, if rid is -1 then no more data available """ result = self.core.threadManager.getInfoResult(rid) - if "ALL_INFO_FETCHED" in result: del result["ALL_INFO_FETCHED"] return OnlineCheck(-1, result) else: return OnlineCheck(rid, result) - @permission(PERMS.ADD) def generatePackages(self, links): """ Parses links, generates packages names from urls @@ -432,8 +422,7 @@ class Api(Iface): :param links: list of urls :return: package names mapped to urls """ - result = parseNames((x, x) for x in links) - return result + return parseNames((x, x) for x in links) @permission(PERMS.ADD) def generateAndAddPackages(self, links, dest=Destination.Queue): @@ -458,7 +447,6 @@ class Api(Iface): data = self.core.pluginManager.parseUrls(links) self.core.threadManager.createResultThread(data, True) - @permission(PERMS.LIST) def getPackageData(self, pid): """Returns complete information about package, and included files. @@ -467,15 +455,11 @@ class Api(Iface): :return: `PackageData` with .links attribute """ data = self.core.files.getPackageData(int(pid)) - if not data: raise PackageDoesNotExists(pid) - - pdata = PackageData(data["id"], data["name"], data["folder"], data["site"], data["password"], - data["queue"], data["order"], - links=[self._convertPyFile(x) for x in data["links"].itervalues()]) - - return pdata + return PackageData(data["id"], data["name"], data["folder"], data["site"], data["password"], + data["queue"], data["order"], + links=[self._convertPyFile(x) for x in data["links"].itervalues()]) @permission(PERMS.LIST) def getPackageInfo(self, pid): @@ -488,12 +472,9 @@ class Api(Iface): if not data: raise PackageDoesNotExists(pid) - - pdata = PackageData(data["id"], data["name"], data["folder"], data["site"], data["password"], - data["queue"], data["order"], - fids=[int(x) for x in data["links"]]) - - return pdata + return PackageData(data["id"], data["name"], data["folder"], data["site"], data["password"], + data["queue"], data["order"], + fids=[int(x) for x in data["links"]]) @permission(PERMS.LIST) def getFileData(self, fid): @@ -505,9 +486,7 @@ class Api(Iface): info = self.core.files.getFileData(int(fid)) if not info: raise FileDoesNotExists(fid) - - fdata = self._convertPyFile(info.values()[0]) - return fdata + return self._convertPyFile(info.values()[0]) @permission(PERMS.DELETE) def deleteFiles(self, fids): @@ -515,9 +494,8 @@ class Api(Iface): :param fids: list of file ids """ - for id in fids: - self.core.files.deleteLink(int(id)) - + for fid in fids: + self.core.files.deleteLink(int(fid)) self.core.files.save() @permission(PERMS.DELETE) @@ -526,9 +504,8 @@ class Api(Iface): :param pids: list of package ids """ - for id in pids: - self.core.files.deletePackage(int(id)) - + for pid in pids: + self.core.files.deletePackage(int(pid)) self.core.files.save() @permission(PERMS.LIST) @@ -581,7 +558,6 @@ class Api(Iface): links=[self._convertPyFile(x) for x in pack["links"].itervalues()]) for pack in self.core.files.getCompleteData(Destination.Collector).itervalues()] - @permission(PERMS.ADD) def addFiles(self, pid, links): """Adds files to specific package. @@ -590,7 +566,6 @@ class Api(Iface): :param links: list of urls """ self.core.files.addLinks(links, int(pid)) - self.core.log.info(_("Added %(count)d links to package #%(package)d ") % {"count": len(links), "package": pid}) self.core.files.save() @@ -651,7 +626,6 @@ class Api(Iface): :return: """ pyfiles = self.core.files.cache.values() - for pyfile in pyfiles: if pyfile.id in fids: pyfile.abortDownload() @@ -674,8 +648,8 @@ class Api(Iface): :param destination: `Destination` :param pid: package id """ - if destination not in (0, 1): return - self.core.files.setPackageLocation(pid, destination) + if destination in (0, 1): + self.core.files.setPackageLocation(pid, destination) @permission(PERMS.MODIFY) def moveFiles(self, fids, pid): @@ -685,7 +659,7 @@ class Api(Iface): :param pid: destination package :return: """ - #TODO: implement + # TODO: implement pass @@ -699,7 +673,6 @@ class Api(Iface): th = open(join(self.core.config["general"]["download_folder"], "tmp_" + filename), "wb") th.write(str(data)) th.close() - self.addPackage(th.name, [th.name], Destination.Queue) @permission(PERMS.MODIFY) @@ -727,14 +700,14 @@ class Api(Iface): :param pid: package id :param data: dict that maps attribute to desired value """ - p = self.core.files.getPackage(pid) - if not p: raise PackageDoesNotExists(pid) - + package = self.core.files.getPackage(pid) + if not package: + raise PackageDoesNotExists(pid) for key, value in data.iteritems(): - if key == "id": continue - setattr(p, key, value) - - p.sync() + if key == "id": + continue + setattr(package, key, value) + package.sync() self.core.files.save() @permission(PERMS.DELETE) @@ -757,13 +730,11 @@ class Api(Iface): :param destination: `Destination` :return: dict mapping order to package id """ - packs = self.core.files.getInfoData(destination) order = {} - for pid in packs: pack = self.core.files.getPackageData(int(pid)) - while pack["order"] in order.keys(): #just in case + while pack["order"] in order.keys(): # just in case pack["order"] += 1 order[pack["order"]] = pack["id"] return order @@ -775,10 +746,10 @@ class Api(Iface): :param pid: :return: dict mapping order to file id """ - rawData = self.core.files.getPackageData(int(pid)) + rawdata = self.core.files.getPackageData(int(pid)) order = {} - for id, pyfile in rawData["links"].iteritems(): - while pyfile["order"] in order.keys(): #just in case + for id, pyfile in rawdata["links"].iteritems(): + while pyfile["order"] in order.keys(): # just in case pyfile["order"] += 1 order[pyfile["order"]] = pyfile["id"] return order @@ -806,10 +777,9 @@ class Api(Iface): if task: task.setWatingForUser(exclusive=exclusive) data, type, result = task.getCaptcha() - t = CaptchaTask(int(task.id), standard_b64encode(data), type, result) - return t - else: - return CaptchaTask(-1) + ctask = CaptchaTask(int(task.id), standard_b64encode(data), type, result) + return ctask + return CaptchaTask(-1) @permission(PERMS.STATUS) def getCaptchaTaskStatus(self, tid): @@ -819,8 +789,8 @@ class Api(Iface): :return: string """ self.core.lastClientConnected = time() - t = self.core.captchaManager.getTaskByID(tid) - return t.getStatus() if t else "" + task = self.core.captchaManager.getTaskByID(tid) + return task.getStatus() if task else "" @permission(PERMS.STATUS) def setCaptchaResult(self, tid, result): @@ -835,7 +805,6 @@ class Api(Iface): task.setResult(result) self.core.captchaManager.removeTask(task) - @permission(PERMS.STATUS) def getEvents(self, uuid): """Lists occured events, may be affected to changes in future. @@ -844,7 +813,7 @@ class Api(Iface): :return: list of `Events` """ events = self.core.pullManager.getEvents(uuid) - newEvents = [] + new_events = [] def convDest(d): return Destination.Queue if d == "queue" else Destination.Collector @@ -863,8 +832,8 @@ class Api(Iface): event.destination = convDest(e[3]) elif e[0] == "reload": event.destination = convDest(e[1]) - newEvents.append(event) - return newEvents + new_events.append(event) + return new_events @permission(PERMS.ACCOUNTS) def getAccounts(self, refresh): @@ -874,12 +843,11 @@ class Api(Iface): :return: list of `AccountInfo` """ accs = self.core.accountManager.getAccountInfos(False, refresh) - accounts = [] for group in accs.values(): - accounts.extend([AccountInfo(acc["validuntil"], acc["login"], acc["options"], acc["valid"], - acc["trafficleft"], acc["maxtraffic"], acc["premium"], acc["type"]) - for acc in group]) - return accounts + accounts = [AccountInfo(acc["validuntil"], acc["login"], acc["options"], acc["valid"], + acc["trafficleft"], acc["maxtraffic"], acc["premium"], acc["type"]) + for acc in group] + return accounts or [] @permission(PERMS.ALL) def getAccountTypes(self): @@ -890,9 +858,9 @@ class Api(Iface): return self.core.accountManager.accounts.keys() @permission(PERMS.ACCOUNTS) - def updateAccount(self, plugin, account, password=None, options={}): + def updateAccount(self, plugin, account, password=None, options=None): """Changes pw/options for specific account.""" - self.core.accountManager.updateAccount(plugin, account, password, options) + self.core.accountManager.updateAccount(plugin, account, password, options or {}) @permission(PERMS.ACCOUNTS) def removeAccount(self, plugin, account): @@ -912,7 +880,7 @@ class Api(Iface): :param remoteip: Omit this argument, its only used internal :return: bool indicating login was successful """ - return True if self.checkAuth(username, password, remoteip) else False + return bool(self.checkAuth(username, password, remoteip)) def checkAuth(self, username, password, remoteip=None): """Check authentication and returns details @@ -941,24 +909,19 @@ class Api(Iface): else: return False - @permission(PERMS.ALL) def getUserData(self, username, password): """similar to `checkAuth` but returns UserData thrift type """ - user = self.checkAuth(username, password) + user = self.checkAuth(username, password) if user: return UserData(user["name"], user["email"], user["role"], user["permission"], user["template"]) else: return UserData() - def getAllUserData(self): """returns all known user and info""" - res = {} - for user, data in self.core.db.getAllUserData().iteritems(): - res[user] = UserData(user, data["email"], data["role"], data["permission"], data["template"]) - - return res + return dict((user, UserData(user, data["email"], data["role"], data["permission"], data["template"])) for user, data + in self.core.db.getAllUserData().iteritems()) @permission(PERMS.STATUS) def getServices(self): @@ -966,11 +929,7 @@ class Api(Iface): :return: dict with this style: {"plugin": {"method": "description"}} """ - data = {} - for plugin, funcs in self.core.addonManager.methods.iteritems(): - data[plugin] = funcs - - return data + return dict((plugin, funcs) for plugin, funcs in self.core.addonManager.methods.iteritems()) @permission(PERMS.STATUS) def hasService(self, plugin, func): @@ -996,13 +955,10 @@ class Api(Iface): func = info.func args = info.arguments parse = info.parseArguments - if not self.hasService(plugin, func): raise ServiceDoesNotExists(plugin, func) - try: ret = self.core.addonManager.callRPC(plugin, func, args, parse) - return str(ret) except Exception, e: raise ServiceException(e.message) @@ -1027,6 +983,6 @@ class Api(Iface): """ changes password for specific user """ return self.core.db.changePassword(user, oldpw, newpw) - def setUserPermission(self, user, permission, role): - self.core.db.setPermission(user, permission) + def setUserPermission(self, user, perm, role): + self.core.db.setPermission(user, perm) self.core.db.setRole(user, role) diff --git a/pyload/api/types.py b/pyload/api/types.py index a945e322a..81385bf9f 100644 --- a/pyload/api/types.py +++ b/pyload/api/types.py @@ -5,11 +5,11 @@ class BaseObject(object): __slots__ = [] -class Destination: +class Destination(object): Collector = 0 Queue = 1 -class DownloadStatus: +class DownloadStatus(object): Aborted = 9 Custom = 11 Decrypting = 10 @@ -26,11 +26,11 @@ class DownloadStatus: Unknown = 14 Waiting = 5 -class ElementType: +class ElementType(object): File = 1 Package = 0 -class Input: +class Input(object): BOOL = 4 CHOICE = 6 CLICK = 5 @@ -42,7 +42,7 @@ class Input: TEXT = 1 TEXTBOX = 2 -class Output: +class Output(object): CAPTCHA = 1 NOTIFICATION = 4 QUESTION = 2 @@ -238,7 +238,7 @@ class UserData(BaseObject): self.permission = permission self.templateName = templateName -class Iface: +class Iface(object): def addFiles(self, pid, links): pass def addPackage(self, name, links, dest): diff --git a/pyload/cli/AddPackage.py b/pyload/cli/AddPackage.py index cc0bf2f7c..b4e978bc5 100644 --- a/pyload/cli/AddPackage.py +++ b/pyload/cli/AddPackage.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -#Copyright (C) 2011-2014 RaNaN +# Copyright (C) 2011-2014 RaNaN # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by @@ -20,6 +20,7 @@ from pyload.cli.Handler import Handler from pyload.utils.printer import * + class AddPackage(Handler): """ let the user add packages """ diff --git a/pyload/cli/Cli.py b/pyload/cli/Cli.py index f05e98b1a..cc285f060 100644 --- a/pyload/cli/Cli.py +++ b/pyload/cli/Cli.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -#Copyright (C) 2008-2014 RaNaN +# Copyright (C) 2008-2014 RaNaN # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by @@ -50,7 +50,7 @@ from pyload.remote.thriftbackend.ThriftClient import ThriftClient, NoConnection, from Getch import Getch from rename_process import renameProcess -class Cli: +class Cli(object): def __init__(self, client, command): self.client = client self.command = command @@ -468,7 +468,7 @@ def writeConfig(opts): cfgfile.write("[cli]") for opt in opts: cfgfile.write("%s=%s\n" % (opt, opts[opt])) - except: + except Exception: print _("Couldn't write user config file") @@ -476,7 +476,7 @@ def main(): config = {"addr": "127.0.0.1", "port": "7227", "language": "en"} try: config["language"] = os.environ["LANG"][0:2] - except: + except Exception: pass if (not exists(join(pypath, "locale", config["language"]))) or config["language"] == "": diff --git a/pyload/cli/Handler.py b/pyload/cli/Handler.py index 37b0d7b99..6ded952ec 100644 --- a/pyload/cli/Handler.py +++ b/pyload/cli/Handler.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -#Copyright (C) 2011-2014 RaNaN +# Copyright (C) 2011-2014 RaNaN # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by @@ -16,7 +16,9 @@ # along with this program; if not, see <http://www.gnu.org/licenses/>. # ### -class Handler: + + +class Handler(object): def __init__(self, cli): self.cli = cli self.init() diff --git a/pyload/cli/ManageFiles.py b/pyload/cli/ManageFiles.py index 335ea1ec1..9bf49c54c 100644 --- a/pyload/cli/ManageFiles.py +++ b/pyload/cli/ManageFiles.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -#Copyright (C) 2011-2014 RaNaN +# Copyright (C) 2011-2014 RaNaN # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by @@ -25,15 +25,15 @@ from pyload.utils.printer import * from pyload.api import Destination, PackageData + class ManageFiles(Handler): """ possibility to manage queue/collector """ def init(self): self.target = Destination.Queue - self.pos = 0 #position in queue + self.pos = 0 #position in queue self.package = -1 #choosen package - self.mode = "" # move/delete/restart - + self.mode = "" # move/delete/restart self.cache = None self.links = None self.time = 0 @@ -81,7 +81,7 @@ class ManageFiles(Handler): #look into package try: self.package = int(input) - except: + except Exception: pass self.cache = None @@ -90,7 +90,6 @@ class ManageFiles(Handler): self.mode = "" self.setInput() - def renderBody(self, line): if self.package < 0: println(line, white(_("Manage Packages:"))) @@ -111,7 +110,7 @@ class ManageFiles(Handler): else: println(line, _("Choose what yout want to do or enter package number.")) println(line + 1, ("%s - %%s, %s - %%s, %s - %%s" % (mag("d"), mag("m"), mag("r"))) % ( - _("delete"), _("move"), _("restart"))) + _("delete"), _("move"), _("restart"))) line += 2 if self.package < 0: @@ -135,7 +134,7 @@ class ManageFiles(Handler): for value in islice(pack.links, self.pos, self.pos + 5): try: println(line, mag(value.fid) + ": %s | %s | %s" % ( - value.name, value.statusmsg, value.plugin)) + value.name, value.statusmsg, value.plugin)) line += 1 i += 1 except Exception, e: @@ -146,10 +145,8 @@ class ManageFiles(Handler): println(line, mag("p") + _(" - previous") + " | " + mag("n") + _(" - next")) println(line + 1, mag("0.") + _(" back to main menu")) - return line + 2 - def getPackages(self): if self.cache and self.time + 2 < time(): return self.cache @@ -159,7 +156,6 @@ class ManageFiles(Handler): else: data = self.client.getCollector() - self.cache = data self.time = time() @@ -168,15 +164,12 @@ class ManageFiles(Handler): def getLinks(self): if self.links and self.time + 1 < time(): return self.links - try: data = self.client.getPackageData(self.package) - except: + except Exception: data = PackageData(links=[]) - self.links = data self.time = time() - return data def parseInput(self, inp, package=True): @@ -196,8 +189,6 @@ class ManageFiles(Handler): for l in self.links.links: if l.lid in r: ret.append(l.lid) - return ret - else: return [int(x) for x in inp.split(",")] diff --git a/pyload/config/Parser.py b/pyload/config/Parser.py index 33f048150..50d862575 100644 --- a/pyload/config/Parser.py +++ b/pyload/config/Parser.py @@ -10,7 +10,7 @@ from utils import chmod, encode, decode CONF_VERSION = 1 -class ConfigParser: +class ConfigParser(object): """ holds and manage the configuration @@ -30,20 +30,17 @@ class ConfigParser: """ - def __init__(self): """Constructor""" - self.config = {} # the config values - self.plugin = {} # the config for plugins + self.config = {} #: the config values + self.plugin = {} #: the config for plugins self.oldRemoteData = {} - self.pluginCB = None # callback when plugin config value is changed + self.pluginCB = None #: callback when plugin config value is changed self.checkVersion() self.readConfig() - - def checkVersion(self, n=0): """determines if config need to be copied""" try: @@ -74,16 +71,14 @@ class ConfigParser: f.write("version: " + str(CONF_VERSION)) f.close() print "Old version of plugin-config replaced" - except: - if n < 3: - sleep(0.3) - self.checkVersion(n + 1) - else: + except Exception: + if n >= 3: raise + sleep(0.3) + self.checkVersion(n + 1) def readConfig(self): """reads the config file""" - self.config = self.parseConfig(join(pypath, "pyload", "config", "default.conf")) self.plugin = self.parseConfig("plugin.conf") @@ -96,12 +91,10 @@ class ConfigParser: del homeconf["remote"]["password"] del homeconf["remote"]["username"] self.updateValues(homeconf, self.config) - - except Exception, e: + except Exception: print "Config Warning" print_exc() - def parseConfig(self, config): """parses a given configfile""" @@ -120,7 +113,7 @@ class ConfigParser: for line in config: comment = line.rfind("#") if line.find(":", comment) < 0 > line.find("=", comment) and comment > 0 and line[comment - 1].isspace(): - line = line.rpartition("#") # removes comments + line = line.rpartition("#") #: removes comments if line[1]: line = line[0] else: @@ -184,7 +177,6 @@ class ConfigParser: f.close() return conf - def updateValues(self, config, dest): """sets the config values from a parsed config file to values in destination""" @@ -196,7 +188,7 @@ class ConfigParser: if option in dest[section]: dest[section][option]["value"] = config[section][option]["value"] - #else: + # else: # dest[section][option] = config[section][option] @@ -237,29 +229,27 @@ class ConfigParser: elif typ == "int": return int(value) elif typ == "bool": - return True if value.lower() in ("1", "true", "on", "an", "yes") else False + return value.lower() in ("1", "true", "on", "an", "yes") elif typ == "time": - if not value: value = "0:00" - if not ":" in value: value += ":00" + if not value: + value = "0:00" + if not ":" in value: + value += ":00" return value elif typ in ("str", "file", "folder"): return encode(value) else: return value - def save(self): """saves the configs to disk""" - self.saveConfig(self.config, "pyload.conf") self.saveConfig(self.plugin, "plugin.conf") - def __getitem__(self, section): """provides dictonary like access: c['section']['option']""" return Section(self, section) - def get(self, section, option): """get value""" value = self.config[section][option]["value"] @@ -314,7 +304,7 @@ class ConfigParser: } values = [x[0] for x in config] + ["desc", "outline"] - #delete old values + # delete old values for item in conf.keys(): if item not in values: del conf[item] @@ -325,7 +315,7 @@ class ConfigParser: del self.plugin[name] -class Section: +class Section(object): """provides dictionary like access for configparser""" def __init__(self, parser, section): diff --git a/pyload/config/Setup.py b/pyload/config/Setup.py index 1fbdc3e51..7f159c01a 100644 --- a/pyload/config/Setup.py +++ b/pyload/config/Setup.py @@ -13,7 +13,7 @@ from subprocess import PIPE, call from pyload.utils import get_console_encoding, versiontuple -class SetupAssistant: +class SetupAssistant(object): """ pyLoads initial setup configuration assistant """ def __init__(self, path, config): @@ -251,7 +251,7 @@ class SetupAssistant: jinja = False else: jinja = True - except: + except Exception: jinja = False jinja = self.print_dep("jinja2", jinja) @@ -451,7 +451,7 @@ class SetupAssistant: try: __import__(module) return True - except: + except Exception: return False @@ -460,7 +460,7 @@ class SetupAssistant: try: call(command, stdout=pipe, stderr=pipe) return True - except: + except Exception: return False diff --git a/pyload/database/DatabaseBackend.py b/pyload/database/DatabaseBackend.py index b25a3c32e..8bde60335 100644 --- a/pyload/database/DatabaseBackend.py +++ b/pyload/database/DatabaseBackend.py @@ -27,12 +27,12 @@ from pyload.utils import chmod try: from pysqlite2 import dbapi2 as sqlite3 -except: +except Exception: import sqlite3 DB_VERSION = 4 -class style: +class style(object): db = None @classmethod @@ -63,7 +63,7 @@ class style: return cls.db.async(f, *args, **kwargs) return x -class DatabaseJob: +class DatabaseJob(object): def __init__(self, f, *args, **kwargs): self.done = Event() @@ -96,7 +96,7 @@ class DatabaseJob: print_exc() try: print "Database Error @", self.f.__name__, self.args[1:], self.kwargs, e - except: + except Exception: pass self.exception = e @@ -170,7 +170,7 @@ class DatabaseBackend(Thread): if v < 2: try: self.manager.core.log.warning(_("Filedatabase was deleted due to incompatible version.")) - except: + except Exception: print "Filedatabase was deleted due to incompatible version." remove("files.version") move("files.db", "files.backup.db") @@ -182,10 +182,10 @@ class DatabaseBackend(Thread): def _convertDB(self, v): try: getattr(self, "_convertV%i" % v)() - except: + except Exception: try: self.core.log.error(_("Filedatabase could NOT be converted.")) - except: + except Exception: print "Filedatabase could NOT be converted." #convert scripts start----------------------------------------------------- @@ -194,7 +194,7 @@ class DatabaseBackend(Thread): self.c.execute('CREATE TABLE IF NOT EXISTS "storage" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "identifier" TEXT NOT NULL, "key" TEXT NOT NULL, "value" TEXT DEFAULT "")') try: self.manager.core.log.info(_("Database was converted from v2 to v3.")) - except: + except Exception: print "Database was converted from v2 to v3." self._convertV3() @@ -202,7 +202,7 @@ class DatabaseBackend(Thread): self.c.execute('CREATE TABLE IF NOT EXISTS "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "name" TEXT NOT NULL, "email" TEXT DEFAULT "" NOT NULL, "password" TEXT NOT NULL, "role" INTEGER DEFAULT 0 NOT NULL, "permission" INTEGER DEFAULT 0 NOT NULL, "template" TEXT DEFAULT "default" NOT NULL)') try: self.manager.core.log.info(_("Database was converted from v3 to v4.")) - except: + except Exception: print "Database was converted from v3 to v4." #convert scripts end------------------------------------------------------- @@ -248,7 +248,7 @@ class DatabaseBackend(Thread): if exists("pyload.db"): try: self.core.log.info(_("Converting old Django DB")) - except: + except Exception: print "Converting old Django DB" conn = sqlite3.connect('pyload.db') c = conn.cursor() diff --git a/pyload/database/FileDatabase.py b/pyload/database/FileDatabase.py index 5bd1e5a5f..39e13fe29 100644 --- a/pyload/database/FileDatabase.py +++ b/pyload/database/FileDatabase.py @@ -28,11 +28,11 @@ from pyload.database import style, DatabaseBackend try: from pysqlite2 import dbapi2 as sqlite3 -except: +except Exception: import sqlite3 -class FileHandler: +class FileHandler(object): """Handles all request made to obtain information, modify status or other request for links or packages""" @@ -572,7 +572,7 @@ class FileHandler: """ restart all failed links """ self.db.restartFailed() -class FileMethods: +class FileMethods(object): @style.queue def filecount(self, queue): """returns number of files in queue""" diff --git a/pyload/database/StorageDatabase.py b/pyload/database/StorageDatabase.py index c2473e7b7..30f12af17 100644 --- a/pyload/database/StorageDatabase.py +++ b/pyload/database/StorageDatabase.py @@ -19,7 +19,7 @@ from pyload.database import style from pyload.database import DatabaseBackend -class StorageMethods: +class StorageMethods(object): @style.queue def setStorage(db, identifier, key, value): db.c.execute("SELECT id FROM storage WHERE identifier=? AND key=?", (identifier, key)) diff --git a/pyload/database/UserDatabase.py b/pyload/database/UserDatabase.py index 59b0f6dbf..59734a518 100644 --- a/pyload/database/UserDatabase.py +++ b/pyload/database/UserDatabase.py @@ -22,7 +22,7 @@ import random from DatabaseBackend import DatabaseBackend from DatabaseBackend import style -class UserMethods: +class UserMethods(object): @style.queue def checkAuth(db, user, password): c = db.c diff --git a/pyload/datatype/PyFile.py b/pyload/datatype/PyFile.py index e8916a921..f4f1cb0de 100644 --- a/pyload/datatype/PyFile.py +++ b/pyload/datatype/PyFile.py @@ -238,21 +238,21 @@ class PyFile(object): """ calculates speed """ try: return self.plugin.req.speed - except: + except Exception: return 0 def getETA(self): """ gets established time of arrival""" try: return self.getBytesLeft() / self.getSpeed() - except: + except Exception: return 0 def getBytesLeft(self): """ gets bytes left """ try: return self.getSize() - self.plugin.req.arrived - except: + except Exception: return 0 def getPercent(self): @@ -260,7 +260,7 @@ class PyFile(object): if self.status == 12: try: return self.plugin.req.percent - except: + except Exception: return 0 else: return self.progress @@ -272,7 +272,7 @@ class PyFile(object): return self.plugin.req.size else: return self.size - except: + except Exception: return self.size def notifyChange(self): diff --git a/pyload/datatype/PyPackage.py b/pyload/datatype/PyPackage.py index c8d3e6096..8439a769b 100644 --- a/pyload/datatype/PyPackage.py +++ b/pyload/datatype/PyPackage.py @@ -19,7 +19,7 @@ from pyload.manager.event.PullEvents import UpdateEvent from pyload.utils import safe_filename -class PyPackage: +class PyPackage(object): """ Represents a package object at runtime """ diff --git a/pyload/manager/AccountManager.py b/pyload/manager/AccountManager.py index 4e9e36cee..9dc98770c 100644 --- a/pyload/manager/AccountManager.py +++ b/pyload/manager/AccountManager.py @@ -11,7 +11,7 @@ from pyload.utils import chmod, lock ACC_VERSION = 1 -class AccountManager: +class AccountManager(object): """manages all accounts""" #---------------------------------------------------------------------- @@ -47,7 +47,7 @@ class AccountManager: return self.plugins[plugin] else: raise - except: + except Exception: return None @@ -100,7 +100,7 @@ class AccountManager: try: option = line[1:].split() self.accounts[plugin][name]['options'][option[0]] = [] if len(option) < 2 else ([option[1]] if len(option) < 3 else option[1:]) - except: + except Exception: pass elif ":" in line: diff --git a/pyload/manager/AddonManager.py b/pyload/manager/AddonManager.py index a394373a9..d4b43cb93 100644 --- a/pyload/manager/AddonManager.py +++ b/pyload/manager/AddonManager.py @@ -28,7 +28,8 @@ from pyload.manager.thread.AddonThread import AddonThread from pyload.manager.PluginManager import literal_eval from utils import lock -class AddonManager: + +class AddonManager(object): """Manages addons, delegates and handles Events. Every plugin can define events, \ @@ -69,7 +70,7 @@ class AddonManager: self.events = {} # contains events - #registering callback for config event + # registering callback for config event self.core.config.pluginCB = MethodType(self.dispatchEvent, "pluginConfigChanged", basestring) self.addEvent("pluginConfigChanged", self.manageAddon) @@ -85,10 +86,8 @@ class AddonManager: args[0].log.error(_("Error executing addon: %s") % e) if args[0].core.debug: traceback.print_exc() - return new - def addRPC(self, plugin, func, doc): plugin = plugin.rpartition(".")[2] doc = doc.strip() if doc else "" @@ -102,22 +101,18 @@ class AddonManager: if not args: args = tuple() if parse: args = tuple([literal_eval(x) for x in args]) - plugin = self.pluginMap[plugin] f = getattr(plugin, func) return f(*args) - def createIndex(self): plugins = [] - active = [] deactive = [] for pluginname in self.core.pluginManager.addonPlugins: try: # hookClass = getattr(plugin, plugin.__name__) - if self.core.config.getPlugin(pluginname, "activated"): pluginClass = self.core.pluginManager.loadClass("addon", pluginname) if not pluginClass: continue @@ -130,8 +125,7 @@ class AddonManager: else: deactive.append(pluginname) - - except: + except Exception: self.core.log.warning(_("Failed activating %(name)s") % {"name": pluginname}) if self.core.debug: traceback.print_exc() @@ -148,14 +142,15 @@ class AddonManager: self.deactivateAddon(plugin) def activateAddon(self, plugin): - #check if already loaded + # check if already loaded for inst in self.plugins: if inst.__name__ == plugin: return pluginClass = self.core.pluginManager.loadClass("addon", plugin) - if not pluginClass: return + if not pluginClass: + return self.core.log.debug("Plugin loaded: %s" % plugin) @@ -193,7 +188,6 @@ class AddonManager: for plugin in self.plugins: if plugin.isActivated(): plugin.coreReady() - self.dispatchEvent("coreReady") @try_catch @@ -201,7 +195,6 @@ class AddonManager: for plugin in self.plugins: if plugin.isActivated(): plugin.coreExiting() - self.dispatchEvent("coreExiting") @lock @@ -209,7 +202,6 @@ class AddonManager: for plugin in self.plugins: if plugin.isActivated(): plugin.downloadPreparing(pyfile) - self.dispatchEvent("downloadPreparing", pyfile) @lock @@ -241,7 +233,6 @@ class AddonManager: def beforeReconnecting(self, ip): for plugin in self.plugins: plugin.beforeReconnecting(ip) - self.dispatchEvent("beforeReconnecting", ip) @lock @@ -249,7 +240,6 @@ class AddonManager: for plugin in self.plugins: if plugin.isActivated(): plugin.afterReconnecting(ip) - self.dispatchEvent("afterReconnecting", ip) def startThread(self, function, *args, **kwargs): @@ -264,17 +254,16 @@ class AddonManager: info = {} for name, plugin in self.pluginMap.iteritems(): if plugin.info: - #copy and convert so str - info[name] = dict([(x, str(y) if not isinstance(y, basestring) else y) for x, y in plugin.info.iteritems()]) + # copy and convert so str + info[name] = dict( + [(x, str(y) if not isinstance(y, basestring) else y) for x, y in plugin.info.iteritems()]) return info - def getInfo(self, plugin): info = {} if plugin in self.pluginMap and self.pluginMap[plugin].info: - info = dict([(x, str(y) if not isinstance(y, basestring) else y) - for x, y in self.pluginMap[plugin].info.iteritems()]) - + info = dict((x, str(y) if not isinstance(y, basestring) else y) + for x, y in self.pluginMap[plugin].info.iteritems()) return info def addEvent(self, event, func): @@ -297,6 +286,6 @@ class AddonManager: f(*args) except Exception, e: self.core.log.warning("Error calling event handler %s: %s, %s, %s" - % (event, f, args, str(e))) + % (event, f, args, str(e))) if self.core.debug: traceback.print_exc() diff --git a/pyload/manager/CaptchaManager.py b/pyload/manager/CaptchaManager.py index b89fb3136..955d35b43 100644 --- a/pyload/manager/CaptchaManager.py +++ b/pyload/manager/CaptchaManager.py @@ -24,13 +24,12 @@ from threading import Lock from pyload.utils import encode -class CaptchaManager: +class CaptchaManager(object): def __init__(self, core): self.lock = Lock() self.core = core - self.tasks = [] #task store, for outgoing tasks only - - self.ids = 0 #only for internal purpose + self.tasks = [] # task store, for outgoing tasks only + self.ids = 0 # only for internal purpose def newTask(self, img, format, file, result_type): task = CaptchaTask(self.ids, img, format, file, result_type) @@ -55,7 +54,7 @@ class CaptchaManager: def getTaskByID(self, tid): self.lock.acquire() for task in self.tasks: - if task.id == str(tid): #task ids are strings + if task.id == str(tid): # task ids are strings self.lock.release() return task self.lock.release() @@ -64,26 +63,24 @@ class CaptchaManager: def handleCaptcha(self, task, timeout=50): cli = self.core.isClientConnected() - if cli: #client connected -> should solve the captcha + if cli: #: client connected -> should solve the captcha task.setWaiting(timeout) #wait 50 sec for response for plugin in self.core.addonManager.activePlugins(): try: plugin.newCaptchaTask(task) - except: + except Exception: if self.core.debug: print_exc() - if task.handler or cli: #the captcha was handled + if task.handler or cli: #: the captcha was handled self.tasks.append(task) return True - task.error = _("No Client connected for captcha decrypting") - return False -class CaptchaTask: +class CaptchaTask(object): def __init__(self, id, img, format, file, result_type='textual'): self.id = str(id) self.captchaImg = img @@ -93,10 +90,9 @@ class CaptchaTask: self.handler = [] #: the hook plugins that will take care of the solution self.result = None self.waitUntil = None - self.error = None #error message - + self.error = None # error message self.status = "init" - self.data = {} #handler can store data here + self.data = {} # handler can store data here def getCaptcha(self): return self.captchaImg, self.captchaFormat, self.captchaResultType @@ -108,7 +104,7 @@ class CaptchaTask: try: parts = text.split(',') self.result = (int(parts[0]), int(parts[1])) - except: + except Exception: self.result = None def getResult(self): diff --git a/pyload/manager/PluginManager.py b/pyload/manager/PluginManager.py index 79c3d6be6..b071ac476 100644 --- a/pyload/manager/PluginManager.py +++ b/pyload/manager/PluginManager.py @@ -12,7 +12,7 @@ from traceback import print_exc from SafeEval import const_eval as literal_eval -class PluginManager: +class PluginManager(object): ROOT = "pyload.plugins." USERROOT = "userplugins." TYPES = [] @@ -141,7 +141,7 @@ class PluginManager: try: regexp = re.compile(pattern) - except: + except Exception: self.core.log.error(_("%s has a invalid pattern") % name) pattern = r'^unmatchable$' regexp = re.compile(pattern) @@ -170,7 +170,7 @@ class PluginManager: config.insert(0, ["activated", "bool", "Activated", False if folder in ("addon", "hook") else True]) self.core.config.addPluginConfig(name, config, desc) - except: + except Exception: self.core.log.error("Invalid config in %s: %s" % (name, config)) elif folder in ("addon", "hook"): #force config creation @@ -180,7 +180,7 @@ class PluginManager: try: self.core.config.addPluginConfig(name, config, desc) - except: + except Exception: self.core.log.error("Invalid config in %s: %s" % (name, config)) if not rootplugins and plugins: #: Double check diff --git a/pyload/manager/RemoteManager.py b/pyload/manager/RemoteManager.py index e53e317e3..1ce007c6c 100644 --- a/pyload/manager/RemoteManager.py +++ b/pyload/manager/RemoteManager.py @@ -55,7 +55,7 @@ class BackendBase(Thread): self.shutdown() -class RemoteManager: +class RemoteManager(object): available = [] def __init__(self, core): diff --git a/pyload/manager/ThreadManager.py b/pyload/manager/ThreadManager.py index 1e7bf0f92..c1204c632 100644 --- a/pyload/manager/ThreadManager.py +++ b/pyload/manager/ThreadManager.py @@ -33,7 +33,7 @@ from pyload.network.RequestFactory import getURL from pyload.utils import freeSpace, lock -class ThreadManager: +class ThreadManager(object): """manages the download threads, assign jobs, reconnect etc""" @@ -190,7 +190,7 @@ class ThreadManager: try: reconn = Popen(self.core.config['reconnect']['method'], bufsize=-1, shell=True)#, stdout=subprocess.PIPE) - except: + except Exception: self.core.log.warning(_("Failed executing reconnect script!")) self.core.config["reconnect"]["activated"] = False self.reconnecting.clear() @@ -219,7 +219,7 @@ class ThreadManager: ip = getURL(sv[0]) ip = re.match(sv[1], ip).group(1) break - except: + except Exception: ip = "" sleep(1) diff --git a/pyload/manager/event/PullEvents.py b/pyload/manager/event/PullEvents.py index 0739b4ec8..aa78f590e 100644 --- a/pyload/manager/event/PullEvents.py +++ b/pyload/manager/event/PullEvents.py @@ -20,7 +20,7 @@ from time import time from pyload.utils import uniqify -class PullManager: +class PullManager(object): def __init__(self, core): self.core = core self.clients = [] @@ -52,7 +52,7 @@ class PullManager: for client in self.clients: client.addEvent(event) -class Client: +class Client(object): def __init__(self, uuid): self.uuid = uuid self.lastActive = time() @@ -69,7 +69,7 @@ class Client: def addEvent(self, event): self.events.append(event) -class UpdateEvent: +class UpdateEvent(object): def __init__(self, itype, iid, destination): assert itype == "pack" or itype == "file" assert destination == "queue" or destination == "collector" @@ -80,7 +80,7 @@ class UpdateEvent: def toList(self): return ["update", self.destination, self.type, self.id] -class RemoveEvent: +class RemoveEvent(object): def __init__(self, itype, iid, destination): assert itype == "pack" or itype == "file" assert destination == "queue" or destination == "collector" @@ -91,7 +91,7 @@ class RemoveEvent: def toList(self): return ["remove", self.destination, self.type, self.id] -class InsertEvent: +class InsertEvent(object): def __init__(self, itype, iid, after, destination): assert itype == "pack" or itype == "file" assert destination == "queue" or destination == "collector" @@ -103,7 +103,7 @@ class InsertEvent: def toList(self): return ["insert", self.destination, self.type, self.id, self.after] -class ReloadAllEvent: +class ReloadAllEvent(object): def __init__(self, destination): assert destination == "queue" or destination == "collector" self.destination = destination @@ -111,10 +111,10 @@ class ReloadAllEvent: def toList(self): return ["reload", self.destination] -class AccountUpdateEvent: +class AccountUpdateEvent(object): def toList(self): return ["account"] -class ConfigUpdateEvent: +class ConfigUpdateEvent(object): def toList(self): return ["config"] diff --git a/pyload/manager/event/Scheduler.py b/pyload/manager/event/Scheduler.py index 39dfbc3cc..59b84cfcf 100644 --- a/pyload/manager/event/Scheduler.py +++ b/pyload/manager/event/Scheduler.py @@ -25,7 +25,7 @@ class AlreadyCalled(Exception): pass -class Deferred: +class Deferred(object): def __init__(self): self.call = [] self.result = () @@ -43,7 +43,7 @@ class Deferred: f(*args ** kwargs) -class Scheduler: +class Scheduler(object): def __init__(self, core): self.core = core @@ -87,7 +87,7 @@ class Scheduler: break -class Job: +class Job(object): def __init__(self, time, call, args=[], kwargs={}, deferred=None, threaded=True): self.time = float(time) self.call = call @@ -112,7 +112,7 @@ class Job: self.run() -class PriorityQueue: +class PriorityQueue(object): """ a non blocking priority queue """ def __init__(self): diff --git a/pyload/manager/thread/DownloadThread.py b/pyload/manager/thread/DownloadThread.py index 86e18973e..5ecdd9953 100644 --- a/pyload/manager/thread/DownloadThread.py +++ b/pyload/manager/thread/DownloadThread.py @@ -93,7 +93,7 @@ class DownloadThread(PluginThread): except Abort: try: self.m.log.info(_("Download aborted: %s") % pyfile.name) - except: + except Exception: pass pyfile.setStatus("aborted") diff --git a/pyload/manager/thread/InfoThread.py b/pyload/manager/thread/InfoThread.py index 4edc55545..807910cd2 100644 --- a/pyload/manager/thread/InfoThread.py +++ b/pyload/manager/thread/InfoThread.py @@ -64,7 +64,7 @@ class InfoThread(PluginThread): for url, plugintype, pluginname in data: try: plugins[plugintype][pluginname].append(url) - except: + except Exception: plugins[plugintype][pluginname] = [url] # filter out container plugins @@ -111,7 +111,7 @@ class InfoThread(PluginThread): #attach container content try: data = self.decryptContainer(name, url) - except: + except Exception: print_exc() self.m.log.error("Could not decrypt container.") data = [] @@ -119,7 +119,7 @@ class InfoThread(PluginThread): for url, plugintype, pluginname in data: try: plugins[plugintype][pluginname].append(url) - except: + except Exception: plugins[plugintype][pluginname] = [url] self.m.infoResults[self.rid] = {} diff --git a/pyload/manager/thread/PluginThread.py b/pyload/manager/thread/PluginThread.py index faa1bba59..f3a49d621 100644 --- a/pyload/manager/thread/PluginThread.py +++ b/pyload/manager/thread/PluginThread.py @@ -64,7 +64,7 @@ class PluginThread(Thread): try: # avoid encoding errors zip.write(join("tmp", pyfile.pluginname, f), safe_join(pyfile.pluginname, f)) - except: + except Exception: pass info = zipfile.ZipInfo(safe_join(pyfile.pluginname, "debug_Report.txt"), gmtime()) diff --git a/pyload/manager/thread/ServerThread.py b/pyload/manager/thread/ServerThread.py index 7de3b1ca1..0f3ed01ff 100644 --- a/pyload/manager/thread/ServerThread.py +++ b/pyload/manager/thread/ServerThread.py @@ -44,7 +44,7 @@ class WebServer(threading.Thread): elif self.server == "fastcgi": try: import flup - except: + except Exception: log.warning(_("Can't use %(server)s, python-flup is not installed!") % { "server": self.server}) reset = True diff --git a/pyload/network/Bucket.py b/pyload/network/Bucket.py index a096d644a..6f1e05b16 100644 --- a/pyload/network/Bucket.py +++ b/pyload/network/Bucket.py @@ -19,7 +19,7 @@ from time import time from threading import Lock -class Bucket: +class Bucket(object): def __init__(self): self.rate = 0 self.tokens = 0 diff --git a/pyload/network/CookieJar.py b/pyload/network/CookieJar.py index a6ae090bc..c7e472484 100644 --- a/pyload/network/CookieJar.py +++ b/pyload/network/CookieJar.py @@ -19,7 +19,7 @@ from time import time -class CookieJar: +class CookieJar(object): def __init__(self, pluginname, account=None): self.cookies = {} self.plugin = pluginname diff --git a/pyload/network/HTTPChunk.py b/pyload/network/HTTPChunk.py index b9d2a5379..c4e294fc8 100644 --- a/pyload/network/HTTPChunk.py +++ b/pyload/network/HTTPChunk.py @@ -29,7 +29,7 @@ class WrongFormat(Exception): pass -class ChunkInfo: +class ChunkInfo(object): def __init__(self, name): self.name = unicode(name) self.size = 0 diff --git a/pyload/network/HTTPDownload.py b/pyload/network/HTTPDownload.py index debd653ee..99e2c3266 100644 --- a/pyload/network/HTTPDownload.py +++ b/pyload/network/HTTPDownload.py @@ -30,7 +30,7 @@ from HTTPRequest import BadHeader from pyload.plugins.Plugin import Abort from pyload.utils import safe_join, fs_encode -class HTTPDownload: +class HTTPDownload(object): """ loads a url http + ftp """ def __init__(self, url, filename, get={}, post={}, referer=None, cj=None, bucket=None, diff --git a/pyload/network/HTTPRequest.py b/pyload/network/HTTPRequest.py index 25f5732b5..c2442367a 100644 --- a/pyload/network/HTTPRequest.py +++ b/pyload/network/HTTPRequest.py @@ -45,7 +45,7 @@ class BadHeader(Exception): self.content = content -class HTTPRequest: +class HTTPRequest(object): def __init__(self, cookies=None, options=None): self.c = pycurl.Curl() self.rep = StringIO() diff --git a/pyload/network/RequestFactory.py b/pyload/network/RequestFactory.py index 58838e707..7e6e9e618 100644 --- a/pyload/network/RequestFactory.py +++ b/pyload/network/RequestFactory.py @@ -26,7 +26,7 @@ from CookieJar import CookieJar from XDCCRequest import XDCCRequest -class RequestFactory: +class RequestFactory(object): def __init__(self, core): self.lock = Lock() self.core = core diff --git a/pyload/network/XDCCRequest.py b/pyload/network/XDCCRequest.py index e4f880d4d..586a82138 100644 --- a/pyload/network/XDCCRequest.py +++ b/pyload/network/XDCCRequest.py @@ -30,7 +30,7 @@ from select import select from pyload.plugins.Plugin import Abort -class XDCCRequest: +class XDCCRequest(object): def __init__(self, timeout=30, proxies={}): self.proxies = proxies diff --git a/pyload/plugins/Plugin.py b/pyload/plugins/Plugin.py index cf4debd37..279986746 100644 --- a/pyload/plugins/Plugin.py +++ b/pyload/plugins/Plugin.py @@ -493,7 +493,7 @@ class Plugin(Base): if not self.core.debug: try: remove(tmpCaptcha.name) - except: + except Exception: pass return result diff --git a/pyload/plugins/account/AlldebridCom.py b/pyload/plugins/account/AlldebridCom.py index d4770426b..4f9164468 100644 --- a/pyload/plugins/account/AlldebridCom.py +++ b/pyload/plugins/account/AlldebridCom.py @@ -34,7 +34,7 @@ class AlldebridCom(Account): exp_time = time() + int(exp_data[0]) * 24 * 60 * 60 + int( exp_data[1]) * 60 * 60 + (int(exp_data[2]) - 1) * 60 #Get expiration date from API - except: + except Exception: data = self.getAccountData(user) page = req.load("http://www.alldebrid.com/api.php?action=info_user&login=%s&pw=%s" % (user, data['password'])) diff --git a/pyload/plugins/account/CatShareNet.py b/pyload/plugins/account/CatShareNet.py index 30a2691da..e172d6aee 100644 --- a/pyload/plugins/account/CatShareNet.py +++ b/pyload/plugins/account/CatShareNet.py @@ -31,7 +31,7 @@ class CatShareNet(Account): m = re.search(self.PREMIUM_PATTERN, html) if "Premium" in m.group(1): premium = True - except: + except Exception: pass try: @@ -39,7 +39,7 @@ class CatShareNet(Account): expiredate = m.group(1) if "-" not in expiredate: validuntil = mktime(strptime(expiredate, "%d.%m.%Y")) - except: + except Exception: pass return {'premium': premium, 'trafficleft': -1, 'validuntil': validuntil} diff --git a/pyload/plugins/addon/ExternalScripts.py b/pyload/plugins/addon/ExternalScripts.py index 5aff0f11f..05aeecff6 100644 --- a/pyload/plugins/addon/ExternalScripts.py +++ b/pyload/plugins/addon/ExternalScripts.py @@ -54,7 +54,7 @@ class ExternalScripts(Addon): if not exists(path): try: makedirs(path) - except: + except Exception: self.logDebug("Script folder %s not created" % folder) return diff --git a/pyload/plugins/addon/IRCInterface.py b/pyload/plugins/addon/IRCInterface.py index a89efcd0c..5b3178852 100644 --- a/pyload/plugins/addon/IRCInterface.py +++ b/pyload/plugins/addon/IRCInterface.py @@ -57,7 +57,7 @@ class IRCInterface(Thread, Addon): try: if self.getConfig("info_pack"): self.response(_("Package finished: %s") % pypack.name) - except: + except Exception: pass @@ -66,7 +66,7 @@ class IRCInterface(Thread, Addon): if self.getConfig("info_file"): self.response( _("Download finished: %(name)s @ %(plugin)s ") % {"name": pyfile.name, "plugin": pyfile.pluginname}) - except: + except Exception: pass @@ -179,7 +179,7 @@ class IRCInterface(Thread, Addon): trigger = temp[0] if len(temp) > 1: args = temp[1:] - except: + except Exception: pass handler = getattr(self, "event_%s" % trigger, self.event_pass) @@ -343,7 +343,7 @@ class IRCInterface(Thread, Addon): return ["INFO: Added %d links to Package %s [#%d]" % (len(links), pack['name'], id)] - except: + except Exception: # create new package id = self.core.api.addPackage(pack, links, 1) return ["INFO: Created new Package %s [#%d] with %d links." % (pack, id, len(links))] diff --git a/pyload/plugins/addon/UpdateManager.py b/pyload/plugins/addon/UpdateManager.py index 082721e2f..622374136 100644 --- a/pyload/plugins/addon/UpdateManager.py +++ b/pyload/plugins/addon/UpdateManager.py @@ -115,7 +115,7 @@ class UpdateManager(Addon): def server_request(self): try: return getURL(self.SERVER_URL, get={'v': self.core.api.getServerVersion()}).splitlines() - except: + except Exception: self.logWarning(_("Unable to contact server to get updates")) diff --git a/pyload/plugins/addon/XMPPInterface.py b/pyload/plugins/addon/XMPPInterface.py index 7b11bd4dd..5bbff8915 100644 --- a/pyload/plugins/addon/XMPPInterface.py +++ b/pyload/plugins/addon/XMPPInterface.py @@ -70,7 +70,7 @@ class XMPPInterface(IRCInterface, JabberClient): try: if self.getConfig("info_pack"): self.announce(_("Package finished: %s") % pypack.name) - except: + except Exception: pass @@ -79,7 +79,7 @@ class XMPPInterface(IRCInterface, JabberClient): if self.getConfig("info_file"): self.announce( _("Download finished: %(name)s @ %(plugin)s") % {"name": pyfile.name, "plugin": pyfile.pluginname}) - except: + except Exception: pass @@ -153,7 +153,7 @@ class XMPPInterface(IRCInterface, JabberClient): trigger = temp[0] if len(temp) > 1: args = temp[1:] - except: + except Exception: pass handler = getattr(self, "event_%s" % trigger, self.event_pass) diff --git a/pyload/plugins/captcha/AdsCaptcha.py b/pyload/plugins/captcha/AdsCaptcha.py index d804d9942..fe8fec29b 100644 --- a/pyload/plugins/captcha/AdsCaptcha.py +++ b/pyload/plugins/captcha/AdsCaptcha.py @@ -56,7 +56,7 @@ class AdsCaptcha(Captcha): try: challenge = re.search("challenge: '(.+?)',", js).group(1) server = re.search("server: '(.+?)',", js).group(1) - except: + except Exception: self.plugin.error(_("AdsCaptcha challenge pattern not found")) result = self.result(server, challenge) diff --git a/pyload/plugins/captcha/ReCaptcha.py b/pyload/plugins/captcha/ReCaptcha.py index c4054c29b..8e4d8c27c 100644 --- a/pyload/plugins/captcha/ReCaptcha.py +++ b/pyload/plugins/captcha/ReCaptcha.py @@ -51,7 +51,7 @@ class ReCaptcha(Captcha): try: challenge = re.search("challenge : '(.+?)',", js).group(1) server = re.search("server : '(.+?)',", js).group(1) - except: + except Exception: self.plugin.error(_("ReCaptcha challenge pattern not found")) result = self.result(server, challenge) diff --git a/pyload/plugins/captcha/SolveMedia.py b/pyload/plugins/captcha/SolveMedia.py index 6420fc326..5d5f6ea9a 100644 --- a/pyload/plugins/captcha/SolveMedia.py +++ b/pyload/plugins/captcha/SolveMedia.py @@ -32,7 +32,7 @@ class SolveMedia(Captcha): challenge = re.search(r'<input type=hidden name="adcopy_challenge" id="adcopy_challenge" value="([^"]+)">', html).group(1) server = "http://api.solvemedia.com/papi/media" - except: + except Exception: self.plugin.error(_("SolveMedia challenge pattern not found")) result = self.result(server, challenge) diff --git a/pyload/plugins/container/LinkList.py b/pyload/plugins/container/LinkList.py index b66e44558..9e6396cab 100644 --- a/pyload/plugins/container/LinkList.py +++ b/pyload/plugins/container/LinkList.py @@ -23,7 +23,7 @@ class LinkList(Container): def decrypt(self, pyfile): try: file_enc = codecs.lookup(self.getConfig("encoding")).name - except: + except Exception: file_enc = "utf-8" file_name = fs_encode(pyfile.url) @@ -64,7 +64,7 @@ class LinkList(Container): try: txt = open(file_name, 'wb') txt.close() - except: + except Exception: self.logWarning(_("LinkList could not be cleared")) for name, links in packages.iteritems(): diff --git a/pyload/plugins/crypter/ChipDe.py b/pyload/plugins/crypter/ChipDe.py index 96892bace..d107f34ae 100644 --- a/pyload/plugins/crypter/ChipDe.py +++ b/pyload/plugins/crypter/ChipDe.py @@ -22,7 +22,7 @@ class ChipDe(Crypter): self.html = self.load(pyfile.url) try: f = re.search(r'"(http://video\.chip\.de/.+)"', self.html) - except: + except Exception: self.fail(_("Failed to find the URL")) else: self.urls = [f.group(1)] diff --git a/pyload/plugins/crypter/LinkCryptWs.py b/pyload/plugins/crypter/LinkCryptWs.py index f01c42268..144bd7bb2 100644 --- a/pyload/plugins/crypter/LinkCryptWs.py +++ b/pyload/plugins/crypter/LinkCryptWs.py @@ -278,7 +278,7 @@ class LinkCryptWs(Crypter): (vcrypted, vjk) = self._getCipherParams(cnl_section) for (crypted, jk) in zip(vcrypted, vjk): package_links.extend(self._getLinks(crypted, jk)) - except: + except Exception: self.logError(_("Unable to decrypt CNL links (JS Error) try to get over links")) return self.handleWebLinks() diff --git a/pyload/plugins/crypter/LinkSaveIn.py b/pyload/plugins/crypter/LinkSaveIn.py index 2e0ac923e..e39d1a13d 100644 --- a/pyload/plugins/crypter/LinkSaveIn.py +++ b/pyload/plugins/crypter/LinkSaveIn.py @@ -202,7 +202,7 @@ class LinkSaveIn(SimpleCrypter): (vcrypted, vjk) = self._getCipherParams() for (crypted, jk) in zip(vcrypted, vjk): package_links.extend(self._getLinks(crypted, jk)) - except: + except Exception: self.fail(_("Unable to decrypt CNL2 links")) return package_links diff --git a/pyload/plugins/crypter/NCryptIn.py b/pyload/plugins/crypter/NCryptIn.py index edb664d32..b5b496a3f 100644 --- a/pyload/plugins/crypter/NCryptIn.py +++ b/pyload/plugins/crypter/NCryptIn.py @@ -229,7 +229,7 @@ class NCryptIn(Crypter): (vcrypted, vjk) = self._getCipherParams() for (crypted, jk) in zip(vcrypted, vjk): package_links.extend(self._getLinks(crypted, jk)) - except: + except Exception: self.fail(_("Unable to decrypt CNL2 links")) return package_links diff --git a/pyload/plugins/crypter/RelinkUs.py b/pyload/plugins/crypter/RelinkUs.py index c27d790b8..419ce4506 100644 --- a/pyload/plugins/crypter/RelinkUs.py +++ b/pyload/plugins/crypter/RelinkUs.py @@ -200,7 +200,7 @@ class RelinkUs(Crypter): (vcrypted, vjk) = self._getCipherParams(cnl2_form) for (crypted, jk) in zip(vcrypted, vjk): package_links.extend(self._getLinks(crypted, jk)) - except: + except Exception: self.logDebug("Unable to decrypt CNL2 links") return package_links @@ -219,7 +219,7 @@ class RelinkUs(Crypter): with open(dlc_filepath, "wb") as f: f.write(dlc) package_links.append(dlc_filepath) - except: + except Exception: self.fail("Unable to download DLC container") return package_links diff --git a/pyload/plugins/crypter/ShareLinksBiz.py b/pyload/plugins/crypter/ShareLinksBiz.py index 7aa5dd17b..64b198100 100644 --- a/pyload/plugins/crypter/ShareLinksBiz.py +++ b/pyload/plugins/crypter/ShareLinksBiz.py @@ -235,7 +235,7 @@ class ShareLinksBiz(Crypter): try: (crypted, jk) = self._getCipherParams() package_links.extend(self._getLinks(crypted, jk)) - except: + except Exception: self.fail(_("Unable to decrypt CNL2 links")) return package_links diff --git a/pyload/plugins/hook/BypassCaptcha.py b/pyload/plugins/hook/BypassCaptcha.py index 112066353..26e6794c0 100644 --- a/pyload/plugins/hook/BypassCaptcha.py +++ b/pyload/plugins/hook/BypassCaptcha.py @@ -50,7 +50,7 @@ class BypassCaptcha(Hook): def getCredits(self): res = getURL(self.GETCREDITS_URL, post={"key": self.getConfig("passkey")}) - data = dict([x.split(' ', 1) for x in res.splitlines()]) + data = dict(x.split(' ', 1) for x in res.splitlines()) return int(data['Left']) @@ -70,7 +70,7 @@ class BypassCaptcha(Hook): finally: req.close() - data = dict([x.split(' ', 1) for x in res.splitlines()]) + data = dict(x.split(' ', 1) for x in res.splitlines()) if not data or "Value" not in data: raise BypassCaptchaException(res) diff --git a/pyload/plugins/hook/ImageTyperz.py b/pyload/plugins/hook/ImageTyperz.py index 57a734884..b7d7cdd21 100644 --- a/pyload/plugins/hook/ImageTyperz.py +++ b/pyload/plugins/hook/ImageTyperz.py @@ -60,7 +60,7 @@ class ImageTyperz(Hook): try: balance = float(res) - except: + except Exception: raise ImageTyperzException("Invalid response") self.logInfo(_("Account balance: $%s left") % res) diff --git a/pyload/plugins/hoster/DepositfilesCom.py b/pyload/plugins/hoster/DepositfilesCom.py index ca26ebc47..001fee199 100644 --- a/pyload/plugins/hoster/DepositfilesCom.py +++ b/pyload/plugins/hoster/DepositfilesCom.py @@ -97,7 +97,7 @@ class DepositfilesCom(SimpleHoster): try: self.download(link, disposition=True) - except: + except Exception: self.retry(wait_time=60) diff --git a/pyload/plugins/hoster/DlFreeFr.py b/pyload/plugins/hoster/DlFreeFr.py index b06609298..2bfd88c22 100644 --- a/pyload/plugins/hoster/DlFreeFr.py +++ b/pyload/plugins/hoster/DlFreeFr.py @@ -33,7 +33,7 @@ class CustomBrowser(Browser): return Browser.load(self, *args, **kwargs) -class AdYouLike: +class AdYouLike(object): """ Class to support adyoulike captcha service """ diff --git a/pyload/plugins/hoster/FilesMailRu.py b/pyload/plugins/hoster/FilesMailRu.py index 1c7c8059e..4a5118fda 100644 --- a/pyload/plugins/hoster/FilesMailRu.py +++ b/pyload/plugins/hoster/FilesMailRu.py @@ -21,7 +21,7 @@ def getInfo(urls): url_pattern = '<a href="(.+?)" onclick="return Act\(this\, \'dlink\'\, event\)">(.+?)</a>' file_name = re.search(url_pattern, html).group(0).split(', event)">')[1].split('</a>')[0] result.append((file_name, 0, 2, url)) - except: + except Exception: pass # status 1=OFFLINE, 2=OK, 3=UNKNOWN diff --git a/pyload/plugins/hoster/FourSharedCom.py b/pyload/plugins/hoster/FourSharedCom.py index 03500654e..79e99aee4 100644 --- a/pyload/plugins/hoster/FourSharedCom.py +++ b/pyload/plugins/hoster/FourSharedCom.py @@ -51,7 +51,7 @@ class FourSharedCom(SimpleHoster): m = re.search(self.FID_PATTERN, self.html) res = self.load('http://www.4shared.com/web/d2/getFreeDownloadLimitInfo?fileId=%s' % m.group(1)) self.logDebug(res) - except: + except Exception: pass self.wait(20) diff --git a/pyload/plugins/hoster/Ftp.py b/pyload/plugins/hoster/Ftp.py index 2baec064b..c130cc395 100644 --- a/pyload/plugins/hoster/Ftp.py +++ b/pyload/plugins/hoster/Ftp.py @@ -35,7 +35,7 @@ class Ftp(Hoster): pyfile.name = parsed_url.path.rpartition('/')[2] try: pyfile.name = unquote(str(pyfile.name)).decode('utf8') - except: + except Exception: pass if not "@" in netloc: diff --git a/pyload/plugins/hoster/MediafireCom.py b/pyload/plugins/hoster/MediafireCom.py index 10d25ab9d..246a5c87e 100644 --- a/pyload/plugins/hoster/MediafireCom.py +++ b/pyload/plugins/hoster/MediafireCom.py @@ -28,7 +28,7 @@ def checkHTMLHeader(url): return url, 2 else: break - except: + except Exception: return url, 3 return url, 0 diff --git a/pyload/plugins/hoster/NetloadIn.py b/pyload/plugins/hoster/NetloadIn.py index b517fe455..07aeb48ca 100644 --- a/pyload/plugins/hoster/NetloadIn.py +++ b/pyload/plugins/hoster/NetloadIn.py @@ -40,10 +40,10 @@ def getInfo(urls): tmp = r.split(";") try: size = int(tmp[2]) - except: + except Exception: size = 0 result.append((tmp[1], size, 2 if tmp[3] == "online" else 1, chunk[i])) - except: + except Exception: self.logDebug("Error while processing response: %s" % r) yield result @@ -201,14 +201,14 @@ class NetloadIn(Hoster): try: url_captcha_html = "http://netload.in/" + re.search('(index.php\?id=10&.*&captcha=1)', page).group(1).replace("amp;", "") - except: + except Exception: page = None continue try: page = self.load(url_captcha_html, cookies=True) captcha_url = "http://netload.in/" + re.search('(share/includes/captcha.php\?t=\d*)', page).group(1) - except: + except Exception: self.logDebug("Could not find captcha, try again from beginning") captchawaited = False continue @@ -243,7 +243,7 @@ class NetloadIn(Hoster): file_url_pattern = r'<a href="(.+)" class="Orange_Link">Click here' attempt = re.search(file_url_pattern, page) return "http://netload.in/" + attempt.group(1) - except: + except Exception: self.logDebug("Getting final link failed") return None diff --git a/pyload/plugins/hoster/PremiumTo.py b/pyload/plugins/hoster/PremiumTo.py index 305b6d1d1..03ac37599 100644 --- a/pyload/plugins/hoster/PremiumTo.py +++ b/pyload/plugins/hoster/PremiumTo.py @@ -72,6 +72,6 @@ class PremiumTo(Hoster): api_r = self.load("http://premium.to/api/straffic.php", get={'username': self.account.username, 'password': self.account.password}) traffic = sum(map(int, api_r.split(';'))) - except: + except Exception: traffic = 0 return traffic diff --git a/pyload/plugins/hoster/ShareonlineBiz.py b/pyload/plugins/hoster/ShareonlineBiz.py index 0769cfe17..59204eb2e 100644 --- a/pyload/plugins/hoster/ShareonlineBiz.py +++ b/pyload/plugins/hoster/ShareonlineBiz.py @@ -177,7 +177,7 @@ class ShareonlineBiz(Hoster): err = m.group(1) try: self.logError(err, re.search(self.ERROR_INFO_PATTERN, self.html).group(1)) - except: + except Exception: self.logError(err, "Unknown error occurred") if err == "invalid": diff --git a/pyload/plugins/hoster/VimeoCom.py b/pyload/plugins/hoster/VimeoCom.py index bfa2cbb79..a24eedee2 100644 --- a/pyload/plugins/hoster/VimeoCom.py +++ b/pyload/plugins/hoster/VimeoCom.py @@ -44,7 +44,7 @@ class VimeoCom(SimpleHoster): html = self.load("https://player.vimeo.com/video/" + id, get={'password': password}) pattern = r'"(?P<QL>\w+)":{"profile".*?"(?P<URL>http://pdl\.vimeocdn\.com.+?)"' - link = dict([(l.group('QL').lower(), l.group('URL')) for l in re.finditer(pattern, html)]) + link = dict((l.group('QL').lower(), l.group('URL')) for l in re.finditer(pattern, html)) if self.getConfig("original"): if "original" in link: diff --git a/pyload/plugins/hoster/YibaishiwuCom.py b/pyload/plugins/hoster/YibaishiwuCom.py index 883dfa947..82ba9e8dc 100644 --- a/pyload/plugins/hoster/YibaishiwuCom.py +++ b/pyload/plugins/hoster/YibaishiwuCom.py @@ -46,7 +46,7 @@ class YibaishiwuCom(SimpleHoster): self.logDebug("Trying URL: " + url) self.download(url) break - except: + except Exception: continue else: self.fail(_("No working link found")) diff --git a/pyload/plugins/hoster/ZippyshareCom.py b/pyload/plugins/hoster/ZippyshareCom.py index 8f9062cfc..53b93d928 100644 --- a/pyload/plugins/hoster/ZippyshareCom.py +++ b/pyload/plugins/hoster/ZippyshareCom.py @@ -56,7 +56,7 @@ class ZippyshareCom(SimpleHoster): c1, c2 = map(int, re.search(r'\(\'downloadB\'\).omg\) \* \((\d+)%(\d+)', self.html).groups()) b = (a1 % a2) * (c1 % c2) - except: + except Exception: self.error(_("Unable to calculate checksum")) else: return b + 18 diff --git a/pyload/plugins/internal/AbstractExtractor.py b/pyload/plugins/internal/AbstractExtractor.py index 54ea9b348..717c91c46 100644 --- a/pyload/plugins/internal/AbstractExtractor.py +++ b/pyload/plugins/internal/AbstractExtractor.py @@ -12,7 +12,7 @@ class WrongPassword(Exception): pass -class AbtractExtractor: +class AbtractExtractor(object): __name__ = "AbtractExtractor" __version__ = "0.1" diff --git a/pyload/plugins/internal/Account.py b/pyload/plugins/internal/Account.py index e6895f119..b5125d61c 100644 --- a/pyload/plugins/internal/Account.py +++ b/pyload/plugins/internal/Account.py @@ -241,7 +241,7 @@ class Account(Base): start, end = time_data.split("-") if not compare_time(start.split(":"), end.split(":")): continue - except: + except Exception: self.logWarning(_("Your Time %s has wrong format, use: 1:22-3:44") % time_data) if user in self.infos: diff --git a/pyload/plugins/internal/Crypter.py b/pyload/plugins/internal/Crypter.py index 974ee60a1..8580def61 100644 --- a/pyload/plugins/internal/Crypter.py +++ b/pyload/plugins/internal/Crypter.py @@ -68,11 +68,11 @@ class Crypter(Plugin): folder_per_package = self.core.config['general']['folder_per_package'] try: use_subfolder = self.getConfig('use_subfolder') - except: + except Exception: use_subfolder = folder_per_package try: subfolder_per_package = self.getConfig('subfolder_per_package') - except: + except Exception: subfolder_per_package = True for pack in self.packages: diff --git a/pyload/plugins/internal/OCR.py b/pyload/plugins/internal/OCR.py index dec9f28b7..4d435d493 100644 --- a/pyload/plugins/internal/OCR.py +++ b/pyload/plugins/internal/OCR.py @@ -99,7 +99,7 @@ class OCR(object): try: with open(tmpTxt.name, 'r') as f: self.result_captcha = f.read().replace("\n", "") - except: + except Exception: self.result_captcha = "" self.logger.debug(self.result_captcha) @@ -108,7 +108,7 @@ class OCR(object): os.remove(tmpTxt.name) if subset and (digits or lowercase or uppercase): os.remove(tmpSub.name) - except: + except Exception: pass @@ -163,7 +163,7 @@ class OCR(object): count += 1 if pixels[x, y - 1] != 255: count += 1 - except: + except Exception: pass # not enough neighbors are dark pixels so mark this pixel diff --git a/pyload/plugins/internal/SimpleCrypter.py b/pyload/plugins/internal/SimpleCrypter.py index 090cf2e9f..4287c4d74 100644 --- a/pyload/plugins/internal/SimpleCrypter.py +++ b/pyload/plugins/internal/SimpleCrypter.py @@ -144,7 +144,7 @@ class SimpleCrypter(Crypter, SimpleHoster): try: m = re.search(self.PAGES_PATTERN, self.html) pages = int(m.group(1)) - except: + except Exception: pages = 1 for p in xrange(2, pages + 1): diff --git a/pyload/plugins/internal/SimpleHoster.py b/pyload/plugins/internal/SimpleHoster.py index a33e48bdf..922361b30 100644 --- a/pyload/plugins/internal/SimpleHoster.py +++ b/pyload/plugins/internal/SimpleHoster.py @@ -198,7 +198,7 @@ class SimpleHoster(Hoster): else: try: info.update(re.match(cls.__pattern__, url).groupdict()) - except: + except Exception: pass for pattern in ("INFO_PATTERN", "NAME_PATTERN", "SIZE_PATTERN"): diff --git a/pyload/plugins/internal/UnRar.py b/pyload/plugins/internal/UnRar.py index 31a0d7642..ebfe53829 100644 --- a/pyload/plugins/internal/UnRar.py +++ b/pyload/plugins/internal/UnRar.py @@ -16,7 +16,7 @@ def renice(pid, value): if os.name != "nt" and value: try: Popen(["renice", str(value), str(pid)], stdout=PIPE, stderr=PIPE, bufsize=-1) - except: + except Exception: print "Renice failed" diff --git a/pyload/plugins/internal/UpdateManager.py b/pyload/plugins/internal/UpdateManager.py index 082721e2f..622374136 100644 --- a/pyload/plugins/internal/UpdateManager.py +++ b/pyload/plugins/internal/UpdateManager.py @@ -115,7 +115,7 @@ class UpdateManager(Addon): def server_request(self): try: return getURL(self.SERVER_URL, get={'v': self.core.api.getServerVersion()}).splitlines() - except: + except Exception: self.logWarning(_("Unable to contact server to get updates")) diff --git a/pyload/plugins/internal/XFSHoster.py b/pyload/plugins/internal/XFSHoster.py index 4d3c848b9..061012059 100644 --- a/pyload/plugins/internal/XFSHoster.py +++ b/pyload/plugins/internal/XFSHoster.py @@ -323,7 +323,7 @@ class XFSHoster(SimpleHoster): recaptcha = ReCaptcha(self) try: captcha_key = re.search(self.RECAPTCHA_PATTERN, self.html).group(1) - except: + except Exception: captcha_key = recaptcha.detect_key() else: self.logDebug("ReCaptcha key: %s" % captcha_key) @@ -335,7 +335,7 @@ class XFSHoster(SimpleHoster): solvemedia = SolveMedia(self) try: captcha_key = re.search(self.SOLVEMEDIA_PATTERN, self.html).group(1) - except: + except Exception: captcha_key = solvemedia.detect_key() else: self.logDebug("SolveMedia key: %s" % captcha_key) diff --git a/pyload/plugins/ocr/LinksaveIn.py b/pyload/plugins/ocr/LinksaveIn.py index a9171ac7c..754bfc39d 100644 --- a/pyload/plugins/ocr/LinksaveIn.py +++ b/pyload/plugins/ocr/LinksaveIn.py @@ -79,7 +79,7 @@ class LinksaveIn(OCR): rgb_c = lut[pix[x, y]] try: cstat[rgb_c] += 1 - except: + except Exception: cstat[rgb_c] = 1 if rgb_bg == rgb_c: stat[bgpath] += 1 diff --git a/pyload/remote/ClickAndLoadBackend.py b/pyload/remote/ClickAndLoadBackend.py index 365364a3b..aaef5a650 100644 --- a/pyload/remote/ClickAndLoadBackend.py +++ b/pyload/remote/ClickAndLoadBackend.py @@ -24,7 +24,7 @@ from binascii import unhexlify try: from Crypto.Cipher import AES -except: +except Exception: pass from pyload.manager.RemoteManager import BackendBase diff --git a/pyload/remote/socketbackend/create_ttypes.py b/pyload/remote/socketbackend/create_ttypes.py index 4563f9711..be1e2aaea 100644 --- a/pyload/remote/socketbackend/create_ttypes.py +++ b/pyload/remote/socketbackend/create_ttypes.py @@ -69,7 +69,7 @@ class BaseObject(object): f.write("\n") - f.write("class Iface:\n") + f.write("class Iface(object):\n") for name in dir(Iface): if name.startswith("_"): continue diff --git a/pyload/remote/thriftbackend/Protocol.py b/pyload/remote/thriftbackend/Protocol.py index a5822df18..417b45834 100644 --- a/pyload/remote/thriftbackend/Protocol.py +++ b/pyload/remote/thriftbackend/Protocol.py @@ -17,7 +17,7 @@ class Protocol(TBinaryProtocol.TBinaryProtocol): str = self.trans.readAll(len) try: str = str.decode("utf8", "ignore") - except: + except Exception: pass return str diff --git a/pyload/remote/thriftbackend/Socket.py b/pyload/remote/thriftbackend/Socket.py index b9fa7edbf..f6edc8408 100644 --- a/pyload/remote/thriftbackend/Socket.py +++ b/pyload/remote/thriftbackend/Socket.py @@ -10,7 +10,7 @@ from thrift.transport.TSocket import TSocket, TServerSocket, TTransportException WantReadError = Exception #overwritten when ssl is used -class SecureSocketConnection: +class SecureSocketConnection(object): def __init__(self, connection): self.__dict__["connection"] = connection diff --git a/pyload/remote/thriftbackend/ThriftClient.py b/pyload/remote/thriftbackend/ThriftClient.py index 913719ed9..d7b0d2919 100644 --- a/pyload/remote/thriftbackend/ThriftClient.py +++ b/pyload/remote/thriftbackend/ThriftClient.py @@ -31,7 +31,7 @@ class NoConnection(Exception): class NoSSL(Exception): pass -class ThriftClient: +class ThriftClient(object): def __init__(self, host="localhost", port=7227, user="", password=""): self.createConnection(host, port) diff --git a/pyload/remote/thriftbackend/ThriftTest.py b/pyload/remote/thriftbackend/ThriftTest.py index aec20fa33..7243cc6f2 100644 --- a/pyload/remote/thriftbackend/ThriftTest.py +++ b/pyload/remote/thriftbackend/ThriftTest.py @@ -25,7 +25,7 @@ def bench(f, *args, **kwargs): e = time() try: print "%s: %f s" % (f._Method__name, e-s) - except: + except Exception: print "%s: %f s" % (f.__name__, e-s) return ret diff --git a/pyload/remote/thriftbackend/Transport.py b/pyload/remote/thriftbackend/Transport.py index b5b6c8104..7db4ba9d7 100644 --- a/pyload/remote/thriftbackend/Transport.py +++ b/pyload/remote/thriftbackend/Transport.py @@ -19,12 +19,12 @@ class TransportCompressed(TZlibTransport): self.handle = trans.handle self.remoteaddr = trans.handle.getpeername() -class TransportFactory: +class TransportFactory(object): def getTransport(self, trans): buffered = Transport(trans) return buffered -class TransportFactoryCompressed: +class TransportFactoryCompressed(object): _last_trans = None _last_z = None diff --git a/pyload/utils/JsEngine.py b/pyload/utils/JsEngine.py index f6f28f457..c516dfc73 100644 --- a/pyload/utils/JsEngine.py +++ b/pyload/utils/JsEngine.py @@ -9,7 +9,7 @@ from urllib import quote from pyload.utils import encode, decode, uniqify -class JsEngine: +class JsEngine(object): """ JS Engine superclass """ def __init__(self, core, engine=None): #: engine can be a jse name """string""" or an AbstractEngine """class""" @@ -103,7 +103,7 @@ class JsEngine: return results[0] -class AbstractEngine: +class AbstractEngine(object): """ JSE base class """ NAME = "" @@ -123,7 +123,7 @@ class AbstractEngine: except ImportError: try: out, err = cls().eval("print(23+19)") - except: + except Exception: res = False else: res = out == "42" diff --git a/pyload/utils/__init__.py b/pyload/utils/__init__.py index 541dedbd8..1c398224f 100644 --- a/pyload/utils/__init__.py +++ b/pyload/utils/__init__.py @@ -23,7 +23,7 @@ json_dumps = json.dumps def chmod(*args): try: os.chmod(*args) - except: + except Exception: pass @@ -53,7 +53,7 @@ def remove_chars(string, repl): if type(string) == str: return string.translate(maketrans("", ""), repl) elif type(string) == unicode: - return string.translate(dict([(ord(s), None) for s in repl])) + return string.translate(dict((ord(s), None) for s in repl)) def safe_filename(name): diff --git a/pyload/webui/app/api.py b/pyload/webui/app/api.py index 286061c2a..9726902fb 100644 --- a/pyload/webui/app/api.py +++ b/pyload/webui/app/api.py @@ -60,7 +60,7 @@ def callApi(func, *args, **kwargs): return HTTPError(404, json.dumps("Not Found")) result = getattr(PYLOAD, func)(*[literal_eval(x) for x in args], - **dict([(x, literal_eval(y)) for x, y in kwargs.iteritems()])) + **dict((x, literal_eval(y)) for x, y in kwargs.iteritems())) # null is invalid json response if result is None: result = True @@ -88,7 +88,7 @@ def login(): try: sid = s._headers["cookie_out"].split("=")[1].split(";")[0] return json.dumps(sid) - except: + except Exception: return json.dumps(True) diff --git a/pyload/webui/app/cnl.py b/pyload/webui/app/cnl.py index 1444983c2..e00e47f66 100644 --- a/pyload/webui/app/cnl.py +++ b/pyload/webui/app/cnl.py @@ -11,7 +11,7 @@ from pyload.webui import PYLOAD, DL_ROOT, JS try: from Crypto.Cipher import AES -except: +except Exception: pass @@ -61,7 +61,7 @@ def addcrypted(): try: PYLOAD.addPackage(package, [dlc_path], 0) - except: + except Exception: return HTTPError() else: return "success\r\n" @@ -82,7 +82,7 @@ def addcrypted2(): else: try: jk = re.findall(r"return ('|\")(.+)('|\")", jk)[0][1] - except: + except Exception: ## Test for some known js functions to decode if jk.find("dec") > -1 and jk.find("org") > -1: org = re.findall(r"var org = ('|\")([^\"']+)", jk)[0][1] @@ -94,7 +94,7 @@ def addcrypted2(): try: Key = unhexlify(jk) - except: + except Exception: print "Could not decrypt key, please install py-spidermonkey or ossp-js" return "failed" @@ -110,7 +110,7 @@ def addcrypted2(): PYLOAD.addPackage(package, result, 0) else: PYLOAD.generateAndAddPackages(result, 0) - except: + except Exception: return "failed can't add" else: return "success\r\n" diff --git a/pyload/webui/app/json.py b/pyload/webui/app/json.py index 8fa675865..096f72ab5 100644 --- a/pyload/webui/app/json.py +++ b/pyload/webui/app/json.py @@ -33,7 +33,7 @@ def status(): status = toDict(PYLOAD.statusServer()) status['captcha'] = PYLOAD.isCaptchaWaiting() return status - except: + except Exception: return HTTPError() @@ -78,7 +78,7 @@ def packages(): return data - except: + except Exception: return HTTPError() @@ -112,7 +112,7 @@ def package(id): data["links"] = tmp return data - except: + except Exception: print_exc() return HTTPError() @@ -124,7 +124,7 @@ def package_order(ids): pid, pos = ids.split("|") PYLOAD.orderPackage(int(pid), int(pos)) return {"response": "success"} - except: + except Exception: return HTTPError() @@ -134,7 +134,7 @@ def abort_link(id): try: PYLOAD.stopDownloads([id]) return {"response": "success"} - except: + except Exception: return HTTPError() @@ -145,7 +145,7 @@ def link_order(ids): pid, pos = ids.split("|") PYLOAD.orderFile(int(pid), int(pos)) return {"response": "success"} - except: + except Exception: return HTTPError() @@ -170,7 +170,7 @@ def add_package(): copyfileobj(f.file, destination) destination.close() links.insert(0, fpath) - except: + except Exception: pass name = name.decode("utf8", "ignore") @@ -191,7 +191,7 @@ def move_package(dest, id): try: PYLOAD.movePackage(dest, id) return {"response": "success"} - except: + except Exception: return HTTPError() @@ -207,7 +207,7 @@ def edit_package(): PYLOAD.setPackageData(id, data) return {"response": "success"} - except: + except Exception: return HTTPError() @@ -218,7 +218,7 @@ def set_captcha(): if request.environ.get('REQUEST_METHOD', "GET") == "POST": try: PYLOAD.setCaptchaResult(request.forms["cap_id"], request.forms["cap_result"]) - except: + except Exception: pass task = PYLOAD.getCaptchaTask() @@ -257,7 +257,7 @@ def save_config(category): for key, value in request.POST.iteritems(): try: section, option = key.split("|") - except: + except Exception: continue if category == "general": category = "core" diff --git a/pyload/webui/app/pyload.py b/pyload/webui/app/pyload.py index c13d5bf48..13e3802d1 100644 --- a/pyload/webui/app/pyload.py +++ b/pyload/webui/app/pyload.py @@ -173,7 +173,7 @@ def logout(): def home(): try: res = [toDict(x) for x in PYLOAD.statusDownloads()] - except: + except Exception: s = request.environ.get('beaker.session') s.delete() return redirect("/login") @@ -231,7 +231,7 @@ def downloads(): try: if isfile(safe_join(root, item, file)): folder['files'].append(file) - except: + except Exception: pass data['folder'].append(folder) @@ -289,7 +289,7 @@ def config(): try: data.options["time"] = data.options["time"][0] - except: + except Exception: data.options["time"] = "0:00-0:00" if "limitDL" in data.options: @@ -334,7 +334,7 @@ def path(file="", path=""): try: cwd = cwd.encode("utf8") - except: + except Exception: pass cwd = os.path.normpath(os.path.abspath(cwd)) @@ -351,7 +351,7 @@ def path(file="", path=""): try: folders = os.listdir(cwd) - except: + except Exception: folders = [] files = [] @@ -363,7 +363,7 @@ def path(file="", path=""): data['sort'] = data['fullpath'].lower() data['modified'] = datetime.fromtimestamp(int(os.path.getmtime(join(cwd, f)))) data['ext'] = os.path.splitext(f)[1] - except: + except Exception: continue if os.path.isdir(join(cwd, f)): @@ -414,7 +414,7 @@ def logs(item=-1): if request.environ.get('REQUEST_METHOD', "GET") == "POST": try: fro = datetime.strptime(request.forms['from'], '%d.%m.%Y %H:%M:%S') - except: + except Exception: pass try: perpage = int(request.forms['perpage']) @@ -422,14 +422,14 @@ def logs(item=-1): reversed = bool(request.forms.get('reversed', False)) s['reversed'] = reversed - except: + except Exception: pass s.save() try: item = int(item) - except: + except Exception: pass log = PYLOAD.getLog() @@ -452,7 +452,7 @@ def logs(item=-1): try: date, time, level, message = l.decode("utf8", "ignore").split(" ", 3) dtime = datetime.strptime(date + ' ' + time, '%d.%m.%Y %H:%M:%S') - except: + except Exception: dtime = None date = '?' time = ' ' @@ -484,7 +484,7 @@ def logs(item=-1): @login_required("ADMIN") def admin(): # convert to dict - user = dict([(name, toDict(y)) for name, y in PYLOAD.getAllUserData().iteritems()]) + user = dict((name, toDict(y)) for name, y in PYLOAD.getAllUserData().iteritems()) perms = permlist() for data in user.itervalues(): diff --git a/pyload/webui/app/utils.py b/pyload/webui/app/utils.py index d5fa66a35..ff0faddd0 100644 --- a/pyload/webui/app/utils.py +++ b/pyload/webui/app/utils.py @@ -32,7 +32,7 @@ def render_to_response(file, args={}, proc=[]): def parse_permissions(session): - perms = dict([(x, False) for x in dir(PERMS) if not x.startswith("_")]) + perms = dict((x, False) for x in dir(PERMS) if not x.startswith("_")) perms["ADMIN"] = False perms["is_admin"] = False diff --git a/pyload/webui/filters.py b/pyload/webui/filters.py index c5e9447ee..527b18446 100644 --- a/pyload/webui/filters.py +++ b/pyload/webui/filters.py @@ -6,7 +6,7 @@ quotechar = "::/" try: from os.path import relpath -except: +except Exception: from posixpath import curdir, sep, pardir def relpath(path, start=curdir): """Return a relative version of a path""" @@ -27,7 +27,7 @@ def quotepath(path): return path.replace("../", quotechar) except AttributeError: return path - except: + except Exception: return "" def unquotepath(path): @@ -35,7 +35,7 @@ def unquotepath(path): return path.replace(quotechar, "../") except AttributeError: return path - except: + except Exception: return "" def path_make_absolute(path): |