Mopidy-dLeyna-1.0.5/0000775000175000017500000000000012650344020015320 5ustar tkemmertkemmer00000000000000Mopidy-dLeyna-1.0.5/setup.cfg0000644000175000017500000000023712650344020017141 0ustar tkemmertkemmer00000000000000[flake8] application-import-names = mopidy_dleyna,tests exclude = .git,.tox [wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 Mopidy-dLeyna-1.0.5/README.rst0000664000175000017500000000556512650343661017034 0ustar tkemmertkemmer00000000000000Mopidy-dLeyna ======================================================================== Mopidy-dLeyna is a Mopidy_ extension that lets you play music from DLNA_ Digital Media Servers using the dLeyna_ D-Bus interface. Dependencies ------------------------------------------------------------------------ - D-Bus Python bindings, such as the package ``python-dbus`` in Debian/Ubuntu/Raspbian. - The ``dleyna-server`` package available in Ubuntu 14.04 and Debian "jessie". For other platforms, please see the dLeyna `installation instructions `_. Installation ------------------------------------------------------------------------ Debian/Ubuntu/Raspbian: Install the ``mopidy-dleyna`` package from `apt.mopidy.com `_:: sudo apt-get install mopidy-dleyna Otherwise, install the dependencies listed above, and then install the package from PyPI_:: pip install Mopidy-dLeyna Configuration ------------------------------------------------------------------------ The following configuration values are provided: - ``dleyna/enabled``: Whether this extension should be enabled or not. Defaults to ``true`` - ``dleyna/upnp_browse_limit``: The maximum number of objects to retrieve per UPnP `Browse` action, or ``0`` to retrieve all objects. Defaults to ``1000``. - ``dleyna/upnp_search_limit``: The maximum number of objects to retrieve per UPnP `Search` action, or ``0`` to retrieve all objects. Defaults to ``0``. Project resources ------------------------------------------------------------------------ .. image:: https://img.shields.io/pypi/v/Mopidy-dLeyna.svg?style=flat :target: https://pypi.python.org/pypi/Mopidy-dLeyna/ :alt: Latest PyPI version .. image:: https://img.shields.io/pypi/dm/Mopidy-dLeyna.svg?style=flat :target: https://pypi.python.org/pypi/Mopidy-dLeyna/ :alt: Number of PyPI downloads .. image:: https://img.shields.io/travis/tkem/mopidy-dleyna/master.svg?style=flat :target: https://travis-ci.org/tkem/mopidy-dleyna :alt: Travis CI build status .. image:: https://img.shields.io/coveralls/tkem/mopidy-dleyna/master.svg?style=flat :target: https://coveralls.io/r/tkem/mopidy-dleyna?branch=master :alt: Test coverage - `Issue Tracker`_ - `Source Code`_ - `Change Log`_ License ------------------------------------------------------------------------ Copyright (c) 2015, 2016 Thomas Kemmer. Licensed under the `Apache License, Version 2.0`_. .. _Mopidy: http://www.mopidy.com/ .. _DLNA: http://www.dlna.org/ .. _dLeyna: http://01.org/dleyna .. _PyPI: https://pypi.python.org/pypi/Mopidy-dLeyna/ .. _Issue Tracker: https://github.com/tkem/mopidy-dleyna/issues/ .. _Source Code: https://github.com/tkem/mopidy-dleyna/ .. _Change Log: https://github.com/tkem/mopidy-dleyna/blob/master/CHANGES.rst .. _Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 Mopidy-dLeyna-1.0.5/Mopidy_dLeyna.egg-info/0000775000175000017500000000000012650344020021547 5ustar tkemmertkemmer00000000000000Mopidy-dLeyna-1.0.5/Mopidy_dLeyna.egg-info/dependency_links.txt0000644000175000017500000000000112650344020025613 0ustar tkemmertkemmer00000000000000 Mopidy-dLeyna-1.0.5/Mopidy_dLeyna.egg-info/entry_points.txt0000644000175000017500000000005712650344020025045 0ustar tkemmertkemmer00000000000000[mopidy.ext] dleyna = mopidy_dleyna:Extension Mopidy-dLeyna-1.0.5/Mopidy_dLeyna.egg-info/SOURCES.txt0000644000175000017500000000111512650344020023427 0ustar tkemmertkemmer00000000000000.coveragerc .travis.yml CHANGES.rst LICENSE MANIFEST.in README.rst setup.cfg setup.py Mopidy_dLeyna.egg-info/PKG-INFO Mopidy_dLeyna.egg-info/SOURCES.txt Mopidy_dLeyna.egg-info/dependency_links.txt Mopidy_dLeyna.egg-info/entry_points.txt Mopidy_dLeyna.egg-info/not-zip-safe Mopidy_dLeyna.egg-info/requires.txt Mopidy_dLeyna.egg-info/top_level.txt mopidy_dleyna/__init__.py mopidy_dleyna/backend.py mopidy_dleyna/client.py mopidy_dleyna/ext.conf mopidy_dleyna/library.py mopidy_dleyna/playback.py mopidy_dleyna/translator.py tests/__init__.py tests/test_extension.py tests/test_translator.pyMopidy-dLeyna-1.0.5/Mopidy_dLeyna.egg-info/requires.txt0000644000175000017500000000006612650344020024147 0ustar tkemmertkemmer00000000000000setuptools Mopidy >= 1.0 Pykka >= 1.2 uritools >= 1.0 Mopidy-dLeyna-1.0.5/Mopidy_dLeyna.egg-info/not-zip-safe0000644000175000017500000000000112611671143024001 0ustar tkemmertkemmer00000000000000 Mopidy-dLeyna-1.0.5/Mopidy_dLeyna.egg-info/top_level.txt0000644000175000017500000000001612650344020024274 0ustar tkemmertkemmer00000000000000mopidy_dleyna Mopidy-dLeyna-1.0.5/Mopidy_dLeyna.egg-info/PKG-INFO0000644000175000017500000001027312650344020022645 0ustar tkemmertkemmer00000000000000Metadata-Version: 1.1 Name: Mopidy-dLeyna Version: 1.0.5 Summary: Mopidy extension for playing music from Digital Media Servers Home-page: https://github.com/tkem/mopidy-dleyna Author: Thomas Kemmer Author-email: tkemmer@computer.org License: Apache License, Version 2.0 Description: Mopidy-dLeyna ======================================================================== Mopidy-dLeyna is a Mopidy_ extension that lets you play music from DLNA_ Digital Media Servers using the dLeyna_ D-Bus interface. Dependencies ------------------------------------------------------------------------ - D-Bus Python bindings, such as the package ``python-dbus`` in Debian/Ubuntu/Raspbian. - The ``dleyna-server`` package available in Ubuntu 14.04 and Debian "jessie". For other platforms, please see the dLeyna `installation instructions `_. Installation ------------------------------------------------------------------------ Debian/Ubuntu/Raspbian: Install the ``mopidy-dleyna`` package from `apt.mopidy.com `_:: sudo apt-get install mopidy-dleyna Otherwise, install the dependencies listed above, and then install the package from PyPI_:: pip install Mopidy-dLeyna Configuration ------------------------------------------------------------------------ The following configuration values are provided: - ``dleyna/enabled``: Whether this extension should be enabled or not. Defaults to ``true`` - ``dleyna/upnp_browse_limit``: The maximum number of objects to retrieve per UPnP `Browse` action, or ``0`` to retrieve all objects. Defaults to ``1000``. - ``dleyna/upnp_search_limit``: The maximum number of objects to retrieve per UPnP `Search` action, or ``0`` to retrieve all objects. Defaults to ``0``. Project resources ------------------------------------------------------------------------ .. image:: https://img.shields.io/pypi/v/Mopidy-dLeyna.svg?style=flat :target: https://pypi.python.org/pypi/Mopidy-dLeyna/ :alt: Latest PyPI version .. image:: https://img.shields.io/pypi/dm/Mopidy-dLeyna.svg?style=flat :target: https://pypi.python.org/pypi/Mopidy-dLeyna/ :alt: Number of PyPI downloads .. image:: https://img.shields.io/travis/tkem/mopidy-dleyna/master.svg?style=flat :target: https://travis-ci.org/tkem/mopidy-dleyna :alt: Travis CI build status .. image:: https://img.shields.io/coveralls/tkem/mopidy-dleyna/master.svg?style=flat :target: https://coveralls.io/r/tkem/mopidy-dleyna?branch=master :alt: Test coverage - `Issue Tracker`_ - `Source Code`_ - `Change Log`_ License ------------------------------------------------------------------------ Copyright (c) 2015, 2016 Thomas Kemmer. Licensed under the `Apache License, Version 2.0`_. .. _Mopidy: http://www.mopidy.com/ .. _DLNA: http://www.dlna.org/ .. _dLeyna: http://01.org/dleyna .. _PyPI: https://pypi.python.org/pypi/Mopidy-dLeyna/ .. _Issue Tracker: https://github.com/tkem/mopidy-dleyna/issues/ .. _Source Code: https://github.com/tkem/mopidy-dleyna/ .. _Change Log: https://github.com/tkem/mopidy-dleyna/blob/master/CHANGES.rst .. _Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 Platform: UNKNOWN Classifier: Environment :: No Input/Output (Daemon) Classifier: Intended Audience :: End Users/Desktop Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Topic :: Multimedia :: Sound/Audio :: Players Mopidy-dLeyna-1.0.5/.travis.yml0000664000175000017500000000046312644172132017442 0ustar tkemmertkemmer00000000000000sudo: false language: python python: - "2.7_with_system_site_packages" addons: apt: packages: - python-dbus env: - TOX_ENV=py27 - TOX_ENV=flake8 install: - "pip install tox" script: - "tox -e $TOX_ENV" after_success: - "if [ $TOX_ENV == 'py27' ]; then pip install coveralls; coveralls; fi" Mopidy-dLeyna-1.0.5/MANIFEST.in0000644000175000017500000000026012611670762017066 0ustar tkemmertkemmer00000000000000include .coveragerc include .travis.yml include CHANGES.rst include LICENSE include MANIFEST.in include README.rst include mopidy_dleyna/ext.conf recursive-include tests *.py Mopidy-dLeyna-1.0.5/.coveragerc0000644000175000017500000000003512611670762017451 0ustar tkemmertkemmer00000000000000[run] source = mopidy_dleyna Mopidy-dLeyna-1.0.5/setup.py0000644000175000017500000000247512611670762017054 0ustar tkemmertkemmer00000000000000from __future__ import unicode_literals import re from setuptools import find_packages, setup def get_version(filename): content = open(filename).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content)) return metadata['version'] setup( name='Mopidy-dLeyna', version=get_version('mopidy_dleyna/__init__.py'), url='https://github.com/tkem/mopidy-dleyna', license='Apache License, Version 2.0', author='Thomas Kemmer', author_email='tkemmer@computer.org', description=( 'Mopidy extension for playing music from Digital Media Servers' ), long_description=open('README.rst').read(), packages=find_packages(exclude=['tests', 'tests.*']), zip_safe=False, include_package_data=True, install_requires=[ 'setuptools', 'Mopidy >= 1.0', 'Pykka >= 1.2', 'uritools >= 1.0' ], entry_points={ 'mopidy.ext': [ 'dleyna = mopidy_dleyna:Extension', ], }, classifiers=[ 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Topic :: Multimedia :: Sound/Audio :: Players', ], ) Mopidy-dLeyna-1.0.5/mopidy_dleyna/0000775000175000017500000000000012650344020020155 5ustar tkemmertkemmer00000000000000Mopidy-dLeyna-1.0.5/mopidy_dleyna/backend.py0000664000175000017500000000407712650343661022140 0ustar tkemmertkemmer00000000000000from __future__ import absolute_import, unicode_literals import errno import logging import os import signal import subprocess from mopidy import backend, exceptions import pykka from . import Extension from .client import dLeynaClient from .library import dLeynaLibraryProvider from .playback import dLeynaPlaybackProvider DBUS_SESSION_BUS_ADDRESS = 'DBUS_SESSION_BUS_ADDRESS' DBUS_SESSION_BUS_PID = 'DBUS_SESSION_BUS_PID' logger = logging.getLogger(__name__) class dLeynaBackend(pykka.ThreadingActor, backend.Backend): uri_schemes = [Extension.ext_name] __dbus_pid = None def __init__(self, config, audio): super(dLeynaBackend, self).__init__() try: if DBUS_SESSION_BUS_ADDRESS in os.environ: self.dleyna = dLeynaClient() else: env = self.__start_dbus() self.__dbus_pid = int(env[DBUS_SESSION_BUS_PID]) self.dleyna = dLeynaClient(str(env[DBUS_SESSION_BUS_ADDRESS])) except Exception as e: logger.error('Error starting %s: %s', Extension.dist_name, e) # TODO: clean way to bail out late? raise exceptions.ExtensionError('Error starting dLeyna client') self.library = dLeynaLibraryProvider(self, config[Extension.ext_name]) self.playback = dLeynaPlaybackProvider(audio, self) def on_stop(self): if self.__dbus_pid is not None: self.__stop_dbus(self.__dbus_pid) def __start_dbus(self): logger.info('Starting %s D-Bus daemon', Extension.dist_name) out = subprocess.check_output(['dbus-launch'], universal_newlines=True) logger.debug('%s D-Bus environment:\n%s', Extension.dist_name, out) return dict(line.split('=', 1) for line in out.splitlines()) def __stop_dbus(self, pid): logger.info('Stopping %s D-Bus daemon', Extension.dist_name) try: os.kill(pid, signal.SIGTERM) except OSError as e: if e.errno != errno.ESRCH: raise logger.debug('Stopped %s D-Bus daemon', Extension.dist_name) Mopidy-dLeyna-1.0.5/mopidy_dleyna/client.py0000664000175000017500000002042312650343661022020 0ustar tkemmertkemmer00000000000000from __future__ import absolute_import, unicode_literals import collections import logging import threading import time import dbus import pykka import uritools from . import translator SERVER_BUS_NAME = 'com.intel.dleyna-server' SERVER_ROOT_PATH = '/com/intel/dLeynaServer' SERVER_MANAGER_IFACE = 'com.intel.dLeynaServer.Manager' logger = logging.getLogger(__name__) class dLeynaFuture(pykka.ThreadingFuture): def apply(self, func): # similar to map(), but always works on single value future = self.__class__() future.set_get_hook(lambda timeout: func(self.get(timeout))) return future @classmethod def fromdbus(cls, func, *args, **kwargs): method = getattr(func, '_method_name', '') logger.debug('Calling D-Bus method %s%s', method, args) future = cls() start = time.time() def reply(*args): logger.debug('%s reply after %.3fs', method, time.time() - start) future.set(args[0] if len(args) == 1 else args) def error(e): logger.debug('%s error after %.3fs', method, time.time() - start) future.set_exception(exc_info=(type(e), e, None)) func(*args, reply_handler=reply, error_handler=error, **kwargs) return future @classmethod def fromvalue(cls, value): future = cls() future.set(value) return future class dLeynaServers(collections.Mapping): def __init__(self, bus): self.__bus = bus self.__lock = threading.RLock() self.__servers = {} bus.add_signal_receiver( self.__found_server, 'FoundServer', bus_name=SERVER_BUS_NAME ) bus.add_signal_receiver( self.__lost_server, 'LostServer', bus_name=SERVER_BUS_NAME ) self.__get_servers() def __getitem__(self, udn): key = udn.lower() with self.__lock: return self.__servers[key] def __iter__(self): with self.__lock: return iter(list(self.__servers)) def __len__(self): with self.__lock: return len(self.__servers) def __add_server(self, obj): udn = obj['UDN'] obj['URI'] = uritools.uricompose('dleyna', udn) key = udn.lower() if key not in self: self.__log_server_action('Found', obj) with self.__lock: self.__servers[key] = obj def __remove_server(self, obj): key = obj['UDN'].lower() with self.__lock: del self.__servers[key] self.__log_server_action('Lost', obj) def __found_server(self, path): def error_handler(e): logger.warn('Cannot access media server %s: %s', path, e) self.__bus.get_object(SERVER_BUS_NAME, path).GetAll( '', # all interfaces dbus_interface=dbus.PROPERTIES_IFACE, reply_handler=self.__add_server, error_handler=error_handler ) def __lost_server(self, path): with self.__lock: servers = list(self.__servers.values()) for obj in servers: if obj['Path'] == path: return self.__remove_server(obj) logger.info('Lost digital media server %s', path) def __get_servers(self): def reply_handler(paths): for path in paths: self.__found_server(path) def error_handler(e): logger.error('Cannot retrieve digital media servers: %s', e) self.__bus.get_object(SERVER_BUS_NAME, SERVER_ROOT_PATH).GetServers( dbus_interface=SERVER_MANAGER_IFACE, reply_handler=reply_handler, error_handler=error_handler ) @classmethod def __log_server_action(cls, action, obj): logger.info( '%s digital media server %s [%s]', action, obj['FriendlyName'], obj['UDN'] ) class dLeynaClient(object): MEDIA_CONTAINER_IFACE = 'org.gnome.UPnP.MediaContainer2' MEDIA_DEVICE_IFACE = 'com.intel.dLeynaServer.MediaDevice' MEDIA_ITEM_IFACE = 'org.gnome.UPnP.MediaItem2' MEDIA_OBJECT_IFACE = 'org.gnome.UPnP.MediaObject2' def __init__(self, address=None, mainloop=None): if address: self.__bus = dbus.bus.BusConnection(address, mainloop=mainloop) else: self.__bus = dbus.SessionBus(mainloop=mainloop) self.__servers = dLeynaServers(self.__bus) def browse(self, uri, offset=0, limit=0, filter=['*'], order=[]): baseuri, objpath = self.__parseuri(uri) future = dLeynaFuture.fromdbus( self.__bus.get_object(SERVER_BUS_NAME, objpath).ListChildrenEx, dbus.UInt32(offset), dbus.UInt32(limit), translator.urifilter(filter), ','.join(order), dbus_interface=self.MEDIA_CONTAINER_IFACE ) if baseuri and (filter == ['*'] or 'URI' in filter): return future.map(translator.urimapper(baseuri)) else: return future def properties(self, uri, iface=None): baseuri, objpath = self.__parseuri(uri) future = dLeynaFuture.fromdbus( self.__bus.get_object(SERVER_BUS_NAME, objpath).GetAll, iface or '', dbus_interface=dbus.PROPERTIES_IFACE ) if baseuri and (not iface or iface == self.MEDIA_OBJECT_IFACE): return future.apply(translator.urimapper(baseuri)) else: return future def rescan(self): return dLeynaFuture.fromdbus( self.__bus.get_object(SERVER_BUS_NAME, SERVER_ROOT_PATH).Rescan, dbus_interface=SERVER_MANAGER_IFACE ) def search(self, uri, query, offset=0, limit=0, filter=['*'], order=[]): baseuri, objpath = self.__parseuri(uri) future = dLeynaFuture.fromdbus( self.__bus.get_object(SERVER_BUS_NAME, objpath).SearchObjectsEx, query, dbus.UInt32(offset), dbus.UInt32(limit), translator.urifilter(filter), ','.join(order), dbus_interface=self.MEDIA_CONTAINER_IFACE ) if baseuri and (filter == ['*'] or 'URI' in filter): mapper = translator.urimapper(baseuri) return future.apply(lambda res: map(mapper, res[0])) else: return future.apply(lambda res: res[0]) def server(self, uri): udn = uritools.urisplit(uri).gethost() return dLeynaFuture.fromvalue(self.__servers[udn]) def servers(self): return dLeynaFuture.fromvalue(self.__servers.values()) def __parseuri(self, uri): parts = uritools.urisplit(uri) if parts.authority: udn = parts.gethost() try: server = self.__servers[udn] except KeyError: raise LookupError('Unknown media server UDN %s' % udn) else: return server['URI'], server['Path'] + parts.path else: return None, uri if __name__ == '__main__': import argparse import json import sys import dbus.mainloop.glib import gobject parser = argparse.ArgumentParser() parser.add_argument('uri', nargs='?') parser.add_argument('-d', '--debug', action='store_true') parser.add_argument('-f', '--filter', default=['*'], nargs='*') # parser.add_argument('-i', '--indent', type=int, default=2) parser.add_argument('-i', '--iface') parser.add_argument('-l', '--list', action='store_true') parser.add_argument('-q', '--query') args = parser.parse_args() logging.basicConfig(level=logging.DEBUG if args.debug else logging.ERROR) client = dLeynaClient(mainloop=dbus.mainloop.glib.DBusGMainLoop()) # FIXME: wait for servers for i in range(0, 10000): gobject.MainLoop().get_context().iteration(True) if not args.uri: future = client.servers() elif args.list: future = client.browse(args.uri, filter=args.filter) elif args.query: future = client.search(args.uri, args.query, filter=args.filter) else: future = client.properties(args.uri, iface=args.iface) while True: try: future.get(timeout=0) except pykka.Timeout: gobject.MainLoop().get_context().iteration(True) else: break json.dump(future.get(), sys.stdout, default=vars, indent=2) sys.stdout.write('\n') Mopidy-dLeyna-1.0.5/mopidy_dleyna/playback.py0000664000175000017500000000110112650343661022320 0ustar tkemmertkemmer00000000000000from __future__ import absolute_import, unicode_literals import logging from mopidy import backend logger = logging.getLogger(__name__) class dLeynaPlaybackProvider(backend.PlaybackProvider): def translate_uri(self, uri): dleyna = self.backend.dleyna try: obj = dleyna.properties(uri, dleyna.MEDIA_ITEM_IFACE).get() except Exception as e: logger.error('Error translating %s: %s', uri, e) return None else: # TODO: GetCompatibleResources w/protocol_info return obj['URLs'][0] Mopidy-dLeyna-1.0.5/mopidy_dleyna/ext.conf0000664000175000017500000000040712650342227021634 0ustar tkemmertkemmer00000000000000[dleyna] enabled = true # maximum number of objects to retrieve per UPnP Browse action, or 0 # to retrieve all objects upnp_browse_limit = 1000 # maximum number of objects to retrieve per UPnP Search action, or 0 # to retrieve all objects upnp_search_limit = 0 Mopidy-dLeyna-1.0.5/mopidy_dleyna/translator.py0000664000175000017500000001013112650343661022726 0ustar tkemmertkemmer00000000000000from __future__ import absolute_import, unicode_literals from mopidy import models ALBUM_TYPE = 'container.album.musicAlbum' ARTIST_TYPE = 'container.person.musicArtist' _PATH_PREFIX = '/com/intel/dLeynaServer/server/' _QUERYMAP = { 'any': lambda caps: ( ' or '.join(s + ' {0} "{1}"' for s in caps & { 'DisplayName', 'Album', 'Artist', 'Genre', 'Creator' }) ), 'album': lambda caps: ( 'Album {0} "{1}"' if 'Album' in caps else None ), 'artist': lambda caps: ( ' or '.join(s + ' {0} "{1}"' for s in caps & {'Artist', 'Creator'}) ), 'date': lambda caps: ( 'Date = "{1}"' if 'Date' in caps else None # TODO: inexact? ), 'genre': lambda caps: ( 'Genre {0} "{1}"' if 'Genre' in caps else None ), 'track_name': lambda caps: ( ('DisplayName {0} "{1}" and Type = "music"' if 'DisplayName' in caps and 'Type' in caps else None) ), 'track_no': lambda caps: ( 'TrackNumber = "{1}"' if 'TrackNumber' in caps else None ) } # TODO: handle playlists and 'container.playlistContainer' _REFMAP = { 'audio': models.Ref.track, 'container': models.Ref.directory, 'container.genre.musicGenre': models.Ref.directory, 'container.storageFolder': models.Ref.directory, 'music': models.Ref.track, ALBUM_TYPE: models.Ref.album, ARTIST_TYPE: models.Ref.artist } def _quote(s): return unicode(s).replace('\\', '\\\\').replace('"', '\\"') def _album(obj): try: name = obj['Album'] except KeyError: return None else: return models.Album(name=name, uri=None) def _artists(obj): artists = [] for name in filter(None, obj.get('Artists', [obj.get('Creator')])): artists.append(models.Artist(name=name, uri=None)) return artists def ref(obj): type = obj.get('TypeEx', obj['Type']) try: return _REFMAP[type](name=obj['DisplayName'], uri=obj['URI']) except KeyError: raise ValueError('Object type "%s" not supported' % type) def album(obj): return models.Album( artists=_artists(obj), name=obj['DisplayName'], num_tracks=obj.get('ItemCount', obj.get('ChildCount')), uri=obj['URI'] ) def artist(obj): return models.Artist(name=obj['DisplayName'], uri=obj['URI']) def track(obj): return models.Track( album=_album(obj), artists=_artists(obj), date=obj.get('Date'), genre=obj.get('Genre'), length=obj.get('Duration', 0) * 1000 or None, name=obj['DisplayName'], track_no=obj.get('TrackNumber'), uri=obj['URI'] ) def model(obj): type = obj.get('TypeEx', obj['Type']) if type == 'music' or type == 'audio': return track(obj) elif type == ALBUM_TYPE: return album(obj) elif type == ARTIST_TYPE: return artist(obj) else: raise ValueError('Object type "%s" not supported' % type) def images(obj): try: return [models.Image(uri=obj['AlbumArtURL'])] except KeyError: return [] def query(query, exact, searchcaps): terms = [] caps = frozenset(searchcaps) op = '=' if exact else 'contains' for key, values in query.items(): try: fmt = _QUERYMAP[key](caps) except KeyError: raise ValueError('Keyword "%s" not supported' % key) if fmt: terms.extend(fmt.format(op, _quote(value)) for value in values) else: raise ValueError('Keyword "%s" not supported by device' % key) return ('(%s)' % ') and ('.join(terms)) or '*' def urifilter(fields): if 'URI' in fields: objfilter = fields[:] objfilter.remove('URI') objfilter.append('Path') objfilter.append('RefPath') return objfilter else: return fields def urimapper(baseuri): def mapper(obj, index=len(_PATH_PREFIX)): objpath = obj.get('RefPath', obj['Path']) assert objpath.startswith(_PATH_PREFIX) _, sep, relpath = objpath[index:].partition('/') obj['URI'] = baseuri + sep + relpath return obj return mapper Mopidy-dLeyna-1.0.5/mopidy_dleyna/library.py0000664000175000017500000001627012650343661022213 0ustar tkemmertkemmer00000000000000from __future__ import absolute_import, unicode_literals import collections import itertools import logging import operator from mopidy import backend, models from uritools import uricompose, urisplit from . import Extension, translator logger = logging.getLogger(__name__) BROWSE_FILTER = [ 'DisplayName', 'Type', 'TypeEx', 'URI' ] IMAGES_FILTER = [ 'AlbumArtURL', 'Path' ] SEARCH_FILTER = [ 'Album', 'AlbumArtURL', 'Artist', 'Artists', 'Creator', 'Date', 'DisplayName', 'Duration', 'Genre', 'TrackNumber', 'Type', 'TypeEx', 'URI' ] BROWSE_ORDER = { models.Ref.ALBUM: ['+TrackNumber', '+DisplayName'], models.Ref.ARTIST: ['+TypeEx', '+DisplayName'], models.Ref.DIRECTORY: ['+TypeEx', '+DisplayName'], } LOOKUP_QUERY = 'Type = "music" or Type = "audio"' # TODO: check SearchCaps def _chunks(seq, n): for i in range(0, len(seq), n): yield seq[i:i+n] def _objmapper(func): def mapper(objs): for obj in objs: try: yield func(obj) except ValueError as e: logger.debug('Skipping %s: %s', obj['URI'], e) return mapper class dLeynaLibraryProvider(backend.LibraryProvider): root_directory = models.Ref.directory( uri=uricompose(Extension.ext_name), name='Digital Media Servers' ) def __init__(self, backend, config): super(dLeynaLibraryProvider, self).__init__(backend) self.__upnp_search_limit = config['upnp_search_limit'] self.__upnp_browse_limit = config['upnp_browse_limit'] def browse(self, uri): if uri == self.root_directory.uri: return self.__browse_root() else: return self.__browse_container(uri) def get_images(self, uris): dleyna = self.backend.dleyna servers = {obj['UDN']: obj for obj in dleyna.servers().get()} searchpaths = collections.defaultdict(list) # for Path queries futures = [] urimap = {} # TODO: refactor for URIs for uri in uris: parts = urisplit(uri) try: server = servers[parts.gethost()] except KeyError: raise LookupError('Cannot resolve URI %s' % uri) root = server['Path'] path = root + parts.getpath() if 'Path' in server['SearchCaps']: searchpaths[root].append(path) else: futures.append(dleyna.properties(path).apply(lambda x: [x])) urimap[path] = uri for root, paths in searchpaths.items(): # TODO: how to determine max. query size for server? config? for chunk in _chunks(paths, 50): query = ' or '.join('Path = "%s"' % path for path in chunk) futures.append(dleyna.search(root, query, 0, 0, IMAGES_FILTER)) results = {} for obj in itertools.chain.from_iterable(f.get() for f in futures): try: uri = urimap[obj['Path']] except KeyError: logger.error('Unexpected path in image result: %r', obj) else: results[uri] = translator.images(obj) return results def lookup(self, uri): dleyna = self.backend.dleyna obj = dleyna.properties(uri).get() if obj['Type'] == 'container': future = dleyna.search(uri, LOOKUP_QUERY, filter=SEARCH_FILTER) return list(map(translator.track, future.get())) elif obj['Type'] in ('music', 'audio'): return [translator.track(obj)] else: logger.error('Invalid object type for %s: %s', uri, obj['Type']) return [] def refresh(self, uri=None): logger.info('Refreshing dLeyna library') self.backend.dleyna.rescan().get() def search(self, query=None, uris=None, exact=False): dleyna = self.backend.dleyna # sanitize uris uris = set(uris or [self.root_directory.uri]) if self.root_directory.uri in uris: uris.update(server['URI'] for server in dleyna.servers().get()) uris.remove(self.root_directory.uri) # start searching futures = [] for uri in uris: try: limit = self.__upnp_search_limit future = self.__search(uri, query or {}, exact, 0, limit) except ValueError as e: logger.warn('Not searching %s: %s', uri, e) else: futures.append(future) # retrieve and merge search results results = collections.defaultdict(collections.OrderedDict) for model in itertools.chain.from_iterable(f.get() for f in futures): results[type(model)][model.uri] = model # merge results w/same uri return models.SearchResult( uri=uricompose(Extension.ext_name, query=query), albums=results[models.Album].values(), artists=results[models.Artist].values(), tracks=results[models.Track].values() ) def __browse_root(self, key=operator.attrgetter('name')): refs = [] for server in self.backend.dleyna.servers().get(): name = server.get('FriendlyName', server['DisplayName']) refs.append(models.Ref.directory(name=name, uri=server['URI'])) return list(sorted(refs, key=key)) def __browse_container(self, uri): # determine sort order dleyna = self.backend.dleyna obj = dleyna.properties(uri, iface=dleyna.MEDIA_OBJECT_IFACE).get() order = self.__sortorder(uri, BROWSE_ORDER[translator.ref(obj).type]) # start browsing refs = [] offset = 0 limit = self.__upnp_browse_limit future = self.__browse(uri, offset, limit, order) while future: result, more = future.get() if more: offset += limit future = self.__browse(uri, offset, limit, order) else: future = None refs.extend(result) return refs def __browse(self, uri, offset=0, limit=0, order=[], mapper=_objmapper(translator.ref)): dleyna = self.backend.dleyna future = dleyna.browse(uri, offset, limit, BROWSE_FILTER, order) return future.apply( lambda objs: (mapper(objs), limit and len(objs) == limit) ) def __search(self, uri, query, exact=False, offset=0, limit=0, order=[], mapper=_objmapper(translator.model)): dleyna = self.backend.dleyna searchcaps = dleyna.server(uri).get().get('SearchCaps', []) logger.debug('SearchCaps for %s: %r', uri, searchcaps) query = translator.query(query, exact, searchcaps) future = dleyna.search(uri, query, offset, limit, SEARCH_FILTER, order) # TODO: return "more" flag as in browse return future.apply(mapper) def __sortorder(self, uri, order): dleyna = self.backend.dleyna sortcaps = frozenset(dleyna.server(uri).get().get('SortCaps', [])) logger.debug('SortCaps for %s: %r', uri, sortcaps) if '*' in sortcaps: return order else: return list(filter(lambda f: f[1:] in sortcaps, order)) Mopidy-dLeyna-1.0.5/mopidy_dleyna/__init__.py0000664000175000017500000000157412650343661022307 0ustar tkemmertkemmer00000000000000from __future__ import unicode_literals import os from mopidy import config, exceptions, ext __version__ = '1.0.5' class Extension(ext.Extension): dist_name = 'Mopidy-dLeyna' ext_name = 'dleyna' version = __version__ def get_default_config(self): return config.read(os.path.join(os.path.dirname(__file__), 'ext.conf')) def get_config_schema(self): schema = super(Extension, self).get_config_schema() schema['upnp_browse_limit'] = config.Integer(minimum=0) schema['upnp_search_limit'] = config.Integer(minimum=0) return schema def setup(self, registry): from .backend import dLeynaBackend registry.add('backend', dLeynaBackend) def validate_environment(self): try: import dbus # noqa except ImportError: raise exceptions.ExtensionError('Cannot import dbus') Mopidy-dLeyna-1.0.5/LICENSE0000644000175000017500000002367612611670762016355 0ustar tkemmertkemmer00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Mopidy-dLeyna-1.0.5/PKG-INFO0000664000175000017500000001027312650344020016420 0ustar tkemmertkemmer00000000000000Metadata-Version: 1.1 Name: Mopidy-dLeyna Version: 1.0.5 Summary: Mopidy extension for playing music from Digital Media Servers Home-page: https://github.com/tkem/mopidy-dleyna Author: Thomas Kemmer Author-email: tkemmer@computer.org License: Apache License, Version 2.0 Description: Mopidy-dLeyna ======================================================================== Mopidy-dLeyna is a Mopidy_ extension that lets you play music from DLNA_ Digital Media Servers using the dLeyna_ D-Bus interface. Dependencies ------------------------------------------------------------------------ - D-Bus Python bindings, such as the package ``python-dbus`` in Debian/Ubuntu/Raspbian. - The ``dleyna-server`` package available in Ubuntu 14.04 and Debian "jessie". For other platforms, please see the dLeyna `installation instructions `_. Installation ------------------------------------------------------------------------ Debian/Ubuntu/Raspbian: Install the ``mopidy-dleyna`` package from `apt.mopidy.com `_:: sudo apt-get install mopidy-dleyna Otherwise, install the dependencies listed above, and then install the package from PyPI_:: pip install Mopidy-dLeyna Configuration ------------------------------------------------------------------------ The following configuration values are provided: - ``dleyna/enabled``: Whether this extension should be enabled or not. Defaults to ``true`` - ``dleyna/upnp_browse_limit``: The maximum number of objects to retrieve per UPnP `Browse` action, or ``0`` to retrieve all objects. Defaults to ``1000``. - ``dleyna/upnp_search_limit``: The maximum number of objects to retrieve per UPnP `Search` action, or ``0`` to retrieve all objects. Defaults to ``0``. Project resources ------------------------------------------------------------------------ .. image:: https://img.shields.io/pypi/v/Mopidy-dLeyna.svg?style=flat :target: https://pypi.python.org/pypi/Mopidy-dLeyna/ :alt: Latest PyPI version .. image:: https://img.shields.io/pypi/dm/Mopidy-dLeyna.svg?style=flat :target: https://pypi.python.org/pypi/Mopidy-dLeyna/ :alt: Number of PyPI downloads .. image:: https://img.shields.io/travis/tkem/mopidy-dleyna/master.svg?style=flat :target: https://travis-ci.org/tkem/mopidy-dleyna :alt: Travis CI build status .. image:: https://img.shields.io/coveralls/tkem/mopidy-dleyna/master.svg?style=flat :target: https://coveralls.io/r/tkem/mopidy-dleyna?branch=master :alt: Test coverage - `Issue Tracker`_ - `Source Code`_ - `Change Log`_ License ------------------------------------------------------------------------ Copyright (c) 2015, 2016 Thomas Kemmer. Licensed under the `Apache License, Version 2.0`_. .. _Mopidy: http://www.mopidy.com/ .. _DLNA: http://www.dlna.org/ .. _dLeyna: http://01.org/dleyna .. _PyPI: https://pypi.python.org/pypi/Mopidy-dLeyna/ .. _Issue Tracker: https://github.com/tkem/mopidy-dleyna/issues/ .. _Source Code: https://github.com/tkem/mopidy-dleyna/ .. _Change Log: https://github.com/tkem/mopidy-dleyna/blob/master/CHANGES.rst .. _Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 Platform: UNKNOWN Classifier: Environment :: No Input/Output (Daemon) Classifier: Intended Audience :: End Users/Desktop Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Topic :: Multimedia :: Sound/Audio :: Players Mopidy-dLeyna-1.0.5/CHANGES.rst0000664000175000017500000000407012650343661017135 0ustar tkemmertkemmer00000000000000v1.0.5 (2016-01-22) ------------------- - Specify sort order when browsing. - Add ``apt.mopidy.com`` to installation options. - Remove ``Album.images`` property (deprecated in Mopidy v1.2). - Handle exceptions in ``dLeynaPlaybackProvider``. v1.0.4 (2015-11-03) ------------------- - Handle uppercase characters in server UDNs. v1.0.3 (2015-10-24) ------------------- - Refactor server handling. - Handle persistent URIs in ``dLeynaClient``. v1.0.2 (2015-10-16) ------------------- - Improve startup error messages. - Performance improvements. v1.0.1 (2015-09-12) ------------------- - Add workaround for permanently lost media servers. v1.0.0 (2015-08-21) ------------------- - Add ``upnp_browse_limit`` config value. - Add ``upnp_search_limit`` config value. - Refactor ``get_images`` implementation. - Improve debug output. v0.5.3 (2015-08-19) ------------------- - Fix lost server handling. - Check device's `SearchCaps` when searching. - Improve log messages. v0.5.2 (2015-08-18) ------------------- - Move mapping helpers to translator module. - Add ``mopidy_dleyna.dleyna.__main__``. - Update `README.rst`. v0.5.1 (2015-08-14) ------------------- - Start/stop D-Bus daemon from backend. v0.5.0 (2015-08-14) ------------------- - Add support for album art. v0.4.2 (2015-08-14) ------------------- - Use asynchronous D-Bus calls to improve performance on Raspberry Pi. v0.4.1 (2015-08-11) ------------------- - Add workaround for integer conversion issues on 32 bit systems. v0.4.0 (2015-08-11) ------------------- - Start session bus on headless systems or when running as a daemon. - Use recursive search for container lookups. - Add browse/search filters. - Peristent URI handling. v0.3.1 (2015-04-11) ------------------- - Perform search asynchronously. v0.3.0 (2015-04-10) ------------------- - Add basic search capabilities. - Return proper reference types when browsing. v0.2.0 (2015-04-08) ------------------- - Add workaround for `minidlna` crashing on empty filter. v0.1.0 (2015-04-07) ------------------- - Initial release. Mopidy-dLeyna-1.0.5/tests/0000775000175000017500000000000012650344020016462 5ustar tkemmertkemmer00000000000000Mopidy-dLeyna-1.0.5/tests/test_extension.py0000664000175000017500000000072612650343661022126 0ustar tkemmertkemmer00000000000000from __future__ import unicode_literals from mopidy_dleyna import Extension def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert '[dleyna]' in config assert 'enabled = true' in config def test_get_config_schema(): ext = Extension() schema = ext.get_config_schema() assert 'enabled' in schema assert 'upnp_browse_limit' in schema assert 'upnp_search_limit' in schema # TODO Write more tests Mopidy-dLeyna-1.0.5/tests/test_translator.py0000664000175000017500000000327212612745323022301 0ustar tkemmertkemmer00000000000000from __future__ import unicode_literals from mopidy.models import Album, Artist, Ref, Track from mopidy_dleyna import translator BASEURI = 'dleyna://foo' BASEPATH = '/com/intel/dLeynaServer/server/0' def test_album_ref(): assert translator.ref({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'container', 'TypeEx': translator.ALBUM_TYPE }) == Ref.album(uri=BASEURI+'/foo', name='Foo') def test_artist_ref(): assert translator.ref({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'container', 'TypeEx': translator.ARTIST_TYPE }) == Ref.artist(uri=BASEURI+'/foo', name='Foo') def test_track_ref(): assert translator.ref({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'music', }) == Ref.track(uri=BASEURI+'/foo', name='Foo') def test_directory_ref(): assert translator.ref({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'container' }) == Ref.directory(uri=BASEURI+'/foo', name='Foo') def test_album(): assert translator.model({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'container', 'TypeEx': translator.ALBUM_TYPE }) == Album(uri=BASEURI+'/foo', name='Foo') def test_artist(): assert translator.model({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'container', 'TypeEx': translator.ARTIST_TYPE }) == Artist(uri=BASEURI+'/foo', name='Foo') def test_track(): assert translator.model({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'music', }) == Track(uri=BASEURI+'/foo', name='Foo') Mopidy-dLeyna-1.0.5/tests/__init__.py0000644000175000017500000000000012611670762020573 0ustar tkemmertkemmer00000000000000