discord-player-deezer 2.5.0-beta.1 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils/util.ts CHANGED
@@ -1,218 +1,266 @@
1
- import { type Player, Track, Util } from "discord-player";
2
- import type { DeezerExtractor } from "../DeezerExtractor";
3
- import { Readable, PassThrough } from 'stream'
4
- import Blowfish from "blowfish-node";
5
- import { JSDecryptor } from "../Crypto/JSDecryptor";
6
-
7
- const IV = Buffer.from(Array.from({ length: 8 }, (_, x) => x))
8
-
9
- let rawCrypto: typeof import("crypto")
10
-
11
- export async function getCrypto() {
12
- if (!rawCrypto) {
13
- rawCrypto = await import("crypto")
14
- return rawCrypto
15
- }
16
-
17
- return rawCrypto
18
- }
19
-
20
- export function isUrl(query: string) {
21
- try {
22
- const url = new URL(query)
23
- return ['https:', 'http:'].includes(url.protocol)
24
- } catch {
25
- return false
26
- }
27
- }
28
-
29
- const DeezerAPIRoutes = {
30
- searchTrack(query: string, limit?: number) {
31
- const url = `https://api.deezer.com/search/track?q=${encodeURIComponent(query)}&${limit ? `limit=${limit}` : ""}`
32
-
33
- return url
34
- }
35
- } as const
36
-
37
- export async function search(query: string, limit: number = 10) {
38
- const route = DeezerAPIRoutes.searchTrack(query, limit);
39
-
40
- const response = await fetch(route)
41
-
42
- if(!response.status.toString().startsWith("2")) throw new Error("Server responded with a non 2xx status.")
43
-
44
- const jsonTrack = await response.json()
45
-
46
- if(!jsonTrack.data || !Array.isArray(jsonTrack.data) || jsonTrack.data.length === 0) throw new Error("Unable get tracks from Deezer for the query '" + query + "'")
47
-
48
- return jsonTrack as DeezerSearchTrackResponse
49
- }
50
-
51
- export type ArrayOrObject<T> = T | T[]
52
-
53
- export interface DeezerSearchTrackResponse {
54
- data: {
55
- link: string,
56
- title: string,
57
- album: {
58
- cover_xl?: string,
59
- cover_medium?: string,
60
- cover_small?: string,
61
- cover?: string
62
- },
63
- artist: {
64
- name: string
65
- },
66
- duration: number, // in seconds
67
- type: "track"
68
- }[]
69
- }
70
-
71
- export function buildTrackFromSearch(track: DeezerSearchTrackResponse, player: Player, requestedBy?: Track['requestedBy']) {
72
- const tracks = track.data.map((v) => new Track(player, {
73
- source: "arbitrary",
74
- duration: Util.buildTimeCode(Util.parseMS(v.duration * 1000)),
75
- author: Array.isArray(v.artist) ? v.artist.map(a => a.name).join(", ") : v.artist.name,
76
- url: v.link,
77
- title: v.title,
78
- thumbnail: v.album.cover_xl || v.album.cover_medium || v.album.cover || v.album.cover_small || "https://play-lh.googleusercontent.com/xtIOV8iPeAY4GrldTDo3CbLAEpbea2DqnfxaB4Nn2p5qz6KAiumY74qH86pgu1HA1A",
79
- live: false,
80
- requestedBy
81
- }))
82
-
83
- return tracks
84
- }
85
-
86
- export function extractTrackId(query: string) {
87
- if (!validate(query)) throw new Error("Invalid track url")
88
- const trackIdWithUrlParams = query.split("/").at(-1)
89
- if (!trackIdWithUrlParams) throw new Error("Cannot find track ID")
90
- return trackIdWithUrlParams.split("?")[0]
91
- }
92
-
93
- // used for bridging
94
- export async function searchOneTrack(query: string) {
95
- const url = DeezerAPIRoutes.searchTrack(query, 1)
96
-
97
- const trackRes = await fetch(url)
98
- if (trackRes.status !== 200) throw new Error("Fetch failed")
99
-
100
- const trackData = await trackRes.json() as DeezerSearchTrackResponse | undefined
101
- return trackData
102
- }
103
-
104
- export async function streamTrack(track: Track, ext: DeezerExtractor) {
105
- const decryptionKey = ext.options.decryptionKey
106
- if (!decryptionKey) throw new Error("MISSING DEEZER DECRYPTION KEY") // cant decrypt due to missing key
107
-
108
- const crypto = await getCrypto()
109
- const trackId = extractTrackId(track.url)
110
-
111
- const trackHash = crypto.createHash("md5").update(trackId, "ascii").digest("hex")
112
- const trackKey = Buffer.alloc(16)
113
-
114
- const Decryptor = ext.options.decryptor || JSDecryptor
115
-
116
- for (let iter = 0; iter < 16; iter++)
117
- /* tslint:disable-next-line no-bitwise */
118
- trackKey.writeInt8(trackHash[iter].charCodeAt(0) ^ trackHash[iter + 16].charCodeAt(0) ^ decryptionKey[iter].charCodeAt(0), iter)
119
-
120
- const trackInfoRes = await ext.fetch(`https://www.deezer.com/ajax/gw-light.php?method=song.getListData&input=3&api_version=1.0&api_token=${ext.userInfo.csrfToken}`, {
121
- method: "POST",
122
- headers: {
123
- Cookie: `${ext.userInfo.cookie}; arl=${ext.options.arl}`,
124
- 'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
125
- 'DNT': '1'
126
- },
127
- body: JSON.stringify({
128
- sng_ids: [trackId]
129
- })
130
- })
131
-
132
- const songInfo = (await trackInfoRes.json()).results.data[0]
133
-
134
- const streamInfoRes = await fetch('https://media.deezer.com/v1/get_url', {
135
- method: "POST",
136
- body: JSON.stringify({
137
- license_token: ext.userInfo.licenseToken,
138
- media: [{
139
- type: 'FULL',
140
- formats: [{
141
- cipher: 'BF_CBC_STRIPE',
142
- format: 'FLAC'
143
- }, {
144
- cipher: 'BF_CBC_STRIPE',
145
- format: 'MP3_256'
146
- }, {
147
- cipher: 'BF_CBC_STRIPE',
148
- format: 'MP3_128'
149
- }, {
150
- cipher: 'BF_CBC_STRIPE',
151
- format: 'MP3_MISC'
152
- }]
153
- }],
154
- track_tokens: [songInfo.TRACK_TOKEN]
155
- })
156
- })
157
- const streamInfo = await streamInfoRes.json()
158
-
159
- const trackMediaUrl = streamInfo.data[0].media[0].sources[0].url
160
-
161
- ext.context.player.debug("DEEZER FOUND MEDIA URL " + trackMediaUrl)
162
-
163
- const trackReq = await ext.fetch(trackMediaUrl)
164
- // @ts-ignore
165
- const readable = Readable.fromWeb(trackReq.body)
166
- let buffer = Buffer.alloc(0)
167
- let i = 0
168
-
169
- const bufferSize = 2048 // 2mb
170
-
171
- const passThrough = new PassThrough()
172
-
173
- const decryptor = new Decryptor(trackKey, IV)
174
-
175
- readable.on("readable", async () => {
176
- let chunk = null;
177
- while (true) {
178
- chunk = readable.read(bufferSize)
179
-
180
- if (!chunk) {
181
- if (readable.readableLength) {
182
- chunk = readable.read(readable.readableLength)
183
- buffer = Buffer.concat([buffer, chunk])
184
- }
185
- break;
186
- } else {
187
- buffer = Buffer.concat([buffer, chunk])
188
- }
189
-
190
- while (buffer.length >= bufferSize) {
191
- const bufferSized = buffer.subarray(0, bufferSize)
192
-
193
- if (i % 3 === 0) {
194
- const decipher = await decryptor.decrypt(bufferSized)
195
- passThrough.write(decipher)
196
- } else {
197
- passThrough.write(bufferSized)
198
- }
199
-
200
- i++
201
-
202
- buffer = buffer.subarray(bufferSize)
203
- }
204
- }
205
- })
206
-
207
- return passThrough
208
- }
209
-
210
- export const deezerRegex = {
211
- track: /(^https:)\/\/(www\.)?deezer.com\/([a-zA-Z]+\/)?track\/[0-9]+/,
212
- playlistNalbums: /(^https:)\/\/(www\.)?deezer.com\/[a-zA-Z]+\/(playlist|album)\/[0-9]+(\?)?(.*)/,
213
- share: /(^https:)\/\/deezer\.page\.link\/[A-Za-z0-9]+/
214
- } as const;
215
-
216
- export function validate(query: string) {
217
- return deezerRegex.track.test(query) ?? deezerRegex.playlistNalbums.test(query) ?? deezerRegex.share.test(query)
218
- }
1
+ import { type Player, Track, Util } from "discord-player";
2
+ import { PassThrough, Readable } from "stream";
3
+ import { JSDecryptor } from "../Crypto/JSDecryptor";
4
+ import type { DeezerExtractor } from "../DeezerExtractor";
5
+
6
+ const IV = Buffer.from(Array.from({ length: 8 }, (_, x) => x));
7
+
8
+ let rawCrypto: typeof import("crypto");
9
+
10
+ export async function getCrypto() {
11
+ if (!rawCrypto) {
12
+ rawCrypto = await import("crypto");
13
+ return rawCrypto;
14
+ }
15
+
16
+ return rawCrypto;
17
+ }
18
+
19
+ export function isUrl(query: string) {
20
+ try {
21
+ const url = new URL(query);
22
+ return ["https:", "http:"].includes(url.protocol);
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ const DeezerAPIRoutes = {
29
+ searchTrack(query: string, limit?: number) {
30
+ const url = `https://api.deezer.com/search/track?q=${encodeURIComponent(query)}&${limit ? `limit=${limit}` : ""}`;
31
+
32
+ return url;
33
+ },
34
+ } as const;
35
+
36
+ export async function search(query: string, limit: number = 10) {
37
+ const route = DeezerAPIRoutes.searchTrack(query, limit);
38
+
39
+ const response = await fetch(route);
40
+
41
+ if (!response.status.toString().startsWith("2"))
42
+ throw new Error("Server responded with a non 2xx status.");
43
+
44
+ const jsonTrack = await response.json();
45
+
46
+ if (
47
+ !jsonTrack.data ||
48
+ !Array.isArray(jsonTrack.data) ||
49
+ jsonTrack.data.length === 0
50
+ )
51
+ throw new Error(
52
+ "Unable get tracks from Deezer for the query '" + query + "'"
53
+ );
54
+
55
+ return jsonTrack as DeezerSearchTrackResponse;
56
+ }
57
+
58
+ export type ArrayOrObject<T> = T | T[];
59
+
60
+ export interface DeezerSearchTrackResponse {
61
+ data: {
62
+ link: string;
63
+ title: string;
64
+ album: {
65
+ cover_xl?: string;
66
+ cover_medium?: string;
67
+ cover_small?: string;
68
+ cover?: string;
69
+ };
70
+ artist: {
71
+ name: string;
72
+ };
73
+ duration: number; // in seconds
74
+ type: "track";
75
+ }[];
76
+ }
77
+
78
+ export function buildTrackFromSearch(
79
+ track: DeezerSearchTrackResponse,
80
+ player: Player,
81
+ requestedBy?: Track["requestedBy"]
82
+ ) {
83
+ const tracks = track.data.map(
84
+ (v) =>
85
+ new Track(player, {
86
+ source: "arbitrary",
87
+ duration: Util.buildTimeCode(Util.parseMS(v.duration * 1000)),
88
+ author: Array.isArray(v.artist)
89
+ ? v.artist.map((a) => a.name).join(", ")
90
+ : v.artist.name,
91
+ url: v.link,
92
+ title: v.title,
93
+ thumbnail:
94
+ v.album.cover_xl ||
95
+ v.album.cover_medium ||
96
+ v.album.cover ||
97
+ v.album.cover_small ||
98
+ "https://play-lh.googleusercontent.com/xtIOV8iPeAY4GrldTDo3CbLAEpbea2DqnfxaB4Nn2p5qz6KAiumY74qH86pgu1HA1A",
99
+ live: false,
100
+ requestedBy,
101
+ })
102
+ );
103
+
104
+ return tracks;
105
+ }
106
+
107
+ export function extractTrackId(query: string) {
108
+ if (!validate(query)) throw new Error("Invalid track url");
109
+ const trackIdWithUrlParams = query.split("/").at(-1);
110
+ if (!trackIdWithUrlParams) throw new Error("Cannot find track ID");
111
+ return trackIdWithUrlParams.split("?")[0];
112
+ }
113
+
114
+ // used for bridging
115
+ export async function searchOneTrack(query: string) {
116
+ const url = DeezerAPIRoutes.searchTrack(query, 1);
117
+
118
+ const trackRes = await fetch(url);
119
+ if (trackRes.status !== 200) throw new Error("Fetch failed");
120
+
121
+ const trackData = (await trackRes.json()) as
122
+ | DeezerSearchTrackResponse
123
+ | undefined;
124
+ return trackData;
125
+ }
126
+
127
+ export async function streamTrack(track: Track, ext: DeezerExtractor) {
128
+ const decryptionKey = ext.options.decryptionKey;
129
+ if (!decryptionKey) throw new Error("MISSING DEEZER DECRYPTION KEY"); // cant decrypt due to missing key
130
+
131
+ const crypto = await getCrypto();
132
+ const trackId = extractTrackId(track.url);
133
+
134
+ const trackHash = crypto
135
+ .createHash("md5")
136
+ .update(trackId, "ascii")
137
+ .digest("hex");
138
+ const trackKey = Buffer.alloc(16);
139
+
140
+ const Decryptor = ext.options.decryptor || JSDecryptor;
141
+
142
+ for (let iter = 0; iter < 16; iter++)
143
+ trackKey.writeInt8(
144
+ /* tslint:disable-next-line no-bitwise */
145
+ trackHash[iter].charCodeAt(0) ^
146
+ /* tslint:disable-next-line no-bitwise */
147
+ trackHash[iter + 16].charCodeAt(0) ^
148
+ decryptionKey[iter].charCodeAt(0),
149
+ iter
150
+ );
151
+
152
+ const trackInfoRes = await ext.fetch(
153
+ `https://www.deezer.com/ajax/gw-light.php?method=song.getListData&input=3&api_version=1.0&api_token=${ext.userInfo.csrfToken}`,
154
+ {
155
+ method: "POST",
156
+ headers: {
157
+ Cookie: `${ext.userInfo.cookie}; arl=${ext.options.arl}`,
158
+ "User-Agent":
159
+ "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
160
+ DNT: "1",
161
+ },
162
+ body: JSON.stringify({
163
+ sng_ids: [trackId],
164
+ }),
165
+ }
166
+ );
167
+
168
+ const songInfo = (await trackInfoRes.json()).results.data[0];
169
+
170
+ const streamInfoRes = await fetch("https://media.deezer.com/v1/get_url", {
171
+ method: "POST",
172
+ body: JSON.stringify({
173
+ license_token: ext.userInfo.licenseToken,
174
+ media: [
175
+ {
176
+ type: "FULL",
177
+ formats: [
178
+ {
179
+ cipher: "BF_CBC_STRIPE",
180
+ format: "FLAC",
181
+ },
182
+ {
183
+ cipher: "BF_CBC_STRIPE",
184
+ format: "MP3_256",
185
+ },
186
+ {
187
+ cipher: "BF_CBC_STRIPE",
188
+ format: "MP3_128",
189
+ },
190
+ {
191
+ cipher: "BF_CBC_STRIPE",
192
+ format: "MP3_MISC",
193
+ },
194
+ ],
195
+ },
196
+ ],
197
+ track_tokens: [songInfo.TRACK_TOKEN],
198
+ }),
199
+ });
200
+ const streamInfo = await streamInfoRes.json();
201
+
202
+ const trackMediaUrl = streamInfo.data[0].media[0].sources[0].url;
203
+
204
+ ext.context.player.debug("DEEZER FOUND MEDIA URL " + trackMediaUrl);
205
+
206
+ const trackReq = await ext.fetch(trackMediaUrl);
207
+ // @ts-ignore
208
+ const readable = Readable.fromWeb(trackReq.body);
209
+ let buffer = Buffer.alloc(0);
210
+ let i = 0;
211
+
212
+ const bufferSize = 2048; // 2mb
213
+
214
+ const passThrough = new PassThrough();
215
+
216
+ const decryptor = new Decryptor(trackKey, IV);
217
+
218
+ readable.on("readable", async () => {
219
+ let chunk = null;
220
+ while (true) {
221
+ chunk = readable.read(bufferSize);
222
+
223
+ if (!chunk) {
224
+ if (readable.readableLength) {
225
+ chunk = readable.read(readable.readableLength);
226
+ buffer = Buffer.concat([buffer, chunk]);
227
+ }
228
+ break;
229
+ } else {
230
+ buffer = Buffer.concat([buffer, chunk]);
231
+ }
232
+
233
+ while (buffer.length >= bufferSize) {
234
+ const bufferSized = buffer.subarray(0, bufferSize);
235
+
236
+ if (i % 3 === 0) {
237
+ const decipher = await decryptor.decrypt(bufferSized);
238
+ passThrough.write(decipher);
239
+ } else {
240
+ passThrough.write(bufferSized);
241
+ }
242
+
243
+ i++;
244
+
245
+ buffer = buffer.subarray(bufferSize);
246
+ }
247
+ }
248
+ });
249
+
250
+ return passThrough;
251
+ }
252
+
253
+ export const deezerRegex = {
254
+ track: /(^https:)\/\/(www\.)?deezer.com\/([a-zA-Z]+\/)?track\/[0-9]+/,
255
+ playlistNalbums:
256
+ /(^https:)\/\/(www\.)?deezer.com\/[a-zA-Z]+\/(playlist|album)\/[0-9]+(\?)?(.*)/,
257
+ share: /(^https:)\/\/dzr\.page\.link\/[A-Za-z0-9]+/,
258
+ } as const;
259
+
260
+ export function validate(query: string) {
261
+ return (
262
+ deezerRegex.track.test(query) ??
263
+ deezerRegex.playlistNalbums.test(query) ??
264
+ deezerRegex.share.test(query)
265
+ );
266
+ }
package/tsconfig.json CHANGED
@@ -1,25 +1,25 @@
1
- {
2
- "$schema": "https://json.schemastore.org/tsconfig",
3
- "display": "Default",
4
- "compilerOptions": {
5
- "target": "ES2020",
6
- "moduleResolution": "node",
7
- "module": "commonjs",
8
- "declaration": true,
9
- "outDir": "./dist",
10
- "strict": true,
11
- "strictNullChecks": true,
12
- "esModuleInterop": true,
13
- "pretty": true,
14
- "skipLibCheck": true,
15
- "skipDefaultLibCheck": true,
16
- "forceConsistentCasingInFileNames": true
17
- },
18
- "exclude": [
19
- "node_modules",
20
- "dist/**/*.ts"
21
- ],
22
- "include": [
23
- "./src/**/*.ts"
24
- ]
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "display": "Default",
4
+ "compilerOptions": {
5
+ "target": "ES2020",
6
+ "moduleResolution": "node",
7
+ "module": "commonjs",
8
+ "declaration": true,
9
+ "outDir": "./dist",
10
+ "strict": true,
11
+ "strictNullChecks": true,
12
+ "esModuleInterop": true,
13
+ "pretty": true,
14
+ "skipLibCheck": true,
15
+ "skipDefaultLibCheck": true,
16
+ "forceConsistentCasingInFileNames": true
17
+ },
18
+ "exclude": [
19
+ "node_modules",
20
+ "dist/**/*.ts"
21
+ ],
22
+ "include": [
23
+ "./src/**/*.ts"
24
+ ]
25
25
  }
package/tslint.json CHANGED
@@ -1,3 +1,3 @@
1
- {
2
- "extends": ["tslint:recommended", "tslint-config-prettier"]
1
+ {
2
+ "extends": ["tslint:recommended", "tslint-config-prettier"]
3
3
  }
package/tsup.config.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { defineConfig } from "tsup"
2
-
3
- export default defineConfig({
4
- format: "cjs",
5
- entry: ['./src/index.ts'],
6
- outDir: "./dist",
7
- skipNodeModulesBundle: true,
8
- dts: true
1
+ import { defineConfig } from "tsup"
2
+
3
+ export default defineConfig({
4
+ format: "cjs",
5
+ entry: ['./src/index.ts'],
6
+ outDir: "./dist",
7
+ skipNodeModulesBundle: true,
8
+ dts: true
9
9
  })