Mopidy-GMusic-4.0.0/0000775000175000017500000000000013577732634014370 5ustar jodaljodal00000000000000Mopidy-GMusic-4.0.0/.circleci/0000775000175000017500000000000013577732634016223 5ustar jodaljodal00000000000000Mopidy-GMusic-4.0.0/.circleci/config.yml0000664000175000017500000000206513577731553020215 0ustar jodaljodal00000000000000version: 2.1 orbs: codecov: codecov/codecov@1.0.5 workflows: version: 2 test: jobs: - py38 - py37 - black - check-manifest - flake8 jobs: py38: &test-template docker: - image: mopidy/ci-python:3.8 steps: - checkout - restore_cache: name: Restoring tox cache key: tox-v1-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.cfg" }} - run: name: Run tests command: | tox -e $CIRCLE_JOB -- \ --junit-xml=test-results/pytest/results.xml \ --cov-report=xml - save_cache: name: Saving tox cache key: tox-v1-{{ .Environment.CIRCLE_JOB }}-{{ checksum "setup.cfg" }} paths: - ./.tox - ~/.cache/pip - codecov/upload: file: coverage.xml - store_test_results: path: test-results py37: <<: *test-template docker: - image: mopidy/ci-python:3.7 black: *test-template check-manifest: *test-template flake8: *test-template Mopidy-GMusic-4.0.0/.mailmap0000664000175000017500000000061013577731553016005 0ustar jodaljodal00000000000000Alexandre Barreira Hans Elias J. Kaleb Elwert q Ronald Hecht Ronald Hecht Shae Erisson Stein Magnus Jodal Yannik Enss Mopidy-GMusic-4.0.0/CHANGELOG.rst0000664000175000017500000000654113577732377016423 0ustar jodaljodal00000000000000 ********* Changelog ********* v4.0.0 (2019-12-22) =================== - Depend on final release of Mopidy 3.0.0. v4.0.0a1 (2019-11-25) ===================== - Require Mopidy >= 3.0.0a5. (PR: #227) - Require Python >= 3.7. (Fixes: #226, PR: #227) - Require gmusicapi >= 12.1. - Switch from username/password to OAuth flow. - Change name of the "Promoted" playlist to "Top". - Report the bitrate of tracks based on the bitrate config. (PR: #111) - Update project setup. (PR: #227) v3.0.0 (2018-06-27) =================== - Add Top Tracks to Artists. - Work around broken track IDs returned by Google. - Require Device ID to be set in the config. v2.0.0 (2016-11-2) =================== - Require gmusicapi >= 10.1. - Make search work for gmusicapi >= 10.0. (Fixes: #116, PR: #117) - Enable search for accounts without All Access. (PR: #117) - Require cachetools. (PR: #119) - Caching should be more consistent. (Fixes: #63, PR: #122) - Autodetect All Access if not specified in config. (PR: #123) - General refactoring. (PR: #120, #121) - Much faster playlist loading. (PR: #130) - Library browse rewrite. (PR: #131) - Add IFL playlist and improve radio caching. (PR: #135) v1.0.0 (2015-10-23) =================== - Require Mopidy >= 1.0. - Require gmusicapi >= 6.0. - Update to work with new playback API in Mopidy 1.0. (PR: #75) - Update to work with new search API in Mopidy 1.0. - Fix crash when tracks lack album or artist information. (Fixes: #74, PR: #24, also thanks to PRs #27, #64) - Log error on login failure instead of swallowing the error. (PR: #36) - Add support for All Access search and lookup (PR: #34) - Add dynamic playlist based on top rated tracks. - Add support for radio stations in browser and/or as playlists. - Add support for browsing artists and albums in the cached library. - Add cover art to ``Album.images`` model field. - Add background refreshing of library and playlists. (Fixes: #21) - Fix authentication issues. (Fixes: #82, #87) - Add LRU cache for All Access albums and tracks. - Increment Google's play count if 50% or 240s of the track has been played. (PR: #51, and later changes) - Let gmusicapi use the device's MAC address as device ID by default. - Fix increasing of play counts in Google Play Music. (Fixes: #96) - Fix scrobbling of tracks to Last.fm through Mopidy-Scrobbler. (Fixes: #60) - Fix unhandled crashes on network connectivity issues. (Fixes: #85) - Add ``gmusic/bitrate`` config to select streaming bitrate. v0.3.0 (2014-01-28) =================== - Issue #19: Public playlist support - Issue #16: All playlist files are playable now - Require Mopidy >= 0.18. v0.2.2 (2013-11-11) =================== - Issue #17: Fixed a bug regarding various artist albums (compilations) - Issue #18: Fixed Google Music API playlist call for version 3.0.0 - Issue #16 (partial): All Access tracks in playlists are playable now v0.2.1 (2013-10-11) =================== - Issue #15: Fixed a bug regarding the translation of Google album artists to Mopidy album artists v0.2 (2013-10-11) ================= - Issue #12: Now able to play music from Google All Access - Issue #9: Switched to the Mobileclient API of Google Music API - Issue #4: Generate Album and Artist Search Results v0.1.1 (2013-09-23) =================== - Issue #11: Browsing the library fixed by implementing find_exact() v0.1 (2013-09-16) ================= - Initial release Mopidy-GMusic-4.0.0/LICENSE0000664000175000017500000002613613577731553015404 0ustar jodaljodal00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Mopidy-GMusic-4.0.0/MANIFEST.in0000664000175000017500000000041213577731553016122 0ustar jodaljodal00000000000000include *.py include *.rst include .mailmap include LICENSE include MANIFEST.in include pyproject.toml include tox.ini recursive-include .circleci * recursive-include .github * include mopidy_*/ext.conf recursive-include tests *.py recursive-include tests/data * Mopidy-GMusic-4.0.0/Mopidy_GMusic.egg-info/0000775000175000017500000000000013577732634020572 5ustar jodaljodal00000000000000Mopidy-GMusic-4.0.0/Mopidy_GMusic.egg-info/PKG-INFO0000664000175000017500000001401713577732634021672 0ustar jodaljodal00000000000000Metadata-Version: 2.1 Name: Mopidy-GMusic Version: 4.0.0 Summary: Mopidy extension for playing music from Google Play Music Home-page: https://github.com/mopidy/mopidy-gmusic Author: Ronald Hecht Author-email: ronald.hecht@gmx.de License: Apache License, Version 2.0 Description: ************* Mopidy-GMusic ************* .. image:: https://img.shields.io/pypi/v/Mopidy-GMusic :target: https://pypi.org/project/Mopidy-GMusic/ :alt: Latest PyPI version .. image:: https://img.shields.io/circleci/build/gh/mopidy/mopidy-gmusic :target: https://circleci.com/gh/mopidy/mopidy-gmusic :alt: CircleCI build status .. image:: https://img.shields.io/codecov/c/gh/mopidy/mopidy-gmusic :target: https://codecov.io/gh/mopidy/mopidy-gmusic :alt: Test coverage `Mopidy `_ extension for playing music from `Google Play Music `_. Co-maintainer wanted ==================== We are currently looking for a co-maintainer. Preferably someone who is familiar with the codebase, familiar with Python development, and uses the uploaded music feature. If you're interested, please take a look at the code base and work on submitting a pull request or two to show you understand how everything works together. If you need help getting a development environment set up, don't hesitate to ping "belak" in the ``#mopidy`` channel on the Freenode IRC network. Dependencies ============ You must have a Google account, and either: - have some music uploaded to your Google Play Music library, or - have a paid subscription for Google Play Music. Installation ============ Install by running:: sudo python3 -m pip install Mopidy-GMusic See https://mopidy.com/ext/gmusic/ for alternative installation methods Configuration ============= Run ``mopidy gmusic login`` to obtain a refresh token, and then include it in your config file:: [gmusic] refresh_token = Google Play Music now requires all clients to provide a device ID. In the past, Mopidy-GMusic generated one automatically from your MAC address, but Google seems to have changed their API in a way that prevents this from working. Therefore you will need to configure one manually. If no device ID is configured, Mopidy-GMusic will output a list of registered devices and their IDs. You can either use one of those IDs in your config file, or use the special value ``mac`` if you want gmusicapi to use the old method of generating an ID from your MAC address:: [gmusic] deviceid = 0123456789abcdef # or deviceid = mac By default, All Access will be enabled automatically if you subscribe. You may force enable or disable it by using the ``all_access`` option:: [gmusic] all_access = true By default, the bitrate is set to 160 kbps. You can change this to either 128 or 320 kbps by setting:: [gmusic] bitrate = 320 All Access radios are available as browsable content or playlist. The following are the default config values:: [gmusic] # Show radio stations in content browser radio_stations_in_browse = true # Show radio stations as playlists radio_stations_as_playlists = false # Limit the number of radio stations, unlimited if unset radio_stations_count = # Limit the number or tracks for each radio station radio_tracks_count = 25 The library and playlists are automatically refresh at regular intervals. Refreshing can be CPU intensive on very low-powered machines, e.g. Raspberry Pi Zero. The refresh intervals can be configured:: [gmusic] # How often to refresh the library, in minutes refresh_library = 1440 # How often to refresh playlists, in minutes refresh_playlists = 60 Usage ===== The extension is enabled by default if all dependencies are available. You can simply browse through your library and search for tracks, albums, and artists. Google Play Music playlists are imported as well. You can even add songs from your All Access subscription to your library. Mopidy will able to play them. Project resources ================= - `Source code `_ - `Issue tracker `_ - `Changelog `_ Credits ======= - Original author: `Ronald Hecht `_ - Current maintainer: `Kaleb Elwert `_ - `Contributors `_ Platform: UNKNOWN Classifier: Environment :: No Input/Output (Daemon) Classifier: Intended Audience :: End Users/Desktop Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Topic :: Multimedia :: Sound/Audio :: Players Requires-Python: >=3.7 Provides-Extra: lint Provides-Extra: release Provides-Extra: test Provides-Extra: dev Mopidy-GMusic-4.0.0/Mopidy_GMusic.egg-info/SOURCES.txt0000664000175000017500000000154713577732634022465 0ustar jodaljodal00000000000000.mailmap CHANGELOG.rst LICENSE MANIFEST.in README.rst pyproject.toml setup.cfg setup.py tox.ini .circleci/config.yml Mopidy_GMusic.egg-info/PKG-INFO Mopidy_GMusic.egg-info/SOURCES.txt Mopidy_GMusic.egg-info/dependency_links.txt Mopidy_GMusic.egg-info/entry_points.txt Mopidy_GMusic.egg-info/not-zip-safe Mopidy_GMusic.egg-info/requires.txt Mopidy_GMusic.egg-info/top_level.txt mopidy_gmusic/__init__.py mopidy_gmusic/backend.py mopidy_gmusic/commands.py mopidy_gmusic/ext.conf mopidy_gmusic/library.py mopidy_gmusic/playback.py mopidy_gmusic/playlists.py mopidy_gmusic/repeating_timer.py mopidy_gmusic/scrobbler_frontend.py mopidy_gmusic/session.py mopidy_gmusic/translator.py tests/__init__.py tests/test_extension.py tests/test_library.py tests/test_playback.py tests/test_playlist.py tests/test_repeating_timer.py tests/test_scrobbler_frontend.py tests/test_session.pyMopidy-GMusic-4.0.0/Mopidy_GMusic.egg-info/dependency_links.txt0000664000175000017500000000000113577732634024640 0ustar jodaljodal00000000000000 Mopidy-GMusic-4.0.0/Mopidy_GMusic.egg-info/entry_points.txt0000664000175000017500000000005713577732634024072 0ustar jodaljodal00000000000000[mopidy.ext] gmusic = mopidy_gmusic:Extension Mopidy-GMusic-4.0.0/Mopidy_GMusic.egg-info/not-zip-safe0000664000175000017500000000000113577732436023020 0ustar jodaljodal00000000000000 Mopidy-GMusic-4.0.0/Mopidy_GMusic.egg-info/requires.txt0000664000175000017500000000052213577732634023171 0ustar jodaljodal00000000000000Mopidy>=3.0.0 Pykka>=2.0.1 setuptools gmusicapi>=12.1 requests>=2.0 cachetools>=1.0 [dev] black check-manifest flake8 flake8-bugbear flake8-import-order isort[pyproject] twine wheel pytest pytest-cov [lint] black check-manifest flake8 flake8-bugbear flake8-import-order isort[pyproject] [release] twine wheel [test] pytest pytest-cov Mopidy-GMusic-4.0.0/Mopidy_GMusic.egg-info/top_level.txt0000664000175000017500000000001613577732634023321 0ustar jodaljodal00000000000000mopidy_gmusic Mopidy-GMusic-4.0.0/PKG-INFO0000664000175000017500000001401713577732634015470 0ustar jodaljodal00000000000000Metadata-Version: 2.1 Name: Mopidy-GMusic Version: 4.0.0 Summary: Mopidy extension for playing music from Google Play Music Home-page: https://github.com/mopidy/mopidy-gmusic Author: Ronald Hecht Author-email: ronald.hecht@gmx.de License: Apache License, Version 2.0 Description: ************* Mopidy-GMusic ************* .. image:: https://img.shields.io/pypi/v/Mopidy-GMusic :target: https://pypi.org/project/Mopidy-GMusic/ :alt: Latest PyPI version .. image:: https://img.shields.io/circleci/build/gh/mopidy/mopidy-gmusic :target: https://circleci.com/gh/mopidy/mopidy-gmusic :alt: CircleCI build status .. image:: https://img.shields.io/codecov/c/gh/mopidy/mopidy-gmusic :target: https://codecov.io/gh/mopidy/mopidy-gmusic :alt: Test coverage `Mopidy `_ extension for playing music from `Google Play Music `_. Co-maintainer wanted ==================== We are currently looking for a co-maintainer. Preferably someone who is familiar with the codebase, familiar with Python development, and uses the uploaded music feature. If you're interested, please take a look at the code base and work on submitting a pull request or two to show you understand how everything works together. If you need help getting a development environment set up, don't hesitate to ping "belak" in the ``#mopidy`` channel on the Freenode IRC network. Dependencies ============ You must have a Google account, and either: - have some music uploaded to your Google Play Music library, or - have a paid subscription for Google Play Music. Installation ============ Install by running:: sudo python3 -m pip install Mopidy-GMusic See https://mopidy.com/ext/gmusic/ for alternative installation methods Configuration ============= Run ``mopidy gmusic login`` to obtain a refresh token, and then include it in your config file:: [gmusic] refresh_token = Google Play Music now requires all clients to provide a device ID. In the past, Mopidy-GMusic generated one automatically from your MAC address, but Google seems to have changed their API in a way that prevents this from working. Therefore you will need to configure one manually. If no device ID is configured, Mopidy-GMusic will output a list of registered devices and their IDs. You can either use one of those IDs in your config file, or use the special value ``mac`` if you want gmusicapi to use the old method of generating an ID from your MAC address:: [gmusic] deviceid = 0123456789abcdef # or deviceid = mac By default, All Access will be enabled automatically if you subscribe. You may force enable or disable it by using the ``all_access`` option:: [gmusic] all_access = true By default, the bitrate is set to 160 kbps. You can change this to either 128 or 320 kbps by setting:: [gmusic] bitrate = 320 All Access radios are available as browsable content or playlist. The following are the default config values:: [gmusic] # Show radio stations in content browser radio_stations_in_browse = true # Show radio stations as playlists radio_stations_as_playlists = false # Limit the number of radio stations, unlimited if unset radio_stations_count = # Limit the number or tracks for each radio station radio_tracks_count = 25 The library and playlists are automatically refresh at regular intervals. Refreshing can be CPU intensive on very low-powered machines, e.g. Raspberry Pi Zero. The refresh intervals can be configured:: [gmusic] # How often to refresh the library, in minutes refresh_library = 1440 # How often to refresh playlists, in minutes refresh_playlists = 60 Usage ===== The extension is enabled by default if all dependencies are available. You can simply browse through your library and search for tracks, albums, and artists. Google Play Music playlists are imported as well. You can even add songs from your All Access subscription to your library. Mopidy will able to play them. Project resources ================= - `Source code `_ - `Issue tracker `_ - `Changelog `_ Credits ======= - Original author: `Ronald Hecht `_ - Current maintainer: `Kaleb Elwert `_ - `Contributors `_ Platform: UNKNOWN Classifier: Environment :: No Input/Output (Daemon) Classifier: Intended Audience :: End Users/Desktop Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Topic :: Multimedia :: Sound/Audio :: Players Requires-Python: >=3.7 Provides-Extra: lint Provides-Extra: release Provides-Extra: test Provides-Extra: dev Mopidy-GMusic-4.0.0/README.rst0000664000175000017500000001024413577732243016054 0ustar jodaljodal00000000000000************* Mopidy-GMusic ************* .. image:: https://img.shields.io/pypi/v/Mopidy-GMusic :target: https://pypi.org/project/Mopidy-GMusic/ :alt: Latest PyPI version .. image:: https://img.shields.io/circleci/build/gh/mopidy/mopidy-gmusic :target: https://circleci.com/gh/mopidy/mopidy-gmusic :alt: CircleCI build status .. image:: https://img.shields.io/codecov/c/gh/mopidy/mopidy-gmusic :target: https://codecov.io/gh/mopidy/mopidy-gmusic :alt: Test coverage `Mopidy `_ extension for playing music from `Google Play Music `_. Co-maintainer wanted ==================== We are currently looking for a co-maintainer. Preferably someone who is familiar with the codebase, familiar with Python development, and uses the uploaded music feature. If you're interested, please take a look at the code base and work on submitting a pull request or two to show you understand how everything works together. If you need help getting a development environment set up, don't hesitate to ping "belak" in the ``#mopidy`` channel on the Freenode IRC network. Dependencies ============ You must have a Google account, and either: - have some music uploaded to your Google Play Music library, or - have a paid subscription for Google Play Music. Installation ============ Install by running:: sudo python3 -m pip install Mopidy-GMusic See https://mopidy.com/ext/gmusic/ for alternative installation methods Configuration ============= Run ``mopidy gmusic login`` to obtain a refresh token, and then include it in your config file:: [gmusic] refresh_token = Google Play Music now requires all clients to provide a device ID. In the past, Mopidy-GMusic generated one automatically from your MAC address, but Google seems to have changed their API in a way that prevents this from working. Therefore you will need to configure one manually. If no device ID is configured, Mopidy-GMusic will output a list of registered devices and their IDs. You can either use one of those IDs in your config file, or use the special value ``mac`` if you want gmusicapi to use the old method of generating an ID from your MAC address:: [gmusic] deviceid = 0123456789abcdef # or deviceid = mac By default, All Access will be enabled automatically if you subscribe. You may force enable or disable it by using the ``all_access`` option:: [gmusic] all_access = true By default, the bitrate is set to 160 kbps. You can change this to either 128 or 320 kbps by setting:: [gmusic] bitrate = 320 All Access radios are available as browsable content or playlist. The following are the default config values:: [gmusic] # Show radio stations in content browser radio_stations_in_browse = true # Show radio stations as playlists radio_stations_as_playlists = false # Limit the number of radio stations, unlimited if unset radio_stations_count = # Limit the number or tracks for each radio station radio_tracks_count = 25 The library and playlists are automatically refresh at regular intervals. Refreshing can be CPU intensive on very low-powered machines, e.g. Raspberry Pi Zero. The refresh intervals can be configured:: [gmusic] # How often to refresh the library, in minutes refresh_library = 1440 # How often to refresh playlists, in minutes refresh_playlists = 60 Usage ===== The extension is enabled by default if all dependencies are available. You can simply browse through your library and search for tracks, albums, and artists. Google Play Music playlists are imported as well. You can even add songs from your All Access subscription to your library. Mopidy will able to play them. Project resources ================= - `Source code `_ - `Issue tracker `_ - `Changelog `_ Credits ======= - Original author: `Ronald Hecht `_ - Current maintainer: `Kaleb Elwert `_ - `Contributors `_ Mopidy-GMusic-4.0.0/mopidy_gmusic/0000775000175000017500000000000013577732634017240 5ustar jodaljodal00000000000000Mopidy-GMusic-4.0.0/mopidy_gmusic/__init__.py0000664000175000017500000000331713577731553021354 0ustar jodaljodal00000000000000import pathlib import pkg_resources from mopidy import config, ext __version__ = pkg_resources.get_distribution("Mopidy-GMusic").version class Extension(ext.Extension): dist_name = "Mopidy-GMusic" ext_name = "gmusic" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["username"] = config.Deprecated() schema["password"] = config.Deprecated() schema["refresh_token"] = config.Secret(optional=True) schema["bitrate"] = config.Integer(choices=(128, 160, 320)) schema["deviceid"] = config.String(optional=True) schema["all_access"] = config.Boolean(optional=True) schema["refresh_library"] = config.Integer(minimum=-1, optional=True) schema["refresh_playlists"] = config.Integer(minimum=-1, optional=True) schema["radio_stations_in_browse"] = config.Boolean(optional=True) schema["radio_stations_as_playlists"] = config.Boolean(optional=True) schema["radio_stations_count"] = config.Integer( minimum=1, optional=True ) schema["radio_tracks_count"] = config.Integer(minimum=1, optional=True) schema["top_tracks_count"] = config.Integer(minimum=1, optional=True) return schema def setup(self, registry): from .backend import GMusicBackend from .scrobbler_frontend import GMusicScrobblerFrontend registry.add("backend", GMusicBackend) registry.add("frontend", GMusicScrobblerFrontend) def get_command(self): from .commands import GMusicCommand return GMusicCommand() Mopidy-GMusic-4.0.0/mopidy_gmusic/backend.py0000664000175000017500000000621413577731553021203 0ustar jodaljodal00000000000000import logging import time from threading import Lock import pykka from mopidy import backend from .library import GMusicLibraryProvider from .playback import GMusicPlaybackProvider from .playlists import GMusicPlaylistsProvider from .repeating_timer import RepeatingTimer from .scrobbler_frontend import GMusicScrobblerListener from .session import GMusicSession logger = logging.getLogger(__name__) class GMusicBackend( pykka.ThreadingActor, backend.Backend, GMusicScrobblerListener ): def __init__(self, config, audio): super().__init__() self.config = config self._refresh_library_rate = config["gmusic"]["refresh_library"] * 60.0 self._refresh_playlists_rate = ( config["gmusic"]["refresh_playlists"] * 60.0 ) self._refresh_library_timer = None self._refresh_playlists_timer = None self._refresh_lock = Lock() self._playlist_lock = Lock() self._refresh_last = 0 # do not run playlist refresh around library refresh self._refresh_threshold = self._refresh_playlists_rate * 0.3 self.library = GMusicLibraryProvider(backend=self) self.playback = GMusicPlaybackProvider(audio=audio, backend=self) self.playlists = GMusicPlaylistsProvider(backend=self) self.session = GMusicSession(all_access=config["gmusic"]["all_access"]) self.uri_schemes = ["gmusic"] def on_start(self): self.session.login( self.config["gmusic"]["refresh_token"], self.config["gmusic"]["deviceid"], ) # wait a few seconds to let mopidy settle # then refresh google music content asynchronously self._refresh_library_timer = RepeatingTimer( self._refresh_library, self._refresh_library_rate ) self._refresh_library_timer.start() # schedule playlist refresh as desired if self._refresh_playlists_rate > 0: self._refresh_playlists_timer = RepeatingTimer( self._refresh_playlists, self._refresh_playlists_rate ) self._refresh_playlists_timer.start() def on_stop(self): if self._refresh_library_timer: self._refresh_library_timer.cancel() self._refresh_library_timer = None if self._refresh_playlists_timer: self._refresh_playlists_timer.cancel() self._refresh_playlists_timer = None self.session.logout() def increment_song_playcount(self, track_id): # Called through GMusicScrobblerListener self.session.increment_song_playcount(track_id) def _refresh_library(self): with self._refresh_lock: t0 = round(time.time()) logger.debug("Refreshing library") self.library.refresh() t = round(time.time()) - t0 logger.debug(f"Refreshed library in {t:.1f}s") def _refresh_playlists(self): with self._playlist_lock: t0 = round(time.time()) logger.debug("Refreshing playlists") self.playlists.refresh() t = round(time.time()) - t0 logger.debug(f"Refreshed playlists in {t:.1f}s") Mopidy-GMusic-4.0.0/mopidy_gmusic/commands.py0000664000175000017500000000170413577731553021414 0ustar jodaljodal00000000000000import gmusicapi from mopidy import commands from oauth2client.client import OAuth2WebServerFlow class GMusicCommand(commands.Command): def __init__(self): super().__init__() self.add_child("login", LoginCommand()) class LoginCommand(commands.Command): def run(self, args, config): oauth_info = gmusicapi.Mobileclient._session_class.oauth flow = OAuth2WebServerFlow(**oauth_info._asdict()) print() print( "Go to the following URL to get an initial auth code, " "then provide it below:" ) print(flow.step1_get_authorize_url()) print() initial_code = input("code: ") credentials = flow.step2_exchange(initial_code) refresh_token = credentials.refresh_token print("\nPlease update your config to include the following:") print() print("[gmusic]") print("refresh_token =", refresh_token) print() Mopidy-GMusic-4.0.0/mopidy_gmusic/ext.conf0000664000175000017500000000040513577731553020705 0ustar jodaljodal00000000000000[gmusic] enabled = true refresh_token = bitrate = 160 deviceid = all_access = refresh_library = 1440 refresh_playlists = 60 radio_stations_in_browse = true radio_stations_as_playlists = false radio_stations_count = radio_tracks_count = 25 top_tracks_count = 20 Mopidy-GMusic-4.0.0/mopidy_gmusic/library.py0000664000175000017500000005573613577731553021275 0ustar jodaljodal00000000000000import logging from functools import reduce from cachetools import LRUCache from mopidy import backend from mopidy.models import Album, Artist, Ref, SearchResult, Track from mopidy_gmusic.translator import ( album_to_ref, artist_to_ref, create_id, track_to_ref, ) logger = logging.getLogger(__name__) class GMusicLibraryProvider(backend.LibraryProvider): root_directory = Ref.directory( uri="gmusic:directory", name="Google Play Music" ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # tracks, albums, and artists here refer to what is explicitly # in our library. self.tracks = {} self.albums = {} self.artists = {} # aa_* caches are *only* used for temporary objects. Library # objects will never make it here. self.aa_artists = LRUCache(1024) self.aa_tracks = LRUCache(1024) self.aa_albums = LRUCache(1024) self._radio_stations_in_browse = self.backend.config["gmusic"][ "radio_stations_in_browse" ] self._radio_stations_count = self.backend.config["gmusic"][ "radio_stations_count" ] self._radio_tracks_count = self.backend.config["gmusic"][ "radio_tracks_count" ] self._top_tracks_count = self.backend.config["gmusic"][ "top_tracks_count" ] # Setup the root of library browsing. self._root = [ Ref.directory(uri="gmusic:album", name="Albums"), Ref.directory(uri="gmusic:artist", name="Artists"), Ref.directory(uri="gmusic:track", name="Tracks"), ] if self._radio_stations_in_browse: self._root.append(Ref.directory(uri="gmusic:radio", name="Radios")) @property def all_access(self): return self.backend.session.all_access def _browse_tracks(self): tracks = list(self.tracks.values()) tracks.sort(key=lambda ref: ref.name) refs = [] for track in tracks: refs.append(track_to_ref(track)) return refs def _browse_albums(self): refs = [] for album in self.albums.values(): refs.append(album_to_ref(album)) refs.sort(key=lambda ref: ref.name) return refs def _browse_album(self, uri): refs = [] for track in self._lookup_album(uri): refs.append(track_to_ref(track, True)) return refs def _browse_artists(self): refs = [] for artist in self.artists.values(): refs.append(artist_to_ref(artist)) refs.sort(key=lambda ref: ref.name) return refs def _browse_artist(self, uri): refs = [] for album in self._get_artist_albums(uri): refs.append(album_to_ref(album)) refs.sort(key=lambda ref: ref.name) if len(refs) > 0: refs.insert(0, Ref.directory(uri=uri + ":all", name="All Tracks")) is_all_access = uri.startswith("gmusic:artist:A") if is_all_access: refs.insert( 1, Ref.directory(uri=uri + ":top", name="Top Tracks") ) return refs else: # Show all tracks if no album is available return self._browse_artist_all_tracks(uri) def _browse_artist_all_tracks(self, uri): artist_uri = ":".join(uri.split(":")[:3]) refs = [] tracks = self._lookup_artist(artist_uri, True) for track in tracks: refs.append(track_to_ref(track)) return refs def _browse_artist_top_tracks(self, uri): artist_uri = ":".join(uri.split(":")[:3]) refs = [] tracks = self._get_artist_top_tracks(artist_uri) for track in tracks: refs.append(track_to_ref(track)) return refs def _browse_radio_stations(self, uri): stations = self.backend.session.get_radio_stations( self._radio_stations_count ) # create Ref objects refs = [] for station in stations: refs.append( Ref.directory( uri="gmusic:radio:" + station["id"], name=station["name"] ) ) return refs def _browse_radio_station(self, uri): station_id = uri.split(":")[2] tracks = self.backend.session.get_station_tracks( station_id, self._radio_tracks_count ) # create Ref objects refs = [] for track in tracks: mopidy_track = self._to_mopidy_track(track) self.aa_tracks[mopidy_track.uri] = mopidy_track refs.append(track_to_ref(mopidy_track)) return refs def browse(self, uri): logger.debug("browse: %s", str(uri)) if not uri: return [] if uri == self.root_directory.uri: return self._root parts = uri.split(":") # tracks if uri == "gmusic:track": return self._browse_tracks() # albums if uri == "gmusic:album": return self._browse_albums() # a single album # uri == 'gmusic:album:album_id' if len(parts) == 3 and parts[1] == "album": return self._browse_album(uri) # artists if uri == "gmusic:artist": return self._browse_artists() # a single artist # uri == 'gmusic:artist:artist_id' if len(parts) == 3 and parts[1] == "artist": return self._browse_artist(uri) # all tracks of a single artist # uri == 'gmusic:artist:artist_id:all' if len(parts) == 4 and parts[1] == "artist" and parts[3] == "all": return self._browse_artist_all_tracks(uri) # top tracks of a single artist # uri == 'gmusic:artist:artist_id:top' if len(parts) == 4 and parts[1] == "artist" and parts[3] == "top": return self._browse_artist_top_tracks(uri) # all radio stations if uri == "gmusic:radio": return self._browse_radio_stations(uri) # a single radio station # uri == 'gmusic:radio:station_id' if len(parts) == 3 and parts[1] == "radio": return self._browse_radio_station(uri) logger.debug("Unknown uri for browse request: %s", uri) return [] def lookup(self, uri): if uri.startswith("gmusic:track:"): return self._lookup_track(uri) elif uri.startswith("gmusic:album:"): return self._lookup_album(uri) elif uri.startswith("gmusic:artist:"): return self._lookup_artist(uri) else: return [] def _lookup_track(self, uri): is_all_access = uri.startswith("gmusic:track:T") try: return [self.tracks[uri]] except KeyError: logger.debug(f"Track {uri!r} is not a library track") pass if is_all_access and self.all_access: track = self.aa_tracks.get(uri) if track: return [track] track = self.backend.session.get_track_info(uri.split(":")[2]) if track is None: logger.warning(f"Could not find track {uri!r}") return [] if "artistId" not in track: logger.warning(f"Failed to lookup {uri!r}") return [] mopidy_track = self._to_mopidy_track(track) self.aa_tracks[mopidy_track.uri] = mopidy_track return [mopidy_track] else: return [] def _lookup_album(self, uri): is_all_access = uri.startswith("gmusic:album:B") if self.all_access and is_all_access: tracks = self.aa_albums.get(uri) if tracks: return tracks album = self.backend.session.get_album_info( uri.split(":")[2], include_tracks=True ) if album and album.get("tracks"): tracks = [ self._to_mopidy_track(track) for track in album["tracks"] ] for track in tracks: self.aa_tracks[track.uri] = track tracks = sorted(tracks, key=lambda t: (t.disc_no, t.track_no)) self.aa_albums[uri] = tracks return tracks logger.warning(f"Failed to lookup all access album {uri!r}") # Even if the album has an all access ID, we need to look it # up here (as a fallback) because purchased tracks can have a # store ID, but only show up in your library. try: album = self.albums[uri] except KeyError: logger.debug(f"Failed to lookup {uri!r}") return [] tracks = self._find_exact( dict( album=album.name, artist=[artist.name for artist in album.artists], date=album.date, ) ).tracks return sorted(tracks, key=lambda t: (t.disc_no, t.track_no)) def _get_artist_top_tracks(self, uri): is_all_access = uri.startswith("gmusic:artist:A") artist_id = uri.split(":")[2] if not is_all_access: logger.debug("Top Tracks not available for non-all-access artists") return [] artist_info = self.backend.session.get_artist_info( artist_id, include_albums=False, max_top_tracks=self._top_tracks_count, max_rel_artist=0, ) top_tracks = [] for track_dict in artist_info["topTracks"]: top_tracks.append(self._to_mopidy_track(track_dict)) return top_tracks def _get_artist_albums(self, uri): is_all_access = uri.startswith("gmusic:artist:A") artist_id = uri.split(":")[2] if is_all_access: # all access artist_infos = self.backend.session.get_artist_info( artist_id, max_top_tracks=0, max_rel_artist=0 ) if artist_infos is None or "albums" not in artist_infos: return [] albums = [] for album in artist_infos["albums"]: albums.append( self._aa_search_album_to_mopidy_album({"album": album}) ) return albums elif self.all_access and artist_id in self.aa_artists: albums = self._get_artist_albums( "gmusic:artist:%s" % self.aa_artists[artist_id] ) if len(albums) > 0: return albums # else fall back to non aa albums if uri in self.artists: artist = self.artists[uri] return [ album for album in self.albums.values() if artist in album.artists ] else: logger.debug(f"No albums available for artist {uri!r}") return [] def _lookup_artist(self, uri, exact_match=False): def sorter(track): return ( track.album.date, track.album.name, track.disc_no, track.track_no, ) if self.all_access: try: all_access_id = self.aa_artists[uri.split(":")[2]] artist_infos = self.backend.session.get_artist_info( all_access_id, max_top_tracks=0, max_rel_artist=0 ) if not artist_infos or not artist_infos["albums"]: logger.warning(f"Failed to lookup {artist_infos}!r") tracks = [ self._lookup_album("gmusic:album:" + album["albumId"]) for album in artist_infos["albums"] ] tracks = reduce(lambda a, b: (a + b), tracks) return sorted(tracks, key=sorter) except KeyError: pass try: artist = self.artists[uri] except KeyError: logger.debug(f"Failed to lookup {uri!r}") return [] tracks = self._find_exact(dict(artist=artist.name)).tracks if exact_match: tracks = filter(lambda t: artist in t.artists, tracks) return sorted(tracks, key=sorter) def refresh(self, uri=None): self.tracks = {} self.albums = {} self.artists = {} album_tracks = {} for track in self.backend.session.get_all_songs(): mopidy_track = self._to_mopidy_track(track) self.tracks[mopidy_track.uri] = mopidy_track self.albums[mopidy_track.album.uri] = mopidy_track.album # We don't care about the order because we're just using # this as a temporary variable to grab the proper album # artist out of the album. if mopidy_track.album.uri not in album_tracks: album_tracks[mopidy_track.album.uri] = [] album_tracks[mopidy_track.album.uri].append(mopidy_track) # Yes, this is awful. No, I don't have a better solution. Yes, # I'm annoyed at Google for not providing album artist IDs. for album in self.albums.values(): artist_found = False for album_artist in album.artists: for track in album_tracks[album.uri]: for artist in track.artists: if album_artist.name == artist.name: artist_found = True self.artists[artist.uri] = artist if not artist_found: for artist in album.artists: self.artists[artist.uri] = artist def search(self, query=None, uris=None, exact=False): if exact: return self._find_exact(query=query, uris=uris) lib_tracks, lib_artists, lib_albums = self._search_library(query, uris) if query: aa_tracks, aa_artists, aa_albums = self._search(query, uris) for aa_artist in aa_artists: lib_artists.add(aa_artist) for aa_album in aa_albums: lib_albums.add(aa_album) lib_tracks = set(lib_tracks) for aa_track in aa_tracks: lib_tracks.add(aa_track) return SearchResult( uri="gmusic:search", tracks=lib_tracks, artists=lib_artists, albums=lib_albums, ) def _find_exact(self, query=None, uris=None): # Find exact can only be done on gmusic library, # since one can't filter all access searches lib_tracks, lib_artists, lib_albums = self._search_library(query, uris) return SearchResult( uri="gmusic:search", tracks=lib_tracks, artists=lib_artists, albums=lib_albums, ) def _search(self, query=None, uris=None): for (field, values) in query.items(): if not hasattr(values, "__iter__"): values = [values] # Since gmusic does not support search filters, just search for the # first 'searchable' filter if field in ["track_name", "album", "artist", "albumartist", "any"]: logger.info(f"Searching Google Play Music for: {values[0]}") res = self.backend.session.search(values[0], max_results=50) if res is None: return [], [], [] albums = [ self._aa_search_album_to_mopidy_album(album_res) for album_res in res["album_hits"] ] artists = [ self._aa_search_artist_to_mopidy_artist(artist_res) for artist_res in res["artist_hits"] ] tracks = [ self._aa_search_track_to_mopidy_track(track_res) for track_res in res["song_hits"] ] return tracks, artists, albums return [], [], [] def _search_library(self, query=None, uris=None): if query is None: query = {} self._validate_query(query) result_tracks = self.tracks.values() for (field, values) in query.items(): if not hasattr(values, "__iter__"): values = [values] # FIXME this is bound to be slow for large libraries for value in values: if field == "track_no": q = self._convert_to_int(value) else: q = value.strip().lower() def uri_filter(track): return q in track.uri.lower() def track_name_filter(track): return q in track.name.lower() def album_filter(track): return q in getattr(track, "album", Album()).name.lower() def artist_filter(track): return any( q in a.name.lower() for a in track.artists ) or albumartist_filter(track) def albumartist_filter(track): album_artists = getattr(track, "album", Album()).artists return any(q in a.name.lower() for a in album_artists) def track_no_filter(track): return track.track_no == q def date_filter(track): return track.date and track.date.startswith(q) def any_filter(track): return any( [ uri_filter(track), track_name_filter(track), album_filter(track), artist_filter(track), albumartist_filter(track), date_filter(track), ] ) if field == "uri": result_tracks = filter(uri_filter, result_tracks) elif field == "track_name": result_tracks = filter(track_name_filter, result_tracks) elif field == "album": result_tracks = filter(album_filter, result_tracks) elif field == "artist": result_tracks = filter(artist_filter, result_tracks) elif field == "albumartist": result_tracks = filter(albumartist_filter, result_tracks) elif field == "track_no": result_tracks = filter(track_no_filter, result_tracks) elif field == "date": result_tracks = filter(date_filter, result_tracks) elif field == "any": result_tracks = filter(any_filter, result_tracks) else: raise LookupError("Invalid lookup field: %s" % field) result_artists = set() result_albums = set() for track in result_tracks: result_artists |= track.artists result_albums.add(track.album) return result_tracks, result_artists, result_albums def _validate_query(self, query): for (_, values) in query.items(): if not values: raise LookupError("Missing query") for value in values: if not value: raise LookupError("Missing query") def _to_mopidy_track(self, song): track_id = song.get("id", song.get("nid")) if track_id is None: raise ValueError if track_id[0] != "T" and "-" not in track_id: track_id = "T" + track_id return Track( uri="gmusic:track:" + track_id, name=song["title"], artists=[self._to_mopidy_artist(song)], album=self._to_mopidy_album(song), track_no=song.get("trackNumber", 1), disc_no=song.get("discNumber", 1), date=str(song.get("year", 0)), length=int(song["durationMillis"]), bitrate=self.backend.config["gmusic"]["bitrate"], ) def _to_mopidy_album(self, song): name = song.get("album", "") artist = self._to_mopidy_album_artist(song) date = str(song.get("year", 0)) album_id = song.get("albumId") if album_id is None: album_id = create_id(artist.name + name + date) uri = "gmusic:album:" + album_id return Album( uri=uri, name=name, artists=[artist], num_tracks=song.get("totalTrackCount"), num_discs=song.get("totalDiscCount"), date=date, ) def _to_mopidy_artist(self, song): name = song.get("artist", "") artist_id = song.get("artistId") if artist_id is not None: artist_id = artist_id[0] else: artist_id = create_id(name) uri = "gmusic:artist:" + artist_id return Artist(uri=uri, name=name) def _to_mopidy_album_artist(self, song): name = song.get("albumArtist", "") if name.strip() == "": name = song.get("artist", "") uri = "gmusic:artist:" + create_id(name) return Artist(uri=uri, name=name) def _aa_search_track_to_mopidy_track(self, search_track): track = search_track["track"] aa_artist_id = create_id(track["artist"]) if "artistId" in track: aa_artist_id = track["artistId"][0] else: logger.warning("No artistId for Track %r", track) artist = Artist( uri="gmusic:artist:" + aa_artist_id, name=track["artist"] ) album = Album( uri="gmusic:album:" + track["albumId"], name=track["album"], artists=[artist], date=str(track.get("year", 0)), ) return Track( uri="gmusic:track:" + track["storeId"], name=track["title"], artists=[artist], album=album, track_no=track.get("trackNumber", 1), disc_no=track.get("discNumber", 1), date=str(track.get("year", 0)), length=int(track["durationMillis"]), bitrate=self.backend.config["gmusic"]["bitrate"], ) def _aa_search_artist_to_mopidy_artist(self, search_artist): artist = search_artist["artist"] uri = "gmusic:artist:" + artist["artistId"] return Artist(uri=uri, name=artist["name"]) def _aa_search_album_to_mopidy_album(self, search_album): album = search_album["album"] uri = "gmusic:album:" + album["albumId"] name = album["name"] artist = self._aa_search_artist_album_to_mopidy_artist_album(album) date = str(album.get("year", 0)) return Album(uri=uri, name=name, artists=[artist], date=date) def _aa_search_artist_album_to_mopidy_artist_album(self, album): name = album.get("albumArtist", "") if name.strip() == "": name = album.get("artist", "") uri = "gmusic:artist:" + create_id(name) return Artist(uri=uri, name=name) def _convert_to_int(self, string): try: return int(string) except ValueError: return object() Mopidy-GMusic-4.0.0/mopidy_gmusic/playback.py0000664000175000017500000000103513577731553021376 0ustar jodaljodal00000000000000import logging from mopidy import backend logger = logging.getLogger(__name__) BITRATES = { 128: "low", 160: "med", 320: "hi", } class GMusicPlaybackProvider(backend.PlaybackProvider): def translate_uri(self, uri): track_id = uri.rsplit(":")[-1] quality = BITRATES[self.backend.config["gmusic"]["bitrate"]] stream_uri = self.backend.session.get_stream_url( track_id, quality=quality ) logger.debug("Translated: %s -> %s", uri, stream_uri) return stream_uri Mopidy-GMusic-4.0.0/mopidy_gmusic/playlists.py0000664000175000017500000001151713577731553021642 0ustar jodaljodal00000000000000import logging import operator from mopidy import backend from mopidy.models import Playlist, Ref logger = logging.getLogger(__name__) class GMusicPlaylistsProvider(backend.PlaylistsProvider): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._radio_stations_as_playlists = self.backend.config["gmusic"][ "radio_stations_as_playlists" ] self._radio_stations_count = self.backend.config["gmusic"][ "radio_stations_count" ] self._radio_tracks_count = self.backend.config["gmusic"][ "radio_tracks_count" ] self._playlists = {} def as_list(self): refs = [ Ref.playlist(uri=pl.uri, name=pl.name) for pl in self._playlists.values() ] return sorted(refs, key=operator.attrgetter("name")) def get_items(self, uri): playlist = self._playlists.get(uri) if playlist is None: return None return [Ref.track(uri=t.uri, name=t.name) for t in playlist.tracks] def lookup(self, uri): return self._playlists.get(uri) def refresh(self): playlists = {} # We need to grab all the songs for later. All access metadata # will be included with the playlist entry, but uploaded music # will not. library_tracks = {} for track in self.backend.session.get_all_songs(): mopidy_track = self.backend.library._to_mopidy_track(track) library_tracks[track["id"]] = mopidy_track # add thumbs up playlist tracks = [] for track in self.backend.session.get_top_songs(): tracks.append(self.backend.library._to_mopidy_track(track)) if len(tracks) > 0: uri = "gmusic:playlist:top" playlists[uri] = Playlist(uri=uri, name="Top", tracks=tracks) # load user playlists for playlist in self.backend.session.get_all_user_playlist_contents(): tracks = [] for entry in playlist["tracks"]: if entry["deleted"]: continue if entry["source"] == "1": tracks.append(library_tracks[entry["trackId"]]) else: entry["track"]["id"] = entry["trackId"] tracks.append( self.backend.library._to_mopidy_track(entry["track"]) ) uri = "gmusic:playlist:" + playlist["id"] playlists[uri] = Playlist( uri=uri, name=playlist["name"], tracks=tracks ) # load shared playlists for playlist in self.backend.session.get_all_playlists(): if playlist.get("type") == "SHARED": tracks = [] tracklist = self.backend.session.get_shared_playlist_contents( playlist["shareToken"] ) for entry in tracklist: if entry["source"] == "1": tracks.append(library_tracks[entry["trackId"]]) else: entry["track"]["id"] = entry["trackId"] tracks.append( self.backend.library._to_mopidy_track( entry["track"] ) ) uri = "gmusic:playlist:" + playlist["id"] playlists[uri] = Playlist( uri=uri, name=playlist["name"], tracks=tracks ) num_playlists = len(playlists) logger.info("Loaded %d playlists from Google Play Music", num_playlists) # load radios as playlists if self._radio_stations_as_playlists: logger.debug("Loading radio stations") stations = self.backend.session.get_radio_stations( self._radio_stations_count ) for station in stations: tracks = [] tracklist = self.backend.session.get_station_tracks( station["id"], self._radio_tracks_count ) for track in tracklist: tracks.append(self.backend.library._to_mopidy_track(track)) uri = "gmusic:playlist:" + station["id"] playlists[uri] = Playlist( uri=uri, name=station["name"], tracks=tracks ) num_radios = len(playlists) - num_playlists logger.info( f"Loaded {num_radios} radio stations from Google Play Music" ) self._playlists = playlists backend.BackendListener.send("playlists_loaded") def create(self, name): raise NotImplementedError def delete(self, uri): raise NotImplementedError def save(self, playlist): raise NotImplementedError Mopidy-GMusic-4.0.0/mopidy_gmusic/repeating_timer.py0000664000175000017500000000101313577731553022762 0ustar jodaljodal00000000000000from threading import Event, Thread class RepeatingTimer(Thread): def __init__(self, method, interval=0): Thread.__init__(self) self._stop_event = Event() self._interval = interval self._method = method def run(self): self._method() while self._interval > 0 and not self._stop_event.wait(self._interval): # wait for interval # call method over and over again self._method() def cancel(self): self._stop_event.set() Mopidy-GMusic-4.0.0/mopidy_gmusic/scrobbler_frontend.py0000664000175000017500000000175613577731553023476 0ustar jodaljodal00000000000000import logging import pykka from mopidy import core, listener logger = logging.getLogger(__name__) class GMusicScrobblerFrontend(pykka.ThreadingActor, core.CoreListener): def __init__(self, config, core): super().__init__() def track_playback_ended(self, tl_track, time_position): track = tl_track.track duration = track.length and track.length // 1000 or 0 time_position = time_position // 1000 if time_position < duration // 2 and time_position < 240: logger.debug( "Track not played long enough too scrobble. (50% or 240s)" ) return track_id = track.uri.rsplit(":")[-1] logger.debug("Increasing play count: %s", track_id) listener.send( GMusicScrobblerListener, "increment_song_playcount", track_id=track_id, ) class GMusicScrobblerListener(listener.Listener): def increment_song_playcount(self, track_id): pass Mopidy-GMusic-4.0.0/mopidy_gmusic/session.py0000664000175000017500000001250713577731553021301 0ustar jodaljodal00000000000000import functools import logging import requests import gmusicapi from gmusicapi.exceptions import CallFailure, NotLoggedIn from gmusicapi.session import credentials_from_refresh_token logger = logging.getLogger(__name__) def endpoint(default=None, require_all_access=False): default = default() if callable(default) else default def outer_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): if require_all_access and not self.all_access: logger.warning( "Google Play Music All Access is required for %s()", func.__name__, ) return default if not self.api.is_authenticated(): return default try: return func(self, *args, **kwargs) except gmusicapi.CallFailure: logger.exception("Call to Google Play Music failed") return default except requests.exceptions.RequestException: logger.exception("HTTP request to Google Play Music failed") return default return inner_wrapper return outer_wrapper class GMusicSession: def __init__(self, all_access, api=None): self._all_access = all_access if api is None: self.api = gmusicapi.Mobileclient() self.api._authtype = "oauth" else: self.api = api def login(self, refresh_token, device_id): if self.api.is_authenticated(): self.api.logout() if device_id is None or device_id == "mac": device_id = gmusicapi.Mobileclient.FROM_MAC_ADDRESS oauth_info = gmusicapi.Mobileclient._session_class.oauth if not refresh_token: logger.error( "No refresh_token in gmusic config. Please run " + "`mopidy gmusic login`." ) return False authenticated = self.api.oauth_login( device_id, oauth_credentials=credentials_from_refresh_token( refresh_token, oauth_info ), ) if authenticated: logger.info("Logged in to Google Play Music") else: logger.error("Failed to login to Google Play Music") return authenticated @property def all_access(self): if self._all_access is None: try: return self.api.is_subscribed except NotLoggedIn: return False return self._all_access @endpoint(default=None) def logout(self): return self.api.logout() @endpoint(default=list) def get_all_songs(self): return self.api.get_all_songs() @endpoint(default=None) def get_stream_url(self, song_id, quality="hi"): try: return self.api.get_stream_url(song_id, quality=quality) except CallFailure: logger.warn("Failed to get stream url for %s.", song_id) logger.warn("Please ensure your deviceid is set correctly.") raise @endpoint(default=list) def get_all_playlists(self): return self.api.get_all_playlists() @endpoint(default=list) def get_all_user_playlist_contents(self): return self.api.get_all_user_playlist_contents() @endpoint(default=list) def get_shared_playlist_contents(self, share_token): return self.api.get_shared_playlist_contents(share_token) @endpoint(default=list) def get_top_songs(self): return self.api.get_top_songs() @endpoint(default=None, require_all_access=True) def get_track_info(self, store_track_id): return self.api.get_track_info(store_track_id) @endpoint(default=None, require_all_access=True) def get_album_info(self, album_id, include_tracks=True): return self.api.get_album_info(album_id, include_tracks=include_tracks) @endpoint(default=None, require_all_access=True) def get_artist_info( self, artist_id, include_albums=True, max_top_tracks=5, max_rel_artist=5 ): return self.api.get_artist_info( artist_id, include_albums=include_albums, max_top_tracks=max_top_tracks, max_rel_artist=max_rel_artist, ) @endpoint(default=None, require_all_access=False) def search(self, query, max_results=50): return self.api.search(query, max_results=max_results) @endpoint(default=list) def get_all_stations(self): return self.api.get_all_stations() def get_radio_stations(self, num_stations=None): stations = self.get_all_stations() # Last played radio first stations.reverse() # Add IFL radio on top stations.insert(0, {"id": "IFL", "name": "I'm Feeling Lucky"}) if num_stations is not None and num_stations > 0: # Limit radio stations stations = stations[:num_stations] return stations @endpoint(default=list, require_all_access=True) def get_station_tracks(self, station_id, num_tracks=25): return self.api.get_station_tracks(station_id, num_tracks=num_tracks) @endpoint(default=None) def increment_song_playcount(self, song_id, plays=1, playtime=None): return self.api.increment_song_playcount( song_id, plays=plays, playtime=playtime ) Mopidy-GMusic-4.0.0/mopidy_gmusic/translator.py0000664000175000017500000000253213577731553022004 0ustar jodaljodal00000000000000import hashlib from mopidy.models import Ref def album_to_ref(album): """Convert a mopidy album to a mopidy ref.""" name = "" for artist in album.artists: if len(name) > 0: name += ", " name += artist.name if (len(name)) > 0: name += " - " if album.name: name += album.name else: name += "Unknown Album" return Ref.directory(uri=album.uri, name=name) def artist_to_ref(artist): """Convert a mopidy artist to a mopidy ref.""" if artist.name: name = artist.name else: name = "Unknown artist" return Ref.directory(uri=artist.uri, name=name) def track_to_ref(track, with_track_no=False): """Convert a mopidy track to a mopidy ref.""" if with_track_no and track.track_no > 0: name = "%d - " % track.track_no else: name = "" for artist in track.artists: if len(name) > 0: name += ", " name += artist.name if (len(name)) > 0: name += " - " name += track.name return Ref.track(uri=track.uri, name=name) def get_images(song): if "albumArtRef" in song: return [ art_ref["url"] for art_ref in song["albumArtRef"] if "url" in art_ref ] return [] def create_id(u): return hashlib.md5(u.encode("utf-8")).hexdigest() Mopidy-GMusic-4.0.0/pyproject.toml0000664000175000017500000000052613577731553017306 0ustar jodaljodal00000000000000[build-system] requires = ["setuptools >= 30.3.0", "wheel"] [tool.black] target-version = ["py37", "py38"] line-length = 80 [tool.isort] multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 use_parentheses = true line_length = 88 known_tests = "tests" sections = "FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,TESTS,LOCALFOLDER" Mopidy-GMusic-4.0.0/setup.cfg0000664000175000017500000000262513577732634016216 0ustar jodaljodal00000000000000[metadata] name = Mopidy-GMusic version = 4.0.0 url = https://github.com/mopidy/mopidy-gmusic author = Ronald Hecht author_email = ronald.hecht@gmx.de license = Apache License, Version 2.0 license_file = LICENSE description = Mopidy extension for playing music from Google Play Music long_description = file: README.rst classifiers = Environment :: No Input/Output (Daemon) Intended Audience :: End Users/Desktop License :: OSI Approved :: Apache Software License Operating System :: OS Independent Programming Language :: Python :: 3 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Topic :: Multimedia :: Sound/Audio :: Players [options] zip_safe = False include_package_data = True packages = find: python_requires = >= 3.7 install_requires = Mopidy >= 3.0.0 Pykka >= 2.0.1 setuptools gmusicapi >= 12.1 requests >= 2.0 cachetools >= 1.0 [options.extras_require] lint = black check-manifest flake8 flake8-bugbear flake8-import-order isort[pyproject] release = twine wheel test = pytest pytest-cov dev = %(lint)s %(release)s %(test)s [options.packages.find] exclude = tests tests.* [options.entry_points] mopidy.ext = gmusic = mopidy_gmusic:Extension [flake8] application-import-names = mopidy_gmusic, tests max-line-length = 80 exclude = .git, .tox, build select = C, E, F, W B B950 N ignore = E203 E501 W503 [egg_info] tag_build = tag_date = 0 Mopidy-GMusic-4.0.0/setup.py0000664000175000017500000000004613577731553016101 0ustar jodaljodal00000000000000from setuptools import setup setup() Mopidy-GMusic-4.0.0/tests/0000775000175000017500000000000013577732634015532 5ustar jodaljodal00000000000000Mopidy-GMusic-4.0.0/tests/__init__.py0000664000175000017500000000000013577731553017630 0ustar jodaljodal00000000000000Mopidy-GMusic-4.0.0/tests/test_extension.py0000664000175000017500000000450413577731553021161 0ustar jodaljodal00000000000000import unittest from unittest import mock from mopidy_gmusic import Extension from mopidy_gmusic import backend as backend_lib from mopidy_gmusic import scrobbler_frontend class ExtensionTest(unittest.TestCase): @staticmethod def get_config(): config = {} config["username"] = "testuser@gmail.com" config["password"] = "secret_password" config["refresh_token"] = "0987654321" config["deviceid"] = "1234567890" config["all_access"] = False config["refresh_library"] = 1440 config["refresh_playlists"] = 60 config["radio_stations_in_browse"] = True config["radio_stations_as_playlists"] = False config["radio_stations_count"] = 0 config["radio_tracks_count"] = 25 config["top_tracks_count"] = 20 return {"gmusic": config} def test_get_default_config(self): ext = Extension() config = ext.get_default_config() assert "[gmusic]" in config assert "enabled = true" in config assert "all_access =" in config assert "radio_stations_in_browse = true" in config assert "radio_stations_count =" in config assert "radio_tracks_count = 25" in config def test_get_config_schema(self): ext = Extension() schema = ext.get_config_schema() assert "username" in schema assert "password" in schema assert "deviceid" in schema assert "refresh_library" in schema assert "refresh_playlists" in schema assert "all_access" in schema assert "radio_stations_in_browse" in schema assert "radio_stations_as_playlists" in schema assert "radio_stations_count" in schema assert "radio_tracks_count" in schema def test_get_backend_classes(self): registry = mock.Mock() ext = Extension() ext.setup(registry) assert ( mock.call("backend", backend_lib.GMusicBackend) in registry.add.mock_calls ) assert ( mock.call("frontend", scrobbler_frontend.GMusicScrobblerFrontend) in registry.add.mock_calls ) def test_init_backend(self): backend = backend_lib.GMusicBackend(ExtensionTest.get_config(), None) assert backend is not None backend.on_start() backend.on_stop() Mopidy-GMusic-4.0.0/tests/test_library.py0000664000175000017500000000747113577731553020617 0ustar jodaljodal00000000000000import unittest from mopidy.models import Ref from mopidy_gmusic import backend as backend_lib from tests.test_extension import ExtensionTest class LibraryTest(unittest.TestCase): def setUp(self): config = ExtensionTest.get_config() self.backend = backend_lib.GMusicBackend(config=config, audio=None) def test_browse_radio_deactivated(self): config = ExtensionTest.get_config() config["gmusic"]["radio_stations_in_browse"] = False self.backend = backend_lib.GMusicBackend(config=config, audio=None) refs = self.backend.library.browse("gmusic:directory") for ref in refs: assert ref.uri != "gmusic:radio" def test_browse_none(self): refs = self.backend.library.browse(None) assert refs == [] def test_browse_invalid(self): refs = self.backend.library.browse("gmusic:invalid_uri") assert refs == [] def test_browse_root(self): refs = self.backend.library.browse("gmusic:directory") found = False for ref in refs: if ref.uri == "gmusic:album": found = True break assert found, "ref 'gmusic:album' not found" found = False for ref in refs: if ref.uri == "gmusic:artist": found = True break assert found, "ref 'gmusic:artist' not found" found = False for ref in refs: if ref.uri == "gmusic:track": found = True break assert found, "ref 'gmusic:track' not found" found = False for ref in refs: if ref.uri == "gmusic:radio": found = True break assert found, "ref 'gmusic:radio' not found" def test_browse_tracks(self): refs = self.backend.library.browse("gmusic:track") assert refs is not None def test_browse_artist(self): refs = self.backend.library.browse("gmusic:artist") assert refs is not None def test_browse_artist_id_invalid(self): refs = self.backend.library.browse("gmusic:artist:artist_id") assert refs is not None assert refs == [] def test_browse_album(self): refs = self.backend.library.browse("gmusic:album") assert refs is not None def test_browse_album_id_invalid(self): refs = self.backend.library.browse("gmusic:album:album_id") assert refs is not None assert refs == [] def test_browse_radio(self): refs = self.backend.library.browse("gmusic:radio") # tests should be unable to fetch stations :( assert refs is not None assert refs == [ Ref.directory(uri="gmusic:radio:IFL", name="I'm Feeling Lucky") ] def test_browse_station(self): refs = self.backend.library.browse("gmusic:radio:invalid_stations_id") # tests should be unable to fetch stations :( assert refs == [] def test_lookup_invalid(self): refs = self.backend.library.lookup("gmusic:invalid_uri") # tests should be unable to fetch any content :( assert refs == [] def test_lookup_invalid_album(self): refs = self.backend.library.lookup("gmusic:album:invalid_uri") # tests should be unable to fetch any content :( assert refs == [] def test_lookup_invalid_artist(self): refs = self.backend.library.lookup("gmusic:artis:invalid_uri") # tests should be unable to fetch any content :( assert refs == [] def test_lookup_invalid_track(self): refs = self.backend.library.lookup("gmusic:track:invalid_uri") # tests should be unable to fetch any content :( assert refs == [] def test_search(self): refs = self.backend.library.search({"artist": ["abba"]}) assert refs is not None Mopidy-GMusic-4.0.0/tests/test_playback.py0000664000175000017500000000232213577731553020727 0ustar jodaljodal00000000000000from unittest import mock import pytest from mopidy_gmusic import playback @pytest.fixture def backend(): backend_mock = mock.Mock() backend_mock.config = {"gmusic": {"bitrate": 160}} return backend_mock @pytest.fixture def provider(backend): return playback.GMusicPlaybackProvider(audio=None, backend=backend) def test_translate_invalid_uri(backend, provider): backend.session.get_stream_url.return_value = None assert provider.translate_uri("gmusic:track:invalid_uri") is None def test_change_track_valid(backend, provider): stream_url = "http://stream.example.com/foo.mp3" backend.session.get_stream_url.return_value = stream_url assert provider.translate_uri("gmusic:track:valid_uri") == stream_url backend.session.get_stream_url.assert_called_once_with( "valid_uri", quality="med" ) def test_changed_bitrate(backend, provider): stream_url = "http://stream.example.com/foo.mp3" backend.session.get_stream_url.return_value = stream_url backend.config["gmusic"]["bitrate"] = 320 assert provider.translate_uri("gmusic:track:valid_uri") == stream_url backend.session.get_stream_url.assert_called_once_with( "valid_uri", quality="hi" ) Mopidy-GMusic-4.0.0/tests/test_playlist.py0000664000175000017500000000401313577731553021001 0ustar jodaljodal00000000000000import unittest from unittest import mock from mopidy.models import Playlist, Ref, Track from mopidy_gmusic.playlists import GMusicPlaylistsProvider from tests.test_extension import ExtensionTest class PlaylistsTest(unittest.TestCase): def setUp(self): backend = mock.Mock() backend.config = ExtensionTest.get_config() self.provider = GMusicPlaylistsProvider(backend) self.provider._playlists = { "gmusic:playlist:foo": Playlist( uri="gmusic:playlist:foo", name="foo", tracks=[Track(uri="gmusic:track:test_track", name="test")], ), "gmusic:playlist:boo": Playlist( uri="gmusic:playlist:boo", name="boo", tracks=[] ), } def test_as_list(self): result = self.provider.as_list() assert len(result) == 2 assert result[0] == Ref.playlist(uri="gmusic:playlist:boo", name="boo") assert result[1] == Ref.playlist(uri="gmusic:playlist:foo", name="foo") def test_get_items(self): result = self.provider.get_items("gmusic:playlist:foo") assert len(result) == 1 assert result[0] == Ref.track( uri="gmusic:track:test_track", name="test" ) def test_get_items_for_unknown_playlist(self): result = self.provider.get_items("gmusic:playlist:bar") assert result is None def test_create(self): with self.assertRaises(NotImplementedError): self.provider.create("foo") def test_delete(self): with self.assertRaises(NotImplementedError): self.provider.delete("gmusic:playlist:foo") def test_save(self): with self.assertRaises(NotImplementedError): self.provider.save(Playlist()) def test_lookup_valid(self): result = self.provider.lookup("gmusic:playlist:foo") assert result is not None def test_lookup_invalid(self): result = self.provider.lookup("gmusic:playlist:bar") assert result is None Mopidy-GMusic-4.0.0/tests/test_repeating_timer.py0000664000175000017500000000155113577731553022322 0ustar jodaljodal00000000000000import logging import unittest from threading import Event from mopidy_gmusic.repeating_timer import RepeatingTimer logger = logging.getLogger(__name__) class ExtensionTest(unittest.TestCase): def setUp(self): self._event = Event() def _run_by_timer(self): self._event.set() logger.debug("Tick.") def test_init(self): timer = RepeatingTimer(self._run_by_timer, 0.5) timer.start() assert self._event.wait(1), "timer was not running" self._event.clear() assert self._event.wait(1), "timer was not running" timer.cancel() def test_stop(self): timer = RepeatingTimer(self._run_by_timer, 10) timer.start() assert timer.is_alive(), "timer is not running" timer.cancel() timer.join(1) assert not timer.is_alive(), "timer is still alive" Mopidy-GMusic-4.0.0/tests/test_scrobbler_frontend.py0000664000175000017500000000175513577731553023026 0ustar jodaljodal00000000000000from unittest import mock import pytest from mopidy import models from mopidy_gmusic import scrobbler_frontend @pytest.yield_fixture def send_mock(): patcher = mock.patch.object(scrobbler_frontend.listener, "send") yield patcher.start() patcher.stop() @pytest.fixture def frontend(send_mock): return scrobbler_frontend.GMusicScrobblerFrontend(config={}, core=None) def test_aborts_if_less_than_half_is_played(frontend, send_mock): track = models.Track(uri="gmusic:track:foo", length=60000) tl_track = models.TlTrack(tlid=17, track=track) frontend.track_playback_ended(tl_track, 20000) assert send_mock.call_count == 0 def test_scrobbles_if_more_than_half_is_played(frontend, send_mock): track = models.Track(uri="gmusic:track:foo", length=60000) tl_track = models.TlTrack(tlid=17, track=track) frontend.track_playback_ended(tl_track, 40000) send_mock.assert_called_once_with( mock.ANY, "increment_song_playcount", track_id="foo" ) Mopidy-GMusic-4.0.0/tests/test_session.py0000664000175000017500000002220413577731553020625 0ustar jodaljodal00000000000000from unittest import mock import pytest import requests import gmusicapi from mopidy_gmusic import session as session_lib @pytest.fixture def offline_session(): api_mock = mock.Mock(spec=gmusicapi.Mobileclient) api_mock.is_authenticated.return_value = False return session_lib.GMusicSession(all_access=True, api=api_mock) @pytest.fixture def online_session(): api_mock = mock.Mock(spec=gmusicapi.Mobileclient) api_mock.is_authenticated.return_value = True return session_lib.GMusicSession(all_access=True, api=api_mock) # TODO login class TestLogout: def test_when_offline(self, offline_session): assert offline_session.logout() is None assert offline_session.api.logout.call_count == 0 def test_when_online(self, online_session): online_session.api.logout.return_value = mock.sentinel.rv assert online_session.logout() is mock.sentinel.rv online_session.api.logout.assert_called_once_with() def test_when_call_failure(self, online_session, caplog): online_session.api.logout.side_effect = gmusicapi.CallFailure( "foo", "bar" ) assert online_session.logout() is None assert "Call to Google Play Music failed" in caplog.text def test_when_connection_error(self, online_session, caplog): online_session.api.logout.side_effect = ( requests.exceptions.ConnectionError ) assert online_session.logout() is None assert "HTTP request to Google Play Music failed" in caplog.text class TestGetAllSongs: def test_when_offline(self, offline_session): assert offline_session.get_all_songs() == [] def test_when_online(self, online_session): online_session.api.get_all_songs.return_value = mock.sentinel.rv assert online_session.get_all_songs() is mock.sentinel.rv online_session.api.get_all_songs.assert_called_once_with() class TestGetStreamUrl: def test_when_offline(self, offline_session): assert offline_session.get_stream_url("abc") is None def test_when_online(self, online_session): online_session.api.get_stream_url.return_value = mock.sentinel.rv assert online_session.get_stream_url("abc") is mock.sentinel.rv online_session.api.get_stream_url.assert_called_once_with( "abc", quality="hi" ) class TestGetAllPlaylists: def test_when_offline(self, offline_session): assert offline_session.get_all_playlists() == [] def test_when_online(self, online_session): online_session.api.get_all_playlists.return_value = mock.sentinel.rv assert online_session.get_all_playlists() is mock.sentinel.rv online_session.api.get_all_playlists.assert_called_once_with() class TestGetAllUserPlaylistContents: def test_when_offline(self, offline_session): assert offline_session.get_all_user_playlist_contents() == [] def test_when_online(self, online_session): online_session.api.get_all_user_playlist_contents.return_value = ( mock.sentinel.rv ) assert ( online_session.get_all_user_playlist_contents() is mock.sentinel.rv ) ( online_session.api.get_all_user_playlist_contents.assert_called_once_with() ) class TestGetSharedPlaylistContents: def test_when_offline(self, offline_session): assert offline_session.get_shared_playlist_contents("token") == [] def test_when_online(self, online_session): online_session.api.get_shared_playlist_contents.return_value = ( mock.sentinel.rv ) assert ( online_session.get_shared_playlist_contents("token") is mock.sentinel.rv ) ( online_session.api.get_shared_playlist_contents.assert_called_once_with( "token" ) ) class TestGetTopSongs: def test_when_offline(self, offline_session): assert offline_session.get_top_songs() == [] def test_when_online(self, online_session): online_session.api.get_top_songs.return_value = mock.sentinel.rv assert online_session.get_top_songs() is mock.sentinel.rv online_session.api.get_top_songs.assert_called_once_with() class TestGetTrackInfo: def test_when_offline(self, offline_session): assert offline_session.get_track_info("id") is None def test_when_online(self, online_session): online_session.api.get_track_info.return_value = mock.sentinel.rv assert online_session.get_track_info("id") is mock.sentinel.rv online_session.api.get_track_info.assert_called_once_with("id") def test_without_all_access(self, online_session, caplog): online_session._all_access = False assert online_session.get_track_info("id") is None assert ( "Google Play Music All Access is required for get_track_info()" in caplog.text ) class TestGetAlbumInfo: def test_when_offline(self, offline_session): assert offline_session.get_album_info("id") is None def test_when_online(self, online_session): online_session.api.get_album_info.return_value = mock.sentinel.rv result = online_session.get_album_info("id", include_tracks=False) assert result is mock.sentinel.rv online_session.api.get_album_info.assert_called_once_with( "id", include_tracks=False ) def test_without_all_access(self, online_session, caplog): online_session._all_access = False assert online_session.get_album_info("id") is None assert ( "Google Play Music All Access is required for get_album_info()" in caplog.text ) class TestGetArtistInfo: def test_when_offline(self, offline_session): assert offline_session.get_artist_info("id") is None def test_when_online(self, online_session): online_session.api.get_artist_info.return_value = mock.sentinel.rv result = online_session.get_artist_info( "id", include_albums=False, max_rel_artist=3, max_top_tracks=4 ) assert result is mock.sentinel.rv online_session.api.get_artist_info.assert_called_once_with( "id", include_albums=False, max_rel_artist=3, max_top_tracks=4 ) def test_without_all_access(self, online_session, caplog): online_session._all_access = False assert online_session.get_artist_info("id") is None assert ( "Google Play Music All Access is required for get_artist_info()" in caplog.text ) class TestSearchAllAccess: def test_when_offline(self, offline_session): assert offline_session.search("abba") is None def test_when_online(self, online_session): online_session.api.search.return_value = mock.sentinel.rv result = online_session.search("abba", max_results=10) assert result is mock.sentinel.rv online_session.api.search.assert_called_once_with( "abba", max_results=10 ) def test_without_all_access(self, online_session, caplog): online_session._all_access = False online_session.api.search.return_value = mock.sentinel.rv assert online_session.search("abba") is mock.sentinel.rv assert "Google Play Music All Access is required for" not in caplog.text class TestGetAllStations: def test_when_offline(self, offline_session): assert offline_session.get_all_stations() == [ {"id": "IFL", "name": "I'm Feeling Lucky"} ] def test_when_online(self, online_session): online_session.api.get_all_stations.return_value = mock.sentinel.rv assert online_session.get_all_stations() is mock.sentinel.rv online_session.api.get_all_stations.assert_called_once_with() class TestGetStationTracks: def test_when_offline(self, offline_session): assert offline_session.get_station_tracks("IFL") == [] def test_when_online(self, online_session): online_session.api.get_station_tracks.return_value = mock.sentinel.rv result = online_session.get_station_tracks("IFL", num_tracks=5) assert result is mock.sentinel.rv online_session.api.get_station_tracks.assert_called_once_with( "IFL", num_tracks=5 ) def test_without_all_access(self, online_session, caplog): online_session._all_access = False assert online_session.get_station_tracks("IFL") == [] assert ( "Google Play Music All Access is required for get_station_tracks()" in caplog.text ) class TestIncrementSongPlayCount: def test_when_offline(self, offline_session): assert offline_session.increment_song_playcount("foo") is None def test_when_online(self, online_session): online_session.api.increment_song_playcount.return_value = ( mock.sentinel.rv ) result = online_session.increment_song_playcount( "foo", plays=2, playtime=1000000000 ) assert result is mock.sentinel.rv online_session.api.increment_song_playcount.assert_called_once_with( "foo", plays=2, playtime=1000000000 ) Mopidy-GMusic-4.0.0/tox.ini0000664000175000017500000000073713577731553015711 0ustar jodaljodal00000000000000[tox] envlist = py37, py38, black, check-manifest, flake8 [testenv] sitepackages = true deps = .[test] commands = python -m pytest \ --basetemp={envtmpdir} \ --cov=mopidy_gmusic --cov-report=term-missing \ {posargs} [testenv:black] deps = .[lint] commands = python -m black --check . [testenv:check-manifest] deps = .[lint] commands = python -m check_manifest [testenv:flake8] deps = .[lint] commands = python -m flake8 --show-source --statistics