onzr 0.1.0__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.
onzr-0.1.0/LICENSE ADDED
@@ -0,0 +1,10 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-present Julien Maupetit <julien@maupetit.net>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10
+
onzr-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.3
2
+ Name: onzr
3
+ Version: 0.1.0
4
+ Summary: The one-hour-late Deezer CLI.
5
+ License: MIT
6
+ Author: Julien Maupetit
7
+ Author-email: julien@maupetit.net
8
+ Requires-Python: >3.9,<4.0.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Dist: deezer-py (>=1.3.7,<2.0.0)
16
+ Requires-Dist: dynaconf (>=3.2.10,<4.0.0)
17
+ Requires-Dist: pycryptodomex (>=3.21.0,<4.0.0)
18
+ Requires-Dist: pynput (>=1.8.1,<2.0.0)
19
+ Requires-Dist: python-vlc (>=3.0.21203,<4.0.0)
20
+ Requires-Dist: typer (>=0.15.2,<0.16.0)
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Onzr
24
+
25
+ The one-hour-late Deezer 💜 CLI.
26
+
27
+ > :warning: This project is a work in progress. It works in its core parts, but
28
+ > will not meet standard requirements for a decent player.
29
+
30
+ ## Requirements
31
+
32
+ - [VLC](https://www.videolan.org/vlc/index.en_GB.html): we use VLC bindings to
33
+ play tracks, so this is a strict requirement.
34
+
35
+ ## Quick start guide (for developers)
36
+
37
+ Install dependencies in a working environment:
38
+
39
+ ```sh
40
+ make bootstrap
41
+ ```
42
+
43
+ Run linters:
44
+
45
+ ```sh
46
+ make lint
47
+ ```
48
+
49
+ Run tests:
50
+
51
+ ```sh
52
+ make test
53
+ ```
54
+
55
+ ## License
56
+
57
+ This work is released under the MIT License.
58
+
onzr-0.1.0/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # Onzr
2
+
3
+ The one-hour-late Deezer 💜 CLI.
4
+
5
+ > :warning: This project is a work in progress. It works in its core parts, but
6
+ > will not meet standard requirements for a decent player.
7
+
8
+ ## Requirements
9
+
10
+ - [VLC](https://www.videolan.org/vlc/index.en_GB.html): we use VLC bindings to
11
+ play tracks, so this is a strict requirement.
12
+
13
+ ## Quick start guide (for developers)
14
+
15
+ Install dependencies in a working environment:
16
+
17
+ ```sh
18
+ make bootstrap
19
+ ```
20
+
21
+ Run linters:
22
+
23
+ ```sh
24
+ make lint
25
+ ```
26
+
27
+ Run tests:
28
+
29
+ ```sh
30
+ make test
31
+ ```
32
+
33
+ ## License
34
+
35
+ This work is released under the MIT License.
@@ -0,0 +1,72 @@
1
+ [tool.poetry]
2
+ name = "onzr"
3
+ version = "0.1.0"
4
+ description = "The one-hour-late Deezer CLI."
5
+ authors = ["Julien Maupetit <julien@maupetit.net>"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+
9
+ [tool.poetry.dependencies]
10
+ deezer-py = "^1.3.7"
11
+ dynaconf = "^3.2.10"
12
+ pycryptodomex = "^3.21.0"
13
+ pynput = "^1.8.1"
14
+ python = ">3.9,<4.0.0"
15
+ python-vlc = "^3.0.21203"
16
+ typer = "^0.15.2"
17
+
18
+ [tool.poetry.group.dev.dependencies]
19
+ black = "^25.1.0"
20
+ mypy = "^1.15.0"
21
+ ruff = "^0.9.7"
22
+ pytest = "^8.3.5"
23
+ types-requests = "^2.32.0.20250306"
24
+ types-pynput = "^1.8.1.20250318"
25
+
26
+ [tool.poetry.scripts]
27
+ onzr = "onzr.cli:cli"
28
+
29
+ [tool.ruff]
30
+ target-version = "py310"
31
+ # Exclude a variety of commonly ignored directories.
32
+ exclude = []
33
+
34
+ [tool.ruff.lint]
35
+ select = [
36
+ "B", # flake8-bugbear
37
+ "C4", # flake8-comprehensions
38
+ "D", # pydocstyle
39
+ "E", # pycodestyle error
40
+ "F", # Pyflakes
41
+ "I", # Isort
42
+ "ISC", # flake8-implicit-str-concat
43
+ "PLC", # Pylint Convention
44
+ "PLE", # Pylint Error
45
+ "PLR", # Pylint Refactor
46
+ "PLW", # Pylint Warning
47
+ "RUF100", # Ruff unused-noqa
48
+ "S", # flake8-bandit
49
+ "T20", # flake8-print
50
+ "W", # pycodestyle warning
51
+ ]
52
+
53
+ [tool.ruff.lint.per-file-ignores]
54
+ "tests/*" = [
55
+ "S101", # use of assert
56
+ ]
57
+
58
+ [tool.ruff.lint.pydocstyle]
59
+ # Use Google-style docstrings.
60
+ convention = "google"
61
+
62
+ [tool.mypy]
63
+ files = "./**/*.py"
64
+ exclude = []
65
+
66
+ [[tool.mypy.overrides]]
67
+ module = ["deezer.*", "dynaconf.*", "vlc.*"]
68
+ ignore_missing_imports = true
69
+
70
+ [build-system]
71
+ requires = ["poetry-core"]
72
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1 @@
1
+ # ARL=
@@ -0,0 +1 @@
1
+ """Onzr."""
@@ -0,0 +1,6 @@
1
+ """Onzr: module script."""
2
+
3
+ from .cli import cli
4
+
5
+ if __name__ == "__main__":
6
+ cli()
@@ -0,0 +1,204 @@
1
+ """Onzr: command line interface."""
2
+
3
+ import logging
4
+ from random import shuffle
5
+ from threading import Thread
6
+ from typing import List
7
+
8
+ import click
9
+ import typer
10
+ from pynput import keyboard
11
+ from rich.console import Console
12
+ from rich.logging import RichHandler
13
+ from rich.table import Table
14
+
15
+ from .core import Onzr
16
+ from .deezer import AlbumShort, ArtistShort, Collection, StreamQuality, TrackShort
17
+
18
+ FORMAT = "%(message)s"
19
+ logging_console = Console(stderr=True)
20
+ logging.basicConfig(
21
+ level=logging.DEBUG,
22
+ format=FORMAT,
23
+ datefmt="[%X]",
24
+ handlers=[RichHandler(console=logging_console)],
25
+ )
26
+
27
+ cli = typer.Typer(name="onzr", no_args_is_help=True, pretty_exceptions_short=True)
28
+ console = Console()
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def start(fast: bool = False, quiet: bool = False) -> Onzr:
33
+ """Start onzr."""
34
+ if not quiet:
35
+ console.print("🚀 login in to Deezer…", style="cyan")
36
+ return Onzr(fast=fast)
37
+
38
+
39
+ def print_collection_ids(collection: Collection):
40
+ """Print a collection as ids."""
41
+ for item in collection:
42
+ console.print(item.id)
43
+
44
+
45
+ def print_collection_table(collection: Collection, title="Collection"):
46
+ """Print a collection as a table."""
47
+ table = Table(title=title)
48
+
49
+ sample = collection[0]
50
+ show_artist = (
51
+ True
52
+ if isinstance(sample, TrackShort)
53
+ or isinstance(sample, AlbumShort)
54
+ or isinstance(sample, ArtistShort)
55
+ else False
56
+ )
57
+ show_album = (
58
+ True
59
+ if isinstance(sample, TrackShort) or isinstance(sample, AlbumShort)
60
+ else False
61
+ )
62
+ show_track = True if isinstance(sample, TrackShort) else False
63
+
64
+ if show_track:
65
+ table.add_column("ID", justify="right")
66
+ table.add_column("Track", style="#9B6BDF")
67
+ if show_album:
68
+ table.add_column("ID", justify="right")
69
+ table.add_column("Album", style="#E356A7")
70
+ if show_artist:
71
+ table.add_column("ID", justify="right")
72
+ table.add_column("Artist", style="#75D7EC")
73
+
74
+ for item in collection:
75
+ table.add_row(*item.to_list())
76
+
77
+ console.print(table)
78
+
79
+
80
+ @cli.command()
81
+ def search( # noqa: PLR0913
82
+ artist: str = "",
83
+ album: str = "",
84
+ track: str = "",
85
+ strict: bool = False,
86
+ quiet: bool = False,
87
+ ids: bool = False,
88
+ ):
89
+ """Search track, artist and/or album."""
90
+ if ids:
91
+ quiet = True
92
+ onzr = start(fast=True, quiet=quiet)
93
+ if not quiet:
94
+ console.print("🔍 start searching…")
95
+
96
+ results = onzr.deezer.search(artist, album, track, strict)
97
+
98
+ if not results:
99
+ console.print("No match found.")
100
+ typer.Exit(code=1)
101
+
102
+ if ids:
103
+ print_collection_ids(results)
104
+ return
105
+
106
+ print_collection_table(results, title="Search results")
107
+
108
+
109
+ @cli.command()
110
+ def artist( # noqa: PLR0913
111
+ artist_id: str,
112
+ top: bool = True,
113
+ radio: bool = False,
114
+ limit: int = 10,
115
+ quiet: bool = True,
116
+ ids: bool = False,
117
+ ):
118
+ """Get artist popular track ids."""
119
+ if not top and not radio:
120
+ console.print("You should choose either top titles or artist radio.")
121
+ raise typer.Exit(code=2)
122
+
123
+ if ids:
124
+ quiet = True
125
+
126
+ if artist_id == "-":
127
+ logger.debug("Reading artist id from stdin…")
128
+ artist_id = click.get_text_stream("stdin").read().strip()
129
+ logger.debug(f"{artist_id=}")
130
+
131
+ onzr = start(fast=True, quiet=quiet)
132
+ tracks = onzr.deezer.artist(artist_id, radio=radio, top=top, limit=limit)
133
+
134
+ if ids:
135
+ print_collection_ids(tracks)
136
+ return
137
+
138
+ print_collection_table(tracks, title="Artist tracks")
139
+
140
+
141
+ @cli.command()
142
+ def mix(
143
+ artist: list[str],
144
+ deep: bool = False,
145
+ limit: int = 10,
146
+ quiet: bool = True,
147
+ ids: bool = False,
148
+ ):
149
+ """Create a playlist from multiple artists."""
150
+ if ids:
151
+ quiet = True
152
+
153
+ onzr = start(fast=True, quiet=quiet)
154
+ tracks = []
155
+
156
+ if not quiet:
157
+ console.print("🍪 cooking the mix…")
158
+
159
+ for artist_ in artist:
160
+ result = onzr.deezer.search(artist_, strict=True)
161
+ # We expect the search engine to be relevant 🤞
162
+ artist_id = result[0].id
163
+ tracks += onzr.deezer.artist(artist_id, radio=deep, top=True, limit=limit)
164
+ shuffle(tracks)
165
+
166
+ if ids:
167
+ print_collection_ids(tracks)
168
+ return
169
+
170
+ print_collection_table(tracks, title="Onzr Mix tracks")
171
+
172
+
173
+ @cli.command()
174
+ def play(
175
+ track_ids: List[str],
176
+ quality: StreamQuality = StreamQuality.MP3_128,
177
+ shuffle: bool = False,
178
+ ):
179
+ """Play one (or more) tracks."""
180
+ onzr = start()
181
+ console.print("🚀 starting the player…")
182
+ if track_ids == ["-"]:
183
+ logger.debug("Reading track ids from stdin…")
184
+ track_ids = click.get_text_stream("stdin").read().split()
185
+ logger.debug(f"{track_ids=}")
186
+ onzr.add(track_ids, quality)
187
+ if shuffle:
188
+ onzr.shuffle()
189
+
190
+ # Start playing in a new thread
191
+ thread = Thread(target=onzr.play)
192
+ thread.start()
193
+
194
+ # Controls
195
+ def on_press(key: keyboard.Key):
196
+ """Player control actions."""
197
+ match key:
198
+ case keyboard.Key.media_play_pause:
199
+ onzr.pause()
200
+
201
+ with keyboard.Listener(on_press=on_press) as listener: # type: ignore[arg-type]
202
+ listener.join()
203
+
204
+ typer.Exit()
@@ -0,0 +1,8 @@
1
+ """Dzr configuration."""
2
+
3
+ from dynaconf import Dynaconf
4
+
5
+ settings = Dynaconf(
6
+ envvar_prefix="ONZR",
7
+ settings_files=["settings.toml", ".secrets.toml"],
8
+ )
@@ -0,0 +1,135 @@
1
+ """Onzr: core module."""
2
+
3
+ import logging
4
+ import random
5
+ import socket
6
+ import struct
7
+ from enum import IntEnum
8
+ from socket import SocketType
9
+ from typing import List
10
+
11
+ from .deezer import DeezerClient, StreamQuality, Track
12
+ from .player import Player
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class Queue:
18
+ """Onzr playing queue."""
19
+
20
+ def __init__(self) -> None:
21
+ """Instantiate the tracks queue."""
22
+ self.current: Track | None = None
23
+ self.tracks: List[Track] = []
24
+
25
+ def __len__(self):
26
+ """Get queue length."""
27
+ return len(self.tracks)
28
+
29
+ @property
30
+ def is_empty(self):
31
+ """Check if tracks are queued."""
32
+ return len(self) == 0 and self.current is None
33
+
34
+ def add(self, track: Track | None = None, tracks: List[Track] | None = None):
35
+ """Add one or more tracks to queue."""
36
+ if track is None and tracks is None:
37
+ raise TypeError("Argument missing, you should either add a track or tracks")
38
+ self.tracks.extend(tracks or [track]) # type: ignore[list-item]
39
+
40
+ def shuffle(self):
41
+ """Shuffle current track list."""
42
+ random.shuffle(self.tracks)
43
+
44
+ def next(self):
45
+ """Set next track as the current."""
46
+ del self.current
47
+ if not len(self):
48
+ self.current = None
49
+ return
50
+ self.current = self.tracks.pop(0)
51
+
52
+
53
+ class OnzrStatus(IntEnum):
54
+ """Onzr player status."""
55
+
56
+ IDLE = 1
57
+ PLAYING = 2
58
+ PAUSED = 3
59
+ STOPPED = 4
60
+
61
+
62
+ class Onzr:
63
+ """Onzr core class."""
64
+
65
+ def __init__(self, fast: bool = False) -> None:
66
+ """Initialize all the things.
67
+
68
+ fast (bool): activate Deezer fast login
69
+ """
70
+ logger.debug("Instantiating Onzr…")
71
+
72
+ self.deezer: DeezerClient = DeezerClient(fast=fast)
73
+ self.socket: SocketType = self.configure_socket()
74
+ self.player: Player = Player(self.socket)
75
+ self._queue: Queue = Queue()
76
+ self.status: OnzrStatus = OnzrStatus.IDLE
77
+
78
+ def configure_socket(self):
79
+ """Open and configure the casting socket."""
80
+ logger.debug("Setting socket…")
81
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
82
+
83
+ # Configure TTL
84
+ ttl = struct.pack("b", 1)
85
+ sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
86
+ logger.debug(f"Socket: {sock}")
87
+ return sock
88
+
89
+ def add(self, track_ids: List[str], quality: StreamQuality = StreamQuality.MP3_320):
90
+ """Little helper to queue tracks."""
91
+ logger.info("➕ Adding new tracks to queue…")
92
+ tracks = [Track(self.deezer, track_id, quality) for track_id in track_ids]
93
+ for track in tracks:
94
+ logger.info(f"{track.full_title}")
95
+ self._queue.add(tracks=tracks)
96
+ logger.info(f"✅ {len(tracks)} tracks queued")
97
+
98
+ def shuffle(self):
99
+ """Shuffle tracks queue."""
100
+ logger.info("🔀 Shuffling tracks queue…")
101
+ self._queue.shuffle()
102
+ for track in self._queue.tracks:
103
+ logger.info(f"{track.full_title}")
104
+
105
+ def play(self):
106
+ """Little helper to start playing the queue."""
107
+ # No active track, try to queue the next one in line
108
+ if self._queue.current is None:
109
+ self._queue.next()
110
+
111
+ # There is no track left in queue
112
+ if self._queue.is_empty:
113
+ return
114
+
115
+ # Play current track
116
+ self.status = OnzrStatus.PLAYING
117
+ self._queue.current.paused = False
118
+ self.player.play(self._queue.current)
119
+ self._queue.next()
120
+
121
+ return self.play()
122
+
123
+ def pause(self):
124
+ """Pause current track playing."""
125
+ logger.info("⏯ Toggling pause…")
126
+ logger.debug(f"Onzr Status? {self.status.name}")
127
+ if self._queue.current is None:
128
+ return
129
+
130
+ if self.status == OnzrStatus.PLAYING:
131
+ self.status = OnzrStatus.PAUSED
132
+ self._queue.current.paused = True
133
+ elif self.status == OnzrStatus.PAUSED:
134
+ self.status = OnzrStatus.PLAYING
135
+ self._queue.current.paused = False
@@ -0,0 +1,405 @@
1
+ """Onzr: deezer client."""
2
+
3
+ import functools
4
+ import hashlib
5
+ import logging
6
+ from dataclasses import asdict, dataclass
7
+ from enum import IntEnum, StrEnum
8
+ from threading import Thread
9
+ from time import sleep
10
+ from typing import Generator, List, Protocol
11
+
12
+ import deezer
13
+ import requests
14
+ from Cryptodome.Cipher import Blowfish
15
+
16
+ from .config import settings
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class StreamQuality(StrEnum):
22
+ """Track stream quality."""
23
+
24
+ MP3_128 = "MP3_128"
25
+ MP3_320 = "MP3_320"
26
+ FLAC = "FLAC"
27
+
28
+
29
+ @dataclass
30
+ class IsDataclassProtocol(Protocol):
31
+ """A protocol to type check dataclass mixins."""
32
+
33
+
34
+ class ToListMixin(IsDataclassProtocol):
35
+ """A dataclass mixin that converts all fields values to a list."""
36
+
37
+ def _dataclass_to_list(self, target=None) -> List[str | List]:
38
+ """Convert all field values to a list."""
39
+ if target is None:
40
+ target = asdict(self)
41
+ return [
42
+ v if not isinstance(v, dict) else self._dataclass_to_list(v)
43
+ for v in target.values()
44
+ ]
45
+
46
+ def to_list(self, target: List[str | List] | None = None) -> List[str]:
47
+ """Convert nested dataclasses to values list."""
48
+ if target is None:
49
+ target = self._dataclass_to_list()
50
+ out = []
51
+ for i in target:
52
+ if isinstance(i, list):
53
+ out += self.to_list(i)
54
+ else:
55
+ out.append(i)
56
+ return out
57
+
58
+
59
+ @dataclass
60
+ class ArtistShort(ToListMixin):
61
+ """A small model to represent an artist."""
62
+
63
+ id: str
64
+ name: str
65
+
66
+
67
+ @dataclass
68
+ class AlbumShort(ToListMixin):
69
+ """A small model to represent an artist."""
70
+
71
+ id: str
72
+ name: str
73
+ artist: ArtistShort
74
+
75
+
76
+ @dataclass
77
+ class TrackShort(ToListMixin):
78
+ """A small model to represent an artist."""
79
+
80
+ id: str
81
+ title: str
82
+ album: AlbumShort
83
+
84
+
85
+ Collection = List[ArtistShort] | list[AlbumShort] | List[TrackShort]
86
+
87
+
88
+ class DeezerClient(deezer.Deezer):
89
+ """A wrapper for the Deezer API client."""
90
+
91
+ def __init__(
92
+ self,
93
+ arl: str | None = None,
94
+ quality: StreamQuality | None = None,
95
+ fast: bool = False,
96
+ ) -> None:
97
+ """Instantiate the Deezer API client.
98
+
99
+ Fast login is useful to quicky access some API endpoints such as "search" but
100
+ won't work if you need to stream tracks.
101
+ """
102
+ super().__init__()
103
+
104
+ self.arl = arl or settings.arl
105
+ self.quality = quality or settings.quality
106
+ if fast:
107
+ self._fast_login()
108
+ else:
109
+ self._login()
110
+
111
+ def _login(self):
112
+ """Login to deezer API."""
113
+ logger.debug("Login in to deezer using defined ARL…")
114
+ self.login_via_arl(self.arl)
115
+
116
+ def _fast_login(self):
117
+ """Fasting login using ARL cookie."""
118
+ cookie_obj = requests.cookies.create_cookie(
119
+ domain=".deezer.com",
120
+ name="arl",
121
+ value=self.arl,
122
+ path="/",
123
+ rest={"HttpOnly": True},
124
+ )
125
+ self.session.cookies.set_cookie(cookie_obj)
126
+ self.logged_in = True
127
+
128
+ @staticmethod
129
+ def _to_tracks(data) -> Generator[TrackShort, None, None]:
130
+ """API results to TrackShort."""
131
+ for track in data:
132
+ yield TrackShort(
133
+ id=str(track.get("id")),
134
+ title=track.get("title"),
135
+ album=AlbumShort(
136
+ id=str(track.get("album").get("id")),
137
+ name=track.get("album").get("title"),
138
+ artist=ArtistShort(
139
+ id=str(track.get("artist").get("id")),
140
+ name=track.get("artist").get("name"),
141
+ ),
142
+ ),
143
+ )
144
+
145
+ def artist(
146
+ self, artist_id: str, radio: bool = False, top: bool = True, limit: int = 10
147
+ ) -> List[TrackShort]:
148
+ """Get artist tracks."""
149
+ if radio:
150
+ response = self.api.get_artist_radio(artist_id, limit=limit)
151
+ elif top:
152
+ response = self.api.get_artist_top(artist_id, limit=limit)
153
+ else:
154
+ raise ValueError("Either radio or top should be True to get artist tracks")
155
+
156
+ return list(self._to_tracks(response["data"]))
157
+
158
+ def search(
159
+ self,
160
+ artist: str = "",
161
+ album: str = "",
162
+ track: str = "",
163
+ strict: bool = False,
164
+ ) -> Collection:
165
+ """Mixed custom search."""
166
+ results: Collection = []
167
+
168
+ if len(list(filter(None, (artist, album, track)))) > 1:
169
+ response = self.api.advanced_search(
170
+ artist=artist, album=album, track=track, strict=strict
171
+ )
172
+ results = list(self._to_tracks(response["data"]))
173
+ elif artist:
174
+ response = self.api.search_artist(artist)
175
+ results = [
176
+ ArtistShort(
177
+ id=str(a.get("id")),
178
+ name=a.get("name"),
179
+ )
180
+ for a in response["data"]
181
+ ]
182
+ elif album:
183
+ response = self.api.search_album(album)
184
+ results = [
185
+ AlbumShort(
186
+ id=str(a.get("id")),
187
+ name=a.get("title"),
188
+ artist=ArtistShort(
189
+ id=str(a.get("artist").get("id")),
190
+ name=str(a.get("artist").get("name")),
191
+ ),
192
+ )
193
+ for a in response["data"]
194
+ ]
195
+ elif track:
196
+ response = self.api.search_track(track)
197
+ results = list(self._to_tracks(response["data"]))
198
+
199
+ return results
200
+
201
+
202
+ class TrackStatus(IntEnum):
203
+ """Track statuses."""
204
+
205
+ IDLE = 1
206
+ FETCHING = 2
207
+ PLAYABLE = 3
208
+ FETCHED = 4
209
+
210
+
211
+ class Track:
212
+ """A Deezer track."""
213
+
214
+ def __init__(
215
+ self,
216
+ client: DeezerClient,
217
+ track_id: str,
218
+ quality: StreamQuality | None = None,
219
+ buffer: float = 0.5, # 500ms
220
+ ) -> None:
221
+ """Instantiate a new track."""
222
+ self.deezer = client
223
+ self.track_id = track_id
224
+ self.session = requests.Session()
225
+ self.quality = quality or self.deezer.quality
226
+ self.track_info: dict = self._get_track_info()
227
+ self.url: str = self._get_url()
228
+ self.key: bytes = self._generate_blowfish_key()
229
+ self.status: TrackStatus = TrackStatus.IDLE
230
+ # Content and related memory view will be allocated later (right before fetching
231
+ # the track to decrease memory footprint while adding tracks to queue).
232
+ self.content: bytearray = bytearray()
233
+ self._content_mv: memoryview = memoryview(self.content)
234
+ self.fetched: int = 0
235
+ self.streamed: int = 0
236
+ self.paused: bool = False
237
+ self.bitrate = self.filesize / self.duration
238
+ self.buffer_size: int = int(self.bitrate * buffer)
239
+
240
+ def _get_track_info(self) -> dict:
241
+ """Get track info."""
242
+ track_info = self.deezer.gw.get_track(self.track_id)
243
+ logger.debug("Track info: %s", track_info)
244
+ return track_info
245
+
246
+ def _get_url(self) -> str:
247
+ """Get URL of the track to stream."""
248
+ logger.debug(f"Getting track url with quality {self.quality}…")
249
+ url = self.deezer.get_track_url(self.token, self.quality.value)
250
+ logger.debug(f"Track url: {url}")
251
+ return url
252
+
253
+ def _allocate_content(self) -> None:
254
+ """Allocate memory where we will read/write track bytes."""
255
+ self.content = bytearray(self.filesize)
256
+ self._content_mv = memoryview(self.content)
257
+
258
+ def _generate_blowfish_key(self) -> bytes:
259
+ """Generate the blowfish key for Deezer downloads.
260
+
261
+ Taken from: https://github.com/nathom/streamrip/
262
+ """
263
+ md5_hash = hashlib.md5(self.track_id.encode()).hexdigest() # noqa: S324
264
+ # good luck :)
265
+ return "".join(
266
+ chr(functools.reduce(lambda x, y: x ^ y, map(ord, t)))
267
+ for t in zip(
268
+ md5_hash[:16],
269
+ md5_hash[16:],
270
+ settings.DEEZER_BLOWFISH_SECRET,
271
+ strict=False,
272
+ )
273
+ ).encode()
274
+
275
+ def _decrypt(self, chunk):
276
+ """Decrypt blowfish encrypted chunk."""
277
+ return Blowfish.new( # noqa: S304
278
+ self.key,
279
+ Blowfish.MODE_CBC,
280
+ b"\x00\x01\x02\x03\x04\x05\x06\x07",
281
+ ).decrypt(chunk)
282
+
283
+ @property
284
+ def token(self) -> str:
285
+ """Get track token."""
286
+ return self.track_info["TRACK_TOKEN"]
287
+
288
+ @property
289
+ def duration(self) -> int:
290
+ """Get track duration (in seconds)."""
291
+ return int(self.track_info["DURATION"])
292
+
293
+ @property
294
+ def filesize(self) -> int:
295
+ """Get file size (in bits)."""
296
+ return int(self.track_info[f"FILESIZE_{self.quality}"])
297
+
298
+ @property
299
+ def artist(self) -> str:
300
+ """Get track artist."""
301
+ return self.track_info["ART_NAME"]
302
+
303
+ @property
304
+ def title(self) -> str:
305
+ """Get track title."""
306
+ return self.track_info["SNG_TITLE"]
307
+
308
+ @property
309
+ def album(self) -> str:
310
+ """Get track album."""
311
+ return self.track_info["ALB_TITLE"]
312
+
313
+ @property
314
+ def full_title(self) -> str:
315
+ """Get track full title (artist/title/album)."""
316
+ return f"{self.artist} - {self.title} [{self.album}]"
317
+
318
+ def fetch(self):
319
+ """Fetch track in-memory.
320
+
321
+ buffer_size (int): the buffer size (defaults to 5 seconds for a 128kbs file)
322
+ """
323
+ logger.debug(f"Start fetching track with {self.buffer_size=}")
324
+ chunk_sep = 2048
325
+ chunk_size = 3 * chunk_sep
326
+ self.fetched = 0
327
+ self.status = TrackStatus.IDLE
328
+ self._allocate_content()
329
+
330
+ with self.session.get(self.url, stream=True) as r:
331
+ r.raise_for_status()
332
+ filesize = int(r.headers.get("Content-Length", 0))
333
+ logger.debug(f"Track size: {filesize} ({self.filesize})")
334
+ self.status = TrackStatus.FETCHING
335
+
336
+ for chunk in r.iter_content(chunk_size):
337
+ if len(chunk) > chunk_sep:
338
+ dchunk = self._decrypt(chunk[:chunk_sep]) + chunk[chunk_sep:]
339
+ else:
340
+ dchunk = chunk
341
+ self._content_mv[self.fetched : self.fetched + chunk_size] = dchunk
342
+ self.fetched += chunk_size
343
+
344
+ if (
345
+ self.fetched >= self.buffer_size
346
+ and self.status < TrackStatus.PLAYABLE
347
+ ):
348
+ logger.debug("Buffering ok")
349
+ self.status = TrackStatus.PLAYABLE
350
+
351
+ # We are done here
352
+ self.status = TrackStatus.FETCHED
353
+ logger.debug("Track fetched")
354
+
355
+ def cast(self, socket, chunk_size: int = 1024):
356
+ """Cast the track via UDP using given socket."""
357
+ multicast_group = tuple(settings.MULTICAST_GROUP)
358
+ logger.debug(
359
+ (
360
+ f"Casting from position {self.streamed} with {chunk_size=} "
361
+ f"using socket {socket} "
362
+ f"({multicast_group=})"
363
+ )
364
+ )
365
+
366
+ if self.status < TrackStatus.FETCHING:
367
+ logger.debug("Will start fetching content in a new thead…")
368
+ thread = Thread(target=self.fetch)
369
+ thread.start()
370
+
371
+ # Wait for the track to be playable
372
+ while self.status < TrackStatus.PLAYABLE:
373
+ sleep(0.01)
374
+
375
+ # Sleep time while playing
376
+ wait = 1.0 / (self.bitrate / chunk_size)
377
+ logger.debug(f"Wait time: {wait}s ({self.bitrate=})")
378
+
379
+ slow_connection: bool = False
380
+ for start in range(self.streamed, self.filesize, chunk_size):
381
+
382
+ # Track has been paused, wait for resume
383
+ while self.paused:
384
+ sleep(0.001)
385
+
386
+ # We have buffering issues
387
+ while (self.fetched - start) < self.buffer_size and start < (
388
+ self.filesize - self.buffer_size
389
+ ):
390
+ if not slow_connection:
391
+ logger.warning(
392
+ "Slow connection, filling the buffer "
393
+ f"{self.fetched - self.streamed} < {self.buffer_size}"
394
+ )
395
+ logger.debug(
396
+ f"{start=} | {self.filesize=} | {self.fetched=} | "
397
+ f"{self.streamed=} | {chunk_size=}"
398
+ )
399
+ slow_connection = True
400
+ sleep(0.05)
401
+ slow_connection = False
402
+
403
+ socket.sendto(self._content_mv[start : start + chunk_size], multicast_group)
404
+ self.streamed += chunk_size
405
+ sleep(wait)
@@ -0,0 +1,41 @@
1
+ """Onzr: player."""
2
+
3
+ import logging
4
+ from socket import SocketType
5
+
6
+ import vlc
7
+ from vlc import MediaPlayer
8
+
9
+ from .config import settings
10
+ from .deezer import Track
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class Player:
16
+ """Onzr player."""
17
+
18
+ def __init__(self, socket: SocketType, local: bool = True) -> None:
19
+ """Instantiate the player."""
20
+ logger.debug(f"Instantiating Player using socket: {socket} ({local=})")
21
+ self.socket: SocketType = socket
22
+ self.track: Track | None = None
23
+ self.chunk_size: int = 1024 * 16
24
+ self.vlc: MediaPlayer | None = None
25
+ if local:
26
+ self._start_udp_client(settings.MULTICAST_URL)
27
+
28
+ def _start_udp_client(self, url: str):
29
+ """Start local UDP client.
30
+
31
+ Start a local UDP client that will listen to the UDP socket and play sound.
32
+ """
33
+ logger.debug(f"Starting local UDP client with: {url=}")
34
+ self.vlc = vlc.MediaPlayer(url)
35
+ self.vlc.play()
36
+
37
+ def play(self, track: Track):
38
+ """Play a track."""
39
+ logger.info(f"▶️ {track.full_title}")
40
+ self.track = track
41
+ self.track.cast(self.socket, self.chunk_size)
@@ -0,0 +1,7 @@
1
+ # FIXME: should not be hard-coded
2
+ DEEZER_BLOWFISH_SECRET = "g4el58wc0zvf9na1"
3
+ QUALITY = "MP3_128"
4
+ MULTICAST_GROUP_HOST = "224.0.0.1"
5
+ MULTICAST_GROUP_PORT = 10000
6
+ MULTICAST_GROUP = ["@format {this.MULTICAST_GROUP_HOST}", "@int @format {this.MULTICAST_GROUP_PORT}"]
7
+ MULTICAST_URL = "@format udp://@{this.MULTICAST_GROUP_HOST}:{this.MULTICAST_GROUP_PORT}"