From c52ee8392501ee916d85fd9da75aa08a8f014493 Mon Sep 17 00:00:00 2001 From: RaNaN Date: Tue, 12 Jul 2011 23:42:11 +0200 Subject: removed server_methods, please test everything entirely --- module/web/json_app.py | 114 ++++++++++++----------- module/web/media/default/js/funktions.js | 4 +- module/web/pyload_app.py | 119 ++++++++++++------------ module/web/templates/default/base.html | 4 +- module/web/templates/default/collector.html | 8 +- module/web/templates/default/home.html | 27 +++--- module/web/templates/default/info.html | 11 ++- module/web/templates/default/package_ui.js | 1 + module/web/templates/default/queue.html | 8 +- module/web/templates/default/settings.html | 10 +- module/web/templates/default/settings_item.html | 84 ++++++++--------- module/web/utils.py | 6 ++ module/web/webinterface.py | 5 +- 13 files changed, 204 insertions(+), 197 deletions(-) (limited to 'module/web') diff --git a/module/web/json_app.py b/module/web/json_app.py index d35ca1ad7..bc95b5ffd 100644 --- a/module/web/json_app.py +++ b/module/web/json_app.py @@ -1,22 +1,21 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -import base64 -from os.path import join, exists +import os +import os.path +from os.path import join from traceback import print_exc +import shutil from shutil import copyfileobj from bottle import route, request, HTTPError, validate from webinterface import PYLOAD -from utils import login_required, render_to_response +from utils import login_required, render_to_response, toDict -from module.utils import decode +from module.utils import decode, formatSize -import os -import shutil -import os.path def format_time(seconds): seconds = int(seconds) @@ -35,8 +34,8 @@ def get_sort_key(item): @login_required('see_downloads') def status(): try: - status = PYLOAD.status_server() - status['captcha'] = PYLOAD.is_captcha_waiting() + status = toDict(PYLOAD.statusServer()) + status['captcha'] = PYLOAD.isCaptchaWaiting() return status except: return HTTPError() @@ -47,17 +46,17 @@ def status(): @login_required('see_downloads') def links(): try: - links = PYLOAD.status_downloads() + links = [toDict(x) for x in PYLOAD.statusDownloads()] ids = [] for link in links: - ids.append(link['id']) + ids.append(link['fid']) if link['status'] == 12: - link['info'] = "%s @ %s kb/s" % (link['format_eta'], round(link['speed'], 2)) + link['info'] = "%s @ %s/s" % (link['format_eta'], formatSize(link['speed'])) elif link['status'] == 5: link['percent'] = 0 link['size'] = 0 - link['kbleft'] = 0 + link['bleft'] = 0 link['info'] = _("waiting %s") % link['format_wait'] else: link['info'] = "" @@ -65,14 +64,16 @@ def links(): data = {'links': links, 'ids': ids} return data except Exception, e: + print_exc() return HTTPError() @route("/json/queue") @login_required('see_downloads') def queue(): + print "/json/queue" try: - return PYLOAD.get_queue() + return PYLOAD.getQueue() except: return HTTPError() @@ -82,7 +83,7 @@ def queue(): @login_required('status') def pause(): try: - return PYLOAD.pause_server() + return PYLOAD.pauseServer() except: return HTTPError() @@ -92,7 +93,7 @@ def pause(): @login_required('status') def unpause(): try: - return PYLOAD.unpause_server() + return PYLOAD.unpauseServer() except: return HTTPError() @@ -102,7 +103,7 @@ def unpause(): @login_required('status') def cancel(): try: - return PYLOAD.stop_downloads() + return PYLOAD.stopDownloads() except: return HTTPError() @@ -110,8 +111,9 @@ def cancel(): @route("/json/packages") @login_required('see_downloads') def packages(): + print "/json/packages" try: - data = PYLOAD.get_queue() + data = PYLOAD.getQueue() for package in data: package['links'] = [] @@ -129,9 +131,10 @@ def packages(): @login_required('see_downloads') def package(id): try: - data = PYLOAD.get_package_data(id) + data = toDict(PYLOAD.getPackageData(id)) + data["links"] = [toDict(x) for x in data["links"]] - for pyfile in data["links"].itervalues(): + for pyfile in data["links"]: if pyfile["status"] == 0: pyfile["icon"] = "status_finished.png" elif pyfile["status"] in (2, 3): @@ -149,12 +152,13 @@ def package(id): else: pyfile["icon"] = "status_downloading.png" - tmp = data["links"].values() + tmp = data["links"] tmp.sort(key=get_sort_key) data["links"] = tmp return data except: + print_exc() return HTTPError() @@ -163,7 +167,7 @@ def package(id): def package_order(ids): try: pid, pos = ids.split("|") - PYLOAD.order_package(int(pid), int(pos)) + PYLOAD.orderPackage(int(pid), int(pos)) return {"response": "success"} except: return HTTPError() @@ -173,8 +177,9 @@ def package_order(ids): @validate(id=int) @login_required('see_downloads') def link(id): + print "/json/link/%d" % id try: - data = PYLOAD.get_file_info(id) + data = toDict(PYLOAD.getFileData(id)) return data except: return HTTPError() @@ -185,7 +190,7 @@ def link(id): @login_required('delete') def remove_link(id): try: - PYLOAD.del_links([id]) + PYLOAD.deleteFiles([id]) return {"response": "success"} except Exception, e: return HTTPError() @@ -196,7 +201,7 @@ def remove_link(id): @login_required('add') def restart_link(id): try: - PYLOAD.restart_file(id) + PYLOAD.restartFile(id) return {"response": "success"} except Exception: return HTTPError() @@ -207,7 +212,7 @@ def restart_link(id): @login_required('delete') def abort_link(id): try: - PYLOAD.stop_download("link", id) + PYLOAD.stopDownload("link", id) return {"response": "success"} except: return HTTPError() @@ -218,7 +223,7 @@ def abort_link(id): def link_order(ids): try: pid, pos = ids.split("|") - PYLOAD.order_file(int(pid), int(pos)) + PYLOAD.orderFile(int(pid), int(pos)) return {"response": "success"} except: return HTTPError() @@ -240,7 +245,7 @@ def add_package(): if not name or name == "New Package": name = f.name - fpath = join(PYLOAD.get_conf_val("general", "download_folder"), "tmp_" + f.filename) + fpath = join(PYLOAD.getConfigValue("general", "download_folder"), "tmp_" + f.filename) destination = open(fpath, 'wb') copyfileobj(f.file, destination) destination.close() @@ -253,11 +258,11 @@ def add_package(): links = map(lambda x: x.strip(), links) links = filter(lambda x: x != "", links) - pack = PYLOAD.add_package(name, links, queue) + pack = PYLOAD.addPackage(name, links, queue) if pw: pw = pw.decode("utf8", "ignore") data = {"password": pw} - PYLOAD.set_package_data(pack, data) + PYLOAD.setPackageData(pack, data) @route("/json/remove_package/:id") @@ -265,7 +270,7 @@ def add_package(): @login_required('delete') def remove_package(id): try: - PYLOAD.del_packages([id]) + PYLOAD.deletePackages([id]) return {"response": "success"} except Exception, e: return HTTPError() @@ -276,7 +281,7 @@ def remove_package(id): @login_required('add') def restart_package(id): try: - PYLOAD.restart_package(id) + PYLOAD.restartPackage(id) return {"response": "success"} except Exception: print_exc() @@ -288,7 +293,7 @@ def restart_package(id): @login_required('add') def move_package(dest, id): try: - PYLOAD.move_package(dest, id) + PYLOAD.movePackage(dest, id) return {"response": "success"} except: return HTTPError() @@ -304,7 +309,7 @@ def edit_package(): "priority": request.forms.get("pack_prio"), "password": request.forms.get("pack_pws").decode("utf8", "ignore")} - PYLOAD.set_package_data(id, data) + PYLOAD.setPackageData(id, data) return {"response": "success"} except: @@ -317,17 +322,16 @@ def edit_package(): def set_captcha(): if request.environ.get('REQUEST_METHOD', "GET") == "POST": try: - PYLOAD.set_captcha_result(request.forms["cap_id"], request.forms["cap_result"]) + PYLOAD.setCaptchaResult(request.forms["cap_id"], request.forms["cap_result"]) except: pass - id, binary, format, result_type = PYLOAD.get_captcha_task() + task = PYLOAD.getCaptchaTask() if id: - binary = base64.standard_b64encode(str(binary)) - src = "data:image/%s;base64,%s" % (format, binary) + src = "data:image/%s;base64,%s" % (task.type, task.data) - return {'captcha': True, 'id': id, 'src': src, 'result_type' : result_type} + return {'captcha': True, 'id': task.tid, 'src': src, 'result_type' : task.resultType} else: return {'captcha': False} @@ -335,13 +339,13 @@ def set_captcha(): @route("/json/delete_finished") @login_required('delete') def delete_finished(): - return {"del": PYLOAD.delete_finished()} + return {"del": PYLOAD.deleteFinished()} @route("/json/restart_failed") @login_required('delete') def restart_failed(): - restart = PYLOAD.restart_failed() + restart = PYLOAD.restartFailed() if restart: return restart return {"response": "success"} @@ -352,17 +356,15 @@ def restart_failed(): def load_config(category, section): conf = None if category == "general": - conf = PYLOAD.get_config() + conf = PYLOAD.getConfig() elif category == "plugin": - conf = PYLOAD.get_plugin_config() - - for key, option in conf[section].iteritems(): - if key == "desc": continue + conf = PYLOAD.getPluginConfig() - if ";" in option["type"]: - option["list"] = option["type"].split(";") + for option in conf[section].items: + if ";" in option.type: + option.type = 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]}) @@ -378,7 +380,7 @@ def save_config(category): if category == "general": category = "core" - PYLOAD.set_conf_val(section, option, decode(value), category) + PYLOAD.setConfigValue(section, option, decode(value), category) @route("/json/add_account", method="POST") @@ -388,7 +390,7 @@ def add_account(): password = request.POST["account_password"] type = request.POST["account_type"] - PYLOAD.update_account(type, login, password) + PYLOAD.updateAccount(type, login, password) @route("/json/update_accounts", method="POST") @@ -406,14 +408,14 @@ def update_accounts(): if (plugin, user) in deleted: continue if action == "password": - PYLOAD.update_account(plugin, user, value) + PYLOAD.updateAccount(plugin, user, value) elif action == "time" and "-" in value: - PYLOAD.update_account(plugin, user, options={"time": [value]}) + PYLOAD.updateAccount(plugin, user, options={"time": [value]}) elif action == "limitdl" and value.isdigit(): - PYLOAD.update_account(plugin, user, options={"limitDL": [value]}) + PYLOAD.updateAccount(plugin, user, options={"limitDL": [value]}) elif action == "delete": deleted.append((plugin,user)) - PYLOAD.remove_account(plugin, user) + PYLOAD.removeAccount(plugin, user) @route("/json/change_password", method="POST") def change_password(): @@ -422,7 +424,7 @@ def change_password(): oldpw = request.POST["login_current_password"] newpw = request.POST["login_new_password"] - if not PYLOAD.change_password(user, oldpw, newpw): + if not PYLOAD.changePassword(user, oldpw, newpw): print "Wrong password" return HTTPError() diff --git a/module/web/media/default/js/funktions.js b/module/web/media/default/js/funktions.js index 8d9d332b3..529b7056b 100644 --- a/module/web/media/default/js/funktions.js +++ b/module/web/media/default/js/funktions.js @@ -1,6 +1,6 @@ // JavaScript Document -function HumanFileSize(size) { - var filesizename = new Array("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"); +function humanFileSize(size) { + var filesizename = new Array("B", "KiB", "MiB", "GiB", "TiB", "PiB"); var loga = Math.log(size) / Math.log(1024); var i = Math.floor(loga); var a = Math.pow(1024, i); diff --git a/module/web/pyload_app.py b/module/web/pyload_app.py index 3bd314a40..0131e888f 100644 --- a/module/web/pyload_app.py +++ b/module/web/pyload_app.py @@ -16,9 +16,8 @@ @author: RaNaN """ -from copy import deepcopy from datetime import datetime -from operator import itemgetter +from operator import itemgetter, attrgetter import time import os @@ -26,14 +25,15 @@ import sys from os import listdir from os.path import isdir, isfile, join, abspath from sys import getfilesystemencoding -from hashlib import sha1 from urllib import unquote from bottle import route, static_file, request, response, redirect, HTTPError, error from webinterface import PYLOAD, PYLOAD_DIR, PROJECT_DIR, SETUP -from utils import render_to_response, parse_permissions, parse_userdata, login_required, get_permission, set_permission +from utils import render_to_response, parse_permissions, parse_userdata, \ + login_required, get_permission, set_permission, toDict + from filters import relpath, unquotepath from module.utils import formatSize, decode, fs_decode, freeSpace @@ -46,10 +46,10 @@ def pre_processor(): perms = parse_permissions(s) status = {} if user["is_authenticated"]: - status = PYLOAD.status_server() + status = PYLOAD.statusServer() captcha = False if user["is_authenticated"]: - captcha = PYLOAD.is_captcha_waiting() + captcha = PYLOAD.isCaptchaWaiting() return {"user": user, 'status': status, 'captcha': captcha, @@ -57,10 +57,6 @@ def pre_processor(): 'url': request.url} -def get_sort_key(item): - return item[1]["order"] - - def base(messages): return render_to_response('base.html', {'messages': messages}, [pre_processor]) @@ -79,7 +75,7 @@ def error500(error): @route('/media/:path#.+#') def server_static(path): response.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", - time.gmtime(time.time() + 60 * 60 * 24 * 7)) + time.gmtime(time.time() + 60 * 60 * 24 * 2)) response.headers['Cache-control'] = "public" return static_file(path, root=join(PROJECT_DIR, "media")) @@ -136,7 +132,7 @@ def logout(): @login_required("see_downloads") def home(): try: - res = PYLOAD.status_downloads() + res = [toDict(x) for x in PYLOAD.statusDownloads()] except: s = request.environ.get('beaker.session') s.delete() @@ -152,29 +148,27 @@ def home(): @route("/queue") @login_required("see_downloads") def queue(): - queue = PYLOAD.get_queue_info() + queue = PYLOAD.getQueue() - data = zip(queue.keys(), queue.values()) - data.sort(key=get_sort_key) + queue.sort(key=attrgetter("order")) - return render_to_response('queue.html', {'content': data}, [pre_processor]) + return render_to_response('queue.html', {'content': queue}, [pre_processor]) @route("/collector") @login_required('see_downloads') def collector(): - queue = PYLOAD.get_collector_info() + queue = PYLOAD.getCollector() - data = zip(queue.keys(), queue.values()) - data.sort(key=get_sort_key) + queue.sort(key=attrgetter("order")) - return render_to_response('collector.html', {'content': data}, [pre_processor]) + return render_to_response('collector.html', {'content': queue}, [pre_processor]) @route("/downloads") @login_required('download') def downloads(): - root = PYLOAD.get_conf_val("general", "download_folder") + root = PYLOAD.getConfigValue("general", "download_folder") if not isdir(root): return base([_('Download directory not found.')]) @@ -213,7 +207,7 @@ def get_download(path): path = unquote(path) #@TODO some files can not be downloaded - root = PYLOAD.get_conf_val("general", "download_folder") + root = PYLOAD.getConfigValue("general", "download_folder") path = path.replace("..", "") try: @@ -227,7 +221,7 @@ def get_download(path): #@route("/filemanager") #@login_required('filemanager') def filemanager(): - root = PYLOAD.get_conf_val("general", "download_folder") + root = PYLOAD.getConfigValue("general", "download_folder") if not isdir(root): return base([_('Download directory not found.')]) @@ -283,48 +277,49 @@ def folder(): @route("/settings") @login_required('settings') def config(): - conf = PYLOAD.get_config() - plugin = PYLOAD.get_plugin_config() + conf = PYLOAD.getConfig() + plugin = PYLOAD.getPluginConfig() conf_menu = [] plugin_menu = [] for entry in sorted(conf.keys()): - conf_menu.append((entry, conf[entry]["desc"])) + conf_menu.append((entry, conf[entry].description)) for entry in sorted(plugin.keys()): - plugin_menu.append((entry, plugin[entry]["desc"])) - - accs = deepcopy(PYLOAD.get_accounts(False, False)) - for accounts in accs.itervalues(): - for data in accounts: - if data["trafficleft"] == -1: - data["trafficleft"] = _("unlimited") - elif not data["trafficleft"]: - data["trafficleft"] = _("not available") - else: - data["trafficleft"] = formatSize(data["trafficleft"] * 1024) + plugin_menu.append((entry, plugin[entry].description)) - if data["validuntil"] == -1: - data["validuntil"] = _("unlimited") - elif not data["validuntil"]: - data["validuntil"] = _("not available") - else: - t = time.localtime(data["validuntil"]) - data["validuntil"] = time.strftime("%d.%m.%Y", t) + accs = PYLOAD.getAccounts(False) - if data["options"].has_key("time"): - try: - data["time"] = data["options"]["time"][0] - except: - data["time"] = "0:00-0:00" - if data["options"].has_key("limitDL"): - data["limitdl"] = data["options"]["limitDL"][0] - else: - data["limitdl"] = "0" + for data in accs: + if data.trafficleft == -1: + data.trafficleft = _("unlimited") + elif not data.trafficleft: + data.trafficleft = _("not available") + else: + data.trafficleft = formatSize(data.trafficleft * 1024) + + if data.validuntil == -1: + data.validuntil = _("unlimited") + elif not data.validuntil : + data.validuntil = _("not available") + else: + t = time.localtime(data.validuntil) + data.validuntil = time.strftime("%d.%m.%Y", t) + + if data.options.has_key("time"): + try: + data.options["time"] = data.options["time"][0] + except: + data.options["time"] = "0:00-0:00" + + if data.options.has_key("limitDL"): + data.options["limitdl"] = data.options["limitDL"][0] + else: + data.options["limitdl"] = "0" return render_to_response('settings.html', - {'conf': {'plugin': plugin_menu, 'general': conf_menu, 'accs': accs}}, + {'conf': {'plugin': plugin_menu, 'general': conf_menu, 'accs': accs}, 'types': PYLOAD.getAccountTypes()}, [pre_processor]) @@ -448,8 +443,8 @@ def logs(item=-1): reversed = s.get('reversed', False) warning = "" - conf = PYLOAD.get_config() - if not conf['log']['file_log']['value']: + conf = PYLOAD.getConfigValue("log","file_log") + if not conf: warning = "Warning: File log is disabled, see settings page." perpage_p = ((20, 20), (34, 34), (40, 40), (100, 100), (0, 'all')) @@ -476,7 +471,7 @@ def logs(item=-1): except: pass - log = PYLOAD.get_log() + log = PYLOAD.getLog() if not perpage: item = 0 @@ -527,7 +522,7 @@ def logs(item=-1): @route("/admin", method="POST") @login_required("is_admin") def admin(): - user = PYLOAD.get_user_data() + user = PYLOAD.getAllUserData() for data in user.itervalues(): data["perms"] = {} get_permission(data["perms"], data["permission"]) @@ -580,7 +575,7 @@ def admin(): user[name]["permission"] = set_permission(user[name]["perms"]) - PYLOAD.set_user_permission(name, user[name]["permission"], user[name]["role"]) + PYLOAD.setUserPermission(name, user[name]["permission"], user[name]["role"]) return render_to_response("admin.html", {"users": user}, [pre_processor]) @@ -595,7 +590,7 @@ def setup(): @route("/info") def info(): - conf = PYLOAD.get_config() + conf = PYLOAD.getConfigDict() if hasattr(os, "uname"): extra = os.uname() @@ -604,10 +599,10 @@ def info(): data = {"python": sys.version, "os": " ".join((os.name, sys.platform) + extra), - "version": PYLOAD.get_server_version(), + "version": PYLOAD.getServerVersion(), "folder": abspath(PYLOAD_DIR), "config": abspath(""), "download": abspath(conf["general"]["download_folder"]["value"]), - "freespace": formatSize(freeSpace(conf["general"]["download_folder"]["value"])), + "freespace": formatSize(PYLOAD.freeSpace()), "remote": conf["remote"]["port"]["value"], "webif": conf["webinterface"]["port"]["value"], "language": conf["general"]["language"]["value"]} diff --git a/module/web/templates/default/base.html b/module/web/templates/default/base.html index 6eb71f737..13538cf08 100644 --- a/module/web/templates/default/base.html +++ b/module/web/templates/default/base.html @@ -86,7 +86,7 @@ document.addEvent("domready", function(){ function LoadJsonToContent(data) { $("speed").set('text', Math.round(data.speed*100)/100); - $("aktiv").set('text', data.activ); + $("aktiv").set('text', data.active); $("aktiv_from").set('text', data.queue); $("aktiv_total").set('text', data.total); @@ -257,7 +257,7 @@ function AddBox(){
  • {{_("Download:")}} {% if status.download %}{{_("on")}}{% else %}{{_("off")}}{% endif %}
  • {{_("Reconnect:")}} {% if status.reconnect %}{{_("on")}}{% else %}{{_("off")}}{% endif %}
  • {{_("Speed:")}} {{ status.speed }} kb/s
  • -
  • {{_("Active:")}} {{ status.activ }} / {{ status.queue }} / {{ status.total }}
  • +
  • {{_("Active:")}} {{ status.active }} / {{ status.queue }} / {{ status.total }}
  • {{_("Reload page")}}
  • {% endif %} diff --git a/module/web/templates/default/collector.html b/module/web/templates/default/collector.html index 2683d8ee5..20221b899 100644 --- a/module/web/templates/default/collector.html +++ b/module/web/templates/default/collector.html @@ -24,9 +24,9 @@ document.addEvent("domready", function(){ {% block content %}