Mopidy-dLeyna-1.2.0/0000775000175000017500000000000012771253017014116 5ustar tkemtkem00000000000000Mopidy-dLeyna-1.2.0/tests/0000775000175000017500000000000012771253017015260 5ustar tkemtkem00000000000000Mopidy-dLeyna-1.2.0/tests/conftest.py0000664000175000017500000000147612720076412017463 0ustar tkemtkem00000000000000from __future__ import unicode_literals import mock import pytest @pytest.fixture def audio(): return mock.Mock() @pytest.fixture def config(): return { 'dleyna': { 'upnp_browse_limit': 1000, 'upnp_lookup_limit': 50, 'upnp_search_limit': 100 } } @pytest.fixture def client(): client_mock = mock.Mock() return client_mock @pytest.fixture def backend(config, audio, client): from mopidy import backend from mopidy_dleyna import library, playback backend_mock = mock.Mock(spec=backend.Backend) backend_mock.client = client backend_mock.library = library.dLeynaLibraryProvider( backend_mock, config ) backend_mock.playback = playback.dLeynaPlaybackProvider( audio, backend_mock ) return backend_mock Mopidy-dLeyna-1.2.0/tests/test_translator.py0000664000175000017500000000425212720076412021061 0ustar tkemtkem00000000000000from __future__ import unicode_literals from mopidy.models import Album, Artist, Ref, Track import pytest from mopidy_dleyna import translator BASEURI = 'dleyna://foo' BASEPATH = '/com/intel/dLeynaServer/server/0' ALBUM_TYPE = 'container.album.musicAlbum' ARTIST_TYPE = 'container.person.musicArtist' def test_album_ref(): assert translator.ref({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'container', 'TypeEx': ALBUM_TYPE }) == Ref.album(uri=BASEURI+'/foo', name='Foo') def test_artist_ref(): assert translator.ref({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'container', 'TypeEx': 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_video_ref(): with pytest.raises(ValueError): translator.ref({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'video' }) def test_album(): assert translator.model({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'container', 'TypeEx': ALBUM_TYPE }) == Album(uri=BASEURI+'/foo', name='Foo') def test_artist(): assert translator.model({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'container', 'TypeEx': ARTIST_TYPE }) == Artist(uri=BASEURI+'/foo', name='Foo') def test_track(): assert translator.model({ 'DisplayName': 'Foo', 'Album': 'Bar', 'URI': BASEURI + '/foo', 'Type': 'music', }) == Track(uri=BASEURI+'/foo', name='Foo', album=Album(name='Bar')) def test_video(): with pytest.raises(ValueError): translator.model({ 'DisplayName': 'Foo', 'URI': BASEURI + '/foo', 'Type': 'video' }) Mopidy-dLeyna-1.2.0/tests/test_images.py0000664000175000017500000000227712720076412020142 0ustar tkemtkem00000000000000from __future__ import unicode_literals import mock from mopidy import models import pytest from mopidy_dleyna.util import Future @pytest.fixture def server(): return { 'FriendlyName': 'Media Server', 'DisplayName': 'Media', 'SearchCaps': ['DisplayName', 'Path'], 'Path': '/com/intel/dLeynaServer/server/0', 'URI': 'dleyna://media' } @pytest.fixture def items(): return [ { 'DisplayName': 'Track #1', 'Type': 'music', 'AlbumArtURL': 'http:://example.com/1.jpg', 'URI': 'dleyna://media/1' }, { 'DisplayName': 'Track #2', 'Type': 'audio', 'URI': 'dleyna://media/2' } ] def test_images(backend, server, items): with mock.patch.object(backend, 'client') as m: m.servers.return_value = Future.fromvalue([server]) m.server.return_value = Future.fromvalue(server) m.search.return_value = Future.fromvalue(items) assert backend.library.get_images(item['URI'] for item in items) == { items[0]['URI']: (models.Image(uri=items[0]['AlbumArtURL']),), items[1]['URI']: tuple() } Mopidy-dLeyna-1.2.0/tests/test_extension.py0000664000175000017500000000075012771252615020712 0ustar tkemtkem00000000000000from __future__ import unicode_literals from mopidy_dleyna import Extension def test_get_default_config(): config = Extension().get_default_config() assert '[' + Extension.ext_name + ']' in config assert 'enabled = true' in config def test_get_config_schema(): schema = Extension().get_config_schema() assert 'upnp_browse_limit' in schema assert 'upnp_lookup_limit' in schema assert 'upnp_search_limit' in schema assert 'dbus_start_session' in schema Mopidy-dLeyna-1.2.0/tests/test_playback.py0000664000175000017500000000136612720076412020461 0ustar tkemtkem00000000000000from __future__ import unicode_literals import mock import pytest from mopidy_dleyna.util import Future @pytest.fixture def item(): return { 'DisplayName': 'Track #1', 'Type': 'music', 'URI': 'dleyna://media/1', 'URLs': ['http://example.com/1.mp3'] } def test_translate_uri(backend, item): with mock.patch.object(backend, 'client') as m: m.properties.return_value = Future.fromvalue(item) assert backend.playback.translate_uri(item['URI']) == item['URLs'][0] def test_translate_unknown_uri(backend): with mock.patch.object(backend, 'client') as m: m.properties.return_value = Future.exception(LookupError('Not Found')) assert backend.playback.translate_uri('') is None Mopidy-dLeyna-1.2.0/tests/test_browse.py0000664000175000017500000000337312720076412020174 0ustar tkemtkem00000000000000from __future__ import unicode_literals import mock from mopidy.models import Ref import pytest from mopidy_dleyna.util import Future @pytest.fixture def servers(): return [ { 'FriendlyName': 'Media Server #1', 'DisplayName': 'Media1', 'URI': 'dleyna://media1' }, { 'FriendlyName': 'Media Server #2', 'DisplayName': 'Media2', 'URI': 'dleyna://media2' } ] @pytest.fixture def container(): return { 'DisplayName': 'Root', 'Type': 'container', 'URI': 'dleyna://media' } @pytest.fixture def items(): return [ { 'DisplayName': 'Track #1', 'Type': 'music', 'URI': 'dleyna://media/1' }, { 'DisplayName': 'Track #2', 'Type': 'audio', 'URI': 'dleyna://media/2' } ] def test_browse_root(backend, servers): with mock.patch.object(backend, 'client') as m: m.servers.return_value = Future.fromvalue(servers) assert backend.library.browse(backend.library.root_directory.uri) == [ Ref.directory(name='Media Server #1', uri='dleyna://media1'), Ref.directory(name='Media Server #2', uri='dleyna://media2'), ] def test_browse_items(backend, container, items): # FIXME: how to patch multiple object methods... with mock.patch.object(backend, 'client') as m: m.properties.return_value = Future.fromvalue(container) m.browse.return_value = Future.fromvalue(items) assert backend.library.browse(container['URI']) == [ Ref.track(name='Track #1', uri='dleyna://media/1'), Ref.track(name='Track #2', uri='dleyna://media/2') ] Mopidy-dLeyna-1.2.0/tests/test_search.py0000664000175000017500000000330712720076412020135 0ustar tkemtkem00000000000000from __future__ import unicode_literals import mock from mopidy import models import pytest from mopidy_dleyna.util import Future @pytest.fixture def server(): return { 'FriendlyName': 'Media Server', 'DisplayName': 'Media', 'SearchCaps': ['DisplayName'], 'URI': 'dleyna://media' } @pytest.fixture def result(): return [ { 'DisplayName': 'Album #1', 'Type': 'container', 'TypeEx': 'container.album.musicAlbum', 'URI': 'dleyna://media/1' }, { 'DisplayName': 'Track #1', 'Type': 'music', 'URI': 'dleyna://media/11' }, { 'DisplayName': 'Track #2', 'Type': 'audio', 'URI': 'dleyna://media/12' } ] def test_search(backend, server, result): with mock.patch.object(backend, 'client') as m: m.servers.return_value = Future.fromvalue([server]) m.server.return_value = Future.fromvalue(server) m.search.return_value = Future.fromvalue(result) # valid search assert backend.library.search({'any': ['foo']}) == models.SearchResult( albums=[ models.Album(name='Album #1', uri='dleyna://media/1') ], tracks=[ models.Track(name='Track #1', uri='dleyna://media/11'), models.Track(name='Track #2', uri='dleyna://media/12') ] ) # unsupported search field yields no result assert backend.library.search({'composer': ['foo']}) is None # search field not supported by device yields no result assert backend.library.search({'genre': ['foo']}) is None Mopidy-dLeyna-1.2.0/tests/__init__.py0000644000175000017500000000000012716604404017354 0ustar tkemtkem00000000000000Mopidy-dLeyna-1.2.0/tests/test_lookup.py0000664000175000017500000000270212720076412020177 0ustar tkemtkem00000000000000from __future__ import unicode_literals import mock from mopidy import models import pytest from mopidy_dleyna.util import Future @pytest.fixture def container(): return { 'DisplayName': 'Album #1', 'Type': 'container', 'TypeEx': 'container.album.musicAlbum', 'URI': 'dleyna://media/1' } @pytest.fixture def items(): return [ { 'DisplayName': 'Track #1', 'Type': 'music', 'URI': 'dleyna://media/11' }, { 'DisplayName': 'Track #2', 'Type': 'audio', 'URI': 'dleyna://media/12' } ] def test_lookup_root(backend): assert backend.library.lookup(backend.library.root_directory.uri) == [] def test_lookup_item(backend, items): with mock.patch.object(backend, 'client') as m: m.properties.return_value = Future.fromvalue(items[0]) assert backend.library.lookup(items[0]['URI']) == [ models.Track(name='Track #1', uri='dleyna://media/11') ] def test_lookup_container(backend, container, items): with mock.patch.object(backend, 'client') as m: m.properties.return_value = Future.fromvalue(container) m.search.return_value = Future.fromvalue(items) assert backend.library.lookup(container['URI']) == [ models.Track(name='Track #1', uri='dleyna://media/11'), models.Track(name='Track #2', uri='dleyna://media/12') ] Mopidy-dLeyna-1.2.0/PKG-INFO0000664000175000017500000000603512771253017015217 0ustar tkemtkem00000000000000Metadata-Version: 1.1 Name: Mopidy-dLeyna Version: 1.2.0 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. This extension lets you browse, search, and stream music from your NAS, PC, or any other device running a UPnP/DLNA compliant media server. Compatible devices are discovered automatically on your local network, so there is no configuration needed. For more information and installation instructions, please see Mopidy-dLeyna's online documentation_. 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/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 .. image:: https://readthedocs.org/projects/mopidy-dleyna/badge/?version=latest&style=flat :target: http://mopidy-dleyna.readthedocs.io/en/latest/ :alt: Documentation Status - `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 .. _Documentation: http://mopidy-dleyna.readthedocs.io/en/latest/ .. _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.2.0/Mopidy_dLeyna.egg-info/0000775000175000017500000000000012771253017020345 5ustar tkemtkem00000000000000Mopidy-dLeyna-1.2.0/Mopidy_dLeyna.egg-info/dependency_links.txt0000644000175000017500000000000112771253016024410 0ustar tkemtkem00000000000000 Mopidy-dLeyna-1.2.0/Mopidy_dLeyna.egg-info/top_level.txt0000644000175000017500000000001612771253016023071 0ustar tkemtkem00000000000000mopidy_dleyna Mopidy-dLeyna-1.2.0/Mopidy_dLeyna.egg-info/PKG-INFO0000644000175000017500000000603512771253016021443 0ustar tkemtkem00000000000000Metadata-Version: 1.1 Name: Mopidy-dLeyna Version: 1.2.0 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. This extension lets you browse, search, and stream music from your NAS, PC, or any other device running a UPnP/DLNA compliant media server. Compatible devices are discovered automatically on your local network, so there is no configuration needed. For more information and installation instructions, please see Mopidy-dLeyna's online documentation_. 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/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 .. image:: https://readthedocs.org/projects/mopidy-dleyna/badge/?version=latest&style=flat :target: http://mopidy-dleyna.readthedocs.io/en/latest/ :alt: Documentation Status - `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 .. _Documentation: http://mopidy-dleyna.readthedocs.io/en/latest/ .. _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.2.0/Mopidy_dLeyna.egg-info/entry_points.txt0000644000175000017500000000005712771253016023642 0ustar tkemtkem00000000000000[mopidy.ext] dleyna = mopidy_dleyna:Extension Mopidy-dLeyna-1.2.0/Mopidy_dLeyna.egg-info/not-zip-safe0000644000175000017500000000000112716604472022575 0ustar tkemtkem00000000000000 Mopidy-dLeyna-1.2.0/Mopidy_dLeyna.egg-info/SOURCES.txt0000644000175000017500000000147712771253017022240 0ustar tkemtkem00000000000000CHANGES.rst LICENSE MANIFEST.in README.rst setup.cfg setup.py tox.ini 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 docs/Makefile docs/changelog.rst docs/conf.py docs/config.rst docs/index.rst docs/install.rst docs/license.rst 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 mopidy_dleyna/util.py tests/__init__.py tests/conftest.py tests/test_browse.py tests/test_extension.py tests/test_images.py tests/test_lookup.py tests/test_playback.py tests/test_search.py tests/test_translator.pyMopidy-dLeyna-1.2.0/Mopidy_dLeyna.egg-info/requires.txt0000644000175000017500000000006612771253016022744 0ustar tkemtkem00000000000000setuptools Mopidy >= 1.0 Pykka >= 1.2 uritools >= 1.0 Mopidy-dLeyna-1.2.0/CHANGES.rst0000664000175000017500000000602512771252615015726 0ustar tkemtkem00000000000000v1.2.0 (2016-09-23) ------------------- - Add ``dbus_start_session`` configuration value for specifying the command to start a session bus. The default is to invoke ``dbus-daemon`` daemon directly, so ``dbus-launch`` is no longer needed (but is still supported for now). - Check for ``$XDG_RUNTIME_DIR/bus`` before starting a session bus. - Update installation dependencies. - Improve log messages if search is not supported. v1.1.1 (2016-06-28) ------------------- - Add workaround for partially retrieved browse results with Kodi 16.0 DLNA server. v1.1.0 (2016-05-21) ------------------- - Add ``upnp_lookup_limit`` configuration value (experimental). - Add support for ``albumartist`` queries. - Add support for minidlna "All Albums" collections. - Add track bitrate according to DLNA specification. - Add basic unit tests for ``library`` and ``playback`` providers. - Update documentation and build environment. - Various code refactorings and improvements. v1.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.2.0/README.rst0000664000175000017500000000374712720076412015614 0ustar tkemtkem00000000000000Mopidy-dLeyna ======================================================================== Mopidy-dLeyna is a Mopidy_ extension that lets you play music from DLNA_ Digital Media Servers using the dLeyna_ D-Bus interface. This extension lets you browse, search, and stream music from your NAS, PC, or any other device running a UPnP/DLNA compliant media server. Compatible devices are discovered automatically on your local network, so there is no configuration needed. For more information and installation instructions, please see Mopidy-dLeyna's online documentation_. 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/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 .. image:: https://readthedocs.org/projects/mopidy-dleyna/badge/?version=latest&style=flat :target: http://mopidy-dleyna.readthedocs.io/en/latest/ :alt: Documentation Status - `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 .. _Documentation: http://mopidy-dleyna.readthedocs.io/en/latest/ .. _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.2.0/docs/0000775000175000017500000000000012771253017015046 5ustar tkemtkem00000000000000Mopidy-dLeyna-1.2.0/docs/config.rst0000664000175000017500000000337012771252615017053 0ustar tkemtkem00000000000000Configuration ======================================================================== This extension provides a number of configuration values that can be tweaked. However, the :ref:`default configuration ` should contain everything to get you up and running, and will usually require only a few modifications, if any, to match personal preferences. .. _confvals: Configuration Values ------------------------------------------------------------------------ .. confval:: dleyna/enabled Whether this extension should be enabled or not. .. confval:: dleyna/upnp_browse_limit The maximum number of objects to retrieve per UPnP `Browse` action, or ``0`` to retrieve all objects. .. note:: Due to a known bug in Mopidy-dLeyna, this should *not* be set above 200 when using Kodi as a DLNA server. .. confval:: dleyna/upnp_lookup_limit The maximum number of objects to retrieve by ID in a single UPnP `Search` action, or ``0`` for no limit. Note that for this setting to have any effect, the media server must advertise that it is capable of searching for object IDs. This is an *experimental* setting and may be changed or removed in future versions. .. confval:: dleyna/upnp_search_limit The maximum number of objects to retrieve per UPnP `Search` action, or ``0`` to retrieve all objects. .. confval:: dleyna/dbus_start_session The command to start a D-Bus session bus if none is found, for example when running Mopidy as a service. .. _defconf: Default Configuration ------------------------------------------------------------------------ For reference, this is the default configuration shipped with Mopidy-dLeyna release |release|: .. literalinclude:: ../mopidy_dleyna/ext.conf :language: ini Mopidy-dLeyna-1.2.0/docs/license.rst0000644000175000017500000000124112716604404017215 0ustar tkemtkem00000000000000License ======================================================================== Mopidy-dLeyna is Copyright (c) 2015, 2016 Thomas Kemmer. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Mopidy-dLeyna-1.2.0/docs/conf.py0000644000175000017500000000144212716604404016343 0ustar tkemtkem00000000000000def setup(app): app.add_object_type( 'confval', 'confval', objname='configuration value', indextemplate='pair: %s; configuration value' ) def get_version(filename): from re import findall with open(filename) as f: metadata = dict(findall(r"__([a-z]+)__ = '([^']+)'", f.read())) return metadata['version'] project = 'Mopidy-dLeyna' copyright = '2015, 2016 Thomas Kemmer' version = get_version(b'../mopidy_dleyna/__init__.py') release = version exclude_patterns = ['_build'] master_doc = 'index' html_theme = 'default' latex_documents = [( 'index', 'Mopidy-dLeyna.tex', 'Mopidy-dLeyna Documentation', 'Thomas Kemmer', 'manual' )] man_pages = [( 'index', 'mopidy-dleyna', 'Mopidy-dLeyna Documentation', ['Thomas Kemmer'], 1 )] Mopidy-dLeyna-1.2.0/docs/Makefile0000644000175000017500000001273012716604404016506 0ustar tkemtkem00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Mopidy-dLeyna.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Mopidy-dLeyna.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Mopidy-dLeyna" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Mopidy-dLeyna" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." Mopidy-dLeyna-1.2.0/docs/changelog.rst0000644000175000017500000000016112716604404017522 0ustar tkemtkem00000000000000Change Log ======================================================================== .. include:: ../CHANGES.rst Mopidy-dLeyna-1.2.0/docs/index.rst0000644000175000017500000000120212716604404016677 0ustar tkemtkem00000000000000Mopidy-dLeyna ======================================================================== Mopidy-dLeyna is a Mopidy_ extension that lets you play music from DLNA_ Digital Media Servers using the dLeyna_ D-Bus interface. This extension lets you browse, search, and stream music from your NAS, PC, or any other device running a UPnP/DLNA compliant media server. Compatible devices are discovered automatically on your local network, so there is no configuration needed. .. toctree:: :hidden: install config changelog license .. _Mopidy: http://www.mopidy.com/ .. _DLNA: http://www.dlna.org/ .. _dLeyna: http://01.org/dleyna Mopidy-dLeyna-1.2.0/docs/install.rst0000664000175000017500000000167612771252615017263 0ustar tkemtkem00000000000000Installation ======================================================================== On Debian Linux and Debian-based distributions like Ubuntu or Raspbian, install the ``mopidy-dleyna`` package from apt.mopidy.com_:: apt-get install mopidy-dleyna Otherwise, first make sure the following dependencies are met on your system: - D-Bus Python bindings, such as the package ``python-dbus`` in Debian/Ubuntu/Raspbian [#footnote1]_. - The ``dleyna-server`` package available in Ubuntu 14.04 and Debian "jessie". For other platforms, please see the dLeyna `installation instructions `_. Then install the Python package from PyPI_:: pip install Mopidy-dLeyna .. rubric:: Footnotes .. [#footnote1] On some distributions such as Arch Linux, it may also be necessary to install the ``dbus-glib`` package. .. _apt.mopidy.com: http://apt.mopidy.com/ .. _PyPI: https://pypi.python.org/pypi/Mopidy-dLeyna/ Mopidy-dLeyna-1.2.0/MANIFEST.in0000644000175000017500000000030412716604404015646 0ustar tkemtkem00000000000000include CHANGES.rst include LICENSE include MANIFEST.in include README.rst include mopidy_dleyna/ext.conf include tox.ini recursive-include tests *.py recursive-include docs * prune docs/_build Mopidy-dLeyna-1.2.0/LICENSE0000644000175000017500000002367612716604404015136 0ustar tkemtkem00000000000000 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.2.0/mopidy_dleyna/0000775000175000017500000000000012771253017016753 5ustar tkemtkem00000000000000Mopidy-dLeyna-1.2.0/mopidy_dleyna/backend.py0000664000175000017500000000531512771252615020723 0ustar tkemtkem00000000000000from __future__ import absolute_import, unicode_literals import errno import logging import os import os.path import re import signal import stat 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_RE = re.compile(r""" ^(?:DBUS_SESSION_BUS_ADDRESS=)?(.*)\n ^(?:DBUS_SESSION_BUS_PID=)?(\d+)$ """, re.MULTILINE | re.VERBOSE) 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 self.__have_session_bus(): self.client = dLeynaClient() else: command = config[Extension.ext_name]['dbus_start_session'] address, self.__dbus_pid = self.__start_session_bus(command) self.client = dLeynaClient(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) self.playback = dLeynaPlaybackProvider(audio, self) def on_stop(self): if self.__dbus_pid is not None: self.__stop_session_bus(self.__dbus_pid) def __have_session_bus(self): if 'DBUS_SESSION_BUS_ADDRESS' in os.environ: return True if 'XDG_RUNTIME_DIR' not in os.environ: return False try: st = os.stat(os.path.expandvars('$XDG_RUNTIME_DIR/bus')) except OSError: return False else: return stat.S_ISSOCK(st.st_mode) and st.st_uid == os.geteuid() def __start_session_bus(self, command): logger.info('Starting %s D-Bus daemon', Extension.dist_name) out = subprocess.check_output(command.split(), universal_newlines=True) logger.debug('Running "%s" returned:\n%s', command, out) match = DBUS_SESSION_BUS_RE.search(out) if not match: raise ValueError('%s returned invalid output: %s' % (command, out)) else: return str(match.group(1)), int(match.group(2)) def __stop_session_bus(self, pid): logger.error('Stopping %s D-Bus daemon (%d)', Extension.dist_name, pid) 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.2.0/mopidy_dleyna/client.py0000664000175000017500000002171312744370664020617 0ustar tkemtkem00000000000000from __future__ import absolute_import, unicode_literals import collections import logging import threading import time import dbus import uritools from . import Extension, util SERVER_BUS_NAME = 'com.intel.dleyna-server' SERVER_ROOT_PATH = '/com/intel/dLeynaServer' SERVER_MANAGER_IFACE = 'com.intel.dLeynaServer.Manager' logger = logging.getLogger(__name__) 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, prefix='/com/intel/dLeynaServer/server/'): def mapper(obj, index=len(prefix)): objpath = obj.get('RefPath', obj['Path']) assert objpath.startswith(prefix) _, sep, relpath = objpath[index:].partition('/') obj['URI'] = baseuri + sep + relpath return obj return mapper class Servers(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(Extension.ext_name, 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 = Servers(self.__bus) def browse(self, uri, offset=0, limit=0, filter=['*'], order=[]): baseuri, objpath = self.__parseuri(uri) future = util.Future.fromdbus( self.__bus.get_object(SERVER_BUS_NAME, objpath).ListChildrenEx, dbus.UInt32(offset), dbus.UInt32(limit), urifilter(filter), ','.join(self.__sortorder(uri, order)), dbus_interface=self.MEDIA_CONTAINER_IFACE ) if baseuri and (filter == ['*'] or 'URI' in filter): return future.map(urimapper(baseuri)) else: return future def properties(self, uri, iface=None): baseuri, objpath = self.__parseuri(uri) future = util.Future.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(urimapper(baseuri)) else: return future def rescan(self): return util.Future.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 = util.Future.fromdbus( self.__bus.get_object(SERVER_BUS_NAME, objpath).SearchObjectsEx, query, dbus.UInt32(offset), dbus.UInt32(limit), urifilter(filter), ','.join(self.__sortorder(uri, order)), dbus_interface=self.MEDIA_CONTAINER_IFACE ) if baseuri and (filter == ['*'] or 'URI' in filter): return future.apply(lambda res: map(urimapper(baseuri), res[0])) else: return future.apply(lambda res: res[0]) def server(self, uri): # return future for consistency/future extensions return util.Future.fromvalue(self.__server(uri)) def servers(self): # return future for consistency/future extensions return util.Future.fromvalue(self.__servers.values()) def __parseuri(self, uri): try: server = self.__server(uri) except ValueError: return None, uri else: return server['URI'], server['Path'] + uritools.urisplit(uri).path def __sortorder(self, uri, order): try: server = self.__server(uri) except ValueError: sortcaps = frozenset('*') else: sortcaps = frozenset(server.get('SortCaps', [])) if '*' in sortcaps: return order else: return list(filter(lambda f: f[1:] in sortcaps, order)) def __server(self, uri): udn = uritools.urisplit(uri).gethost() if not udn: raise ValueError('Invalid URI %s' % uri) try: server = self.__servers[udn] except KeyError: raise LookupError('Unknown media server UDN %s' % udn) else: return server if __name__ == '__main__': # pragma: no cover import argparse import json import sys import dbus.mainloop.glib import gobject parser = argparse.ArgumentParser() parser.add_argument('uri', metavar='PATH | URI', nargs='?') parser.add_argument('-b', '--browse', action='store_true') parser.add_argument('-f', '--filter', default=['*'], nargs='*') parser.add_argument('-i', '--iface') parser.add_argument('-m', '--offset', default=0, type=int) parser.add_argument('-n', '--limit', default=0, type=int) parser.add_argument('-o', '--order', default=[], nargs='*') parser.add_argument('-q', '--query') parser.add_argument('-t', '--timeout', default=1.0, type=float) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARN) client = dLeynaClient(mainloop=dbus.mainloop.glib.DBusGMainLoop()) start = time.time() while time.time() < start + args.timeout: if args.uri: try: client.server(args.uri).get() except LookupError: pass except ValueError: break # D-BUS path given else: break gobject.MainLoop().get_context().iteration(False) kwargs = { 'offset': args.offset, 'limit': args.limit, 'filter': args.filter, 'order': args.order } if not args.uri: future = client.servers() elif args.browse: future = client.browse(args.uri, **kwargs) elif args.query: future = client.search(args.uri, args.query, **kwargs) else: future = client.properties(args.uri, iface=args.iface) while True: try: future.get(timeout=0) except util.Future.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.2.0/mopidy_dleyna/ext.conf0000664000175000017500000000110412771252615020421 0ustar tkemtkem00000000000000[dleyna] enabled = true # maximum number of objects to retrieve per UPnP Browse action, or 0 # to retrieve all objects upnp_browse_limit = 200 # maximum number of objects to retrieve by ID in a single UPnP Search # action (if supported by device), or 0 for no limit upnp_lookup_limit = 20 # maximum number of objects to retrieve per UPnP Search action, or 0 # to retrieve all objects upnp_search_limit = 100 # command to start session bus if none found, e.g. when running Mopidy # as a service dbus_start_session = dbus-daemon --fork --session --print-address=1 --print-pid=1 Mopidy-dLeyna-1.2.0/mopidy_dleyna/util.py0000664000175000017500000000247612756622130020312 0ustar tkemtkem00000000000000from __future__ import absolute_import, unicode_literals import logging import time import pykka logger = logging.getLogger(__name__) class Future(pykka.ThreadingFuture): Timeout = pykka.Timeout 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 exception(cls, exc_info=None): future = cls() future.set_exception(exc_info) 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 Mopidy-dLeyna-1.2.0/mopidy_dleyna/translator.py0000664000175000017500000000740512771252615021527 0ustar tkemtkem00000000000000from __future__ import absolute_import, unicode_literals from mopidy import models _QUERY = { 'any': lambda caps: ( ' or '.join(s + ' {0} "{1}"' for s in caps & { 'DisplayName', 'Album', 'Artist', 'Genre' }) ), 'album': lambda caps: ( 'Album {0} "{1}"' if 'Album' in caps else None ), 'albumartist': lambda caps: ( 'Artist {0} "{1}" and TypeEx = "container.album.musicAlbum"' if 'Artist' in caps and 'TypeEx' in caps else None ), 'artist': lambda caps: ( 'Artist {0} "{1}"' if 'Artist' in caps else None ), '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' _REFS = { 'audio': models.Ref.track, 'container': models.Ref.directory, 'container.album': models.Ref.directory, 'container.album.musicAlbum': models.Ref.album, 'container.genre.musicGenre': models.Ref.directory, 'container.person.musicArtist': models.Ref.artist, 'container.storageFolder': models.Ref.directory, 'music': models.Ref.track } def _album(obj): try: name = obj['Album'] except KeyError: return None else: return models.Album(name=name, uri=None) def _artists(obj): return (models.Artist(name=name) for name in obj.get('Artists', [])) def _quote(s): return unicode(s).replace('\\', '\\\\').replace('"', '\\"') def ref(obj): type = obj.get('TypeEx', obj['Type']) try: translate = _REFS[type] except KeyError: raise ValueError('Object type "%s" not supported' % type) else: return translate(name=obj['DisplayName'], uri=obj['URI']) def album(obj): return models.Album( uri=obj['URI'], name=obj['DisplayName'], artists=list(_artists(obj)), num_tracks=obj.get('ItemCount', obj.get('ChildCount')), ) def artist(obj): return models.Artist(name=obj['DisplayName'], uri=obj['URI']) def track(obj): return models.Track( uri=obj['URI'], name=obj['DisplayName'], artists=list(_artists(obj)), album=_album(obj), genre=obj.get('Genre'), track_no=obj.get('TrackNumber'), date=obj.get('Date'), length=obj.get('Duration', 0) * 1000 or None, bitrate=obj.get('Bitrate', 0) * 8 or None ) def model(obj): type = obj.get('TypeEx', obj['Type']) if type == 'music' or type == 'audio': return track(obj) elif type == 'container.album.musicAlbum': return album(obj) elif type == 'container.person.musicArtist': return artist(obj) else: raise ValueError('Object type "%s" not supported' % type) def images(obj): if 'AlbumArtURL' in obj: return obj['URI'], [models.Image(uri=obj['AlbumArtURL'])] else: return obj['URI'], [] def query(query, exact, searchcaps): op = '=' if exact else 'contains' terms = [] for key, values in query.items(): try: translate = _QUERY[key] except KeyError: raise NotImplementedError('Keyword "%s" not supported' % key) else: fmt = translate(frozenset(searchcaps)) if fmt: terms.extend(fmt.format(op, _quote(value)) for value in values) else: raise NotImplementedError('Keyword "%s" not searchable' % key) return ('(%s)' % ') and ('.join(terms)) or '*' Mopidy-dLeyna-1.2.0/mopidy_dleyna/__init__.py0000664000175000017500000000176312771252615021076 0ustar tkemtkem00000000000000from __future__ import unicode_literals import os from mopidy import config, exceptions, ext __version__ = '1.2.0' 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_lookup_limit'] = config.Integer(minimum=0) schema['upnp_search_limit'] = config.Integer(minimum=0) schema['dbus_start_session'] = config.String() 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.2.0/mopidy_dleyna/playback.py0000664000175000017500000000104512720076412021107 0ustar tkemtkem00000000000000from __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): # TODO: GetCompatibleResources w/protocol_info client = self.backend.client try: obj = client.properties(uri, client.MEDIA_ITEM_IFACE).get() except Exception as e: logger.error('Error translating %s: %s', uri, e) else: return obj['URLs'][0] Mopidy-dLeyna-1.2.0/mopidy_dleyna/library.py0000664000175000017500000001637712771252615021012 0ustar tkemtkem00000000000000from __future__ import absolute_import, unicode_literals import collections import itertools import logging import operator from mopidy import backend, models import uritools from . import Extension, translator logger = logging.getLogger(__name__) BROWSE_FILTER = [ 'DisplayName', 'Type', 'TypeEx', 'URI' ] IMAGES_FILTER = [ 'AlbumArtURL', 'URI' ] LOOKUP_FILTER = SEARCH_FILTER = [ 'Album', 'AlbumArtURL', 'Artist', 'Artists', 'Bitrate', '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 iterate(func, translate, limit): def generate(future): offset = limit while future: objs, more = future.get() if more: future = func(offset, limit) else: future = None for obj in objs: try: result = translate(obj) except ValueError as e: logger.debug('Skipping %s: %s', obj.get('URI'), e) else: yield result offset += limit return generate(func(0, limit)) class dLeynaLibraryProvider(backend.LibraryProvider): root_directory = models.Ref.directory( uri=uritools.uricompose(Extension.ext_name), name='Digital Media Servers' ) def __init__(self, backend, config): super(dLeynaLibraryProvider, self).__init__(backend) ext_config = config[Extension.ext_name] self.__upnp_browse_limit = ext_config['upnp_browse_limit'] self.__upnp_lookup_limit = ext_config['upnp_lookup_limit'] self.__upnp_search_limit = ext_config['upnp_search_limit'] def browse(self, uri): if uri == self.root_directory.uri: refs = sorted(self.__servers, key=operator.attrgetter('name')) else: refs = self.__browse(uri) return list(refs) def get_images(self, uris): # TODO: suggest as API improvement uris = frozenset(uris) # group uris by authority (media server) queries = collections.defaultdict(list) for uri in uris.difference([self.root_directory.uri]): parts = uritools.urisplit(uri) baseuri = parts.scheme + '://' + parts.authority queries[baseuri].append(parts.path) # start searching - blocks only when iterating over results results = [] for baseuri, paths in queries.items(): try: iterable = self.__images(baseuri, paths) except NotImplementedError as e: logger.warn('Not retrieving images for %s: %s', baseuri, e) else: results.append(iterable) # merge results result = {} for uri, images in itertools.chain.from_iterable(results): result[uri] = tuple(images) if self.root_directory.uri in uris: result[self.root_directory.uri] = tuple() return result def lookup(self, uri): if uri == self.root_directory.uri: tracks = [] else: tracks = self.__lookup(uri) return list(tracks) def refresh(self, uri=None): logger.info('Refreshing dLeyna library') self.backend.client.rescan().get() def search(self, query=None, uris=None, exact=False): # sanitize uris - remove duplicates, replace root with server uris uris = set(uris or [self.root_directory.uri]) if self.root_directory.uri in uris: uris.update(ref.uri for ref in self.__servers) uris.remove(self.root_directory.uri) # start searching - blocks only when iterating over results results = [] for uri in uris: try: iterable = self.__search(uri, query, exact) except NotImplementedError as e: logger.warn('Not searching %s: %s', uri, e) else: results.append(iterable) if not results: return None # retrieve and merge search results - TODO: handle exceptions? result = collections.defaultdict(collections.OrderedDict) for model in itertools.chain.from_iterable(results): result[type(model)][model.uri] = model return models.SearchResult( albums=result[models.Album].values(), artists=result[models.Artist].values(), tracks=result[models.Track].values() ) def __browse(self, uri, filter=BROWSE_FILTER): client = self.backend.client obj = client.properties(uri, iface=client.MEDIA_OBJECT_IFACE).get() order = BROWSE_ORDER[translator.ref(obj).type] def browse(offset, limit): return client.browse(uri, offset, limit, filter, order).apply( lambda objs: (objs, limit and len(objs) == limit) ) return iterate(browse, translator.ref, self.__upnp_browse_limit) def __images(self, baseuri, paths, filter=IMAGES_FILTER): client = self.backend.client server = client.server(baseuri).get() # fall back on properties if path search is not available/enabled if self.__upnp_lookup_limit == 1 or 'Path' not in server['SearchCaps']: futures = [client.properties(baseuri + path) for path in paths] return (translator.images(f.get()) for f in futures) # use path search for retrieving multiple results at once root = server['Path'] def images(offset, limit): slice = paths[offset:offset + limit if limit else None] query = ' or '.join('Path = "%s%s"' % (root, p) for p in slice) return client.search(baseuri, query, 0, 0, filter).apply( lambda objs: (objs, limit and offset + limit < len(paths)) ) return iterate(images, translator.images, self.__upnp_lookup_limit) def __lookup(self, uri, filter=LOOKUP_FILTER): client = self.backend.client obj = client.properties(uri).get() if translator.ref(obj).type == models.Ref.TRACK: objs = [obj] else: objs = client.search(uri, LOOKUP_QUERY, filter=filter).get() return map(translator.track, objs) def __search(self, uri, query, exact, filter=SEARCH_FILTER): client = self.backend.client server = client.server(uri).get() if server['SearchCaps']: q = translator.query(query or {}, exact, server['SearchCaps']) else: raise NotImplementedError('Search is not supported by this device') def search(offset, limit): return client.search(uri, q, offset, limit, filter).apply( lambda objs: (objs, limit and len(objs) == limit) ) return iterate(search, translator.model, self.__upnp_search_limit) @property def __servers(self): for server in self.backend.client.servers().get(): name = server.get('FriendlyName', server['DisplayName']) yield models.Ref.directory(name=name, uri=server['URI']) Mopidy-dLeyna-1.2.0/setup.cfg0000644000175000017500000000035012771253017015733 0ustar tkemtkem00000000000000[flake8] application-import-names = mopidy_dleyna,tests exclude = .git,.tox [wheel] universal = 1 [build_sphinx] source-dir = docs/ build-dir = docs/_build all_files = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 Mopidy-dLeyna-1.2.0/tox.ini0000664000175000017500000000100712720076412015423 0ustar tkemtkem00000000000000[tox] envlist = check-manifest,docs,flake8,py27 [testenv] deps = mock pytest pytest-cov pytest-xdist commands = py.test --basetemp={envtmpdir} --cov=mopidy_dleyna {posargs} [testenv:check-manifest] deps = check-manifest commands = check-manifest skip_install = true [testenv:docs] deps = sphinx commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html [testenv:flake8] deps = flake8 flake8-import-order commands = flake8 skip_install = true Mopidy-dLeyna-1.2.0/setup.py0000664000175000017500000000244012720076412015624 0ustar tkemtkem00000000000000from setuptools import find_packages, setup def get_version(filename): from re import findall with open(filename) as f: metadata = dict(findall("__([a-z]+)__ = '([^']+)'", f.read())) 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', ], )