distube 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.
distube/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ from .compat import apply_dave_compat_patch
2
+
3
+ apply_dave_compat_patch()
4
+
5
+ from .core import DisTubeHandler, TaskQueue
6
+ from .distube import DisTube
7
+ from .enums import PluginType, RepeatMode
8
+ from .errors import DisTubeError
9
+ from .events import Events
10
+ from .managers import FilterManager, QueueManager, VoiceManager
11
+ from .models import Playlist, Queue, Song
12
+ from .options import DEFAULT_FILTERS, FFmpegOptions, Options, default_filters, defaultFilters
13
+ from .plugins import ExtractorPlugin, InfoExtractorPlugin, PlayableExtractorPlugin, Plugin, YtDlpPlugin
14
+ from .utils import (
15
+ check_invalid_key,
16
+ checkInvalidKey,
17
+ format_duration,
18
+ formatDuration,
19
+ is_member_instance,
20
+ is_object,
21
+ is_url,
22
+ isMemberInstance,
23
+ isObject,
24
+ isURL,
25
+ )
26
+
27
+ __version__ = "0.1.0"
28
+
29
+ __all__ = [
30
+ "DEFAULT_FILTERS",
31
+ "DisTube",
32
+ "DisTubeError",
33
+ "DisTubeHandler",
34
+ "Events",
35
+ "ExtractorPlugin",
36
+ "FFmpegOptions",
37
+ "FilterManager",
38
+ "InfoExtractorPlugin",
39
+ "Options",
40
+ "PlayableExtractorPlugin",
41
+ "Playlist",
42
+ "Queue",
43
+ "QueueManager",
44
+ "Plugin",
45
+ "PluginType",
46
+ "RepeatMode",
47
+ "Song",
48
+ "TaskQueue",
49
+ "VoiceManager",
50
+ "YtDlpPlugin",
51
+ "apply_dave_compat_patch",
52
+ "check_invalid_key",
53
+ "checkInvalidKey",
54
+ "default_filters",
55
+ "defaultFilters",
56
+ "format_duration",
57
+ "formatDuration",
58
+ "is_member_instance",
59
+ "is_object",
60
+ "is_url",
61
+ "isMemberInstance",
62
+ "isObject",
63
+ "isURL",
64
+ ]
@@ -0,0 +1,3 @@
1
+ from .dave import apply_dave_compat_patch
2
+
3
+ __all__ = ["apply_dave_compat_patch"]
distube/compat/dave.py ADDED
@@ -0,0 +1,304 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import logging
5
+ import struct
6
+ from importlib import metadata
7
+ from typing import Any
8
+
9
+ _LOG = logging.getLogger(__name__)
10
+ _PATCH_MARKER = "__distube_dave_compat_patch__"
11
+ _PATCH_APPLIED = False
12
+ _PATCHING = False
13
+
14
+
15
+ def _version_at_least(version: str, minimum: tuple[int, ...]) -> bool:
16
+ parts: list[int] = []
17
+ for component in version.split("."):
18
+ digits = "".join(character for character in component if character.isdigit())
19
+ if not digits:
20
+ break
21
+ parts.append(int(digits))
22
+ return tuple((parts + [0] * len(minimum))[: len(minimum)]) >= minimum
23
+
24
+
25
+ def apply_dave_compat_patch() -> bool:
26
+ """Apply discord.py PR #10548 at runtime for discord.py 2.7.1 and davey >= 0.2."""
27
+ global _PATCH_APPLIED, _PATCHING
28
+ if _PATCH_APPLIED:
29
+ return True
30
+ if _PATCHING:
31
+ return False
32
+ try:
33
+ discord_version = metadata.version("discord.py")
34
+ davey_version = metadata.version("davey")
35
+ except metadata.PackageNotFoundError:
36
+ _LOG.debug("DAVE compatibility patch skipped: discord.py or davey is not installed")
37
+ return False
38
+
39
+ if discord_version != "2.7.1" or not _version_at_least(davey_version, (0, 2, 0)):
40
+ _LOG.debug(
41
+ "DAVE compatibility patch not needed for discord.py %s and davey %s",
42
+ discord_version,
43
+ davey_version,
44
+ )
45
+ return False
46
+
47
+ try:
48
+ # Import davey before discord voice modules. discord.voice_state decides
49
+ # whether DAVE is available once, at module import time.
50
+ davey = importlib.import_module("davey")
51
+ gateway = importlib.import_module("discord.gateway")
52
+ voice_state = importlib.import_module("discord.voice_state")
53
+ voice_client = importlib.import_module("discord.voice_client")
54
+ voice_state.davey = davey
55
+ voice_state.has_dave = True
56
+ voice_client.has_dave = True
57
+ except (ImportError, AttributeError):
58
+ _LOG.exception("DAVE compatibility patch could not import discord.py internals")
59
+ return False
60
+
61
+ websocket = gateway.DiscordVoiceWebSocket
62
+ connection_state = voice_state.VoiceConnectionState
63
+ client = voice_client.VoiceClient
64
+ if all(getattr(cls, _PATCH_MARKER, False) for cls in (websocket, connection_state, client)):
65
+ _LOG.debug("DAVE compatibility patch already applied")
66
+ return True
67
+
68
+ _PATCHING = True
69
+ original_init = connection_state.__init__
70
+ original_connect_websocket = connection_state._connect_websocket
71
+ original_send_audio_packet = client.send_audio_packet
72
+
73
+ def state_init(self: Any, *args: Any, **kwargs: Any) -> None:
74
+ original_init(self, *args, **kwargs)
75
+ self.connected_user_ids = set()
76
+
77
+ async def reinit_dave_session(self: Any) -> None:
78
+ self.dave_pending_transitions.clear()
79
+ if self.dave_protocol_version > 0:
80
+ if not voice_state.has_dave:
81
+ raise RuntimeError("davey library needed in order to use E2EE voice")
82
+ session = self.dave_session
83
+ if session is not None:
84
+ session.reinit(self.dave_protocol_version, self.user.id, self.voice_client.channel.id)
85
+ else:
86
+ session = davey.DaveSession(self.dave_protocol_version, self.user.id, self.voice_client.channel.id)
87
+ self.dave_session = session
88
+ if self.dave_downgraded:
89
+ session.set_passthrough_mode(True)
90
+ await self.voice_client.ws.send_binary(
91
+ websocket.MLS_KEY_PACKAGE, session.get_serialized_key_package()
92
+ )
93
+ elif self.dave_session:
94
+ self.dave_session.reset()
95
+ self.dave_session.set_passthrough_mode(True)
96
+
97
+ async def execute_transition(self: Any, transition_id: int) -> None:
98
+ voice_state._log.debug("Executing transition id %d", transition_id)
99
+ if transition_id not in self.dave_pending_transitions:
100
+ voice_state._log.warning(
101
+ "Received execute transition, but we don't have a pending transition for id %d",
102
+ transition_id,
103
+ )
104
+ return
105
+ if self.dave_session and transition_id != 0:
106
+ try:
107
+ if not self.dave_session.execute_transition(transition_id):
108
+ self.dave_pending_transitions.pop(transition_id, None)
109
+ voice_state._log.warning(
110
+ "Failed to execute DAVE transition id %d: davey did not execute it",
111
+ transition_id,
112
+ )
113
+ return
114
+ except Exception:
115
+ self.dave_pending_transitions.pop(transition_id, None)
116
+ voice_state._log.exception("Failed to execute DAVE transition id %d", transition_id)
117
+ return
118
+ old_version = self.dave_protocol_version
119
+ self.dave_protocol_version = self.dave_pending_transitions.pop(transition_id)
120
+ if old_version != self.dave_protocol_version and self.dave_protocol_version == 0:
121
+ self.dave_downgraded = True
122
+ voice_state._log.debug("DAVE Session downgraded")
123
+ elif transition_id > 0 and self.dave_downgraded:
124
+ self.dave_downgraded = False
125
+ if self.dave_session:
126
+ self.dave_session.set_passthrough_mode(False, 10)
127
+ voice_state._log.debug("DAVE Session upgraded")
128
+ voice_state._log.debug("Transition id %d executed", transition_id)
129
+
130
+ async def connect_websocket(self: Any, resume: bool) -> Any:
131
+ if not resume:
132
+ self.connected_user_ids.clear()
133
+ return await original_connect_websocket(self, resume)
134
+
135
+ def can_encrypt(self: Any) -> bool:
136
+ return (
137
+ self.dave_protocol_version != 0
138
+ and not self.dave_downgraded
139
+ and self.dave_session is not None
140
+ and self.dave_session.ready
141
+ )
142
+
143
+ async def received_message(self: Any, msg: dict[str, Any]) -> None:
144
+ gateway._log.debug("Voice websocket frame received: %s", msg)
145
+ op = msg["op"]
146
+ data = msg["d"]
147
+ self.seq_ack = msg.get("seq", self.seq_ack)
148
+ state = self._connection
149
+ if op == self.READY:
150
+ await self.initial_connection(data)
151
+ elif op == self.HEARTBEAT_ACK:
152
+ if self._keep_alive:
153
+ self._keep_alive.ack()
154
+ elif op == self.RESUMED:
155
+ gateway._log.debug("Voice RESUME succeeded.")
156
+ elif op == self.SESSION_DESCRIPTION:
157
+ state.mode = data["mode"]
158
+ await self.load_secret_key(data)
159
+ state.dave_protocol_version = data["dave_protocol_version"]
160
+ state.dave_downgraded = data["dave_protocol_version"] == 0
161
+ if data["dave_protocol_version"] > 0:
162
+ await state.reinit_dave_session()
163
+ elif op == self.HELLO:
164
+ interval = data["heartbeat_interval"] / 1000.0
165
+ self._keep_alive = gateway.VoiceKeepAliveHandler(ws=self, interval=min(interval, 5.0))
166
+ self._keep_alive.start()
167
+ elif op == self.CLIENTS_CONNECT:
168
+ state.connected_user_ids.update(int(user_id) for user_id in data["user_ids"])
169
+ elif op == self.CLIENT_DISCONNECT:
170
+ state.connected_user_ids.discard(int(data["user_id"]))
171
+ elif state.dave_session:
172
+ if op == self.DAVE_PREPARE_TRANSITION:
173
+ gateway._log.debug(
174
+ "Preparing for DAVE transition id %d for protocol version %d",
175
+ data["transition_id"],
176
+ data["protocol_version"],
177
+ )
178
+ state.dave_pending_transitions[data["transition_id"]] = data["protocol_version"]
179
+ try:
180
+ state.dave_session.prepare_transition(data["transition_id"], data["protocol_version"])
181
+ except Exception:
182
+ gateway._log.exception(
183
+ "Failed to prepare DAVE transition id %d", data["transition_id"]
184
+ )
185
+ if data["protocol_version"] == 0:
186
+ state.dave_session.set_passthrough_mode(True)
187
+ if data["transition_id"] == 0:
188
+ await state._execute_transition(data["transition_id"])
189
+ else:
190
+ await self.send_transition_ready(data["transition_id"])
191
+ elif op == self.DAVE_EXECUTE_TRANSITION:
192
+ gateway._log.debug("Executing DAVE transition id %d", data["transition_id"])
193
+ await state._execute_transition(data["transition_id"])
194
+ elif op == self.DAVE_PREPARE_EPOCH:
195
+ gateway._log.debug("Preparing for DAVE epoch %d", data["epoch"])
196
+ if data["epoch"] == 1:
197
+ state.dave_protocol_version = data["protocol_version"]
198
+ await state.reinit_dave_session()
199
+ await self._hook(self, msg)
200
+
201
+ async def received_binary_message(self: Any, msg: bytes) -> None:
202
+ self.seq_ack = struct.unpack_from(">H", msg, 0)[0]
203
+ op = msg[2]
204
+ gateway._log.debug(
205
+ "Voice websocket binary frame received: %d bytes; seq=%s op=%s",
206
+ len(msg),
207
+ self.seq_ack,
208
+ op,
209
+ )
210
+ state = self._connection
211
+ if state.dave_session is None:
212
+ return
213
+ if op == self.MLS_EXTERNAL_SENDER:
214
+ state.dave_session.set_external_sender(msg[3:])
215
+ gateway._log.debug("Set MLS external sender")
216
+ elif op == self.MLS_PROPOSALS:
217
+ optype = msg[3]
218
+ result = state.dave_session.process_proposals(
219
+ davey.ProposalsOperationType.append
220
+ if optype == 0
221
+ else davey.ProposalsOperationType.revoke,
222
+ msg[4:],
223
+ [*state.connected_user_ids, state.user.id],
224
+ )
225
+ if isinstance(result, davey.CommitWelcome):
226
+ await self.send_binary(
227
+ websocket.MLS_COMMIT_WELCOME,
228
+ result.commit + result.welcome if result.welcome else result.commit,
229
+ )
230
+ gateway._log.debug("MLS proposals processed")
231
+ elif op == self.MLS_ANNOUNCE_COMMIT_TRANSITION:
232
+ transition_id = struct.unpack_from(">H", msg, 3)[0]
233
+ try:
234
+ if not state.dave_session.process_commit(msg[5:]):
235
+ gateway._log.debug("MLS commit ignored for transition id %d", transition_id)
236
+ return
237
+ state.dave_session.prepare_transition(
238
+ transition_id, state.dave_session.protocol_version
239
+ )
240
+ if transition_id != 0:
241
+ state.dave_pending_transitions[transition_id] = state.dave_protocol_version
242
+ await self.send_transition_ready(transition_id)
243
+ gateway._log.debug("MLS commit processed for transition id %d", transition_id)
244
+ except Exception:
245
+ await state._recover_from_invalid_commit(transition_id)
246
+ elif op == self.MLS_WELCOME:
247
+ transition_id = struct.unpack_from(">H", msg, 3)[0]
248
+ try:
249
+ state.dave_session.process_welcome(
250
+ msg[5:], [*state.connected_user_ids, state.user.id]
251
+ )
252
+ state.dave_session.prepare_transition(
253
+ transition_id, state.dave_session.protocol_version
254
+ )
255
+ if transition_id != 0:
256
+ state.dave_pending_transitions[transition_id] = state.dave_protocol_version
257
+ await self.send_transition_ready(transition_id)
258
+ gateway._log.debug("MLS welcome processed for transition id %d", transition_id)
259
+ except Exception:
260
+ await state._recover_from_invalid_commit(transition_id)
261
+
262
+ def get_voice_packet(self: Any, data: bytes) -> bytes | None:
263
+ packet = data
264
+ if self._connection.dave_session and self._connection.can_encrypt:
265
+ if not self._connection.dave_session.can_encrypt:
266
+ return None
267
+ packet = self._connection.dave_session.encrypt_opus(data)
268
+ header = bytearray(12)
269
+ header[0] = 0x80
270
+ header[1] = 0x78
271
+ struct.pack_into(">H", header, 2, self.sequence)
272
+ struct.pack_into(">I", header, 4, self.timestamp)
273
+ struct.pack_into(">I", header, 8, self.ssrc)
274
+ encrypt_packet = getattr(self, "_encrypt_" + self.mode)
275
+ return encrypt_packet(header, packet)
276
+
277
+ def send_audio_packet(self: Any, data: bytes, *, encode: bool = True) -> None:
278
+ if (
279
+ self._connection.dave_session
280
+ and self._connection.can_encrypt
281
+ and not self._connection.dave_session.can_encrypt
282
+ ):
283
+ self.checked_add("sequence", 1, 65535)
284
+ self.checked_add("timestamp", voice_client.opus.Encoder.SAMPLES_PER_FRAME, 4294967295)
285
+ return
286
+ original_send_audio_packet(self, data, encode=encode)
287
+
288
+ websocket.received_message = received_message
289
+ websocket.received_binary_message = received_binary_message
290
+ connection_state.__init__ = state_init
291
+ connection_state.reinit_dave_session = reinit_dave_session
292
+ connection_state._execute_transition = execute_transition
293
+ connection_state._connect_websocket = connect_websocket
294
+ connection_state.can_encrypt = property(can_encrypt)
295
+ client._get_voice_packet = get_voice_packet
296
+ client.send_audio_packet = send_audio_packet
297
+ for cls in (websocket, connection_state, client):
298
+ setattr(cls, _PATCH_MARKER, True)
299
+ _PATCH_APPLIED = True
300
+ _PATCHING = False
301
+ _LOG.info(
302
+ "Applied discord.py 2.7.1 DAVE compatibility patch for davey %s", davey_version
303
+ )
304
+ return True
@@ -0,0 +1,4 @@
1
+ from .handler import DisTubeHandler
2
+ from .task_queue import TaskQueue
3
+
4
+ __all__ = ["DisTubeHandler", "TaskQueue"]
@@ -0,0 +1,144 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import inspect
5
+ from typing import Any
6
+ from urllib.error import HTTPError
7
+ from urllib.parse import urljoin
8
+ from urllib.request import Request, urlopen
9
+
10
+ from ..enums import PluginType
11
+ from ..errors import DisTubeError
12
+ from ..models import Playlist, Song
13
+ from ..utils import is_url
14
+
15
+
16
+ async def _call(obj: Any, snake: str, camel: str, *args: Any, **kwargs: Any) -> Any:
17
+ method = getattr(obj, snake, None) or getattr(obj, camel)
18
+ result = method(*args, **kwargs)
19
+ return await result if inspect.isawaitable(result) else result
20
+
21
+
22
+ class DisTubeHandler:
23
+ def __init__(self, distube: Any) -> None:
24
+ self.distube = distube
25
+
26
+ @property
27
+ def plugins(self) -> list[Any]:
28
+ return self.distube.plugins
29
+
30
+ async def resolve(self, value: str | Song | Playlist, **options: Any) -> Song | Playlist:
31
+ if isinstance(value, (Song, Playlist)):
32
+ if "metadata" in options:
33
+ value.metadata = options["metadata"]
34
+ if "member" in options:
35
+ value.member = options["member"]
36
+ return value
37
+ if not isinstance(value, str):
38
+ raise DisTubeError("CANNOT_RESOLVE_SONG", value)
39
+ if is_url(value):
40
+ plugin = await self.get_plugin_from_url(value)
41
+ if plugin is None:
42
+ value = await self.follow_redirect_link(value)
43
+ plugin = await self.get_plugin_from_url(value)
44
+ if plugin is None:
45
+ raise DisTubeError("NOT_SUPPORTED_URL")
46
+ return await _call(plugin, "resolve", "resolve", value, **options)
47
+ song = await self._search_song(value, options)
48
+ if song is None:
49
+ raise DisTubeError("NO_RESULT", value)
50
+ return song
51
+
52
+ async def get_plugin_from_url(self, url: str) -> Any | None:
53
+ for plugin in self.plugins:
54
+ try:
55
+ if await _call(plugin, "validate", "validate", url):
56
+ return plugin
57
+ except Exception as error:
58
+ self.distube.debug(f"Plugin {plugin!r} validate failed: {error}")
59
+ return None
60
+
61
+ async def get_plugin_from_song(
62
+ self, song: Song, types: tuple[PluginType, ...] | None = None, validate: bool = True
63
+ ) -> Any | None:
64
+ plugin = song.plugin
65
+ if plugin is not None and (types is None or plugin.type in types):
66
+ return plugin
67
+ if not song.url:
68
+ return None
69
+ for candidate in self.plugins:
70
+ if types is not None and candidate.type not in types:
71
+ continue
72
+ try:
73
+ if not validate or await _call(candidate, "validate", "validate", song.url):
74
+ return candidate
75
+ except Exception as error:
76
+ self.distube.debug(f"Plugin {candidate!r} validate failed: {error}")
77
+ return None
78
+
79
+ _getPluginFromURL = get_plugin_from_url
80
+ _getPluginFromSong = get_plugin_from_song
81
+
82
+ async def _search_song(self, query: str, options: dict[str, Any], get_stream_url: bool = False) -> Song | None:
83
+ for plugin in self.plugins:
84
+ if plugin.type is not PluginType.EXTRACTOR:
85
+ continue
86
+ result = await _call(plugin, "search_song", "searchSong", query, **options)
87
+ if result is not None:
88
+ if get_stream_url and result.stream["play_from_source"]:
89
+ result.stream["url"] = await _call(plugin, "get_stream_url", "getStreamURL", result)
90
+ return result
91
+ if not any(plugin.type is PluginType.EXTRACTOR for plugin in self.plugins):
92
+ raise DisTubeError("NO_EXTRACTOR_PLUGIN")
93
+ return None
94
+
95
+ async def attach_stream_info(self, song: Song) -> None:
96
+ if song.stream["play_from_source"]:
97
+ plugin = await self.get_plugin_from_song(
98
+ song, (PluginType.EXTRACTOR, PluginType.PLAYABLE_EXTRACTOR)
99
+ )
100
+ if plugin is None:
101
+ raise DisTubeError("NOT_SUPPORTED_SONG", str(song))
102
+ # Extractors commonly return signed CDN URLs that expire. Refresh
103
+ # immediately before every playback/restart instead of caching them.
104
+ song.stream["url"] = await _call(plugin, "get_stream_url", "getStreamURL", song)
105
+ if not song.stream["url"]:
106
+ raise DisTubeError("CANNOT_GET_STREAM_URL", str(song))
107
+ return
108
+ alternate = song.stream.get("song")
109
+ if alternate is not None:
110
+ await self.attach_stream_info(alternate)
111
+ return
112
+ plugin = await self.get_plugin_from_song(song, (PluginType.INFO_EXTRACTOR,))
113
+ if plugin is None:
114
+ raise DisTubeError("NOT_SUPPORTED_SONG", str(song))
115
+ query = await _call(plugin, "create_search_query", "createSearchQuery", song)
116
+ alternate = await self._search_song(
117
+ query, {"metadata": song.metadata, "member": song.member}, get_stream_url=True
118
+ )
119
+ if alternate is None:
120
+ raise DisTubeError("NO_RESULT", query)
121
+ song.stream["song"] = alternate
122
+
123
+ attachStreamInfo = attach_stream_info
124
+
125
+ async def follow_redirect_link(self, url: str, max_redirect: int = 5) -> str:
126
+ def request() -> str:
127
+ current = url
128
+ for _ in range(max_redirect):
129
+ try:
130
+ response = urlopen(Request(current, method="HEAD"), timeout=10)
131
+ next_url = response.geturl()
132
+ except HTTPError as error:
133
+ location = error.headers.get("Location")
134
+ next_url = urljoin(current, location) if location else current
135
+ except Exception:
136
+ return current
137
+ if next_url == current:
138
+ return current
139
+ current = next_url
140
+ return current
141
+
142
+ return await asyncio.to_thread(request)
143
+
144
+ followRedirectLink = follow_redirect_link
@@ -0,0 +1,53 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass
8
+ class _Task:
9
+ is_play: bool
10
+ ready: asyncio.Future[None]
11
+
12
+
13
+ class TaskQueue:
14
+ """FIFO async task gate compatible with the TypeScript TaskQueue API."""
15
+
16
+ def __init__(self) -> None:
17
+ self._tasks: list[_Task] = []
18
+
19
+ async def queuing(self, is_play: bool = False) -> None:
20
+ loop = asyncio.get_running_loop()
21
+ ready: asyncio.Future[None] = loop.create_future()
22
+ previous = self._tasks[-1].ready if self._tasks else None
23
+ task = _Task(is_play, ready)
24
+ self._tasks.append(task)
25
+ if previous is not None:
26
+ try:
27
+ await previous
28
+ except asyncio.CancelledError:
29
+ if task in self._tasks:
30
+ index = self._tasks.index(task)
31
+ self._tasks.remove(task)
32
+ # A cancelled waiter must release the next task that was
33
+ # waiting on its future, otherwise the FIFO chain deadlocks.
34
+ if index < len(self._tasks) and not ready.done():
35
+ ready.set_result(None)
36
+ raise
37
+
38
+ def resolve(self) -> None:
39
+ if not self._tasks:
40
+ return
41
+ task = self._tasks.pop(0)
42
+ if not task.ready.done():
43
+ task.ready.set_result(None)
44
+
45
+ @property
46
+ def remaining(self) -> int:
47
+ return len(self._tasks)
48
+
49
+ @property
50
+ def has_play_task(self) -> bool:
51
+ return any(task.is_play for task in self._tasks)
52
+
53
+ hasPlayTask = property(lambda self: self.has_play_task)