-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
169 lines (141 loc) · 5.49 KB
/
client.py
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
import time
from datetime import datetime
from hashlib import md5
import xml.dom.minidom as minidom
import requests
DEBUG = True
class Session(requests.Session):
def __init__(self, token):
super().__init__()
self.base_url = 'https://api.music.yandex.net'
self.headers.update({
'X-Yandex-Music-Client': 'YandexMusicAndroid/23020251',
'Authorization': f'OAuth {token}',
'Accept-Language': 'ru',
})
def request(self, method, url, raw=False, *args, **kwargs):
kwargs.pop('allow_redirects', None)
error = None
for i in range(10):
try:
result = super().request(
method,
url if raw else f"{self.base_url}{url}",
*args, **kwargs
)
break
except Exception as err:
time.sleep(5)
error = err
else:
raise(error)
# first request should be without user-agent header
self.headers.update({
'User-Agent': "Yandex-Music-API",
})
if DEBUG:
print(method, url, *args, kwargs or '')
if raw:
return result.content
return result.json()['result']
class Client:
def __init__(self, token, station_id) -> None:
self.session = Session(token)
self.id = station_id
self.me = self.session.get('/account/status')['account']
self.batch_id = None
def get_station_tracks(self, track_id=None):
params = { 'settings2': True }
if track_id:
params['queue'] = track_id
data = self.session.get(f'/rotor/station/{self.id}/tracks', params=params)
self.batch_id = data['batchId']
tracks = [
dict(
**t['track'],
liked=t['liked'],
params=t['trackParameters'],
)
for t in data['sequence']
]
return tracks
def feedback(self, type, **kwargs):
return self.session.post(f'/rotor/station/{self.id}/feedback',
json={
'type': type,
'timestamp': datetime.now().timestamp(),
**kwargs,
},
params={
'batch-id': self.batch_id,
},
) == 'ok'
def event_radio_started(self):
self.feedback('radioStarted', **{'from': self.id.replace(':', '-')})
def event_track_started(self, track_id):
self.feedback('trackStarted', trackId=track_id)
def event_track_finished(self, track_id, total_played_seconds):
self.feedback('trackFinished', trackId=track_id, totalPlayedSeconds=total_played_seconds)
def event_track_skip(self, track_id, total_played_seconds):
self.feedback('skip', trackId=track_id, totalPlayedSeconds=total_played_seconds)
def event_play_audio(self, track_id, from_cache, play_id, duration, played, album_id):
self.session.post(f'/play-audio', {
'track-id': track_id,
'from-cache': str(from_cache),
'from': "desktop_win-home-playlist_of_the_day-playlist-default",
'play-id': play_id,
'uid': self.me['uid'],
'timestamp': f'{datetime.now().isoformat()}Z',
'track-length-seconds': duration,
'total-played-seconds': played,
'end-position-seconds': played,
'album-id': album_id,
'playlist-id': None,
'client-now': f'{datetime.now().isoformat()}Z',
})
def get_lyrics(self, track_id):
data = self.session.get(f'/tracks/{track_id}/supplement')
return data.get('lyrics', dict()).get('fullLyrics')
def download(self, track_id, filename):
data = self.session.get(f'/tracks/{track_id}/download-info')
br = 0
info = None
for di in data:
if di['codec'] == 'mp3':
if di['bitrateInKbps'] > br:
info = di
br = di['bitrateInKbps']
if not info:
raise Exception(f'Download info unavailable')
xml = self.session.get(info['downloadInfoUrl'], raw=True)
def _get_text_node_data(elements):
for element in elements:
nodes = element.childNodes
for node in nodes:
if node.nodeType == node.TEXT_NODE:
return node.data
doc = minidom.parseString(xml)
host = _get_text_node_data(doc.getElementsByTagName('host'))
path = _get_text_node_data(doc.getElementsByTagName('path'))
ts = _get_text_node_data(doc.getElementsByTagName('ts'))
s = _get_text_node_data(doc.getElementsByTagName('s'))
sign = md5(('XGRlBW9FXlekgbPrRHuSiA' + path[1::] + s).encode('utf-8')).hexdigest()
with open(filename, 'wb') as f:
f.write(
self.session.get(
f'https://{host}/get-mp3/{sign}/{ts}{path}',
raw=True,
)
)
def event_like(self, track_id, remove=False):
action = 'remove' if remove else 'add-multiple'
self.session.post(
f'/users/{self.me["uid"]}/likes/tracks/{action}',
{'track-ids': track_id},
)
def event_dislike(self, track_id, remove=False):
action = 'remove' if remove else 'add-multiple'
self.session.post(
f'/users/{self.me["uid"]}/dislikes/tracks/{action}',
{'track-ids': track_id},
)