py-music-assistant 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: py-music-assistant
3
+ Version: 0.0.1
4
+ Summary: Python HTTP client and mediavocab bridge for a Music Assistant server
5
+ Author-email: JarbasAI <jarbasai@mailfence.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/TigreGotico/py-music-assistant
8
+ Project-URL: Source, https://github.com/TigreGotico/py-music-assistant
9
+ Keywords: music-assistant,mediavocab,ovos,OpenVoiceOS,OCP,media
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: requests
21
+ Requires-Dist: ovos-utils>=0.0.38
22
+ Requires-Dist: mediavocab>=1.0.0
23
+ Requires-Dist: music-assistant-models>=1.0.0
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest; extra == "test"
26
+ Requires-Dist: pytest-cov; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # py-music-assistant
30
+
31
+ Python HTTP client and [mediavocab](https://github.com/TigreGotico/mediavocab)
32
+ bridge for a [Music Assistant](https://www.music-assistant.io/) server.
33
+
34
+ It is the single transport + conversion layer shared by the OVOS Music Assistant
35
+ integrations:
36
+
37
+ - **[ovos-media-plugin-mass](https://github.com/OpenVoiceOS/ovos-media-plugin-mass)** — playback backend (`opm.media.audio`)
38
+ - **[ovos-media-provider-mass](https://github.com/OpenVoiceOS/ovos-media-provider-mass)** — catalog/search provider (`opm.media.provider`)
39
+ - **[ovos-skill-music-assistant](https://github.com/OpenVoiceOS/ovos-skill-music-assistant)** — legacy OCP search skill
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install py-music-assistant
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ```python
50
+ from py_music_assistant import SimpleHTTPMusicAssistantClient, search_to_releases
51
+
52
+ api = SimpleHTTPMusicAssistantClient("http://192.168.1.100:8095")
53
+
54
+ # raw search (dict of buckets: tracks/albums/artists/radio/podcasts/audiobooks)
55
+ res = api.search_media("viagra boys", limit=10)
56
+
57
+ # mapped to typed mediavocab.Release objects (unranked; score them yourself)
58
+ releases = search_to_releases(res)
59
+ for r in releases:
60
+ print(r.work.title, r.work.media_type, r.uri) # e.g. "Worms" MUSIC library://track/9903
61
+ ```
62
+
63
+ The client talks to the server's synchronous JSON `/api` endpoint (no WebSocket
64
+ lifecycle). Item `uri`s are `library://<type>/<id>` identifiers that the
65
+ `ovos-media-plugin-mass` backend resolves and plays.
66
+
67
+ ## Docs
68
+
69
+ - [docs/index.md](docs/index.md) — overview
70
+ - [docs/client-api.md](docs/client-api.md) — `SimpleHTTPMusicAssistantClient` reference
71
+ - [docs/mediavocab-bridge.md](docs/mediavocab-bridge.md) — dict → `Release` mapping
72
+
73
+ ## Tests
74
+
75
+ ```bash
76
+ pip install -e .[test]
77
+ pytest test/ # network-free (mocked + fixtures)
78
+ MASS_SERVER_URL=http://<host>:8095 pytest test/live/ # opt-in, against a real server
79
+ ```
80
+
81
+ ## License
82
+
83
+ Apache-2.0
@@ -0,0 +1,55 @@
1
+ # py-music-assistant
2
+
3
+ Python HTTP client and [mediavocab](https://github.com/TigreGotico/mediavocab)
4
+ bridge for a [Music Assistant](https://www.music-assistant.io/) server.
5
+
6
+ It is the single transport + conversion layer shared by the OVOS Music Assistant
7
+ integrations:
8
+
9
+ - **[ovos-media-plugin-mass](https://github.com/OpenVoiceOS/ovos-media-plugin-mass)** — playback backend (`opm.media.audio`)
10
+ - **[ovos-media-provider-mass](https://github.com/OpenVoiceOS/ovos-media-provider-mass)** — catalog/search provider (`opm.media.provider`)
11
+ - **[ovos-skill-music-assistant](https://github.com/OpenVoiceOS/ovos-skill-music-assistant)** — legacy OCP search skill
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pip install py-music-assistant
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```python
22
+ from py_music_assistant import SimpleHTTPMusicAssistantClient, search_to_releases
23
+
24
+ api = SimpleHTTPMusicAssistantClient("http://192.168.1.100:8095")
25
+
26
+ # raw search (dict of buckets: tracks/albums/artists/radio/podcasts/audiobooks)
27
+ res = api.search_media("viagra boys", limit=10)
28
+
29
+ # mapped to typed mediavocab.Release objects (unranked; score them yourself)
30
+ releases = search_to_releases(res)
31
+ for r in releases:
32
+ print(r.work.title, r.work.media_type, r.uri) # e.g. "Worms" MUSIC library://track/9903
33
+ ```
34
+
35
+ The client talks to the server's synchronous JSON `/api` endpoint (no WebSocket
36
+ lifecycle). Item `uri`s are `library://<type>/<id>` identifiers that the
37
+ `ovos-media-plugin-mass` backend resolves and plays.
38
+
39
+ ## Docs
40
+
41
+ - [docs/index.md](docs/index.md) — overview
42
+ - [docs/client-api.md](docs/client-api.md) — `SimpleHTTPMusicAssistantClient` reference
43
+ - [docs/mediavocab-bridge.md](docs/mediavocab-bridge.md) — dict → `Release` mapping
44
+
45
+ ## Tests
46
+
47
+ ```bash
48
+ pip install -e .[test]
49
+ pytest test/ # network-free (mocked + fixtures)
50
+ MASS_SERVER_URL=http://<host>:8095 pytest test/live/ # opt-in, against a real server
51
+ ```
52
+
53
+ ## License
54
+
55
+ Apache-2.0
@@ -0,0 +1,29 @@
1
+ """Python client + mediavocab bridge for a Music Assistant server.
2
+
3
+ Exposes the synchronous :class:`SimpleHTTPMusicAssistantClient` HTTP client and
4
+ converters that map Music Assistant API dicts into :class:`mediavocab.Release`
5
+ objects, shared by the OVOS Music Assistant integrations.
6
+ """
7
+ from py_music_assistant.client import (
8
+ SimpleHTTPMusicAssistantClient,
9
+ debug_method,
10
+ )
11
+ from py_music_assistant.converters import (
12
+ PLATFORM,
13
+ item_to_release,
14
+ items_to_releases,
15
+ recently_played_to_releases,
16
+ search_to_releases,
17
+ )
18
+ from py_music_assistant.version import __version__
19
+
20
+ __all__ = [
21
+ "SimpleHTTPMusicAssistantClient",
22
+ "debug_method",
23
+ "item_to_release",
24
+ "items_to_releases",
25
+ "search_to_releases",
26
+ "recently_played_to_releases",
27
+ "PLATFORM",
28
+ "__version__",
29
+ ]
@@ -0,0 +1,278 @@
1
+ """HTTP client for a Music Assistant server's REST API.
2
+
3
+ A thin, synchronous wrapper over the Music Assistant ``/api`` JSON-RPC-style
4
+ endpoint that avoids the WebSocket client's connection lifecycle. It is the
5
+ single transport shared by the OVOS Music Assistant integrations
6
+ (``ovos-media-plugin-mass`` for playback, ``ovos-media-provider-mass`` for
7
+ catalog search, and the legacy ``ovos-skill-music-assistant``).
8
+ """
9
+ import functools
10
+ import json
11
+ import uuid
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ import requests
15
+ from ovos_utils.log import LOG
16
+
17
+ from music_assistant_models.enums import MediaType, QueueOption
18
+ from music_assistant_models.errors import MusicAssistantError
19
+ from music_assistant_models.player import Player
20
+
21
+
22
+ def debug_method(func):
23
+ """Decorator to log method inputs and outputs for debugging purposes."""
24
+
25
+ @functools.wraps(func)
26
+ def wrapper(self, *args, **kwargs):
27
+ # Format arguments for logging
28
+ args_str = ", ".join([repr(arg) for arg in args])
29
+ kwargs_str = ", ".join([f"{k}={repr(v)}" for k, v in kwargs.items()])
30
+
31
+ # Combine args and kwargs for display
32
+ all_args = []
33
+ if args_str:
34
+ all_args.append(args_str)
35
+ if kwargs_str:
36
+ all_args.append(kwargs_str)
37
+ args_display = ", ".join(all_args)
38
+
39
+ # Log the method call
40
+ method_name = f"{self.__class__.__name__}.{func.__name__}"
41
+ self.log.debug(f"CALL {method_name}({args_display})")
42
+
43
+ try:
44
+ # Execute the function
45
+ result = func(self, *args, **kwargs)
46
+
47
+ # Format result for logging (truncate if too long)
48
+ if result is None:
49
+ result_str = "None"
50
+ elif isinstance(result, (str, int, float, bool)):
51
+ result_str = repr(result)
52
+ elif isinstance(result, (list, dict)):
53
+ result_str = json.dumps(result, default=str, indent=None)
54
+ if len(result_str) > 200:
55
+ result_str = result_str[:200] + "..."
56
+ else:
57
+ result_str = f"<{type(result).__name__} object>"
58
+
59
+ self.log.debug(f"RETURN {method_name} -> {result_str}")
60
+ return result
61
+
62
+ except Exception as e:
63
+ self.log.debug(f"ERROR {method_name} -> {type(e).__name__}: {e}")
64
+ raise
65
+
66
+ return wrapper
67
+
68
+
69
+ class SimpleHTTPMusicAssistantClient:
70
+ """Simple HTTP-based Music Assistant client that avoids WebSocket issues."""
71
+
72
+ def __init__(self, server_url: str, session: Optional[requests.Session] = None):
73
+ self.server_url = server_url.rstrip("/")
74
+ self.api_url = f"{self.server_url}/api"
75
+ self.session = session or requests.Session()
76
+ self.log = LOG()
77
+
78
+ @debug_method
79
+ def send_command(self, command: str, **args) -> Any:
80
+ """Send a command to Music Assistant via HTTP API."""
81
+ payload = {"command": command, "message_id": uuid.uuid4().hex, "args": args}
82
+
83
+ response = self.session.post(self.api_url, json=payload)
84
+ if response.status_code == 200:
85
+ return response.json()
86
+ raise MusicAssistantError(f"HTTP {response.status_code}: {response.text}")
87
+
88
+ @debug_method
89
+ def get_players(self) -> List[Player]:
90
+ """Get all available players."""
91
+ result = self.send_command("players/all")
92
+ return [Player.from_dict(player_data) for player_data in result]
93
+
94
+ def search_media(
95
+ self, query: str, media_types: Optional[List[MediaType]] = None, limit: int = 20
96
+ ) -> Dict[str, Any]:
97
+ """Search for media."""
98
+ args = {"search_query": query, "limit": limit}
99
+ if media_types:
100
+ args["media_types"] = [mt.value for mt in media_types]
101
+ return self.send_command("music/search", **args)
102
+
103
+ def track_info(self, uri: str) -> Dict[str, Any]:
104
+ """Resolve metadata for a single media item by uri."""
105
+ args = {"uri": uri}
106
+ return self.send_command("music/item_by_uri", **args)
107
+
108
+ def recommendations(self) -> Dict[str, Any]:
109
+ """Fetch the server's recommendations feed."""
110
+ return self.send_command("music/recommendations")
111
+
112
+ def recently_played(self) -> Dict[str, Any]:
113
+ """Fetch the server's recently-played items feed."""
114
+ return self.send_command("music/recently_played_items")
115
+
116
+ def play_media(
117
+ self,
118
+ queue_id: str,
119
+ media: str,
120
+ option: QueueOption = QueueOption.PLAY, # type: ignore
121
+ radio_mode: bool = False,
122
+ ):
123
+ """Play media on a player queue."""
124
+ self.log.info(
125
+ f"Sending play_media: queue_id={queue_id}, media={media}, option={option.value}, "
126
+ f"radio_mode={radio_mode}"
127
+ )
128
+ return self.send_command(
129
+ command="player_queues/play_media",
130
+ queue_id=queue_id,
131
+ media=media,
132
+ option=option.value,
133
+ radio_mode=radio_mode,
134
+ )
135
+
136
+ def queue_command_play(self, queue_id: str):
137
+ """Send PLAY command to given queue."""
138
+ return self.send_command("player_queues/play", queue_id=queue_id)
139
+
140
+ def queue_command_pause(self, queue_id: str):
141
+ """Pause playback."""
142
+ return self.send_command("player_queues/play_pause", queue_id=queue_id)
143
+
144
+ def queue_command_next(self, queue_id: str):
145
+ """Skip to next track."""
146
+ return self.send_command("player_queues/next", queue_id=queue_id)
147
+
148
+ def queue_command_previous(self, queue_id: str):
149
+ """Go to previous track."""
150
+ return self.send_command("player_queues/previous", queue_id=queue_id)
151
+
152
+ def player_command_power_on(self, player_id: str):
153
+ """Power on a player."""
154
+ return self.send_command("players/player_command_power_on", player_id=player_id)
155
+
156
+ def player_command_power_off(self, player_id: str):
157
+ """Power off a player."""
158
+ return self.send_command("players/player_command_power_off", player_id=player_id)
159
+
160
+ # Volume control commands
161
+ def player_command_volume_set(self, player_id: str, volume: int):
162
+ """Set player volume (0-100)."""
163
+ return self.send_command("players/cmd/volume_set", player_id=player_id, volume_level=volume)
164
+
165
+ def player_command_volume_up(self, player_id: str):
166
+ """Increase player volume."""
167
+ return self.send_command("players/cmd/volume_up", player_id=player_id)
168
+
169
+ def player_command_volume_down(self, player_id: str):
170
+ """Decrease player volume."""
171
+ return self.send_command("players/cmd/volume_down", player_id=player_id)
172
+
173
+ def player_command_volume_mute(self, player_id: str, muted: bool = True):
174
+ """Mute/unmute player."""
175
+ return self.send_command("players/cmd/volume_mute", player_id=player_id, muted=muted)
176
+
177
+ # player controls
178
+ def player_command_seek(self, player_id: str, position: int) -> None:
179
+ """Handle SEEK command for given player.
180
+
181
+ - player_id: player_id of the player to handle the command.
182
+ - position: position in seconds to seek to in the current playing item.
183
+ """
184
+ return self.send_command("players/cmd/seek", player_id=player_id, position=position)
185
+
186
+ def player_command_stop(self, player_id: str) -> None:
187
+ """Handle STOP command for given player.
188
+
189
+ - player_id: player_id of the player to handle the command.
190
+ """
191
+ return self.send_command("players/cmd/stop", player_id=player_id)
192
+
193
+ # State checking methods
194
+ def get_player_queue_items(self, queue_id: str, limit: int = 10, offset: int = 0):
195
+ """Get current queue items for a player."""
196
+ return self.send_command("player_queues/items", queue_id=queue_id, limit=limit, offset=offset)
197
+
198
+ def get_active_queue(self, player_id: str):
199
+ """Get the current active queue for a player."""
200
+ return self.send_command("player_queues/get_active_queue", player_id=player_id)
201
+
202
+ def _find_player_by_id(self, player_id: str) -> Optional[Player]:
203
+ """Find a player by ID."""
204
+ players = self.get_players()
205
+ for player in players:
206
+ if player.player_id == player_id:
207
+ return player
208
+ return None
209
+
210
+ def _extract_playback_state(self, player: Player) -> str:
211
+ """Extract playback state from player object."""
212
+ if not hasattr(player, "playback_state"):
213
+ return "unknown"
214
+
215
+ state = player.playback_state
216
+ return state.value if hasattr(state, "value") else str(state)
217
+
218
+ def _extract_track_from_media(self, player: Player) -> Optional[str]:
219
+ """Extract track name from player's current_media."""
220
+ if not (hasattr(player, "current_media") and player.current_media):
221
+ return None
222
+
223
+ media = player.current_media
224
+ if not (hasattr(media, "title") and media.title):
225
+ return None
226
+
227
+ track_name = media.title
228
+ if hasattr(media, "artist") and media.artist:
229
+ return f"{media.artist} - {track_name}"
230
+ return track_name
231
+
232
+ def _extract_track_from_queue(self, player: Player) -> Optional[str]:
233
+ """Extract track name from player's queue items."""
234
+ if not (hasattr(player, "current_item_id") and player.current_item_id):
235
+ return None
236
+
237
+ try:
238
+ queue_items = self.get_player_queue_items(player.player_id, limit=1)
239
+ if not (queue_items and len(queue_items) > 0):
240
+ return None
241
+
242
+ item = queue_items[0]
243
+ if hasattr(item, "name") and item.name:
244
+ return item.name
245
+ if hasattr(item, "media_item") and item.media_item:
246
+ return getattr(item.media_item, "name", None)
247
+ except Exception:
248
+ self.log.exception("Error extracting track from queue, returning None")
249
+ return None
250
+
251
+ def _extract_current_track(self, player: Player) -> str:
252
+ """Extract current track name with artist info."""
253
+ track_name = self._extract_track_from_media(player)
254
+ if track_name:
255
+ return track_name
256
+
257
+ track_name = self._extract_track_from_queue(player)
258
+ if track_name:
259
+ return track_name
260
+
261
+ return "No track"
262
+
263
+ def get_player_state(self, player_id: str):
264
+ """Get current player state (playing, paused, etc.)."""
265
+ player = self._find_player_by_id(player_id)
266
+ if not player:
267
+ return None
268
+
269
+ return {
270
+ "state": self._extract_playback_state(player),
271
+ "powered": getattr(player, "powered", True),
272
+ "volume_level": getattr(player, "volume_level", None),
273
+ "volume_muted": getattr(player, "volume_muted", False),
274
+ "current_track": self._extract_current_track(player),
275
+ "player_name": getattr(player, "name", "Unknown"),
276
+ "player_type": getattr(player, "provider", "Unknown"),
277
+ "available": getattr(player, "available", False),
278
+ }
@@ -0,0 +1,156 @@
1
+ """Converters from Music Assistant API dicts to mediavocab typed objects.
2
+
3
+ Music Assistant's ``music/search`` and ``music/recently_played_items`` endpoints
4
+ return media items as plain dicts. Each item carries (among others) ``name``,
5
+ ``uri`` (a ``library://<type>/<id>`` identifier the ``ovos-media-plugin-mass``
6
+ playback backend resolves), ``media_type`` (``track``/``album``/``artist``/
7
+ ``playlist``/``radio``/``podcast``/``audiobook``), ``is_playable``, ``favorite``,
8
+ an ``artists`` list, an ``album`` object, ``duration`` (seconds) and image data.
9
+
10
+ This module maps those dicts into :class:`mediavocab.Release` objects so a
11
+ :class:`MediaProvider` can stay a thin shim. Results are returned **unranked**
12
+ (``match_confidence`` left at ``0.0``); the provider scores them against the
13
+ parsed request ``Signals``.
14
+ """
15
+ from typing import Any, Dict, List, Optional
16
+
17
+ from mediavocab import MediaType, Release, Work
18
+
19
+
20
+ # Music Assistant ``media_type`` string -> mediavocab ``MediaType``.
21
+ _MEDIA_TYPE_MAP: Dict[str, MediaType] = {
22
+ "track": MediaType.MUSIC,
23
+ "album": MediaType.MUSIC,
24
+ "artist": MediaType.MUSIC,
25
+ "playlist": MediaType.PLAYLIST,
26
+ "radio": MediaType.RADIO,
27
+ "podcast": MediaType.PODCAST,
28
+ "audiobook": MediaType.AUDIOBOOK,
29
+ }
30
+
31
+ PLATFORM = "music-assistant"
32
+
33
+
34
+ def _extract_image(entry: Dict[str, Any]) -> str:
35
+ """Return the first remotely-accessible image path for an item, or ``""``.
36
+
37
+ Music Assistant exposes art either as a top-level ``image`` object or as a
38
+ list under ``metadata.images``; in both cases an image is only usable when
39
+ ``remotely_accessible`` is set (a local-only path is unreachable by OVOS).
40
+ """
41
+ img = entry.get("image")
42
+ if isinstance(img, dict) and img.get("path") and img.get("remotely_accessible"):
43
+ return img["path"]
44
+ meta = entry.get("metadata") or {}
45
+ for im in meta.get("images") or []:
46
+ if isinstance(im, dict) and im.get("path") and im.get("remotely_accessible"):
47
+ return im["path"]
48
+ return ""
49
+
50
+
51
+ def _extract_artists(entry: Dict[str, Any]) -> List[str]:
52
+ """Return artist names for an item, guarding against missing/empty fields.
53
+
54
+ (The legacy ``load_track`` path crashed on items with no ``artists``/
55
+ ``album``; the None-guards live here so every consumer benefits.)
56
+ """
57
+ if entry.get("media_type") == "artist":
58
+ name = (entry.get("name") or "").strip()
59
+ return [name] if name else []
60
+ out: List[str] = []
61
+ for a in entry.get("artists") or []:
62
+ if isinstance(a, dict):
63
+ n = (a.get("name") or "").strip()
64
+ if n:
65
+ out.append(n)
66
+ return out
67
+
68
+
69
+ def item_to_release(entry: Dict[str, Any]) -> Optional[Release]:
70
+ """Convert a single Music Assistant media-item dict to a :class:`Release`.
71
+
72
+ Returns ``None`` for items that are not playable or have no ``uri``/``name``
73
+ (e.g. an artist identity with no playable radio). ``artist``, ``album`` and
74
+ ``duration`` are mirrored into ``work.extra`` so a player can render them
75
+ without a second API call; ``match_confidence`` is left at ``0.0`` for the
76
+ caller to score.
77
+ """
78
+ if not isinstance(entry, dict):
79
+ return None
80
+ if not entry.get("is_playable", True):
81
+ return None
82
+
83
+ name = (entry.get("name") or "").strip()
84
+ uri = (entry.get("uri") or "").strip()
85
+ if not name or not uri:
86
+ return None
87
+
88
+ media_type = _MEDIA_TYPE_MAP.get(entry.get("media_type"), MediaType.MUSIC)
89
+
90
+ external_ids: Dict[str, str] = {}
91
+ raw_ext = entry.get("external_ids")
92
+ if isinstance(raw_ext, dict):
93
+ external_ids = {str(k): str(v) for k, v in raw_ext.items() if v}
94
+
95
+ artists = _extract_artists(entry)
96
+ album = entry.get("album")
97
+ album_name = album.get("name") if isinstance(album, dict) else None
98
+
99
+ work_extra: Dict[str, Any] = {"mass_media_type": entry.get("media_type")}
100
+ if artists:
101
+ work_extra["artist"] = " & ".join(artists)
102
+ if album_name:
103
+ work_extra["album"] = album_name
104
+ if entry.get("favorite"):
105
+ work_extra["favorite"] = True
106
+ duration = entry.get("duration")
107
+
108
+ work = Work(
109
+ title=name,
110
+ media_type=media_type,
111
+ runtime=float(duration) if isinstance(duration, (int, float)) and duration else None,
112
+ external_ids=dict(external_ids),
113
+ extra=work_extra,
114
+ )
115
+
116
+ return Release(
117
+ work=work,
118
+ uri=uri,
119
+ image=_extract_image(entry),
120
+ platform=PLATFORM,
121
+ match_confidence=0.0,
122
+ external_ids=dict(external_ids),
123
+ )
124
+
125
+
126
+ def items_to_releases(items: Any) -> List[Release]:
127
+ """Map a flat iterable of media-item dicts to a list of Releases.
128
+
129
+ Non-dict and non-playable items are skipped. Used directly for the
130
+ ``recently_played`` feed.
131
+ """
132
+ out: List[Release] = []
133
+ for entry in items or []:
134
+ rel = item_to_release(entry)
135
+ if rel is not None:
136
+ out.append(rel)
137
+ return out
138
+
139
+
140
+ def search_to_releases(res: Dict[str, Any]) -> List[Release]:
141
+ """Flatten a Music Assistant ``music/search`` response to a list of Releases.
142
+
143
+ The response is a dict of buckets (``tracks``, ``albums``, ``artists``,
144
+ ``playlists``, ``radio``, ``podcasts``, ``audiobooks``); each bucket is a
145
+ list of media-item dicts. This is bucket-agnostic — every list-valued bucket
146
+ is flattened — so new bucket keys are handled without code changes.
147
+ """
148
+ out: List[Release] = []
149
+ for bucket in (res or {}).values():
150
+ if isinstance(bucket, list):
151
+ out.extend(items_to_releases(bucket))
152
+ return out
153
+
154
+
155
+ # Recently-played feed shares the media-item shape, so it reuses the flat mapper.
156
+ recently_played_to_releases = items_to_releases
@@ -0,0 +1,10 @@
1
+ # START_VERSION_BLOCK
2
+ VERSION_MAJOR = 0
3
+ VERSION_MINOR = 0
4
+ VERSION_BUILD = 1
5
+ VERSION_ALPHA = 0
6
+ # END_VERSION_BLOCK
7
+
8
+ __version__ = f"{VERSION_MAJOR}.{VERSION_MINOR}.{VERSION_BUILD}"
9
+ if VERSION_ALPHA:
10
+ __version__ += f"a{VERSION_ALPHA}"
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: py-music-assistant
3
+ Version: 0.0.1
4
+ Summary: Python HTTP client and mediavocab bridge for a Music Assistant server
5
+ Author-email: JarbasAI <jarbasai@mailfence.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/TigreGotico/py-music-assistant
8
+ Project-URL: Source, https://github.com/TigreGotico/py-music-assistant
9
+ Keywords: music-assistant,mediavocab,ovos,OpenVoiceOS,OCP,media
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: requests
21
+ Requires-Dist: ovos-utils>=0.0.38
22
+ Requires-Dist: mediavocab>=1.0.0
23
+ Requires-Dist: music-assistant-models>=1.0.0
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest; extra == "test"
26
+ Requires-Dist: pytest-cov; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # py-music-assistant
30
+
31
+ Python HTTP client and [mediavocab](https://github.com/TigreGotico/mediavocab)
32
+ bridge for a [Music Assistant](https://www.music-assistant.io/) server.
33
+
34
+ It is the single transport + conversion layer shared by the OVOS Music Assistant
35
+ integrations:
36
+
37
+ - **[ovos-media-plugin-mass](https://github.com/OpenVoiceOS/ovos-media-plugin-mass)** — playback backend (`opm.media.audio`)
38
+ - **[ovos-media-provider-mass](https://github.com/OpenVoiceOS/ovos-media-provider-mass)** — catalog/search provider (`opm.media.provider`)
39
+ - **[ovos-skill-music-assistant](https://github.com/OpenVoiceOS/ovos-skill-music-assistant)** — legacy OCP search skill
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install py-music-assistant
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ```python
50
+ from py_music_assistant import SimpleHTTPMusicAssistantClient, search_to_releases
51
+
52
+ api = SimpleHTTPMusicAssistantClient("http://192.168.1.100:8095")
53
+
54
+ # raw search (dict of buckets: tracks/albums/artists/radio/podcasts/audiobooks)
55
+ res = api.search_media("viagra boys", limit=10)
56
+
57
+ # mapped to typed mediavocab.Release objects (unranked; score them yourself)
58
+ releases = search_to_releases(res)
59
+ for r in releases:
60
+ print(r.work.title, r.work.media_type, r.uri) # e.g. "Worms" MUSIC library://track/9903
61
+ ```
62
+
63
+ The client talks to the server's synchronous JSON `/api` endpoint (no WebSocket
64
+ lifecycle). Item `uri`s are `library://<type>/<id>` identifiers that the
65
+ `ovos-media-plugin-mass` backend resolves and plays.
66
+
67
+ ## Docs
68
+
69
+ - [docs/index.md](docs/index.md) — overview
70
+ - [docs/client-api.md](docs/client-api.md) — `SimpleHTTPMusicAssistantClient` reference
71
+ - [docs/mediavocab-bridge.md](docs/mediavocab-bridge.md) — dict → `Release` mapping
72
+
73
+ ## Tests
74
+
75
+ ```bash
76
+ pip install -e .[test]
77
+ pytest test/ # network-free (mocked + fixtures)
78
+ MASS_SERVER_URL=http://<host>:8095 pytest test/live/ # opt-in, against a real server
79
+ ```
80
+
81
+ ## License
82
+
83
+ Apache-2.0
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ py_music_assistant/__init__.py
5
+ py_music_assistant/client.py
6
+ py_music_assistant/converters.py
7
+ py_music_assistant/version.py
8
+ py_music_assistant.egg-info/PKG-INFO
9
+ py_music_assistant.egg-info/SOURCES.txt
10
+ py_music_assistant.egg-info/dependency_links.txt
11
+ py_music_assistant.egg-info/requires.txt
12
+ py_music_assistant.egg-info/top_level.txt
13
+ test/test_client.py
14
+ test/test_converters.py
@@ -0,0 +1,8 @@
1
+ requests
2
+ ovos-utils>=0.0.38
3
+ mediavocab>=1.0.0
4
+ music-assistant-models>=1.0.0
5
+
6
+ [test]
7
+ pytest
8
+ pytest-cov
@@ -0,0 +1 @@
1
+ py_music_assistant
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "py-music-assistant"
7
+ dynamic = ["version"]
8
+ description = "Python HTTP client and mediavocab bridge for a Music Assistant server"
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ authors = [{ name = "JarbasAI", email = "jarbasai@mailfence.com" }]
12
+ requires-python = ">=3.10"
13
+ keywords = ["music-assistant", "mediavocab", "ovos", "OpenVoiceOS", "OCP", "media"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ ]
23
+ dependencies = [
24
+ "requests",
25
+ "ovos-utils>=0.0.38",
26
+ "mediavocab>=1.0.0",
27
+ "music-assistant-models>=1.0.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ test = ["pytest", "pytest-cov"]
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/TigreGotico/py-music-assistant"
35
+ Source = "https://github.com/TigreGotico/py-music-assistant"
36
+
37
+ [tool.setuptools]
38
+ packages = ["py_music_assistant"]
39
+
40
+ [tool.setuptools.dynamic]
41
+ version = { attr = "py_music_assistant.version.__version__" }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,67 @@
1
+ """Tests for SimpleHTTPMusicAssistantClient (network-free, mocked session)."""
2
+ from unittest.mock import MagicMock
3
+
4
+ import pytest
5
+
6
+ from music_assistant_models.errors import MusicAssistantError
7
+
8
+ from py_music_assistant import SimpleHTTPMusicAssistantClient
9
+
10
+
11
+ def _client(json_return=None, status=200):
12
+ session = MagicMock()
13
+ resp = MagicMock()
14
+ resp.status_code = status
15
+ resp.json.return_value = json_return if json_return is not None else {}
16
+ resp.text = "error body"
17
+ session.post.return_value = resp
18
+ return SimpleHTTPMusicAssistantClient("http://mass.local:8095/", session=session), session
19
+
20
+
21
+ def test_url_normalisation():
22
+ client, _ = _client()
23
+ assert client.server_url == "http://mass.local:8095"
24
+ assert client.api_url == "http://mass.local:8095/api"
25
+
26
+
27
+ def test_send_command_posts_payload_and_returns_json():
28
+ client, session = _client(json_return={"ok": True})
29
+ out = client.send_command("music/search", search_query="worms", limit=5)
30
+
31
+ assert out == {"ok": True}
32
+ session.post.assert_called_once()
33
+ args, kwargs = session.post.call_args
34
+ assert args[0] == "http://mass.local:8095/api"
35
+ payload = kwargs["json"]
36
+ assert payload["command"] == "music/search"
37
+ assert payload["args"] == {"search_query": "worms", "limit": 5}
38
+ assert "message_id" in payload
39
+
40
+
41
+ def test_send_command_raises_on_non_200():
42
+ client, _ = _client(status=500)
43
+ with pytest.raises(MusicAssistantError):
44
+ client.send_command("players/all")
45
+
46
+
47
+ def test_search_media_builds_args():
48
+ client, session = _client(json_return={"tracks": []})
49
+ client.search_media("worms", limit=7)
50
+ payload = session.post.call_args.kwargs["json"]
51
+ assert payload["command"] == "music/search"
52
+ assert payload["args"]["search_query"] == "worms"
53
+ assert payload["args"]["limit"] == 7
54
+
55
+
56
+ def test_recently_played_command():
57
+ client, session = _client(json_return=[])
58
+ client.recently_played()
59
+ assert session.post.call_args.kwargs["json"]["command"] == "music/recently_played_items"
60
+
61
+
62
+ def test_track_info_passes_uri():
63
+ client, session = _client(json_return={})
64
+ client.track_info("library://track/9903")
65
+ payload = session.post.call_args.kwargs["json"]
66
+ assert payload["command"] == "music/item_by_uri"
67
+ assert payload["args"] == {"uri": "library://track/9903"}
@@ -0,0 +1,146 @@
1
+ """Tests for the Music Assistant -> mediavocab converters (network-free)."""
2
+ import json
3
+ from os.path import dirname, join
4
+
5
+ from mediavocab import MediaType, Release, Work
6
+
7
+ from py_music_assistant.converters import (
8
+ PLATFORM,
9
+ item_to_release,
10
+ items_to_releases,
11
+ recently_played_to_releases,
12
+ search_to_releases,
13
+ )
14
+
15
+ FIXTURES = join(dirname(__file__), "fixtures")
16
+
17
+
18
+ def _search_fixture():
19
+ with open(join(FIXTURES, "search_worms.json")) as f:
20
+ return json.load(f)
21
+
22
+
23
+ TRACK = {
24
+ "media_type": "track",
25
+ "name": "Worms",
26
+ "uri": "library://track/9903",
27
+ "is_playable": True,
28
+ "favorite": True,
29
+ "duration": 208,
30
+ "artists": [{"name": "Viagra Boys"}],
31
+ "album": {"name": "Street Worms"},
32
+ "image": {"path": "https://art.example/worms.jpg", "remotely_accessible": True},
33
+ "external_ids": {"musicbrainz": "mbid-worms-123"},
34
+ }
35
+
36
+
37
+ def test_item_to_release_builds_valid_release():
38
+ rel = item_to_release(TRACK)
39
+ assert isinstance(rel, Release)
40
+ assert isinstance(rel.work, Work)
41
+ assert rel.work.title == "Worms"
42
+ assert rel.work.media_type == MediaType.MUSIC
43
+ assert rel.uri == "library://track/9903"
44
+ assert rel.image == "https://art.example/worms.jpg"
45
+ assert rel.platform == PLATFORM
46
+ assert rel.match_confidence == 0.0
47
+ assert rel.work.runtime == 208.0
48
+ assert rel.work.extra["artist"] == "Viagra Boys"
49
+ assert rel.work.extra["album"] == "Street Worms"
50
+ assert rel.work.extra["favorite"] is True
51
+ assert rel.external_ids["musicbrainz"] == "mbid-worms-123"
52
+
53
+
54
+ def test_media_type_mapping():
55
+ def mt(kind, uri="library://x/1"):
56
+ return item_to_release(
57
+ {"media_type": kind, "name": "x", "uri": uri, "is_playable": True}
58
+ ).work.media_type
59
+
60
+ assert mt("track") == MediaType.MUSIC
61
+ assert mt("album") == MediaType.MUSIC
62
+ assert mt("artist") == MediaType.MUSIC
63
+ assert mt("playlist") == MediaType.PLAYLIST
64
+ assert mt("radio") == MediaType.RADIO
65
+ assert mt("podcast") == MediaType.PODCAST
66
+ assert mt("audiobook") == MediaType.AUDIOBOOK
67
+ assert mt("something-new") == MediaType.MUSIC # unknown -> music fallback
68
+
69
+
70
+ def test_item_to_release_skips_unplayable():
71
+ assert item_to_release({**TRACK, "is_playable": False}) is None
72
+
73
+
74
+ def test_item_to_release_skips_missing_name_or_uri():
75
+ assert item_to_release({"name": "", "uri": "library://x/1", "is_playable": True}) is None
76
+ assert item_to_release({"name": "x", "uri": "", "is_playable": True}) is None
77
+ assert item_to_release("not a dict") is None
78
+
79
+
80
+ def test_item_to_release_none_guards_missing_artists_and_album():
81
+ """Items with no artists/album must not raise (the legacy load_track crash)."""
82
+ rel = item_to_release(
83
+ {"media_type": "track", "name": "bare", "uri": "library://track/1", "is_playable": True,
84
+ "artists": None, "album": None}
85
+ )
86
+ assert isinstance(rel, Release)
87
+ assert "artist" not in rel.work.extra
88
+ assert "album" not in rel.work.extra
89
+
90
+
91
+ def test_image_falls_back_to_metadata_images():
92
+ rel = item_to_release(
93
+ {"media_type": "track", "name": "x", "uri": "library://track/2", "is_playable": True,
94
+ "metadata": {"images": [{"path": "https://m/i.jpg", "remotely_accessible": True}]}}
95
+ )
96
+ assert rel.image == "https://m/i.jpg"
97
+
98
+
99
+ def test_image_skipped_when_not_remotely_accessible():
100
+ rel = item_to_release(
101
+ {"media_type": "track", "name": "x", "uri": "library://track/3", "is_playable": True,
102
+ "image": {"path": "/local/x.jpg", "remotely_accessible": False}}
103
+ )
104
+ assert rel.image == ""
105
+
106
+
107
+ def test_artist_identity_uses_own_name():
108
+ rel = item_to_release(
109
+ {"media_type": "artist", "name": "Viagra Boys", "uri": "library://artist/77",
110
+ "is_playable": True}
111
+ )
112
+ assert rel.work.extra["artist"] == "Viagra Boys"
113
+
114
+
115
+ def test_search_to_releases_flattens_all_buckets():
116
+ res = _search_fixture()
117
+ releases = search_to_releases(res)
118
+ titles = [r.work.title for r in releases]
119
+ # the unplayable artist and the local-only-art track are still playable-by-flag;
120
+ # only the non-playable artist is dropped
121
+ assert "Worms" in titles
122
+ assert "Street Worms" in titles
123
+ assert "Viagra Boys" in titles
124
+ assert "Worm Radio" in titles
125
+ assert "The Worm Cast" in titles
126
+ assert "How to Train Your Worm" in titles
127
+ assert "Not Playable Artist" not in titles
128
+ assert all(isinstance(r, Release) for r in releases)
129
+ # media types preserved across buckets
130
+ by_title = {r.work.title: r.work.media_type for r in releases}
131
+ assert by_title["Worm Radio"] == MediaType.RADIO
132
+ assert by_title["The Worm Cast"] == MediaType.PODCAST
133
+ assert by_title["How to Train Your Worm"] == MediaType.AUDIOBOOK
134
+
135
+
136
+ def test_search_to_releases_handles_empty_and_garbage():
137
+ assert search_to_releases({}) == []
138
+ assert search_to_releases(None) == []
139
+ assert search_to_releases({"tracks": "notalist", "albums": None}) == []
140
+
141
+
142
+ def test_recently_played_is_items_mapper():
143
+ assert recently_played_to_releases is items_to_releases
144
+ rels = recently_played_to_releases([TRACK, {"is_playable": False}])
145
+ assert len(rels) == 1
146
+ assert rels[0].work.title == "Worms"