summaryrefslogtreecommitdiffstats
path: root/pyload/webui
diff options
context:
space:
mode:
authorGravatar ardi69 <armin@diedering.de> 2015-04-18 14:08:18 +0200
committerGravatar ardi69 <armin@diedering.de> 2015-04-18 14:08:18 +0200
commit6e8f84e1dc06cff6fa9387559992f555182c1774 (patch)
tree476600f9896fae029880e4049eb4c5e6021b202d /pyload/webui
parentfix: config cast (diff)
parentSpare code cosmetics (5) (diff)
downloadpyload-6e8f84e1dc06cff6fa9387559992f555182c1774.tar.xz
Merge pull request #3 from vuolter/0.4.10
merge vuolter HEAD
Diffstat (limited to 'pyload/webui')
-rw-r--r--pyload/webui/__init__.py23
-rw-r--r--pyload/webui/app/api.py14
-rw-r--r--pyload/webui/app/cnl.py4
-rw-r--r--pyload/webui/app/json.py72
-rw-r--r--pyload/webui/app/pyloadweb.py52
-rw-r--r--pyload/webui/app/utils.py20
-rw-r--r--pyload/webui/filters.py9
-rw-r--r--pyload/webui/middlewares.py20
-rw-r--r--pyload/webui/servers/lighttpd_default.conf2
9 files changed, 116 insertions, 100 deletions
diff --git a/pyload/webui/__init__.py b/pyload/webui/__init__.py
index d965db3a0..841e5abd9 100644
--- a/pyload/webui/__init__.py
+++ b/pyload/webui/__init__.py
@@ -65,19 +65,19 @@ env = Environment(loader=loader, extensions=['jinja2.ext.i18n', 'jinja2.ext.auto
from filters import quotepath, path_make_relative, path_make_absolute, truncate, date
-env.filters["quotepath"] = quotepath
-env.filters["truncate"] = truncate
-env.filters["date"] = date
-env.filters["path_make_relative"] = path_make_relative
-env.filters["path_make_absolute"] = path_make_absolute
-env.filters["decode"] = decode
-env.filters["type"] = lambda x: str(type(x))
-env.filters["formatsize"] = formatSize
-env.filters["getitem"] = lambda x, y: x.__getitem__(y)
+env.filters['quotepath'] = quotepath
+env.filters['truncate'] = truncate
+env.filters['date'] = date
+env.filters['path_make_relative'] = path_make_relative
+env.filters['path_make_absolute'] = path_make_absolute
+env.filters['decode'] = decode
+env.filters['type'] = lambda x: str(type(x))
+env.filters['formatsize'] = formatSize
+env.filters['getitem'] = lambda x, y: x.__getitem__(y)
if PREFIX:
- env.filters["url"] = lambda x: x
+ env.filters['url'] = lambda x: x
else:
- env.filters["url"] = lambda x: PREFIX + x if x.startswith("/") else x
+ env.filters['url'] = lambda x: PREFIX + x if x.startswith("/") else x
gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
translation = gettext.translation("django", join(PYLOAD_DIR, "locale"),
@@ -102,6 +102,7 @@ if PREFIX:
import pyload.webui.app
+
def run_simple(host="0.0.0.0", port="8000"):
run(app=web, host=host, port=port, quiet=True)
diff --git a/pyload/webui/app/api.py b/pyload/webui/app/api.py
index dd8521a07..0e36b7c1f 100644
--- a/pyload/webui/app/api.py
+++ b/pyload/webui/app/api.py
@@ -13,6 +13,8 @@ from pyload.utils import json
from SafeEval import const_eval as literal_eval
from pyload.api import BaseObject
+
+
# json encoder that accepts TBase objects
class TBaseEncoder(json.JSONEncoder):
@@ -23,7 +25,6 @@ class TBaseEncoder(json.JSONEncoder):
# accepting positional arguments, as well as kwargs via post and get
-
@route('/api/<func><args:re:[a-zA-Z0-9\-_/\"\'\[\]%{},]*>')
@route('/api/<func><args:re:[a-zA-Z0-9\-_/\"\'\[\]%{},]*>', method='POST')
def call_api(func, args=""):
@@ -37,14 +38,15 @@ def call_api(func, args=""):
if not s or not s.get("authenticated", False):
return HTTPError(403, json.dumps("Forbidden"))
- if not PYLOAD.isAuthorized(func, {"role": s["role"], "permission": s["perms"]}):
+ if not PYLOAD.isAuthorized(func, {"role": s['role'], "permission": s['perms']}):
return HTTPError(401, json.dumps("Unauthorized"))
args = args.split("/")[1:]
kwargs = {}
for x, y in chain(request.GET.iteritems(), request.POST.iteritems()):
- if x == "session": continue
+ if x == "session":
+ continue
kwargs[x] = unquote(y)
try:
@@ -63,9 +65,7 @@ def callApi(func, *args, **kwargs):
**dict((x, literal_eval(y)) for x, y in kwargs.iteritems()))
# null is invalid json response
- if result is None: result = True
-
- return json.dumps(result, cls=TBaseEncoder)
+ return json.dumps(result or True, cls=TBaseEncoder)
# post -> username, password
@@ -86,7 +86,7 @@ def login():
# get the session id by dirty way, documentations seems wrong
try:
- sid = s._headers["cookie_out"].split("=")[1].split(";")[0]
+ sid = s._headers['cookie_out'].split("=")[1].split(";")[0]
return json.dumps(sid)
except Exception:
return json.dumps(True)
diff --git a/pyload/webui/app/cnl.py b/pyload/webui/app/cnl.py
index 51767033f..73087ad2d 100644
--- a/pyload/webui/app/cnl.py
+++ b/pyload/webui/app/cnl.py
@@ -73,8 +73,8 @@ def addcrypted():
@local_check
def addcrypted2():
package = request.forms.get("source", None)
- crypted = request.forms["crypted"]
- jk = request.forms["jk"]
+ crypted = request.forms['crypted']
+ jk = request.forms['jk']
crypted = standard_b64decode(unquote(crypted.replace(" ", "+")))
if JS:
diff --git a/pyload/webui/app/json.py b/pyload/webui/app/json.py
index 700b310a0..12dce2484 100644
--- a/pyload/webui/app/json.py
+++ b/pyload/webui/app/json.py
@@ -22,7 +22,7 @@ def format_time(seconds):
def get_sort_key(item):
- return item["order"]
+ return item['order']
@route('/json/status')
@@ -87,29 +87,29 @@ def packages():
def package(id):
try:
data = toDict(PYLOAD.getPackageData(id))
- data["links"] = [toDict(x) for x in data["links"]]
-
- for pyfile in data["links"]:
- if pyfile["status"] == 0:
- pyfile["icon"] = "status_finished.png"
- elif pyfile["status"] in (2, 3):
- pyfile["icon"] = "status_queue.png"
- elif pyfile["status"] in (9, 1):
- pyfile["icon"] = "status_offline.png"
- elif pyfile["status"] == 5:
- pyfile["icon"] = "status_waiting.png"
- elif pyfile["status"] == 8:
- pyfile["icon"] = "status_failed.png"
- elif pyfile["status"] == 4:
- pyfile["icon"] = "arrow_right.png"
- elif pyfile["status"] in (11, 13):
- pyfile["icon"] = "status_proc.png"
+ data['links'] = [toDict(x) for x in data['links']]
+
+ for pyfile in data['links']:
+ if pyfile['status'] == 0:
+ pyfile['icon'] = "status_finished.png"
+ elif pyfile['status'] in (2, 3):
+ pyfile['icon'] = "status_queue.png"
+ elif pyfile['status'] in (9, 1):
+ pyfile['icon'] = "status_offline.png"
+ elif pyfile['status'] == 5:
+ pyfile['icon'] = "status_waiting.png"
+ elif pyfile['status'] == 8:
+ pyfile['icon'] = "status_failed.png"
+ elif pyfile['status'] == 4:
+ pyfile['icon'] = "arrow_right.png"
+ elif pyfile['status'] in (11, 13):
+ pyfile['icon'] = "status_proc.png"
else:
- pyfile["icon"] = "status_downloading.png"
+ pyfile['icon'] = "status_downloading.png"
- tmp = data["links"]
+ tmp = data['links']
tmp.sort(key=get_sort_key)
- data["links"] = tmp
+ data['links'] = tmp
return data
except Exception:
@@ -217,7 +217,7 @@ def edit_package():
def set_captcha():
if request.environ.get('REQUEST_METHOD', "GET") == "POST":
try:
- PYLOAD.setCaptchaResult(request.forms["cap_id"], request.forms["cap_result"])
+ PYLOAD.setCaptchaResult(request.forms['cap_id'], request.forms['cap_result'])
except Exception:
pass
@@ -241,12 +241,13 @@ def load_config(category, section):
conf = PYLOAD.getPluginConfigDict()
for key, option in conf[section].iteritems():
- if key in ("desc", "outline"): continue
+ if key in ("desc", "outline"):
+ continue
- if ";" in option["type"]:
- option["list"] = option["type"].split(";")
+ if ";" in option['type']:
+ option['list'] = option['type'].split(";")
- option["value"] = decode(option["value"])
+ option['value'] = decode(option['value'])
return render_to_response("settings_item.html", {"skey": section, "section": conf[section]})
@@ -268,9 +269,9 @@ def save_config(category):
@route('/json/add_account', method='POST')
@login_required("ACCOUNTS")
def add_account():
- login = request.POST["account_login"]
- password = request.POST["account_password"]
- type = request.POST["account_type"]
+ login = request.POST['account_login']
+ password = request.POST['account_password']
+ type = request.POST['account_type']
PYLOAD.updateAccount(type, login, password)
@@ -282,12 +283,14 @@ def update_accounts():
for name, value in request.POST.iteritems():
value = value.strip()
- if not value: continue
+ if not value:
+ continue
tmp, user = name.split(";")
plugin, action = tmp.split("|")
- if (plugin, user) in deleted: continue
+ if (plugin, user) in deleted:
+ continue
if action == "password":
PYLOAD.updateAccount(plugin, user, value)
@@ -299,12 +302,13 @@ def update_accounts():
deleted.append((plugin,user))
PYLOAD.removeAccount(plugin, user)
+
@route('/json/change_password', method='POST')
def change_password():
- user = request.POST["user_login"]
- oldpw = request.POST["login_current_password"]
- newpw = request.POST["login_new_password"]
+ user = request.POST['user_login']
+ oldpw = request.POST['login_current_password']
+ newpw = request.POST['login_new_password']
if not PYLOAD.changePassword(user, oldpw, newpw):
print "Wrong password"
diff --git a/pyload/webui/app/pyloadweb.py b/pyload/webui/app/pyloadweb.py
index cc2185fd4..1604bd576 100644
--- a/pyload/webui/app/pyloadweb.py
+++ b/pyload/webui/app/pyloadweb.py
@@ -34,16 +34,16 @@ def pre_processor():
captcha = False
update = False
plugins = False
- if user["is_authenticated"]:
+ if user['is_authenticated']:
status = PYLOAD.statusServer()
info = PYLOAD.getInfoByPlugin("UpdateManager")
captcha = PYLOAD.isCaptchaWaiting()
# check if update check is available
if info:
- if info["pyload"] == "True":
- update = info["version"]
- if info["plugins"] == "True":
+ if info['pyload'] == "True":
+ update = info['version']
+ if info['plugins'] == "True":
plugins = True
return {"user": user,
@@ -165,8 +165,8 @@ def home():
return redirect("/login")
for link in res:
- if link["status"] == 12:
- link["information"] = "%s kB @ %s kB/s" % (link["size"] - link["bleft"], link["speed"])
+ if link['status'] == 12:
+ link['information'] = "%s kB @ %s kB/s" % (link['size'] - link['bleft'], link['speed'])
return render_to_response("home.html", {"res": res}, [pre_processor])
@@ -282,14 +282,14 @@ def config():
data.validuntil = time.strftime("%d.%m.%Y - %H:%M:%S", t)
try:
- data.options["time"] = data.options["time"][0]
+ data.options['time'] = data.options['time'][0]
except Exception:
- data.options["time"] = "0:00-0:00"
+ data.options['time'] = "0:00-0:00"
if "limitDL" in data.options:
- data.options["limitdl"] = data.options["limitDL"][0]
+ data.options['limitdl'] = data.options['limitDL'][0]
else:
- data.options["limitdl"] = "0"
+ data.options['limitdl'] = "0"
return render_to_response('settings.html',
{'conf': {'plugin': plugin_menu, 'general': conf_menu, 'accs': accs}, 'types': PYLOAD.getAccountTypes()},
@@ -482,30 +482,30 @@ def admin():
perms = permlist()
for data in user.itervalues():
- data["perms"] = {}
- get_permission(data["perms"], data["permission"])
- data["perms"]["admin"] = True if data["role"] is 0 else False
+ data['perms'] = {}
+ get_permission(data['perms'], data['permission'])
+ data['perms']['admin'] = True if data['role'] is 0 else False
s = request.environ.get('beaker.session')
if request.environ.get('REQUEST_METHOD', "GET") == "POST":
for name in user:
if request.POST.get("%s|admin" % name, False):
- user[name]["role"] = 0
- user[name]["perms"]["admin"] = True
- elif name != s["name"]:
- user[name]["role"] = 1
- user[name]["perms"]["admin"] = False
+ user[name]['role'] = 0
+ user[name]['perms']['admin'] = True
+ elif name != s['name']:
+ user[name]['role'] = 1
+ user[name]['perms']['admin'] = False
# set all perms to false
for perm in perms:
- user[name]["perms"][perm] = False
+ user[name]['perms'][perm] = False
for perm in request.POST.getall("%s|perms" % name):
- user[name]["perms"][perm] = True
+ user[name]['perms'][perm] = True
- user[name]["permission"] = set_permission(user[name]["perms"])
+ user[name]['permission'] = set_permission(user[name]['perms'])
- PYLOAD.setUserPermission(name, user[name]["permission"], user[name]["role"])
+ PYLOAD.setUserPermission(name, user[name]['permission'], user[name]['role'])
return render_to_response("admin.html", {"users": user, "permlist": perms}, [pre_processor])
@@ -528,10 +528,10 @@ def info():
"os" : " ".join((os.name, sys.platform) + extra),
"version" : PYLOAD.getServerVersion(),
"folder" : abspath(PYLOAD_DIR), "config": abspath(""),
- "download" : abspath(conf["general"]["download_folder"]["value"]),
+ "download" : abspath(conf['general']['download_folder']['value']),
"freespace": formatSize(PYLOAD.freeSpace()),
- "remote" : conf["remote"]["port"]["value"],
- "webif" : conf["webui"]["port"]["value"],
- "language" : conf["general"]["language"]["value"]}
+ "remote" : conf['remote']['port']['value'],
+ "webif" : conf['webui']['port']['value'],
+ "language" : conf['general']['language']['value']}
return render_to_response("info.html", data, [pre_processor])
diff --git a/pyload/webui/app/utils.py b/pyload/webui/app/utils.py
index ac7fa84fb..69067d8fe 100644
--- a/pyload/webui/app/utils.py
+++ b/pyload/webui/app/utils.py
@@ -9,6 +9,7 @@ from pyload.webui import env, THEME
from pyload.api import has_permission, PERMS, ROLE
+
def render_to_response(file, args={}, proc=[]):
for p in proc:
args.update(p())
@@ -18,8 +19,8 @@ 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["ADMIN"] = False
- perms["is_admin"] = False
+ perms['ADMIN'] = False
+ perms['is_admin'] = False
if not session.get("authenticated", False):
return perms
@@ -56,7 +57,8 @@ def set_permission(perms):
"""
permission = 0
for name in dir(PERMS):
- if name.startswith("_"): continue
+ if name.startswith("_"):
+ continue
if name in perms and perms[name]:
permission |= getattr(PERMS, name)
@@ -66,12 +68,12 @@ def set_permission(perms):
def set_session(request, info):
s = request.environ.get('beaker.session')
- s["authenticated"] = True
- s["user_id"] = info["id"]
- s["name"] = info["name"]
- s["role"] = info["role"]
- s["perms"] = info["permission"]
- s["template"] = info["template"]
+ s['authenticated'] = True
+ s['user_id'] = info['id']
+ s['name'] = info['name']
+ s['role'] = info['role']
+ s['perms'] = info['permission']
+ s['template'] = info['template']
s.save()
return s
diff --git a/pyload/webui/filters.py b/pyload/webui/filters.py
index c784b248d..ea4b159fa 100644
--- a/pyload/webui/filters.py
+++ b/pyload/webui/filters.py
@@ -18,7 +18,7 @@ except Exception:
path_list = abspath(path).split(sep)
# Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list]))
- rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
+ rel_list = [pardir] * (len(start_list) - i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
@@ -32,6 +32,7 @@ def quotepath(path):
except Exception:
return ""
+
def unquotepath(path):
try:
return path.replace(quotechar, "../")
@@ -40,6 +41,7 @@ def unquotepath(path):
except Exception:
return ""
+
def path_make_absolute(path):
p = os.path.abspath(path)
if p[-1] == os.path.sep:
@@ -47,6 +49,7 @@ def path_make_absolute(path):
else:
return p + os.path.sep
+
def path_make_relative(path):
p = relpath(path)
if p[-1] == os.path.sep:
@@ -54,10 +57,12 @@ def path_make_relative(path):
else:
return p + os.path.sep
+
def truncate(value, n):
if (n - len(value)) < 3:
- return value[:n]+"..."
+ return value[:n] + "..."
return value
+
def date(date, format):
return date
diff --git a/pyload/webui/middlewares.py b/pyload/webui/middlewares.py
index 26537f900..c3f4952db 100644
--- a/pyload/webui/middlewares.py
+++ b/pyload/webui/middlewares.py
@@ -7,6 +7,7 @@ try:
except ImportError:
from StringIO import StringIO
+
class StripPathMiddleware(object):
def __init__(self, app):
@@ -26,7 +27,7 @@ class PrefixMiddleware(object):
def __call__(self, e, h):
- path = e["PATH_INFO"]
+ path = e['PATH_INFO']
if path.startswith(self.prefix):
e['PATH_INFO'] = path.replace(self.prefix, "", 1)
return self.app(e, h)
@@ -40,6 +41,7 @@ class PrefixMiddleware(object):
# WSGI middleware
# Gzip-encodes the response.
+
class GZipMiddleWare(object):
def __init__(self, application, compress_level=6):
@@ -60,21 +62,25 @@ class GZipMiddleWare(object):
return response.write()
+
def header_value(headers, key):
for header, value in headers:
if key.lower() == header.lower():
return value
+
def update_header(headers, key, value):
remove_header(headers, key)
headers.append((key, value))
+
def remove_header(headers, key):
for header, value in headers:
if key.lower() == header.lower():
headers.remove((header, value))
break
+
class GzipResponse(object):
def __init__(self, start_response, compress_level):
@@ -88,16 +94,15 @@ class GzipResponse(object):
def gzip_start_response(self, status, headers, exc_info=None):
self.headers = headers
- ct = header_value(headers,'content-type')
- ce = header_value(headers,'content-encoding')
+ ct = header_value(headers, 'content-type')
+ ce = header_value(headers, 'content-encoding')
cl = header_value(headers, 'content-length')
if cl:
cl = int(cl)
else:
cl = 201
self.compressible = False
- if ct and (ct.startswith('text/') or ct.startswith('application/')) \
- and 'zip' not in ct and cl > 200:
+ if ct and (ct.startswith('text/') or ct.startswith('application/')) and 'zip' not in ct and cl > 200:
self.compressible = True
if ce:
self.compressible = False
@@ -119,8 +124,7 @@ class GzipResponse(object):
def finish_response(self, app_iter):
if self.compressible:
- output = gzip.GzipFile(mode='wb', compresslevel=self.compress_level,
- fileobj=self.buffer)
+ output = gzip.GzipFile(mode='wb', compresslevel=self.compress_level, fileobj=self.buffer)
else:
output = self.buffer
try:
@@ -136,5 +140,5 @@ class GzipResponse(object):
pass
content_length = self.buffer.tell()
- update_header(self.headers, "Content-Length" , str(content_length))
+ update_header(self.headers, "Content-Length", str(content_length))
self.start_response(self.status, self.headers)
diff --git a/pyload/webui/servers/lighttpd_default.conf b/pyload/webui/servers/lighttpd_default.conf
index a821096c6..444ef39c5 100644
--- a/pyload/webui/servers/lighttpd_default.conf
+++ b/pyload/webui/servers/lighttpd_default.conf
@@ -115,7 +115,7 @@ accesslog.filename = "%(path)/access.log"
url.access-deny = ( "~", ".inc" )
-$HTTP["url"] =~ "\.pdf$" {
+$HTTP['url'] =~ "\.pdf$" {
server.range-requests = "disable"
}