|
1 | 1 | import axios from 'axios'; |
2 | 2 | import SpotifyWebApi from 'spotify-web-api-node'; |
3 | 3 | import PQueue from 'p-queue'; |
| 4 | +import {TOTP} from 'otpauth'; |
| 5 | +import {base32} from '@scure/base'; |
4 | 6 | import {isrc2deezer, upc2deezer} from './deezer'; |
5 | 7 | import type {playlistInfo, trackType} from '../types'; |
6 | 8 |
|
@@ -35,18 +37,59 @@ const queue = new PQueue({concurrency: 25}); |
35 | 37 | /** |
36 | 38 | * Export core spotify module |
37 | 39 | */ |
38 | | -export const spotifyApi = new SpotifyWebApi(); |
| 40 | +export let spotifyApi = new SpotifyWebApi(); |
| 41 | + |
| 42 | +/** |
| 43 | + * Generate Spotify auth TOTP |
| 44 | + */ |
| 45 | +const generateTotp = async (): Promise<string> => { |
| 46 | + const secretSauce = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; |
| 47 | + const secretCipherBytes = [12, 56, 76, 33, 88, 44, 88, 33, 78, 78, 11, 66, 22, 22, 55, 69, 54].map( |
| 48 | + (e, t) => e ^ ((t % 33) + 9), |
| 49 | + ); |
| 50 | + |
| 51 | + const secretBytes = new TextEncoder().encode(secretCipherBytes.join('')); |
| 52 | + |
| 53 | + const secret = base32.encode(secretBytes); |
| 54 | + |
| 55 | + const response = await axios.get('https://open.spotify.com/server-time'); |
| 56 | + const serverTimeSeconds = response.data.serverTime; |
| 57 | + |
| 58 | + const totp = new TOTP({ |
| 59 | + algorithm: 'SHA1', |
| 60 | + digits: 6, |
| 61 | + period: 30, |
| 62 | + secret: secret, |
| 63 | + }); |
| 64 | + |
| 65 | + const otp = totp.generate(serverTimeSeconds); |
| 66 | + |
| 67 | + return otp; |
| 68 | +}; |
39 | 69 |
|
40 | 70 | /** |
41 | 71 | * Set spotify tokens anonymously. This is required to bypass api limits. |
42 | 72 | * @returns {tokensType} |
43 | 73 | */ |
44 | 74 | export const setSpotifyAnonymousToken = async () => { |
45 | | - const {data} = await axios.get<tokensType>( |
46 | | - 'https://open.spotify.com/get_access_token?reason=transport&productType=embed', |
47 | | - ); |
48 | | - spotifyApi.setAccessToken(data.accessToken); |
49 | | - return data; |
| 75 | + const timestamp = Math.floor(Date.now() / 1000); |
| 76 | + const totp = await generateTotp(); |
| 77 | + |
| 78 | + for (let i = 0; i <= 10; i++) { |
| 79 | + const {data} = await axios.get<tokensType>( |
| 80 | + `https://open.spotify.com/get_access_token?reason=transport&productType=web_player&totp=${totp}&totpVer=5&ts=${timestamp}`, |
| 81 | + ); |
| 82 | + |
| 83 | + if (data.accessToken.includes('_') || data.accessToken.includes('-')) { |
| 84 | + spotifyApi = new SpotifyWebApi({ |
| 85 | + clientId: data.clientId, |
| 86 | + }); |
| 87 | + |
| 88 | + spotifyApi.setAccessToken(data.accessToken); |
| 89 | + return data; |
| 90 | + } |
| 91 | + } |
| 92 | + throw new Error('Unable to find a valid Spotify access token'); |
50 | 93 | }; |
51 | 94 |
|
52 | 95 | /** |
|
0 commit comments