summaryrefslogtreecommitdiffstats
path: root/module/web
diff options
context:
space:
mode:
authorGravatar RaNaN <Mast3rRaNaN@hotmail.de> 2012-09-22 16:21:17 +0200
committerGravatar RaNaN <Mast3rRaNaN@hotmail.de> 2012-09-22 16:21:17 +0200
commit2bbdd6cf3a0ea429583a9e4b840e68c238e08a46 (patch)
tree3adf00866aa7fe5ac59bd5430754ad9dfcbc72b8 /module/web
parentadded websocket backend, removed thrift (diff)
downloadpyload-2bbdd6cf3a0ea429583a9e4b840e68c238e08a46.tar.xz
web socket api handler
Diffstat (limited to 'module/web')
-rw-r--r--module/web/api_app.py35
-rw-r--r--module/web/filters.py62
-rw-r--r--module/web/webinterface.py22
3 files changed, 23 insertions, 96 deletions
diff --git a/module/web/api_app.py b/module/web/api_app.py
index b2d7fa5b6..c3237c743 100644
--- a/module/web/api_app.py
+++ b/module/web/api_app.py
@@ -10,19 +10,8 @@ from bottle import route, request, response, HTTPError
from utils import set_session, get_user_api
from webinterface import PYLOAD
-from module.common.json_layer import json
-from module.utils import remove_chars, to_dict
-from module.lib.SafeEval import const_eval as literal_eval
-from module.Api import BaseObject
-
-# json encoder that accepts TBase objects
-class TBaseEncoder(json.JSONEncoder):
-
- def default(self, o):
- if isinstance(o, BaseObject):
- return to_dict(o)
- return json.JSONEncoder.default(self, o)
-
+from module.remote.json_converter import loads, dumps
+from module.utils import remove_chars
def add_header(r):
r.headers.replace("Content-type", "application/json")
@@ -43,10 +32,10 @@ def call_api(func, args=""):
api = get_user_api(s)
if not api:
- return HTTPError(403, json.dumps("Forbidden"))
+ return HTTPError(403, dumps("Forbidden"))
if not PYLOAD.isAuthorized(func, api.user):
- return HTTPError(401, json.dumps("Unauthorized"))
+ return HTTPError(401, dumps("Unauthorized"))
args = args.split("/")[1:]
kwargs = {}
@@ -59,23 +48,23 @@ def call_api(func, args=""):
return callApi(func, *args, **kwargs)
except Exception, e:
print_exc()
- return HTTPError(500, json.dumps({"error": e.message, "traceback": format_exc()}))
+ return HTTPError(500, dumps({"error": e.message, "traceback": format_exc()}))
# Better error codes on invalid input
def callApi(func, *args, **kwargs):
if not hasattr(PYLOAD.EXTERNAL, func) or func.startswith("_"):
print "Invalid API call", func
- return HTTPError(404, json.dumps("Not Found"))
+ return HTTPError(404, dumps("Not Found"))
# TODO: encoding
- result = getattr(PYLOAD, func)(*[literal_eval(x) for x in args],
- **dict([(x, literal_eval(y)) for x, y in kwargs.iteritems()]))
+ result = getattr(PYLOAD, func)(*[loads(x) for x in args],
+ **dict([(x, loads(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 dumps(result)
#post -> username, password
@@ -89,17 +78,17 @@ def login():
user = PYLOAD.checkAuth(username, password)
if not user:
- return json.dumps(False)
+ return dumps(False)
s = set_session(request, user)
# get the session id by dirty way, documentations seems wrong
try:
sid = s._headers["cookie_out"].split("=")[1].split(";")[0]
- return json.dumps(sid)
+ return dumps(sid)
except:
print "Could not get session"
- return json.dumps(True)
+ return dumps(True)
@route("/api/logout")
diff --git a/module/web/filters.py b/module/web/filters.py
deleted file mode 100644
index 13b8345fc..000000000
--- a/module/web/filters.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-import os
-from os.path import abspath, commonprefix, join
-
-quotechar = "::/"
-
-try:
- from os.path import relpath
-except:
- from posixpath import curdir, sep, pardir
- def relpath(path, start=curdir):
- """Return a relative version of a path"""
- if not path:
- raise ValueError("no path specified")
- start_list = abspath(start).split(sep)
- 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:]
- if not rel_list:
- return curdir
- return join(*rel_list)
-
-
-def quotepath(path):
- try:
- return path.replace("../", quotechar)
- except AttributeError:
- return path
- except:
- return ""
-
-def unquotepath(path):
- try:
- return path.replace(quotechar, "../")
- except AttributeError:
- return path
- except:
- return ""
-
-def path_make_absolute(path):
- p = os.path.abspath(path)
- if p[-1] == os.path.sep:
- return p
- else:
- return p + os.path.sep
-
-def path_make_relative(path):
- p = relpath(path)
- if p[-1] == os.path.sep:
- return p
- else:
- return p + os.path.sep
-
-def truncate(value, n):
- if (n - len(value)) < 3:
- return value[:n]+"..."
- return value
-
-def date(date, format):
- return date \ No newline at end of file
diff --git a/module/web/webinterface.py b/module/web/webinterface.py
index ae97406c7..196825bfb 100644
--- a/module/web/webinterface.py
+++ b/module/web/webinterface.py
@@ -30,7 +30,7 @@ PYLOAD_DIR = abspath(join(PROJECT_DIR, "..", ".."))
sys.path.append(PYLOAD_DIR)
from module import InitHomeDir
-from module.utils import decode, format_size
+from module.utils import format_size
import bottle
from bottle import run, app
@@ -64,7 +64,7 @@ PREFIX = config.get('webinterface', 'prefix')
if PREFIX:
PREFIX = PREFIX.rstrip("/")
- if not PREFIX.startswith("/"):
+ if PREFIX and not PREFIX.startswith("/"):
PREFIX = "/" + PREFIX
DEBUG = config.get("general", "debug_mode") or "-d" in sys.argv or "--debug" in sys.argv
@@ -84,28 +84,26 @@ loader = PrefixLoader({
env = Environment(loader=loader, extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape'], trim_blocks=True, auto_reload=False,
bytecode_cache=bcc)
-from filters import quotepath, path_make_relative, path_make_absolute, truncate, date
+# Filter
-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"] = format_size
env.filters["getitem"] = lambda x, y: x.__getitem__(y)
-if PREFIX:
+if not PREFIX:
env.filters["url"] = lambda x: x
else:
env.filters["url"] = lambda x: PREFIX + x if x.startswith("/") else x
+# Locale
+
gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
translation = gettext.translation("django", join(PYLOAD_DIR, "locale"),
languages=[config.get("general", "language"), "en"],fallback=True)
translation.install(True)
env.install_gettext_translations(translation)
+# Middlewares
+
from beaker.middleware import SessionMiddleware
session_opts = {
@@ -125,6 +123,9 @@ import pyload_app
import cnl_app
import api_app
+
+# Server Adapter
+
def run_simple(host="0.0.0.0", port="8000"):
run(app=web, host=host, port=port, quiet=True)
@@ -140,7 +141,6 @@ def run_threaded(host="0.0.0.0", port="8000", threads=6, cert="", key=""):
CherryPyWSGIServer.ssl_certificate = cert
CherryPyWSGIServer.ssl_private_key = key
-
# todo: threads configurable
from utils import CherryPyWSGI
CherryPyWSGI.numthreads = threads