diff options
author | Calum Lind <calumlind+deluge@gmail.com> | 2016-11-03 21:26:46 +0000 |
---|---|---|
committer | Calum Lind <calumlind+deluge@gmail.com> | 2016-11-03 21:45:45 +0000 |
commit | 3a2ff0c188b0e8da893b733cccb1e164b54f2471 (patch) | |
tree | 2997d64b20e6e280016792cd4a04bfd20ff89992 /deluge/ui/web | |
parent | d4a8a38586251575a17c50735a10ddfba30fdc31 (diff) | |
download | deluge-3a2ff0c188b0e8da893b733cccb1e164b54f2471.tar.gz deluge-3a2ff0c188b0e8da893b733cccb1e164b54f2471.tar.bz2 deluge-3a2ff0c188b0e8da893b733cccb1e164b54f2471.zip |
[Lint] Convert all python double quotes to single quotes
* A rather disruptive change but for a few reasons such as easier to read,
easier type, keep consistent and javascript code uses single quotes.
* There are a few exceptions for the automated process:
* Any double quotes in comments
* Triple double quotes for docstrings
* Strings containing single quotes are left e.g. "they're"
* To deal with merge conflicts from feature branches it is best to follow
these steps for each commit:
* Create a patch: `git format-patch -1 <sha1>`
* Edit the patch and replace double quotes with single except those in
comments or strings containing an unescaped apostrophe.
* Check the patch `git apply --check <patchfile>` and fix any remaining
issues if it outputs an error.
* Apply the patch `git am < <patchfile>`
Diffstat (limited to 'deluge/ui/web')
-rw-r--r-- | deluge/ui/web/auth.py | 104 | ||||
-rw-r--r-- | deluge/ui/web/common.py | 14 | ||||
-rw-r--r-- | deluge/ui/web/json_api.py | 298 | ||||
-rw-r--r-- | deluge/ui/web/pluginmanager.py | 68 | ||||
-rw-r--r-- | deluge/ui/web/server.py | 326 | ||||
-rw-r--r-- | deluge/ui/web/web.py | 22 |
6 files changed, 416 insertions, 416 deletions
diff --git a/deluge/ui/web/auth.py b/deluge/ui/web/auth.py index 5ff450bf3..cc4350752 100644 --- a/deluge/ui/web/auth.py +++ b/deluge/ui/web/auth.py @@ -79,7 +79,7 @@ class Auth(JSONComponent): """ def __init__(self, config): - super(Auth, self).__init__("Auth") + super(Auth, self).__init__('Auth') self.worker = LoopingCall(self._clean_sessions) self.config = config @@ -90,18 +90,18 @@ class Auth(JSONComponent): self.worker.stop() def _clean_sessions(self): - session_ids = self.config["sessions"].keys() + session_ids = self.config['sessions'].keys() now = time.gmtime() for session_id in session_ids: - session = self.config["sessions"][session_id] + session = self.config['sessions'][session_id] - if "expires" not in session: - del self.config["sessions"][session_id] + if 'expires' not in session: + del self.config['sessions'][session_id] continue - if time.gmtime(session["expires"]) < now: - del self.config["sessions"][session_id] + if time.gmtime(session['expires']) < now: + del self.config['sessions'][session_id] continue def _create_session(self, request, login='admin'): @@ -116,75 +116,75 @@ class Auth(JSONComponent): m.update(os.urandom(32)) session_id = m.hexdigest() - expires, expires_str = make_expires(self.config["session_timeout"]) + expires, expires_str = make_expires(self.config['session_timeout']) checksum = str(make_checksum(session_id)) request.addCookie('_session_id', session_id + checksum, - path=request.base + "json", expires=expires_str) + path=request.base + 'json', expires=expires_str) - log.debug("Creating session for %s", login) + log.debug('Creating session for %s', login) - if isinstance(self.config["sessions"], list): - self.config["sessions"] = {} + if isinstance(self.config['sessions'], list): + self.config['sessions'] = {} - self.config["sessions"][session_id] = { - "login": login, - "level": AUTH_LEVEL_ADMIN, - "expires": expires + self.config['sessions'][session_id] = { + 'login': login, + 'level': AUTH_LEVEL_ADMIN, + 'expires': expires } return True def check_password(self, password): config = self.config - if "pwd_md5" in config.config: + if 'pwd_md5' in config.config: # We are using the 1.2-dev auth method - log.debug("Received a password via the 1.2-dev auth method") + log.debug('Received a password via the 1.2-dev auth method') m = hashlib.md5() - m.update(config["pwd_salt"]) + m.update(config['pwd_salt']) m.update(utf8_encoded(password)) if m.hexdigest() == config['pwd_md5']: # We want to move the password over to sha1 and remove # the old passwords from the config file. self._change_password(password) - del config.config["pwd_md5"] + del config.config['pwd_md5'] # Remove the older password if there is now. - if "old_pwd_md5" in config.config: - del config.config["old_pwd_salt"] - del config.config["old_pwd_md5"] + if 'old_pwd_md5' in config.config: + del config.config['old_pwd_salt'] + del config.config['old_pwd_md5'] return True - elif "old_pwd_md5" in config.config: + elif 'old_pwd_md5' in config.config: # We are using the 1.1 webui auth method - log.debug("Received a password via the 1.1 auth method") + log.debug('Received a password via the 1.1 auth method') from base64 import decodestring m = hashlib.md5() - m.update(decodestring(config["old_pwd_salt"])) + m.update(decodestring(config['old_pwd_salt'])) m.update(utf8_encoded(password)) - if m.digest() == decodestring(config["old_pwd_md5"]): + if m.digest() == decodestring(config['old_pwd_md5']): # We want to move the password over to sha1 and remove # the old passwords from the config file. self._change_password(password) - del config.config["old_pwd_salt"] - del config.config["old_pwd_md5"] + del config.config['old_pwd_salt'] + del config.config['old_pwd_md5'] return True - elif "pwd_sha1" in config.config: + elif 'pwd_sha1' in config.config: # We are using the 1.2 auth method - log.debug("Received a password via the 1.2 auth method") + log.debug('Received a password via the 1.2 auth method') s = hashlib.sha1() - s.update(config["pwd_salt"]) + s.update(config['pwd_salt']) s.update(utf8_encoded(password)) - if s.hexdigest() == config["pwd_sha1"]: + if s.hexdigest() == config['pwd_sha1']: return True else: # Can't detect which method we should be using so just deny # access. - log.debug("Failed to detect the login method") + log.debug('Failed to detect the login method') return False def check_request(self, request, method=None, level=None): @@ -202,39 +202,39 @@ class Auth(JSONComponent): :raises: Exception """ - session_id = get_session_id(request.getCookie("_session_id")) + session_id = get_session_id(request.getCookie('_session_id')) - if session_id not in self.config["sessions"]: + if session_id not in self.config['sessions']: auth_level = AUTH_LEVEL_NONE session_id = None else: - session = self.config["sessions"][session_id] - auth_level = session["level"] - expires, expires_str = make_expires(self.config["session_timeout"]) - session["expires"] = expires + session = self.config['sessions'][session_id] + auth_level = session['level'] + expires, expires_str = make_expires(self.config['session_timeout']) + session['expires'] = expires - _session_id = request.getCookie("_session_id") + _session_id = request.getCookie('_session_id') request.addCookie('_session_id', _session_id, - path=request.base + "json", expires=expires_str) + path=request.base + 'json', expires=expires_str) if method: - if not hasattr(method, "_json_export"): - raise Exception("Not an exported method") + if not hasattr(method, '_json_export'): + raise Exception('Not an exported method') - method_level = getattr(method, "_json_auth_level") + method_level = getattr(method, '_json_auth_level') if method_level is None: - raise Exception("Method has no auth level") + raise Exception('Method has no auth level') level = method_level if level is None: - raise Exception("No level specified to check against") + raise Exception('No level specified to check against') request.auth_level = auth_level request.session_id = session_id if auth_level < level: - raise AuthError("Not authenticated") + raise AuthError('Not authenticated') def _change_password(self, new_password): """ @@ -244,12 +244,12 @@ class Auth(JSONComponent): :param new_password: the password to change to :type new_password: string """ - log.debug("Changing password") + log.debug('Changing password') salt = hashlib.sha1(os.urandom(32)).hexdigest() s = hashlib.sha1(salt) s.update(utf8_encoded(new_password)) - self.config["pwd_salt"] = salt - self.config["pwd_sha1"] = s.hexdigest() + self.config['pwd_salt'] = salt + self.config['pwd_sha1'] = s.hexdigest() return True @export @@ -284,7 +284,7 @@ class Auth(JSONComponent): :param session_id: the id for the session to remove :type session_id: string """ - del self.config["sessions"][__request__.session_id] + del self.config['sessions'][__request__.session_id] return True @export(AUTH_LEVEL_NONE) diff --git a/deluge/ui/web/common.py b/deluge/ui/web/common.py index 41ad776c8..ede22767d 100644 --- a/deluge/ui/web/common.py +++ b/deluge/ui/web/common.py @@ -14,7 +14,7 @@ from deluge import common def _(text): - return gettext.gettext(text).decode("utf-8") + return gettext.gettext(text).decode('utf-8') def escape(text): @@ -30,7 +30,7 @@ def escape(text): def compress(contents, request): - request.setHeader("content-encoding", "gzip") + request.setHeader('content-encoding', 'gzip') compress_zlib = zlib.compressobj(6, zlib.DEFLATED, zlib.MAX_WBITS + 16, zlib.DEF_MEM_LEVEL, 0) contents = compress_zlib.compress(contents) contents += compress_zlib.flush() @@ -47,9 +47,9 @@ try: """ builtins = { - "_": _, - "escape": escape, - "version": common.get_version() + '_': _, + 'escape': escape, + 'version': common.get_version() } def render(self, *args, **data): @@ -58,11 +58,11 @@ try: return rendered.encode('utf-8', 'replace') except ImportError: import warnings - warnings.warn("The Mako library is required to run deluge.ui.web", + warnings.warn('The Mako library is required to run deluge.ui.web', RuntimeWarning) class Template(object): def __new__(cls, *args, **kwargs): raise RuntimeError( - "The Mako library is required to run deluge.ui.web" + 'The Mako library is required to run deluge.ui.web' ) diff --git a/deluge/ui/web/json_api.py b/deluge/ui/web/json_api.py index f7c370012..2599b7180 100644 --- a/deluge/ui/web/json_api.py +++ b/deluge/ui/web/json_api.py @@ -41,7 +41,7 @@ AuthError = None class JSONComponent(component.Component): def __init__(self, name, interval=1, depend=None): super(JSONComponent, self).__init__(name, interval, depend) - self._json = component.get("JSON") + self._json = component.get('JSON') self._json.register_object(self, name) @@ -87,7 +87,7 @@ class JSON(resource.Resource, component.Component): def __init__(self): resource.Resource.__init__(self) - component.Component.__init__(self, "JSON") + component.Component.__init__(self, 'JSON') self._remote_methods = [] self._local_methods = {} if client.is_standalone(): @@ -109,7 +109,7 @@ class JSON(resource.Resource, component.Component): """ Handles executing all local methods. """ - if method == "system.listMethods": + if method == 'system.listMethods': d = Deferred() methods = list(self._remote_methods) methods.extend(self._local_methods) @@ -120,16 +120,16 @@ class JSON(resource.Resource, component.Component): # and any plugins. meth = self._local_methods[method] meth.__globals__['__request__'] = request - component.get("Auth").check_request(request, meth) + component.get('Auth').check_request(request, meth) return meth(*params) - raise JSONException("Unknown system method") + raise JSONException('Unknown system method') def _exec_remote(self, method, params, request): """ Executes methods using the Deluge client. """ - component.get("Auth").check_request(request, level=AUTH_LEVEL_DEFAULT) - core_component, method = method.split(".") + component.get('Auth').check_request(request, level=AUTH_LEVEL_DEFAULT) + core_component, method = method.split('.') return getattr(getattr(client, core_component), method)(*params) def _handle_request(self, request): @@ -141,29 +141,29 @@ class JSON(resource.Resource, component.Component): try: request.json = json.loads(request.json) except (ValueError, TypeError): - raise JSONException("JSON not decodable") - if "method" not in request.json or "id" not in request.json or \ - "params" not in request.json: - raise JSONException("Invalid JSON request") + raise JSONException('JSON not decodable') + if 'method' not in request.json or 'id' not in request.json or \ + 'params' not in request.json: + raise JSONException('Invalid JSON request') - method, params = request.json["method"], request.json["params"] - request_id = request.json["id"] + method, params = request.json['method'], request.json['params'] + request_id = request.json['id'] result = None error = None try: - if method.startswith("system.") or method in self._local_methods: + if method.startswith('system.') or method in self._local_methods: result = self._exec_local(method, params, request) elif method in self._remote_methods: result = self._exec_remote(method, params, request) else: - error = {"message": "Unknown method", "code": 2} + error = {'message': 'Unknown method', 'code': 2} except AuthError: - error = {"message": "Not authenticated", "code": 1} + error = {'message': 'Not authenticated', 'code': 1} except Exception as ex: - log.error("Error calling method `%s`", method) + log.error('Error calling method `%s`', method) log.exception(ex) - error = {"message": "%s: %s" % (ex.__class__.__name__, str(ex)), "code": 3} + error = {'message': '%s: %s' % (ex.__class__.__name__, str(ex)), 'code': 3} return request_id, result, error @@ -171,7 +171,7 @@ class JSON(resource.Resource, component.Component): """ Sends the response of any rpc calls back to the json-rpc client. """ - response["result"] = result + response['result'] = result return self._send_response(request, response) def _on_rpc_request_failed(self, reason, response, request): @@ -179,7 +179,7 @@ class JSON(resource.Resource, component.Component): Handles any failures that occurred while making an rpc call. """ log.exception(reason) - response["error"] = {"message": "%s: %s" % (reason.__class__.__name__, str(reason)), "code": 4} + response['error'] = {'message': '%s: %s' % (reason.__class__.__name__, str(reason)), 'code': 4} return self._send_response(request, response) def _on_json_request(self, request): @@ -187,16 +187,16 @@ class JSON(resource.Resource, component.Component): Handler to take the json data as a string and pass it on to the _handle_request method for further processing. """ - log.debug("json-request: %s", request.json) - response = {"result": None, "error": None, "id": None} - response["id"], d, response["error"] = self._handle_request(request) + log.debug('json-request: %s', request.json) + response = {'result': None, 'error': None, 'id': None} + response['id'], d, response['error'] = self._handle_request(request) if isinstance(d, Deferred): d.addCallback(self._on_rpc_request_finished, response, request) d.addErrback(self._on_rpc_request_failed, response, request) return d else: - response["result"] = d + response['result'] = d return self._send_response(request, response) def _on_json_request_failed(self, reason, request): @@ -204,16 +204,16 @@ class JSON(resource.Resource, component.Component): Returns the error in json response. """ log.exception(reason) - response = {"result": None, "id": None, - "error": {"code": 5, - "message": "%s: %s" % (reason.__class__.__name__, str(reason))}} + response = {'result': None, 'id': None, + 'error': {'code': 5, + 'message': '%s: %s' % (reason.__class__.__name__, str(reason))}} return self._send_response(request, response) def _send_response(self, request, response): if request._disconnected: - return "" + return '' response = json.dumps(response) - request.setHeader("content-type", "application/x-json") + request.setHeader('content-type', 'application/x-json') request.write(compress(response, request)) request.finish() return server.NOT_DONE_YET @@ -222,7 +222,7 @@ class JSON(resource.Resource, component.Component): """ Handles all the POST requests made to the /json controller. """ - if request.method != "POST": + if request.method != 'POST': request.setResponseCode(http.NOT_ALLOWED) request.finish() return server.NOT_DONE_YET @@ -249,11 +249,11 @@ class JSON(resource.Resource, component.Component): name = name.lower() for d in dir(obj): - if d[0] == "_": + if d[0] == '_': continue if getattr(getattr(obj, d), '_json_export', False): - log.debug("Registering method: %s", name + "." + d) - self._local_methods[name + "." + d] = getattr(obj, d) + log.debug('Registering method: %s', name + '.' + d) + self._local_methods[name + '.' + d] = getattr(obj, d) HOSTLIST_ID = 0 @@ -269,7 +269,7 @@ HOSTS_USER = HOSTLIST_USER HOSTS_STATUS = 3 HOSTS_INFO = 4 -FILES_KEYS = ["files", "file_progress", "file_priorities"] +FILES_KEYS = ['files', 'file_progress', 'file_priorities'] class EventQueue(object): @@ -363,45 +363,45 @@ class WebApi(JSONComponent): """ def __init__(self): - super(WebApi, self).__init__("Web", depend=["SessionProxy"]) - self.host_list = ConfigManager("hostlist.conf.1.2", uicommon.DEFAULT_HOSTS) + super(WebApi, self).__init__('Web', depend=['SessionProxy']) + self.host_list = ConfigManager('hostlist.conf.1.2', uicommon.DEFAULT_HOSTS) if not os.path.isfile(self.host_list.config_file): self.host_list.save() self.core_config = CoreConfig() self.event_queue = EventQueue() try: - self.sessionproxy = component.get("SessionProxy") + self.sessionproxy = component.get('SessionProxy') except KeyError: self.sessionproxy = SessionProxy() def disable(self): - client.deregister_event_handler("PluginEnabledEvent", self._json.get_remote_methods) - client.deregister_event_handler("PluginDisabledEvent", self._json.get_remote_methods) + client.deregister_event_handler('PluginEnabledEvent', self._json.get_remote_methods) + client.deregister_event_handler('PluginDisabledEvent', self._json.get_remote_methods) if client.is_standalone(): - component.get("Web.PluginManager").stop() + component.get('Web.PluginManager').stop() else: client.disconnect() client.set_disconnect_callback(None) def enable(self): - client.register_event_handler("PluginEnabledEvent", self._json.get_remote_methods) - client.register_event_handler("PluginDisabledEvent", self._json.get_remote_methods) + client.register_event_handler('PluginEnabledEvent', self._json.get_remote_methods) + client.register_event_handler('PluginDisabledEvent', self._json.get_remote_methods) if client.is_standalone(): - component.get("Web.PluginManager").start() + component.get('Web.PluginManager').start() else: client.set_disconnect_callback(self._on_client_disconnect) - if component.get("DelugeWeb").config["default_daemon"]: + if component.get('DelugeWeb').config['default_daemon']: # Sort out getting the default daemon here - default_host_id = component.get("DelugeWeb").config["default_daemon"] - host_info = component.get("Web")._get_host(default_host_id) + default_host_id = component.get('DelugeWeb').config['default_daemon'] + host_info = component.get('Web')._get_host(default_host_id) return self._connect_daemon(*host_info[1:]) return defer.succeed(True) def _on_client_disconnect(self, *args): - component.get("Web.PluginManager").stop() + component.get('Web.PluginManager').stop() return self.stop() def _get_host(self, host_id): @@ -415,7 +415,7 @@ class WebApi(JSONComponent): """ host_info = [] - for host_entry in self.host_list["hosts"]: + for host_entry in self.host_list['hosts']: if host_entry[0] == host_id: host_info = host_entry break @@ -430,7 +430,7 @@ class WebApi(JSONComponent): self.sessionproxy.stop() return defer.succeed(True) - def _connect_daemon(self, host="localhost", port=58846, username="", password=""): + def _connect_daemon(self, host='localhost', port=58846, username='', password=''): """ Connects the client to a daemon """ @@ -442,7 +442,7 @@ class WebApi(JSONComponent): invokes retrieving the method names. """ d = self._json.get_remote_methods() - component.get("Web.PluginManager").start() + component.get('Web.PluginManager').start() self.start() return d @@ -461,7 +461,7 @@ class WebApi(JSONComponent): host = self._get_host(host_id) if host: return self._connect_daemon(*host[1:]) - return defer.fail(Exception("Bad host id")) + return defer.fail(Exception('Bad host id')) @export def connected(self): @@ -499,13 +499,13 @@ class WebApi(JSONComponent): """ d = Deferred() ui_info = { - "connected": client.connected(), - "torrents": None, - "filters": None, - "stats": { - "max_download": self.core_config.get("max_download_speed"), - "max_upload": self.core_config.get("max_upload_speed"), - "max_num_connections": self.core_config.get("max_connections_global") + 'connected': client.connected(), + 'torrents': None, + 'filters': None, + 'stats': { + 'max_download': self.core_config.get('max_download_speed'), + 'max_upload': self.core_config.get('max_upload_speed'), + 'max_num_connections': self.core_config.get('max_connections_global') } } @@ -514,47 +514,47 @@ class WebApi(JSONComponent): return d def got_stats(stats): - ui_info["stats"]["num_connections"] = stats["num_peers"] - ui_info["stats"]["upload_rate"] = stats["payload_upload_rate"] - ui_info["stats"]["download_rate"] = stats["payload_download_rate"] - ui_info["stats"]["download_protocol_rate"] = stats["download_rate"] - stats["payload_download_rate"] - ui_info["stats"]["upload_protocol_rate"] = stats["upload_rate"] - stats["payload_upload_rate"] - ui_info["stats"]["dht_nodes"] = stats["dht_nodes"] - ui_info["stats"]["has_incoming_connections"] = stats["has_incoming_connections"] + ui_info['stats']['num_connections'] = stats['num_peers'] + ui_info['stats']['upload_rate'] = stats['payload_upload_rate'] + ui_info['stats']['download_rate'] = stats['payload_download_rate'] + ui_info['stats']['download_protocol_rate'] = stats['download_rate'] - stats['payload_download_rate'] + ui_info['stats']['upload_protocol_rate'] = stats['upload_rate'] - stats['payload_upload_rate'] + ui_info['stats']['dht_nodes'] = stats['dht_nodes'] + ui_info['stats']['has_incoming_connections'] = stats['has_incoming_connections'] def got_filters(filters): - ui_info["filters"] = filters + ui_info['filters'] = filters def got_free_space(free_space): - ui_info["stats"]["free_space"] = free_space + ui_info['stats']['free_space'] = free_space def got_external_ip(external_ip): - ui_info["stats"]["external_ip"] = external_ip + ui_info['stats']['external_ip'] = external_ip def got_torrents(torrents): - ui_info["torrents"] = torrents + ui_info['torrents'] = torrents def on_complete(result): d.callback(ui_info) - d1 = component.get("SessionProxy").get_torrents_status(filter_dict, keys) + d1 = component.get('SessionProxy').get_torrents_status(filter_dict, keys) d1.addCallback(got_torrents) d2 = client.core.get_filter_tree() d2.addCallback(got_filters) d3 = client.core.get_session_status([ - "num_peers", - "payload_download_rate", - "payload_upload_rate", - "download_rate", - "upload_rate", - "dht_nodes", - "has_incoming_connections" + 'num_peers', + 'payload_download_rate', + 'payload_upload_rate', + 'download_rate', + 'upload_rate', + 'dht_nodes', + 'has_incoming_connections' ]) d3.addCallback(got_stats) - d4 = client.core.get_free_space(self.core_config.get("download_location")) + d4 = client.core.get_free_space(self.core_config.get('download_location')) d4.addCallback(got_free_space) d5 = client.core.get_external_ip() @@ -565,40 +565,40 @@ class WebApi(JSONComponent): return d def _on_got_files(self, torrent, d): - files = torrent.get("files") - file_progress = torrent.get("file_progress") - file_priorities = torrent.get("file_priorities") + files = torrent.get('files') + file_progress = torrent.get('file_progress') + file_priorities = torrent.get('file_priorities') paths = [] info = {} for index, torrent_file in enumerate(files): - path = torrent_file["path"] + path = torrent_file['path'] paths.append(path) - torrent_file["progress"] = file_progress[index] - torrent_file["priority"] = file_priorities[index] - torrent_file["index"] = index - torrent_file["path"] = path + torrent_file['progress'] = file_progress[index] + torrent_file['priority'] = file_priorities[index] + torrent_file['index'] = index + torrent_file['path'] = path info[path] = torrent_file # update the directory info dirname = os.path.dirname(path) while dirname: dirinfo = info.setdefault(dirname, {}) - dirinfo["size"] = dirinfo.get("size", 0) + torrent_file["size"] - if "priority" not in dirinfo: - dirinfo["priority"] = torrent_file["priority"] + dirinfo['size'] = dirinfo.get('size', 0) + torrent_file['size'] + if 'priority' not in dirinfo: + dirinfo['priority'] = torrent_file['priority'] else: - if dirinfo["priority"] != torrent_file["priority"]: - dirinfo["priority"] = 9 + if dirinfo['priority'] != torrent_file['priority']: + dirinfo['priority'] = 9 - progresses = dirinfo.setdefault("progresses", []) - progresses.append(torrent_file["size"] * torrent_file["progress"] / 100) - dirinfo["progress"] = sum(progresses) / dirinfo["size"] * 100 - dirinfo["path"] = dirname + progresses = dirinfo.setdefault('progresses', []) + progresses.append(torrent_file['size'] * torrent_file['progress'] / 100) + dirinfo['progress'] = sum(progresses) / dirinfo['size'] * 100 + dirinfo['path'] = dirname dirname = os.path.dirname(dirname) def walk(path, item): - if item["type"] == "dir": + if item['type'] == 'dir': item.update(info[path]) return item else: @@ -611,7 +611,7 @@ class WebApi(JSONComponent): @export def get_torrent_status(self, torrent_id, keys): - return component.get("SessionProxy").get_torrent_status(torrent_id, keys) + return component.get('SessionProxy').get_torrent_status(torrent_id, keys) @export def get_torrent_files(self, torrent_id): @@ -624,7 +624,7 @@ class WebApi(JSONComponent): :rtype: dictionary """ main_deferred = Deferred() - d = component.get("SessionProxy").get_torrent_status(torrent_id, FILES_KEYS) + d = component.get('SessionProxy').get_torrent_status(torrent_id, FILES_KEYS) d.addCallback(self._on_got_files, main_deferred) return main_deferred @@ -640,20 +640,20 @@ class WebApi(JSONComponent): """ def on_download_success(result): - log.debug("Successfully downloaded %s to %s", url, result) + log.debug('Successfully downloaded %s to %s', url, result) return result def on_download_fail(result): - log.error("Failed to add torrent from url %s", url) + log.error('Failed to add torrent from url %s', url) return result - tempdir = tempfile.mkdtemp(prefix="delugeweb-") - tmp_file = os.path.join(tempdir, url.split("/")[-1]) - log.debug("filename: %s", tmp_file) + tempdir = tempfile.mkdtemp(prefix='delugeweb-') + tmp_file = os.path.join(tempdir, url.split('/')[-1]) + log.debug('filename: %s', tmp_file) headers = {} if cookie: - headers["Cookie"] = cookie - log.debug("cookie: %s", cookie) + headers['Cookie'] = cookie + log.debug('cookie: %s', cookie) d = httpdownloader.download_file(url, tmp_file, headers=headers) d.addCallbacks(on_download_success, on_download_fail) return d @@ -680,7 +680,7 @@ class WebApi(JSONComponent): """ try: torrent_info = uicommon.TorrentInfo(filename.strip(), 2) - return torrent_info.as_dict("name", "info_hash", "files_tree") + return torrent_info.as_dict('name', 'info_hash', 'files_tree') except Exception as ex: log.exception(ex) return False @@ -709,18 +709,18 @@ class WebApi(JSONComponent): deferreds = [] for torrent in torrents: - if common.is_magnet(torrent["path"]): - log.info("Adding torrent from magnet uri `%s` with options `%r`", - torrent["path"], torrent["options"]) - d = client.core.add_torrent_magnet(torrent["path"], torrent["options"]) + if common.is_magnet(torrent['path']): + log.info('Adding torrent from magnet uri `%s` with options `%r`', + torrent['path'], torrent['options']) + d = client.core.add_torrent_magnet(torrent['path'], torrent['options']) deferreds.append(d) else: - filename = os.path.basename(torrent["path"]) - with open(torrent["path"], "rb") as _file: + filename = os.path.basename(torrent['path']) + with open(torrent['path'], 'rb') as _file: fdump = base64.encodestring(_file.read()) - log.info("Adding torrent from file `%s` with options `%r`", - filename, torrent["options"]) - d = client.core.add_torrent_file(filename, fdump, torrent["options"]) + log.info('Adding torrent from file `%s` with options `%r`', + filename, torrent['options']) + d = client.core.add_torrent_file(filename, fdump, torrent['options']) deferreds.append(d) return DeferredList(deferreds, consumeErrors=False) @@ -729,8 +729,8 @@ class WebApi(JSONComponent): """ Return the hosts in the hostlist. """ - log.debug("get_hosts called") - return [(tuple(host[HOSTS_ID:HOSTS_USER + 1]) + ("Offline",)) for host in self.host_list["hosts"]] + log.debug('get_hosts called') + return [(tuple(host[HOSTS_ID:HOSTS_USER + 1]) + ('Offline',)) for host in self.host_list['hosts']] @export def get_host_status(self, host_id): @@ -748,30 +748,30 @@ class WebApi(JSONComponent): except TypeError: host = None port = None - return response("Offline") + return response('Offline') def on_connect(connected, c, host_id): def on_info(info, c): c.disconnect() - return response("Online", info) + return response('Online', info) def on_info_fail(reason, c): c.disconnect() - return response("Offline") + return response('Offline') if not connected: - return response("Offline") + return response('Offline') return c.daemon.info().addCallback(on_info, c).addErrback(on_info_fail, c) def on_connect_failed(reason, host_id): - return response("Offline") + return response('Offline') - if client.connected() and (host, port, "localclient" if not - user and host in ("127.0.0.1", "localhost") else + if client.connected() and (host, port, 'localclient' if not + user and host in ('127.0.0.1', 'localhost') else user) == client.connection_info(): def on_info(info): - return response("Connected", info) + return response('Connected', info) return client.daemon.info().addCallback(on_info) else: @@ -804,7 +804,7 @@ class WebApi(JSONComponent): try: def on_connect(connected, c): if not connected: - main_deferred.callback((False, _("Daemon not running"))) + main_deferred.callback((False, _('Daemon not running'))) return c.daemon.shutdown() main_deferred.callback((True, )) @@ -818,11 +818,11 @@ class WebApi(JSONComponent): d.addCallback(on_connect, c) d.addErrback(on_connect_failed) except Exception: - main_deferred.callback((False, "An error occurred")) + main_deferred.callback((False, 'An error occurred')) return main_deferred @export - def add_host(self, host, port, username="", password=""): + def add_host(self, host, port, username='', password=''): """ Adds a host to the list. @@ -838,18 +838,18 @@ class WebApi(JSONComponent): """ # Check to see if there is already an entry for this host and return # if thats the case - for entry in self.host_list["hosts"]: + for entry in self.host_list['hosts']: if (entry[1], entry[2], entry[3]) == (host, port, username): - return (False, "Host already in the list") + return (False, 'Host already in the list') try: port = int(port) except ValueError: - return (False, "Port is invalid") + return (False, 'Port is invalid') # Host isn't in the list, so lets add it connection_id = hashlib.sha1(str(time.time())).hexdigest() - self.host_list["hosts"].append([connection_id, host, port, username, + self.host_list['hosts'].append([connection_id, host, port, username, password]) self.host_list.save() return True, connection_id @@ -866,7 +866,7 @@ class WebApi(JSONComponent): if not host: return False - self.host_list["hosts"].remove(host) + self.host_list['hosts'].remove(host) self.host_list.save() return True @@ -878,10 +878,10 @@ class WebApi(JSONComponent): :rtype: dictionary :returns: the configuration """ - config = component.get("DelugeWeb").config.config.copy() - del config["sessions"] - del config["pwd_salt"] - del config["pwd_sha1"] + config = component.get('DelugeWeb').config.config.copy() + del config['sessions'] + del config['pwd_salt'] + del config['pwd_sha1'] return config @export @@ -892,13 +892,13 @@ class WebApi(JSONComponent): :param config: The configuration options to update :type config: dictionary """ - web_config = component.get("DelugeWeb").config + web_config = component.get('DelugeWeb').config for key in config.keys(): - if key in ["sessions", "pwd_salt", "pwd_sha1"]: + if key in ['sessions', 'pwd_salt', 'pwd_sha1']: log.warn("Ignored attempt to overwrite web config key '%s'", key) continue if isinstance(config[key], basestring): - config[key] = config[key].encode("utf8") + config[key] = config[key].encode('utf8') web_config[key] = config[key] @export @@ -914,34 +914,34 @@ class WebApi(JSONComponent): """ return { - "enabled_plugins": component.get("Web.PluginManager").plugins.keys(), - "available_plugins": component.get("Web.PluginManager").available_plugins + 'enabled_plugins': component.get('Web.PluginManager').plugins.keys(), + 'available_plugins': component.get('Web.PluginManager').available_plugins } @export def get_plugin_info(self, name): - return component.get("Web.PluginManager").get_plugin_info(name) + return component.get('Web.PluginManager').get_plugin_info(name) @export def get_plugin_resources(self, name): - return component.get("Web.PluginManager").get_plugin_resources(name) + return component.get('Web.PluginManager').get_plugin_resources(name) @export def upload_plugin(self, filename, path): main_deferred = Deferred() - shutil.copyfile(path, os.path.join(get_config_dir(), "plugins", filename)) - component.get("Web.PluginManager").scan_for_plugins() + shutil.copyfile(path, os.path.join(get_config_dir(), 'plugins', filename)) + component.get('Web.PluginManager').scan_for_plugins() if client.is_localhost(): client.core.rescan_plugins() return True - with open(path, "rb") as _file: + with open(path, 'rb') as _file: plugin_data = base64.encodestring(_file.read()) def on_upload_complete(*args): client.core.rescan_plugins() - component.get("Web.PluginManager").scan_for_plugins() + component.get('Web.PluginManager').scan_for_plugins() main_deferred.callback(True) def on_upload_error(*args): @@ -985,7 +985,7 @@ class WebUtils(JSONComponent): Utility functions for the webui that do not fit in the WebApi. """ def __init__(self): - super(WebUtils, self).__init__("WebUtils") + super(WebUtils, self).__init__('WebUtils') @export def get_languages(self): diff --git a/deluge/ui/web/pluginmanager.py b/deluge/ui/web/pluginmanager.py index f5485cfea..f636db5d7 100644 --- a/deluge/ui/web/pluginmanager.py +++ b/deluge/ui/web/pluginmanager.py @@ -20,8 +20,8 @@ log = logging.getLogger(__name__) def gather_info(plugin): # Get the scripts for the plugin - scripts = getattr(plugin, "scripts", ()) - debug_scripts = getattr(plugin, "debug_scripts") or scripts + scripts = getattr(plugin, 'scripts', ()) + debug_scripts = getattr(plugin, 'debug_scripts') or scripts directories = [] for script in scripts + debug_scripts: @@ -29,20 +29,20 @@ def gather_info(plugin): directories.append(os.path.dirname(script)) return { - "scripts": scripts, - "debug_scripts": debug_scripts, - "script_directories": directories + 'scripts': scripts, + 'debug_scripts': debug_scripts, + 'script_directories': directories } class PluginManager(PluginManagerBase, component.Component): def __init__(self): - component.Component.__init__(self, "Web.PluginManager") - self.config = ConfigManager("web.conf") - PluginManagerBase.__init__(self, "web.conf", "deluge.plugin.web") + component.Component.__init__(self, 'Web.PluginManager') + self.config = ConfigManager('web.conf') + PluginManagerBase.__init__(self, 'web.conf', 'deluge.plugin.web') - client.register_event_handler("PluginEnabledEvent", self._on_plugin_enabled_event) - client.register_event_handler("PluginDisabledEvent", self._on_plugin_disabled_event) + client.register_event_handler('PluginEnabledEvent', self._on_plugin_enabled_event) + client.register_event_handler('PluginDisabledEvent', self._on_plugin_disabled_event) def _on_get_enabled_plugins(self, plugins): for plugin in plugins: @@ -57,20 +57,20 @@ class PluginManager(PluginManagerBase, component.Component): def disable_plugin(self, name): # Get the plugin instance try: - plugin = component.get("WebPlugin." + name) + plugin = component.get('WebPlugin.' + name) except KeyError: log.debug("'%s' plugin contains no WebUI code, ignoring WebUI disable call.", name) return info = gather_info(plugin) - scripts = component.get("Scripts") - for script in info["scripts"]: - scripts.remove_script("%s/%s" % (name.lower(), os.path.basename(script).lower())) + scripts = component.get('Scripts') + for script in info['scripts']: + scripts.remove_script('%s/%s' % (name.lower(), os.path.basename(script).lower())) - for script in info["debug_scripts"]: - scripts.remove_script("%s/%s" % (name.lower(), os.path.basename(script).lower()), "debug") - scripts.remove_script("%s/%s" % (name.lower(), os.path.basename(script).lower()), "dev") + for script in info['debug_scripts']: + scripts.remove_script('%s/%s' % (name.lower(), os.path.basename(script).lower()), 'debug') + scripts.remove_script('%s/%s' % (name.lower(), os.path.basename(script).lower()), 'dev') super(PluginManager, self).disable_plugin(name) @@ -79,22 +79,22 @@ class PluginManager(PluginManagerBase, component.Component): # Get the plugin instance try: - plugin = component.get("WebPlugin." + name) + plugin = component.get('WebPlugin.' + name) except KeyError: log.info("'%s' plugin contains no WebUI code, ignoring WebUI enable call.", name) return info = gather_info(plugin) - scripts = component.get("Scripts") - for script in info["scripts"]: - log.debug("adding script %s for %s", name, os.path.basename(script)) - scripts.add_script("%s/%s" % (name.lower(), os.path.basename(script)), script) + scripts = component.get('Scripts') + for script in info['scripts']: + log.debug('adding script %s for %s', name, os.path.basename(script)) + scripts.add_script('%s/%s' % (name.lower(), os.path.basename(script)), script) - for script in info["debug_scripts"]: - log.debug("adding debug script %s for %s", name, os.path.basename(script)) - scripts.add_script("%s/%s" % (name.lower(), os.path.basename(script)), script, "debug") - scripts.add_script("%s/%s" % (name.lower(), os.path.basename(script)), script, "dev") + for script in info['debug_scripts']: + log.debug('adding debug script %s for %s', name, os.path.basename(script)) + scripts.add_script('%s/%s' % (name.lower(), os.path.basename(script)), script, 'debug') + scripts.add_script('%s/%s' % (name.lower(), os.path.basename(script)), script, 'dev') def start(self): """ @@ -109,8 +109,8 @@ class PluginManager(PluginManagerBase, component.Component): Stop the plugin manager """ self.disable_plugins() - client.deregister_event_handler("PluginEnabledEvent", self._on_plugin_enabled_event) - client.deregister_event_handler("PluginDisabledEvent", self._on_plugin_disabled_event) + client.deregister_event_handler('PluginEnabledEvent', self._on_plugin_enabled_event) + client.deregister_event_handler('PluginDisabledEvent', self._on_plugin_disabled_event) def update(self): pass @@ -118,13 +118,13 @@ class PluginManager(PluginManagerBase, component.Component): def get_plugin_resources(self, name): # Get the plugin instance try: - plugin = component.get("WebPlugin." + name) + plugin = component.get('WebPlugin.' + name) except KeyError: - log.info("Plugin has no web ui") + log.info('Plugin has no web ui') return info = gather_info(plugin) - info["name"] = name - info["scripts"] = ["js/%s/%s" % (name.lower(), os.path.basename(s)) for s in info["scripts"]] - info["debug_scripts"] = ["js/%s/%s" % (name.lower(), os.path.basename(s)) for s in info["debug_scripts"]] - del info["script_directories"] + info['name'] = name + info['scripts'] = ['js/%s/%s' % (name.lower(), os.path.basename(s)) for s in info['scripts']] + info['debug_scripts'] = ['js/%s/%s' % (name.lower(), os.path.basename(s)) for s in info['debug_scripts']] + del info['script_directories'] return info diff --git a/deluge/ui/web/server.py b/deluge/ui/web/server.py index 3ec16f824..26a20e268 100644 --- a/deluge/ui/web/server.py +++ b/deluge/ui/web/server.py @@ -33,36 +33,36 @@ log = logging.getLogger(__name__) CONFIG_DEFAULTS = { # Misc Settings - "enabled_plugins": [], - "default_daemon": "", + 'enabled_plugins': [], + 'default_daemon': '', # Auth Settings - "pwd_salt": "c26ab3bbd8b137f99cd83c2c1c0963bcc1a35cad", - "pwd_sha1": "2ce1a410bcdcc53064129b6d950f2e9fee4edc1e", - "session_timeout": 3600, - "sessions": {}, + 'pwd_salt': 'c26ab3bbd8b137f99cd83c2c1c0963bcc1a35cad', + 'pwd_sha1': '2ce1a410bcdcc53064129b6d950f2e9fee4edc1e', + 'session_timeout': 3600, + 'sessions': {}, # UI Settings - "sidebar_show_zero": False, - "sidebar_multiple_filters": True, - "show_session_speed": False, - "show_sidebar": True, - "theme": "gray", - "first_login": True, - "language": "", + 'sidebar_show_zero': False, + 'sidebar_multiple_filters': True, + 'show_session_speed': False, + 'show_sidebar': True, + 'theme': 'gray', + 'first_login': True, + 'language': '', # Server Settings - "base": "/", - "interface": "0.0.0.0", - "port": 8112, - "https": False, - "pkey": "ssl/daemon.pkey", - "cert": "ssl/daemon.cert" + 'base': '/', + 'interface': '0.0.0.0', + 'port': 8112, + 'https': False, + 'pkey': 'ssl/daemon.pkey', + 'cert': 'ssl/daemon.cert' } UI_CONFIG_KEYS = ( - "theme", "sidebar_show_zero", "sidebar_multiple_filters", - "show_session_speed", "base", "first_login" + 'theme', 'sidebar_show_zero', 'sidebar_multiple_filters', + 'show_session_speed', 'base', 'first_login' ) @@ -70,13 +70,13 @@ def rpath(*paths): """Convert a relative path into an absolute path relative to the location of this script. """ - return common.resource_filename("deluge.ui.web", os.path.join(*paths)) + return common.resource_filename('deluge.ui.web', os.path.join(*paths)) class GetText(resource.Resource): def render(self, request): - request.setHeader("content-type", "text/javascript; encoding=utf-8") - template = Template(filename=rpath("js", "gettext.js")) + request.setHeader('content-type', 'text/javascript; encoding=utf-8') + template = Template(filename=rpath('js', 'gettext.js')) return compress(template.render(), request) @@ -92,29 +92,29 @@ class Upload(resource.Resource): """ # Block all other HTTP methods. - if request.method != "POST": + if request.method != 'POST': request.setResponseCode(http.NOT_ALLOWED) - return "" + return '' - if "file" not in request.args: + if 'file' not in request.args: request.setResponseCode(http.OK) return json.dumps({ 'success': True, 'files': [] }) - tempdir = tempfile.mkdtemp(prefix="delugeweb-") - log.debug("uploading files to %s", tempdir) + tempdir = tempfile.mkdtemp(prefix='delugeweb-') + log.debug('uploading files to %s', tempdir) filenames = [] - for upload in request.args.get("file"): + for upload in request.args.get('file'): fd, fn = tempfile.mkstemp('.torrent', dir=tempdir) os.write(fd, upload) os.close(fd) filenames.append(fn) - log.debug("uploaded %d file(s)", len(filenames)) + log.debug('uploaded %d file(s)', len(filenames)) - request.setHeader("content-type", "text/html") + request.setHeader('content-type', 'text/html') request.setResponseCode(http.OK) return compress(json.dumps({ 'success': True, @@ -129,13 +129,13 @@ class Render(resource.Resource): return self def render(self, request): - if not hasattr(request, "render_file"): + if not hasattr(request, 'render_file'): request.setResponseCode(http.INTERNAL_SERVER_ERROR) - return "" + return '' - filename = os.path.join("render", request.render_file) + filename = os.path.join('render', request.render_file) template = Template(filename=rpath(filename)) - request.setHeader("content-type", "text/html") + request.setHeader('content-type', 'text/html') request.setResponseCode(http.OK) return compress(template.render(), request) @@ -145,7 +145,7 @@ class Tracker(resource.Resource): def __init__(self): resource.Resource.__init__(self) try: - self.tracker_icons = component.get("TrackerIcons") + self.tracker_icons = component.get('TrackerIcons') except KeyError: self.tracker_icons = TrackerIcons() @@ -155,9 +155,9 @@ class Tracker(resource.Resource): def on_got_icon(self, icon, request): if icon: - request.setHeader("cache-control", - "public, must-revalidate, max-age=86400") - request.setHeader("content-type", icon.get_mimetype()) + request.setHeader('cache-control', + 'public, must-revalidate, max-age=86400') + request.setHeader('content-type', icon.get_mimetype()) request.setResponseCode(http.OK) request.write(icon.get_data()) request.finish() @@ -177,19 +177,19 @@ class Flag(resource.Resource): return self def render(self, request): - path = ("ui", "data", "pixmaps", "flags", request.country.lower() + ".png") - filename = common.resource_filename("deluge", os.path.join(*path)) + path = ('ui', 'data', 'pixmaps', 'flags', request.country.lower() + '.png') + filename = common.resource_filename('deluge', os.path.join(*path)) if os.path.exists(filename): - request.setHeader("cache-control", - "public, must-revalidate, max-age=86400") - request.setHeader("content-type", "image/png") - with open(filename, "rb") as _file: + request.setHeader('cache-control', + 'public, must-revalidate, max-age=86400') + request.setHeader('content-type', 'image/png') + with open(filename, 'rb') as _file: data = _file.read() request.setResponseCode(http.OK) return data else: request.setResponseCode(http.NOT_FOUND) - return "" + return '' class LookupResource(resource.Resource, component.Component): @@ -202,13 +202,13 @@ class LookupResource(resource.Resource, component.Component): for directory in directories: self.add_directory(directory) - def add_directory(self, directory, path=""): - log.debug("Adding directory `%s` with path `%s`", directory, path) + def add_directory(self, directory, path=''): + log.debug('Adding directory `%s` with path `%s`', directory, path) paths = self.__paths.setdefault(path, []) paths.append(directory) - def remove_directory(self, directory, path=""): - log.debug("Removing directory `%s`", directory) + def remove_directory(self, directory, path=''): + log.debug('Removing directory `%s`', directory) self.__paths[path].remove(directory) def getChild(self, path, request): # NOQA @@ -224,7 +224,7 @@ class LookupResource(resource.Resource, component.Component): if path not in self.__paths: request.setResponseCode(http.NOT_FOUND) - return "<h1>404 - Not Found</h1>" + return '<h1>404 - Not Found</h1>' filename = os.path.basename(request.path) for directory in self.__paths[path]: @@ -232,23 +232,23 @@ class LookupResource(resource.Resource, component.Component): path = os.path.join(directory, filename) log.debug("Serving path: '%s'", path) mime_type = mimetypes.guess_type(path) - request.setHeader("content-type", mime_type[0]) - with open(path, "rb") as _file: + request.setHeader('content-type', mime_type[0]) + with open(path, 'rb') as _file: data = _file.read() return compress(data, request) request.setResponseCode(http.NOT_FOUND) - return "<h1>404 - Not Found</h1>" + return '<h1>404 - Not Found</h1>' class ScriptResource(resource.Resource, component.Component): def __init__(self): resource.Resource.__init__(self) - component.Component.__init__(self, "Scripts") + component.Component.__init__(self, 'Scripts') self.__scripts = {} - for script_type in ["normal", "debug", "dev"]: - self.__scripts[script_type] = {"scripts": {}, "order": [], "files_exist": True} + for script_type in ['normal', 'debug', 'dev']: + self.__scripts[script_type] = {'scripts': {}, 'order': [], 'files_exist': True} def has_script_type_files(self, script_type): """Returns whether all the script files exist for this script type. @@ -260,7 +260,7 @@ class ScriptResource(resource.Resource, component.Component): bool: True if the files for this script type exist, otherwise False. """ - return self.__scripts[script_type]["files_exist"] + return self.__scripts[script_type]['files_exist'] def add_script(self, path, filepath, script_type=None): """ @@ -273,13 +273,13 @@ class ScriptResource(resource.Resource, component.Component): :keyword script_type: The type of script to add (normal, debug, dev) :param script_type: string """ - if script_type not in ("dev", "debug", "normal"): - script_type = "normal" + if script_type not in ('dev', 'debug', 'normal'): + script_type = 'normal' - self.__scripts[script_type]["scripts"][path] = filepath - self.__scripts[script_type]["order"].append(path) + self.__scripts[script_type]['scripts'][path] = filepath + self.__scripts[script_type]['order'].append(path) if not os.path.isfile(filepath): - self.__scripts[script_type]["files_exist"] = False + self.__scripts[script_type]['files_exist'] = False def add_script_folder(self, path, filepath, script_type=None, recurse=True): """ @@ -294,13 +294,13 @@ class ScriptResource(resource.Resource, component.Component): :keyword recurse: Whether or not to recurse into other folders :param recurse: bool """ - if script_type not in ("dev", "debug", "normal"): - script_type = "normal" + if script_type not in ('dev', 'debug', 'normal'): + script_type = 'normal' - self.__scripts[script_type]["scripts"][path] = (filepath, recurse) - self.__scripts[script_type]["order"].append(path) + self.__scripts[script_type]['scripts'][path] = (filepath, recurse) + self.__scripts[script_type]['order'].append(path) if not os.path.isdir(filepath): - self.__scripts[script_type]["files_exist"] = False + self.__scripts[script_type]['files_exist'] = False def remove_script(self, path, script_type=None): """ @@ -311,11 +311,11 @@ class ScriptResource(resource.Resource, component.Component): :keyword script_type: The type of script to add (normal, debug, dev) :param script_type: string """ - if script_type not in ("dev", "debug", "normal"): - script_type = "normal" + if script_type not in ('dev', 'debug', 'normal'): + script_type = 'normal' - del self.__scripts[script_type]["scripts"][path] - self.__scripts[script_type]["order"].remove(path) + del self.__scripts[script_type]['scripts'][path] + self.__scripts[script_type]['order'].remove(path) def get_scripts(self, script_type=None): """ @@ -325,11 +325,11 @@ class ScriptResource(resource.Resource, component.Component): :keyword script_type: The type of scripts to get (normal, debug, dev) :param script_type: string """ - if script_type not in ("dev", "debug", "normal"): + if script_type not in ('dev', 'debug', 'normal'): script_type = 'normal' - _scripts = self.__scripts[script_type]["scripts"] - _order = self.__scripts[script_type]["order"] + _scripts = self.__scripts[script_type]['scripts'] + _order = self.__scripts[script_type]['order'] scripts = [] for path in _order: @@ -340,34 +340,34 @@ class ScriptResource(resource.Resource, component.Component): filepath, recurse = _scripts[path] for root, dirnames, filenames in os.walk(filepath): dirnames.sort(reverse=True) - files = sorted(fnmatch.filter(filenames, "*.js")) + files = sorted(fnmatch.filter(filenames, '*.js')) - order_file = os.path.join(root, ".order") + order_file = os.path.join(root, '.order') if os.path.isfile(order_file): - with open(order_file, "r") as _file: + with open(order_file, 'r') as _file: for line in _file: - if line.startswith("+ "): + if line.startswith('+ '): order_filename = line.split()[1] files.pop(files.index(order_filename)) files.insert(0, order_filename) # Ensure sub-directory scripts are top of list with root directory scripts bottom. if dirnames: - scripts.extend(["js/" + os.path.basename(root) + "/" + f for f in files]) + scripts.extend(['js/' + os.path.basename(root) + '/' + f for f in files]) else: - dirpath = os.path.basename(os.path.dirname(root)) + "/" + os.path.basename(root) + dirpath = os.path.basename(os.path.dirname(root)) + '/' + os.path.basename(root) for filename in reversed(files): - scripts.insert(script_idx, "js/" + dirpath + "/" + filename) + scripts.insert(script_idx, 'js/' + dirpath + '/' + filename) if not recurse: break else: - scripts.append("js/" + path) + scripts.append('js/' + path) return scripts def getChild(self, path, request): # NOQA - if hasattr(request, "lookup_path"): - request.lookup_path += "/" + path + if hasattr(request, 'lookup_path'): + request.lookup_path += '/' + path else: request.lookup_path = path return self @@ -375,8 +375,8 @@ class ScriptResource(resource.Resource, component.Component): def render(self, request): log.debug("Requested path: '%s'", request.lookup_path) - for script_type in ("dev", "debug", "normal"): - scripts = self.__scripts[script_type]["scripts"] + for script_type in ('dev', 'debug', 'normal'): + scripts = self.__scripts[script_type]['scripts'] for pattern in scripts: if not request.lookup_path.startswith(pattern): continue @@ -392,64 +392,64 @@ class ScriptResource(resource.Resource, component.Component): log.debug("Serving path: '%s'", path) mime_type = mimetypes.guess_type(path) - request.setHeader("content-type", mime_type[0]) - with open(path, "rb") as _file: + request.setHeader('content-type', mime_type[0]) + with open(path, 'rb') as _file: data = _file.read() return compress(data, request) request.setResponseCode(http.NOT_FOUND) - return "<h1>404 - Not Found</h1>" + return '<h1>404 - Not Found</h1>' class TopLevel(resource.Resource): addSlash = True __stylesheets = [ - "css/ext-all-notheme.css", - "css/ext-extensions.css", - "css/deluge.css" + 'css/ext-all-notheme.css', + 'css/ext-extensions.css', + 'css/deluge.css' ] def __init__(self): resource.Resource.__init__(self) - self.putChild("css", LookupResource("Css", rpath("css"))) - self.putChild("gettext.js", GetText()) - self.putChild("flag", Flag()) - self.putChild("icons", LookupResource("Icons", rpath("icons"))) - self.putChild("images", LookupResource("Images", rpath("images"))) + self.putChild('css', LookupResource('Css', rpath('css'))) + self.putChild('gettext.js', GetText()) + self.putChild('flag', Flag()) + self.putChild('icons', LookupResource('Icons', rpath('icons'))) + self.putChild('images', LookupResource('Images', rpath('images'))) js = ScriptResource() # configure the dev scripts - js.add_script("ext-base-debug.js", rpath("js", "extjs", "ext-base-debug.js"), "dev") - js.add_script("ext-all-debug.js", rpath("js", "extjs", "ext-all-debug.js"), "dev") - js.add_script_folder("ext-extensions", rpath("js", "extjs", "ext-extensions"), "dev") - js.add_script_folder("deluge-all", rpath("js", "deluge-all"), "dev") + js.add_script('ext-base-debug.js', rpath('js', 'extjs', 'ext-base-debug.js'), 'dev') + js.add_script('ext-all-debug.js', rpath('js', 'extjs', 'ext-all-debug.js'), 'dev') + js.add_script_folder('ext-extensions', rpath('js', 'extjs', 'ext-extensions'), 'dev') + js.add_script_folder('deluge-all', rpath('js', 'deluge-all'), 'dev') # configure the debug scripts - js.add_script("ext-base-debug.js", rpath("js", "extjs", "ext-base-debug.js"), "debug") - js.add_script("ext-all-debug.js", rpath("js", "extjs", "ext-all-debug.js"), "debug") - js.add_script("ext-extensions-debug.js", rpath("js", "extjs", "ext-extensions-debug.js"), "debug") - js.add_script("deluge-all-debug.js", rpath("js", "deluge-all-debug.js"), "debug") + js.add_script('ext-base-debug.js', rpath('js', 'extjs', 'ext-base-debug.js'), 'debug') + js.add_script('ext-all-debug.js', rpath('js', 'extjs', 'ext-all-debug.js'), 'debug') + js.add_script('ext-extensions-debug.js', rpath('js', 'extjs', 'ext-extensions-debug.js'), 'debug') + js.add_script('deluge-all-debug.js', rpath('js', 'deluge-all-debug.js'), 'debug') # configure the normal scripts - js.add_script("ext-base.js", rpath("js", "extjs", "ext-base.js")) - js.add_script("ext-all.js", rpath("js", "extjs", "ext-all.js")) - js.add_script("ext-extensions.js", rpath("js", "extjs", "ext-extensions.js")) - js.add_script("deluge-all.js", rpath("js", "deluge-all.js")) + js.add_script('ext-base.js', rpath('js', 'extjs', 'ext-base.js')) + js.add_script('ext-all.js', rpath('js', 'extjs', 'ext-all.js')) + js.add_script('ext-extensions.js', rpath('js', 'extjs', 'ext-extensions.js')) + js.add_script('deluge-all.js', rpath('js', 'deluge-all.js')) self.js = js - self.putChild("js", js) - self.putChild("json", JSON()) - self.putChild("upload", Upload()) - self.putChild("render", Render()) - self.putChild("themes", static.File(rpath("themes"))) - self.putChild("tracker", Tracker()) - - theme = component.get("DelugeWeb").config["theme"] - if not os.path.isfile(rpath("themes", "css", "xtheme-%s.css" % theme)): - theme = CONFIG_DEFAULTS.get("theme") - self.__stylesheets.insert(1, "themes/css/xtheme-%s.css" % theme) + self.putChild('js', js) + self.putChild('json', JSON()) + self.putChild('upload', Upload()) + self.putChild('render', Render()) + self.putChild('themes', static.File(rpath('themes'))) + self.putChild('tracker', Tracker()) + + theme = component.get('DelugeWeb').config['theme'] + if not os.path.isfile(rpath('themes', 'css', 'xtheme-%s.css' % theme)): + theme = CONFIG_DEFAULTS.get('theme') + self.__stylesheets.insert(1, 'themes/css/xtheme-%s.css' % theme) @property def stylesheets(self): @@ -478,7 +478,7 @@ class TopLevel(resource.Resource): self.__debug_scripts.remove(script) def getChild(self, path, request): # NOQA - if path == "": + if path == '': return self else: return resource.Resource.getChild(self, path, request) @@ -486,7 +486,7 @@ class TopLevel(resource.Resource): def getChildWithDefault(self, path, request): # NOQA # Calculate the request base header = request.getHeader('x-deluge-base') - base = header if header else component.get("DelugeWeb").base + base = header if header else component.get('DelugeWeb').base # validate the base parameter if not base: @@ -503,37 +503,37 @@ class TopLevel(resource.Resource): return resource.Resource.getChildWithDefault(self, path, request) def render(self, request): - uri_true = ("true", "yes", "1") - debug_arg = request.args.get("debug", [""])[-1] in uri_true - dev_arg = request.args.get("dev", [""])[-1] in uri_true - dev_ver = "dev" in common.get_version() + uri_true = ('true', 'yes', '1') + debug_arg = request.args.get('debug', [''])[-1] in uri_true + dev_arg = request.args.get('dev', [''])[-1] in uri_true + dev_ver = 'dev' in common.get_version() - script_type = "normal" + script_type = 'normal' if debug_arg: - script_type = "debug" + script_type = 'debug' # Override debug if dev arg or version. if dev_arg or dev_ver: - script_type = "dev" + script_type = 'dev' if not self.js.has_script_type_files(script_type): if not dev_ver: log.warning("Failed to enable WebUI '%s' mode, script files are missing!", script_type) # Fallback to checking other types in order and selecting first with files available. - for alt_script_type in [x for x in ["normal", "debug", "dev"] if x != script_type]: + for alt_script_type in [x for x in ['normal', 'debug', 'dev'] if x != script_type]: if self.js.has_script_type_files(alt_script_type): script_type = alt_script_type if not dev_ver: log.warning("WebUI falling back to '%s' mode.", script_type) break - scripts = component.get("Scripts").get_scripts(script_type) - scripts.insert(0, "gettext.js") + scripts = component.get('Scripts').get_scripts(script_type) + scripts.insert(0, 'gettext.js') - template = Template(filename=rpath("index.html")) - request.setHeader("content-type", "text/html; charset=utf-8") + template = Template(filename=rpath('index.html')) + request.setHeader('content-type', 'text/html; charset=utf-8') - web_config = component.get("Web").get_config() - web_config["base"] = request.base + web_config = component.get('Web').get_config() + web_config['base'] = request.base config = dict([(key, web_config[key]) for key in UI_CONFIG_KEYS]) js_config = json.dumps(config) # Insert the values into 'index.html' and return. @@ -553,19 +553,19 @@ class DelugeWeb(component.Component): reactor). If False shares the process and twisted reactor from WebUI plugin or tests. """ - component.Component.__init__(self, "DelugeWeb", depend=["Web"]) - self.config = configmanager.ConfigManager("web.conf", defaults=CONFIG_DEFAULTS, file_version=2) + component.Component.__init__(self, 'DelugeWeb', depend=['Web']) + self.config = configmanager.ConfigManager('web.conf', defaults=CONFIG_DEFAULTS, file_version=2) self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2) - self.config.register_set_function("language", self._on_language_changed) + self.config.register_set_function('language', self._on_language_changed) self.socket = None self.top_level = TopLevel() - self.interface = self.config["interface"] - self.port = self.config["port"] - self.https = self.config["https"] - self.pkey = self.config["pkey"] - self.cert = self.config["cert"] - self.base = self.config["base"] + self.interface = self.config['interface'] + self.port = self.config['port'] + self.https = self.config['https'] + self.pkey = self.config['pkey'] + self.cert = self.config['cert'] + self.base = self.config['base'] if options: self.interface = options.interface if options.interface else self.interface @@ -576,7 +576,7 @@ class DelugeWeb(component.Component): elif options.no_ssl: self.https = False - if self.base != "/": + if self.base != '/': # Strip away slashes and serve on the base path as well as root path self.top_level.putChild(self.base.strip('/'), self.top_level) @@ -598,7 +598,7 @@ class DelugeWeb(component.Component): def install_signal_handlers(self): # Since twisted assigns itself all the signals may as well make # use of it. - reactor.addSystemEventTrigger("after", "shutdown", self.shutdown) + reactor.addSystemEventTrigger('after', 'shutdown', self.shutdown) # Twisted doesn't handle windows specific signals so we still # need to attach to those to handle the close correctly. @@ -607,7 +607,7 @@ class DelugeWeb(component.Component): from win32con import CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT def win_handler(ctrl_type): - log.debug("ctrl type: %s", ctrl_type) + log.debug('ctrl type: %s', ctrl_type) if ctrl_type == CTRL_CLOSE_EVENT or \ ctrl_type == CTRL_SHUTDOWN_EVENT: self.shutdown() @@ -619,27 +619,27 @@ class DelugeWeb(component.Component): Start the DelugeWeb server """ if self.socket: - log.warn("DelugeWeb is already running and cannot be started") + log.warn('DelugeWeb is already running and cannot be started') return - log.info("Starting webui server at PID %s", os.getpid()) + log.info('Starting webui server at PID %s', os.getpid()) if self.https: self.start_ssl() else: self.start_normal() - component.get("Web").enable() + component.get('Web').enable() if self.daemon: reactor.run() def start_normal(self): self.socket = reactor.listenTCP(self.port, self.site, interface=self.interface) - log.info("Serving at http://%s:%s%s", self.interface, self.port, self.base) + log.info('Serving at http://%s:%s%s', self.interface, self.port, self.base) def start_ssl(self): check_ssl_keys() - log.debug("Enabling SSL with PKey: %s, Cert: %s", self.pkey, self.cert) + log.debug('Enabling SSL with PKey: %s, Cert: %s', self.pkey, self.cert) with open(configmanager.get_config_dir(self.cert)) as cert: certificate = Certificate.loadPEM(cert.read()).original @@ -649,17 +649,17 @@ class DelugeWeb(component.Component): options.getContext().set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3) self.socket = reactor.listenSSL(self.port, self.site, options, interface=self.interface) - log.info("Serving at https://%s:%s%s", self.interface, self.port, self.base) + log.info('Serving at https://%s:%s%s', self.interface, self.port, self.base) def stop(self): - log.info("Shutting down webserver") + log.info('Shutting down webserver') try: - component.get("Web").disable() + component.get('Web').disable() except KeyError: pass self.plugins.disable_plugins() - log.debug("Saving configuration file") + log.debug('Saving configuration file') self.config.save() if self.socket: @@ -676,16 +676,16 @@ class DelugeWeb(component.Component): reactor.stop() def _migrate_config_1_to_2(self, config): - config["language"] = CONFIG_DEFAULTS["language"] + config['language'] = CONFIG_DEFAULTS['language'] return config -if __name__ == "__builtin__": +if __name__ == '__builtin__': deluge_web = DelugeWeb() - application = service.Application("DelugeWeb") + application = service.Application('DelugeWeb') sc = service.IServiceCollection(application) i = internet.TCPServer(deluge_web.port, deluge_web.site) i.setServiceParent(sc) -elif __name__ == "__main__": +elif __name__ == '__main__': deluge_web = DelugeWeb() deluge_web.start() diff --git a/deluge/ui/web/web.py b/deluge/ui/web/web.py index dd3aab5b7..38c725aed 100644 --- a/deluge/ui/web/web.py +++ b/deluge/ui/web/web.py @@ -24,18 +24,18 @@ class Web(UI): cmd_description = """Web-based user interface (http://localhost:8112)""" def __init__(self, *args, **kwargs): - super(Web, self).__init__("web", *args, description="Starts the Deluge Web interface", **kwargs) + super(Web, self).__init__('web', *args, description='Starts the Deluge Web interface', **kwargs) self.__server = None - group = self.parser.add_argument_group(_("Web Server Options")) - group.add_argument("-i", "--interface", metavar="<ip_address>", action="store", - help=_("IP address for web server to listen on")) - group.add_argument("-p", "--port", metavar="<port>", type=int, action="store", - help=_("Port for web server to listen on")) - group.add_argument("-b", "--base", metavar="<path>", action="store", - help=_("Set the base path that the ui is running on")) - group.add_argument("--ssl", action="store_true", help=_("Force the web server to use SSL")) - group.add_argument("--no-ssl", action="store_true", help=_("Force the web server to disable SSL")) + group = self.parser.add_argument_group(_('Web Server Options')) + group.add_argument('-i', '--interface', metavar='<ip_address>', action='store', + help=_('IP address for web server to listen on')) + group.add_argument('-p', '--port', metavar='<port>', type=int, action='store', + help=_('Port for web server to listen on')) + group.add_argument('-b', '--base', metavar='<path>', action='store', + help=_('Set the base path that the ui is running on')) + group.add_argument('--ssl', action='store_true', help=_('Force the web server to use SSL')) + group.add_argument('--no-ssl', action='store_true', help=_('Force the web server to disable SSL')) self.parser.add_process_arg_group() @property @@ -53,7 +53,7 @@ class Web(UI): self.server.install_signal_handlers() self.server.start() except CannotListenError as ex: - log.error("%s \nCheck that deluge-web or webui plugin is not already running.", ex) + log.error('%s \nCheck that deluge-web or webui plugin is not already running.', ex) except Exception as ex: log.exception(ex) raise |