Mopidy-TuneIn-1.0.0/0000755000175000017500000000000013577726166014067 5ustar nicknick00000000000000Mopidy-TuneIn-1.0.0/.circleci/0000755000175000017500000000000013577726166015722 5ustar nicknick00000000000000Mopidy-TuneIn-1.0.0/.circleci/config.yml0000644000175000017500000000206513577413040017675 0ustar nicknick00000000000000version: 2.1 orbs: codecov: codecov/codecov@1.0.5 workflows: version: 2 test: jobs: - py38 - py37 - black - check-manifest - flake8 jobs: py38: &test-template docker: - image: mopidy/ci-python:3.8 steps: - checkout - restore_cache: name: Restoring tox cache key: tox-v1-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.cfg" }} - run: name: Run tests command: | tox -e $CIRCLE_JOB -- \ --junit-xml=test-results/pytest/results.xml \ --cov-report=xml - save_cache: name: Saving tox cache key: tox-v1-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.cfg" }} paths: - ./.tox - ~/.cache/pip - codecov/upload: file: coverage.xml - store_test_results: path: test-results py37: <<: *test-template docker: - image: mopidy/ci-python:3.7 black: *test-template check-manifest: *test-template flake8: *test-template Mopidy-TuneIn-1.0.0/CHANGELOG.rst0000644000175000017500000000441713577725657016122 0ustar nicknick00000000000000********* Changelog ********* v1.0.0 (2019-12-22) =================== - Depend on final release of Mopidy 3.0.0. v1.0.0rc1 (21/12/19) =================== Alpha release. - Require Mopidy >= 3.0.0a5. (PR: #36) - Require Python >= 3.7. (PR: #36) - Update project setup. (PR: #36) - Support filtering search results by station or program. (PR: #34) v0.4.1 (2016-06-14) =================== - Port timeout fix for Mopidy's internal stream unwrapping code from mopidy/mopidy#1522 (Fixes: #31) v0.4.0 (2016-02-16) =================== - Borrow Mopidy's internal stream unwrapping to avoid incompatibilities with Mopidy v2.0.0 (PR: #28) - Improved handling of malformed pls playlists. v0.3.0 (2016-02-06) =================== - Requires Mopidy v1.1 - Respect user's Mopidy proxy configuration and set user-agent. - Utilise Mopidy's nested playlist handling (Fixes: #23 PR: #22) v0.2.2 (2015-04-24) =================== - Fix infinite loop when adding some stations, again (my bad). v0.2.1 (2015-04-24) =================== - Fix infinite loop when adding some stations. (PR: #17) v0.2 (2015-03-26) ================= - Fix utf-8 encoding for searches. (PR: #15) - Fixed inaccessible stream URIs identified as recursive playlist and not using the remaining stream URIs. - Update to work with new playback API in Mopidy 1.0. - Update to work with new backend search API in Mopidy 1.0. - Requires Mopidy v1.0. v0.1.3 (2014-01-22) =================== - Don't submit a search (and receive an error) when the query is empty. - Improved nested playlist support. - Support for 'protocol rollover' style ASX playlists. - ASF HTTP streams in ASX playlists are converted to MMS steams. - Ignore nested subtypes in content-type header field to fix #5. - Added support for a station's logo. - Include currently playing info. - Unplayable streams now correctly recognised by Mopidy and playback fails rather than continuing to play the previous track. v0.1.2 (2014-04-13) =================== - Improved stream selection for stations using PLS format playlists. - Added suggested additional gstreamer plugin packages. v0.1.1 (2014-02-24) =================== - Fixed package description typo and capitalisation inconsistency in name! v0.1.0 (2014-02-23) =================== - Initial release. Mopidy-TuneIn-1.0.0/LICENSE0000644000175000017500000002613513414754525015071 0ustar nicknick00000000000000 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 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-TuneIn-1.0.0/MANIFEST.in0000644000175000017500000000041213577413040015602 0ustar nicknick00000000000000include *.py include *.rst include .mailmap include LICENSE include MANIFEST.in include pyproject.toml include tox.ini recursive-include .circleci * recursive-include .github * include mopidy_*/ext.conf recursive-include tests *.py recursive-include tests/data * Mopidy-TuneIn-1.0.0/Mopidy_TuneIn.egg-info/0000755000175000017500000000000013577726166020304 5ustar nicknick00000000000000Mopidy-TuneIn-1.0.0/Mopidy_TuneIn.egg-info/PKG-INFO0000644000175000017500000001015013577726166021376 0ustar nicknick00000000000000Metadata-Version: 2.1 Name: Mopidy-TuneIn Version: 1.0.0 Summary: Mopidy extension for playing music from TuneIn Home-page: https://github.com/kingosticks/mopidy-tunein Author: Nick Steel Author-email: nickasteel@gmail.com License: Apache License, Version 2.0 Description: ************* Mopidy-TuneIn ************* .. image:: https://img.shields.io/pypi/v/Mopidy-TuneIn :target: https://pypi.org/project/Mopidy-TuneIn/ :alt: Latest PyPI version .. image:: https://img.shields.io/circleci/build/gh/kingosticks/mopidy-tunein :target: https://circleci.com/gh/kingosticks/mopidy-tunein :alt: CircleCI build status .. image:: https://img.shields.io/codecov/c/gh/kingosticks/mopidy-tunein :target: https://codecov.io/gh/kingosticks/mopidy-tunein :alt: Test coverage `Mopidy `_ extension for playing music from `TuneIn `_. Listen to the world’s radio with 70,000 stations of music, sports and news streaming from every continent. Acknowledgement and thanks to Marius Wyss for his original version of this extension and Brian Hornsby's `XBMC plugin `_ that was based on. This product uses TuneIn but is not endorsed, certified or otherwise approved in any way by TuneIn. TuneIn is the registered trade mark of TuneIn Inc. Installation ============ Install by running:: python3 -m pip install Mopidy-TuneIn Or, if available, install the Debian/Ubuntu package from `apt.mopidy.com `_. Some radio streams may require additional audio plugins. These can be found in the gstreamer plugin packages for your system. For Mopidy v3.0.0 and later, these might include: * `gstreamer1.0-plugins-ugly` * `gstreamer1.0-plugins-bad` * `gstreamer1.0-libav` Known issues ============ The following functionality is not yet implemented: * Playback of podcasts/shows. * User login and access to saved stations. Configuration ============= You can add configuration for Mopidy-TuneIn to your Mopidy configuration file but it's not required:: [tunein] timeout = 5000 The following configuration values are available: - ``tunein/enabled``: If the TuneIn extension should be enabled or not. Defaults to true. - ``tunein/filter``: Limit the search results. ``station``, ``program`` or leave blank to disable filtering. Defaults to blank. - ``tunein/timeout``: Milliseconds before giving up waiting for results. Defaults to ``5000``. Project resources ================= - `Source code `_ - `Issue tracker `_ - `Changelog `_ Credits ======= - Original author: `Nick Steel `__ - Current maintainer: `Nick Steel `__ - `Contributors `_ 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 :: 3 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Topic :: Multimedia :: Sound/Audio :: Players Requires-Python: >=3.7 Provides-Extra: lint Provides-Extra: release Provides-Extra: test Provides-Extra: dev Mopidy-TuneIn-1.0.0/Mopidy_TuneIn.egg-info/SOURCES.txt0000644000175000017500000000105513577726166022171 0ustar nicknick00000000000000CHANGELOG.rst LICENSE MANIFEST.in README.rst pyproject.toml setup.cfg setup.py tox.ini .circleci/config.yml Mopidy_TuneIn.egg-info/PKG-INFO Mopidy_TuneIn.egg-info/SOURCES.txt Mopidy_TuneIn.egg-info/dependency_links.txt Mopidy_TuneIn.egg-info/entry_points.txt Mopidy_TuneIn.egg-info/not-zip-safe Mopidy_TuneIn.egg-info/requires.txt Mopidy_TuneIn.egg-info/top_level.txt mopidy_tunein/__init__.py mopidy_tunein/actor.py mopidy_tunein/ext.conf mopidy_tunein/translator.py mopidy_tunein/tunein.py tests/__init__.py tests/test_extension.py tests/test_playlists.pyMopidy-TuneIn-1.0.0/Mopidy_TuneIn.egg-info/dependency_links.txt0000644000175000017500000000000113577726166024352 0ustar nicknick00000000000000 Mopidy-TuneIn-1.0.0/Mopidy_TuneIn.egg-info/entry_points.txt0000644000175000017500000000005713577726166023604 0ustar nicknick00000000000000[mopidy.ext] tunein = mopidy_tunein:Extension Mopidy-TuneIn-1.0.0/Mopidy_TuneIn.egg-info/not-zip-safe0000644000175000017500000000000113577002107022510 0ustar nicknick00000000000000 Mopidy-TuneIn-1.0.0/Mopidy_TuneIn.egg-info/requires.txt0000644000175000017500000000046413577726166022710 0ustar nicknick00000000000000Mopidy>=3.0.0 Pykka>=2.0.1 requests>=2.0.0 setuptools [dev] black check-manifest flake8 flake8-bugbear flake8-import-order isort[pyproject] twine wheel pytest pytest-cov [lint] black check-manifest flake8 flake8-bugbear flake8-import-order isort[pyproject] [release] twine wheel [test] pytest pytest-cov Mopidy-TuneIn-1.0.0/Mopidy_TuneIn.egg-info/top_level.txt0000644000175000017500000000001613577726166023033 0ustar nicknick00000000000000mopidy_tunein Mopidy-TuneIn-1.0.0/PKG-INFO0000644000175000017500000001015013577726166015161 0ustar nicknick00000000000000Metadata-Version: 2.1 Name: Mopidy-TuneIn Version: 1.0.0 Summary: Mopidy extension for playing music from TuneIn Home-page: https://github.com/kingosticks/mopidy-tunein Author: Nick Steel Author-email: nickasteel@gmail.com License: Apache License, Version 2.0 Description: ************* Mopidy-TuneIn ************* .. image:: https://img.shields.io/pypi/v/Mopidy-TuneIn :target: https://pypi.org/project/Mopidy-TuneIn/ :alt: Latest PyPI version .. image:: https://img.shields.io/circleci/build/gh/kingosticks/mopidy-tunein :target: https://circleci.com/gh/kingosticks/mopidy-tunein :alt: CircleCI build status .. image:: https://img.shields.io/codecov/c/gh/kingosticks/mopidy-tunein :target: https://codecov.io/gh/kingosticks/mopidy-tunein :alt: Test coverage `Mopidy `_ extension for playing music from `TuneIn `_. Listen to the world’s radio with 70,000 stations of music, sports and news streaming from every continent. Acknowledgement and thanks to Marius Wyss for his original version of this extension and Brian Hornsby's `XBMC plugin `_ that was based on. This product uses TuneIn but is not endorsed, certified or otherwise approved in any way by TuneIn. TuneIn is the registered trade mark of TuneIn Inc. Installation ============ Install by running:: python3 -m pip install Mopidy-TuneIn Or, if available, install the Debian/Ubuntu package from `apt.mopidy.com `_. Some radio streams may require additional audio plugins. These can be found in the gstreamer plugin packages for your system. For Mopidy v3.0.0 and later, these might include: * `gstreamer1.0-plugins-ugly` * `gstreamer1.0-plugins-bad` * `gstreamer1.0-libav` Known issues ============ The following functionality is not yet implemented: * Playback of podcasts/shows. * User login and access to saved stations. Configuration ============= You can add configuration for Mopidy-TuneIn to your Mopidy configuration file but it's not required:: [tunein] timeout = 5000 The following configuration values are available: - ``tunein/enabled``: If the TuneIn extension should be enabled or not. Defaults to true. - ``tunein/filter``: Limit the search results. ``station``, ``program`` or leave blank to disable filtering. Defaults to blank. - ``tunein/timeout``: Milliseconds before giving up waiting for results. Defaults to ``5000``. Project resources ================= - `Source code `_ - `Issue tracker `_ - `Changelog `_ Credits ======= - Original author: `Nick Steel `__ - Current maintainer: `Nick Steel `__ - `Contributors `_ 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 :: 3 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Topic :: Multimedia :: Sound/Audio :: Players Requires-Python: >=3.7 Provides-Extra: lint Provides-Extra: release Provides-Extra: test Provides-Extra: dev Mopidy-TuneIn-1.0.0/README.rst0000644000175000017500000000525413577431503015550 0ustar nicknick00000000000000************* Mopidy-TuneIn ************* .. image:: https://img.shields.io/pypi/v/Mopidy-TuneIn :target: https://pypi.org/project/Mopidy-TuneIn/ :alt: Latest PyPI version .. image:: https://img.shields.io/circleci/build/gh/kingosticks/mopidy-tunein :target: https://circleci.com/gh/kingosticks/mopidy-tunein :alt: CircleCI build status .. image:: https://img.shields.io/codecov/c/gh/kingosticks/mopidy-tunein :target: https://codecov.io/gh/kingosticks/mopidy-tunein :alt: Test coverage `Mopidy `_ extension for playing music from `TuneIn `_. Listen to the world’s radio with 70,000 stations of music, sports and news streaming from every continent. Acknowledgement and thanks to Marius Wyss for his original version of this extension and Brian Hornsby's `XBMC plugin `_ that was based on. This product uses TuneIn but is not endorsed, certified or otherwise approved in any way by TuneIn. TuneIn is the registered trade mark of TuneIn Inc. Installation ============ Install by running:: python3 -m pip install Mopidy-TuneIn Or, if available, install the Debian/Ubuntu package from `apt.mopidy.com `_. Some radio streams may require additional audio plugins. These can be found in the gstreamer plugin packages for your system. For Mopidy v3.0.0 and later, these might include: * `gstreamer1.0-plugins-ugly` * `gstreamer1.0-plugins-bad` * `gstreamer1.0-libav` Known issues ============ The following functionality is not yet implemented: * Playback of podcasts/shows. * User login and access to saved stations. Configuration ============= You can add configuration for Mopidy-TuneIn to your Mopidy configuration file but it's not required:: [tunein] timeout = 5000 The following configuration values are available: - ``tunein/enabled``: If the TuneIn extension should be enabled or not. Defaults to true. - ``tunein/filter``: Limit the search results. ``station``, ``program`` or leave blank to disable filtering. Defaults to blank. - ``tunein/timeout``: Milliseconds before giving up waiting for results. Defaults to ``5000``. Project resources ================= - `Source code `_ - `Issue tracker `_ - `Changelog `_ Credits ======= - Original author: `Nick Steel `__ - Current maintainer: `Nick Steel `__ - `Contributors `_ Mopidy-TuneIn-1.0.0/mopidy_tunein/0000755000175000017500000000000013577726166016752 5ustar nicknick00000000000000Mopidy-TuneIn-1.0.0/mopidy_tunein/__init__.py0000644000175000017500000000135413577413040021046 0ustar nicknick00000000000000import pathlib import pkg_resources from mopidy import config, ext __version__ = pkg_resources.get_distribution("Mopidy-TuneIn").version class Extension(ext.Extension): dist_name = "Mopidy-TuneIn" ext_name = "tunein" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["timeout"] = config.Integer(minimum=0) schema["filter"] = config.String( optional=True, choices=("station", "program") ) return schema def setup(self, registry): from .actor import TuneInBackend registry.add("backend", TuneInBackend) Mopidy-TuneIn-1.0.0/mopidy_tunein/actor.py0000644000175000017500000002163613577413040020424 0ustar nicknick00000000000000import logging import time import pykka import requests from mopidy import backend, exceptions, httpclient from mopidy.audio import scan # TODO: Something else, using internal APIs is not cool. from mopidy.internal import http, playlists from mopidy.models import Ref, SearchResult from mopidy_tunein import translator, tunein, Extension, __version__ logger = logging.getLogger(__name__) def get_requests_session(proxy_config): user_agent = f"{Extension.dist_name}/{__version__}" proxy = httpclient.format_proxy(proxy_config) full_user_agent = httpclient.format_user_agent(user_agent) session = requests.Session() session.proxies.update({"http": proxy, "https": proxy}) session.headers.update({"user-agent": full_user_agent}) return session class TuneInBackend(pykka.ThreadingActor, backend.Backend): uri_schemes = ["tunein"] def __init__(self, config, audio): super().__init__() self._session = get_requests_session(config["proxy"]) self._timeout = config["tunein"]["timeout"] self._filter = config["tunein"]["filter"] self._scanner = scan.Scanner( timeout=config["tunein"]["timeout"], proxy_config=config["proxy"] ) self.tunein = tunein.TuneIn( config["tunein"]["timeout"], config["tunein"]["filter"], self._session, ) self.library = TuneInLibrary(self) self.playback = TuneInPlayback(audio=audio, backend=self) class TuneInLibrary(backend.LibraryProvider): root_directory = Ref.directory(uri="tunein:root", name="TuneIn") def __init__(self, backend): super().__init__(backend) def browse(self, uri): result = [] variant, identifier = translator.parse_uri(uri) logger.debug(f"Browsing {uri!r}") if variant == "root": for category in self.backend.tunein.categories(): result.append(translator.category_to_ref(category)) elif variant == "category" and identifier: for section in self.backend.tunein.categories(identifier): result.append(translator.section_to_ref(section, identifier)) elif variant == "location" and identifier: for location in self.backend.tunein.locations(identifier): result.append(translator.section_to_ref(location, "local")) for station in self.backend.tunein.stations(identifier): result.append(translator.station_to_ref(station)) elif variant == "section" and identifier: if self.backend.tunein.related(identifier): result.append( Ref.directory( uri=f"tunein:related:{identifier}", name="Related" ) ) if self.backend.tunein.shows(identifier): result.append( Ref.directory( uri=f"tunein:shows:{identifier}", name="Shows" ) ) for station in self.backend.tunein.featured(identifier): result.append(translator.section_to_ref(station)) for station in self.backend.tunein.local(identifier): result.append(translator.station_to_ref(station)) for station in self.backend.tunein.stations(identifier): result.append(translator.station_to_ref(station)) elif variant == "related" and identifier: for section in self.backend.tunein.related(identifier): result.append(translator.section_to_ref(section)) elif variant == "shows" and identifier: for show in self.backend.tunein.shows(identifier): result.append(translator.show_to_ref(show)) elif variant == "episodes" and identifier: for episode in self.backend.tunein.episodes(identifier): result.append(translator.station_to_ref(episode)) else: logger.debug(f"Unknown URI: {uri!r}") return result def refresh(self, uri=None): self.backend.tunein.reload() def lookup(self, uri): variant, identifier = translator.parse_uri(uri) if variant != "station": return [] station = self.backend.tunein.station(identifier) if not station: return [] track = translator.station_to_track(station) return [track] def get_images(self, uris): results = {} for uri in uris: variant, identifier = translator.parse_uri(uri) if variant != "station": continue station = self.backend.tunein.station(identifier) image = translator.station_to_image(station) if image is not None: results[uri] = [image] return results def search(self, query=None, uris=None, exact=False): if query is None or not query: return tunein_query = translator.mopidy_to_tunein_query(query) tracks = [] for station in self.backend.tunein.search(tunein_query): track = translator.station_to_track(station) tracks.append(track) return SearchResult(uri="tunein:search", tracks=tracks) class TuneInPlayback(backend.PlaybackProvider): def translate_uri(self, uri): variant, identifier = translator.parse_uri(uri) station = self.backend.tunein.station(identifier) if not station: return None stream_uris = self.backend.tunein.tune(station) while stream_uris: uri = stream_uris.pop(0) logger.debug(f"Looking up URI: {uri!r}") new_uri = self.unwrap_stream(uri) if new_uri: return new_uri else: logger.debug("Mopidy translate_uri failed.") new_uris = self.backend.tunein.parse_stream_url(uri) if new_uris == [uri]: logger.debug(f"Last attempt, play stream anyway: {uri!r}") return uri stream_uris.extend(new_uris) logger.debug("TuneIn lookup failed.") return None def unwrap_stream(self, uri): unwrapped_uri, _ = _unwrap_stream( uri, timeout=self.backend._timeout, scanner=self.backend._scanner, requests_session=self.backend._session, ) return unwrapped_uri # Shamelessly taken from mopidy.stream.actor def _unwrap_stream(uri, timeout, scanner, requests_session): """ Get a stream URI from a playlist URI, ``uri``. Unwraps nested playlists until something that's not a playlist is found or the ``timeout`` is reached. """ original_uri = uri seen_uris = set() deadline = time.time() + timeout while time.time() < deadline: if uri in seen_uris: logger.info( f"Unwrapping stream from URI ({uri!r}) failed: " "playlist referenced itself", ) return None, None else: seen_uris.add(uri) logger.debug(f"Unwrapping stream from URI: {uri!r}") try: scan_timeout = deadline - time.time() if scan_timeout < 0: logger.info( f"Unwrapping stream from URI ({uri!r}) failed: " f"timed out in {timeout}ms", ) return None, None scan_result = scanner.scan(uri, timeout=scan_timeout) except exceptions.ScannerError as exc: logger.debug(f"GStreamer failed scanning URI ({uri!r}): {exc}") scan_result = None if scan_result is not None: if scan_result.playable or ( not scan_result.mime.startswith("text/") and not scan_result.mime.startswith("application/") ): logger.debug( f"Unwrapped potential {scan_result.mime} stream: {uri!r}" ) return uri, scan_result download_timeout = deadline - time.time() if download_timeout < 0: logger.info( f"Unwrapping stream from URI ({uri!r}) failed: timed out in {timeout}ms" ) return None, None content = http.download( requests_session, uri, timeout=download_timeout / 1000 ) if content is None: logger.info( f"Unwrapping stream from URI ({original_uri!r}) failed: " f"error downloading URI {uri!r}", ) return None, None uris = playlists.parse(content) if not uris: logger.debug( f"Failed parsing URI ({uri!r}) as playlist; " "found potential stream.", ) return uri, None # TODO Test streams and return first that seems to be playable logger.debug( f"Parsed playlist ({uri!r}) and found new URI: {uris[0]!r}" ) uri = uris[0] Mopidy-TuneIn-1.0.0/mopidy_tunein/ext.conf0000644000175000017500000000006213577413040020377 0ustar nicknick00000000000000[tunein] enabled = true filter = timeout = 5000 Mopidy-TuneIn-1.0.0/mopidy_tunein/translator.py0000644000175000017500000000533113577413040021477 0ustar nicknick00000000000000import logging import re from urllib import request from mopidy.models import Album, Artist, Image, Ref, Track from mopidy_tunein.tunein import TuneIn logger = logging.getLogger(__name__) def unparse_uri(variant, identifier): return f"tunein:{variant}:{identifier}" def parse_uri(uri): result = re.findall(r"^tunein:([a-z]+)(?::(\w+))?$", uri) if result: return result[0] return None, None def station_to_ref(station): if station["type"] != "audio": logger.debug(f'Expecting station but got {station["type"]}') guide_id = station.get("guide_id", "??") uri = unparse_uri("station", guide_id) name = station.get("text", station["URL"]) # TODO: Should the name include 'now playing' for all stations? if get_id_type(guide_id) == TuneIn.ID_TOPIC: name = f'{name} [{station.get("subtext", "??")}]' return Ref.track(uri=uri, name=name) def station_to_track(station): ref = station_to_ref(station) return Track( uri=ref.uri, name=station.get("subtext", ref.name), album=Album(name=ref.name, uri=ref.uri), artists=[Artist(name=ref.name, uri=ref.uri)], ) def station_to_image(station): if station is not None and "image" in station: return Image(uri=station["image"]) def show_to_ref(show): if show["item"] != "show": logger.debug(f'Expecting show but got {show["item"]}') uri = unparse_uri("episodes", show.get("guide_id", "??")) name = show.get("text", show["URL"]) return Ref.directory(uri=uri, name=name) def category_to_ref(category): uri = unparse_uri("category", category["key"]) return Ref.directory(uri=uri, name=category["text"]) def section_to_ref(section, identifier=""): if section.get("type", "link") == "audio": return station_to_ref(section) guide_id = section.get("guide_id", "??") if get_id_type(guide_id) == TuneIn.ID_REGION or identifier == "local": uri = unparse_uri("location", guide_id) else: uri = unparse_uri("section", guide_id) return Ref.directory(uri=uri, name=section["text"]) def get_id_type(guide_id): return { "p": TuneIn.ID_PROGRAM, "s": TuneIn.ID_STATION, "g": TuneIn.ID_GROUP, "t": TuneIn.ID_TOPIC, "c": TuneIn.ID_CATEGORY, "r": TuneIn.ID_REGION, "f": TuneIn.ID_PODCAST, "a": TuneIn.ID_AFFILIATE, "e": TuneIn.ID_STREAM, }.get(guide_id[0], TuneIn.ID_UNKNOWN) def mopidy_to_tunein_query(mopidy_query): tunein_query = [] for (field, values) in mopidy_query.items(): for value in values: if field == "any": tunein_query.append(value) query = " ".join(tunein_query) return request.pathname2url(query) Mopidy-TuneIn-1.0.0/mopidy_tunein/tunein.py0000644000175000017500000003203013577413040020604 0ustar nicknick00000000000000import configparser import io import logging import re import time from collections import OrderedDict from contextlib import closing from urllib.parse import urlparse import requests import xml.etree.ElementTree as elementtree # noqa: N813 logger = logging.getLogger(__name__) class PlaylistError(Exception): pass class cache: # noqa N801 # TODO: merge this to util library (copied from mopidy-spotify) def __init__(self, ctl=0, ttl=3600): self.cache = {} self.ctl = ctl self.ttl = ttl self._call_count = 0 def __call__(self, func): def _memoized(*args): now = time.time() try: value, last_update = self.cache[args] age = now - last_update if self._call_count > self.ctl or age > self.ttl: self._call_count = 0 raise AttributeError if self.ctl: self._call_count += 1 return value except (KeyError, AttributeError): value = func(*args) if value: self.cache[args] = (value, now) return value except TypeError: return func(*args) def clear(): self.cache.clear() _memoized.clear = clear return _memoized def parse_m3u(data): # Copied from mopidy.audio.playlists # Mopidy version expects a header but it's not always present for line in data.splitlines(): if not line.strip() or line.startswith(b"#"): continue try: line = line.decode() except UnicodeDecodeError: continue yield line.strip() def parse_pls(data): # Copied from mopidy.audio.playlists try: cp = configparser.RawConfigParser() cp.read_string(data.decode()) except configparser.Error: return for section in cp.sections(): if section.lower() != "playlist": continue for i in range(cp.getint(section, "numberofentries")): try: # TODO: Remove this horrible hack to avoid adverts if cp.has_option(section, f"length{i + 1}"): if cp.get(section, f"length{i + 1}") == "-1": yield cp.get(section, f"file{i + 1}").strip("\"'") else: yield cp.get(section, f"file{i + 1}").strip("\"'") except configparser.NoOptionError: return def fix_asf_uri(uri): return re.sub(r"http://(.+\?mswmext=\.asf)", r"mms://\1", uri, flags=re.I) def parse_old_asx(data): try: cp = configparser.RawConfigParser() cp.read_string(data.decode()) except configparser.Error: return for section in cp.sections(): if section.lower() != "reference": continue for option in cp.options(section): if option.lower().startswith("ref"): uri = cp.get(section, option).lower() yield fix_asf_uri(uri.strip()) def parse_new_asx(data): # Copied from mopidy.audio.playlists try: # Last element will be root. for _event, element in elementtree.iterparse(io.BytesIO(data)): element.tag = element.tag.lower() # normalize except elementtree.ParseError: return for ref in element.findall("entry/ref[@href]"): yield fix_asf_uri(ref.get("href", "").strip()) for entry in element.findall("entry[@href]"): yield fix_asf_uri(entry.get("href", "").strip()) def parse_asx(data): if b"asx" in data[0:50].lower(): return parse_new_asx(data) else: return parse_old_asx(data) # This is all broken: mopidy/mopidy#225 # from gi.repository import TotemPlParser # def totem_plparser(uri): # results = [] # def entry_parsed(parser, uri, metadata): # results.append(uri) # parser = TotemPlParser.Parser.new() # someid = parser.connect('entry-parsed', entry_parsed) # res = parser.parse(uri, False) # parser.disconnect(someid) # if res != TotemPlParser.ParserResult.SUCCESS: # logger.debug('Failed to parse playlist') # return results def find_playlist_parser(extension, content_type): extension_map = { ".asx": parse_asx, ".wax": parse_asx, ".m3u": parse_m3u, ".pls": parse_pls, } content_type_map = { "video/x-ms-asf": parse_asx, "application/x-mpegurl": parse_m3u, "audio/x-scpls": parse_pls, } parser = extension_map.get(extension, None) if not parser and content_type: # Annoying case where the url gave us no hints so try and work it out # from the header's content-type instead. # This might turn out to be server-specific... parser = content_type_map.get(content_type.lower(), None) return parser class TuneIn: """Wrapper for the TuneIn API.""" ID_PROGRAM = "program" ID_STATION = "station" ID_GROUP = "group" ID_TOPIC = "topic" ID_CATEGORY = "category" ID_REGION = "region" ID_PODCAST = "podcast_category" ID_AFFILIATE = "affiliate" ID_STREAM = "stream" ID_UNKNOWN = "unknown" def __init__(self, timeout, filter_=None, session=None): self._base_uri = "http://opml.radiotime.com/%s" self._session = session or requests.Session() self._timeout = timeout / 1000.0 if filter_ in [TuneIn.ID_PROGRAM, TuneIn.ID_STATION]: self._filter = f"&filter={filter_[0]}" else: self._filter = "" self._stations = {} def reload(self): self._stations.clear() self._tunein.clear() self._get_playlist.clear() def _flatten(self, data): results = [] for item in data: if "children" in item: results.extend(item["children"]) else: results.append(item) return results def _filter_results(self, data, section_name=None, map_func=None): results = [] def grab_item(item): if "guide_id" not in item: return if map_func: station = map_func(item) elif item.get("type", "link") == "link": results.append(item) return else: station = item self._stations[station["guide_id"]] = station results.append(station) for item in data: if section_name is not None: section_key = item.get("key", "").lower() if section_key.startswith(section_name.lower()): for child in item["children"]: grab_item(child) else: grab_item(item) return results def categories(self, category=""): if category == "location": args = "&id=r0" # Annoying special case elif category == "language": args = "&c=lang" return [] # TuneIn's API is a mess here, cba else: args = "&c=" + category # Take a copy so we don't modify the cached data results = list(self._tunein("Browse.ashx", args)) if category in ("podcast", "local"): # Flatten the results! results = self._filter_results(self._flatten(results)) elif category == "": trending = { "text": "Trending", "key": "trending", "type": "link", "URL": self._base_uri % "Browse.ashx?c=trending", } # Filter out the language root category for now results = [x for x in results if x["key"] != "language"] results.append(trending) else: results = self._filter_results(results) return results def locations(self, location): args = "&id=" + location results = self._tunein("Browse.ashx", args) # TODO: Support filters here return [x for x in results if x.get("type", "") == "link"] def _browse(self, section_name, guide_id): args = "&id=" + guide_id results = self._tunein("Browse.ashx", args) return self._filter_results(results, section_name) def featured(self, guide_id): return self._browse("Featured", guide_id) def local(self, guide_id): return self._browse("Local", guide_id) def stations(self, guide_id): return self._browse("Station", guide_id) def related(self, guide_id): return self._browse("Related", guide_id) def shows(self, guide_id): return self._browse("Show", guide_id) def episodes(self, guide_id): args = f"&c=pbrowse&id={guide_id}" results = self._tunein("Tune.ashx", args) return self._filter_results(results, "Topic") def _map_listing(self, listing): # We've already checked 'guide_id' exists url_args = f'Tune.ashx?id={listing["guide_id"]}' return { "text": listing.get("name", "???"), "guide_id": listing["guide_id"], "type": "audio", "image": listing.get("logo", ""), "subtext": listing.get("slogan", ""), "URL": self._base_uri % url_args, } def _station_info(self, station_id): logger.debug(f"Fetching info for station {station_id}") args = f"&c=composite&detail=listing&id={station_id}" results = self._tunein("Describe.ashx", args) listings = self._filter_results(results, "Listing", self._map_listing) if listings: return listings[0] def parse_stream_url(self, url): logger.debug(f"Extracting URIs from {url!r}") extension = urlparse(url).path[-4:] if extension in [".mp3", ".wma"]: return [url] # Catch these easy ones results = [] playlist_data, content_type = self._get_playlist(url) if playlist_data: parser = find_playlist_parser(extension, content_type) if parser: try: results = [ u for u in parser(playlist_data) if u and u != url ] except Exception as e: logger.error(f"TuneIn playlist parsing failed {e}") if not results: playlist_str = playlist_data.decode(errors="ignore") logger.debug( f"Parsing failure, malformed playlist: {playlist_str}" ) elif content_type: results = [url] logger.debug(f"Got {results}") return list(OrderedDict.fromkeys(results)) def tune(self, station): logger.debug(f'Tuning station id {station["guide_id"]}') args = f'&id={station["guide_id"]}' stream_uris = [] for stream in self._tunein("Tune.ashx", args): if "url" in stream: stream_uris.append(stream["url"]) if not stream_uris: logger.error(f'Failed to tune station id {station["guide_id"]}') return list(OrderedDict.fromkeys(stream_uris)) def station(self, station_id): if station_id in self._stations: station = self._stations[station_id] else: station = self._station_info(station_id) self._stations["station_id"] = station return station def search(self, query): # "Search.ashx?query=" + query + filterVal if not query: logger.debug("Empty search query") return [] logger.debug(f"Searching TuneIn for '{query}'") args = f"&query={query}{self._filter}" search_results = self._tunein("Search.ashx", args) results = [] for item in self._flatten(search_results): if item.get("type", "") == "audio": # Only return stations self._stations[item["guide_id"]] = item results.append(item) return results @cache() def _tunein(self, variant, args): uri = (self._base_uri % variant) + f"?render=json{args}" logger.debug(f"TuneIn request: {uri!r}") try: with closing(self._session.get(uri, timeout=self._timeout)) as r: r.raise_for_status() return r.json()["body"] except Exception as e: logger.info(f"TuneIn API request for {variant} failed: {e}") return {} @cache() def _get_playlist(self, uri): data, content_type = None, None try: # Defer downloading the body until know it's not a stream with closing( self._session.get(uri, timeout=self._timeout, stream=True) ) as r: r.raise_for_status() content_type = r.headers.get("content-type", "audio/mpeg") logger.debug(f"{uri} has content-type: {content_type}") if content_type != "audio/mpeg": data = r.content except Exception as e: logger.info(f"TuneIn playlist request for {uri} failed: {e}") return (data, content_type) Mopidy-TuneIn-1.0.0/pyproject.toml0000644000175000017500000000052613577413040016766 0ustar nicknick00000000000000[build-system] requires = ["setuptools >= 30.3.0", "wheel"] [tool.black] target-version = ["py37", "py38"] line-length = 80 [tool.isort] multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 use_parentheses = true line_length = 88 known_tests = "tests" sections = "FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,TESTS,LOCALFOLDER" Mopidy-TuneIn-1.0.0/setup.cfg0000644000175000017500000000255213577726166015714 0ustar nicknick00000000000000[metadata] name = Mopidy-TuneIn version = 1.0.0 url = https://github.com/kingosticks/mopidy-tunein author = Nick Steel author_email = nickasteel@gmail.com license = Apache License, Version 2.0 license_file = LICENSE description = Mopidy extension for playing music from TuneIn long_description = file: README.rst classifiers = Environment :: No Input/Output (Daemon) Intended Audience :: End Users/Desktop License :: OSI Approved :: Apache Software License Operating System :: OS Independent Programming Language :: Python :: 3 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Topic :: Multimedia :: Sound/Audio :: Players [options] zip_safe = False include_package_data = True packages = find: python_requires = >= 3.7 install_requires = Mopidy >= 3.0.0 Pykka >= 2.0.1 requests >= 2.0.0 setuptools [options.extras_require] lint = black check-manifest flake8 flake8-bugbear flake8-import-order isort[pyproject] release = twine wheel test = pytest pytest-cov dev = %(lint)s %(release)s %(test)s [options.packages.find] exclude = tests tests.* [options.entry_points] mopidy.ext = tunein = mopidy_tunein:Extension [flake8] application-import-names = mopidy_tunein, tests max-line-length = 80 exclude = .git, .tox, build select = C, E, F, W B B950 N ignore = E203 E501 W503 [egg_info] tag_build = tag_date = 0 Mopidy-TuneIn-1.0.0/setup.py0000644000175000017500000000004613577413040015561 0ustar nicknick00000000000000from setuptools import setup setup() Mopidy-TuneIn-1.0.0/tests/0000755000175000017500000000000013577726166015231 5ustar nicknick00000000000000Mopidy-TuneIn-1.0.0/tests/__init__.py0000644000175000017500000000000013414754525017316 0ustar nicknick00000000000000Mopidy-TuneIn-1.0.0/tests/test_extension.py0000644000175000017500000000074313577413040020642 0ustar nicknick00000000000000import unittest from mopidy_tunein import Extension class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn("[tunein]", config) self.assertIn("enabled = true", config) def test_get_config_schema(self): ext = Extension() schema = ext.get_config_schema() self.assertIn("timeout", schema) self.assertIn("filter", schema) Mopidy-TuneIn-1.0.0/tests/test_playlists.py0000644000175000017500000000304313577413040020646 0ustar nicknick00000000000000from mopidy_tunein import tunein ASX = b""" Example Sample Title Example title Other title """ SIMPLE_ASX = b""" """ OLD_ASX = b"""[Reference] Ref1=file:///tmp/foo Ref2=file:///tmp/bar Ref3=file:///tmp/baz """ ASF_ASX = b"""[Reference] Ref1=http://tmp.com/foo-mbr?MSWMExt=.asf Ref2=mms://tmp.com:80/bar-mbr?mswmext=.asf Ref3=http://tmp.com/baz """ class BasePlaylistAsx: valid = None parse = staticmethod(tunein.parse_asx) def test_parse_valid_playlist(self): uris = list(self.parse(self.valid)) expected = ["file:///tmp/foo", "file:///tmp/bar", "file:///tmp/baz"] assert uris == expected class AsxPlaylistTest(BasePlaylistAsx): valid = ASX class AsxSimplePlaylistTest(BasePlaylistAsx): valid = SIMPLE_ASX class AsxOldPlaylistTest(BasePlaylistAsx): valid = OLD_ASX class TestPlaylist: parse = staticmethod(tunein.parse_asx) def test_parse_asf_playlist(self): uris = list(self.parse(ASF_ASX)) expected = [ "mms://tmp.com/foo-mbr?mswmext=.asf", "mms://tmp.com:80/bar-mbr?mswmext=.asf", "http://tmp.com/baz", ] assert uris == expected Mopidy-TuneIn-1.0.0/tox.ini0000644000175000017500000000073713577413040015371 0ustar nicknick00000000000000[tox] envlist = py37, py38, black, check-manifest, flake8 [testenv] sitepackages = true deps = .[test] commands = python -m pytest \ --basetemp={envtmpdir} \ --cov=mopidy_tunein --cov-report=term-missing \ {posargs} [testenv:black] deps = .[lint] commands = python -m black --check . [testenv:check-manifest] deps = .[lint] commands = python -m check_manifest [testenv:flake8] deps = .[lint] commands = python -m flake8 --show-source --statistics