Repository navigation
Expand file tree
/
Copy pathYNDXMusic.py
More file actions
2887 lines (2717 loc) · 120 KB
/
Copy pathYNDXMusic.py
File metadata and controls
2887 lines (2717 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# CopyLeft 2026 github.com/i-execute
# Author: I_execute.t.me
# Licensed under AGPLv3.
__version__ = (3, 0, 0)
# meta developer: Execute_forge.t.me
# meta banner: https://github.com/i-execute/Modules/raw/main/Storage/YNDXMusic/MetaBannerNew.jpeg
import os
import io
import re
import time
import json
import random
import string
import hashlib
import logging
import tempfile
import shutil
import asyncio
import subprocess
import sys
import traceback
import uuid
from telethon.tl.types import Message, DocumentAttributeAudio
from telethon import functions
from telethon.tl.types import InputMediaWebPage
from .. import loader, utils
logger = logging.getLogger(__name__)
FAVORITE_COVER_URL = "https://github.com/i-execute/Modules/raw/main/Storage/YNDXMusic/Favorite.jpeg"
YM_TOKEN_PATTERN = re.compile(r"access_token=([^&]+)")
YM_ALBUM_TRACK_RE = re.compile(
r"https?://music\.yandex\.(?:ru|com|by|kz|uz)/album/\d+/track/(\d+)"
)
YM_DIRECT_TRACK_RE = re.compile(
r"https?://music\.yandex\.(?:ru|com|by|kz|uz)/track/(\d+)"
)
YM_PLAYLIST_RE = re.compile(
r"https?://music\.yandex\.(?:ru|com|by|kz|uz)/users/([^/]+)/playlists/(\d+)"
)
YM_PLAYLIST_UUID_RE = re.compile(
r"https?://music\.yandex\.(?:ru|com|by|kz|uz)/playlists/([a-f0-9\-]{36})"
)
YM_PLAYLIST_LK_RE = re.compile(
r"https?://music\.yandex\.(?:ru|com|by|kz|uz)/playlists/lk\.([a-f0-9\-]{36})"
)
YM_ALBUM_RE = re.compile(
r"https?://music\.yandex\.(?:ru|com|by|kz|uz)/album/(\d+)(?:[/?]|$)"
)
REQUEST_OK = 200
CACHE_TTL = 600
COVER_SIZES = [1000, 900, 800, 700, 600, 400, 300, 200]
LOG_ENTRIES = []
MAX_LOG = 300
def _log(tag: str, msg: str):
ts = time.strftime("%H:%M:%S")
entry = f"[{ts}] [{tag}] {msg}"
LOG_ENTRIES.append(entry)
if len(LOG_ENTRIES) > MAX_LOG:
LOG_ENTRIES.pop(0)
logger.info(entry)
def _ensure_all_deps():
for mod, pip in {
"mutagen": "mutagen",
"yandex_music": "yandex-music",
"PIL": "Pillow",
"aiofiles": "aiofiles",
"curl_cffi": "curl_cffi",
}.items():
try:
__import__(mod)
except ImportError:
subprocess.check_call(
[sys.executable, "-m", "pip", "install", pip, "-q"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
_ensure_all_deps()
import aiohttp
from yandex_music import ClientAsync
from yandex_music.exceptions import TimedOutError as YMTimedOutError
from yandex_music.utils.request_async import Request as _YMRequest
from yandex_music.exceptions import TimedOutError as _YMTimedOutError, NetworkError as _YMNetworkError
from curl_cffi.requests import AsyncSession as _CurlSession
_YNDX_IMPERSONATE = "chrome116"
_YNDX_TIMEOUT = 0.7
_YNDX_ATTEMPTS = 30
_YNDX_HEAVY_BODY_THRESHOLD = 200
_YNDX_HEAVY_TIMEOUT = 3.0
def _yndx_request_body_size(params, data, json):
size = 0
for part in (params, data, json):
if not part:
continue
try:
size += len(str(part))
except Exception:
pass
return size
async def _yndx_curl_get(url, headers=None, timeout=10, attempts=3):
last_exc = None
async with _CurlSession(impersonate=_YNDX_IMPERSONATE) as session:
for _ in range(attempts):
try:
return await session.get(url, headers=headers, timeout=timeout)
except Exception as e:
last_exc = e
continue
if last_exc:
raise last_exc
return None
if not getattr(_YMRequest, "_yndx_curl_patched", False):
import asyncio as _asyncio
async def _yndx_curl_request_wrapper(self, *args, **kwargs):
method = args[0] if args else kwargs.pop("method", "GET")
url = args[1] if len(args) > 1 else kwargs.pop("url")
kwargs.pop("timeout", None)
headers = kwargs.pop("headers", self.headers)
params = kwargs.pop("params", None)
data = kwargs.pop("data", None)
json = kwargs.pop("json", None)
proxy = kwargs.pop("proxy", self.proxy_url)
body_size = _yndx_request_body_size(params, data, json)
req_timeout = _YNDX_HEAVY_TIMEOUT if body_size > _YNDX_HEAVY_BODY_THRESHOLD else _YNDX_TIMEOUT
last_exc = None
async with _CurlSession(impersonate=_YNDX_IMPERSONATE) as session:
for _ in range(_YNDX_ATTEMPTS):
try:
r = await session.request(
method, url,
headers=headers,
params=params,
data=data,
json=json,
proxy=proxy,
timeout=req_timeout,
)
content = r.content
if 200 <= r.status_code <= 299:
return content
self._handle_error_response(r.status_code, content)
return None
except Exception as e:
last_exc = e
continue
raise _YMTimedOutError from last_exc
_YMRequest._request_wrapper = _yndx_curl_request_wrapper
_YMRequest._yndx_curl_patched = True
from PIL import Image
try:
from mutagen.id3 import ID3, TIT2, TPE1, TALB, APIC, ID3NoHeaderError
except ImportError:
ID3 = None
def escape_html(t):
return (t or "").replace("&", "&").replace("<", "<").replace(">", ">")
def sanitize_fn(n):
return re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", n).strip(". ")[:180] or "track"
def parse_ym_track_id(text):
if not text:
return None
for pat in [YM_ALBUM_TRACK_RE, YM_DIRECT_TRACK_RE]:
m = pat.search(text)
if m:
return m.group(1)
return None
def extract_ym_token(text):
if not text:
return None
m = YM_TOKEN_PATTERN.search(text)
return m.group(1) if m else None
def _build_ym_auth_url(client_id):
return (
f"https://oauth.yandex.ru/authorize?"
f"response_type=token&client_id={client_id}"
)
def _is_ym_track_link(text):
if not text:
return False
return bool(YM_ALBUM_TRACK_RE.search(text) or YM_DIRECT_TRACK_RE.search(text))
def _is_ym_album_link(text):
if not text:
return False
m = YM_ALBUM_RE.search(text)
if not m:
return False
if YM_ALBUM_TRACK_RE.search(text):
return False
return True
def normalize_cover(raw_data, max_size=None, force_jpeg=False):
if not raw_data or len(raw_data) < 100:
return None
try:
img = Image.open(io.BytesIO(raw_data))
w, h = img.size
needs_resize = max_size is not None and (w > max_size or h > max_size)
if force_jpeg:
img = img.convert("RGB")
if needs_resize:
ratio = min(max_size / w, max_size / h)
img = img.resize((int(w * ratio), int(h * ratio)), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=95)
result = buf.getvalue()
return result if len(result) >= 100 else None
is_png = raw_data[:8] == b'\x89PNG\r\n\x1a\n'
if is_png and not needs_resize:
return raw_data
img = img.convert("RGB")
if needs_resize:
ratio = min(max_size / w, max_size / h)
img = img.resize((int(w * ratio), int(h * ratio)), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="PNG")
result = buf.getvalue()
return result if len(result) >= 100 else None
except Exception:
return None
async def _get_best_cover_url(cover_uri):
if not cover_uri:
return None
for sz in COVER_SIZES:
url = f"https://{cover_uri.replace('%%', f'{sz}x{sz}')}"
try:
r = await _yndx_curl_get(url, timeout=5, attempts=1)
if r is not None and r.status_code == 200:
return url
except Exception:
continue
return None
async def _download_cover_best(cover_uri, covers_dir=None):
if not cover_uri:
return None
cache_key = hashlib.md5(cover_uri.encode()).hexdigest()
if covers_dir:
cache_path = os.path.join(covers_dir, f"{cache_key}.jpg")
if os.path.exists(cache_path):
try:
with open(cache_path, "rb") as f:
return f.read()
except Exception:
pass
url = await _get_best_cover_url(cover_uri)
if not url:
return None
try:
r = await _yndx_curl_get(url, timeout=15)
if r is None or r.status_code != 200:
return None
data = r.content
if not data or len(data) < 500:
return None
if covers_dir:
try:
with open(cache_path, "wb") as f:
f.write(data)
except Exception:
pass
return data
except Exception:
return None
async def _convert_to_mp3(inp, out):
try:
proc = await asyncio.create_subprocess_exec(
"ffmpeg", "-hide_banner", "-loglevel", "error",
"-y", "-i", inp, "-vn", "-acodec", "libmp3lame", "-ab", "320k", out,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.PIPE,
)
await asyncio.wait_for(proc.communicate(), timeout=60)
return proc.returncode == 0 and os.path.exists(out) and os.path.getsize(out) > 0
except Exception:
return False
async def _embed_cover(mp3_path, cover_path, out_path):
try:
proc = await asyncio.create_subprocess_exec(
"ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-i", mp3_path, "-i", cover_path,
"-map", "0:a", "-map", "1:0",
"-c:a", "copy", "-c:v", "copy",
"-id3v2_version", "3",
"-metadata:s:v", "title=Cover",
"-metadata:s:v", "comment=Cover (front)",
"-disposition:v", "attached_pic", out_path,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.PIPE,
)
await asyncio.wait_for(proc.communicate(), timeout=30)
return proc.returncode == 0 and os.path.exists(out_path) and os.path.getsize(out_path) > 0
except Exception:
return False
def _write_id3_tags(filepath, title, artist, album_title=None, cover_data=None):
if not ID3:
return
try:
try:
tags = ID3(filepath)
except ID3NoHeaderError:
tags = ID3()
tags.add(TIT2(encoding=3, text=[title]))
tags.add(TPE1(encoding=3, text=[artist]))
if album_title:
tags.add(TALB(encoding=3, text=[album_title]))
if cover_data and len(cover_data) > 100:
is_png = cover_data[:8] == b'\x89PNG\r\n\x1a\n'
mime = "image/png" if is_png else "image/jpeg"
tags.add(APIC(encoding=3, mime=mime, type=3, desc="Cover", data=cover_data))
tags.save(filepath)
except Exception:
pass
async def _upload_to_x0(data: bytes, filename: str, content_type: str = "audio/mpeg") -> str:
try:
form = aiohttp.FormData()
form.add_field("file", data, filename=filename, content_type=content_type)
async with aiohttp.ClientSession() as s:
async with s.post(
"https://x0.at",
data=form,
timeout=aiohttp.ClientTimeout(total=60),
) as r:
text = (await r.text()).strip()
if text.startswith("http"):
return text
except Exception:
pass
return ""
class YMApiClient:
def __init__(self):
self._token = None
self._client = None
self._ok = False
self._uid = None
self._login = None
self._has_plus = False
@property
def ok(self):
return self._ok and self._token is not None
@property
def has_plus(self):
return self._has_plus
async def auth(self, token):
if not token:
self.reset()
return False
self._token = token
try:
self._client = ClientAsync(token)
await self._client.init()
me = self._client.me
self._uid = me.account.uid
self._login = me.account.login
plus = getattr(me, 'plus', None)
self._has_plus = bool(getattr(plus, 'has_plus', False)) if plus else False
self._ok = True
return True
except Exception as e:
_log("AUTH", f"Auth failed: {e}")
self.reset()
return False
def reset(self):
self._token = None
self._client = None
self._ok = False
self._uid = None
self._login = None
self._has_plus = False
async def fetch_track(self, track_id):
if not self._client:
return None
try:
tracks = await self._client.tracks(track_id, with_positions=False)
return tracks[0] if tracks else None
except Exception as e:
_log("FETCH", f"fetch_track error: {e}")
return None
async def fetch_playlist(self, user_login, playlist_id):
if not self._client:
return None
try:
return await self._client.users_playlists(playlist_id, user_login)
except Exception as e:
_log("FETCH", f"fetch_playlist error: {e}")
return None
async def fetch_playlist_by_uuid(self, uuid):
if not self._client:
return None
try:
all_pl = await self._client.users_playlists_list(self._uid)
if not all_pl:
return None
for pl in all_pl:
if getattr(pl, "playlist_uuid", None) == uuid:
owner = getattr(pl, "owner", None)
login = getattr(owner, "login", None) if owner else None
kind = getattr(pl, "kind", None)
if login and kind is not None:
return await self._client.users_playlists(kind, login)
return None
except Exception as e:
_log("FETCH", f"fetch_playlist_by_uuid error: {e}")
return None
async def fetch_all_playlists_meta(self):
if not self._client:
return []
try:
return await self._client.users_playlists_list(self._uid) or []
except Exception as e:
_log("FETCH", f"fetch_all_playlists_meta error: {e}")
return []
async def fetch_liked_tracks(self):
if not self._client or not self._login:
return []
try:
result = await self._client.users_playlists(3, self._login)
if not result:
return []
tracks_short = getattr(result, "tracks", None) or []
if not tracks_short:
return []
ids = []
for t in tracks_short:
tid = getattr(t, "id", None)
if tid is not None:
ids.append(str(tid))
else:
raw = getattr(t, "track_id", None)
if raw:
ids.append(str(raw).split(":")[0])
if not ids:
return []
fetched = []
for i in range(0, len(ids), 50):
chunk = ids[i:i + 50]
try:
res = await self._client.tracks(chunk)
if res:
fetched.extend(res)
except Exception as e:
_log("LIKED", f"batch {i} error: {e}")
return fetched
except Exception as e:
_log("LIKED", f"fetch_liked_tracks error: {e}")
return []
async def fetch_liked_albums_books(self):
if not self._client:
return []
try:
liked = await self._client.users_likes_albums(self._uid)
if not liked:
return []
result = []
for item in liked:
al = getattr(item, 'album', item)
if getattr(al, 'type', None) == 'audiobook':
result.append(al)
return result
except Exception as e:
_log("BOOKS", f"fetch_liked_albums_books error: {e}")
return []
async def fetch_liked_albums_music(self):
if not self._client:
return []
try:
liked = await self._client.users_likes_albums(self._uid)
if not liked:
return []
result = []
for item in liked:
al = getattr(item, 'album', item)
if getattr(al, 'type', None) not in ('audiobook', 'podcast'):
result.append(al)
return result
except Exception as e:
_log("ALBUMS", f"fetch_liked_albums_music error: {e}")
return []
async def fetch_album_with_tracks(self, album_id):
if not self._client:
return None
try:
return await self._client.albums_with_tracks(album_id)
except Exception as e:
_log("FETCH", f"fetch_album_with_tracks error: {e}")
return None
async def fetch_playlist_cover_url(self, pl):
og_image = getattr(pl, "og_image", None)
if og_image:
url = await _get_best_cover_url(og_image)
if url:
return url
cover = getattr(pl, "cover", None)
if cover:
uri = getattr(cover, "uri", None)
if uri:
url = await _get_best_cover_url(uri)
if url:
return url
return None
async def download_track_file(self, track, filepath):
try:
if os.path.exists(filepath):
try:
os.remove(filepath)
except Exception:
pass
await track.download_async(filepath)
return os.path.exists(filepath) and os.path.getsize(filepath) > 0
except Exception as e:
_log("DOWNLOAD", f"download_track_file failed: {e}")
return False
async def download_book_part_file(self, track, filepath, retries=10, timeout_pause=60):
last_err = None
for attempt in range(retries):
try:
if os.path.exists(filepath):
try:
os.remove(filepath)
except Exception:
pass
await track.download_async(filepath)
if os.path.exists(filepath) and os.path.getsize(filepath) > 0:
return True
last_err = "empty file"
except (YMTimedOutError, asyncio.TimeoutError) as e:
last_err = e
_log("DOWNLOAD", f"download_book_part_file attempt {attempt + 1}/{retries} timed out: {e}")
if attempt != retries - 1:
_log("DOWNLOAD", f"Pausing {timeout_pause}s before retry due to timeout")
await asyncio.sleep(timeout_pause)
continue
except Exception as e:
last_err = e
_log("DOWNLOAD", f"download_book_part_file attempt {attempt + 1}/{retries} failed: {e}")
if attempt != retries - 1:
await asyncio.sleep(2 * (attempt + 1))
_log("DOWNLOAD", f"download_book_part_file gave up after {retries} attempts: {last_err}")
return False
async def search_track(self, query, count=5):
if not self._client:
return []
try:
result = await self._client.search(query, type_="track")
if not result or not result.tracks or not result.tracks.results:
return []
return result.tracks.results[:count]
except Exception as e:
_log("SEARCH", f"search failed: {e}")
try:
self._client = None
self._ok = False
await self.auth(self._token)
result = await self._client.search(query, type_="track")
if not result or not result.tracks or not result.tracks.results:
return []
return result.tracks.results[:count]
except Exception as e2:
_log("SEARCH", f"retry failed: {e2}")
return []
@staticmethod
def track_artist(track):
if track.artists:
return ", ".join(a.name for a in track.artists if a.name) or "Unknown"
return "Unknown"
@staticmethod
def track_title(track):
return track.title or "Unknown"
@staticmethod
def cover_url(cover_uri, size="200x200"):
if not cover_uri:
return None
return f"https://{cover_uri.replace('%%', size)}"
@loader.tds
class YNDXMusic(loader.Module):
"""Yandex Music audio downloader and search"""
strings = {
"name": "YNDXMusic",
"ymauth_menu_title": (
"<b>YNDXMusic - Authorization</b>\n"
"<blockquote>"
"1. Open the link below\n"
"2. Sign in and grant permissions\n"
"3. Copy the full URL from the address bar\n"
"4. Tap the button below and paste the URL"
"</blockquote>\n"
'<a href="{ym_url}">Authorize via Yandex</a>'
),
"ymauth_paste_btn": "Paste URL",
"ymauth_enter_url": "Paste full URL from address bar:",
"ymauth_cancel": "Cancel",
"token_ok": (
"<b>Yandex Music authorized!</b>\n"
"<blockquote>UID: <code>{uid}</code>\n"
"Login: <code>{login}</code>\n"
"Plus: {plus}</blockquote>"
),
"token_fail": "<b>Token is invalid!</b>",
"token_bad_format": "<b>Wrong format!</b> Provide the full URL or token.",
"no_token": "<b>Not authorized.</b> Use <code>{prefix}ymauth</code>",
"no_plus": "<b>Yandex Plus not active.</b> Download may fail.",
"no_playing": "<b>Nothing is playing right now</b>",
"fetching": "<b>Fetching current track...</b>",
"downloading": "<b>Downloading...</b>",
"uploading": "<b>Uploading...</b>",
"fetching_link": "<b>Fetching link...</b>",
"invalid_link": "<b>Invalid link</b>",
"error": "<b>Error:</b> {msg}",
"download_fail": "<b>Download failed.</b> Check your Yandex Plus subscription or try again.",
"track_text": (
"<blockquote>"
"<b>Listening on:</b> {device}\n"
"<b>Playing from:</b> <tg-emoji emoji-id=5256072030704410885>📂</tg-emoji>{source}\n"
"<b>Played till:</b> <tg-emoji emoji-id=5256060906739113185>🎶</tg-emoji> {played_till}\n"
"<b>Track link:</b> <tg-emoji emoji-id=5258508389557771865>🔗</tg-emoji>{link}"
"</blockquote>"
),
"yms_searching": "<b>Searching</b> <code>{query}</code>",
"yms_download": "⬇️ Download",
"yms_cancel": "✖️ Close",
"yms_new_search": "🔍 New search",
"yms_downloading": "Downloading...",
"yms_edit_dl": "<b>Downloading</b> <code>{title}</code>",
"yms_no_results": "<b>Nothing found</b>",
"yms_provide_query": "<b>Provide a search query</b>",
"yms_menu_title": "<b>Yandex Music</b>\n<blockquote>Search a track</blockquote>",
"yms_via_link": "Via link",
"yms_via_query": "Via query",
"yms_enter_link": "Enter track link:",
"yms_enter_query": "Enter search query:",
"ymp_title": "<b>{name}</b>\n<blockquote>{count} tracks</blockquote>",
"ymp_progress": "<b>{name}</b>\n<blockquote>{done}/{total} downloaded</blockquote>",
"ymp_no_url": "<b>Provide a playlist URL</b>",
"ymp_not_found": "<b>Playlist not found</b>",
"ymp_download": "Download",
"ymp_cancel": "Cancel",
"ymp_kill": "Kill",
"ymp_menu_my": "My playlists",
"ymp_menu_link": "Enter link",
"ymp_enter_link": "Enter playlist link:",
"ymp_fetching_pl": "<b>Fetching playlist...</b>",
"ymp_favorites": "Favorites",
"ymp_menu_title": "<b>Yandex Music</b>\n<blockquote>Select playlist source</blockquote>",
"ymp_playlist_title": "<b>{title}</b>\n<blockquote>{count} tracks</blockquote>",
"ymb_menu_title": "<b>Yandex Music</b>\n<blockquote>Select audiobook source</blockquote>",
"ymb_menu_my": "My books",
"ymb_menu_link": "Enter link",
"ymb_enter_link": "Enter audiobook link:",
"ymb_fetching": "<b>Fetching audiobook...</b>",
"ymb_not_found": "<b>Audiobook not found</b>",
"ymb_not_book": "<b>This is not an audiobook link</b>",
"ymb_title": "<b>{name}</b>\n<blockquote>{count} parts</blockquote>",
"ymb_progress": "<b>{name}</b>\n<blockquote>{done}/{total} parts downloaded</blockquote>",
"ymb_download": "Download",
"ymb_cancel": "Cancel",
"ymb_kill": "Kill",
"ymb_no_books": "<b>No audiobooks in library</b>",
"ymb_stopped": "<b>Download stopped: {done}/{total} parts sent.</b>\n<blockquote>Failed on part {idx}: {name}\nReason: {error}</blockquote>",
"yma_menu_title": "<b>Yandex Music</b>\n<blockquote>Select album source</blockquote>",
"yma_menu_my": "My albums",
"yma_menu_link": "Enter link",
"yma_enter_link": "Enter album link:",
"yma_no_albums": "<b>No albums in library</b>",
"yma_no_link": "<b>Provide an album link.</b> Usage: <code>{prefix}yma <link></code>",
"yma_not_album": "<b>This is not an album link</b>",
"yma_is_book": "<b>This album is an audiobook.</b> Use <code>{prefix}ymb</code>",
"yma_fetching": "<b>Fetching album...</b>",
"yma_not_found": "<b>Album not found</b>",
"yma_title": "<b>{name}</b>\n<blockquote>{artist}\n{count} tracks</blockquote>",
"yma_progress": "<b>{name}</b>\n<blockquote>{done}/{total} tracks downloaded</blockquote>",
"yma_download": "Download",
"yma_cancel": "Cancel",
"yma_kill": "Kill",
"yma_stopped": "<b>Download stopped: {done}/{total} tracks sent.</b>\n<blockquote>Failed on track {idx}: {name}\nReason: {error}</blockquote>",
"btn_left": "⬅️",
"btn_right": "➡️",
"unknown_device": "Unknown",
"source_liked": "Liked",
"link_text": "Song",
}
strings_ru = {
"ymauth_menu_title": (
"<b>YNDXMusic - Авторизация</b>\n"
"<blockquote>"
"1. Откройте ссылку ниже\n"
"2. Войдите в аккаунт и дайте разрешения\n"
"3. Скопируйте полный URL из адресной строки\n"
"4. Нажмите кнопку ниже и вставьте URL"
"</blockquote>\n"
'<a href="{ym_url}">Авторизация через Яндекс</a>'
),
"ymauth_paste_btn": "Вставить URL",
"ymauth_enter_url": "Вставьте полный URL из адресной строки:",
"ymauth_cancel": "Отмена",
"token_ok": (
"<b>Yandex Music авторизован!</b>\n"
"<blockquote>UID: <code>{uid}</code>\n"
"Логин: <code>{login}</code>\n"
"Плюс: {plus}</blockquote>"
),
"token_fail": "<b>Токен недействителен!</b>",
"token_bad_format": "<b>Неверный формат!</b> Укажите полный URL или токен.",
"no_token": "<b>Не авторизован.</b> Используйте <code>{prefix}ymauth</code>",
"no_plus": "<b>Яндекс Плюс не активен.</b> Скачивание может не работать.",
"no_playing": "<b>Сейчас ничего не играет</b>",
"fetching": "<b>Получение текущего трека...</b>",
"downloading": "<b>Скачивание...</b>",
"uploading": "<b>Загрузка...</b>",
"fetching_link": "<b>Получаю ссылку...</b>",
"invalid_link": "<b>Некорректная ссылка</b>",
"error": "<b>Ошибка:</b> {msg}",
"download_fail": "<b>Ошибка скачивания.</b> Проверьте подписку Яндекс Плюс или попробуйте позже.",
"track_text": (
"<blockquote>"
"<b>Слушаю на:</b> {device}\n"
"<b>Играет из:</b> <tg-emoji emoji-id=5256072030704410885>📂</tg-emoji>{source}\n"
"<b>Прослушано до:</b> <tg-emoji emoji-id=5256060906739113185>🎶</tg-emoji> {played_till}\n"
"<b>Ссылка на трек:</b> <tg-emoji emoji-id=5258508389557771865>🔗</tg-emoji>{link}"
"</blockquote>"
),
"yms_searching": "<b>Поиск</b> <code>{query}</code>",
"yms_download": "⬇️ Скачать",
"yms_cancel": "✖️ Закрыть",
"yms_new_search": "🔍 Новый поиск",
"yms_downloading": "Загрузка...",
"yms_edit_dl": "<b>Загружаю</b> <code>{title}</code>",
"yms_no_results": "<b>Ничего не найдено</b>",
"yms_provide_query": "<b>Укажите поисковый запрос</b>",
"yms_menu_title": "<b>Yandex Music</b>\n<blockquote>Поиск трека</blockquote>",
"yms_via_link": "По ссылке",
"yms_via_query": "По запросу",
"yms_enter_link": "Введите ссылку на трек:",
"yms_enter_query": "Введите поисковый запрос:",
"ymp_title": "<b>{name}</b>\n<blockquote>{count} треков</blockquote>",
"ymp_progress": "<b>{name}</b>\n<blockquote>{done}/{total} загружено</blockquote>",
"ymp_no_url": "<b>Укажите URL плейлиста</b>",
"ymp_not_found": "<b>Плейлист не найден</b>",
"ymp_download": "Скачать",
"ymp_cancel": "Отмена",
"ymp_kill": "Остановить",
"ymp_menu_my": "Мои плейлисты",
"ymp_menu_link": "Ввести ссылку",
"ymp_enter_link": "Введите ссылку на плейлист:",
"ymp_fetching_pl": "<b>Получаю плейлист...</b>",
"ymp_favorites": "Избранное",
"ymp_menu_title": "<b>Yandex Music</b>\n<blockquote>Выберите источник плейлиста</blockquote>",
"ymp_playlist_title": "<b>{title}</b>\n<blockquote>{count} треков</blockquote>",
"ymb_menu_title": "<b>Yandex Music</b>\n<blockquote>Выберите источник аудиокниги</blockquote>",
"ymb_menu_my": "Мои книги",
"ymb_menu_link": "Ввести ссылку",
"ymb_enter_link": "Введите ссылку на аудиокнигу:",
"ymb_fetching": "<b>Получаю аудиокнигу...</b>",
"ymb_not_found": "<b>Аудиокнига не найдена</b>",
"ymb_not_book": "<b>Это не ссылка на аудиокнигу</b>",
"ymb_title": "<b>{name}</b>\n<blockquote>{count} частей</blockquote>",
"ymb_progress": "<b>{name}</b>\n<blockquote>{done}/{total} частей загружено</blockquote>",
"ymb_download": "Скачать",
"ymb_cancel": "Отмена",
"ymb_kill": "Остановить",
"ymb_no_books": "<b>Нет аудиокниг в библиотеке</b>",
"ymb_stopped": "<b>Загрузка остановлена: {done}/{total} частей отправлено.</b>\n<blockquote>Ошибка на части {idx}: {name}\nПричина: {error}</blockquote>",
"yma_menu_title": "<b>Yandex Music</b>\n<blockquote>Выберите источник альбома</blockquote>",
"yma_menu_my": "Мои альбомы",
"yma_menu_link": "Ввести ссылку",
"yma_enter_link": "Введите ссылку на альбом:",
"yma_no_albums": "<b>Нет альбомов в библиотеке</b>",
"yma_no_link": "<b>Укажи ссылку на альбом.</b> Использование: <code>{prefix}yma <ссылка></code>",
"yma_not_album": "<b>Это не ссылка на альбом</b>",
"yma_is_book": "<b>Это аудиокнига.</b> Используй <code>{prefix}ymb</code>",
"yma_fetching": "<b>Получаю альбом...</b>",
"yma_not_found": "<b>Альбом не найден</b>",
"yma_title": "<b>{name}</b>\n<blockquote>{artist}\n{count} треков</blockquote>",
"yma_progress": "<b>{name}</b>\n<blockquote>{done}/{total} треков загружено</blockquote>",
"yma_download": "Скачать",
"yma_cancel": "Отмена",
"yma_kill": "Остановить",
"yma_stopped": "<b>Загрузка остановлена: {done}/{total} треков отправлено.</b>\n<blockquote>Ошибка на треке {idx}: {name}\nПричина: {error}</blockquote>",
"btn_left": "⬅️",
"btn_right": "➡️",
"unknown_device": "Неизвестно",
"source_liked": "Мне нравится",
"link_text": "Песня",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"YM_TOKEN", "",
"Yandex Music access token",
validator=loader.validators.Hidden(),
),
loader.ConfigValue(
"SEARCH_LIMIT", 5,
"Search results limit (1-10)",
validator=loader.validators.Integer(minimum=1, maximum=10),
),
loader.ConfigValue(
"YM_CLIENT_ID", "23cabbbdc6cd418abb4b39c32c41195d",
"OAuth client_id used for Yandex Music authorization",
validator=loader.validators.Hidden(),
),
)
self._tmp = None
self._covers_dir = None
self._ym = None
self._upload_lock = None
self._now_track_id = None
self._now_mp3_url = None
self._ymauth_sessions = {}
self._yms_sessions = {}
self._yms_locks = {}
self._ymp_sessions = {}
self._ymp_my_sessions = {}
self._ymb_sessions = {}
self._ymb_my_sessions = {}
self._yma_sessions = {}
self._yma_my_sessions = {}
def _init_dirs(self):
if self._tmp and os.path.exists(self._tmp):
shutil.rmtree(self._tmp, ignore_errors=True)
os.makedirs(self._tmp, exist_ok=True)
self._covers_dir = os.path.join(self._tmp, "covers")
os.makedirs(self._covers_dir, exist_ok=True)
async def client_ready(self, client, db):
self._client = client
self._db = db
self._upload_lock = asyncio.Lock()
me = await client.get_me()
self._me_id = me.id
self._tmp = os.path.join(tempfile.gettempdir(), f"YNDXMusic_{me.id}")
self._init_dirs()
self._ym = YMApiClient()
await self._ensure_ym()
async def _ensure_ym(self):
token = self.config["YM_TOKEN"]
if not token:
self._ym.reset()
return False
if self._ym.ok and self._ym._token == token:
return True
return await self._ym.auth(token)
def _get_client_id(self):
cid = (self.config["YM_CLIENT_ID"] or "").strip()
if cid:
return cid
return "23cabbbdc6cd418abb4b39c32c41195d"
def _get_limit(self):
try:
return max(1, min(10, int(self.config["SEARCH_LIMIT"])))
except Exception:
return 5
async def _get_ynison(self):
token = self._ym._token
device_id = "".join(random.choices(string.ascii_lowercase, k=16))
ws_proto = {
"Ynison-Device-Id": device_id,
"Ynison-Device-Info": json.dumps({"app_name": "Chrome", "type": 1}),
}
try:
async with aiohttp.ClientSession() as session:
async with session.ws_connect(
"wss://ynison.music.yandex.ru/redirector.YnisonRedirectService/GetRedirectToYnison",
headers={
"Sec-WebSocket-Protocol": f"Bearer, v2, {json.dumps(ws_proto)}",
"Origin": "http://music.yandex.ru",
"Authorization": f"OAuth {token}",
},
timeout=10,
) as ws:
response = await asyncio.wait_for(ws.receive(), timeout=10)
if response.type != aiohttp.WSMsgType.TEXT:
_log("YNISON", f"Unexpected redirect frame type: {response.type}")
return None
redirect_data = json.loads(response.data)
host = redirect_data.get("host")
ticket = redirect_data.get("redirect_ticket")
if not host or not ticket:
return None
ws_proto2 = {
"Ynison-Device-Id": device_id,
"Ynison-Redirect-Ticket": ticket,
"Ynison-Device-Info": json.dumps({"app_name": "Chrome", "type": 1}),
}
async with session.ws_connect(
f"wss://{host}/ynison_state.YnisonStateService/PutYnisonState",
headers={
"Sec-WebSocket-Protocol": f"Bearer, v2, {json.dumps(ws_proto2)}",
"Origin": "http://music.yandex.ru",
"Authorization": f"OAuth {token}",
},
timeout=10,
) as ws2:
await ws2.send_str(json.dumps({
"update_full_state": {
"player_state": {
"player_queue": {
"current_playable_index": -1,
"entity_id": "",
"entity_type": "VARIOUS",
"playable_list": [],
"options": {"repeat_mode": "NONE"},
"entity_context": "BASED_ON_ENTITY_BY_DEFAULT",
"version": {
"device_id": device_id,
"version": random.randint(1, 9999999999999999),
"timestamp_ms": 0,
},
"from_optional": "",
},
"status": {
"duration_ms": 0,
"paused": True,
"playback_speed": 1,
"progress_ms": 0,
"version": {
"device_id": device_id,
"version": random.randint(1, 9999999999999999),
"timestamp_ms": 0,
},