From 712743a0136ae9718a6b5ca3f5855b4f3b4f9d61 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Thu, 8 Nov 2012 21:39:48 +0100 Subject: [PATCH 01/47] Working PoC of a CherryPy HTTP frontend --- mopidy/frontends/cherrypyhttp.py | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 mopidy/frontends/cherrypyhttp.py diff --git a/mopidy/frontends/cherrypyhttp.py b/mopidy/frontends/cherrypyhttp.py new file mode 100644 index 00000000..453731fd --- /dev/null +++ b/mopidy/frontends/cherrypyhttp.py @@ -0,0 +1,43 @@ +from __future__ import absolute_import + +import logging + +import cherrypy +import pykka + + +logger = logging.getLogger('mopidy.frontends.cherrypyhttp') + + +class CherryPyHttpFrontend(pykka.ThreadingActor): + def __init__(self, core): + super(CherryPyHttpFrontend, self).__init__() + self.core = core + + def on_start(self): + logger.debug(u'Starting CherryPy HTTP server') + cherrypy.tree.mount(Root(self.core), '/', {}) + cherrypy.server.socket_port = 6680 + cherrypy.server.start() + logger.info(u'CherryPy HTTP server running at %s', + cherrypy.server.base()) + + def on_stop(self): + cherrypy.server.stop() + + +class Root(object): + def __init__(self, core): + self.core = core + + @cherrypy.expose + @cherrypy.tools.json_out() + def index(self): + playback_state = self.core.playback.state.get() + track = self.core.playback.current_track.get() + if track: + track = track.serialize() + return { + 'playback_state': playback_state, + 'current_track': track, + } From 06818b284d566aecb16b635b781f2e8b522392bb Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Thu, 8 Nov 2012 22:50:35 +0100 Subject: [PATCH 02/47] http: Don't crash if cherrypy is missing --- mopidy/frontends/cherrypyhttp.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/mopidy/frontends/cherrypyhttp.py b/mopidy/frontends/cherrypyhttp.py index 453731fd..1eaf4b90 100644 --- a/mopidy/frontends/cherrypyhttp.py +++ b/mopidy/frontends/cherrypyhttp.py @@ -2,9 +2,15 @@ from __future__ import absolute_import import logging -import cherrypy import pykka +from mopidy import exceptions + +try: + import cherrypy +except ImportError as import_error: + raise exceptions.OptionalDependencyError(import_error) + logger = logging.getLogger('mopidy.frontends.cherrypyhttp') From 93f6378cf52713ca738d0bf26e9b3b6c2201bcd8 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Thu, 8 Nov 2012 22:57:22 +0100 Subject: [PATCH 03/47] http: Rename frontend to simply 'HttpFrontend' --- mopidy/frontends/{cherrypyhttp.py => http/__init__.py} | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) rename mopidy/frontends/{cherrypyhttp.py => http/__init__.py} (77%) diff --git a/mopidy/frontends/cherrypyhttp.py b/mopidy/frontends/http/__init__.py similarity index 77% rename from mopidy/frontends/cherrypyhttp.py rename to mopidy/frontends/http/__init__.py index 1eaf4b90..9808a12d 100644 --- a/mopidy/frontends/cherrypyhttp.py +++ b/mopidy/frontends/http/__init__.py @@ -12,20 +12,20 @@ except ImportError as import_error: raise exceptions.OptionalDependencyError(import_error) -logger = logging.getLogger('mopidy.frontends.cherrypyhttp') +logger = logging.getLogger('mopidy.frontends.http') -class CherryPyHttpFrontend(pykka.ThreadingActor): +class HttpFrontend(pykka.ThreadingActor): def __init__(self, core): - super(CherryPyHttpFrontend, self).__init__() + super(HttpFrontend, self).__init__() self.core = core def on_start(self): - logger.debug(u'Starting CherryPy HTTP server') + logger.debug(u'Starting HTTP server') cherrypy.tree.mount(Root(self.core), '/', {}) cherrypy.server.socket_port = 6680 cherrypy.server.start() - logger.info(u'CherryPy HTTP server running at %s', + logger.info(u'HTTP server running at %s', cherrypy.server.base()) def on_stop(self): From e5053c929a32493dd43958fd8acb66e40eef0e34 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Thu, 8 Nov 2012 23:07:42 +0100 Subject: [PATCH 04/47] http: Add HTTP_SERVER_{HOSTNAME,PORT} settings --- mopidy/frontends/http/__init__.py | 9 ++++++--- mopidy/settings.py | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 9808a12d..28cd92ea 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -4,7 +4,7 @@ import logging import pykka -from mopidy import exceptions +from mopidy import exceptions, settings try: import cherrypy @@ -19,11 +19,14 @@ class HttpFrontend(pykka.ThreadingActor): def __init__(self, core): super(HttpFrontend, self).__init__() self.core = core + cherrypy.config.update({ + 'server.socket_host': settings.HTTP_SERVER_HOSTNAME, + 'server.socket_port': settings.HTTP_SERVER_PORT, + }) + cherrypy.tree.mount(Root(self.core), '/') def on_start(self): logger.debug(u'Starting HTTP server') - cherrypy.tree.mount(Root(self.core), '/', {}) - cherrypy.server.socket_port = 6680 cherrypy.server.start() logger.info(u'HTTP server running at %s', cherrypy.server.base()) diff --git a/mopidy/settings.py b/mopidy/settings.py index 12acd281..36057869 100644 --- a/mopidy/settings.py +++ b/mopidy/settings.py @@ -78,6 +78,29 @@ FRONTENDS = ( u'mopidy.frontends.mpris.MprisFrontend', ) +#: Which address Mopidy's HTTP server should bind to. +#: +#: Used by :mod:`mopidy.frontends.http`. +#: +#: Examples: +#: +#: ``127.0.0.1`` +#: Listens only on the IPv4 loopback interface. Default. +#: ``::1`` +#: Listens only on the IPv6 loopback interface. +#: ``0.0.0.0`` +#: Listens on all IPv4 interfaces. +#: ``::`` +#: Listens on all interfaces, both IPv4 and IPv6. +HTTP_SERVER_HOSTNAME = u'127.0.0.1' + +#: Which TCP port Mopidy's HTTP server should listen to. +#: +#: Used by :mod:`mopidy.frontends.http`. +#: +#: Default: 6680 +HTTP_SERVER_PORT = 6680 + #: Your `Last.fm `_ username. #: #: Used by :mod:`mopidy.frontends.lastfm`. From 509c7c82ea77955bbc01940370d15eaee7bdefb8 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 00:32:13 +0100 Subject: [PATCH 05/47] http: Only include cherrypy in debug log --- mopidy/frontends/http/__init__.py | 11 ++++++++++- mopidy/utils/log.py | 3 +++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 28cd92ea..4305ef6b 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -23,7 +23,16 @@ class HttpFrontend(pykka.ThreadingActor): 'server.socket_host': settings.HTTP_SERVER_HOSTNAME, 'server.socket_port': settings.HTTP_SERVER_PORT, }) - cherrypy.tree.mount(Root(self.core), '/') + app = cherrypy.tree.mount(Root(self.core), '/') + self._setup_logging(app) + + def _setup_logging(self, app): + cherrypy.log.access_log.setLevel(logging.NOTSET) + cherrypy.log.error_log.setLevel(logging.NOTSET) + cherrypy.log.screen = False + + app.log.access_log.setLevel(logging.NOTSET) + app.log.error_log.setLevel(logging.NOTSET) def on_start(self): logger.debug(u'Starting HTTP server') diff --git a/mopidy/utils/log.py b/mopidy/utils/log.py index bb966a1d..6bb29f8a 100644 --- a/mopidy/utils/log.py +++ b/mopidy/utils/log.py @@ -44,6 +44,9 @@ def setup_console_logging(verbosity_level): if verbosity_level < 3: logging.getLogger('pykka').setLevel(logging.INFO) + if verbosity_level < 2: + logging.getLogger('cherrypy').setLevel(logging.WARNING) + def setup_debug_logging_to_file(): formatter = logging.Formatter(settings.DEBUG_LOG_FORMAT) From 5d8929986d278d97e33d425ae10bee0d29631886 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 10:06:15 +0100 Subject: [PATCH 06/47] http: Encode the hostname to a str --- mopidy/frontends/http/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 4305ef6b..555758a8 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -20,7 +20,8 @@ class HttpFrontend(pykka.ThreadingActor): super(HttpFrontend, self).__init__() self.core = core cherrypy.config.update({ - 'server.socket_host': settings.HTTP_SERVER_HOSTNAME, + 'server.socket_host': + settings.HTTP_SERVER_HOSTNAME.encode('utf-8'), 'server.socket_port': settings.HTTP_SERVER_PORT, }) app = cherrypy.tree.mount(Root(self.core), '/') From 4d5122094f65b5ccc6a11c0c36669c79d8fde525 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 10:07:38 +0100 Subject: [PATCH 07/47] http: Start the CherryPy bus, and not just the server --- mopidy/frontends/http/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 555758a8..f46ba1e2 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -37,12 +37,12 @@ class HttpFrontend(pykka.ThreadingActor): def on_start(self): logger.debug(u'Starting HTTP server') - cherrypy.server.start() + cherrypy.engine.start() logger.info(u'HTTP server running at %s', cherrypy.server.base()) def on_stop(self): - cherrypy.server.stop() + cherrypy.engine.stop() class Root(object): From dda5ee42f068699017feebb1548929e43c7dea11 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 10:46:46 +0100 Subject: [PATCH 08/47] http: Turn off autoreloading --- mopidy/frontends/http/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index f46ba1e2..5e722b22 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -20,6 +20,7 @@ class HttpFrontend(pykka.ThreadingActor): super(HttpFrontend, self).__init__() self.core = core cherrypy.config.update({ + 'engine.autoreload_on': False, 'server.socket_host': settings.HTTP_SERVER_HOSTNAME.encode('utf-8'), 'server.socket_port': settings.HTTP_SERVER_PORT, From e41f9e3871a38e330dec03bf02d0a3c1749c67bf Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 10:47:17 +0100 Subject: [PATCH 09/47] http: Working WebSockets which emits playback state changes --- mopidy/frontends/http/__init__.py | 59 ++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 5e722b22..488db370 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -5,9 +5,13 @@ import logging import pykka from mopidy import exceptions, settings +from mopidy.core import CoreListener try: import cherrypy + from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool + from ws4py.websocket import WebSocket + from ws4py.messaging import TextMessage except ImportError as import_error: raise exceptions.OptionalDependencyError(import_error) @@ -15,18 +19,34 @@ except ImportError as import_error: logger = logging.getLogger('mopidy.frontends.http') -class HttpFrontend(pykka.ThreadingActor): +class HttpFrontend(pykka.ThreadingActor, CoreListener): def __init__(self, core): super(HttpFrontend, self).__init__() self.core = core + self._setup_server() + self._setup_websocket_plugin() + app = self._create_app() + self._setup_logging(app) + + def _setup_server(self): cherrypy.config.update({ 'engine.autoreload_on': False, 'server.socket_host': settings.HTTP_SERVER_HOSTNAME.encode('utf-8'), 'server.socket_port': settings.HTTP_SERVER_PORT, }) - app = cherrypy.tree.mount(Root(self.core), '/') - self._setup_logging(app) + + def _setup_websocket_plugin(self): + WebSocketPlugin(cherrypy.engine).subscribe() + cherrypy.tools.websocket = WebSocketTool() + + def _create_app(self): + return cherrypy.tree.mount(Root(self.core), '/', { + '/ws': { + 'tools.websocket.on': True, + 'tools.websocket.handler_cls': EventWebSocketHandler, + }, + }) def _setup_logging(self, app): cherrypy.log.access_log.setLevel(logging.NOTSET) @@ -39,11 +59,36 @@ class HttpFrontend(pykka.ThreadingActor): def on_start(self): logger.debug(u'Starting HTTP server') cherrypy.engine.start() - logger.info(u'HTTP server running at %s', - cherrypy.server.base()) + logger.info(u'HTTP server running at %s', cherrypy.server.base()) def on_stop(self): + logger.debug(u'Stopping HTTP server') cherrypy.engine.stop() + logger.info(u'Stopped HTTP server') + + def playback_state_changed(self, old_state, new_state): + cherrypy.engine.publish('websocket-broadcast', + TextMessage('playback_state_changed: %s -> %s' % ( + old_state, new_state))) + + +class EventWebSocketHandler(WebSocket): + def opened(self): + remote = cherrypy.request.remote + logger.debug(u'New WebSocket connection from %s:%d', + remote.ip, remote.port) + + def closed(self, code, reason=None): + remote = cherrypy.request.remote + logger.debug(u'Closed WebSocket connection from %s:%d ' + 'with code %s and reason %r', + remote.ip, remote.port, code, reason) + + def received_message(self, message): + remote = cherrypy.request.remote + logger.debug(u'Received WebSocket message from %s:%d: %s', + remote.ip, remote.port, message) + # This is where we would handle incoming messages from the clients class Root(object): @@ -61,3 +106,7 @@ class Root(object): 'playback_state': playback_state, 'current_track': track, } + + @cherrypy.expose + def ws(self): + logger.debug(u'WebSocket handler created') From 5b8f391bc77130620187ae582f435ec63f94e878 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 10:51:53 +0100 Subject: [PATCH 10/47] http: Exit CherryPy engine properly --- mopidy/frontends/http/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 488db370..7294b40d 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -63,7 +63,7 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): def on_stop(self): logger.debug(u'Stopping HTTP server') - cherrypy.engine.stop() + cherrypy.engine.exit() logger.info(u'Stopped HTTP server') def playback_state_changed(self, old_state, new_state): From 37ab7c766d22f7b3f4f2d5e91566ac39106aa8e6 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 10:58:48 +0100 Subject: [PATCH 11/47] http: Move web socket code to new module --- mopidy/frontends/http/__init__.py | 32 +++++--------------------- mopidy/frontends/http/ws.py | 37 +++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 26 deletions(-) create mode 100644 mopidy/frontends/http/ws.py diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 7294b40d..61aa5625 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -10,11 +10,12 @@ from mopidy.core import CoreListener try: import cherrypy from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool - from ws4py.websocket import WebSocket from ws4py.messaging import TextMessage except ImportError as import_error: raise exceptions.OptionalDependencyError(import_error) +from . import ws + logger = logging.getLogger('mopidy.frontends.http') @@ -41,10 +42,12 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): cherrypy.tools.websocket = WebSocketTool() def _create_app(self): - return cherrypy.tree.mount(Root(self.core), '/', { + root = Root(self.core) + root.ws = ws.WebSocketResource() + return cherrypy.tree.mount(root, '/', { '/ws': { 'tools.websocket.on': True, - 'tools.websocket.handler_cls': EventWebSocketHandler, + 'tools.websocket.handler_cls': ws.WebSocketHandler, }, }) @@ -72,25 +75,6 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): old_state, new_state))) -class EventWebSocketHandler(WebSocket): - def opened(self): - remote = cherrypy.request.remote - logger.debug(u'New WebSocket connection from %s:%d', - remote.ip, remote.port) - - def closed(self, code, reason=None): - remote = cherrypy.request.remote - logger.debug(u'Closed WebSocket connection from %s:%d ' - 'with code %s and reason %r', - remote.ip, remote.port, code, reason) - - def received_message(self, message): - remote = cherrypy.request.remote - logger.debug(u'Received WebSocket message from %s:%d: %s', - remote.ip, remote.port, message) - # This is where we would handle incoming messages from the clients - - class Root(object): def __init__(self, core): self.core = core @@ -106,7 +90,3 @@ class Root(object): 'playback_state': playback_state, 'current_track': track, } - - @cherrypy.expose - def ws(self): - logger.debug(u'WebSocket handler created') diff --git a/mopidy/frontends/http/ws.py b/mopidy/frontends/http/ws.py new file mode 100644 index 00000000..53ad651d --- /dev/null +++ b/mopidy/frontends/http/ws.py @@ -0,0 +1,37 @@ +import logging + +from mopidy import exceptions + +try: + import cherrypy + from ws4py.websocket import WebSocket +except ImportError as import_error: + raise exceptions.OptionalDependencyError(import_error) + + +logger = logging.getLogger('mopidy.frontends.http') + + +class WebSocketResource(object): + @cherrypy.expose + def index(self): + logger.debug(u'WebSocket handler created') + + +class WebSocketHandler(WebSocket): + def opened(self): + remote = cherrypy.request.remote + logger.debug(u'New WebSocket connection from %s:%d', + remote.ip, remote.port) + + def closed(self, code, reason=None): + remote = cherrypy.request.remote + logger.debug(u'Closed WebSocket connection from %s:%d ' + 'with code %s and reason %r', + remote.ip, remote.port, code, reason) + + def received_message(self, message): + remote = cherrypy.request.remote + logger.debug(u'Received WebSocket message from %s:%d: %s', + remote.ip, remote.port, message) + # This is where we would handle incoming messages from the clients From 92dc9740289da52ad786c7ab91d68ae657384ac2 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 11:06:51 +0100 Subject: [PATCH 12/47] http: Move web service code to new module --- mopidy/frontends/http/__init__.py | 27 ++++++++------------------- mopidy/frontends/http/api.py | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 19 deletions(-) create mode 100644 mopidy/frontends/http/api.py diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 61aa5625..7b5cb049 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -14,7 +14,7 @@ try: except ImportError as import_error: raise exceptions.OptionalDependencyError(import_error) -from . import ws +from . import api, ws logger = logging.getLogger('mopidy.frontends.http') @@ -42,14 +42,16 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): cherrypy.tools.websocket = WebSocketTool() def _create_app(self): - root = Root(self.core) + root = RootResource() + root.api = api.ApiResource(self.core) root.ws = ws.WebSocketResource() - return cherrypy.tree.mount(root, '/', { + config = { '/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': ws.WebSocketHandler, }, - }) + } + return cherrypy.tree.mount(root, '/', config) def _setup_logging(self, app): cherrypy.log.access_log.setLevel(logging.NOTSET) @@ -75,18 +77,5 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): old_state, new_state))) -class Root(object): - def __init__(self, core): - self.core = core - - @cherrypy.expose - @cherrypy.tools.json_out() - def index(self): - playback_state = self.core.playback.state.get() - track = self.core.playback.current_track.get() - if track: - track = track.serialize() - return { - 'playback_state': playback_state, - 'current_track': track, - } +class RootResource(object): + pass diff --git a/mopidy/frontends/http/api.py b/mopidy/frontends/http/api.py new file mode 100644 index 00000000..b414c60c --- /dev/null +++ b/mopidy/frontends/http/api.py @@ -0,0 +1,23 @@ +from mopidy import exceptions + +try: + import cherrypy +except ImportError as import_error: + raise exceptions.OptionalDependencyError(import_error) + + +class ApiResource(object): + def __init__(self, core): + self.core = core + + @cherrypy.expose + @cherrypy.tools.json_out() + def index(self): + playback_state = self.core.playback.state.get() + track = self.core.playback.current_track.get() + if track: + track = track.serialize() + return { + 'playback_state': playback_state, + 'current_track': track, + } From 9b90e64dfb7197908ac5c3fa1dbfb507c6c078dd Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 11:08:23 +0100 Subject: [PATCH 13/47] http: Move frontend actor to new module --- mopidy/frontends/http/__init__.py | 83 +------------------------------ mopidy/frontends/http/actor.py | 79 +++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 81 deletions(-) create mode 100644 mopidy/frontends/http/actor.py diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 7b5cb049..e740677a 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -1,81 +1,2 @@ -from __future__ import absolute_import - -import logging - -import pykka - -from mopidy import exceptions, settings -from mopidy.core import CoreListener - -try: - import cherrypy - from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool - from ws4py.messaging import TextMessage -except ImportError as import_error: - raise exceptions.OptionalDependencyError(import_error) - -from . import api, ws - - -logger = logging.getLogger('mopidy.frontends.http') - - -class HttpFrontend(pykka.ThreadingActor, CoreListener): - def __init__(self, core): - super(HttpFrontend, self).__init__() - self.core = core - self._setup_server() - self._setup_websocket_plugin() - app = self._create_app() - self._setup_logging(app) - - def _setup_server(self): - cherrypy.config.update({ - 'engine.autoreload_on': False, - 'server.socket_host': - settings.HTTP_SERVER_HOSTNAME.encode('utf-8'), - 'server.socket_port': settings.HTTP_SERVER_PORT, - }) - - def _setup_websocket_plugin(self): - WebSocketPlugin(cherrypy.engine).subscribe() - cherrypy.tools.websocket = WebSocketTool() - - def _create_app(self): - root = RootResource() - root.api = api.ApiResource(self.core) - root.ws = ws.WebSocketResource() - config = { - '/ws': { - 'tools.websocket.on': True, - 'tools.websocket.handler_cls': ws.WebSocketHandler, - }, - } - return cherrypy.tree.mount(root, '/', config) - - def _setup_logging(self, app): - cherrypy.log.access_log.setLevel(logging.NOTSET) - cherrypy.log.error_log.setLevel(logging.NOTSET) - cherrypy.log.screen = False - - app.log.access_log.setLevel(logging.NOTSET) - app.log.error_log.setLevel(logging.NOTSET) - - def on_start(self): - logger.debug(u'Starting HTTP server') - cherrypy.engine.start() - logger.info(u'HTTP server running at %s', cherrypy.server.base()) - - def on_stop(self): - logger.debug(u'Stopping HTTP server') - cherrypy.engine.exit() - logger.info(u'Stopped HTTP server') - - def playback_state_changed(self, old_state, new_state): - cherrypy.engine.publish('websocket-broadcast', - TextMessage('playback_state_changed: %s -> %s' % ( - old_state, new_state))) - - -class RootResource(object): - pass +# flake8: noqa +from .actor import HttpFrontend diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py new file mode 100644 index 00000000..57af23d0 --- /dev/null +++ b/mopidy/frontends/http/actor.py @@ -0,0 +1,79 @@ +import logging + +import pykka + +from mopidy import exceptions, settings +from mopidy.core import CoreListener + +try: + import cherrypy + from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool + from ws4py.messaging import TextMessage +except ImportError as import_error: + raise exceptions.OptionalDependencyError(import_error) + +from . import api, ws + + +logger = logging.getLogger('mopidy.frontends.http') + + +class HttpFrontend(pykka.ThreadingActor, CoreListener): + def __init__(self, core): + super(HttpFrontend, self).__init__() + self.core = core + self._setup_server() + self._setup_websocket_plugin() + app = self._create_app() + self._setup_logging(app) + + def _setup_server(self): + cherrypy.config.update({ + 'engine.autoreload_on': False, + 'server.socket_host': + settings.HTTP_SERVER_HOSTNAME.encode('utf-8'), + 'server.socket_port': settings.HTTP_SERVER_PORT, + }) + + def _setup_websocket_plugin(self): + WebSocketPlugin(cherrypy.engine).subscribe() + cherrypy.tools.websocket = WebSocketTool() + + def _create_app(self): + root = RootResource() + root.api = api.ApiResource(self.core) + root.ws = ws.WebSocketResource() + config = { + '/ws': { + 'tools.websocket.on': True, + 'tools.websocket.handler_cls': ws.WebSocketHandler, + }, + } + return cherrypy.tree.mount(root, '/', config) + + def _setup_logging(self, app): + cherrypy.log.access_log.setLevel(logging.NOTSET) + cherrypy.log.error_log.setLevel(logging.NOTSET) + cherrypy.log.screen = False + + app.log.access_log.setLevel(logging.NOTSET) + app.log.error_log.setLevel(logging.NOTSET) + + def on_start(self): + logger.debug(u'Starting HTTP server') + cherrypy.engine.start() + logger.info(u'HTTP server running at %s', cherrypy.server.base()) + + def on_stop(self): + logger.debug(u'Stopping HTTP server') + cherrypy.engine.exit() + logger.info(u'Stopped HTTP server') + + def playback_state_changed(self, old_state, new_state): + cherrypy.engine.publish('websocket-broadcast', + TextMessage('playback_state_changed: %s -> %s' % ( + old_state, new_state))) + + +class RootResource(object): + pass From 256c5a817911bc6c8bd636adcc768f7329353076 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 11:19:40 +0100 Subject: [PATCH 14/47] http: Document existence of the new frontend --- docs/conf.py | 6 ++++++ docs/modules/frontends/http.rst | 8 ++++++++ mopidy/frontends/http/__init__.py | 34 +++++++++++++++++++++++++++++++ mopidy/frontends/http/actor.py | 2 +- 4 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 docs/modules/frontends/http.rst diff --git a/docs/conf.py b/docs/conf.py index d02303df..7e626d99 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -37,6 +37,7 @@ class Mock(object): MOCK_MODULES = [ + 'cherrypy', 'dbus', 'dbus.mainloop', 'dbus.mainloop.glib', @@ -51,6 +52,11 @@ MOCK_MODULES = [ 'pykka.registry', 'pylast', 'serial', + 'ws4py', + 'ws4py.messaging', + 'ws4py.server', + 'ws4py.server.cherrypyserver', + 'ws4py.websocket', ] for mod_name in MOCK_MODULES: sys.modules[mod_name] = Mock() diff --git a/docs/modules/frontends/http.rst b/docs/modules/frontends/http.rst new file mode 100644 index 00000000..31366bd1 --- /dev/null +++ b/docs/modules/frontends/http.rst @@ -0,0 +1,8 @@ +.. _http-frontend: + +********************************************* +:mod:`mopidy.frontends.http` -- HTTP frontend +********************************************* + +.. automodule:: mopidy.frontends.http + :synopsis: HTTP and WebSockets frontend diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index e740677a..ab5c3e22 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -1,2 +1,36 @@ +""" +Frontend which lets you control Mopidy through HTTP and WebSockets. + +**Dependencies** + +- ``cherrypy`` + +- ``ws4py`` + +**Settings** + +- :attr:`mopidy.settings.HTTP_SERVER_HOSTNAME` + +- :attr:`mopidy.settings.HTTP_SERVER_PORT` + +**Usage** + +When this frontend is included in :attr:`mopidy.settings.FRONTENDS`, it starts +a web server at the port specified by :attr:`mopidy.settings.HTTP_SERVER_PORT`. +This web server exposes both a REST web service at the URL ``/api``, and a +WebSocket at ``/ws``. + +The REST API gives you access to most Mopidy functionality, while the WebSocket +enables Mopidy to instantly push events to the client, as they happen. + +It is also the intention that the frontend should be able to host static files +for any external JavaScript client. This has currently not been implemented. + +**API stability** + +This frontend is currently to be regarded as **experimental**, and we are not +promising to keep any form of backwards compatibility between releases. +""" + # flake8: noqa from .actor import HttpFrontend diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index 57af23d0..c9ae651e 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -7,8 +7,8 @@ from mopidy.core import CoreListener try: import cherrypy - from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool from ws4py.messaging import TextMessage + from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool except ImportError as import_error: raise exceptions.OptionalDependencyError(import_error) From a2259fad57c59c40883125179f3756311819193f Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 13:27:27 +0100 Subject: [PATCH 15/47] http: Add static files hosting --- mopidy/frontends/http/__init__.py | 16 ++++++++++------ mopidy/frontends/http/actor.py | 11 +++++++++++ mopidy/settings.py | 12 +++++++++++- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index ab5c3e22..d674e1d0 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -13,18 +13,22 @@ Frontend which lets you control Mopidy through HTTP and WebSockets. - :attr:`mopidy.settings.HTTP_SERVER_PORT` +- :attr:`mopidy.settings.HTTP_SERVER_STATIC_DIR` + **Usage** When this frontend is included in :attr:`mopidy.settings.FRONTENDS`, it starts a web server at the port specified by :attr:`mopidy.settings.HTTP_SERVER_PORT`. + This web server exposes both a REST web service at the URL ``/api``, and a -WebSocket at ``/ws``. +WebSocket at ``/ws``. The REST API gives you access to most Mopidy +functionality, while the WebSocket enables Mopidy to instantly push events to +the client, as they happen. -The REST API gives you access to most Mopidy functionality, while the WebSocket -enables Mopidy to instantly push events to the client, as they happen. - -It is also the intention that the frontend should be able to host static files -for any external JavaScript client. This has currently not been implemented. +The web server can also host any static files, for example the HTML, CSS, +JavaScript and images needed by a web based Mopidy client. To host static +files, change :attr:`mopidy.settings.HTTP_SERVER_STATIC_DIR` to point to the +directory you want to serve. **API stability** diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index c9ae651e..5c997f79 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -43,12 +43,23 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): root = RootResource() root.api = api.ApiResource(self.core) root.ws = ws.WebSocketResource() + config = { '/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': ws.WebSocketHandler, }, } + + if settings.HTTP_SERVER_STATIC_DIR: + logger.debug(u'HTTP server will serve "%s" at /', + settings.HTTP_SERVER_STATIC_DIR) + config['/'] = { + 'tools.staticdir.on': True, + 'tools.staticdir.index': 'index.html', + 'tools.staticdir.dir': settings.HTTP_SERVER_STATIC_DIR, + } + return cherrypy.tree.mount(root, '/', config) def _setup_logging(self, app): diff --git a/mopidy/settings.py b/mopidy/settings.py index 36057869..3603eda6 100644 --- a/mopidy/settings.py +++ b/mopidy/settings.py @@ -49,7 +49,7 @@ DEBUG_LOG_FILENAME = u'mopidy.log' #: get a SIGUSR1. Mainly a debug tool for figuring out deadlocks. #: #: Default:: -#: +#: #: DEBUG_THREAD = False DEBUG_THREAD = False @@ -101,6 +101,16 @@ HTTP_SERVER_HOSTNAME = u'127.0.0.1' #: Default: 6680 HTTP_SERVER_PORT = 6680 +#: Which directory Mopidy's HTTP server should serve at /. +#: +#: Change this to have Mopidy serve e.g. files for your JavaScript client. +#: /api and /ws will continue to work as usual even if you change this setting. +#: +#: Used by :mod:`mopidy.frontends.http`. +#: +#: Default: None +HTTP_SERVER_STATIC_DIR = None + #: Your `Last.fm `_ username. #: #: Used by :mod:`mopidy.frontends.lastfm`. From 9d2732703dbab0f308cfc56a6a5013e176ac2bd1 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 14:22:54 +0100 Subject: [PATCH 16/47] http: Serve placeholder index.html when no STATIC_DIR set --- MANIFEST.in | 1 + mopidy/frontends/http/actor.py | 21 +++--- mopidy/frontends/http/index.html | 111 +++++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+), 9 deletions(-) create mode 100644 mopidy/frontends/http/index.html diff --git a/MANIFEST.in b/MANIFEST.in index f3723ecd..476cd5c1 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,6 +4,7 @@ include LICENSE include MANIFEST.in include data/mopidy.desktop include mopidy/backends/spotify/spotify_appkey.key +include mopidy/frontends/http/index.html include pylintrc recursive-include docs * prune docs/_build diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index 5c997f79..7eed0937 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -1,4 +1,5 @@ import logging +import os import pykka @@ -44,22 +45,24 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): root.api = api.ApiResource(self.core) root.ws = ws.WebSocketResource() + if settings.HTTP_SERVER_STATIC_DIR: + static_dir = settings.HTTP_SERVER_STATIC_DIR + else: + static_dir = os.path.dirname(__file__) + logger.debug(u'HTTP server will serve "%s" at /', static_dir) + config = { + '/': { + 'tools.staticdir.on': True, + 'tools.staticdir.index': 'index.html', + 'tools.staticdir.dir': static_dir, + }, '/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': ws.WebSocketHandler, }, } - if settings.HTTP_SERVER_STATIC_DIR: - logger.debug(u'HTTP server will serve "%s" at /', - settings.HTTP_SERVER_STATIC_DIR) - config['/'] = { - 'tools.staticdir.on': True, - 'tools.staticdir.index': 'index.html', - 'tools.staticdir.dir': settings.HTTP_SERVER_STATIC_DIR, - } - return cherrypy.tree.mount(root, '/', config) def _setup_logging(self, app): diff --git a/mopidy/frontends/http/index.html b/mopidy/frontends/http/index.html new file mode 100644 index 00000000..f3f0b208 --- /dev/null +++ b/mopidy/frontends/http/index.html @@ -0,0 +1,111 @@ + + + + + Mopidy HTTP frontend + + + +
+

