-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtidalApi.ts
428 lines (364 loc) · 12.1 KB
/
tidalApi.ts
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
import axios, { AxiosError } from 'axios'
import adapter from 'axios/lib/adapters/http'
import { APIParser } from './apiParser'
import { URL, URLSearchParams } from 'url'
import { CacheHandler } from './cacheHandler'
import { Song, Playlist } from '@moosync/moosync-types'
import { resolve } from 'path'
const API_V2 = 'https://api.tidal.com/v2'
const API_V1 = 'https://api.tidalhifi.com/v1'
const API_V1_ALT = 'https://api.tidal.com/v1'
const LISTEN_TIDAL = 'https://listen.tidal.com/v1'
const AUTH_URL = 'https://auth.tidal.com/v1/oauth2'
const API_KEY = { clientId: '7m7Ap0JC9j1cOM3n', clientSecret: 'vRAdA108tlvkJpTsGZS8rGZ7xTlbJ0qaZ2K9saEzsgY=' }
export class TidalAPI {
private axios = axios.create({ adapter })
private _countryCode?: string = 'GB'
private _accessToken?: string
private _refreshToken?: string
private _deviceCode?: string
private _sessionId?: string
private accountId?: string
private parser = new APIParser()
private cacheHandler = new CacheHandler('./tidal.cache', false)
public get isLoggedIn() {
return !!this.accessToken
}
public get refreshToken() {
return this._refreshToken
}
public set refreshToken(token: string | undefined) {
this._refreshToken = token
}
public get countryCode() {
return this._countryCode
}
public set countryCode(code: string | undefined) {
this._countryCode = code
}
public get deviceCode() {
return this._deviceCode
}
public get sessionId() {
return this._sessionId
}
public set sessionId(id: string) {
this._sessionId = id
}
public set deviceCode(code: string | undefined) {
this._deviceCode = code
}
public set accessToken(token: string | undefined) {
this._accessToken = token
if (!token) {
this.accountId = undefined
this.countryCode = undefined
this._refreshToken = undefined
}
}
public get accessToken() {
return this._accessToken
}
public async clearCache() {
await this.cacheHandler.clearCache()
}
public async performDeviceAuthorization() {
try {
const res = await this.axios.post<TidalResponses.DeviceAuth.Root>(
`${AUTH_URL}/device_authorization`,
new URLSearchParams({
client_id: API_KEY.clientId,
scope: 'r_usr+w_usr+w_sub'
})
)
this.deviceCode = res.data.deviceCode
return res.data.verificationUriComplete
} catch (e) {
console.error('Tidal device authorization failed', (e as AxiosError).code, (e as AxiosError).message)
}
}
public async performLogin() {
try {
const data = new URLSearchParams({
client_id: API_KEY.clientId,
scope: 'r_usr+w_usr+w_sub'
})
if (this.refreshToken) {
data.set('refresh_token', this.refreshToken)
data.set('grant_type', 'refresh_token')
} else {
data.set('device_code', this.deviceCode)
data.set('grant_type', 'urn:ietf:params:oauth:grant-type:device_code')
}
const res = await this.axios.post<TidalResponses.LoginAuth.Root>(`${AUTH_URL}/token`, data, {
auth: {
username: API_KEY.clientId,
password: API_KEY.clientSecret
}
})
this.accessToken = res.data.access_token
this.countryCode = res.data.user.countryCode
this.accountId = res.data.user.userId.toString()
this.refreshToken = res.data.refresh_token
return {
refreshToken: res.data.refresh_token,
accessToken: res.data.access_token,
countryCode: res.data.user.countryCode,
username: res.data.user.fullName ?? res.data.user.username
}
} catch (e) {
if ((e as AxiosError).isAxiosError) {
console.error('Tidal authorization failed', (e as AxiosError).code, (e as AxiosError).response.data)
if (((e as AxiosError).response.data as any).sub_status === 1002) {
return 1
}
} else {
console.error('Something went wrong', e)
}
}
return 0
}
private async get<T>(path: string, query?: any, customUrl?: string): Promise<T> {
const cacheId = `${customUrl ?? API_V1}/${path}/${JSON.stringify(query)}`
const cache = this.cacheHandler.getCache(cacheId)
if (cache) {
return JSON.parse(cache) as T
}
let optionalParams = {
countryCode: this.countryCode
}
let headers = {
authorization: `Bearer ${this.accessToken}`,
'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
}
if (path.includes('playbackinfopostpaywall')) {
optionalParams['streamingsessionid'] = this.sessionId
headers['X-Tidal-SessionID'] = this.sessionId
} else {
optionalParams['locale'] = 'en_US'
optionalParams['deviceType'] = 'BROWSER'
}
try {
const resp = await this.axios.get<T>(`${customUrl ?? API_V1}/${path}`, {
params: {
...query,
...optionalParams
},
headers
})
this.cacheHandler.addToCache(cacheId, JSON.stringify(resp?.data))
return resp?.data
} catch (e) {
console.error(
customUrl ?? API_V1 + '/' + path,
query,
optionalParams,
(e as AxiosError).code,
(e as AxiosError).response?.data
)
throw new Error('Failed to fetch from Tidal API')
}
}
public async getSessionId() {
try {
const resp = await this.get<{ sessionId: string }>('sessions')
this.sessionId = resp.sessionId
console.log(resp)
} catch (e) {
console.error(e)
}
}
private async getFavoriteTracks() {
const resp = await this.get<TidalResponses.PlaylistItems.Root>(`users/${this.accountId}/favorites/tracks`)
return this.parser.parseTracks(...resp.items.map((val) => val.item))
}
public async getPlaylists(): Promise<Playlist[]> {
const resp = await this.get<TidalResponses.Playlists.Root>(
'my-collection/playlists/folders',
{
folderId: 'root',
offset: 0,
limit: 50,
order: 'DATE',
orderDirection: 'DESC',
includeOnly: 'PLAYLIST'
},
API_V2
)
return [
...this.parser.parsePlaylists(...resp.items.map((val) => val.data)),
{
playlist_id: 'favorite',
playlist_name: 'Favorite Tracks',
playlist_song_count: 0,
playlist_coverPath: resolve(__dirname, '../assets/favorite.svg')
}
]
}
public async getPlaylistItems(playlistID: string) {
if (playlistID === 'favorite') {
return await this.getFavoriteTracks()
} else {
const resp = await this.get<TidalResponses.PlaylistItems.Root>(`playlists/${playlistID}/items`, {
offset: 0,
limit: 50
})
return this.parser.parseTracks(...resp.items.map((val) => val.item))
}
}
public async getStreamURL(songId: string, quality: string, tries = 0): Promise<string | undefined> {
if (!this.sessionId) {
await this.getSessionId()
}
if (tries < 2) {
try {
const resp = await this.get<TidalResponses.StreamDetails.Root>(`tracks/${songId}/playbackinfopostpaywall`, {
audioquality: quality,
playbackmode: 'STREAM',
assetpresentation: 'FULL'
})
if (resp.manifest) {
const decoded = Buffer.from(resp.manifest, 'base64').toString('utf-8')
return decoded
}
} catch (e) {
console.error(e)
return this.getStreamURL(songId, 'HI_RES', tries + 1)
}
}
}
private matchTidalHostname(url: URL) {
return url.hostname === 'tidal.com' || url.hostname === 'listen.tidal.com'
}
public async getTrackIfValid(url: string) {
try {
const parsed = new URL(url)
//https://tidal.com/browse/track/34156240
if (this.matchTidalHostname(parsed) && parsed.pathname.includes('/track/')) {
const trackId = parsed.pathname.substring(parsed.pathname.lastIndexOf('/') + 1)
const song = await this.getTrack(trackId)
return song
}
} catch (e) {
console.debug('Invalid URL', url, (e as Error).name)
}
}
public async getPlaylistIfValid(url: string) {
try {
const parsed = new URL(url)
//https://tidal.com/browse/playlist/48fb1098-5be4-4570-b95b-91c8f9bf4814
//https://listen.tidal.com/playlist/48fb1098-5be4-4570-b95b-91c8f9bf4814
if (this.matchTidalHostname(parsed) && parsed.pathname.includes('/playlist/')) {
const playlistId = parsed.pathname.substring(parsed.pathname.lastIndexOf('/') + 1)
const resp = await this.getPlaylist(playlistId)
return resp
}
} catch (e) {
console.debug('Invalid URL', url, (e as Error).name)
}
}
public async getLyrics(id: string) {
try {
// const resp = await this.get<TidalResponses.Lyrics.Root>(`tracks/${id}/lyrics`, {}, LISTEN_TIDAL)
// return resp.lyrics
} catch (e) {
console.error(e)
}
}
private async getTrack(id: number | string) {
const resp = await this.get<TidalResponses.SingleTrack.Root>('tracks/' + id.toString())
return this.parser.parseTracks(resp)[0]
}
private async getPlaylist(id: string) {
const resp = await this.get<TidalResponses.Playlists.Data>('playlists/' + id)
const playlist = this.parser.parsePlaylists(resp)[0]
if (playlist) {
const songs = await this.getPlaylistItems(id)
return { playlist, songs }
}
}
public async search(term: string) {
const resp = await this.get<TidalResponses.SearchResults.Root>('search', {
query: term,
offset: 0,
limit: 50,
types: ['TRACKS', 'ARTISTS', 'ALBUMS', 'PLAYLIST']
})
const songs = this.parser.parseTracks(...resp.tracks.items)
const artists = this.parser.parseArtists(...resp.artists.items)
const playlists = this.parser.parsePlaylists(...resp.playlists.items)
const albums = this.parser.parseAlbums(...resp.albums.items)
return { songs, artists, playlists, albums }
}
public async getRecommendations() {
const songList: Song[] = []
const songs = await api.getSongs({ song: { extension: 'moosync.tidal' } })
for (const s of songs) {
const recommendations = await this.get<TidalResponses.Recommendations.Root>(
`tracks/${s._id.replace('moosync.tidal:', '')}/recommendations`,
{
limit: 20,
offset: 0
}
)
songList.push(...this.parser.parseTracks(...recommendations.items.map((val) => val.track)))
}
const data = await this.get<TidalResponses.Pages.Root>('pages/staff_picks', {}, LISTEN_TIDAL)
const filteredModules = data.rows.filter(
(val) => val.modules.filter((val2) => val2.type === 'TRACK_LIST').length > 0
)
for (const moduleList of filteredModules) {
for (const module of moduleList.modules) {
if (module.showMore) {
const fetch = await this.get<TidalResponses.Pages.Root>(module.showMore.apiPath, {}, LISTEN_TIDAL)
const tracks = fetch.rows[0].modules[0].pagedList.items
songList.push(...this.parser.parseTracks(...tracks))
}
}
}
return songList
}
public async searchArtists(term: string) {
const resp = await this.get<TidalResponses.SearchResults.Root>('search', {
query: term,
offset: 0,
limit: 50,
types: ['ARTISTS']
})
return this.parser.parseArtists(...resp.artists.items)
}
public async searchAlbums(term: string) {
const resp = await this.get<TidalResponses.SearchResults.Root>('search', {
query: term,
offset: 0,
limit: 50,
types: ['ALBUMS']
})
return this.parser.parseAlbums(...resp.albums.items)
}
public async getArtistSongs(artistId: string) {
const resp = await this.get<TidalResponses.ArtistSongs.Root>(
'pages/data/25b47120-6a2f-4dbb-8a38-daa415367d22',
{
artistId,
limit: 50,
offset: 0
},
LISTEN_TIDAL
)
return this.parser.parseTracks(...resp.items)
}
public async getAlbumSongs(albumId: string) {
const resp = await this.get<TidalResponses.AlbumSongs.Root>(
'pages/data/2fbf68c2-dc58-49b1-b1be-6958e66383f3',
{
albumId,
limit: 50,
offset: 0
},
LISTEN_TIDAL
)
return this.parser.parseTracks(...resp.items.map((val) => val.item))
}
}