discord-player-deezer 2.6.0 → 3.0.0-dev.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,266 +1,274 @@
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
- }
1
+ import { type Player, Track, Util } from "discord-player";
2
+ import { Readable } from "stream";
3
+ import { CacheTapStream } from "../Cache/CacheTapStream";
4
+ import { JSDecryptor } from "../Crypto/JSDecryptor";
5
+ import { StripeDecryptStream } from "../Crypto/StripeDecryptStream";
6
+ import type { DeezerExtractor } from "../DeezerExtractor";
7
+ import { getCrypto } from "./crypto";
8
+
9
+ export { getCrypto } from "./crypto";
10
+
11
+ const IV = Buffer.from(Array.from({ length: 8 }, (_, x) => x));
12
+
13
+ export function isUrl(query: string) {
14
+ try {
15
+ const url = new URL(query);
16
+ return ["https:", "http:"].includes(url.protocol);
17
+ } catch {
18
+ return false;
19
+ }
20
+ }
21
+
22
+ const DeezerAPIRoutes = {
23
+ searchTrack(query: string, limit?: number) {
24
+ const url = `https://api.deezer.com/search/track?q=${encodeURIComponent(query)}&${limit ? `limit=${limit}` : ""}`;
25
+
26
+ return url;
27
+ },
28
+ } as const;
29
+
30
+ export async function search(query: string, limit: number = 10) {
31
+ const route = DeezerAPIRoutes.searchTrack(query, limit);
32
+
33
+ const response = await fetch(route);
34
+
35
+ if (!response.status.toString().startsWith("2"))
36
+ throw new Error("Server responded with a non 2xx status.");
37
+
38
+ const jsonTrack = await response.json();
39
+
40
+ if (
41
+ !jsonTrack.data ||
42
+ !Array.isArray(jsonTrack.data) ||
43
+ jsonTrack.data.length === 0
44
+ )
45
+ throw new Error(
46
+ "Unable get tracks from Deezer for the query '" + query + "'"
47
+ );
48
+
49
+ return jsonTrack as DeezerSearchTrackResponse;
50
+ }
51
+
52
+ export type ArrayOrObject<T> = T | T[];
53
+
54
+ export interface DeezerSearchTrackResponse {
55
+ data: {
56
+ link: string;
57
+ title: string;
58
+ album: {
59
+ cover_xl?: string;
60
+ cover_medium?: string;
61
+ cover_small?: string;
62
+ cover?: string;
63
+ };
64
+ artist: {
65
+ name: string;
66
+ };
67
+ duration: number; // in seconds
68
+ type: "track";
69
+ }[];
70
+ }
71
+
72
+ export function buildTrackFromSearch(
73
+ track: DeezerSearchTrackResponse,
74
+ player: Player,
75
+ requestedBy?: Track["requestedBy"]
76
+ ) {
77
+ const tracks = track.data.map(
78
+ (v) =>
79
+ new Track(player, {
80
+ source: "arbitrary",
81
+ duration: Util.buildTimeCode(Util.parseMS(v.duration * 1000)),
82
+ author: Array.isArray(v.artist)
83
+ ? v.artist.map((a) => a.name).join(", ")
84
+ : v.artist.name,
85
+ url: v.link,
86
+ title: v.title,
87
+ thumbnail:
88
+ v.album.cover_xl ||
89
+ v.album.cover_medium ||
90
+ v.album.cover ||
91
+ v.album.cover_small ||
92
+ "https://play-lh.googleusercontent.com/xtIOV8iPeAY4GrldTDo3CbLAEpbea2DqnfxaB4Nn2p5qz6KAiumY74qH86pgu1HA1A",
93
+ live: false,
94
+ requestedBy,
95
+ })
96
+ );
97
+
98
+ return tracks;
99
+ }
100
+
101
+ export function extractTrackId(query: string) {
102
+ if (!validate(query)) throw new Error("Invalid track url");
103
+ const trackIdWithUrlParams = query.split("/").at(-1);
104
+ if (!trackIdWithUrlParams) throw new Error("Cannot find track ID");
105
+ return trackIdWithUrlParams.split("?")[0];
106
+ }
107
+
108
+ // used for bridging
109
+ export async function searchOneTrack(query: string) {
110
+ const url = DeezerAPIRoutes.searchTrack(query, 1);
111
+
112
+ const trackRes = await fetch(url);
113
+ if (trackRes.status !== 200) throw new Error("Fetch failed");
114
+
115
+ const trackData = (await trackRes.json()) as
116
+ | DeezerSearchTrackResponse
117
+ | undefined;
118
+ return trackData;
119
+ }
120
+
121
+ export async function streamTrack(track: Track, ext: DeezerExtractor) {
122
+ const cache = ext.options.cache;
123
+ const trackId = extractTrackId(track.url);
124
+
125
+ if (cache) {
126
+ try {
127
+ const cached = await cache.read(trackId);
128
+
129
+ if (cached) {
130
+ ext.context.player.debug(`DEEZER CACHE HIT ${trackId}`);
131
+ return cached;
132
+ }
133
+ } catch (error) {
134
+ ext.context.player.debug(`DEEZER CACHE READ ERROR ${String(error)}`);
135
+ }
136
+ }
137
+
138
+ const decryptionKey = ext.options.decryptionKey;
139
+ if (!decryptionKey) throw new Error("MISSING DEEZER DECRYPTION KEY"); // cant decrypt due to missing key
140
+
141
+ const crypto = await getCrypto();
142
+
143
+ const trackHash = crypto
144
+ .createHash("md5")
145
+ .update(trackId, "ascii")
146
+ .digest("hex");
147
+ const trackKey = Buffer.alloc(16);
148
+
149
+ const Decryptor = ext.options.decryptor || JSDecryptor;
150
+
151
+ for (let iter = 0; iter < 16; iter++)
152
+ trackKey.writeInt8(
153
+ /* tslint:disable-next-line no-bitwise */
154
+ trackHash[iter].charCodeAt(0) ^
155
+ /* tslint:disable-next-line no-bitwise */
156
+ trackHash[iter + 16].charCodeAt(0) ^
157
+ decryptionKey[iter].charCodeAt(0),
158
+ iter
159
+ );
160
+
161
+ const trackInfoRes = await ext.fetch(
162
+ `https://www.deezer.com/ajax/gw-light.php?method=song.getListData&input=3&api_version=1.0&api_token=${ext.userInfo.csrfToken}`,
163
+ {
164
+ method: "POST",
165
+ headers: {
166
+ Cookie: `${ext.userInfo.cookie}; arl=${ext.options.arl}`,
167
+ "User-Agent":
168
+ "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
169
+ DNT: "1",
170
+ },
171
+ body: JSON.stringify({
172
+ sng_ids: [trackId],
173
+ }),
174
+ }
175
+ );
176
+
177
+ const songInfo = (await trackInfoRes.json()).results.data[0];
178
+
179
+ const streamInfoRes = await fetch("https://media.deezer.com/v1/get_url", {
180
+ method: "POST",
181
+ body: JSON.stringify({
182
+ license_token: ext.userInfo.licenseToken,
183
+ media: [
184
+ {
185
+ type: "FULL",
186
+ formats: [
187
+ {
188
+ cipher: "BF_CBC_STRIPE",
189
+ format: "FLAC",
190
+ },
191
+ {
192
+ cipher: "BF_CBC_STRIPE",
193
+ format: "MP3_256",
194
+ },
195
+ {
196
+ cipher: "BF_CBC_STRIPE",
197
+ format: "MP3_128",
198
+ },
199
+ {
200
+ cipher: "BF_CBC_STRIPE",
201
+ format: "MP3_MISC",
202
+ },
203
+ ],
204
+ },
205
+ ],
206
+ track_tokens: [songInfo.TRACK_TOKEN],
207
+ }),
208
+ });
209
+ const streamInfo = await streamInfoRes.json();
210
+
211
+ const trackMediaUrl = streamInfo.data[0].media[0].sources[0].url;
212
+
213
+ ext.context.player.debug("DEEZER FOUND MEDIA URL " + trackMediaUrl);
214
+
215
+ const trackReq = await ext.fetch(trackMediaUrl);
216
+ // @ts-ignore
217
+ const readable = Readable.fromWeb(trackReq.body);
218
+
219
+ const decryptor = new Decryptor(trackKey, IV);
220
+ const stream = new StripeDecryptStream(decryptor);
221
+
222
+ // Piping (instead of draining in a "readable" listener) applies
223
+ // backpressure: the body is only pulled as the player consumes it, so a
224
+ // slow consumer won't cause the whole track to be downloaded into memory.
225
+ readable.on("error", (error) => stream.destroy(error));
226
+ readable.pipe(stream);
227
+
228
+ // Release the HTTP body if the consumer aborts before the track ends.
229
+ stream.once("close", () => {
230
+ if (!stream.readableEnded && !readable.destroyed) readable.destroy();
231
+ });
232
+
233
+ if (!cache) return stream;
234
+
235
+ try {
236
+ const sink = await cache.write(trackId);
237
+
238
+ sink.on("error", (error) => {
239
+ ext.context.player.debug(`DEEZER CACHE WRITE ERROR ${String(error)}`);
240
+ });
241
+
242
+ const output = new CacheTapStream(sink);
243
+ stream.on("error", (error) => output.destroy(error));
244
+
245
+ // On abort, discard the partial cache entry and tear down the pipeline.
246
+ output.once("close", () => {
247
+ if (output.readableEnded) return;
248
+ if (!stream.destroyed) stream.destroy();
249
+ if (!readable.destroyed) readable.destroy();
250
+ });
251
+
252
+ stream.pipe(output);
253
+
254
+ return output;
255
+ } catch (error) {
256
+ ext.context.player.debug(`DEEZER CACHE WRITE ERROR ${String(error)}`);
257
+ return stream;
258
+ }
259
+ }
260
+
261
+ export const deezerRegex = {
262
+ track: /(^https:)\/\/(www\.)?deezer.com\/([a-zA-Z]+\/)?track\/[0-9]+/,
263
+ playlistNalbums:
264
+ /(^https:)\/\/(www\.)?deezer.com\/[a-zA-Z]+\/(playlist|album)\/[0-9]+(\?)?(.*)/,
265
+ share: /(^https:)\/\/dzr\.page\.link\/[A-Za-z0-9]+/,
266
+ } as const;
267
+
268
+ export function validate(query: string) {
269
+ return (
270
+ deezerRegex.track.test(query) ??
271
+ deezerRegex.playlistNalbums.test(query) ??
272
+ deezerRegex.share.test(query)
273
+ );
274
+ }
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
  })