diff options
Diffstat (limited to 'module/remote')
-rw-r--r-- | module/remote/WebSocketBackend.py | 10 | ||||
-rw-r--r-- | module/remote/json_converter.py | 39 | ||||
-rw-r--r-- | module/remote/wsbackend/ApiHandler.py | 109 | ||||
-rw-r--r-- | module/remote/wsbackend/Dispatcher.py | 24 | ||||
-rw-r--r-- | module/remote/wsbackend/EventHandler.py | 41 | ||||
-rw-r--r-- | module/remote/wsbackend/Server.py | 2 |
6 files changed, 198 insertions, 27 deletions
diff --git a/module/remote/WebSocketBackend.py b/module/remote/WebSocketBackend.py index 7af927d8f..6e01dad87 100644 --- a/module/remote/WebSocketBackend.py +++ b/module/remote/WebSocketBackend.py @@ -21,7 +21,7 @@ import logging from module.remote.RemoteManager import BackendBase from mod_pywebsocket import util -def get_class_logger(o): +def get_class_logger(o=None): return logging.getLogger('log') # Monkey patch for our logger @@ -30,15 +30,17 @@ util.get_class_logger = get_class_logger class WebSocketBackend(BackendBase): def setup(self, host, port): - from wsbackend.Server import WebSocketServer, DefaultOptions - from wsbackend.Dispatcher import Dispatcher, ApiHandler + from wsbackend.Dispatcher import Dispatcher + from wsbackend.ApiHandler import ApiHandler + from wsbackend.EventHandler import EventHandler options = DefaultOptions() options.server_host = host options.port = port options.dispatcher = Dispatcher() - options.dispatcher.addHandler('/api', ApiHandler()) + options.dispatcher.addHandler('/api', ApiHandler(self.core.api)) + options.dispatcher.addHandler('/events', EventHandler(self.core.api)) self.server = WebSocketServer(options) diff --git a/module/remote/json_converter.py b/module/remote/json_converter.py new file mode 100644 index 000000000..57e85fd16 --- /dev/null +++ b/module/remote/json_converter.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from module.common.json_layer import json +from ttypes import BaseObject + +# json encoder that accepts TBase objects +class BaseEncoder(json.JSONEncoder): + + def default(self, o): + if isinstance(o, BaseObject): + ret = {"@class" : o.__class__.__name__} + for att in o.__slots__: + ret[att] = getattr(o, att) + return ret + + return json.JSONEncoder.default(self, o) + +class BaseDecoder(json.JSONDecoder): + + def __init__(self, *args, **kwargs): + json.JSONDecoder.__init__(self, *args, **kwargs) + self.object_hook = self.convertObject + + def convertObject(self, dct): + if '@class' in dct: + # TODO: convert + pass + + return dct + +def dumps(*args, **kwargs): + kwargs['cls'] = BaseEncoder + return json.dumps(*args, **kwargs) + + +def loads(*args, **kwargs): + kwargs['cls'] = BaseDecoder + return json.loads(*args, **kwargs)
\ No newline at end of file diff --git a/module/remote/wsbackend/ApiHandler.py b/module/remote/wsbackend/ApiHandler.py new file mode 100644 index 000000000..8f6bb3a0a --- /dev/null +++ b/module/remote/wsbackend/ApiHandler.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +############################################################################### +# Copyright(c) 2008-2012 pyLoad Team +# http://www.pyload.org +# +# This file is part of pyLoad. +# pyLoad is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# Subjected to the terms and conditions in LICENSE +# +# @author: RaNaN +############################################################################### + +from mod_pywebsocket.util import get_class_logger +from mod_pywebsocket.msgutil import receive_message, send_message +from module.remote.json_converter import loads, dumps + +class ApiHandler: + """Provides access to the API. + + Send your request as json encoded string in the following manner: + ["function", [*args]] or ["function", {**kwargs}] + + the result will be: + + [code, result] + + Don't forget to login first. + Non json request will be ignored. + """ + + def __init__(self, api): + self.log = get_class_logger() + self.api = api + + def do_extra_handshake(self, req): + self.log.debug("WS Connected: %s" % req) + + def transfer_data(self, req): + + while True: + try: + line = receive_message(req) + self.handle_message(line, req) + except TypeError, e: # connection closed + print e + return + + def passive_closing_handshake(self, req): + self.log.debug("WS Closed: %s" % req) + + def handle_message(self, msg, req): + try: + o = loads(msg) + except ValueError, e: #invalid json object + self.log.debug("Invalid Request: %s" % e) + return + + if type(o) != list and len(o) > 2: + self.log.debug("Invalid Api call: %s" % o) + return self.send_result(req, 500, "Invalid Api call") + if len(o) == 1: # arguments ommited + o.append([]) + + func, args = o + if type(args) == list: + kwargs = {} + else: + args, kwargs = [], args + + if func == 'login': + user = self.api.checkAuth(*args, **kwargs) + if user: + req.api = self.api.withUserContext(user.uid) + return self.send_result(req, 200, True) + + else: + return self.send_result(req, 403, "Forbidden") + + elif func == 'logout': + req.api = None + return self.send_result(req, 200, True) + + else: + if not req.api: + return self.send_result(req, 403, "Forbidden") + + if not self.api.isAuthorized(func, req.api.user): + return self.send_result(req, 401, "Unauthorized") + + try: + result = getattr(req.api, func)(*args, **kwargs) + except AttributeError: + return self.send_result(req, 404, "Not Found") + except Exception, e: + return self.send_result(req, 500, str(e)) + + if result is None: result = True + + return self.send_result(req, 200, result) + + + def send_result(self, req, code, result): + return send_message(req, dumps([code, result]))
\ No newline at end of file diff --git a/module/remote/wsbackend/Dispatcher.py b/module/remote/wsbackend/Dispatcher.py index eb1c9a291..44cc7555e 100644 --- a/module/remote/wsbackend/Dispatcher.py +++ b/module/remote/wsbackend/Dispatcher.py @@ -18,7 +18,6 @@ from mod_pywebsocket import util from mod_pywebsocket.dispatch import Dispatcher as BaseDispatcher -from mod_pywebsocket.msgutil import receive_message, send_message class Dispatcher(BaseDispatcher): @@ -29,25 +28,4 @@ class Dispatcher(BaseDispatcher): self._source_warnings = [] def addHandler(self, path, handler): - self._handler_suite_map[path] = handler - - - -class ApiHandler: - - def do_extra_handshake(self, req): - pass - - def transfer_data(self, req): - - while True: - try: - line = receive_message(req) - except TypeError: # connection closed - return - - print "Got", line - send_message(req, "You send: %s" % line) - - def passive_closing_handshake(self, req): - print "Closed", req
\ No newline at end of file + self._handler_suite_map[path] = handler
\ No newline at end of file diff --git a/module/remote/wsbackend/EventHandler.py b/module/remote/wsbackend/EventHandler.py new file mode 100644 index 000000000..deab25a6c --- /dev/null +++ b/module/remote/wsbackend/EventHandler.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +############################################################################### +# Copyright(c) 2008-2012 pyLoad Team +# http://www.pyload.org +# +# This file is part of pyLoad. +# pyLoad is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# Subjected to the terms and conditions in LICENSE +# +# @author: RaNaN +############################################################################### + +from mod_pywebsocket.msgutil import receive_message, send_message + +class EventHandler: + + def __init__(self, api): + self.api = api + + def do_extra_handshake(self, req): + pass + + def transfer_data(self, req): + + while True: + try: + line = receive_message(req) + except TypeError: # connection closed + return + + print "Got", line + send_message(req, "You send: %s" % line) + + def passive_closing_handshake(self, req): + print "Closed", req
\ No newline at end of file diff --git a/module/remote/wsbackend/Server.py b/module/remote/wsbackend/Server.py index 570753073..65f4fe5d5 100644 --- a/module/remote/wsbackend/Server.py +++ b/module/remote/wsbackend/Server.py @@ -32,6 +32,7 @@ # A copy of standalone.py with uneeded stuff removed # some logging methods removed +# Added api attribute to request import BaseHTTPServer import CGIHTTPServer @@ -129,6 +130,7 @@ class _StandaloneRequest(object): """ self._logger = logging.getLogger("log") + self.api = None self._request_handler = request_handler self.connection = _StandaloneConnection(request_handler) |