-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsaavn_nn.py
317 lines (268 loc) · 8.39 KB
/
saavn_nn.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
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
import base64
import json
from traceback import print_exc
from typing import Any
from typing import Dict
from typing import List
from typing import Union
import requests
from fastapi.applications import FastAPI
from pyDes import ECB
from pyDes import PAD_PKCS5
from pyDes import des
from pydantic import BaseModel
from pydantic import validator
app = FastAPI()
base_url = "https://www.jiosaavn.com/api.php"
des_cipher = des(b"38346591", ECB, b"\0\0\0\0\0\0\0\0", pad = None,
padmode = PAD_PKCS5)
################################################################################
# pydantic models
################################################################################
class Artist(BaseModel):
id: int
name: str
role: str
image: str
type: str
perma_url: str
@validator('image', allow_reuse = True)
def fix_artist_image(cls, v):
return fix_image_url(v)
class ArtistsMap(BaseModel):
primary_artists: List[Artist]
featured_artists: List[Artist]
artists: List[Artist]
class SongDetails(BaseModel):
id: str
title: str
subtitle: str
type: str = "song"
perma_url: str
image: str
language: str
play_count: int = None
explicit_content: bool = None
list_count: int = None
list_type: str = None
list: Any = None
music: str
album: str
album_id: str
album_url: str
label: str
origin: str
is_320kbps: bool
encrypted_media_url: str
media_url: str
media_url_default: str
duration: int
has_lyrics: bool
lyrics_snippet: str
lyrics_id: str = None
starred: bool
copyright_text: str
artistMap: ArtistsMap
release_date: str
year: int
vlink: str = None
@validator('title', 'subtitle', 'album', allow_reuse = True)
def fix_title_(cls, v):
return fix_title(v)
@validator('image', allow_reuse = True)
def fix_image(cls, v):
return fix_image_url(v)
class AlbumDetails(BaseModel):
id: int
title: str
subtitle: str
type: str
perma_url: str
image: str
language: str
year: int
play_count: str
explicit_content: bool
list_count: int
list_type: str
songs: List[SongDetails]
# @validator('title', 'subtitle')
# def fix_title_(cls, v):
# return fix_title(v)
@validator('image', allow_reuse = True)
def fix_image(cls, v):
return fix_image_url(v)
class PlaylistDetails(AlbumDetails):
# more_info
uid: str
last_updated: str
username: str
firstname: str
lastname: str
follower_count: int
fan_count: int
################################################################################
# jiosaavn_api functions
################################################################################
def jiosaavn_request(search_params, headers = None, resp_only = False) -> Union[
requests.Response, Dict, None]:
if headers is None:
headers = {}
search_params = {'api_version': 4, '_format': 'json', '_marker': 0,
**search_params}
headers = {
# "Host": "c.saavncdn.com",
"Referer": "https://www.jiosaavn.com",
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/84.0.4147.89 Safari/537.36 "
"Edg/84.0.522.40",
**headers
}
resp = requests.get(base_url, params = search_params, headers = headers)
if resp_only:
return resp
try:
return resp.json()
except:
print_exc()
print(resp.text)
try:
return json.loads(resp.text.strip())
except:
print_exc()
return None
def search_query(query: str) -> List[SongDetails]:
query_results = jiosaavn_request({
'__call': "autocomplete.get",
'ctx': "wap6dot0",
'query': query
})
if query_results is None:
return []
return [
get_song_details(song['id'])
for song in query_results["songs"]['data']
]
def get_song_details(song_id: str) -> Union[SongDetails, None]:
resp = jiosaavn_request({
'__call': "song.getDetails",
'pids': song_id,
# 'ctx': "wap6dot0",
})
if resp is None:
return None
return fix_song_details(resp[song_id])
def get_song_details_from_url(song_url: str) -> SongDetails:
resp = jiosaavn_request({
"__call": "webapi.get",
"token": song_url,
"type": "song"
})
if resp is None:
return None
if type(resp) == dict and len(resp) == 1:
return fix_song_details(resp.popitem()[1])
else:
print("Error", resp)
return None
def fix_song_details(song_details) -> SongDetails:
song_more_details = song_details["more_info"]
default_media_url, media_url = decrypt_url(
song_more_details["encrypted_media_url"])
song_details["media_url"] = media_url
song_details["media_url_default"] = default_media_url
# song_details["media_url"] = check_media_url(decrypt_url(
# song_more_details['encrypted_media_url']))
# song_details["image"] = fix_image_url(song_details["image"])
# song_details["title"] = fix_title(song_details["title"])
# song_more_details["album"] = fix_title(song_more_details["album"])
return SongDetails(
**song_details,
**song_more_details,
is_320kbps = song_more_details["320kbps"]
) # .dict(exclude_none = True)
def get_album_details(album_id: str) -> AlbumDetails:
album_results = jiosaavn_request({
"__call": "content.getAlbumDetails",
"albumid": album_id
})
if album_results is None:
return None
return AlbumDetails(**album_results, songs = list(
map(fix_song_details, album_results["list"])))
def get_album_details_from_url(album_url: str) -> AlbumDetails:
album_results = jiosaavn_request({
"__call": "webapi.get",
"token": album_url,
"type": "album"
})
if album_results is None:
return None
return AlbumDetails(**album_results, songs = list(
map(fix_song_details, album_results["list"])))
def get_playlist_details(playlist_id: str, page_no: int) -> PlaylistDetails:
playlist_details = jiosaavn_request({
"__call": "playlist.getDetails",
"listid": playlist_id,
"p": page_no
})
if playlist_details is None:
return None
return PlaylistDetails(
**playlist_details, **playlist_details["more_info"], songs = list(
map(fix_song_details, playlist_details["list"])))
def get_playlist_details_from_url(
playlist_url: str, page_no: int) -> PlaylistDetails:
playlist_details = jiosaavn_request({
"__call": "webapi.get",
"token": playlist_url,
"type": "playlist",
"p": page_no
})
if playlist_details is None:
return None
return PlaylistDetails(
**playlist_details, **playlist_details["more_info"], songs = list(
map(fix_song_details, playlist_details["list"])))
def get_lyrics(song_id: str):
lyrics_json = jiosaavn_request({
"__call": "lyrics.getLyrics",
"lyrics_id": song_id,
"ctx": "wap6dot0"
})
return lyrics_json
################################################################################
# utility functions
################################################################################
def decrypt_url(url):
enc_url = base64.b64decode(url.strip())
default_dec_url = des_cipher.decrypt(enc_url, padmode = PAD_PKCS5).decode(
'utf-8')
dec_url = default_dec_url.replace("_96.mp4", "_320.mp3")
return default_dec_url, dec_url
def fix_image_url(url):
url = str(url)
if 'http://' in url:
url = url.replace("http://", "https://")
url = url.replace('150x150', '500x500')
return url
def fix_title(title):
title = title.replace('"', '')
return title
def expand_url(url):
try:
session = requests.Session()
resp = session.head(url, allow_redirects = True)
return (resp.url)
except Exception as e:
print("URL Redirect Error: ", e)
return url
def check_media_url(dec_url):
ex_dec_url = expand_url(dec_url)
r = requests.head(ex_dec_url)
if r.status_code != 200:
fixed_dec_url = dec_url.replace(".mp3", '.mp4')
fixed_dec_url = expand_url(fixed_dec_url)
return fixed_dec_url
return ex_dec_url