Mopidy HTTP frontend

+ +

This web server is a part of the music server Mopidy. To learn more + about Mopidy, please visit www.mopidy.com.

+
+ +
+

Static content serving

+ +

To see your own content here, change the setting + HTTP_SERVER_STATIC_DIR to point to the directory containing your + content. This can be used to host a web based Mopidy client here.

+ +

Even if you host your own content on the root of the web server, + you'll always have the following services available.

+
+ +
+

Web service

+ +

Mopidy makes it's API available for use over HTTP at + /api/. The service tries to be RESTful. It serves and + eats JSON data.

+
+ +
+

WebSocket endpoint

+ +

Mopidy has a WebSocket endpoint at /ws/. You can + use WebSockets to get notified about events happening in Mopidy. The + alternative would be to regularly poll the conventional web service for + updates.

+ +

To connect to the endpoint from a browser with WebSocket support, + simply enter the following JavaScript code in the browser's console:

+ +
var ws = new WebSocket("ws://myhost:myport/ws/');
+ws.onmessage = function (event) {
+  console.log("Incoming message: ", event.data);
+};
+ws.send("Message to the server, ahoy!");
+
+ +
+

Documentation

+ +

For more information, please refer to the Mopidy documentation at + docs.mopidy.com.

+
+ + From 5458c1271fc720b85f120308c931224532356cb5 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 9 Nov 2012 14:52:46 +0100 Subject: [PATCH 17/47] http: Switch to HTTP method dispatcher for /api --- mopidy/frontends/http/actor.py | 3 +++ mopidy/frontends/http/api.py | 5 +++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index 7eed0937..8678d8b0 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -57,6 +57,9 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): 'tools.staticdir.index': 'index.html', 'tools.staticdir.dir': static_dir, }, + '/api': { + 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), + }, '/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': ws.WebSocketHandler, diff --git a/mopidy/frontends/http/api.py b/mopidy/frontends/http/api.py index b414c60c..0003f06a 100644 --- a/mopidy/frontends/http/api.py +++ b/mopidy/frontends/http/api.py @@ -7,12 +7,13 @@ except ImportError as import_error: class ApiResource(object): + exposed = True + def __init__(self, core): self.core = core - @cherrypy.expose @cherrypy.tools.json_out() - def index(self): + def GET(self): playback_state = self.core.playback.state.get() track = self.core.playback.current_track.get() if track: From 86e0eff21db537d8974b23c8ed066fc635becba6 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Sat, 10 Nov 2012 20:57:18 +0100 Subject: [PATCH 18/47] http: Extend player resource, add tracklist and playlists resources --- mopidy/frontends/http/api.py | 94 ++++++++++++++++++++++-- tests/frontends/http/__init__.py | 0 tests/frontends/http/api_test.py | 118 +++++++++++++++++++++++++++++++ tests/frontends/http/ws_test.py | 5 ++ 4 files changed, 211 insertions(+), 6 deletions(-) create mode 100644 tests/frontends/http/__init__.py create mode 100644 tests/frontends/http/api_test.py create mode 100644 tests/frontends/http/ws_test.py diff --git a/mopidy/frontends/http/api.py b/mopidy/frontends/http/api.py index 0003f06a..66caeb1a 100644 --- a/mopidy/frontends/http/api.py +++ b/mopidy/frontends/http/api.py @@ -11,14 +11,96 @@ class ApiResource(object): def __init__(self, core): self.core = core + self.player = PlayerResource(core) + self.tracklist = TrackListResource(core) + self.playlists = PlaylistsResource(core) @cherrypy.tools.json_out() def GET(self): - playback_state = self.core.playback.state.get() - track = self.core.playback.current_track.get() - if track: - track = track.serialize() return { - 'playback_state': playback_state, - 'current_track': track, + 'resources': { + 'player': { + 'href': '/api/player/', + }, + 'tracklist': { + 'href': '/api/tracklist/', + }, + 'playlists': { + 'href': '/api/playlists/', + }, + } + } + + +class PlayerResource(object): + exposed = True + + def __init__(self, core): + self.core = core + + @cherrypy.tools.json_out() + def GET(self): + futures = { + 'state': self.core.playback.state, + 'current_track': self.core.playback.current_track, + 'consume': self.core.playback.consume, + 'random': self.core.playback.random, + 'repeat': self.core.playback.repeat, + 'single': self.core.playback.single, + 'volume': self.core.playback.volume, + 'time_position': self.core.playback.time_position, + } + current_track = futures['current_track'].get() + if current_track: + current_track = current_track.serialize() + return { + 'properties': { + 'state': futures['state'].get(), + 'currentTrack': current_track, + 'consume': futures['consume'].get(), + 'random': futures['random'].get(), + 'repeat': futures['repeat'].get(), + 'single': futures['single'].get(), + 'volume': futures['volume'].get(), + 'timePosition': futures['time_position'].get(), + } + } + + +class TrackListResource(object): + exposed = True + + def __init__(self, core): + self.core = core + + @cherrypy.tools.json_out() + def GET(self): + futures = { + 'cp_tracks': self.core.current_playlist.cp_tracks, + 'current_cp_track': self.core.playback.current_cp_track, + } + cp_tracks = futures['cp_tracks'].get() + tracks = [] + for cp_track in cp_tracks: + track = cp_track.track.serialize() + track['cpid'] = cp_track.cpid + tracks.append(track) + current_cp_track = futures['current_cp_track'].get() + return { + 'currentTrackCpid': current_cp_track and current_cp_track.cpid, + 'tracks': tracks, + } + + +class PlaylistsResource(object): + exposed = True + + def __init__(self, core): + self.core = core + + @cherrypy.tools.json_out() + def GET(self): + playlists = self.core.stored_playlists.playlists.get() + return { + 'playlists': [p.serialize() for p in playlists], } diff --git a/tests/frontends/http/__init__.py b/tests/frontends/http/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/frontends/http/api_test.py b/tests/frontends/http/api_test.py new file mode 100644 index 00000000..14f94773 --- /dev/null +++ b/tests/frontends/http/api_test.py @@ -0,0 +1,118 @@ +import pykka + +from tests import unittest + +from mopidy import core +from mopidy.backends import dummy +from mopidy.frontends.http import api +from mopidy.models import Track + + +class ApiResourceTest(unittest.TestCase): + def setUp(self): + self.backend = dummy.DummyBackend.start(audio=None).proxy() + self.core = core.Core.start(backends=[self.backend]).proxy() + self.api = api.ApiResource(core=self.core) + + self.core.stored_playlists.create('x') + self.core.stored_playlists.create('y') + self.core.stored_playlists.create('z') + self.core.current_playlist.append([ + Track(uri='dummy:a'), + Track(uri='dummy:b'), + Track(uri='dummy:c'), + ]) + + def tearDown(self): + pykka.ActorRegistry.stop_all() + + def test_api_get_returns_list_of_resources(self): + result = self.api.GET() + + self.assertIn('resources', result) + + self.assertIn('player', result['resources']) + self.assertEquals('/api/player/', + result['resources']['player']['href']) + + self.assertIn('tracklist', result['resources']) + self.assertEquals('/api/tracklist/', + result['resources']['tracklist']['href']) + + self.assertIn('playlists', result['resources']) + self.assertEquals('/api/playlists/', + result['resources']['playlists']['href']) + + def test_player_get_returns_playback_properties(self): + result = self.api.player.GET() + + self.assertIn('properties', result) + + self.assertIn('state', result['properties']) + self.assertEqual('stopped', result['properties']['state']) + + self.assertIn('currentTrack', result['properties']) + self.assertEqual(None, result['properties']['currentTrack']) + + self.assertIn('consume', result['properties']) + self.assertEqual(False, result['properties']['consume']) + + self.assertIn('random', result['properties']) + self.assertEqual(False, result['properties']['random']) + + self.assertIn('repeat', result['properties']) + self.assertEqual(False, result['properties']['repeat']) + + self.assertIn('single', result['properties']) + self.assertEqual(False, result['properties']['single']) + + self.assertIn('volume', result['properties']) + self.assertEqual(None, result['properties']['volume']) + + self.assertIn('timePosition', result['properties']) + self.assertEqual(0, result['properties']['timePosition']) + + def test_player_state_changes_when_playing(self): + self.core.playback.play() + + result = self.api.player.GET() + + self.assertEqual('playing', result['properties']['state']) + + def test_player_volume_changes(self): + self.core.playback.volume = 37 + + result = self.api.player.GET() + + self.assertEqual(37, result['properties']['volume']) + + def test_tracklist_returns_current_playlist(self): + result = self.api.tracklist.GET() + + self.assertIn('tracks', result) + self.assertEqual(3, len(result['tracks'])) + + self.assertEqual('dummy:a', result['tracks'][0]['uri']) + self.assertEqual(0, result['tracks'][0]['cpid']) + + self.assertEqual('dummy:b', result['tracks'][1]['uri']) + self.assertEqual(1, result['tracks'][1]['cpid']) + + self.assertEqual('dummy:c', result['tracks'][2]['uri']) + self.assertEqual(2, result['tracks'][2]['cpid']) + + def test_tracklist_includes_current_track(self): + self.core.playback.play() + + result = self.api.tracklist.GET() + + self.assertIn('currentTrackCpid', result) + self.assertEqual(0, result['currentTrackCpid']) + + def test_playlists_returns_stored_playlists(self): + result = self.api.playlists.GET() + + self.assertIn('playlists', result) + self.assertEqual('x', result['playlists'][0]['name']) + self.assertEqual('y', result['playlists'][1]['name']) + self.assertEqual('z', result['playlists'][2]['name']) diff --git a/tests/frontends/http/ws_test.py b/tests/frontends/http/ws_test.py new file mode 100644 index 00000000..0615052e --- /dev/null +++ b/tests/frontends/http/ws_test.py @@ -0,0 +1,5 @@ +from tests import unittest + + +class WebSocketsTest(unittest.TestCase): + pass # TODO From 90ca6a786a32a01763ea9649f6900f06ba8b4d44 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Sat, 10 Nov 2012 21:30:11 +0100 Subject: [PATCH 19/47] http: Add pip requirements file. Make Travis use it. --- .travis.yml | 1 + requirements/http.txt | 2 ++ 2 files changed, 3 insertions(+) create mode 100644 requirements/http.txt diff --git a/.travis.yml b/.travis.yml index df08679b..7acda2bd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ install: - "sudo wget -q -O /etc/apt/sources.list.d/mopidy.list http://apt.mopidy.com/mopidy.list" - "sudo apt-get update || true" - "sudo apt-get install $(apt-cache depends mopidy | awk '$2 !~ /mopidy/ {print $2}')" + - "pip install -r requirements/http.txt" # Until ws4py is packaged as a .deb before_script: - "rm $VIRTUAL_ENV/lib/python$TRAVIS_PYTHON_VERSION/no-global-site-packages.txt" diff --git a/requirements/http.txt b/requirements/http.txt new file mode 100644 index 00000000..d8757e29 --- /dev/null +++ b/requirements/http.txt @@ -0,0 +1,2 @@ +cherrypy >= 3.2.2 +ws4py >= 0.2.3 From 0fc0b4b1efecf3ce35500340e73541eec8a80461 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Sun, 11 Nov 2012 19:13:15 +0100 Subject: [PATCH 20/47] http: Don't build almost the same dict twice --- mopidy/frontends/http/api.py | 37 ++++++++++++------------------------ 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/mopidy/frontends/http/api.py b/mopidy/frontends/http/api.py index 66caeb1a..1c0aa85b 100644 --- a/mopidy/frontends/http/api.py +++ b/mopidy/frontends/http/api.py @@ -40,31 +40,21 @@ class PlayerResource(object): @cherrypy.tools.json_out() def GET(self): - futures = { + properties = { 'state': self.core.playback.state, - 'current_track': self.core.playback.current_track, + 'currentTrack': self.core.playback.current_track, 'consume': self.core.playback.consume, 'random': self.core.playback.random, 'repeat': self.core.playback.repeat, 'single': self.core.playback.single, 'volume': self.core.playback.volume, - 'time_position': self.core.playback.time_position, - } - current_track = futures['current_track'].get() - if current_track: - current_track = current_track.serialize() - return { - 'properties': { - 'state': futures['state'].get(), - 'currentTrack': current_track, - 'consume': futures['consume'].get(), - 'random': futures['random'].get(), - 'repeat': futures['repeat'].get(), - 'single': futures['single'].get(), - 'volume': futures['volume'].get(), - 'timePosition': futures['time_position'].get(), - } + 'timePosition': self.core.playback.time_position, } + for key, value in properties.items(): + properties[key] = value.get() + if properties['currentTrack']: + properties['currentTrack'] = properties['currentTrack'].serialize() + return {'properties': properties} class TrackListResource(object): @@ -75,17 +65,14 @@ class TrackListResource(object): @cherrypy.tools.json_out() def GET(self): - futures = { - 'cp_tracks': self.core.current_playlist.cp_tracks, - 'current_cp_track': self.core.playback.current_cp_track, - } - cp_tracks = futures['cp_tracks'].get() + cp_tracks_future = self.core.current_playlist.cp_tracks + current_cp_track_future = self.core.playback.current_cp_track tracks = [] - for cp_track in cp_tracks: + for cp_track in cp_tracks_future.get(): track = cp_track.track.serialize() track['cpid'] = cp_track.cpid tracks.append(track) - current_cp_track = futures['current_cp_track'].get() + current_cp_track = current_cp_track_future.get() return { 'currentTrackCpid': current_cp_track and current_cp_track.cpid, 'tracks': tracks, From 1d14740a661488ab34b2c97b6aa86b9591b7289e Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Sun, 11 Nov 2012 20:13:20 +0100 Subject: [PATCH 21/47] http: Show incoming WebSocket messages on the placeholder page --- mopidy/frontends/http/index.html | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/mopidy/frontends/http/index.html b/mopidy/frontends/http/index.html index f3f0b208..37823577 100644 --- a/mopidy/frontends/http/index.html +++ b/mopidy/frontends/http/index.html @@ -8,7 +8,7 @@ background: #e8ecef; color: #555; font-family: "Droid Serif", Georgia, "Times New Roman", Palatino, - "Hoefler Text", Baskerville, serif;; + "Hoefler Text", Baskerville, serif; font-size: 150%; line-height: 1.4em; } @@ -53,6 +53,10 @@ .box.focus a { color: #e8ecef; } + #ws-console { + height: 200px; + overflow: auto; + } @@ -99,6 +103,10 @@ ws.onmessage = function (event) { console.log("Incoming message: ", event.data); }; ws.send("Message to the server, ahoy!"); + +

