././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5483925 mopidy_tunein-2.0.0/0000755000175100017510000000000015252072240014041 5ustar00runnerrunner././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1789424794.437573 mopidy_tunein-2.0.0/.copier-answers.yml0000644000175100017510000000037515252072232017611 0ustar00runnerrunner_commit: v2.4.0 _src_path: gh:mopidy/mopidy-ext-template author_email: nickasteel@gmail.com author_full_name: Nick Steel dist_name: mopidy-tunein ext_name: tunein github_username: mopidy short_description: Mopidy extension for playing music from TuneIn ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1789424799.544327 mopidy_tunein-2.0.0/.github/0000755000175100017510000000000015252072240015401 5ustar00runnerrunner././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5457606 mopidy_tunein-2.0.0/.github/workflows/0000755000175100017510000000000015252072240017436 5ustar00runnerrunner././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1789424794.438573 mopidy_tunein-2.0.0/.github/workflows/ci.yml0000644000175100017510000000460615252072232020563 0ustar00runnerrunnername: CI on: pull_request: push: branches: - main workflow_dispatch: # No permissions by default; each job requests what it needs. permissions: {} concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: build: name: Build runs-on: ubuntu-24.04 permissions: contents: read # Check out the repository. steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: hynek/build-and-inspect-python-package@2abe76da66d0a6a4a227101f9348ee855797cfa5 # v3.0.1 main: strategy: fail-fast: false matrix: include: - name: "pytest (3.13)" python: "3.13" tox: "3.13" - name: "pytest (3.14)" python: "3.14" tox: "3.14" coverage: true - name: "pyright" python: "3.14" tox: "pyright" - name: "ruff check" python: "3.14" tox: "ruff-check" - name: "ruff format" python: "3.14" tox: "ruff-format" name: ${{ matrix.name }} runs-on: ubuntu-24.04 # Deliberately unpinned: this is our own image, and we always want the # latest version of it. container: ghcr.io/mopidy/ci:latest # zizmor: ignore[unpinned-images] permissions: contents: read # Check out the repository. steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - name: Fix home dir permissions to enable pip caching run: chown -R root /github/home - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python }} cache: pip allow-prereleases: true - run: python -m pip install tox - env: TOX_ENV: ${{ matrix.tox }} run: python -m tox -e "$TOX_ENV" if: ${{ ! matrix.coverage }} - env: TOX_ENV: ${{ matrix.tox }} run: python -m tox -e "$TOX_ENV" -- --cov-report=xml if: ${{ matrix.coverage }} - uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 if: ${{ matrix.coverage }} with: token: ${{ secrets.CODECOV_TOKEN }} ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4386983 mopidy_tunein-2.0.0/.github/workflows/release.yml0000644000175100017510000000167515252072232021613 0ustar00runnerrunnername: Release on: release: types: [published] # No permissions by default; each job requests what it needs. permissions: {} jobs: release: name: Release runs-on: ubuntu-24.04 environment: name: pypi url: https://pypi.org/project/mopidy-tunein/ permissions: contents: read # Check out the repository. id-token: write # Authenticate with PyPI using trusted publishing. steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: hynek/build-and-inspect-python-package@2abe76da66d0a6a4a227101f9348ee855797cfa5 # v3.0.1 id: build - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: ${{ steps.build.outputs.artifact-name }} path: dist - uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4386983 mopidy_tunein-2.0.0/.gitignore0000644000175100017510000000012515252072232016030 0ustar00runnerrunner*.egg-info/ /*.lock /.*_cache/ /.coverage /.tox/ /.venv/ /build/ /dist/ __pycache__/ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4386983 mopidy_tunein-2.0.0/LICENSE0000644000175100017510000002613615252072232015057 0ustar00runnerrunner 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. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5483599 mopidy_tunein-2.0.0/PKG-INFO0000644000175100017510000001263415252072240015144 0ustar00runnerrunnerMetadata-Version: 2.4 Name: mopidy-tunein Version: 2.0.0 Summary: Mopidy extension for playing music from TuneIn Author-email: Nick Steel License: Apache-2.0 Project-URL: Homepage, https://github.com/mopidy/mopidy-tunein 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: Topic :: Multimedia :: Sound/Audio :: Players Requires-Python: >=3.13 Description-Content-Type: text/markdown License-File: LICENSE Requires-Dist: httpx>=0.28.1 Requires-Dist: mopidy>=4.0.0 Requires-Dist: pykka>=4.1 Dynamic: license-file # mopidy-tunein [![Latest PyPI version](https://img.shields.io/pypi/v/mopidy-tunein)](https://pypi.org/p/mopidy-tunein) [![CI build status](https://img.shields.io/github/actions/workflow/status/mopidy/mopidy-tunein/ci.yml)](https://github.com/mopidy/mopidy-tunein/actions/workflows/ci.yml) [![Test coverage](https://img.shields.io/codecov/c/gh/mopidy/mopidy-tunein)](https://codecov.io/gh/mopidy/mopidy-tunein) [Mopidy](https://mopidy.com/) extension for playing music from [TuneIn](https://tunein.com). Listen to the world's radio with 70,000 stations of music, sports and news streaming from every continent. 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: ```sh python3 -m pip install mopidy-tunein ``` See https://mopidy.com/ext/tunein/ for alternative installation methods. Most stations stream MP3, which the GStreamer plugins that Mopidy already needs can decode. Some stations only stream AAC. To play those, install `gstreamer1.0-plugins-bad` or `gstreamer1.0-libav`, or the packages that hold these GStreamer plugin sets on your system. If you do not want the AAC stations at all, see the `tunein/formats` config value below. ## Configuration The extension is enabled by default when it is installed. Configuration is not required, but you can add this to your Mopidy configuration file: ```ini [tunein] timeout = 5000 formats = mp3, aac ``` 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 to `station` or `program`. Leave it blank to turn off filtering. Defaults to blank. - `tunein/timeout`: Milliseconds before giving up waiting for results. Defaults to `5000`. - `tunein/formats`: The stream formats to ask TuneIn for, as a comma separated list. TuneIn leaves out the stations that it cannot give you in any of these formats. Defaults to `mp3, aac`. Set it to `mp3` if you do not have the GStreamer plugins for AAC. Mopidy plays the MP3 stream of a station when there is one, and uses AAC only for the stations that have no MP3 stream. - `tunein/location`: The place to use for the "Local Radio" category, as a comma separated latitude and longitude pair, e.g. `51.5,-0.13`. Leave it blank to let TuneIn choose the place from your IP address. ## Usage Browse the "TuneIn" directory to find stations by category, by location, or among the ones that are popular now. TuneIn gives 25 stations at a time, so a category that holds more ends with a "More stations" entry that opens the next 25. ## Known issues The following functionality is not implemented: - User login and access to saved stations. ## Project resources - [Source code](https://github.com/mopidy/mopidy-tunein) - [Issues](https://github.com/mopidy/mopidy-tunein/issues) - [Releases](https://github.com/mopidy/mopidy-tunein/releases) ## Development ### Set up development environment Clone the repo using, e.g. using [gh](https://cli.github.com/): ```sh gh repo clone mopidy/mopidy-tunein ``` Enter the directory, and install dependencies using [uv](https://docs.astral.sh/uv/): ```sh cd mopidy-tunein/ uv sync ``` ### Running tests To run all tests and linters in isolated environments, use [tox](https://tox.wiki/): ```sh tox ``` To only run tests, use [pytest](https://pytest.org/): ```sh pytest ``` To format the code, use [ruff](https://docs.astral.sh/ruff/): ```sh ruff format . ``` To check for lints with ruff, run: ```sh ruff check . ``` To check for type errors, use [pyright](https://microsoft.github.io/pyright/): ```sh pyright . ``` ### Making a release To make a release to PyPI, go to the project's [GitHub releases page](https://github.com/mopidy/mopidy-tunein/releases) and click the "Draft a new release" button. In the "choose a tag" dropdown, select the tag you want to release or create a new tag, e.g. `v0.1.0`. Add a title, e.g. `v0.1.0`, and a description of the changes. Decide if the release is a pre-release (alpha, beta, or release candidate) or should be marked as the latest release, and click "Publish release". Once the release is created, the `release.yml` GitHub Action will automatically build and publish the release to [PyPI](https://pypi.org/project/mopidy-tunein/). ## Credits - Original author: [Nick Steel](https://github.com/kingosticks) - Current maintainer: [Nick Steel](https://github.com/kingosticks) - [Contributors](https://github.com/mopidy/mopidy-tunein/graphs/contributors) Thanks to Marius Wyss for the original version of this extension, and to Brian Hornsby's [XBMC plugin](https://github.com/brianhornsby/plugin.audio.tuneinradio), which it was based on. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4386983 mopidy_tunein-2.0.0/README.md0000644000175100017510000001133015252072232015317 0ustar00runnerrunner# mopidy-tunein [![Latest PyPI version](https://img.shields.io/pypi/v/mopidy-tunein)](https://pypi.org/p/mopidy-tunein) [![CI build status](https://img.shields.io/github/actions/workflow/status/mopidy/mopidy-tunein/ci.yml)](https://github.com/mopidy/mopidy-tunein/actions/workflows/ci.yml) [![Test coverage](https://img.shields.io/codecov/c/gh/mopidy/mopidy-tunein)](https://codecov.io/gh/mopidy/mopidy-tunein) [Mopidy](https://mopidy.com/) extension for playing music from [TuneIn](https://tunein.com). Listen to the world's radio with 70,000 stations of music, sports and news streaming from every continent. 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: ```sh python3 -m pip install mopidy-tunein ``` See https://mopidy.com/ext/tunein/ for alternative installation methods. Most stations stream MP3, which the GStreamer plugins that Mopidy already needs can decode. Some stations only stream AAC. To play those, install `gstreamer1.0-plugins-bad` or `gstreamer1.0-libav`, or the packages that hold these GStreamer plugin sets on your system. If you do not want the AAC stations at all, see the `tunein/formats` config value below. ## Configuration The extension is enabled by default when it is installed. Configuration is not required, but you can add this to your Mopidy configuration file: ```ini [tunein] timeout = 5000 formats = mp3, aac ``` 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 to `station` or `program`. Leave it blank to turn off filtering. Defaults to blank. - `tunein/timeout`: Milliseconds before giving up waiting for results. Defaults to `5000`. - `tunein/formats`: The stream formats to ask TuneIn for, as a comma separated list. TuneIn leaves out the stations that it cannot give you in any of these formats. Defaults to `mp3, aac`. Set it to `mp3` if you do not have the GStreamer plugins for AAC. Mopidy plays the MP3 stream of a station when there is one, and uses AAC only for the stations that have no MP3 stream. - `tunein/location`: The place to use for the "Local Radio" category, as a comma separated latitude and longitude pair, e.g. `51.5,-0.13`. Leave it blank to let TuneIn choose the place from your IP address. ## Usage Browse the "TuneIn" directory to find stations by category, by location, or among the ones that are popular now. TuneIn gives 25 stations at a time, so a category that holds more ends with a "More stations" entry that opens the next 25. ## Known issues The following functionality is not implemented: - User login and access to saved stations. ## Project resources - [Source code](https://github.com/mopidy/mopidy-tunein) - [Issues](https://github.com/mopidy/mopidy-tunein/issues) - [Releases](https://github.com/mopidy/mopidy-tunein/releases) ## Development ### Set up development environment Clone the repo using, e.g. using [gh](https://cli.github.com/): ```sh gh repo clone mopidy/mopidy-tunein ``` Enter the directory, and install dependencies using [uv](https://docs.astral.sh/uv/): ```sh cd mopidy-tunein/ uv sync ``` ### Running tests To run all tests and linters in isolated environments, use [tox](https://tox.wiki/): ```sh tox ``` To only run tests, use [pytest](https://pytest.org/): ```sh pytest ``` To format the code, use [ruff](https://docs.astral.sh/ruff/): ```sh ruff format . ``` To check for lints with ruff, run: ```sh ruff check . ``` To check for type errors, use [pyright](https://microsoft.github.io/pyright/): ```sh pyright . ``` ### Making a release To make a release to PyPI, go to the project's [GitHub releases page](https://github.com/mopidy/mopidy-tunein/releases) and click the "Draft a new release" button. In the "choose a tag" dropdown, select the tag you want to release or create a new tag, e.g. `v0.1.0`. Add a title, e.g. `v0.1.0`, and a description of the changes. Decide if the release is a pre-release (alpha, beta, or release candidate) or should be marked as the latest release, and click "Publish release". Once the release is created, the `release.yml` GitHub Action will automatically build and publish the release to [PyPI](https://pypi.org/project/mopidy-tunein/). ## Credits - Original author: [Nick Steel](https://github.com/kingosticks) - Current maintainer: [Nick Steel](https://github.com/kingosticks) - [Contributors](https://github.com/mopidy/mopidy-tunein/graphs/contributors) Thanks to Marius Wyss for the original version of this extension, and to Brian Hornsby's [XBMC plugin](https://github.com/brianhornsby/plugin.audio.tuneinradio), which it was based on. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4386983 mopidy_tunein-2.0.0/pyproject.toml0000644000175100017510000000672615252072232016771 0ustar00runnerrunner[project] name = "mopidy-tunein" description = "Mopidy extension for playing music from TuneIn" readme = "README.md" requires-python = ">= 3.13" license = { text = "Apache-2.0" } authors = [{ name = "Nick Steel", email = "nickasteel@gmail.com" }] classifiers = [ "Environment :: No Input/Output (Daemon)", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Multimedia :: Sound/Audio :: Players", ] dynamic = ["version"] dependencies = [ "httpx >= 0.28.1", "mopidy >= 4.0.0", "pykka >= 4.1", ] [project.urls] Homepage = "https://github.com/mopidy/mopidy-tunein" [project.entry-points."mopidy.ext"] tunein = "mopidy_tunein:Extension" [build-system] requires = ["setuptools >= 78", "setuptools-scm >= 8.2"] build-backend = "setuptools.build_meta" [dependency-groups] dev = [ "tox", { include-group = "ruff" }, { include-group = "tests" }, { include-group = "typing" }, ] ruff = ["ruff"] tests = ["pytest", "pytest-cov", "pytest-httpx"] typing = ["pyright"] [tool.coverage.paths] source = ["src/", "*/site-packages/"] [tool.coverage.run] source_pkgs = ["mopidy_tunein"] [tool.coverage.report] show_missing = true [tool.pyright] pythonVersion = "3.13" typeCheckingMode = "standard" # Not all dependencies have type hints: reportMissingTypeStubs = false # Already covered by ruff's flake8-self checks: reportPrivateImportUsage = false [tool.pytest.ini_options] filterwarnings = [ # By default, fail tests on warnings from our own code "error:::mopidy_tunein", # # Add any warnings you want to ignore here ] [tool.ruff] target-version = "py313" [tool.ruff.lint] select = ["ALL"] ignore = [ # Add rules you want to ignore here "BLE001", # blind-except # TODO "CPY", # flake8-copyright "D", # pydocstyle "D203", # one-blank-line-before-class "D213", # multi-line-summary-second-line "FIX002", # line-contains-todo "G004", # logging-f-string "PLW2901", # redefined-loop-name "S314", # suspicious-xml-element-tree-usage -- ElementTree is safe given expat >= 2.6.1 "SLF001", # private-member-access # TODO "TD002", # missing-todo-author "TD003", # missing-todo-link "TRY400", # error-instead-of-exception # # Conflicting with `ruff format` "COM812", # missing-trailing-comma "ISC001", # single-line-implicit-string-concatenation ] [tool.ruff.lint.per-file-ignores] "tests/*" = [ "ARG", # flake8-unused-arguments "D", # pydocstyle "PLR2004", # magic-value-comparison "S101", # assert ] [tool.setuptools.package-data] "*" = ["*.conf"] [tool.setuptools_scm] # This section, even if empty, must be present for setuptools_scm to work [tool.tox] env_list = [ "3.13", "3.14", "pyright", "ruff-check", "ruff-format", ] [tool.tox.env_run_base] package = "wheel" wheel_build_env = ".pkg" dependency_groups = ["tests"] commands = [ [ "pytest", "--cov", "--basetemp={envtmpdir}", { replace = "posargs", extend = true }, ], ] [tool.tox.env.pyright] dependency_groups = ["typing"] commands = [["pyright", "{posargs:src}"]] [tool.tox.env.ruff-check] skip_install = true dependency_groups = ["ruff"] commands = [["ruff", "check", "{posargs:.}"]] [tool.tox.env.ruff-format] skip_install = true dependency_groups = ["ruff"] commands = [["ruff", "format", "--check", "--diff", "{posargs:.}"]] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5486672 mopidy_tunein-2.0.0/setup.cfg0000644000175100017510000000004615252072240015662 0ustar00runnerrunner[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1789424799.544327 mopidy_tunein-2.0.0/src/0000755000175100017510000000000015252072240014630 5ustar00runnerrunner././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5464835 mopidy_tunein-2.0.0/src/mopidy_tunein/0000755000175100017510000000000015252072240017513 5ustar00runnerrunner././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4389915 mopidy_tunein-2.0.0/src/mopidy_tunein/__init__.py0000644000175100017510000000170415252072232021627 0ustar00runnerrunnerimport pathlib from importlib.metadata import version from typing import override from mopidy import config, ext __version__ = version("mopidy-tunein") class Extension(ext.Extension): dist_name = "mopidy-tunein" ext_name = "tunein" version = __version__ @override def get_default_config(self) -> str: return config.read(pathlib.Path(__file__).parent / "ext.conf") @override def get_config_schema(self) -> config.ConfigSchema: schema = super().get_config_schema() schema["timeout"] = config.Integer(minimum=0) schema["filter"] = config.String(optional=True, choices=("station", "program")) schema["formats"] = config.List(optional=True) schema["location"] = config.String(optional=True) return schema @override def setup(self, registry: ext.Registry) -> None: from .actor import TuneInBackend # noqa: PLC0415 registry.add("backend", TuneInBackend) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4390485 mopidy_tunein-2.0.0/src/mopidy_tunein/actor.py0000644000175100017510000003027115252072232021201 0ustar00runnerrunnerfrom __future__ import annotations import logging import time import urllib.parse from typing import TYPE_CHECKING, ClassVar, override import pykka from mopidy import backend, exceptions from mopidy.audio import scan from mopidy.models import Ref, SearchResult from mopidy.types import Uri, UriScheme from mopidy_tunein import Extension, http, parsers, translator, tunein if TYPE_CHECKING: from collections.abc import Iterable import httpx from mopidy.audio import AudioProxy from mopidy.config import Config, ProxyConfig from mopidy.models import Image, Track from mopidy.types import Query, SearchField logger = logging.getLogger(__name__) def get_httpx_client(proxy_config: ProxyConfig) -> httpx.Client: user_agent = f"{Extension.dist_name}/{Extension.version}" return http.get_httpx_client(proxy_config=proxy_config, user_agent=user_agent) class TuneInBackend(pykka.ThreadingActor, backend.Backend): uri_schemes: ClassVar[list[UriScheme]] = [UriScheme("tunein")] def __init__(self, config: Config, audio: AudioProxy) -> None: super().__init__() self._client = get_httpx_client(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( timeout=config["tunein"]["timeout"], filter_=config["tunein"]["filter"], formats=config["tunein"]["formats"], location=config["tunein"]["location"], client=self._client, ) self.library = TuneInLibrary(self) self.playback = TuneInPlayback(audio=audio, backend=self) class TuneInLibrary(backend.LibraryProvider): backend: TuneInBackend root_directory = Ref.directory(uri=Uri("tunein:root"), name="TuneIn") def __init__(self, backend: TuneInBackend) -> None: super().__init__(backend) @override def browse(self, uri: Uri) -> list[Ref]: variant, identifier = translator.parse_uri(uri) logger.debug(f"Browsing {uri!r}") if variant == "root": return self._browse_root() if variant is None or variant == "station" or identifier is None: # A station is a track, so there is nothing to browse. logger.debug(f"Cannot browse URI: {uri!r}") return [] # pyright checks that every variant has a case here, because it # reports refs as possibly unbound when one is missing. match variant: case "category": refs = self._browse_category(identifier) case "location": refs = self._browse_location(identifier) case "section": refs = self._browse_section(identifier) case "stations": refs = self._browse_stations(identifier) case "related": refs = self._browse_related(identifier) case "shows": refs = self._browse_shows(identifier) case "episodes": refs = self._browse_episodes(identifier) return refs def _browse_root(self) -> list[Ref]: return [ translator.category_to_ref(category) for category in self.backend.tunein.categories() ] def _browse_category(self, identifier: str) -> list[Ref]: return [ translator.section_to_ref(section, identifier) for section in self.backend.tunein.categories(identifier) ] def _browse_location(self, identifier: str) -> list[Ref]: result = [ translator.section_to_ref(location, "local") for location in self.backend.tunein.locations(identifier) ] result.extend( translator.station_to_ref(station) for station in self.backend.tunein.stations(identifier) ) return result def _browse_section(self, identifier: str) -> list[Ref]: result: list[Ref] = [] if self.backend.tunein.related(identifier): result.append( Ref.directory(uri=Uri(f"tunein:related:{identifier}"), name="Related") ) if self.backend.tunein.shows(identifier): result.append( Ref.directory(uri=Uri(f"tunein:shows:{identifier}"), name="Shows") ) result.extend( translator.section_to_ref(station) for station in self.backend.tunein.featured(identifier) ) result.extend( translator.station_to_ref(station) for station in self.backend.tunein.local(identifier) ) result.extend( translator.station_to_ref(station) for station in self.backend.tunein.stations(identifier) ) result.extend(self._more_stations_ref(identifier)) return result def _browse_stations(self, identifier: str) -> list[Ref]: guide_id, offset = translator.parse_page(identifier) result = [ translator.station_to_ref(station) for station in self.backend.tunein.stations(guide_id, offset) ] result.extend(self._more_stations_ref(guide_id, offset)) return result def _more_stations_ref(self, guide_id: str, offset: int = 0) -> list[Ref]: next_offset = self.backend.tunein.next_stations_offset(guide_id, offset) if next_offset is None: return [] return [ Ref.directory( uri=translator.unparse_page_uri(guide_id, next_offset), name="More stations", ) ] def _browse_related(self, identifier: str) -> list[Ref]: return [ translator.section_to_ref(section) for section in self.backend.tunein.related(identifier) ] def _browse_shows(self, identifier: str) -> list[Ref]: return [ translator.show_to_ref(show) for show in self.backend.tunein.shows(identifier) ] def _browse_episodes(self, identifier: str) -> list[Ref]: return [ translator.station_to_ref(episode) for episode in self.backend.tunein.episodes(identifier) ] @override def refresh(self, uri: Uri | None = None) -> None: self.backend.tunein.reload() @override def lookup(self, uri: Uri) -> list[Track]: variant, identifier = translator.parse_uri(uri) if variant != "station" or identifier is None: return [] station = self.backend.tunein.station(identifier) if not station: return [] track = translator.station_to_track(station) return [track] @override def get_images(self, uris: Iterable[Uri]) -> dict[Uri, list[Image]]: results: dict[Uri, list[Image]] = {} for uri in uris: variant, identifier = translator.parse_uri(uri) if variant != "station" or identifier is None: continue station = self.backend.tunein.station(identifier) image = translator.station_to_image(station) if image is not None: results[uri] = [image] return results @override def search( self, query: Query[SearchField] | None = None, uris: Iterable[Uri] | None = None, exact: bool = False, ) -> SearchResult | None: if query is None or not query: return None tunein_query = translator.mopidy_to_tunein_query(query) tracks = [ translator.station_to_track(station) for station in self.backend.tunein.search(tunein_query) ] return SearchResult(uri=Uri("tunein:search"), tracks=tuple(tracks)) class TuneInPlayback(backend.PlaybackProvider): backend: TuneInBackend def __init__(self, audio: AudioProxy, backend: TuneInBackend) -> None: super().__init__(audio, backend) self._stream_info: scan._Result | None = None @override def translate_uri(self, uri: Uri) -> Uri | None: _variant, identifier = translator.parse_uri(uri) if identifier is None: return None station = self.backend.tunein.station(identifier) if not station: return None stream_uris = self.backend.tunein.tune(station) while stream_uris: stream_uri = Uri(stream_uris.pop(0)) logger.debug(f"Looking up URI: {stream_uri!r}") new_uri = self.unwrap_stream(stream_uri) if new_uri: return new_uri logger.debug("Mopidy translate_uri failed.") new_uris = self.backend.tunein.parse_stream_url(stream_uri) if new_uris == [stream_uri]: logger.debug(f"Last attempt, play stream anyway: {stream_uri!r}") return stream_uri stream_uris.extend(new_uris) logger.debug("TuneIn lookup failed.") return None def unwrap_stream(self, uri: Uri) -> Uri | None: unwrapped_uri, self._stream_info = _unwrap_stream( uri, timeout=self.backend._timeout, scanner=self.backend._scanner, http_client=self.backend._client, ) return unwrapped_uri @override def is_live(self, uri: Uri) -> bool: return ( self._stream_info is not None and self._stream_info.uri == uri and self._stream_info.playable and not self._stream_info.seekable ) # Shamelessly taken from mopidy.stream.actor def _unwrap_stream( # noqa: PLR0911 uri: Uri, timeout: int, scanner: scan.Scanner, http_client: httpx.Client, ) -> tuple[Uri | None, scan._Result | None]: """ 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[Uri] = 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 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: has_interesting_mime = ( scan_result.mime is not None and not scan_result.mime.startswith("text/") and not scan_result.mime.startswith("application/") ) if scan_result.playable or has_interesting_mime: 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(http_client, 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 = parsers.parse_playlist(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 = Uri(urllib.parse.urljoin(uri, uris[0])) return None, None ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4390485 mopidy_tunein-2.0.0/src/mopidy_tunein/ext.conf0000644000175100017510000000012715252072232021163 0ustar00runnerrunner[tunein] enabled = true filter = timeout = 5000 formats = mp3 aac location = ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4390485 mopidy_tunein-2.0.0/src/mopidy_tunein/http.py0000644000175100017510000000362415252072232021052 0ustar00runnerrunnerfrom __future__ import annotations import logging import time from typing import TYPE_CHECKING import httpx from mopidy import httpclient if TYPE_CHECKING: from mopidy.httpclient import ProxyConfig logger = logging.getLogger(__name__) def get_httpx_client( proxy_config: ProxyConfig, user_agent: str, ) -> httpx.Client: return httpx.Client( proxy=httpclient.format_proxy(proxy_config), headers={"user-agent": httpclient.format_user_agent(user_agent)}, follow_redirects=True, ) def download( client: httpx.Client, uri: str, timeout: float = 1.0, chunk_size: int = 4096, ) -> bytes | None: try: with client.stream("GET", uri, timeout=timeout) as response: content = [] deadline = time.time() + timeout for chunk in response.iter_bytes(chunk_size): content.append(chunk) if time.time() > deadline: logger.warning( "Download of %r failed due to download taking more than %.3fs", uri, timeout, ) return None if not response.is_success: logger.warning( "Problem downloading %r: %s", uri, response.reason_phrase ) return None return b"".join(content) except httpx.TimeoutException: logger.warning( "Download of %r failed due to connection timeout after %.3fs", uri, timeout, ) return None except httpx.UnsupportedProtocol: logger.warning("Download of %r failed due to unsupported schema", uri) return None except httpx.HTTPError as exc: logger.warning("Download of %r failed: %s", uri, exc) logger.debug("Download exception details", exc_info=True) return None ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4390485 mopidy_tunein-2.0.0/src/mopidy_tunein/parsers.py0000644000175100017510000001154115252072232021547 0ustar00runnerrunnerimport configparser import io import urllib.parse from collections.abc import Generator from xml.etree import ElementTree as ET def parse_playlist(data: bytes) -> list[str]: handlers = { detect_extm3u_header: parse_extm3u, detect_pls_header: parse_pls, detect_asx_reference_header: parse_asx_reference, detect_asx_header: parse_asx, detect_xspf_header: parse_xspf, } for detector, parser in handlers.items(): if detector(data): return list(parser(data)) return list(parse_urilist(data)) # Fallback def detect_extm3u_header(data: bytes) -> bool: return data[0:7].upper() == b"#EXTM3U" def detect_pls_header(data: bytes) -> bool: return data[0:10].lower() == b"[playlist]" def detect_asx_reference_header(data: bytes) -> bool: return data[0:11].lower() == b"[reference]" def detect_xspf_header(data: bytes) -> bool: data = data[0:150] if b"xspf" not in data.lower(): return False try: fh = io.BytesIO(data) for _event, element in ET.iterparse(fh, events=["start"]): return element.tag.lower() == "{http://xspf.org/ns/0/}playlist" except ET.ParseError: pass return False def detect_asx_header(data: bytes) -> bool: data = data[0:50] if b"asx" not in data.lower(): return False try: fh = io.BytesIO(data) for _event, element in ET.iterparse(fh, events=["start"]): return element.tag.lower() == "asx" except ET.ParseError: pass return False def parse_extm3u(data: bytes) -> Generator[str]: # TODO: convert non URIs to file URIs. found_header = False for line in data.splitlines(): if found_header or line.startswith(b"#EXTM3U"): found_header = True else: continue if not line.strip() or line.startswith(b"#"): continue try: line = line.decode() except UnicodeDecodeError: continue yield line.strip() def parse_pls(data: bytes) -> Generator[str]: # TODO: convert non URIs to file URIs. try: cp = configparser.RawConfigParser(strict=False) cp.read_string(data.decode()) except configparser.Error: return for section in cp.sections(): if section.lower() != "playlist": continue # Malformed playlists often declare a NumberOfEntries that does not # match the File keys they have. Use the File keys instead. entries = ( (int(option[4:]), cp.get(section, option)) for option in cp.options(section) if option.startswith("file") and option[4:].isdigit() ) for _index, entry in sorted(entries): if uri := entry.strip("\"'"): yield uri def parse_asx_reference(data: bytes) -> Generator[str]: try: cp = configparser.RawConfigParser(strict=False) cp.read_string(data.decode()) except configparser.Error: return for section in cp.sections(): if section.lower() != "reference": continue references = ( (int(option[3:]), cp.get(section, option)) for option in cp.options(section) if option.startswith("ref") and option[3:].isdigit() ) for _index, reference in sorted(references): if uri := reference.strip("\"'"): yield uri def parse_xspf(data: bytes) -> Generator[str]: element = None try: # Last element will be root. for _event, element in ET.iterparse(io.BytesIO(data)): element.tag = element.tag.lower() # normalize except ET.ParseError: return if element is None: return ns = "http://xspf.org/ns/0/" path = f"{{{ns}}}tracklist/{{{ns}}}track" for track in element.iterfind(str(path)): if result := track.findtext(f"{{{ns}}}location"): yield result def parse_asx(data: bytes) -> Generator[str]: element = None try: # Last element will be root. for _event, element in ET.iterparse(io.BytesIO(data)): element.tag = element.tag.lower() # normalize except ET.ParseError: return if element is None: return for ref in element.findall("entry/ref[@href]"): yield ref.get("href", "").strip() for entry in element.findall("entry[@href]"): yield entry.get("href", "").strip() def parse_urilist(data: bytes) -> Generator[str]: for line in data.splitlines(): if not line.strip() or line.startswith(b"#"): continue try: line = line.decode() except UnicodeDecodeError: continue try: result = urllib.parse.urlparse(line) except ValueError: continue if result.scheme == "": continue yield line.strip() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4390485 mopidy_tunein-2.0.0/src/mopidy_tunein/translator.py0000644000175100017510000001065315252072232022264 0ustar00runnerrunnerfrom __future__ import annotations import logging import re from typing import TYPE_CHECKING, Final, Literal, get_args from urllib import request from urllib.parse import urlsplit, urlunsplit from mopidy.models import Album, Artist, Image, Ref, Track from mopidy.types import Uri from mopidy_tunein.tunein import TuneIn if TYPE_CHECKING: from mopidy.types import Query, SearchField from mopidy_tunein.tunein import TuneInItem logger = logging.getLogger(__name__) type Variant = Literal[ "root", "category", "location", "section", "stations", "related", "shows", "episodes", "station", ] """The kinds of thing a tunein URI can point at.""" VARIANTS: Final = get_args(Variant.__value__) def secure_image_uri(uri: str) -> Uri: """Give back a TuneIn image URI with the https scheme. The API answers with http, which a browser blocks as mixed content when it shows a Mopidy web client over https. """ parts = urlsplit(uri) if ( parts.scheme == "http" and parts.hostname and (parts.hostname == "tunein.com" or parts.hostname.endswith(".tunein.com")) ): return Uri(urlunsplit(parts._replace(scheme="https"))) return Uri(uri) def unparse_uri(variant: str, identifier: str) -> Uri: return Uri(f"tunein:{variant}:{identifier}") def parse_uri(uri: str) -> tuple[Variant | None, str | None]: result = re.findall(r"^tunein:([a-z]+)(?::(\w+))?$", uri) if not result: return None, None variant, identifier = result[0] if variant not in VARIANTS: return None, None return variant, identifier or None def unparse_page_uri(guide_id: str, offset: int) -> Uri: return unparse_uri("stations", f"{guide_id}_{offset}") def parse_page(identifier: str) -> tuple[str, int]: guide_id, _, offset = identifier.partition("_") try: return guide_id, int(offset) except ValueError: return guide_id, 0 def station_to_ref(station: TuneInItem) -> Ref: 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: TuneInItem) -> Track: 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=frozenset([Artist(name=ref.name, uri=ref.uri)]), ) def station_to_image(station: TuneInItem | None) -> Image | None: if station is not None and "image" in station: return Image(uri=secure_image_uri(station["image"])) return None def show_to_ref(show: TuneInItem) -> Ref: 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: TuneInItem) -> Ref: uri = unparse_uri("category", category["key"]) return Ref.directory(uri=uri, name=category["text"]) def section_to_ref(section: TuneInItem, identifier: str = "") -> Ref: 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: str) -> str: 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: Query[SearchField]) -> str: tunein_query = [ str(value) for field, values in mopidy_query.items() if field == "any" for value in values ] query = " ".join(tunein_query) return request.pathname2url(query) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4390485 mopidy_tunein-2.0.0/src/mopidy_tunein/tunein.py0000644000175100017510000004342415252072232021377 0ustar00runnerrunnerfrom __future__ import annotations import configparser import io import logging import re import time from collections import OrderedDict from collections.abc import Callable, Generator, Iterable from typing import Any from urllib.parse import parse_qs, urlparse from xml.etree import ElementTree as ET import httpx logger = logging.getLogger(__name__) type TuneInItem = dict[str, Any] """One category, section, show, or station from the TuneIn API.""" type PlaylistParser = Callable[[bytes], Generator[str]] PLAYLIST_MAX_BYTES = 512 * 1024 """Anything larger than this is a stream, not a playlist.""" PLAYLIST_CHUNK_SIZE = 8192 FORMAT_ARG_VARIANTS = ("Browse.ashx", "Search.ashx", "Tune.ashx") """The API requests that honour the formats argument.""" FORMAT_PRIORITY = ("mp3", "aac") """Stream formats, best first. Anything else goes last.""" PLACEHOLDER_STREAM = "notcompatible" """TuneIn answers with this recording for a station it cannot serve.""" class PlaylistError(Exception): pass def read_playlist_body( response: httpx.Response, timeout: float, max_bytes: int, ) -> bytes | None: """Read a playlist body, or give up if the URI turns out to be a stream. A stream does not end, so stop at the first of the size limit and the deadline, and report that there is no playlist to parse. """ deadline = time.time() + timeout chunks: list[bytes] = [] size = 0 for chunk in response.iter_bytes(PLAYLIST_CHUNK_SIZE): chunks.append(chunk) size += len(chunk) if size > max_bytes: logger.debug(f"Stopped reading {response.url} after {size} bytes") return None if time.time() > deadline: logger.debug(f"Stopped reading {response.url} after {timeout}s") return None return b"".join(chunks) class cache: # noqa: N801 # TODO: merge this to util library (copied from mopidy-spotify) def __init__(self, ctl: int = 0, ttl: int = 3600) -> None: self.cache: dict[Any, tuple[Any, float]] = {} self.ctl = ctl self.ttl = ttl self._call_count = 0 def __call__[**P, R](self, func: Callable[P, R]) -> Callable[P, R]: def _memoized(*args: P.args, **kwargs: P.kwargs) -> R: now = time.time() key = (args, tuple(sorted(kwargs.items()))) try: value, last_update = self.cache[key] age = now - last_update if self._call_count > self.ctl or age > self.ttl: self._call_count = 0 raise AttributeError # noqa: TRY301 if self.ctl: self._call_count += 1 except (KeyError, AttributeError): value = func(*args, **kwargs) if value: self.cache[key] = (value, now) return value except TypeError: return func(*args, **kwargs) else: return value return _memoized def clear(self) -> None: self.cache.clear() def parse_m3u(data: bytes) -> Generator[str]: # 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: bytes) -> Generator[str]: # Copied from mopidy.audio.playlists try: cp = configparser.RawConfigParser(strict=False) 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: str) -> str: return re.sub(r"http://(.+\?mswmext=\.asf)", r"mms://\1", uri, flags=re.IGNORECASE) def parse_old_asx(data: bytes) -> Generator[str]: 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: bytes) -> Generator[str]: # Copied from mopidy.audio.playlists element = None try: # Last element will be root. for _event, element in ET.iterparse(io.BytesIO(data)): element.tag = element.tag.lower() # normalize except ET.ParseError: return if element is None: 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: bytes) -> Generator[str]: if b"asx" in data[0:50].lower(): return parse_new_asx(data) return parse_old_asx(data) def stream_priority(stream: TuneInItem) -> tuple[int, int]: """Order a station's streams, best first. Prefer the format over the bitrate. Mopidy keeps the first stream that it can open, so it cannot go back to another one, and MP3 plays with the GStreamer plugins that Mopidy already asks for, while AAC does not. MP3 is also the higher bitrate for most stations that give both. """ try: rank = FORMAT_PRIORITY.index(stream.get("media_type", "")) except ValueError: rank = len(FORMAT_PRIORITY) try: bitrate = int(stream.get("bitrate") or 0) except (TypeError, ValueError): bitrate = 0 return (rank, -bitrate) def page_offset(uri: str) -> int | None: values = parse_qs(urlparse(uri).query).get("offset", []) try: return int(values[0]) except (IndexError, ValueError): return None def media_type(content_type: str) -> str: """Get the media type from a content type, without its parameters. For example, "audio/x-scpls; charset=UTF-8" gives "audio/x-scpls". """ return content_type.split(";", maxsplit=1)[0].strip().lower() def find_playlist_parser( extension: str, content_type: str | None, ) -> PlaylistParser | None: extension_map: dict[str, PlaylistParser] = { ".asx": parse_asx, ".wax": parse_asx, ".m3u": parse_m3u, ".pls": parse_pls, } content_type_map: dict[str, PlaylistParser] = { "video/x-ms-asf": parse_asx, "application/x-mpegurl": parse_m3u, "audio/x-mpegurl": parse_m3u, "audio/x-scpls": parse_pls, } parser = extension_map.get(extension) 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(media_type(content_type)) 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" _tunein_cache = cache() _playlist_cache = cache() def __init__( self, timeout: int, filter_: str | None = None, formats: Iterable[str] | None = None, location: str | None = None, client: httpx.Client | None = None, ) -> None: self._base_uri = "https://opml.radiotime.com/%s" self._client = client or httpx.Client(follow_redirects=True) self._timeout = timeout / 1000.0 if filter_ in [TuneIn.ID_PROGRAM, TuneIn.ID_STATION]: self._filter = f"&filter={filter_[0]}" else: self._filter = "" self._formats = f"&formats={','.join(formats)}" if formats else "" self._location = f"&latlon={location}" if location else "" self._stations: dict[str, TuneInItem] = {} def reload(self) -> None: self._stations.clear() self._tunein_cache.clear() self._playlist_cache.clear() def _flatten(self, data: Iterable[TuneInItem]) -> list[TuneInItem]: results = [] for item in data: if "children" in item: results.extend(item["children"]) else: results.append(item) return results def _filter_results( self, data: Iterable[TuneInItem], section_name: str | None = None, map_func: Callable[[TuneInItem], TuneInItem] | None = None, ) -> list[TuneInItem]: results: list[TuneInItem] = [] def grab_item(item: TuneInItem) -> None: 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: str = "") -> list[TuneInItem]: 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 if category == "local": args += self._location # 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: TuneInItem = { "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: str) -> list[TuneInItem]: 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_page(self, guide_id: str, offset: int = 0) -> list[TuneInItem]: args = "&id=" + guide_id if offset: args += f"&offset={offset}" return self._tunein("Browse.ashx", args) def _browse(self, section_name: str, guide_id: str) -> list[TuneInItem]: return self._filter_results(self._browse_page(guide_id), section_name) def next_stations_offset(self, guide_id: str, offset: int = 0) -> int | None: for item in self._browse_page(guide_id, offset): if not item.get("key", "").lower().startswith("station"): continue for child in item.get("children", []): if child.get("key") == "nextStations": return page_offset(child.get("URL", "")) return None def featured(self, guide_id: str) -> list[TuneInItem]: return self._browse("Featured", guide_id) def local(self, guide_id: str) -> list[TuneInItem]: return self._browse("Local", guide_id) def stations(self, guide_id: str, offset: int = 0) -> list[TuneInItem]: return self._filter_results(self._browse_page(guide_id, offset), "Station") def related(self, guide_id: str) -> list[TuneInItem]: return self._browse("Related", guide_id) def shows(self, guide_id: str) -> list[TuneInItem]: return self._browse("Show", guide_id) def episodes(self, guide_id: str) -> list[TuneInItem]: args = f"&c=pbrowse&id={guide_id}" results = self._tunein("Tune.ashx", args) return self._filter_results(results, "Topic") def _map_listing(self, listing: TuneInItem) -> TuneInItem: # 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: str) -> TuneInItem | None: 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] return None def parse_stream_url(self, url: str) -> list[str]: 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: list[str] = [] playlist_data, content_type = self._get_playlist(url) or (None, None) 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: TuneInItem) -> list[str]: logger.debug(f"Tuning station id {station['guide_id']}") args = f"&id={station['guide_id']}" streams = [ stream for stream in self._tunein("Tune.ashx", args) if "url" in stream and PLACEHOLDER_STREAM not in stream["url"] ] streams.sort(key=stream_priority) stream_uris = [stream["url"] for stream in streams] 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: str) -> TuneInItem | None: if station_id in self._stations: return self._stations[station_id] station = self._station_info(station_id) if station: self._stations[station_id] = station return station def search(self, query: str) -> list[TuneInItem]: 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) # Only return stations results = [ item for item in self._flatten(search_results) if item.get("type", "") == "audio" ] for item in results: self._stations[item["guide_id"]] = item return results @_tunein_cache def _tunein(self, variant: str, args: str) -> list[TuneInItem]: if variant in FORMAT_ARG_VARIANTS: args += self._formats uri = (self._base_uri % variant) + f"?render=json{args}" logger.debug(f"TuneIn request: {uri!r}") try: r = self._client.get(uri, timeout=self._timeout) r.raise_for_status() return r.json()["body"] except Exception as e: logger.info(f"TuneIn API request for {variant} failed: {e}") return [] @_playlist_cache def _get_playlist(self, uri: str) -> tuple[bytes | None, str | None] | None: """Get the body and the content type of a URI, or None if it failed. The cache keeps what this gives back, so a failed request must give back something falsy for the next try to reach the server. """ data, content_type = None, None try: # Defer downloading the body until know it's not a stream with self._client.stream("GET", uri, timeout=self._timeout) 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 media_type(content_type) != "audio/mpeg": data = read_playlist_body(r, self._timeout, PLAYLIST_MAX_BYTES) except Exception as e: logger.info(f"TuneIn playlist request for {uri} failed: {e}") return None return (data, content_type) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5473597 mopidy_tunein-2.0.0/src/mopidy_tunein.egg-info/0000755000175100017510000000000015252072240021205 5ustar00runnerrunner././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1789424799.535532 mopidy_tunein-2.0.0/src/mopidy_tunein.egg-info/PKG-INFO0000644000175100017510000001263415252072240022310 0ustar00runnerrunnerMetadata-Version: 2.4 Name: mopidy-tunein Version: 2.0.0 Summary: Mopidy extension for playing music from TuneIn Author-email: Nick Steel License: Apache-2.0 Project-URL: Homepage, https://github.com/mopidy/mopidy-tunein 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: Topic :: Multimedia :: Sound/Audio :: Players Requires-Python: >=3.13 Description-Content-Type: text/markdown License-File: LICENSE Requires-Dist: httpx>=0.28.1 Requires-Dist: mopidy>=4.0.0 Requires-Dist: pykka>=4.1 Dynamic: license-file # mopidy-tunein [![Latest PyPI version](https://img.shields.io/pypi/v/mopidy-tunein)](https://pypi.org/p/mopidy-tunein) [![CI build status](https://img.shields.io/github/actions/workflow/status/mopidy/mopidy-tunein/ci.yml)](https://github.com/mopidy/mopidy-tunein/actions/workflows/ci.yml) [![Test coverage](https://img.shields.io/codecov/c/gh/mopidy/mopidy-tunein)](https://codecov.io/gh/mopidy/mopidy-tunein) [Mopidy](https://mopidy.com/) extension for playing music from [TuneIn](https://tunein.com). Listen to the world's radio with 70,000 stations of music, sports and news streaming from every continent. 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: ```sh python3 -m pip install mopidy-tunein ``` See https://mopidy.com/ext/tunein/ for alternative installation methods. Most stations stream MP3, which the GStreamer plugins that Mopidy already needs can decode. Some stations only stream AAC. To play those, install `gstreamer1.0-plugins-bad` or `gstreamer1.0-libav`, or the packages that hold these GStreamer plugin sets on your system. If you do not want the AAC stations at all, see the `tunein/formats` config value below. ## Configuration The extension is enabled by default when it is installed. Configuration is not required, but you can add this to your Mopidy configuration file: ```ini [tunein] timeout = 5000 formats = mp3, aac ``` 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 to `station` or `program`. Leave it blank to turn off filtering. Defaults to blank. - `tunein/timeout`: Milliseconds before giving up waiting for results. Defaults to `5000`. - `tunein/formats`: The stream formats to ask TuneIn for, as a comma separated list. TuneIn leaves out the stations that it cannot give you in any of these formats. Defaults to `mp3, aac`. Set it to `mp3` if you do not have the GStreamer plugins for AAC. Mopidy plays the MP3 stream of a station when there is one, and uses AAC only for the stations that have no MP3 stream. - `tunein/location`: The place to use for the "Local Radio" category, as a comma separated latitude and longitude pair, e.g. `51.5,-0.13`. Leave it blank to let TuneIn choose the place from your IP address. ## Usage Browse the "TuneIn" directory to find stations by category, by location, or among the ones that are popular now. TuneIn gives 25 stations at a time, so a category that holds more ends with a "More stations" entry that opens the next 25. ## Known issues The following functionality is not implemented: - User login and access to saved stations. ## Project resources - [Source code](https://github.com/mopidy/mopidy-tunein) - [Issues](https://github.com/mopidy/mopidy-tunein/issues) - [Releases](https://github.com/mopidy/mopidy-tunein/releases) ## Development ### Set up development environment Clone the repo using, e.g. using [gh](https://cli.github.com/): ```sh gh repo clone mopidy/mopidy-tunein ``` Enter the directory, and install dependencies using [uv](https://docs.astral.sh/uv/): ```sh cd mopidy-tunein/ uv sync ``` ### Running tests To run all tests and linters in isolated environments, use [tox](https://tox.wiki/): ```sh tox ``` To only run tests, use [pytest](https://pytest.org/): ```sh pytest ``` To format the code, use [ruff](https://docs.astral.sh/ruff/): ```sh ruff format . ``` To check for lints with ruff, run: ```sh ruff check . ``` To check for type errors, use [pyright](https://microsoft.github.io/pyright/): ```sh pyright . ``` ### Making a release To make a release to PyPI, go to the project's [GitHub releases page](https://github.com/mopidy/mopidy-tunein/releases) and click the "Draft a new release" button. In the "choose a tag" dropdown, select the tag you want to release or create a new tag, e.g. `v0.1.0`. Add a title, e.g. `v0.1.0`, and a description of the changes. Decide if the release is a pre-release (alpha, beta, or release candidate) or should be marked as the latest release, and click "Publish release". Once the release is created, the `release.yml` GitHub Action will automatically build and publish the release to [PyPI](https://pypi.org/project/mopidy-tunein/). ## Credits - Original author: [Nick Steel](https://github.com/kingosticks) - Current maintainer: [Nick Steel](https://github.com/kingosticks) - [Contributors](https://github.com/mopidy/mopidy-tunein/graphs/contributors) Thanks to Marius Wyss for the original version of this extension, and to Brian Hornsby's [XBMC plugin](https://github.com/brianhornsby/plugin.audio.tuneinradio), which it was based on. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5422766 mopidy_tunein-2.0.0/src/mopidy_tunein.egg-info/SOURCES.txt0000644000175100017510000000142515252072240023073 0ustar00runnerrunner.copier-answers.yml .gitignore LICENSE README.md pyproject.toml .github/workflows/ci.yml .github/workflows/release.yml src/mopidy_tunein/__init__.py src/mopidy_tunein/actor.py src/mopidy_tunein/ext.conf src/mopidy_tunein/http.py src/mopidy_tunein/parsers.py src/mopidy_tunein/translator.py src/mopidy_tunein/tunein.py src/mopidy_tunein.egg-info/PKG-INFO src/mopidy_tunein.egg-info/SOURCES.txt src/mopidy_tunein.egg-info/dependency_links.txt src/mopidy_tunein.egg-info/entry_points.txt src/mopidy_tunein.egg-info/requires.txt src/mopidy_tunein.egg-info/scm_file_list.json src/mopidy_tunein.egg-info/scm_version.json src/mopidy_tunein.egg-info/top_level.txt tests/__init__.py tests/test_extension.py tests/test_parsers.py tests/test_playlists.py tests/test_translator.py tests/test_tunein.py././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1789424799.535728 mopidy_tunein-2.0.0/src/mopidy_tunein.egg-info/dependency_links.txt0000644000175100017510000000000115252072240025253 0ustar00runnerrunner ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5359457 mopidy_tunein-2.0.0/src/mopidy_tunein.egg-info/entry_points.txt0000644000175100017510000000005615252072240024504 0ustar00runnerrunner[mopidy.ext] tunein = mopidy_tunein:Extension ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5360994 mopidy_tunein-2.0.0/src/mopidy_tunein.egg-info/requires.txt0000644000175100017510000000004715252072240023606 0ustar00runnerrunnerhttpx>=0.28.1 mopidy>=4.0.0 pykka>=4.1 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424799.5344996 mopidy_tunein-2.0.0/src/mopidy_tunein.egg-info/scm_file_list.json0000644000175100017510000000114415252072240024714 0ustar00runnerrunner{ "files": [ ".copier-answers.yml", ".github/workflows/ci.yml", ".github/workflows/release.yml", ".gitignore", "LICENSE", "README.md", "pyproject.toml", "src/mopidy_tunein/__init__.py", "src/mopidy_tunein/actor.py", "src/mopidy_tunein/ext.conf", "src/mopidy_tunein/http.py", "src/mopidy_tunein/parsers.py", "src/mopidy_tunein/translator.py", "src/mopidy_tunein/tunein.py", "tests/__init__.py", "tests/test_extension.py", "tests/test_parsers.py", "tests/test_playlists.py", "tests/test_translator.py", "tests/test_tunein.py" ] } ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1789424799.530293 mopidy_tunein-2.0.0/src/mopidy_tunein.egg-info/scm_version.json0000644000175100017510000000024015252072240024423 0ustar00runnerrunner{ "tag": "2.0.0", "distance": 0, "node": "ga12326304bbdcfe80b99fcdfd941442e47ae2c2c", "dirty": false, "branch": "HEAD", "node_date": "2026-09-14" } ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1789424799.536187 mopidy_tunein-2.0.0/src/mopidy_tunein.egg-info/top_level.txt0000644000175100017510000000001615252072240023734 0ustar00runnerrunnermopidy_tunein ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1789424799.547998 mopidy_tunein-2.0.0/tests/0000755000175100017510000000000015252072240015203 5ustar00runnerrunner././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4390485 mopidy_tunein-2.0.0/tests/__init__.py0000644000175100017510000000000015252072232017303 0ustar00runnerrunner././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1789424794.43947 mopidy_tunein-2.0.0/tests/test_extension.py0000644000175100017510000000056315252072232020635 0ustar00runnerrunnerfrom mopidy_tunein import Extension def test_get_default_config() -> None: ext = Extension() config = ext.get_default_config() assert "[tunein]" in config assert "enabled = true" in config def test_get_config_schema() -> None: ext = Extension() schema = ext.get_config_schema() assert "timeout" in schema assert "filter" in schema ././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1789424794.43947 mopidy_tunein-2.0.0/tests/test_parsers.py0000644000175100017510000001420115252072232020272 0ustar00runnerrunnerfrom collections.abc import Callable, Generator import pytest from mopidy_tunein import parsers type Detector = Callable[[bytes], bool] type Parser = Callable[[bytes], Generator[str]] BAD = b"foobarbaz" EXTM3U = b"""#EXTM3U #EXTINF:123, Sample artist - Sample title file:///tmp/foo #EXTINF:321,Example Artist - Example \xc5\xa7\xc5\x95 file:///tmp/bar #EXTINF:213,Some Artist - Other title file:///tmp/baz """ URILIST = b""" file:///tmp/foo # a comment \xc5\xa7\xc5\x95 file:///tmp/bar file:///tmp/baz """ PLS = b"""[Playlist] NumberOfEntries=3 File1="file:///tmp/foo" Title1=Sample Title Length1=123 Version=2 File2='file:///tmp/bar' Title2=Example \xc5\xa7\xc5\x95 Length2=321 File3=file:///tmp/baz Title3=Other title Length3=213 Version=2 """ MALFORMED_PLS_WITHOUT_NUMBER_OF_ENTRIES = b"""[Playlist] File1=file:///tmp/foo """ MALFORMED_PLS_WITH_TOO_MANY_ENTRIES = b"""[Playlist] NumberOfEntries=3 File1=file:///tmp/foo """ MALFORMED_PLS_WITH_TOO_FEW_ENTRIES = b"""[Playlist] NumberOfEntries=1 File1=file:///tmp/foo File2=file:///tmp/bar File3=file:///tmp/baz """ MALFORMED_PLS_WITH_INVALID_NUMBER_OF_ENTRIES = b"""[Playlist] NumberOfEntries=three File1=file:///tmp/foo """ MALFORMED_PLS_WITH_HUGE_NUMBER_OF_ENTRIES = b"""[Playlist] NumberOfEntries=5000000 File1=file:///tmp/foo """ MALFORMED_PLS_WITH_UNORDERED_ENTRIES = b"""[Playlist] File10=file:///tmp/baz File2=file:///tmp/bar File1=file:///tmp/foo """ MALFORMED_PLS_WITH_EMPTY_ENTRIES = b"""[Playlist] NumberOfEntries=3 File1= File2="" File3=file:///tmp/foo """ ASX_REFERENCE = b"""[Reference] Ref1=file:///tmp/foo Ref2=file:///tmp/bar Ref3=file:///tmp/baz """ MALFORMED_ASX_REFERENCE_WITH_EMPTY_ENTRIES = b"""[Reference] Ref1= Ref2="" Ref3=file:///tmp/foo """ ASX = b""" Example Sample Title Example \xc5\xa7\xc5\x95 Other title """ SIMPLE_ASX = b""" """ XSPF = b""" Sample Title file:///tmp/foo Example \xc5\xa7\xc5\x95 file:///tmp/bar Other title file:///tmp/baz """ EXPECTED = ["file:///tmp/foo", "file:///tmp/bar", "file:///tmp/baz"] @pytest.mark.parametrize( ("detect_fn", "data"), [ (parsers.detect_extm3u_header, EXTM3U), (parsers.detect_pls_header, PLS), (parsers.detect_asx_reference_header, ASX_REFERENCE), (parsers.detect_asx_header, ASX), (parsers.detect_asx_header, SIMPLE_ASX), (parsers.detect_xspf_header, XSPF), ], ) def test_detect_from_valid_header(detect_fn: Detector, data: bytes) -> None: assert detect_fn(data) is True @pytest.mark.parametrize( "detect_fn", [ parsers.detect_extm3u_header, parsers.detect_pls_header, parsers.detect_asx_reference_header, parsers.detect_asx_header, parsers.detect_xspf_header, ], ) def test_detect_from_invalid_header(detect_fn: Detector) -> None: assert detect_fn(BAD) is False @pytest.mark.parametrize( ("parse_fn", "data"), [ (parsers.parse_extm3u, EXTM3U), (parsers.parse_pls, PLS), (parsers.parse_asx_reference, ASX_REFERENCE), (parsers.parse_asx, ASX), (parsers.parse_asx, SIMPLE_ASX), (parsers.parse_xspf, XSPF), (parsers.parse_urilist, URILIST), ], ) def test_parse_given_format_from_valid_data(parse_fn: Parser, data: bytes) -> None: assert list(parse_fn(data)) == EXPECTED @pytest.mark.parametrize( "parse_fn", [ parsers.parse_extm3u, parsers.parse_pls, parsers.parse_asx_reference, parsers.parse_asx, parsers.parse_xspf, parsers.parse_urilist, ], ) def test_parse_given_format_from_invalid_data(parse_fn: Parser) -> None: assert list(parse_fn(BAD)) == [] @pytest.mark.parametrize( "data", [URILIST, EXTM3U, PLS, ASX_REFERENCE, ASX, SIMPLE_ASX, XSPF], ) def test_parse_any_format_from_valid_data(data: bytes) -> None: assert parsers.parse_playlist(data) == EXPECTED def test_parse_from_invalid_data() -> None: assert parsers.parse_playlist(BAD) == [] @pytest.mark.parametrize( ("data", "expected"), [ pytest.param( MALFORMED_PLS_WITHOUT_NUMBER_OF_ENTRIES, ["file:///tmp/foo"], id="without-number-of-entries", ), pytest.param( MALFORMED_PLS_WITH_TOO_MANY_ENTRIES, ["file:///tmp/foo"], id="with-too-many-entries", ), pytest.param( MALFORMED_PLS_WITH_TOO_FEW_ENTRIES, EXPECTED, id="with-too-few-entries", ), pytest.param( MALFORMED_PLS_WITH_INVALID_NUMBER_OF_ENTRIES, ["file:///tmp/foo"], id="with-invalid-number-of-entries", ), pytest.param( MALFORMED_PLS_WITH_HUGE_NUMBER_OF_ENTRIES, ["file:///tmp/foo"], id="with-huge-number-of-entries", ), pytest.param( MALFORMED_PLS_WITH_UNORDERED_ENTRIES, EXPECTED, id="with-unordered-entries", ), pytest.param( MALFORMED_PLS_WITH_EMPTY_ENTRIES, ["file:///tmp/foo"], id="with-empty-entries", ), ], ) def test_parse_malformed_pls(data: bytes, expected: list[str]) -> None: assert list(parsers.parse_pls(data)) == expected def test_parse_malformed_asx_reference() -> None: # An entry with an empty value must be skipped, not give an empty URI. assert list( parsers.parse_asx_reference(MALFORMED_ASX_REFERENCE_WITH_EMPTY_ENTRIES) ) == ["file:///tmp/foo"] ././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1789424794.43947 mopidy_tunein-2.0.0/tests/test_playlists.py0000644000175100017510000000250515252072232020643 0ustar00runnerrunnerimport pytest from 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 """ EXPECTED = ["file:///tmp/foo", "file:///tmp/bar", "file:///tmp/baz"] @pytest.mark.parametrize( "data", [ pytest.param(ASX, id="asx"), pytest.param(SIMPLE_ASX, id="simple-asx"), pytest.param(OLD_ASX, id="old-asx"), ], ) def test_parse_valid_playlist(data: bytes) -> None: assert list(tunein.parse_asx(data)) == EXPECTED def test_parse_asf_playlist() -> None: assert list(tunein.parse_asx(ASF_ASX)) == [ "mms://tmp.com/foo-mbr?mswmext=.asf", "mms://tmp.com:80/bar-mbr?mswmext=.asf", "http://tmp.com/baz", ] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4395728 mopidy_tunein-2.0.0/tests/test_translator.py0000644000175100017510000000472715252072232021020 0ustar00runnerrunnerfrom __future__ import annotations import pytest from mopidy_tunein import translator @pytest.mark.parametrize( ("uri", "expected"), [ ( "http://cdn-profiles.tunein.com/s1/images/logoq.jpg", "https://cdn-profiles.tunein.com/s1/images/logoq.jpg", ), ( "http://cdn-radiotime-logos.tunein.com/s1q.png", "https://cdn-radiotime-logos.tunein.com/s1q.png", ), ("http://tunein.com/logo.png", "https://tunein.com/logo.png"), # Keep the query and the port. ( "http://cdn-profiles.tunein.com:80/s1.png?t=2", "https://cdn-profiles.tunein.com:80/s1.png?t=2", ), # Leave what is already secure, and what is not TuneIn's, alone. ( "https://cdn-profiles.tunein.com/s1.png", "https://cdn-profiles.tunein.com/s1.png", ), ("http://example.com/s1.png", "http://example.com/s1.png"), ("http://nottunein.com/s1.png", "http://nottunein.com/s1.png"), ( "http://tunein.com.evil.example/s1.png", "http://tunein.com.evil.example/s1.png", ), ], ) def test_secure_image_uri(uri: str, expected: str) -> None: assert translator.secure_image_uri(uri) == expected def test_unparse_page_uri() -> None: assert translator.unparse_page_uri("c57943", 26) == "tunein:stations:c57943_26" @pytest.mark.parametrize( ("identifier", "expected"), [ ("c57943_26", ("c57943", 26)), ("c57943", ("c57943", 0)), ("c57943_", ("c57943", 0)), ("c57943_lots", ("c57943", 0)), ], ) def test_parse_page(identifier: str, expected: tuple[str, int]) -> None: assert translator.parse_page(identifier) == expected def test_a_page_uri_can_be_parsed_back() -> None: uri = translator.unparse_page_uri("c57943", 26) variant, identifier = translator.parse_uri(uri) assert variant == "stations" assert identifier is not None assert translator.parse_page(identifier) == ("c57943", 26) def test_station_to_image_uses_https() -> None: station = {"image": "http://cdn-profiles.tunein.com/s1/images/logoq.jpg"} image = translator.station_to_image(station) assert image is not None assert image.uri == "https://cdn-profiles.tunein.com/s1/images/logoq.jpg" def test_station_to_image_without_an_image() -> None: assert translator.station_to_image({"guide_id": "s1"}) is None assert translator.station_to_image(None) is None ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1789424794.4395728 mopidy_tunein-2.0.0/tests/test_tunein.py0000644000175100017510000006246115252072232020130 0ustar00runnerrunnerfrom __future__ import annotations import logging import re from typing import TYPE_CHECKING, Any import httpx import pytest from mopidy_tunein import tunein if TYPE_CHECKING: from collections.abc import Callable, Generator from pytest_httpx import HTTPXMock type Parser = Callable[[bytes], Generator[str]] BASE = "https://opml.radiotime.com/" ROOT = [ {"element": "outline", "type": "link", "text": "Local Radio", "key": "local"}, {"element": "outline", "type": "link", "text": "Music", "key": "music"}, {"element": "outline", "type": "link", "text": "By Language", "key": "language"}, ] STATION_ONE = { "element": "outline", "type": "audio", "text": "Beat FM 105.5", "URL": "http://opml.radiotime.com/Tune.ashx?id=s128641", "guide_id": "s128641", "subtext": "Mer variert musikk", "item": "station", "image": "http://cdn.example.com/s128641.png", } STATION_TWO = { "element": "outline", "type": "audio", "text": "Heart Radio", "URL": "http://opml.radiotime.com/Tune.ashx?id=s346757", "guide_id": "s346757", "subtext": "Non-stop feel good", "item": "station", } SECTION_LINK = { "element": "outline", "type": "link", "text": "Country", "URL": "http://opml.radiotime.com/Browse.ashx?id=c57940", "guide_id": "c57940", } STATIONS_SECTION = [ { "element": "outline", "text": "Stations", "key": "stations", "children": [STATION_ONE, STATION_TWO], }, { "element": "outline", "text": "Local Stations", "key": "local", "children": [STATION_TWO], }, ] NEXT_STATIONS = { "element": "outline", "type": "link", "text": "More Stations", "URL": "http://opml.radiotime.com/Browse.ashx?offset=26&id=c1&filter=s", "key": "nextStations", } PAGED_SECTION = [ { "element": "outline", "text": "Stations", "key": "stations", "children": [STATION_ONE, STATION_TWO, NEXT_STATIONS], } ] DESCRIBE = [ { "element": "outline", "text": "Listing", "key": "listing", "children": [ { "element": "station", "guide_id": "s24791", "name": "WYPR", "slogan": "Baltimore Public Media", "logo": "http://cdn.example.com/s24791.png", } ], } ] DUAL_FORMAT_TUNE = [ { "element": "audio", "url": "http://a/aac-high", "media_type": "aac", "bitrate": 128, }, {"element": "audio", "url": "http://a/mp3-low", "media_type": "mp3", "bitrate": 64}, { "element": "audio", "url": "http://a/mp3-high", "media_type": "mp3", "bitrate": 192, }, {"element": "audio", "url": "http://a/aac-low", "media_type": "aac", "bitrate": 48}, ] PLACEHOLDER_TUNE = [ { "element": "audio", "url": "http://cdn-cms.tunein.com/service/Audio/notcompatible.enUS.mp3", "media_type": "mp3", "bitrate": 24, }, {"element": "audio", "url": "http://a/real", "media_type": "aac", "bitrate": 64}, ] TUNE = [ {"element": "audio", "url": "http://stream.example.com/one", "guide_id": "e1"}, {"element": "audio", "url": "http://stream.example.com/two", "guide_id": "e2"}, {"element": "audio", "url": "http://stream.example.com/one", "guide_id": "e3"}, ] SEARCH = [ {"element": "outline", "type": "link", "text": "Artist: BBC", "guide_id": "m1"}, STATION_ONE, {"element": "outline", "text": "Group", "children": [STATION_TWO]}, ] def api_body(body: Any) -> dict[str, Any]: # noqa: ANN401 return {"head": {"status": "200"}, "body": body} @pytest.fixture(autouse=True) def _clear_caches() -> None: # The cache decorators are class attributes, so they outlive an instance. tunein.TuneIn._tunein_cache.clear() tunein.TuneIn._playlist_cache.clear() @pytest.fixture def api() -> tunein.TuneIn: return tunein.TuneIn(timeout=1000) def api_url(variant: str) -> re.Pattern[str]: """Match an API request whatever query string it carries.""" return re.compile(rf"^{re.escape(BASE + variant)}\?") def add_response( httpx_mock: HTTPXMock, variant: str, body: Any, # noqa: ANN401 **kwargs: Any, # noqa: ANN401 ) -> None: httpx_mock.add_response( url=api_url(variant), json=api_body(body), **kwargs, ) def request_url(httpx_mock: HTTPXMock, index: int = 0) -> str: return str(httpx_mock.get_requests()[index].url) def test_no_filter_by_default(api: tunein.TuneIn) -> None: assert api._filter == "" @pytest.mark.parametrize( ("filter_", "expected"), [("station", "&filter=s"), ("program", "&filter=p")], ) def test_known_filter_is_abbreviated(filter_: str, expected: str) -> None: assert tunein.TuneIn(1000, filter_)._filter == expected def test_unknown_filter_is_ignored() -> None: assert tunein.TuneIn(1000, "nonsense")._filter == "" def test_request_returns_the_body(api: tunein.TuneIn, httpx_mock: HTTPXMock) -> None: add_response(httpx_mock, "Browse.ashx", ROOT) assert api._tunein("Browse.ashx", "&c=music") == ROOT def test_request_sends_the_expected_query( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", ROOT) api._tunein("Browse.ashx", "&c=music") assert request_url(httpx_mock) == BASE + "Browse.ashx?render=json&c=music" def test_request_http_error_gives_no_results( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", ROOT, status_code=500) assert api._tunein("Browse.ashx", "") == [] def test_request_connection_error_gives_no_results( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_exception(httpx.ConnectError("boom"), url=api_url("Browse.ashx")) assert api._tunein("Browse.ashx", "") == [] def test_request_result_is_cached(api: tunein.TuneIn, httpx_mock: HTTPXMock) -> None: add_response(httpx_mock, "Browse.ashx", ROOT) api._tunein("Browse.ashx", "") api._tunein("Browse.ashx", "") assert len(httpx_mock.get_requests()) == 1 def test_reload_clears_the_request_cache( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", ROOT, is_reusable=True) api._tunein("Browse.ashx", "") api.reload() api._tunein("Browse.ashx", "") assert len(httpx_mock.get_requests()) == 2 def test_categories_root_appends_trending_and_drops_language( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", ROOT) keys = [c["key"] for c in api.categories()] assert keys == ["local", "music", "trending"] def test_categories_root_does_not_modify_the_cached_data( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", ROOT) first = api.categories() second = api.categories() assert first == second def test_categories_language_is_not_requested( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: assert api.categories("language") == [] assert not httpx_mock.get_requests() def test_categories_local_sends_the_configured_location(httpx_mock: HTTPXMock) -> None: api = tunein.TuneIn(timeout=1000, location="51.5,-0.13") add_response(httpx_mock, "Browse.ashx", []) api.categories("local") assert "latlon=51.5,-0.13" in request_url(httpx_mock) def test_categories_local_without_a_location( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", []) api.categories("local") assert "latlon=" not in request_url(httpx_mock) def test_the_location_is_only_for_local_radio(httpx_mock: HTTPXMock) -> None: api = tunein.TuneIn(timeout=1000, location="51.5,-0.13") add_response(httpx_mock, "Browse.ashx", []) api.categories("music") assert "latlon=" not in request_url(httpx_mock) def test_categories_location_uses_the_root_region( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", [SECTION_LINK]) api.categories("location") assert "id=r0" in request_url(httpx_mock) def test_categories_podcast_is_flattened( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", STATIONS_SECTION) result = api.categories("podcast") assert [s["guide_id"] for s in result] == ["s128641", "s346757", "s346757"] def test_stations_returns_the_matching_section( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", STATIONS_SECTION) result = api.stations("c1") assert [s["guide_id"] for s in result] == ["s128641", "s346757"] @pytest.mark.parametrize( ("uri", "expected"), [ ("http://a/Browse.ashx?offset=26&id=c1", 26), ("http://a/Browse.ashx?id=c1&offset=51&filter=s", 51), ("http://a/Browse.ashx?id=c1", None), ("http://a/Browse.ashx?offset=lots", None), ("", None), ], ) def test_page_offset(uri: str, expected: int | None) -> None: assert tunein.page_offset(uri) == expected def test_next_stations_offset_finds_the_link( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", PAGED_SECTION) assert api.next_stations_offset("c1") == 26 def test_next_stations_offset_without_a_link( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", STATIONS_SECTION) assert api.next_stations_offset("c1") is None def test_the_next_page_link_is_not_a_station( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", PAGED_SECTION) assert [s["guide_id"] for s in api.stations("c1")] == ["s128641", "s346757"] def test_stations_asks_for_the_given_page( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", PAGED_SECTION) api.stations("c1", offset=26) assert "offset=26" in request_url(httpx_mock) def test_stations_asks_for_no_offset_on_the_first_page( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", PAGED_SECTION) api.stations("c1") assert "offset=" not in request_url(httpx_mock) def test_local_returns_the_matching_section( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", STATIONS_SECTION) assert [s["guide_id"] for s in api.local("c1")] == ["s346757"] def test_browse_unmatched_section_is_empty( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", STATIONS_SECTION) assert api.shows("c1") == [] def test_locations_keeps_only_links(api: tunein.TuneIn, httpx_mock: HTTPXMock) -> None: add_response(httpx_mock, "Browse.ashx", [SECTION_LINK, STATION_ONE]) assert api.locations("r0") == [SECTION_LINK] def test_browse_fills_the_station_cache( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", STATIONS_SECTION) api.stations("c1") assert set(api._stations) == {"s128641", "s346757"} def test_filter_results_drops_items_without_a_guide_id(api: tunein.TuneIn) -> None: assert api._filter_results([{"element": "outline", "text": "No id"}]) == [] def test_flatten_expands_children(api: tunein.TuneIn) -> None: result = api._flatten(STATIONS_SECTION) assert [s["guide_id"] for s in result] == ["s128641", "s346757", "s346757"] def test_flatten_keeps_childless_items(api: tunein.TuneIn) -> None: assert api._flatten([STATION_ONE]) == [STATION_ONE] def test_station_maps_the_listing(api: tunein.TuneIn, httpx_mock: HTTPXMock) -> None: add_response(httpx_mock, "Describe.ashx", DESCRIBE) station = api.station("s24791") assert station == { "text": "WYPR", "guide_id": "s24791", "type": "audio", "image": "http://cdn.example.com/s24791.png", "subtext": "Baltimore Public Media", "URL": BASE + "Tune.ashx?id=s24791", } def test_station_is_cached_after_the_first_lookup( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Describe.ashx", DESCRIBE) api.station("s24791") api.reload() # Only clears the request cache, not the station cache. api._stations["s24791"] = {"guide_id": "s24791", "text": "From cache"} station = api.station("s24791") assert station is not None assert station["text"] == "From cache" def test_unknown_station_is_none(api: tunein.TuneIn, httpx_mock: HTTPXMock) -> None: add_response(httpx_mock, "Describe.ashx", []) assert api.station("s404") is None def test_failed_station_lookup_is_not_cached( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Describe.ashx", []) api.station("s404") assert "s404" not in api._stations def test_tune_returns_the_stream_urls_without_duplicates( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Tune.ashx", TUNE) assert api.tune({"guide_id": "s1"}) == [ "http://stream.example.com/one", "http://stream.example.com/two", ] def test_tune_prefers_mp3_then_the_higher_bitrate(httpx_mock: HTTPXMock) -> None: api = tunein.TuneIn(timeout=1000, formats=["mp3", "aac"]) add_response(httpx_mock, "Tune.ashx", DUAL_FORMAT_TUNE) assert api.tune({"guide_id": "s1"}) == [ "http://a/mp3-high", "http://a/mp3-low", "http://a/aac-high", "http://a/aac-low", ] def test_tune_keeps_an_aac_only_station( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Tune.ashx", [DUAL_FORMAT_TUNE[0], DUAL_FORMAT_TUNE[3]]) assert api.tune({"guide_id": "s1"}) == ["http://a/aac-high", "http://a/aac-low"] def test_tune_drops_the_not_compatible_recording( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Tune.ashx", PLACEHOLDER_TUNE) assert api.tune({"guide_id": "s1"}) == ["http://a/real"] def test_tune_puts_an_unknown_format_last( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response( httpx_mock, "Tune.ashx", [ { "element": "audio", "url": "http://a/wma", "media_type": "wma", "bitrate": 999, }, { "element": "audio", "url": "http://a/aac", "media_type": "aac", "bitrate": 32, }, ], ) assert api.tune({"guide_id": "s1"}) == ["http://a/aac", "http://a/wma"] @pytest.mark.parametrize( ("stream", "expected"), [ ({"media_type": "mp3", "bitrate": 128}, (0, -128)), ({"media_type": "aac", "bitrate": 64}, (1, -64)), ({"media_type": "wma", "bitrate": 128}, (2, -128)), ({"media_type": "mp3", "bitrate": "96"}, (0, -96)), ({"media_type": "mp3"}, (0, 0)), ({"media_type": "mp3", "bitrate": None}, (0, 0)), ({"media_type": "mp3", "bitrate": "many"}, (0, 0)), ({}, (2, 0)), ], ) def test_stream_priority(stream: dict[str, Any], expected: tuple[int, int]) -> None: assert tunein.stream_priority(stream) == expected def test_formats_are_sent_with_browse_search_and_tune(httpx_mock: HTTPXMock) -> None: api = tunein.TuneIn(timeout=1000, formats=["mp3", "aac"]) add_response(httpx_mock, "Browse.ashx", []) add_response(httpx_mock, "Search.ashx", []) add_response(httpx_mock, "Tune.ashx", []) api.stations("c1") api.search("bbc") api.tune({"guide_id": "s1"}) assert all("formats=mp3,aac" in request_url(httpx_mock, i) for i in range(3)) def test_formats_are_not_sent_when_not_configured( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Browse.ashx", []) api.stations("c1") assert "formats=" not in request_url(httpx_mock) def test_formats_are_not_sent_when_describing_a_station(httpx_mock: HTTPXMock) -> None: api = tunein.TuneIn(timeout=1000, formats=["mp3", "aac"]) add_response(httpx_mock, "Describe.ashx", DESCRIBE) api.station("s24791") assert "formats=" not in request_url(httpx_mock) def test_tune_drops_entries_without_a_url( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Tune.ashx", [{"element": "audio", "guide_id": "e1"}]) assert api.tune({"guide_id": "s1"}) == [] def test_tune_logs_a_station_without_streams( api: tunein.TuneIn, caplog: pytest.LogCaptureFixture, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Tune.ashx", []) with caplog.at_level(logging.ERROR): api.tune({"guide_id": "s1"}) assert "Failed to tune station id s1" in caplog.text def test_search_keeps_only_stations(api: tunein.TuneIn, httpx_mock: HTTPXMock) -> None: add_response(httpx_mock, "Search.ashx", SEARCH) result = api.search("bbc") assert [s["guide_id"] for s in result] == ["s128641", "s346757"] def test_search_fills_the_station_cache( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: add_response(httpx_mock, "Search.ashx", SEARCH) api.search("bbc") assert set(api._stations) == {"s128641", "s346757"} def test_search_empty_query_is_not_requested( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: assert api.search("") == [] assert not httpx_mock.get_requests() def test_search_filter_is_part_of_the_query(httpx_mock: HTTPXMock) -> None: add_response(httpx_mock, "Search.ashx", []) tunein.TuneIn(1000, "station").search("bbc") assert "filter=s" in request_url(httpx_mock) @pytest.mark.parametrize("url", ["http://a/b.mp3", "http://a/b.wma"]) def test_parse_stream_url_uses_an_audio_extension_as_is( api: tunein.TuneIn, url: str, httpx_mock: HTTPXMock ) -> None: assert api.parse_stream_url(url) == [url] assert not httpx_mock.get_requests() def test_parse_stream_url_parses_a_playlist( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response( url="http://a/b.pls", content=b"[playlist]\nNumberOfEntries=1\nFile1=http://a/stream\n", headers={"content-type": "audio/x-scpls"}, ) assert api.parse_stream_url("http://a/b.pls") == ["http://a/stream"] def test_parse_stream_url_uses_a_stream_as_is( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response( url="http://a/stream", content=b"", headers={"content-type": "audio/mpeg"} ) assert api.parse_stream_url("http://a/stream") == ["http://a/stream"] def test_parse_stream_url_falls_back_to_the_content_type( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response( url="http://a/listen", content=b"[playlist]\nNumberOfEntries=1\nFile1=http://a/stream\n", headers={"content-type": "audio/x-scpls; charset=UTF-8"}, ) assert api.parse_stream_url("http://a/listen") == ["http://a/stream"] def test_parse_stream_url_gives_no_results_for_a_malformed_playlist( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response( url="http://a/b.pls", content=b"not a playlist", headers={"content-type": "audio/x-scpls"}, ) assert api.parse_stream_url("http://a/b.pls") == [] @pytest.mark.parametrize( ("content_type", "expected"), [ ("audio/x-scpls", "audio/x-scpls"), ("audio/x-scpls; charset=UTF-8", "audio/x-scpls"), ("Audio/X-SCPLS", "audio/x-scpls"), (" audio/mpeg ; charset=utf-8", "audio/mpeg"), ("", ""), ], ) def test_media_type_drops_parameters(content_type: str, expected: str) -> None: assert tunein.media_type(content_type) == expected @pytest.mark.parametrize( ("extension", "expected"), [ (".pls", tunein.parse_pls), (".m3u", tunein.parse_m3u), (".asx", tunein.parse_asx), (".wax", tunein.parse_asx), (".mp3", None), ], ) def test_find_playlist_parser_uses_the_extension_first( extension: str, expected: Parser | None ) -> None: assert tunein.find_playlist_parser(extension, None) is expected @pytest.mark.parametrize( ("content_type", "expected"), [ # These are the content types the TuneIn servers were seen to send. ("audio/x-scpls; charset=UTF-8", tunein.parse_pls), ("audio/x-scpls", tunein.parse_pls), ("audio/x-mpegurl", tunein.parse_m3u), ("application/x-mpegurl", tunein.parse_m3u), ("video/x-ms-asf", tunein.parse_asx), ("text/html", None), ("audio/mpeg", None), ], ) def test_find_playlist_parser_falls_back_to_the_content_type( content_type: str, expected: Parser | None ) -> None: assert tunein.find_playlist_parser(".xxx", content_type) is expected def test_find_playlist_parser_prefers_the_extension() -> None: parser = tunein.find_playlist_parser(".pls", "audio/x-mpegurl") assert parser is tunein.parse_pls def test_find_playlist_parser_without_hints() -> None: assert tunein.find_playlist_parser("", None) is None class EndlessResponse: """Stands in for a live stream: a body that never ends.""" url = "http://a/stream" def __init__(self) -> None: self.chunks_read = 0 def iter_bytes(self, chunk_size: int) -> Generator[bytes]: while True: self.chunks_read += 1 yield b"x" * chunk_size def test_read_playlist_body_gives_up_on_an_endless_body() -> None: response = EndlessResponse() result = tunein.read_playlist_body(response, timeout=30, max_bytes=1024) # type: ignore[arg-type] assert result is None assert response.chunks_read < 10 # Stopped early, did not run away. def test_read_playlist_body_gives_up_at_the_deadline( monkeypatch: pytest.MonkeyPatch, ) -> None: clock = iter([0.0, 0.0, 100.0]) monkeypatch.setattr(tunein.time, "time", lambda: next(clock)) response = EndlessResponse() result = tunein.read_playlist_body( response, # type: ignore[arg-type] timeout=1, max_bytes=1024 * 1024, ) assert result is None def test_get_playlist_skips_an_audio_body( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response( url="http://a/s", content=b"audio", headers={"content-type": "audio/mpeg"} ) assert api._get_playlist("http://a/s") == (None, "audio/mpeg") def test_get_playlist_skips_an_audio_body_with_a_charset( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response( url="http://a/s", content=b"audio", headers={"content-type": "audio/mpeg; charset=UTF-8"}, ) result = api._get_playlist("http://a/s") assert result == (None, "audio/mpeg; charset=UTF-8") def test_get_playlist_reads_a_playlist_body( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response( url="http://a/p.pls", content=b"[playlist]", headers={"content-type": "audio/x-scpls"}, ) assert api._get_playlist("http://a/p.pls") == (b"[playlist]", "audio/x-scpls") def test_get_playlist_failed_request_gives_nothing( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response(url="http://a/p.pls", status_code=404) assert api._get_playlist("http://a/p.pls") is None def test_get_playlist_does_not_keep_a_failed_request( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response(url="http://a/p.pls", status_code=503) httpx_mock.add_response( url="http://a/p.pls", content=b"[playlist]", headers={"content-type": "audio/x-scpls"}, ) first = api._get_playlist("http://a/p.pls") second = api._get_playlist("http://a/p.pls") assert first is None assert second == (b"[playlist]", "audio/x-scpls") def test_get_playlist_keeps_a_result_that_worked( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response( url="http://a/p.pls", content=b"[playlist]", headers={"content-type": "audio/x-scpls"}, ) api._get_playlist("http://a/p.pls") api._get_playlist("http://a/p.pls") assert len(httpx_mock.get_requests()) == 1 def test_parse_stream_url_after_a_failed_request( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response(url="http://a/p.pls", status_code=503) httpx_mock.add_response( url="http://a/p.pls", content=b"[playlist]\nNumberOfEntries=1\nFile1=http://a/stream\n", headers={"content-type": "audio/x-scpls"}, ) assert api.parse_stream_url("http://a/p.pls") == [] assert api.parse_stream_url("http://a/p.pls") == ["http://a/stream"] def test_get_playlist_body_over_the_size_limit_is_not_a_playlist( api: tunein.TuneIn, monkeypatch: pytest.MonkeyPatch, httpx_mock: HTTPXMock ) -> None: monkeypatch.setattr(tunein, "PLAYLIST_MAX_BYTES", 1024) httpx_mock.add_response( url="http://a/stream", content=b"x" * 4096, headers={"content-type": "audio/aac"}, ) assert api._get_playlist("http://a/stream") == (None, "audio/aac") def test_get_playlist_body_under_the_size_limit_is_a_playlist( api: tunein.TuneIn, httpx_mock: HTTPXMock ) -> None: httpx_mock.add_response( url="http://a/p.pls", content=b"[playlist]\nFile1=http://a/s\n", headers={"content-type": "audio/x-scpls"}, ) result = api._get_playlist("http://a/p.pls") assert result is not None assert result[0] == b"[playlist]\nFile1=http://a/s\n"