spicetify-websocket 0.1.0__py3-none-any.whl
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.
- spicetify/__init__.py +19 -0
- spicetify/exceptions.py +27 -0
- spicetify/models.py +459 -0
- spicetify/server.py +695 -0
- spicetify_websocket-0.1.0.dist-info/METADATA +115 -0
- spicetify_websocket-0.1.0.dist-info/RECORD +9 -0
- spicetify_websocket-0.1.0.dist-info/WHEEL +5 -0
- spicetify_websocket-0.1.0.dist-info/licenses/LICENSE +21 -0
- spicetify_websocket-0.1.0.dist-info/top_level.txt +1 -0
spicetify/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
__title__ = "spicetify-websocket"
|
|
2
|
+
__license__ = "MIT"
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .exceptions import NotConnectedError, RequestTimeoutError, SpicetifyError
|
|
6
|
+
from .models import ArtistInfo, PlayerState, RepeatMode, TrackInfo
|
|
7
|
+
from .server import SpotifyServer
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"ArtistInfo",
|
|
11
|
+
"NotConnectedError",
|
|
12
|
+
"PlayerState",
|
|
13
|
+
"RepeatMode",
|
|
14
|
+
"RequestTimeoutError",
|
|
15
|
+
"SpicetifyError",
|
|
16
|
+
"SpotifyServer",
|
|
17
|
+
"TrackInfo",
|
|
18
|
+
"__version__",
|
|
19
|
+
]
|
spicetify/exceptions.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
class SpicetifyError(Exception):
|
|
2
|
+
"""Base exception for all errors raised by this library."""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class NotConnectedError(SpicetifyError):
|
|
6
|
+
"""Raised when an action is attempted without an active connection.
|
|
7
|
+
|
|
8
|
+
Args:
|
|
9
|
+
message: Human-readable error message.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, message="No active connection to Spicetify is available."):
|
|
13
|
+
super().__init__(message)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RequestTimeoutError(SpicetifyError):
|
|
17
|
+
"""Raised when Spotify does not respond to a command in time.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
command: Name of the command that timed out.
|
|
21
|
+
timeout: Timeout value in seconds.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, command: str, timeout: float):
|
|
25
|
+
self.command = command
|
|
26
|
+
self.timeout = timeout
|
|
27
|
+
super().__init__(f"Command '{command}' did not respond within {timeout}s.")
|
spicetify/models.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from enum import IntEnum
|
|
3
|
+
from typing import Any, Literal
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field, model_serializer
|
|
6
|
+
|
|
7
|
+
# --- Utility Helpers ---
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _convert_spotify_image_url(url: str) -> str:
|
|
11
|
+
"""Convert a Spotify image URL to a standard HTTP URL.
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
url: The Spotify image URL to convert.
|
|
15
|
+
|
|
16
|
+
Returns:
|
|
17
|
+
The converted HTTP URL, or the original URL if it doesn't match the expected format.
|
|
18
|
+
"""
|
|
19
|
+
if url and url.startswith("spotify:image:"):
|
|
20
|
+
image_id = url.replace("spotify:image:", "")
|
|
21
|
+
return f"https://i.scdn.co/image/{image_id}"
|
|
22
|
+
return url
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _generate_id() -> str:
|
|
26
|
+
"""Generate a unique request ID."""
|
|
27
|
+
return str(uuid.uuid4())
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# --- Request Models ---
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class BaseRequest(BaseModel):
|
|
34
|
+
"""Base model for requests sent to Spicetify.
|
|
35
|
+
|
|
36
|
+
The serialized form contains `requestName`, `requestId`, and a nested
|
|
37
|
+
`payload` object with the remaining fields.
|
|
38
|
+
|
|
39
|
+
Attributes:
|
|
40
|
+
requestName: The request type name sent over the wire.
|
|
41
|
+
requestId: Unique request identifier used to match responses.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
requestName: str
|
|
45
|
+
requestId: str = Field(default_factory=_generate_id)
|
|
46
|
+
|
|
47
|
+
@model_serializer(mode="wrap")
|
|
48
|
+
def _serialize(self, handler) -> dict:
|
|
49
|
+
"""Serialize the request into the wire format expected by Spicetify.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
dict: Serialized request with `requestName`, `requestId`, and
|
|
53
|
+
`payload`.
|
|
54
|
+
"""
|
|
55
|
+
data = handler(self)
|
|
56
|
+
|
|
57
|
+
req_name = data.pop("requestName")
|
|
58
|
+
req_id = data.pop("requestId")
|
|
59
|
+
|
|
60
|
+
return {"requestName": req_name, "requestId": req_id, "payload": data}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# --- Playback control requests ---
|
|
64
|
+
class PlayRequest(BaseRequest):
|
|
65
|
+
"""Request to start playback."""
|
|
66
|
+
|
|
67
|
+
requestName: Literal["Play"] = "Play"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class TogglePlayRequest(BaseRequest):
|
|
71
|
+
"""Request to toggle playback."""
|
|
72
|
+
|
|
73
|
+
requestName: Literal["TogglePlay"] = "TogglePlay"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class NextSongRequest(BaseRequest):
|
|
77
|
+
"""Request to skip to the next song."""
|
|
78
|
+
|
|
79
|
+
requestName: Literal["NextSong"] = "NextSong"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class PreviousSongRequest(BaseRequest):
|
|
83
|
+
"""Request to skip to the previous song."""
|
|
84
|
+
|
|
85
|
+
requestName: Literal["PreviousSong"] = "PreviousSong"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ForcePreviousSongRequest(BaseRequest):
|
|
89
|
+
"""Request to force skip to the previous song."""
|
|
90
|
+
|
|
91
|
+
requestName: Literal["ForcePreviousSong"] = "ForcePreviousSong"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# --- State Query Requests ---
|
|
95
|
+
class GetPlayerStateRequest(BaseRequest):
|
|
96
|
+
"""Request to retrieve the current player state."""
|
|
97
|
+
|
|
98
|
+
requestName: Literal["GetPlayerState"] = "GetPlayerState"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class GetCurrentTrackRequest(BaseRequest):
|
|
102
|
+
"""Request to retrieve the current track information."""
|
|
103
|
+
|
|
104
|
+
requestName: Literal["GetCurrentTrack"] = "GetCurrentTrack"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class GetVolumeRequest(BaseRequest):
|
|
108
|
+
"""Request to retrieve the current playback volume."""
|
|
109
|
+
|
|
110
|
+
requestName: Literal["GetVolume"] = "GetVolume"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class GetPlayPauseRequest(BaseRequest):
|
|
114
|
+
"""Request to retrieve the current play/pause state."""
|
|
115
|
+
|
|
116
|
+
requestName: Literal["GetPlayPause"] = "GetPlayPause"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class PauseRequest(BaseRequest):
|
|
120
|
+
"""Request to pause playback."""
|
|
121
|
+
|
|
122
|
+
requestName: Literal["Pause"] = "Pause"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# --- Playback Setting Requests ---
|
|
126
|
+
class SetShuffleRequest(BaseRequest):
|
|
127
|
+
"""Request to enable or disable shuffle mode.
|
|
128
|
+
|
|
129
|
+
Attributes:
|
|
130
|
+
state: True to enable shuffle, False to disable.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
requestName: Literal["SetShuffle"] = "SetShuffle"
|
|
134
|
+
state: bool = Field(..., description="True to enable shuffle, False to disable")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class SetMuteRequest(BaseRequest):
|
|
138
|
+
"""Request to mute or unmute the playback.
|
|
139
|
+
|
|
140
|
+
Attributes:
|
|
141
|
+
state: True to mute, False to unmute.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
requestName: Literal["SetMute"] = "SetMute"
|
|
145
|
+
state: bool = Field(..., description="True to mute, False to unmute")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class SeekRequest(BaseRequest):
|
|
149
|
+
"""Request to seek to a specific position in the current track.
|
|
150
|
+
|
|
151
|
+
Attributes:
|
|
152
|
+
position: Position in milliseconds to seek to.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
requestName: Literal["Seek"] = "Seek"
|
|
156
|
+
position: int | float = Field(..., ge=0, description="Position in milliseconds to seek to")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class SetVolumeRequest(BaseRequest):
|
|
160
|
+
"""Request to set the playback volume.
|
|
161
|
+
|
|
162
|
+
Attributes:
|
|
163
|
+
level: Desired volume level between 0.0 and 1.0.
|
|
164
|
+
"""
|
|
165
|
+
|
|
166
|
+
requestName: Literal["SetVolume"] = "SetVolume"
|
|
167
|
+
level: float | int = Field(..., ge=0.0, le=1.0, description="Volume between 0.0 and 1.0")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class SetRepeatRequest(BaseRequest):
|
|
171
|
+
"""Request to change the repeat mode.
|
|
172
|
+
|
|
173
|
+
Attributes:
|
|
174
|
+
mode: Repeat mode, where 0 means off, 1 means context, and 2 means track.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
requestName: Literal["SetRepeat"] = "SetRepeat"
|
|
178
|
+
mode: int = Field(..., ge=0, le=2, description="0=Off, 1=Context, 2=Track")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class PlayUriRequest(BaseRequest):
|
|
182
|
+
"""Request to start playback from a Spotify URI or URL.
|
|
183
|
+
|
|
184
|
+
Attributes:
|
|
185
|
+
uri: Spotify URI/URL to play.
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
requestName: Literal["PlayUri"] = "PlayUri"
|
|
189
|
+
uri: str
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# --- Metadata Models ---
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class ArtistInfo(BaseModel):
|
|
196
|
+
"""Metadata for an artist.
|
|
197
|
+
|
|
198
|
+
Attributes:
|
|
199
|
+
name: Artist name.
|
|
200
|
+
uri: Spotify URI of the artist.
|
|
201
|
+
"""
|
|
202
|
+
|
|
203
|
+
name: str
|
|
204
|
+
uri: str
|
|
205
|
+
|
|
206
|
+
def __str__(self) -> str:
|
|
207
|
+
"""Return a human-readable string representation of the artist."""
|
|
208
|
+
return f"{self.name} ({self.uri})"
|
|
209
|
+
|
|
210
|
+
@property
|
|
211
|
+
def url(self) -> str:
|
|
212
|
+
"""Return the Spotify web URL for the artist.
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
Spotify web URL for the artist.
|
|
216
|
+
"""
|
|
217
|
+
return f"https://open.spotify.com/artist/{self.uri.split(':')[-1]}"
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class TrackInfo(BaseModel):
|
|
221
|
+
"""Metadata for the currently playing track.
|
|
222
|
+
|
|
223
|
+
Attributes:
|
|
224
|
+
uri: Spotify URI of the track.
|
|
225
|
+
title: Track title.
|
|
226
|
+
duration_ms: Track duration in milliseconds.
|
|
227
|
+
artists: List of artists associated with the track.
|
|
228
|
+
album_name: Name of the album.
|
|
229
|
+
album_uri: Spotify URI of the album.
|
|
230
|
+
image_url: URL of the album artwork image. Default is None if not available.
|
|
231
|
+
is_explicit: Whether the track is marked as explicit. Default is False.
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
uri: str
|
|
235
|
+
title: str
|
|
236
|
+
duration_ms: int
|
|
237
|
+
artists: list[ArtistInfo]
|
|
238
|
+
album_name: str
|
|
239
|
+
album_uri: str
|
|
240
|
+
image_url: str | None = None
|
|
241
|
+
is_explicit: bool = False
|
|
242
|
+
|
|
243
|
+
def __str__(self) -> str:
|
|
244
|
+
"""Return a human-readable string representation of the track."""
|
|
245
|
+
artist_names = ", ".join(artist.name for artist in self.artists)
|
|
246
|
+
return f"{self.title} by {artist_names} from the album '{self.album_name}'"
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def url(self) -> str:
|
|
250
|
+
"""Return the Spotify web URL for the track.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
Spotify web URL for the track.
|
|
254
|
+
"""
|
|
255
|
+
return f"https://open.spotify.com/track/{self.uri.split(':')[-1]}"
|
|
256
|
+
|
|
257
|
+
@property
|
|
258
|
+
def album_url(self) -> str:
|
|
259
|
+
"""Return the Spotify web URL for the album.
|
|
260
|
+
|
|
261
|
+
Returns:
|
|
262
|
+
Spotify web URL for the album.
|
|
263
|
+
"""
|
|
264
|
+
return f"https://open.spotify.com/album/{self.album_uri.split(':')[-1]}"
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def duration_seconds(self) -> float | int:
|
|
268
|
+
"""Return the track duration in seconds.
|
|
269
|
+
|
|
270
|
+
Returns:
|
|
271
|
+
Track duration in seconds.
|
|
272
|
+
"""
|
|
273
|
+
return self.duration_ms / 1000
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
def from_payload(payload: dict[str, Any]) -> "TrackInfo":
|
|
277
|
+
"""Create a TrackInfo instance from a payload dictionary.
|
|
278
|
+
|
|
279
|
+
Args:
|
|
280
|
+
payload: Payload containing track information.
|
|
281
|
+
|
|
282
|
+
Returns:
|
|
283
|
+
A :class:`TrackInfo` instance populated from the payload.
|
|
284
|
+
|
|
285
|
+
"""
|
|
286
|
+
track_data = payload.get("track", {})
|
|
287
|
+
metadata = track_data.get("metadata", {})
|
|
288
|
+
|
|
289
|
+
raw_artists = track_data.get("artists", [])
|
|
290
|
+
artists = [
|
|
291
|
+
ArtistInfo(name=artist.get("name"), uri=artist.get("uri")) for artist in raw_artists
|
|
292
|
+
]
|
|
293
|
+
|
|
294
|
+
duration = track_data.get("duration", {})
|
|
295
|
+
if isinstance(duration, dict):
|
|
296
|
+
duration_ms = duration.get("milliseconds", 0)
|
|
297
|
+
else:
|
|
298
|
+
duration_ms = int(duration) if duration else 0
|
|
299
|
+
|
|
300
|
+
images = track_data.get("images", [])
|
|
301
|
+
has_image = False
|
|
302
|
+
raw_image_url = ""
|
|
303
|
+
if images and len(images) > 0:
|
|
304
|
+
has_image = True
|
|
305
|
+
raw_image_url = images[0].get("url")
|
|
306
|
+
elif "image_url" in metadata:
|
|
307
|
+
has_image = True
|
|
308
|
+
raw_image_url = metadata.get("image_url")
|
|
309
|
+
|
|
310
|
+
image_url = _convert_spotify_image_url(raw_image_url) if has_image else None
|
|
311
|
+
|
|
312
|
+
return TrackInfo(
|
|
313
|
+
uri=track_data.get("uri", ""),
|
|
314
|
+
title=track_data.get("name", ""),
|
|
315
|
+
duration_ms=duration_ms,
|
|
316
|
+
artists=artists,
|
|
317
|
+
album_name=track_data.get("album", {}).get("name", ""),
|
|
318
|
+
album_uri=track_data.get("album", {}).get("uri", ""),
|
|
319
|
+
image_url=image_url,
|
|
320
|
+
is_explicit=track_data.get("isExplicit", False),
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# --- Playback State Models ---
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class PlayerStateEvent(BaseModel):
|
|
328
|
+
"""Represents the current Spotify player state.
|
|
329
|
+
|
|
330
|
+
Attributes:
|
|
331
|
+
event: Event name emitted by the client.
|
|
332
|
+
is_playing: Whether playback is currently active.
|
|
333
|
+
volume: Current playback volume.
|
|
334
|
+
current_track: Information about the current track, if available.
|
|
335
|
+
See :class:`TrackInfo`.
|
|
336
|
+
"""
|
|
337
|
+
|
|
338
|
+
event: Literal["player_state_changed"] = "player_state_changed"
|
|
339
|
+
is_playing: bool
|
|
340
|
+
volume: float
|
|
341
|
+
current_track: TrackInfo | None = None
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
class RepeatMode(IntEnum):
|
|
345
|
+
"""Enumeration of supported repeat modes."""
|
|
346
|
+
|
|
347
|
+
OFF = 0
|
|
348
|
+
CONTEXT = 1
|
|
349
|
+
TRACK = 2
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
class PlayerState(BaseModel):
|
|
353
|
+
"""Represents the current Spotify player state.
|
|
354
|
+
|
|
355
|
+
Attributes:
|
|
356
|
+
is_playing: Whether playback is currently active.
|
|
357
|
+
position_ms: Current playback position in milliseconds.
|
|
358
|
+
duration_ms: Total duration of the current track in milliseconds.
|
|
359
|
+
shuffle: Whether shuffle mode is enabled.
|
|
360
|
+
smart_shuffle: Whether smart shuffle mode is enabled.
|
|
361
|
+
repeat_mode: Current repeat mode. See :class:`RepeatMode`.
|
|
362
|
+
track: Information about the current track, if available.
|
|
363
|
+
See :class:`TrackInfo`.
|
|
364
|
+
context_uri: Spotify URI of the current playback context, if available.
|
|
365
|
+
"""
|
|
366
|
+
|
|
367
|
+
is_playing: bool
|
|
368
|
+
position_ms: int
|
|
369
|
+
duration_ms: int
|
|
370
|
+
shuffle: bool
|
|
371
|
+
smart_shuffle: bool
|
|
372
|
+
repeat_mode: RepeatMode
|
|
373
|
+
track: TrackInfo | None = None
|
|
374
|
+
context_uri: str | None = None
|
|
375
|
+
|
|
376
|
+
def __str__(self) -> str:
|
|
377
|
+
"""Return a human-readable string of the PlayerState"""
|
|
378
|
+
track_info = str(self.track) if self.track else "No track playing"
|
|
379
|
+
return (
|
|
380
|
+
f"PlayerState:\n"
|
|
381
|
+
f" Is Playing: {self.is_playing}\n"
|
|
382
|
+
f" Position: {self.position_ms} ms\n"
|
|
383
|
+
f" Duration: {self.duration_ms} ms\n"
|
|
384
|
+
f" Shuffle: {self.shuffle}\n"
|
|
385
|
+
f" Smart Shuffle: {self.smart_shuffle}\n"
|
|
386
|
+
f" Repeat Mode: {self.repeat_mode.name}\n"
|
|
387
|
+
f" Track Info: {track_info}\n"
|
|
388
|
+
f" Context URI: {self.context_uri}"
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
@property
|
|
392
|
+
def position_seconds(self) -> float | int:
|
|
393
|
+
"""Return the current playback position in seconds.
|
|
394
|
+
|
|
395
|
+
Returns:
|
|
396
|
+
Current playback position in seconds.
|
|
397
|
+
"""
|
|
398
|
+
return self.position_ms / 1000
|
|
399
|
+
|
|
400
|
+
@property
|
|
401
|
+
def duration_seconds(self) -> float | int:
|
|
402
|
+
"""Return the total duration of the current track in seconds.
|
|
403
|
+
|
|
404
|
+
Returns:
|
|
405
|
+
Total duration of the current track in seconds.
|
|
406
|
+
"""
|
|
407
|
+
return self.duration_ms / 1000
|
|
408
|
+
|
|
409
|
+
@property
|
|
410
|
+
def context_url(self) -> str | None:
|
|
411
|
+
"""Return the Spotify web URL for the current playback context.
|
|
412
|
+
|
|
413
|
+
Returns:
|
|
414
|
+
Spotify web URL for the context, or None if not available.
|
|
415
|
+
"""
|
|
416
|
+
if self.context_uri:
|
|
417
|
+
return f"https://open.spotify.com/{self.context_uri.split(':')[1]}/{self.context_uri.split(':')[-1]}"
|
|
418
|
+
return None
|
|
419
|
+
|
|
420
|
+
@staticmethod
|
|
421
|
+
def from_payload(payload: dict[str, Any]) -> "PlayerState":
|
|
422
|
+
"""Create a PlayerState instance from a payload dictionary.
|
|
423
|
+
|
|
424
|
+
Args:
|
|
425
|
+
payload: Payload containing player state information.
|
|
426
|
+
|
|
427
|
+
Returns:
|
|
428
|
+
A :class:`PlayerState` instance populated with data from the
|
|
429
|
+
payload.
|
|
430
|
+
|
|
431
|
+
"""
|
|
432
|
+
track = None
|
|
433
|
+
item = payload.get("item")
|
|
434
|
+
if item and isinstance(item, dict):
|
|
435
|
+
track = TrackInfo.from_payload({"track": item})
|
|
436
|
+
|
|
437
|
+
context = payload.get("context", {})
|
|
438
|
+
context_uri = context.get("uri") if isinstance(context, dict) else None
|
|
439
|
+
|
|
440
|
+
is_paused = payload.get("isPaused", True)
|
|
441
|
+
is_playing = not is_paused
|
|
442
|
+
|
|
443
|
+
position_ms = payload.get("positionAsOfTimestamp", 0)
|
|
444
|
+
duration_ms = payload.get("duration", 0)
|
|
445
|
+
|
|
446
|
+
shuffle = payload.get("shuffle", False)
|
|
447
|
+
smart_shuffle = payload.get("smartShuffle", False)
|
|
448
|
+
repeat_mode = RepeatMode(payload.get("repeat", 0))
|
|
449
|
+
|
|
450
|
+
return PlayerState(
|
|
451
|
+
is_playing=is_playing,
|
|
452
|
+
position_ms=position_ms,
|
|
453
|
+
duration_ms=duration_ms,
|
|
454
|
+
shuffle=shuffle,
|
|
455
|
+
smart_shuffle=smart_shuffle,
|
|
456
|
+
repeat_mode=repeat_mode,
|
|
457
|
+
track=track,
|
|
458
|
+
context_uri=context_uri,
|
|
459
|
+
)
|
spicetify/server.py
ADDED
|
@@ -0,0 +1,695 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from typing_extensions import Self
|
|
9
|
+
from websockets.asyncio.server import Server, ServerConnection, serve
|
|
10
|
+
|
|
11
|
+
from .exceptions import NotConnectedError, RequestTimeoutError, SpicetifyError
|
|
12
|
+
from .models import (
|
|
13
|
+
BaseRequest,
|
|
14
|
+
ForcePreviousSongRequest,
|
|
15
|
+
GetCurrentTrackRequest,
|
|
16
|
+
GetPlayerStateRequest,
|
|
17
|
+
GetPlayPauseRequest,
|
|
18
|
+
GetVolumeRequest,
|
|
19
|
+
NextSongRequest,
|
|
20
|
+
PauseRequest,
|
|
21
|
+
PlayerState,
|
|
22
|
+
PlayRequest,
|
|
23
|
+
PlayUriRequest,
|
|
24
|
+
PreviousSongRequest,
|
|
25
|
+
RepeatMode,
|
|
26
|
+
SeekRequest,
|
|
27
|
+
SetMuteRequest,
|
|
28
|
+
SetRepeatRequest,
|
|
29
|
+
SetShuffleRequest,
|
|
30
|
+
SetVolumeRequest,
|
|
31
|
+
TogglePlayRequest,
|
|
32
|
+
TrackInfo,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SpotifyServer:
|
|
39
|
+
"""WebSocket server for controlling Spotify via Spicetify.
|
|
40
|
+
|
|
41
|
+
The server starts a WebSocket listener, waits for a Spicetify client to
|
|
42
|
+
connect, and exposes convenience methods for playback control and state
|
|
43
|
+
queries.
|
|
44
|
+
|
|
45
|
+
Note:
|
|
46
|
+
This class is asynchronous and is intended to be used as an async
|
|
47
|
+
context manager.
|
|
48
|
+
|
|
49
|
+
Attributes:
|
|
50
|
+
host: Hostname to bind the server to.
|
|
51
|
+
port: Port to bind the server to.
|
|
52
|
+
websocket: Active WebSocket connection, if any.
|
|
53
|
+
server: Running WebSocket server instance, if any.
|
|
54
|
+
|
|
55
|
+
Examples:
|
|
56
|
+
>>> import asyncio
|
|
57
|
+
>>> from spicetify import SpotifyServer
|
|
58
|
+
>>>
|
|
59
|
+
>>> async def main():
|
|
60
|
+
... async with SpotifyServer() as server:
|
|
61
|
+
... await server.wait_for_connection()
|
|
62
|
+
...
|
|
63
|
+
... await server.set_repeat(RepeatMode.CONTEXT)
|
|
64
|
+
...
|
|
65
|
+
... @server.on_play_pause_changed
|
|
66
|
+
... def callback(player: PlayerState):
|
|
67
|
+
... print(player)
|
|
68
|
+
... if player.track:
|
|
69
|
+
... print(", ".join([artist.name for artist in player.track.artists]))
|
|
70
|
+
...
|
|
71
|
+
... await asyncio.Event().wait()
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(self, host: str = "127.0.0.1", port: int = 9090) -> None:
|
|
75
|
+
self.host = host
|
|
76
|
+
self.port = port
|
|
77
|
+
self.websocket: ServerConnection | None = None
|
|
78
|
+
self.server: Server | None = None
|
|
79
|
+
self._pending_requests: dict[str, asyncio.Future] = {}
|
|
80
|
+
self._connected_event = asyncio.Event()
|
|
81
|
+
self._event_callbacks: dict[str, list[Callable]] = {}
|
|
82
|
+
self._background_tasks: set[asyncio.Task[Any]] = set()
|
|
83
|
+
|
|
84
|
+
# --- Event Registration ---
|
|
85
|
+
|
|
86
|
+
def on(self, event_name: str) -> Callable[[Callable[[Any], Any]], Callable[[Any], Any]]:
|
|
87
|
+
"""Register a callback for a Spicetify event.
|
|
88
|
+
|
|
89
|
+
The decorated callback is invoked whenever the matching event is
|
|
90
|
+
received from the connected Spicetify client. Callback names are
|
|
91
|
+
matched case-insensitively.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
event_name: Name of the Spicetify event to subscribe to.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
A decorator that registers the given function as event
|
|
98
|
+
handler.
|
|
99
|
+
|
|
100
|
+
Note:
|
|
101
|
+
This method is a decorator factory and must be called with the
|
|
102
|
+
event name, for example ``@server.on("SongChanged")``.
|
|
103
|
+
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
|
|
107
|
+
"""Attach `func` as a callback for the configured event.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
func: The callback function to register.
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
The original function, unchanged.
|
|
114
|
+
|
|
115
|
+
"""
|
|
116
|
+
key = event_name.lower()
|
|
117
|
+
if key not in self._event_callbacks:
|
|
118
|
+
self._event_callbacks[key] = []
|
|
119
|
+
self._event_callbacks[key].append(func)
|
|
120
|
+
return func
|
|
121
|
+
|
|
122
|
+
return decorator
|
|
123
|
+
|
|
124
|
+
# --- Convenience Event Decorators ---
|
|
125
|
+
|
|
126
|
+
def on_initial_state(self, func: Callable[[PlayerState], Any]) -> Callable[[PlayerState], Any]:
|
|
127
|
+
"""Register a callback for the ``InitialState`` event.
|
|
128
|
+
|
|
129
|
+
The callback receives a :class:`PlayerState` instance parsed from the
|
|
130
|
+
initial player data.
|
|
131
|
+
|
|
132
|
+
Note:
|
|
133
|
+
Use this decorator without parentheses, for example
|
|
134
|
+
``@server.on_initial_state``.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
func: Callback that accepts the initial player state.
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
The original callback, unchanged.
|
|
141
|
+
|
|
142
|
+
"""
|
|
143
|
+
return self.on("InitialState")(func)
|
|
144
|
+
|
|
145
|
+
def on_song_changed(self, func: Callable[[TrackInfo], Any]) -> Callable[[TrackInfo], Any]:
|
|
146
|
+
"""Register a callback for the ``SongChanged`` event.
|
|
147
|
+
|
|
148
|
+
The callback receives a :class:`TrackInfo` instance for the current
|
|
149
|
+
song.
|
|
150
|
+
|
|
151
|
+
Note:
|
|
152
|
+
Use this decorator without parentheses, for example
|
|
153
|
+
``@server.on_song_changed``.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
func: Callback that accepts the current track information.
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
The original callback, unchanged.
|
|
160
|
+
|
|
161
|
+
"""
|
|
162
|
+
return self.on("SongChanged")(func)
|
|
163
|
+
|
|
164
|
+
def on_play_pause_changed(
|
|
165
|
+
self, func: Callable[[PlayerState], Any]
|
|
166
|
+
) -> Callable[[PlayerState], Any]:
|
|
167
|
+
"""Register a callback for the ``PlayPauseChanged`` event.
|
|
168
|
+
|
|
169
|
+
The callback receives a :class:`PlayerState` instance representing the
|
|
170
|
+
current playback state.
|
|
171
|
+
|
|
172
|
+
Note:
|
|
173
|
+
Use this decorator without parentheses, for example
|
|
174
|
+
``@server.on_play_pause_changed``.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
func: Callback that accepts the current player state.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
The original callback, unchanged.
|
|
181
|
+
|
|
182
|
+
"""
|
|
183
|
+
return self.on("PlayPauseChanged")(func)
|
|
184
|
+
|
|
185
|
+
def on_volume_changed(self, func: Callable[[float | int], Any]) -> Callable[[float | int], Any]:
|
|
186
|
+
"""Register a callback for the ``VolumeChanged`` event.
|
|
187
|
+
|
|
188
|
+
The callback receives the current volume as a number in the range
|
|
189
|
+
``0`` to ``100``.
|
|
190
|
+
|
|
191
|
+
Note:
|
|
192
|
+
Use this decorator without parentheses, for example
|
|
193
|
+
``@server.on_volume_changed``.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
func: Callback that accepts the current volume percentage.
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
The original callback, unchanged.
|
|
200
|
+
|
|
201
|
+
"""
|
|
202
|
+
return self.on("VolumeChanged")(func)
|
|
203
|
+
|
|
204
|
+
def on_repeat_changed(self, func: Callable[[RepeatMode], Any]) -> Callable[[RepeatMode], Any]:
|
|
205
|
+
"""Register a callback for the ``RepeatChanged`` event.
|
|
206
|
+
|
|
207
|
+
The callback receives a :class:`RepeatMode` value.
|
|
208
|
+
|
|
209
|
+
Note:
|
|
210
|
+
Use this decorator without parentheses, for example
|
|
211
|
+
``@server.on_repeat_changed``.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
func: Callback that accepts the current repeat mode.
|
|
215
|
+
|
|
216
|
+
Returns:
|
|
217
|
+
The original callback, unchanged.
|
|
218
|
+
|
|
219
|
+
"""
|
|
220
|
+
return self.on("RepeatChanged")(func)
|
|
221
|
+
|
|
222
|
+
def on_shuffle_changed(self, func: Callable[[bool], Any]) -> Callable[[bool], Any]:
|
|
223
|
+
"""Register a callback for the ``ShuffleChanged`` event.
|
|
224
|
+
|
|
225
|
+
The callback receives ``True`` or ``False`` to indicate whether
|
|
226
|
+
shuffle is enabled.
|
|
227
|
+
|
|
228
|
+
Note:
|
|
229
|
+
Use this decorator without parentheses, for example
|
|
230
|
+
``@server.on_shuffle_changed``.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
func: Callback that accepts the shuffle state.
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
The original callback, unchanged.
|
|
237
|
+
|
|
238
|
+
"""
|
|
239
|
+
return self.on("ShuffleChanged")(func)
|
|
240
|
+
|
|
241
|
+
def on_seek_changed(self, func: Callable[[int | float], Any]) -> Callable[[int | float], Any]:
|
|
242
|
+
"""Register a callback for the ``SeekChanged`` event.
|
|
243
|
+
|
|
244
|
+
The callback receives the seek position in milliseconds.
|
|
245
|
+
|
|
246
|
+
Note:
|
|
247
|
+
Use this decorator without parentheses, for example
|
|
248
|
+
``@server.on_seek_changed``.
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
func: Callback that accepts the current seek position.
|
|
252
|
+
|
|
253
|
+
Returns:
|
|
254
|
+
The original callback, unchanged.
|
|
255
|
+
|
|
256
|
+
"""
|
|
257
|
+
return self.on("SeekChanged")(func)
|
|
258
|
+
|
|
259
|
+
# -------------------------------
|
|
260
|
+
|
|
261
|
+
# --- Event Dispatch ---
|
|
262
|
+
|
|
263
|
+
async def _dispatch_event(self, event_name: str, payload: dict[str, Any]) -> None:
|
|
264
|
+
"""Dispatch an incoming event to all registered callbacks.
|
|
265
|
+
|
|
266
|
+
The event payload is converted into a typed Python object when a known
|
|
267
|
+
event type is received. Synchronous callbacks are invoked directly,
|
|
268
|
+
while coroutine callbacks are scheduled as background tasks.
|
|
269
|
+
|
|
270
|
+
Args:
|
|
271
|
+
event_name: Name of the received event.
|
|
272
|
+
payload: Event payload received from Spicetify.
|
|
273
|
+
|
|
274
|
+
"""
|
|
275
|
+
key = event_name.lower()
|
|
276
|
+
callbacks = self._event_callbacks.get(key, [])
|
|
277
|
+
|
|
278
|
+
if not callbacks:
|
|
279
|
+
return
|
|
280
|
+
|
|
281
|
+
parsed_data = self._parse_event_payload(event_name, payload)
|
|
282
|
+
|
|
283
|
+
for callback in callbacks:
|
|
284
|
+
# noinspection broad-exception
|
|
285
|
+
try:
|
|
286
|
+
if inspect.iscoroutinefunction(callback):
|
|
287
|
+
task = asyncio.create_task(callback(parsed_data))
|
|
288
|
+
self._background_tasks.add(task)
|
|
289
|
+
task.add_done_callback(self._background_tasks.discard)
|
|
290
|
+
else:
|
|
291
|
+
callback(parsed_data)
|
|
292
|
+
except Exception:
|
|
293
|
+
logger.exception("Error executing the event callback for %s", event_name)
|
|
294
|
+
|
|
295
|
+
@staticmethod
|
|
296
|
+
def _parse_event_payload(event_name: str, payload: dict[str, Any]) -> Any:
|
|
297
|
+
"""Convert a raw event payload into a typed Python value.
|
|
298
|
+
|
|
299
|
+
Args:
|
|
300
|
+
event_name: Name of the event that produced the payload.
|
|
301
|
+
payload: Raw payload as received from Spicetify.
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
A typed representation for known events, or the raw payload for unknown events.
|
|
305
|
+
|
|
306
|
+
"""
|
|
307
|
+
key = event_name.lower()
|
|
308
|
+
|
|
309
|
+
if key == "initialstate":
|
|
310
|
+
return PlayerState.from_payload(payload.get("playerData", payload))
|
|
311
|
+
elif key == "playpausechanged":
|
|
312
|
+
return PlayerState.from_payload(payload.get("playerState", payload))
|
|
313
|
+
elif key == "songchanged":
|
|
314
|
+
return TrackInfo.from_payload(payload)
|
|
315
|
+
elif key == "volumechanged":
|
|
316
|
+
return payload.get("level", 0) * 100
|
|
317
|
+
elif key == "repeatchanged":
|
|
318
|
+
return RepeatMode(payload.get("mode"))
|
|
319
|
+
elif key == "shufflechanged":
|
|
320
|
+
return payload.get("state")
|
|
321
|
+
elif key == "seekchanged":
|
|
322
|
+
return payload.get("position")
|
|
323
|
+
|
|
324
|
+
return payload
|
|
325
|
+
|
|
326
|
+
# --- Async Context Manager ---
|
|
327
|
+
|
|
328
|
+
async def __aenter__(self) -> Self:
|
|
329
|
+
"""Enter the async context manager.
|
|
330
|
+
|
|
331
|
+
Returns:
|
|
332
|
+
The running server instance.
|
|
333
|
+
"""
|
|
334
|
+
await self.start()
|
|
335
|
+
return self
|
|
336
|
+
|
|
337
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
338
|
+
"""Exit the async context manager and stop the server."""
|
|
339
|
+
await self.stop()
|
|
340
|
+
|
|
341
|
+
# --- Connection Management ---
|
|
342
|
+
|
|
343
|
+
async def wait_for_connection(self, timeout: float | None = None) -> None:
|
|
344
|
+
"""Wait for a Spicetify client connection.
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
timeout: Maximum time to wait in seconds. If ``None``, waits indefinitely.
|
|
348
|
+
Defaults to ``None``.
|
|
349
|
+
|
|
350
|
+
Raises:
|
|
351
|
+
NotConnectedError: If timeout expires before connection is established.
|
|
352
|
+
"""
|
|
353
|
+
if self.websocket is not None:
|
|
354
|
+
return
|
|
355
|
+
|
|
356
|
+
if timeout is None:
|
|
357
|
+
await self._connected_event.wait()
|
|
358
|
+
else:
|
|
359
|
+
try:
|
|
360
|
+
await asyncio.wait_for(self._connected_event.wait(), timeout=timeout)
|
|
361
|
+
except asyncio.TimeoutError:
|
|
362
|
+
logger.warning("Connection timeout after %f seconds", timeout)
|
|
363
|
+
raise NotConnectedError("Timeout: Spicetify did not connect in time.") from None
|
|
364
|
+
|
|
365
|
+
# --- Server Lifecycle ---
|
|
366
|
+
|
|
367
|
+
async def _send_command(self, request: BaseRequest, timeout: float = 5.0) -> dict:
|
|
368
|
+
"""Send a command request to Spicetify and wait for its response.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
request: The request object to send.
|
|
372
|
+
timeout: Maximum time to wait for a response. Defaults to ``5.0``.
|
|
373
|
+
|
|
374
|
+
Returns:
|
|
375
|
+
The response data from Spicetify.
|
|
376
|
+
|
|
377
|
+
Raises:
|
|
378
|
+
NotConnectedError: If no active WebSocket connection exists.
|
|
379
|
+
RequestTimeoutError: If the response doesn't arrive within timeout.
|
|
380
|
+
"""
|
|
381
|
+
if not self.websocket:
|
|
382
|
+
raise NotConnectedError()
|
|
383
|
+
|
|
384
|
+
loop = asyncio.get_running_loop()
|
|
385
|
+
future = loop.create_future()
|
|
386
|
+
|
|
387
|
+
self._pending_requests[request.requestId] = future
|
|
388
|
+
|
|
389
|
+
json_data = request.model_dump_json()
|
|
390
|
+
logger.debug("Send: %s", json_data)
|
|
391
|
+
await self.websocket.send(json_data)
|
|
392
|
+
|
|
393
|
+
try:
|
|
394
|
+
response_data = await asyncio.wait_for(future, timeout=timeout)
|
|
395
|
+
return response_data
|
|
396
|
+
except asyncio.TimeoutError:
|
|
397
|
+
self._pending_requests.pop(request.requestId, None)
|
|
398
|
+
raise RequestTimeoutError(request.requestName, timeout) from None
|
|
399
|
+
|
|
400
|
+
async def start(self) -> None:
|
|
401
|
+
"""Start the WebSocket server."""
|
|
402
|
+
self.server = await serve(self._handler, self.host, self.port)
|
|
403
|
+
logger.info("Server started on %s:%d", self.host, self.port)
|
|
404
|
+
|
|
405
|
+
async def stop(self) -> None:
|
|
406
|
+
"""Stop the WebSocket server and close any active connection."""
|
|
407
|
+
if self.websocket:
|
|
408
|
+
await self.websocket.close()
|
|
409
|
+
self.websocket = None
|
|
410
|
+
logger.info("WebSocket connection closed.")
|
|
411
|
+
if self.server:
|
|
412
|
+
self.server.close()
|
|
413
|
+
await self.server.wait_closed()
|
|
414
|
+
logger.info("Server has stopped.")
|
|
415
|
+
|
|
416
|
+
# --- WebSocket Message Handling ---
|
|
417
|
+
|
|
418
|
+
async def _handler(self, websocket: ServerConnection) -> None:
|
|
419
|
+
"""Handle incoming WebSocket messages and resolve pending requests.
|
|
420
|
+
|
|
421
|
+
Args:
|
|
422
|
+
websocket: The WebSocket connection from a client.
|
|
423
|
+
"""
|
|
424
|
+
self.websocket = websocket
|
|
425
|
+
self._connected_event.set()
|
|
426
|
+
logger.info(f"Connection established with {websocket.remote_address[0]}.")
|
|
427
|
+
try:
|
|
428
|
+
async for message in websocket:
|
|
429
|
+
try:
|
|
430
|
+
data = json.loads(message)
|
|
431
|
+
|
|
432
|
+
event_name = data.get("eventName")
|
|
433
|
+
request_id = data.get("requestId")
|
|
434
|
+
|
|
435
|
+
if (
|
|
436
|
+
event_name == "Response"
|
|
437
|
+
and request_id
|
|
438
|
+
and request_id in self._pending_requests
|
|
439
|
+
):
|
|
440
|
+
future = self._pending_requests.pop(request_id)
|
|
441
|
+
if not future.done():
|
|
442
|
+
if data.get("success") is False:
|
|
443
|
+
msg = data.get("message", "Unknown Spicetify error")
|
|
444
|
+
future.set_exception(SpicetifyError(f"Request failed: {msg}"))
|
|
445
|
+
else:
|
|
446
|
+
future.set_result(data)
|
|
447
|
+
logger.debug(
|
|
448
|
+
"Received response for requestId: %s, Data: %s",
|
|
449
|
+
request_id,
|
|
450
|
+
data,
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
elif event_name:
|
|
454
|
+
logger.debug("Event received: %s: %s", event_name, data.get("payload"))
|
|
455
|
+
await self._dispatch_event(event_name, data.get("payload", {}))
|
|
456
|
+
|
|
457
|
+
else:
|
|
458
|
+
logger.debug("Event received: %s: %s", event_name, data.get("payload"))
|
|
459
|
+
except json.JSONDecodeError:
|
|
460
|
+
logger.error("JSON parsing error: %s", message)
|
|
461
|
+
finally:
|
|
462
|
+
self.websocket = None
|
|
463
|
+
self._connected_event.clear()
|
|
464
|
+
logger.info("Connection lost.")
|
|
465
|
+
|
|
466
|
+
# --- Playback Controls ---
|
|
467
|
+
|
|
468
|
+
async def play(self) -> None:
|
|
469
|
+
"""Send a command to start playback.
|
|
470
|
+
|
|
471
|
+
Raises:
|
|
472
|
+
NotConnectedError: If not connected to Spicetify.
|
|
473
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
474
|
+
"""
|
|
475
|
+
await self._send_command(PlayRequest())
|
|
476
|
+
|
|
477
|
+
async def pause(self) -> None:
|
|
478
|
+
"""Send a command to pause playback.
|
|
479
|
+
|
|
480
|
+
Raises:
|
|
481
|
+
NotConnectedError: If not connected to Spicetify.
|
|
482
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
483
|
+
"""
|
|
484
|
+
await self._send_command(PauseRequest())
|
|
485
|
+
|
|
486
|
+
async def next_song(self) -> None:
|
|
487
|
+
"""Send a command to play the next song.
|
|
488
|
+
|
|
489
|
+
Raises:
|
|
490
|
+
NotConnectedError: If not connected to Spicetify.
|
|
491
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
492
|
+
"""
|
|
493
|
+
await self._send_command(NextSongRequest())
|
|
494
|
+
|
|
495
|
+
async def previous_song(self, force: bool = False) -> None:
|
|
496
|
+
"""Send a command to play the previous song.
|
|
497
|
+
|
|
498
|
+
Notes:
|
|
499
|
+
If force is ``True``, the previous song will be played
|
|
500
|
+
regardless of the current playback position.
|
|
501
|
+
If force is ``False``, it could either restart the current
|
|
502
|
+
song or play the previous song based on the playback position.
|
|
503
|
+
|
|
504
|
+
Args:
|
|
505
|
+
force: If ``True``, ensures the previous song is played.
|
|
506
|
+
|
|
507
|
+
Raises:
|
|
508
|
+
NotConnectedError: If not connected to Spicetify.
|
|
509
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
510
|
+
"""
|
|
511
|
+
if force:
|
|
512
|
+
await self._send_command(ForcePreviousSongRequest())
|
|
513
|
+
else:
|
|
514
|
+
await self._send_command(PreviousSongRequest())
|
|
515
|
+
|
|
516
|
+
async def set_repeat(self, mode: RepeatMode) -> RepeatMode:
|
|
517
|
+
"""Set the repeat mode for playback.
|
|
518
|
+
|
|
519
|
+
Args:
|
|
520
|
+
mode: The repeat mode to set (off, context, track).
|
|
521
|
+
|
|
522
|
+
Returns:
|
|
523
|
+
The repeat mode that was set.
|
|
524
|
+
|
|
525
|
+
Raises:
|
|
526
|
+
NotConnectedError: If not connected to Spicetify.
|
|
527
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
528
|
+
"""
|
|
529
|
+
await self._send_command(SetRepeatRequest(mode=mode))
|
|
530
|
+
return mode
|
|
531
|
+
|
|
532
|
+
async def set_shuffle(self, state: bool) -> bool:
|
|
533
|
+
"""Enable or disable shuffle mode.
|
|
534
|
+
|
|
535
|
+
Args:
|
|
536
|
+
state: ``True`` to enable shuffle, ``False`` to disable.
|
|
537
|
+
|
|
538
|
+
Returns:
|
|
539
|
+
The shuffle state that was set.
|
|
540
|
+
|
|
541
|
+
Raises:
|
|
542
|
+
NotConnectedError: If not connected to Spicetify.
|
|
543
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
544
|
+
"""
|
|
545
|
+
await self._send_command(SetShuffleRequest(state=state))
|
|
546
|
+
return state
|
|
547
|
+
|
|
548
|
+
async def set_mute(self, state: bool) -> bool:
|
|
549
|
+
"""Enable or disable mute for playback.
|
|
550
|
+
|
|
551
|
+
Args:
|
|
552
|
+
state: ``True`` to mute, ``False`` to unmute.
|
|
553
|
+
|
|
554
|
+
Returns:
|
|
555
|
+
The mute state that was set.
|
|
556
|
+
|
|
557
|
+
Raises:
|
|
558
|
+
NotConnectedError: If not connected to Spicetify.
|
|
559
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
560
|
+
"""
|
|
561
|
+
await self._send_command(SetMuteRequest(state=state))
|
|
562
|
+
return state
|
|
563
|
+
|
|
564
|
+
async def toggle_play(self) -> None:
|
|
565
|
+
"""Send a command to toggle playback (play/pause).
|
|
566
|
+
|
|
567
|
+
Raises:
|
|
568
|
+
NotConnectedError: If not connected to Spicetify.
|
|
569
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
570
|
+
"""
|
|
571
|
+
await self._send_command(TogglePlayRequest())
|
|
572
|
+
|
|
573
|
+
async def set_volume(self, percent: float) -> float | int:
|
|
574
|
+
"""Set Spotify volume level.
|
|
575
|
+
|
|
576
|
+
Args:
|
|
577
|
+
percent: Volume level between 0 and 100.
|
|
578
|
+
|
|
579
|
+
Returns:
|
|
580
|
+
The volume level that was set.
|
|
581
|
+
|
|
582
|
+
Raises:
|
|
583
|
+
NotConnectedError: If not connected to Spicetify.
|
|
584
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
585
|
+
ValueError: If percent is not between 0 and 100.
|
|
586
|
+
"""
|
|
587
|
+
if not 0 <= percent <= 100:
|
|
588
|
+
raise ValueError("percent must be between 0 and 100.")
|
|
589
|
+
await self._send_command(SetVolumeRequest(level=(percent / 100)))
|
|
590
|
+
return percent
|
|
591
|
+
|
|
592
|
+
async def play_uri(self, uri: str) -> str:
|
|
593
|
+
"""Play a specific Spotify URI.
|
|
594
|
+
|
|
595
|
+
Args:
|
|
596
|
+
uri: Spotify URI or URL to play.
|
|
597
|
+
|
|
598
|
+
Returns:
|
|
599
|
+
The URI/URL that was played.
|
|
600
|
+
|
|
601
|
+
Raises:
|
|
602
|
+
NotConnectedError: If not connected to Spicetify.
|
|
603
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
604
|
+
"""
|
|
605
|
+
await self._send_command(PlayUriRequest(uri=uri))
|
|
606
|
+
return uri
|
|
607
|
+
|
|
608
|
+
async def play_url(self, url: str) -> str:
|
|
609
|
+
"""Alias for play_uri. Play a specific Spotify URL.
|
|
610
|
+
|
|
611
|
+
Args:
|
|
612
|
+
url: Spotify URL to play.
|
|
613
|
+
|
|
614
|
+
Returns:
|
|
615
|
+
The URL that was played.
|
|
616
|
+
|
|
617
|
+
Raises:
|
|
618
|
+
NotConnectedError: If not connected to Spicetify.
|
|
619
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
620
|
+
"""
|
|
621
|
+
await self.play_uri(uri=url)
|
|
622
|
+
return url
|
|
623
|
+
|
|
624
|
+
async def seek(self, position: float) -> int | float:
|
|
625
|
+
"""Seek to a specific position in the current track.
|
|
626
|
+
|
|
627
|
+
Args:
|
|
628
|
+
position: Position in milliseconds to seek to.
|
|
629
|
+
|
|
630
|
+
Returns:
|
|
631
|
+
The position that was sought to.
|
|
632
|
+
|
|
633
|
+
Raises:
|
|
634
|
+
NotConnectedError: If not connected to Spicetify.
|
|
635
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
636
|
+
ValueError: If position is negative.
|
|
637
|
+
"""
|
|
638
|
+
if not position >= 0:
|
|
639
|
+
raise ValueError("position must be greater than or equal to 0.")
|
|
640
|
+
await self._send_command(SeekRequest(position=position))
|
|
641
|
+
return position
|
|
642
|
+
|
|
643
|
+
# --- Playback State Queries ---
|
|
644
|
+
|
|
645
|
+
async def get_player_state(self) -> PlayerState:
|
|
646
|
+
"""Get the current playback state from Spicetify.
|
|
647
|
+
|
|
648
|
+
Returns:
|
|
649
|
+
A ``PlayerState`` object containing the current playback state.
|
|
650
|
+
|
|
651
|
+
Raises:
|
|
652
|
+
NotConnectedError: If not connected to Spicetify.
|
|
653
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
654
|
+
"""
|
|
655
|
+
response = await self._send_command(GetPlayerStateRequest())
|
|
656
|
+
return PlayerState.from_payload(response.get("payload", {}).get("playerData", {}))
|
|
657
|
+
|
|
658
|
+
async def get_is_playing(self) -> bool:
|
|
659
|
+
"""Get the current play/pause state from Spicetify.
|
|
660
|
+
|
|
661
|
+
Returns:
|
|
662
|
+
``True`` if currently playing, ``False`` if paused.
|
|
663
|
+
|
|
664
|
+
Raises:
|
|
665
|
+
NotConnectedError: If not connected to Spicetify.
|
|
666
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
667
|
+
"""
|
|
668
|
+
response = await self._send_command(GetPlayPauseRequest())
|
|
669
|
+
return response.get("payload", {}).get("isPlaying", False)
|
|
670
|
+
|
|
671
|
+
async def get_volume(self) -> float | int:
|
|
672
|
+
"""Get the current volume level from Spicetify.
|
|
673
|
+
|
|
674
|
+
Returns:
|
|
675
|
+
The current volume level between ``0`` and ``100``.
|
|
676
|
+
|
|
677
|
+
Raises:
|
|
678
|
+
NotConnectedError: If not connected to Spicetify.
|
|
679
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
680
|
+
"""
|
|
681
|
+
response = await self._send_command(GetVolumeRequest())
|
|
682
|
+
return response.get("payload", {}).get("level", 0) * 100
|
|
683
|
+
|
|
684
|
+
async def get_current_track(self) -> TrackInfo:
|
|
685
|
+
"""Get the current track information from Spicetify.
|
|
686
|
+
|
|
687
|
+
Returns:
|
|
688
|
+
A ``TrackInfo`` object containing details about the current track.
|
|
689
|
+
|
|
690
|
+
Raises:
|
|
691
|
+
NotConnectedError: If not connected to Spicetify.
|
|
692
|
+
RequestTimeoutError: If Spicetify doesn't respond in time.
|
|
693
|
+
"""
|
|
694
|
+
response = await self._send_command(GetCurrentTrackRequest())
|
|
695
|
+
return TrackInfo.from_payload(response.get("payload", {}))
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: spicetify-websocket
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: An asynchronous Python wrapper and WebSocket server for controlling the Spotify desktop client via Spicetify and the spicetify-connect-api extension.
|
|
5
|
+
Author-email: Tobias Schmitt <support@tobfd.de>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Github, https://github.com/tobfd/spicetify-websocket
|
|
8
|
+
Project-URL: Documentation, https://spicetify-websocket.readthedocs.io
|
|
9
|
+
Project-URL: Changelog, https://github.com/tobfd/spicetify-websocket/releases
|
|
10
|
+
Keywords: spicetify,websocket,local,spotify
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Operating System :: OS Independent
|
|
20
|
+
Classifier: Topic :: Utilities
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: pydantic<3.0,>=2.13.4
|
|
27
|
+
Requires-Dist: websockets<17.0,>=16.1.1
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
[](https://github.com/tobfd/spicetify-websocket)
|
|
31
|
+
|
|
32
|
+
[](https://pypi.org/project/spicetify-websocket/)
|
|
33
|
+
[](https://github.com/tobfd/spicetify-websocket/blob/master/LICENSE)
|
|
34
|
+
[](https://www.python.org/)
|
|
35
|
+
[](https://spicetify-websocket.readthedocs.io/)
|
|
36
|
+
|
|
37
|
+
An asynchronous Python wrapper and WebSocket server for controlling the Spotify desktop client via [Spicetify](https://spicetify.app/) and the [spicetify-connect-api]([https://github.com/tobfd/spicetify-connect-api) extension.
|
|
38
|
+
|
|
39
|
+
## ✨ Features
|
|
40
|
+
|
|
41
|
+
- ⚡ **Real-time Push Events:** Instant updates for song changes, volume, seeking, and playback state.
|
|
42
|
+
- 🎮 **Full Playback Control:** Play, pause, skip, seek, volume, repeat, and shuffle.
|
|
43
|
+
- 🛠️ **Convenience Decorators:** Easy event listening with syntax like `@server.on_song_changed`.
|
|
44
|
+
- 🏷️ **Fully Typed:** Pydantic V2 models (`TrackInfo`, `PlayerState`, `RepeatMode`).
|
|
45
|
+
- 🔄 **Async & Non-blocking:** Built on `asyncio` and `websockets` for maximum performance.
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## ⚙️ Installation
|
|
49
|
+
|
|
50
|
+
Python 3.10 or higher is required.
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install spicetify-websocket
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## 📋 Prerequisites
|
|
59
|
+
|
|
60
|
+
To use this library, ensure you have:
|
|
61
|
+
1. **Spotify Desktop Client** installed.
|
|
62
|
+
2. **[Spicetify CLI](https://spicetify.app/)** installed and configured.
|
|
63
|
+
3. The [spicetify-connect-api]([https://github.com/tobfd/spicetify-connect-api) extension enabled in Spicetify.
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## 🚀 Example Usage
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import asyncio
|
|
71
|
+
from spicetify import RepeatMode, SpotifyServer, TrackInfo
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
async def main():
|
|
75
|
+
async with SpotifyServer() as server:
|
|
76
|
+
# Wait until Spicetify client connects
|
|
77
|
+
await server.wait_for_connection()
|
|
78
|
+
|
|
79
|
+
# Playback Controls
|
|
80
|
+
await server.play_url(url="https://open.spotify.com/intl-de/track/55pBIZO1cqoldeqpp5WR7H?si=57cde33a1bd34ac9")
|
|
81
|
+
await server.set_volume(percent=75)
|
|
82
|
+
await server.set_repeat(mode=RepeatMode.TRACK)
|
|
83
|
+
|
|
84
|
+
# Playback State
|
|
85
|
+
current_track: TrackInfo = await server.get_current_track()
|
|
86
|
+
print(current_track)
|
|
87
|
+
|
|
88
|
+
# Events
|
|
89
|
+
@server.on_song_changed
|
|
90
|
+
def callback(track: TrackInfo):
|
|
91
|
+
print("New song is playing:", track.title)
|
|
92
|
+
print("Artist/s:", ", ".join(artist.name for artist in track.artists))
|
|
93
|
+
|
|
94
|
+
# Keep the server running to receive events
|
|
95
|
+
await asyncio.Event().wait()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
if __name__ == "__main__":
|
|
99
|
+
asyncio.run(main())
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 📻 Events Reference
|
|
105
|
+
|
|
106
|
+
| Event Name | Convenience Decorator | Callback Payload Type | Description |
|
|
107
|
+
| :--- | :--- | :--- | :--- |
|
|
108
|
+
| `InitialState` | `@server.on_initial_state` | `PlayerState` | Fired immediately when Spicetify connects. |
|
|
109
|
+
| `SongChanged` | `@server.on_song_changed` | `TrackInfo` | Fired when a new track starts playing. |
|
|
110
|
+
| `PlayPauseChanged` | `@server.on_play_pause_changed` | `PlayerState` | Fired when playback state changes. |
|
|
111
|
+
| `VolumeChanged` | `@server.on_volume_changed` | `float` (0–100%) | Fired when volume level changes. |
|
|
112
|
+
| `RepeatChanged` | `@server.on_repeat_changed` | `RepeatMode` | Fired when repeat mode changes (OFF, CONTEXT, TRACK). |
|
|
113
|
+
| `ShuffleChanged` | `@server.on_shuffle_changed` | `bool` | Fired when shuffle mode is toggled. |
|
|
114
|
+
| `SeekChanged` | `@server.on_seek_changed` | `int` (ms) | Fired when timeline position is manually changed. |
|
|
115
|
+
---
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
spicetify/__init__.py,sha256=J5RW22mxf1ukLB8Mxu5s4M_k6JoJXEPDtfbfSF8836E,477
|
|
2
|
+
spicetify/exceptions.py,sha256=4OW8SLQFujRY3ZFkc8PBlsfmgaVYMra95sZdgTK8ek8,850
|
|
3
|
+
spicetify/models.py,sha256=Ww71uwV6NbeIvYAFj8Fs66vsMhJK5l9XWix-mHW0t1c,13788
|
|
4
|
+
spicetify/server.py,sha256=0TD_nptLSCIb0fNtlzqBAMwp8L9eOXhD6s4FU4VQeuo,24100
|
|
5
|
+
spicetify_websocket-0.1.0.dist-info/licenses/LICENSE,sha256=zht6N0Z-g7To_wE77T80ci3UfXA0LA-PofRub-k1-ok,1071
|
|
6
|
+
spicetify_websocket-0.1.0.dist-info/METADATA,sha256=s6fk9E0HMHNxMWoP9jzo3mSALyCgHddbbcT1xOo8p7g,5320
|
|
7
|
+
spicetify_websocket-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
8
|
+
spicetify_websocket-0.1.0.dist-info/top_level.txt,sha256=-lJY1CHEqqFMWhl2Zl_ih6foLtRJ4ZQkmPMRFLsNqE0,10
|
|
9
|
+
spicetify_websocket-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tobias Schmitt
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
spicetify
|