Here you can see events arriving from Mopidy in real time:

+ +

     
 
     
@@ -107,5 +115,16 @@ ws.send("Message to the server, ahoy!");

For more information, please refer to the Mopidy documentation at docs.mopidy.com.

+ + From df4d7cd4c987f758289654f7b1bbe5c17e9e7d0a Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 16 Nov 2012 22:11:45 +0100 Subject: [PATCH 22/47] http: Update to use unicode literals and not cause warnings with flake8 --- mopidy/frontends/http/actor.py | 25 ++++++++++++++----------- mopidy/frontends/http/api.py | 2 ++ mopidy/frontends/http/ws.py | 13 +++++++++---- tests/frontends/http/api_test.py | 14 ++++++++------ tests/frontends/http/ws_test.py | 2 ++ 5 files changed, 35 insertions(+), 21 deletions(-) diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index 8678d8b0..f6a9a441 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import logging import os @@ -31,8 +33,8 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): def _setup_server(self): cherrypy.config.update({ 'engine.autoreload_on': False, - 'server.socket_host': - settings.HTTP_SERVER_HOSTNAME.encode('utf-8'), + 'server.socket_host': ( + settings.HTTP_SERVER_HOSTNAME.encode('utf-8')), 'server.socket_port': settings.HTTP_SERVER_PORT, }) @@ -49,18 +51,18 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): static_dir = settings.HTTP_SERVER_STATIC_DIR else: static_dir = os.path.dirname(__file__) - logger.debug(u'HTTP server will serve "%s" at /', static_dir) + logger.debug('HTTP server will serve "%s" at /', static_dir) config = { - '/': { + b'/': { 'tools.staticdir.on': True, 'tools.staticdir.index': 'index.html', 'tools.staticdir.dir': static_dir, }, - '/api': { + b'/api': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), }, - '/ws': { + b'/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': ws.WebSocketHandler, }, @@ -77,17 +79,18 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): app.log.error_log.setLevel(logging.NOTSET) def on_start(self): - logger.debug(u'Starting HTTP server') + logger.debug('Starting HTTP server') cherrypy.engine.start() - logger.info(u'HTTP server running at %s', cherrypy.server.base()) + logger.info('HTTP server running at %s', cherrypy.server.base()) def on_stop(self): - logger.debug(u'Stopping HTTP server') + logger.debug('Stopping HTTP server') cherrypy.engine.exit() - logger.info(u'Stopped HTTP server') + logger.info('Stopped HTTP server') def playback_state_changed(self, old_state, new_state): - cherrypy.engine.publish('websocket-broadcast', + cherrypy.engine.publish( + 'websocket-broadcast', TextMessage('playback_state_changed: %s -> %s' % ( old_state, new_state))) diff --git a/mopidy/frontends/http/api.py b/mopidy/frontends/http/api.py index caaf69e2..f5a78f99 100644 --- a/mopidy/frontends/http/api.py +++ b/mopidy/frontends/http/api.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from mopidy import exceptions try: diff --git a/mopidy/frontends/http/ws.py b/mopidy/frontends/http/ws.py index 53ad651d..98fe8562 100644 --- a/mopidy/frontends/http/ws.py +++ b/mopidy/frontends/http/ws.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import logging from mopidy import exceptions @@ -15,23 +17,26 @@ logger = logging.getLogger('mopidy.frontends.http') class WebSocketResource(object): @cherrypy.expose def index(self): - logger.debug(u'WebSocket handler created') + logger.debug('WebSocket handler created') class WebSocketHandler(WebSocket): def opened(self): remote = cherrypy.request.remote - logger.debug(u'New WebSocket connection from %s:%d', + logger.debug( + 'New WebSocket connection from %s:%d', remote.ip, remote.port) def closed(self, code, reason=None): remote = cherrypy.request.remote - logger.debug(u'Closed WebSocket connection from %s:%d ' + logger.debug( + 'Closed WebSocket connection from %s:%d ' 'with code %s and reason %r', remote.ip, remote.port, code, reason) def received_message(self, message): remote = cherrypy.request.remote - logger.debug(u'Received WebSocket message from %s:%d: %s', + logger.debug( + 'Received WebSocket message from %s:%d: %s', remote.ip, remote.port, message) # This is where we would handle incoming messages from the clients diff --git a/tests/frontends/http/api_test.py b/tests/frontends/http/api_test.py index 88aa5682..cd77b923 100644 --- a/tests/frontends/http/api_test.py +++ b/tests/frontends/http/api_test.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import pykka from tests import unittest @@ -32,16 +34,16 @@ class ApiResourceTest(unittest.TestCase): self.assertIn('resources', result) self.assertIn('player', result['resources']) - self.assertEquals('/api/player/', - result['resources']['player']['href']) + self.assertEquals( + '/api/player/', result['resources']['player']['href']) self.assertIn('tracklist', result['resources']) - self.assertEquals('/api/tracklist/', - result['resources']['tracklist']['href']) + self.assertEquals( + '/api/tracklist/', result['resources']['tracklist']['href']) self.assertIn('playlists', result['resources']) - self.assertEquals('/api/playlists/', - result['resources']['playlists']['href']) + self.assertEquals( + '/api/playlists/', result['resources']['playlists']['href']) def test_player_get_returns_playback_properties(self): result = self.api.player.GET() diff --git a/tests/frontends/http/ws_test.py b/tests/frontends/http/ws_test.py index 0615052e..0f0f6ff3 100644 --- a/tests/frontends/http/ws_test.py +++ b/tests/frontends/http/ws_test.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from tests import unittest From 97ca863c5d633e4e3b0dd6fa3b6d2d8f29c0c29c Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 16 Nov 2012 22:35:00 +0100 Subject: [PATCH 23/47] http: Pass core to WebSocket handler --- mopidy/frontends/http/actor.py | 2 +- mopidy/frontends/http/ws.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index f6a9a441..181eb93c 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -45,7 +45,7 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): def _create_app(self): root = RootResource() root.api = api.ApiResource(self.core) - root.ws = ws.WebSocketResource() + root.ws = ws.WebSocketResource(self.core) if settings.HTTP_SERVER_STATIC_DIR: static_dir = settings.HTTP_SERVER_STATIC_DIR diff --git a/mopidy/frontends/http/ws.py b/mopidy/frontends/http/ws.py index 98fe8562..581eb849 100644 --- a/mopidy/frontends/http/ws.py +++ b/mopidy/frontends/http/ws.py @@ -15,9 +15,13 @@ logger = logging.getLogger('mopidy.frontends.http') class WebSocketResource(object): + def __init__(self, core): + self.core = core + @cherrypy.expose def index(self): logger.debug('WebSocket handler created') + cherrypy.request.ws_handler.core = self.core class WebSocketHandler(WebSocket): @@ -40,3 +44,6 @@ class WebSocketHandler(WebSocket): 'Received WebSocket message from %s:%d: %s', remote.ip, remote.port, message) # This is where we would handle incoming messages from the clients + + # This is just for demonstration purposes + self.send('Playback state: %s' % self.core.playback.state.get()) From 02360ae9c0d553e8ac172b241b70a0518d8dbe3a Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Sun, 18 Nov 2012 18:27:50 +0100 Subject: [PATCH 24/47] http: Move static files to its own dir --- mopidy/frontends/http/actor.py | 2 +- mopidy/frontends/http/{ => data}/index.html | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename mopidy/frontends/http/{ => data}/index.html (100%) diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index 181eb93c..b0697409 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -50,7 +50,7 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): if settings.HTTP_SERVER_STATIC_DIR: static_dir = settings.HTTP_SERVER_STATIC_DIR else: - static_dir = os.path.dirname(__file__) + static_dir = os.path.join(os.path.dirname(__file__), 'data') logger.debug('HTTP server will serve "%s" at /', static_dir) config = { diff --git a/mopidy/frontends/http/index.html b/mopidy/frontends/http/data/index.html similarity index 100% rename from mopidy/frontends/http/index.html rename to mopidy/frontends/http/data/index.html From e87a73298cf86814e4143f8f4885e3b7c4b3b18c Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Sun, 18 Nov 2012 18:31:22 +0100 Subject: [PATCH 25/47] http: Include data dir in distribution packages --- MANIFEST.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MANIFEST.in b/MANIFEST.in index 476cd5c1..6a64cb9a 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,10 +4,10 @@ include LICENSE include MANIFEST.in include data/mopidy.desktop include mopidy/backends/spotify/spotify_appkey.key -include mopidy/frontends/http/index.html include pylintrc recursive-include docs * prune docs/_build +recursive-include mopidy/frontends/http/data/ recursive-include requirements * recursive-include tests *.py recursive-include tests/data * From fd47d19ff4be6ee90c51ccf02a2f9611e1414c7c Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Sun, 18 Nov 2012 18:31:49 +0100 Subject: [PATCH 26/47] http: Bundle jQuery --- mopidy/frontends/http/data/index.html | 4 +--- mopidy/frontends/http/data/jquery-1.8.3.min.js | 2 ++ 2 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 mopidy/frontends/http/data/jquery-1.8.3.min.js diff --git a/mopidy/frontends/http/data/index.html b/mopidy/frontends/http/data/index.html index 37823577..a426b4d5 100644 --- a/mopidy/frontends/http/data/index.html +++ b/mopidy/frontends/http/data/index.html @@ -115,9 +115,7 @@ ws.send("Message to the server, ahoy!");

For more information, please refer to the Mopidy documentation at docs.mopidy.com.

- + From 96a31adf637635e6279f048fe12a2a242eb7b463 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Wed, 28 Nov 2012 19:17:46 +0100 Subject: [PATCH 37/47] http: Use CSS file from mopidy.com --- mopidy/frontends/http/data/index.html | 56 +-------------------- mopidy/frontends/http/data/mopidy.css | 71 +++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 55 deletions(-) create mode 100644 mopidy/frontends/http/data/mopidy.css diff --git a/mopidy/frontends/http/data/index.html b/mopidy/frontends/http/data/index.html index f706a317..c3a4199b 100644 --- a/mopidy/frontends/http/data/index.html +++ b/mopidy/frontends/http/data/index.html @@ -3,61 +3,7 @@ Mopidy HTTP frontend - +
diff --git a/mopidy/frontends/http/data/mopidy.css b/mopidy/frontends/http/data/mopidy.css new file mode 100644 index 00000000..7944a53a --- /dev/null +++ b/mopidy/frontends/http/data/mopidy.css @@ -0,0 +1,71 @@ +html { + background: #e8ecef; + color: #555; + font-family: "Droid Serif", "Georgia", "Times New Roman", "Palatino", + "Hoefler Text", "Baskerville", serif; + font-size: 150%; + line-height: 1.4em; +} +body { + max-width: 20em; + margin: 0 auto; +} +div.box { + background: white; + border-radius: 5px; + box-shadow: 5px 5px 5px #d8dcdf; + margin: 2em 0; + padding: 1em; +} +div.box.focus { + background: #465158; + color: #e8ecef; +} +div.icon { + float: right; +} +h1, h2 { + font-family: "Ubuntu", "Arial", "Helvetica", "Lucida Grande", + "Verdana", "Gill Sans", sans-serif; + line-height: 1.1em; +} +h2 { + margin: 0.2em 0 0; +} +p.next { + text-align: right; +} +a { + color: #555; + text-decoration: none; + border-bottom: 1px dotted; +} +img { + border: 0; +} +code, pre { + font-family: "Droid Sans Mono", Menlo, Courier New, Courier, Mono, monospace; + font-size: 9pt; + line-height: 1.2em; + padding: 0.5em 1em; + margin: 1em 0; + white-space: pre; + overflow: auto; +} +.box code, +.box pre { + background: #e8ecef; + color: #555; +} +.box a { + color: #465158; +} +.box a:hover { + opacity: 0.8; +} +.box.focus a { + color: #e8ecef; +} +.center { + text-align: center; +} From c1e60ba3787ca227150987c459accd2853091f78 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Wed, 28 Nov 2012 19:18:13 +0100 Subject: [PATCH 38/47] http: Add /mopidy/ static dir that is always available --- mopidy/frontends/http/actor.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index 3f7fa1aa..65cf9445 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -54,12 +54,19 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): static_dir = os.path.join(os.path.dirname(__file__), 'data') logger.debug('HTTP server will serve "%s" at /', static_dir) + mopidy_dir = os.path.join(os.path.dirname(__file__), 'data') + config = { b'/': { 'tools.staticdir.on': True, 'tools.staticdir.index': 'index.html', 'tools.staticdir.dir': static_dir, }, + b'/mopidy': { + 'tools.staticdir.on': True, + 'tools.staticdir.index': 'mopidy.html', + 'tools.staticdir.dir': mopidy_dir, + }, b'/mopidy/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': ws.WebSocketHandler, From 67c92ceab99d1a66962d4223e366cb80a52032ef Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Wed, 28 Nov 2012 19:19:06 +0100 Subject: [PATCH 39/47] http: Move resource details to /mopidy/ page --- mopidy/frontends/http/data/index.html | 56 ++++--------------------- mopidy/frontends/http/data/mopidy.html | 58 ++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 47 deletions(-) create mode 100644 mopidy/frontends/http/data/mopidy.html diff --git a/mopidy/frontends/http/data/index.html b/mopidy/frontends/http/data/index.html index c3a4199b..37885eef 100644 --- a/mopidy/frontends/http/data/index.html +++ b/mopidy/frontends/http/data/index.html @@ -3,65 +3,27 @@ Mopidy HTTP frontend - +

Mopidy HTTP frontend

This web server is a part of the music server Mopidy. To learn more - about Mopidy, please visit www.mopidy.com.

+ about Mopidy, please visit + www.mopidy.com.

Static content serving

-

To see your own content here, change the setting - HTTP_SERVER_STATIC_DIR to point to the directory containing your - content. This can be used to host a web based Mopidy client here.

+

To see your own content instead of this placeholder page, change the + setting HTTP_SERVER_STATIC_DIR to point to the directory + containing your static files. This can be used to host e.g. a pure + HTML/CSS/JavaScript Mopidy client.

-

Even if you host your own content on the root of the web server, - you'll always have the following services available.

+

If you replace this page with your own content, the Mopidy resources + at /mopidy/ will still be available.

- -
-

WebSocket endpoint

- -

Mopidy has a WebSocket endpoint at /mopidy/ws/. You can - use WebSockets to get notified about events happening in Mopidy. The - alternative would be to regularly poll the conventional web service for - updates.

- -

To connect to the endpoint from a browser with WebSocket support, - simply enter the following JavaScript code in the browser's console:

- -
var ws = new WebSocket("ws://myhost:myport/mopidy/ws/');
-ws.onmessage = function (event) {
-  console.log("Incoming message: ", event.data);
-};
-ws.send("Message to the server, ahoy!");
- -

Here you can see events arriving from Mopidy in real time:

- -

-    
- -
-

Documentation

- -

For more information, please refer to the Mopidy documentation at - docs.mopidy.com.

-
- - diff --git a/mopidy/frontends/http/data/mopidy.html b/mopidy/frontends/http/data/mopidy.html new file mode 100644 index 00000000..81fe445a --- /dev/null +++ b/mopidy/frontends/http/data/mopidy.html @@ -0,0 +1,58 @@ + + + + + Mopidy HTTP frontend + + + + +
+

Mopidy HTTP frontend

+ +

This web server is a part of the music server Mopidy. To learn more + about Mopidy, please visit www.mopidy.com.

+
+ +
+

WebSocket endpoint

+ +

Mopidy has a WebSocket endpoint at /mopidy/ws/. You can use + this end point to access Mopidy's full API, and to get notified about + events happening in Mopidy.

+
+ +
+

Example

+ +

Here you can see events arriving from Mopidy in real time:

+ +

+
+      

Nothing to see? Try playing a track using your MPD client.

+
+ +
+

Documentation

+ +

For more information, please refer to the Mopidy documentation at + docs.mopidy.com.

+
+ + + + From df6df5b46aac128d2ac24ed40a373a0936c8439c Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Wed, 28 Nov 2012 19:35:17 +0100 Subject: [PATCH 40/47] http: Minor HTML/CSS tweaks --- mopidy/frontends/http/data/index.html | 2 +- mopidy/frontends/http/data/mopidy.css | 4 ++++ mopidy/frontends/http/data/mopidy.html | 8 +------- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/mopidy/frontends/http/data/index.html b/mopidy/frontends/http/data/index.html index 37885eef..85d3d331 100644 --- a/mopidy/frontends/http/data/index.html +++ b/mopidy/frontends/http/data/index.html @@ -3,7 +3,7 @@ Mopidy HTTP frontend - +
diff --git a/mopidy/frontends/http/data/mopidy.css b/mopidy/frontends/http/data/mopidy.css index 7944a53a..c5042769 100644 --- a/mopidy/frontends/http/data/mopidy.css +++ b/mopidy/frontends/http/data/mopidy.css @@ -69,3 +69,7 @@ code, pre { .center { text-align: center; } +#ws-console { + height: 200px; + overflow: auto; +} diff --git a/mopidy/frontends/http/data/mopidy.html b/mopidy/frontends/http/data/mopidy.html index 81fe445a..64501830 100644 --- a/mopidy/frontends/http/data/mopidy.html +++ b/mopidy/frontends/http/data/mopidy.html @@ -3,13 +3,7 @@ Mopidy HTTP frontend - - +
From bc151b32a76e7b52d6ffb6120ac04bd9455b7bcb Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Wed, 28 Nov 2012 19:42:34 +0100 Subject: [PATCH 41/47] http: Rewrite example to avoid jQuery use --- mopidy/frontends/http/data/jquery-1.8.3.min.js | 2 -- mopidy/frontends/http/data/mopidy.html | 15 +++++++-------- 2 files changed, 7 insertions(+), 10 deletions(-) delete mode 100644 mopidy/frontends/http/data/jquery-1.8.3.min.js diff --git a/mopidy/frontends/http/data/jquery-1.8.3.min.js b/mopidy/frontends/http/data/jquery-1.8.3.min.js deleted file mode 100644 index 83589daa..00000000 --- a/mopidy/frontends/http/data/jquery-1.8.3.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v1.8.3 jquery.com | jquery.org/license */ -(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/mopidy/frontends/http/data/mopidy.html b/mopidy/frontends/http/data/mopidy.html index 64501830..c756cd6c 100644 --- a/mopidy/frontends/http/data/mopidy.html +++ b/mopidy/frontends/http/data/mopidy.html @@ -38,15 +38,14 @@

For more information, please refer to the Mopidy documentation at docs.mopidy.com.

- From 0423d5289b0134f42d1b4c1cadc8be1d4ef95efe Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 30 Nov 2012 18:26:25 +0100 Subject: [PATCH 42/47] http: Mark security and API stability sections as warnings --- mopidy/frontends/http/__init__.py | 40 +++++++++++++++++-------------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index fd1d2b01..44096f6f 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -20,14 +20,16 @@ Frontend which lets you control Mopidy through HTTP and WebSockets. When this frontend is included in :attr:`mopidy.settings.FRONTENDS`, it starts a web server at the port specified by :attr:`mopidy.settings.HTTP_SERVER_PORT`. -As a simple security measure, the web server is by default only available from -localhost. To make it available from other computers, change -:attr:`mopidy.settings.HTTP_SERVER_HOSTNAME`. Before you do so, note that the -HTTP frontend does not feature any form of user authentication or -authorization. Anyone able to access the web server can use the full core API -of Mopidy. Thus, you probably only want to make the web server available from -your local network or place it behind a web proxy which takes care or user -authentication. You have been warned. +.. warning:: Security + + As a simple security measure, the web server is by default only available + from localhost. To make it available from other computers, change + :attr:`mopidy.settings.HTTP_SERVER_HOSTNAME`. Before you do so, note that + the HTTP frontend does not feature any form of user authentication or + authorization. Anyone able to access the web server can use the full core + API of Mopidy. Thus, you probably only want to make the web server + available from your local network or place it behind a web proxy which + takes care or user authentication. You have been warned. This web server exposes a WebSocket at ``/mopidy/ws/``. The WebSocket gives you access to Mopidy's full API and enables Mopidy to instantly push events to the @@ -40,6 +42,18 @@ directory you want to serve. **WebSocket API** +.. warning:: API stability + + Since this frontend exposes our internal core API directly it is to be + regarded as **experimental**. We cannot promise to keep any form of + backwards compatibility between releases as we will need to change the core + API while working out how to support new use cases. Thus, if you use this + API, you must expect to do small adjustments to your client for every + release of Mopidy. + + From Mopidy 1.0 and onwards, we intend to keep the core API far more + stable. + On the WebSocket we send two different kind of messages: The client can send JSON-RPC 2.0 requests, and the server will respond with JSON-RPC 2.0 responses. In addition, the server will send event messages when something happens on the @@ -84,16 +98,6 @@ look at the ``core.describe`` response can be helpful. A JavaScript library wrapping the JSON-RPC over WebSocket API is under development. Details on it will appear here when it's released. - -**API stability** - -Since this frontend exposes our internal core API directly it is to be regarded -as **experimental**. We cannot promise to keep any form of backwards -compatibility between releases as we will need to change the core API while -working out how to support new use cases. Thus, if you use this API, you must -expect to do small adjustments to your client for every release of Mopidy. - -From Mopidy 1.0 and onwards, we intend to keep the core API far more stable. """ # flake8: noqa From 90859c903b4ff5b268e5bd177de98065f6799ccb Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 30 Nov 2012 21:57:12 +0100 Subject: [PATCH 43/47] http: Add favicon --- mopidy/frontends/http/actor.py | 5 +++++ mopidy/frontends/http/data/favicon.png | Bin 0 -> 5997 bytes 2 files changed, 5 insertions(+) create mode 100644 mopidy/frontends/http/data/favicon.png diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index 65cf9445..ef6808f0 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -55,6 +55,7 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): logger.debug('HTTP server will serve "%s" at /', static_dir) mopidy_dir = os.path.join(os.path.dirname(__file__), 'data') + favicon = os.path.join(mopidy_dir, 'favicon.png') config = { b'/': { @@ -62,6 +63,10 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): 'tools.staticdir.index': 'index.html', 'tools.staticdir.dir': static_dir, }, + b'/favicon.ico': { + 'tools.staticfile.on': True, + 'tools.staticfile.filename': favicon, + }, b'/mopidy': { 'tools.staticdir.on': True, 'tools.staticdir.index': 'mopidy.html', diff --git a/mopidy/frontends/http/data/favicon.png b/mopidy/frontends/http/data/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..a214c91fb4fa045dfbb5ea7d5414eda99d6d4dbe GIT binary patch literal 5997 zcmb7Ii9gf-AOCE~(l8n((nL|YBXS?P%~i?Gay3`Tk#h^Vk0NB1G?|c94@G8hjJ}8?Ynb zvrQ9A1z$&Qni^gK4*$Cgn@Y05nWF(lc6R{a*zx}c1Ry>|fs^dP#u$C}(PJXW3l~4U zTP1>1g2DQ>!Fsp-{5<@F0lgp(Y_NwrIt&+l3vFnOvAl7QO8@})2aK=iT)R8G^lbO` zNEct{#41@bxk2hn;p3eT;ohDI&$>l=Ug zg2lsdw6y8&WrG^AJA`}gLT@uxyv8HfXYT@5jWo`&YVO5`<*wc|M35M;obabjvo=xy zs~u)^7kT#s2cQgVdl^SqChXk0vVF+UuQ@7l0vc@iSweU0&?#VpZW+dsdHfipLF{+- zJ@fEP9U$t59}oaNX`#y6&+1T9xPt_~J9|M9J8xAAc5Dj8R>CyV6h_0XK6K&P;0-;a zs3U+aF!{mo=Rb|9bbofh43Gn~x$BNT4u-utD#HB8RtO=CjgRv`*ND6{=3jfKtc(nA zOTwlJj?_5idTf@KmTv9uM>W|>g?^o>bd=)H5v_{LB&YHKwF1!7u6sjGO--YR2iwin zG#V|(`HgZ>nfI_FhRZEYC4-Siorw!=WJW|sGo#Pv#NK@OC!QQ1V+o@$%)cQ6v!u1Z zv%O6rC1r`{oJjBRZXA>0JQ9~iVSHdT#G_%+xgPWL^EeMV)E_dgtUxV558=oGkIq{^ z6DKDRz>W7DgCG>fS$JF5t1{v#_>rqk&a%Y})kJxN4Epy5ibXxe0SzPZrM44+!h~-c z9Bc`50a0Jjmd92161xGFw7}NN*L7HwywhO#NX=2O)Z}gw$;Erj7^_^5(uoyQXSqKK zjw$mR+!j1zg+4o3u5}k^+C*{VTr^mjs5JQ*m7Z{s7DY@YZQgxrYm47DH)M8p_R-9Y zhqOp0d$!Rh$JnKi#ZRkNTdSt`u-1?r7&J@VIE4gDAt5j{Z3HWqHi6jfIVzWSIUez? zyL)qPZm!xeQv_n1HKiWAYzMvYNQJ|T`$yj7>9c|aQv`xlhxgP8T^K}H5~W4J5#1Zd z_{}XWj>)=wbbKMnv9z*M@^$9#+Txu{%2YuV4=|0hIy4gLK?ek^w^ z=Z%uAKt$aLwDqL};SP$ztNH6l97F>Jx0aBQNcOHiUo+xoW%Wp3|_w@2|NWMZc zw0iVgr!W$Y3V3L6a1IqU7(hplvH=NKd14`=!RG=lVzPa!?T^NyVHn!YbOX1A=0oO+ z_t|XRY*4+;J6m5cAxal=Ov-JgwxH<8qT8;C1Xu&CZXR{7!H0w|I|BgUL!POsshKLC z;G9|-sl9(!or1w&j4xiin7+HaOWWMs6iZu6mQ1-`Fvl*!8qsy075mnJ5FjGutjrqr z6B=)bU;VL7%b=q>1C83`jDSK9yV>j4XF{9=f}JeN%7_&M-WS!>)VgoJ`?clRhUQP* z461*suBJ9Z4|hH}b#{M}=YCb{;87jcmR{c!(%Wi#=`qIU@5IDJHXVeG+q=hEM&f%U z$8t@AJCie|j@0bhKag*~z>&ZaPizL!MOPo)d`t?`Mvr?P#&HDO!&li?|tdUBquCU(I`^bwN+5yt?kPt(* zFgzDZi%;P(*?737+bzu)j2F}Vyv(MYrnSGScjlRS?VWnZ=!l3t-#d5KSD)Pec$r_{ zYAeg+yyK!q-9t{vhip4(FXGF}(y*xDs-ZL%?R!|1TD}<$=9^zC2mQFcC)obLEDS~x`vHAH_%+6Gyb*ZqlwDhwas>dk+1^_yy2s^@B zFLd@;vajev(R(Yg{BCJ`OwHRPp)bb#QyUu_i`(1V|Ni{>lj>O|s0Vvt zU5XUm)w|k7uY~ddfOeL666scVPtQUFMGSCNd&cEv$3LaQ)rt}u43T9^ZEH=!>WKZ9 z@t0UsRPD%&Pc`usL)Fv@2{K1&`%~*u_m)lvS~MWMf=_Sfy8_(hM?W-rJQGwe0gH`U z8P|9qo~)^%!PnE%6K`J9b}mI1e>PRSpRp;WdkbTQd`X0Y5syaRo@jo%kco?VyO^1}km-fcei0CVG|jzJ`p8 z)WQ8q_BT@2Hd-mVL%{84dwX0>eu+JK!(aGU&+o2Mr%Tj(>Gm zNXe5TLF@0m>xL~aN}=~7sg-ZBs9X?$v8W)hct0|?M(odKU;b~?jLitLO}R(;fcHn| zH(pP=J>_*EhGe?Zm@PkLnnJEIAJTiVIacV;xjNj;*? zz0`Hcl}k^Sv|{#c_m*zsBh3)376{fG6*e?57rSF)WAn|hrGYUnBlmv!))Jx72-9PuS? zSj+V*6p%62+3aRe?eKsYL%&_IL#;{S} zOY7a9RRO`livNDMrxxeQy7VYL>5j*urjznp6IaJWjAaXjL-X0v#6*!0#Ew5RSr^SR zC*ko;J5=Vbf%dje*W9{^=JPz|OPB0{fHIu@!aS|yn7A>KNPdXauU`svK*5jb(Z0b% z^Tdt6RZ5X1zc!us;;|#h&#{B5hFvQPwJ$s2(jwoq@_lu*bvIY8U@qOHIF>yQl0-!h+DZGFQm&Pi-fOWOn-1k*{{~0BxeMEo>w+F426E&{+3g zQ1MB31D?rnsnBB1Ta5k3JO(8+o)hT_u6F!byPx&p+Xl_~CdH51+x72z*a_)&_M8U% zd!)5t@sr^?6S@yXO{V~WEXe@@K2=IpRaOSsNFs-ad@p&~@ei$R3*Meb8D$0EB3{zB z>Q`S&^cTwn>OTE){d@;z*4s)z+|#xSbh`1yv#M`nBlyPk>zC^4uF&4MSH8|QFZmbn z&Q7rssQq;!N-_HwvtTuTBMd486OAL|a_B1Q;>LJ}zytC5&-67NDSpNo-lKe)Lm%_>m)z1SZrk7m>h z)*;5`W1I4vTeTzSXo`XWkU{SUnJoKuGjprE$S{+uYUs5BlpqQF&>kLFPANVEAw>P# zs#x9MU3aV+GAk|n$^v}8DSsx9Ixsgoo6)>G`=rRabox1(qXTez1~mYp#vf|+L-)ZG zM?IX=I<$*C*bgsuej^~)A>O-gQtvoke(n65yu3Va(_(9O85ebIo08L2A&8tN>;aDW znO0)44kB-Tjaj)hG$?NMD0f`YP(w4ko)t&IRd3DZW#5s~^KmowBn z>}sC%&bd&)<@_2Rj@Smbw+qu;RO$2g-Y^8xjH7^n4{ajP*uh{k;U5jN#G4u#?3sIv zH|5~WEt=xV4>q2Ucl?9Z_o=*Eb&~EZz#4OVBFxLvvj&8-t;-o=KL-aZd@l)o5Ox2> z>E`zQpCJ&{^NL&aFiXNE3NPIP1!}EJCrye;pY(qYxae}Zh=f#-|68d|i@=Vx94xQ* zkPfhZ>J&PMISyG3uh6#Kn7qa9zYG_F9R6vY|C9SxRwy<=odEU6+P2)K&&;0&Iv8Az zJM*V=0Tp}8C=AaZ+%Rqf08!U@HFJ2UY^Dy&ZmtXgruzvD8 zf)?MGn~I@4J~$bD;F12R70v^%Wg~p&e4_IrSyU{%|CLB6K$BfW#uJjHK1oAdy9UbI zD7I%3l9bDme!pd0W8UO^zb$ACirVRFqb(umh)*AMYF=Ifc8)g=A^LjYK2W|vE*0G*=(D$+43c1axjd~mm^A( z3t&wlp<>ZSv1rn0X9yI*tEIA#Pgqq4RzZ5;=HluDWveu`@)eHgO7#3D2k&9{HcxnA zXfI*0Knlq>0V`E7#|eINJ*sV`$f=}PNDel?h=^fFd;3-ZokZ#i6gJ#_(en1(w9|Wd zzf#hvw4S3YN^z~7fHpwb`M14tthYepLUY7snPd4t%9y`0jj_pFR@MP;o0OuG#`(C21sasef`P!j_i_loH z34!P9@tNEIqSu)Jw(m2U%=x&uxO&iu_8lC=lsdn$2vI!=x;PyxWKVgi+MYflh`v@= z@WuU+d5M@{!b4?DRd=QD9UmW4t;?6c*yZxE17FLVQw{b{Awf)_tqlH1g=qgCD8JE; zKUjaB1IC>xDk^G^XwsCX21UrBKJ)2MUBB+3gej7up4Ob%MCwmD4xW*w{sztC!t}KJ z?BrzO_6q*c0W>)pphdCE)n@@t*nGZR3D9v@x;E|4ds8X8Qo9~O4yjYcU2~C zDJmpjdYH@Kfs=BEu z8V_DCK*5Kh2~#6Kp^9RfExd^a5w)SBBQ^N>6gPKBj6Pt*0+g3|N8$0!8=!d0q0{L> zjbrBQ?akhg@MRNQhlyT1EtOL4c0Vohch>(MBwj;2|7GA9#|CQv38Oa(G=Z4bv6Qul1iyg`3`0O6dqjyBIsyr0792b z_m4ee%ZzjkCOcN3H>tu^!H6)kdi0pWF#GiypD{ml{ZQ=B%~;BPG%OK|iu16GBfSb3 z`q;>J{mYMM$$l~LA*HCaXe)N`PNu4-r)o>Y;s zZ4UcA1_W~Qqis#P$+%%7ao(nD=Laz2yu{~QochzxFE*UQ9pH$eDeX7C0t46X`ui^{ z=21hYf*^A~vh=NX7KFmXx%7&T;ne=L3Y2Bd3Yji{Y~$mr;q%gdj3I{}o%$n`OP+CX&ybG3EuUo#;(}*xF8}=-q{N@fnE)U#Ecp97lI{?=4&qUFcX!9| zF!4@Q)YGw%ktbHj`zxW1Br-1TxgdOQ9dG_u!j}`O)%eBT`dl7W0$j`JI7pVvoi%!` zOZ4V|Ah0n>O4+U!2rQ5UbZ4%`=@icIf0J$SZQ%D?inI0=HZ_Bcc4j)d zIk>$i@g7N1IJNyX*jebL2P!=@+5j!qo$&D8G0<*4nb@CIX7};&kpR$bi3-bM-W!=p z=Z+&}>sAi?LgkFJ`ap%>zO=M-f3ElW#J{!9Q+XMgnO@%2!;i#`12MG6F7mZu$CKj= zs58@Go6Dx&QPaV}LCqE%QaL6AzL!SMBRMME6^7zc6_yj`%4FCG*{XY;3s3{(^_nJG zK?v}YhEslK?f~xZdLBtK2b~1z46H=MoQ$&+%E~xEEXkl-I=8~ucn#--RQ3ngm6Q7v z{npgqbkf&iWb%A^ySuO7u(27(A2PSKG-LL6`h}KK1_xTYYM1-|G-sgY9&>Jt5oE`U zfj~Dmw@ivBx+&eB<1^5Ny4cLzgsGd^ zl5-)Nt522SaTSA%H4t&Z#Nc#uJ)8$ae%APXt?_FO6rNV$3UU%K%6bnrGw?AnA05u; zL{Oz2LsEBwBRPlZ5vJ;P=o`CX%qY+b8$+NMQ9o z^00eJ#vyfKAnQh)799+68mYM_Zk$M0QR7b?g17yG+)E7cieC*g+4o^{Wo0cghh?v> z>2psVJM}&3wHVjq^}_GiA1m)ym7&_OSS&jJRN@$C03R?_^c(xGjbyQ?uu{S18m|PP zqK|i#jQ_jnyBpqrq*qOLKbbV&%hX?GeHSSJc*l<_xnztiZ5! qA{5YsB$bahs+|`T{G#5#JXL!B^k3gTJ3QD02aNU2uTXSdWB&*Elu9%J literal 0 HcmV?d00001 From 6238f55ae20a29fea8cf99af05332ab3c2166bc2 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 30 Nov 2012 22:39:34 +0100 Subject: [PATCH 44/47] core: Add CoreListener.on_event() The `on_event()` method is called on all events. By default, it forwards the event to the specific event handler methods. It's also a convenient method to override if you want to handle all events in one place. --- mopidy/core/listener.py | 15 ++++++++++++++- tests/core/listener_test.py | 11 +++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/mopidy/core/listener.py b/mopidy/core/listener.py index dc8bf1d7..7c4ab093 100644 --- a/mopidy/core/listener.py +++ b/mopidy/core/listener.py @@ -19,7 +19,20 @@ class CoreListener(object): """Helper to allow calling of core listener events""" listeners = pykka.ActorRegistry.get_by_class(CoreListener) for listener in listeners: - getattr(listener.proxy(), event)(**kwargs) + listener.proxy().on_event(event, **kwargs) + + def on_event(self, event, **kwargs): + """ + Called on all events. + + *MAY* be implemented by actor. By default, this method forwards the + event to the specific event methods. + + :param event: the event name + :type event: string + :param kwargs: any other arguments to the specific event handlers + """ + getattr(self, event)(**kwargs) def track_playback_paused(self, track, time_position): """ diff --git a/tests/core/listener_test.py b/tests/core/listener_test.py index 2e121796..8aaf1234 100644 --- a/tests/core/listener_test.py +++ b/tests/core/listener_test.py @@ -1,5 +1,7 @@ from __future__ import unicode_literals +import mock + from mopidy.core import CoreListener, PlaybackState from mopidy.models import Playlist, Track @@ -10,6 +12,15 @@ class CoreListenerTest(unittest.TestCase): def setUp(self): self.listener = CoreListener() + def test_on_event_forwards_to_specific_handler(self): + self.listener.track_playback_paused = mock.Mock() + + self.listener.on_event( + 'track_playback_paused', track=Track(), position=0) + + self.listener.track_playback_paused.assert_called_with( + track=Track(), position=0) + def test_listener_has_default_impl_for_track_playback_paused(self): self.listener.track_playback_paused(Track(), 0) From 2edc884e76fcb7a4bd7d46f73aee96c9c86da16f Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 30 Nov 2012 22:41:13 +0100 Subject: [PATCH 45/47] http: Override CoreListener.on_event() instead of the specific event handlers --- mopidy/frontends/http/actor.py | 35 +---------- tests/frontends/http/events_test.py | 94 +---------------------------- 2 files changed, 3 insertions(+), 126 deletions(-) diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index ef6808f0..34f39a4c 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -98,40 +98,7 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): cherrypy.engine.exit() logger.info('Stopped HTTP server') - def track_playback_paused(self, **data): - self._broadcast_event('track_playback_paused', data) - - def track_playback_resumed(self, **data): - self._broadcast_event('track_playback_resumed', data) - - def track_playback_started(self, **data): - self._broadcast_event('track_playback_started', data) - - def track_playback_ended(self, **data): - self._broadcast_event('track_playback_ended', data) - - def playback_state_changed(self, **data): - self._broadcast_event('playback_state_changed', data) - - def tracklist_changed(self, **data): - self._broadcast_event('tracklist_changed', data) - - def playlists_loaded(self, **data): - self._broadcast_event('playlists_loaded', data) - - def playlist_changed(self, **data): - self._broadcast_event('playlist_changed', data) - - def options_changed(self, **data): - self._broadcast_event('options_changed', data) - - def volume_changed(self, **data): - self._broadcast_event('volume_changed', data) - - def seeked(self, **data): - self._broadcast_event('seeked', data) - - def _broadcast_event(self, name, data): + def on_event(self, name, **data): event = {} event.update(data) event['event'] = name diff --git a/tests/frontends/http/events_test.py b/tests/frontends/http/events_test.py index 9df4a2b5..d04eb93e 100644 --- a/tests/frontends/http/events_test.py +++ b/tests/frontends/http/events_test.py @@ -15,7 +15,7 @@ class HttpEventsTest(unittest.TestCase): def test_track_playback_paused_is_broadcasted(self, publish): publish.reset_mock() - self.http.track_playback_paused(foo='bar') + self.http.on_event('track_playback_paused', foo='bar') self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') self.assertDictEqual( json.loads(str(publish.call_args[0][1])), { @@ -25,100 +25,10 @@ class HttpEventsTest(unittest.TestCase): def test_track_playback_resumed_is_broadcasted(self, publish): publish.reset_mock() - self.http.track_playback_resumed(foo='bar') + self.http.on_event('track_playback_resumed', foo='bar') self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') self.assertDictEqual( json.loads(str(publish.call_args[0][1])), { 'event': 'track_playback_resumed', 'foo': 'bar', }) - - def test_track_playback_started_is_broadcasted(self, publish): - publish.reset_mock() - self.http.track_playback_started(foo='bar') - self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') - self.assertDictEqual( - json.loads(str(publish.call_args[0][1])), { - 'event': 'track_playback_started', - 'foo': 'bar', - }) - - def test_track_playback_ended_is_broadcasted(self, publish): - publish.reset_mock() - self.http.track_playback_ended(foo='bar') - self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') - self.assertDictEqual( - json.loads(str(publish.call_args[0][1])), { - 'event': 'track_playback_ended', - 'foo': 'bar', - }) - - def test_playback_state_changed_is_broadcasted(self, publish): - publish.reset_mock() - self.http.playback_state_changed(foo='bar') - self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') - self.assertDictEqual( - json.loads(str(publish.call_args[0][1])), { - 'event': 'playback_state_changed', - 'foo': 'bar', - }) - - def test_tracklist_changed_is_broadcasted(self, publish): - publish.reset_mock() - self.http.tracklist_changed(foo='bar') - self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') - self.assertDictEqual( - json.loads(str(publish.call_args[0][1])), { - 'event': 'tracklist_changed', - 'foo': 'bar', - }) - - def test_playlists_loaded_is_broadcasted(self, publish): - publish.reset_mock() - self.http.playlists_loaded(foo='bar') - self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') - self.assertDictEqual( - json.loads(str(publish.call_args[0][1])), { - 'event': 'playlists_loaded', - 'foo': 'bar', - }) - - def test_playlist_changed_is_broadcasted(self, publish): - publish.reset_mock() - self.http.playlist_changed(foo='bar') - self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') - self.assertDictEqual( - json.loads(str(publish.call_args[0][1])), { - 'event': 'playlist_changed', - 'foo': 'bar', - }) - - def test_options_changed_is_broadcasted(self, publish): - publish.reset_mock() - self.http.options_changed(foo='bar') - self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') - self.assertDictEqual( - json.loads(str(publish.call_args[0][1])), { - 'event': 'options_changed', - 'foo': 'bar', - }) - - def test_volume_changed_is_broadcasted(self, publish): - publish.reset_mock() - self.http.volume_changed(foo='bar') - self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') - self.assertDictEqual( - json.loads(str(publish.call_args[0][1])), { - 'event': 'volume_changed', - 'foo': 'bar', - }) - - def test_seeked_is_broadcasted(self, publish): - publish.reset_mock() - self.http.seeked(foo='bar') - self.assertEqual(publish.call_args[0][0], 'websocket-broadcast') - self.assertDictEqual( - json.loads(str(publish.call_args[0][1])), { - 'event': 'seeked', - 'foo': 'bar', - }) From d6a906a723cf045bcb040e556460724dc11e8f98 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 30 Nov 2012 23:15:13 +0100 Subject: [PATCH 46/47] http: No need to copy dict --- mopidy/frontends/http/actor.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/mopidy/frontends/http/actor.py b/mopidy/frontends/http/actor.py index 34f39a4c..8ad0f026 100644 --- a/mopidy/frontends/http/actor.py +++ b/mopidy/frontends/http/actor.py @@ -99,8 +99,7 @@ class HttpFrontend(pykka.ThreadingActor, CoreListener): logger.info('Stopped HTTP server') def on_event(self, name, **data): - event = {} - event.update(data) + event = data event['event'] = name message = json.dumps(event, cls=models.ModelJSONEncoder) cherrypy.engine.publish('websocket-broadcast', TextMessage(message)) From 430d604509e2e45bbc08bd9883901c6b2180c1ec Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 30 Nov 2012 23:50:55 +0100 Subject: [PATCH 47/47] http: Revised the HTTP frontend docs --- mopidy/frontends/http/__init__.py | 48 ++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 10 deletions(-) diff --git a/mopidy/frontends/http/__init__.py b/mopidy/frontends/http/__init__.py index 44096f6f..d98734b2 100644 --- a/mopidy/frontends/http/__init__.py +++ b/mopidy/frontends/http/__init__.py @@ -1,5 +1,6 @@ """ -Frontend which lets you control Mopidy through HTTP and WebSockets. +The HTTP frontends lets you control Mopidy through HTTP and WebSockets, e.g. +from a web based client. **Dependencies** @@ -15,7 +16,9 @@ Frontend which lets you control Mopidy through HTTP and WebSockets. - :attr:`mopidy.settings.HTTP_SERVER_STATIC_DIR` -**Usage** + +Setup +===== When this frontend is included in :attr:`mopidy.settings.FRONTENDS`, it starts a web server at the port specified by :attr:`mopidy.settings.HTTP_SERVER_PORT`. @@ -31,16 +34,28 @@ a web server at the port specified by :attr:`mopidy.settings.HTTP_SERVER_PORT`. available from your local network or place it behind a web proxy which takes care or user authentication. You have been warned. -This web server exposes a WebSocket at ``/mopidy/ws/``. The WebSocket gives you -access to Mopidy's full API and enables Mopidy to instantly push events to the -client, as they happen. + +Using a web based Mopidy client +=============================== The web server can also host any static files, for example the HTML, CSS, -JavaScript and images needed by a web based Mopidy client. To host static +JavaScript, and images needed for a web based Mopidy client. To host static files, change :attr:`mopidy.settings.HTTP_SERVER_STATIC_DIR` to point to the -directory you want to serve. +root directory of your web client, e.g.:: -**WebSocket API** + HTTP_SERVER_STATIC_DIR = u'/home/alice/dev/the-client' + +If the directory includes a file named ``index.html``, it will be served on the +root of Mopidy's web server. + +If you're making a web based client and wants to do server side development as +well, you are of course free to run your own web server and just use Mopidy's +web server for the APIs. But, for clients implemented purely in JavaScript, +letting Mopidy host the files is a simpler solution. + + +WebSocket API +============= .. warning:: API stability @@ -54,11 +69,19 @@ directory you want to serve. From Mopidy 1.0 and onwards, we intend to keep the core API far more stable. +The web server exposes a WebSocket at ``/mopidy/ws/``. The WebSocket gives you +access to Mopidy's full API and enables Mopidy to instantly push events to the +client, as they happen. + On the WebSocket we send two different kind of messages: The client can send JSON-RPC 2.0 requests, and the server will respond with JSON-RPC 2.0 responses. In addition, the server will send event messages when something happens on the server. Both message types are encoded as JSON objects. + +Event messages +-------------- + Event objects will always have a key named ``event`` whose value is the event type. Depending on the event type, the event may include additional fields for related data. The events maps directly to the :class:`mopidy.core.CoreListener` @@ -68,6 +91,10 @@ fields on the event objects. Example event message:: {"event": "track_playback_started", "track": {...}} + +JSON-RPC 2.0 messaging +---------------------- + JSON-RPC 2.0 messages can be recognized by checking for the key named ``jsonrpc`` with the string value ``2.0``. For details on the messaging format, please refer to the `JSON-RPC 2.0 spec @@ -80,7 +107,7 @@ JSON-RPC calls over the WebSocket. For example, The core API's attributes is made available through setters and getters. For example, the attribute :attr:`mopidy.core.PlaybackController.current_track` is -availableas the JSON-RPC method ``core.playback.get_current_track`. +available as the JSON-RPC method ``core.playback.get_current_track``. Example JSON-RPC request:: @@ -94,7 +121,8 @@ The JSON-RPC method ``core.describe`` returns a data structure describing all available methods. If you're unsure how the core API maps to JSON-RPC, having a look at the ``core.describe`` response can be helpful. -**JavaScript wrapper** +JavaScript wrapper +================== A JavaScript library wrapping the JSON-RPC over WebSocket API is under development. Details on it will appear here when it's released.