discord-player-deezer 2.5.0 → 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.
@@ -1,259 +1,259 @@
1
- import {
2
- Playlist as DeezerPlaylist,
3
- Track as DeezerTrack,
4
- getData,
5
- } from "@mithron/deezer-music-metadata";
6
- import {
7
- BaseExtractor,
8
- Util as DPUtil,
9
- ExtractorInfo,
10
- ExtractorSearchContext,
11
- ExtractorStreamable,
12
- Playlist,
13
- SearchQueryType,
14
- Track,
15
- } from "discord-player";
16
- import { setTimeout } from "node:timers/promises";
17
- import { BaseDecryptor } from "./Crypto/BaseDecryptor";
18
- import {
19
- buildTrackFromSearch,
20
- deezerRegex,
21
- getCrypto,
22
- isUrl,
23
- search,
24
- searchOneTrack,
25
- streamTrack,
26
- validate,
27
- } from "./utils/util";
28
-
29
- /**
30
- * -------------------------------NOTICE-------------------------------------
31
- * STREAMING CODE IS MAINLY TAKEN FROM https://github.com/PerformanC/NodeLink
32
- * WHICH HAS THE "BSD 2-Clause "Simplified" License"
33
- *
34
- * PLEASE SHOW THE ORIGINAL AUTHOR SUPPORT BY STARING HIS GITHUB REPO
35
- * --------------------------------------------------------------------------
36
- */
37
-
38
- export type DeezerExtractorOptions = {
39
- decryptionKey?: string; // needed for decrypting deezer songs
40
- createStream?: (
41
- track: Track,
42
- ext: DeezerExtractor
43
- ) => Promise<ExtractorStreamable>;
44
- searchLimit?: number;
45
- reloadUserInterval?: number;
46
- priority?: number;
47
- arl: string;
48
- decryptor?: typeof BaseDecryptor;
49
- };
50
-
51
- export type DeezerUserInfo = {
52
- cookie: string;
53
- licenseToken: string;
54
- csrfToken: string;
55
- mediaUrl: string;
56
- };
57
-
58
- export const Warnings = {
59
- MissingDecryption:
60
- "Decryption Key missing! This is needed for extracting streams.",
61
- } as const;
62
- export type Warnings = (typeof Warnings)[keyof typeof Warnings];
63
-
64
- function parseCookie(obj: Record<string, string>) {
65
- let str = "";
66
- for (const key of Object.keys(obj)) {
67
- str += ` ${key}=${obj[key]};`;
68
- }
69
-
70
- return str.trim();
71
- }
72
-
73
- async function fetchDeezerUser(ext: DeezerExtractor): Promise<DeezerUserInfo> {
74
- // extract deezer username
75
- // dynamically load crypto because some might not want streaming
76
- const crypto = await getCrypto();
77
- const randomToken = crypto.randomBytes(16).toString("hex");
78
- const deezerUsrDataUrl = `https://www.deezer.com/ajax/gw-light.php?method=deezer.getUserData&input=3&api_version=1.0&api_token=${randomToken}`;
79
-
80
- const usrDataRes = await ext.fetch(deezerUsrDataUrl);
81
- const usrData = await usrDataRes.json();
82
-
83
- const licenseToken = usrData.results.USER.OPTIONS.license_token;
84
- if (typeof licenseToken !== "string")
85
- throw new Error("Unable to get licenseToken");
86
-
87
- const csrfToken = usrData.results.checkForm;
88
- if (typeof csrfToken !== "string")
89
- throw new Error(
90
- "Unable to get csrf token which is required for decryption"
91
- );
92
-
93
- return {
94
- cookie: usrDataRes.headers.get("set-cookie")!,
95
- licenseToken,
96
- csrfToken,
97
- mediaUrl: usrData.results.URL_MEDIA || "https://media.deezer.com",
98
- };
99
- }
100
-
101
- export class DeezerExtractor extends BaseExtractor<DeezerExtractorOptions> {
102
- static readonly identifier: string =
103
- "com.retrouser955.discord-player.deezr-ext";
104
- userInfo!: DeezerUserInfo;
105
- /* tslint:disable-next-line */
106
- __interval?: ReturnType<typeof setInterval>;
107
-
108
- async fetch(
109
- input: Parameters<typeof fetch>[0],
110
- options?: Parameters<typeof fetch>[1]
111
- ) {
112
- if (!options) options = {};
113
- options.headers = {
114
- Cookie: parseCookie({ arl: this.options.arl }),
115
- "User-Agent":
116
- "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
117
- DNT: "1",
118
- Origin: "https://www.deezer.com",
119
- Connection: "keep-alive",
120
- Referer: "https://www.deezer.com/login",
121
- ...options?.headers,
122
- };
123
- return fetch(input, options);
124
- }
125
-
126
- async activate(): Promise<void> {
127
- this.protocols = ["deezer"];
128
- if (!this.options.decryptionKey)
129
- process.emitWarning(Warnings.MissingDecryption);
130
- else {
131
- this.userInfo = await fetchDeezerUser(this);
132
-
133
- this.context.player.debug(
134
- "USER INFO EXT: " + JSON.stringify(this.userInfo)
135
- );
136
- }
137
-
138
- if (this.options.priority) {
139
- this.priority = this.options.priority;
140
- }
141
-
142
- this.__interval = setInterval(async () => {
143
- try {
144
- this.userInfo = await fetchDeezerUser(this);
145
- } catch {
146
- this.context.player.debug(
147
- "[DEEZER_EXTRACTOR_ERR]: Unable to fetch user information from Deezer. Retrying in 3 seconds ..."
148
- );
149
- await setTimeout(3000 /* 3 seconds */);
150
- try {
151
- this.userInfo = await fetchDeezerUser(this);
152
- } catch (err) {
153
- this.context.player.debug(
154
- "[DEEZER_EXTRACTOR_ERR]: Retry failed. Using old user ..."
155
- );
156
- }
157
- }
158
- }, this.options.reloadUserInterval || 8.64e7 /* one day */).unref();
159
- }
160
-
161
- async deactivate() {
162
- if (this.__interval) clearInterval(this.__interval);
163
- this.protocols = [];
164
- }
165
-
166
- async validate(
167
- query: string,
168
- type: SearchQueryType & "deezer"
169
- ): Promise<boolean> {
170
- return validate(query) || type === "deezer" || !isUrl(query);
171
- }
172
-
173
- buildPlaylistData(
174
- data: DeezerPlaylist,
175
- handleContext: ExtractorSearchContext
176
- ) {
177
- const raw: string[] = data.url.split("/");
178
- const identifier: string = raw[raw.length - 1].split("?")[0];
179
-
180
- return new Playlist(this.context.player, {
181
- title: data.name,
182
- thumbnail: data.thumbnail[0].url,
183
- author: {
184
- name: data.artist.name,
185
- url: data.artist.url,
186
- },
187
- type: data.type,
188
- tracks: data.tracks.map((v) => this.buildTrack(v, handleContext)),
189
- description: "",
190
- source: "arbitrary",
191
- id: identifier,
192
- url: data.url,
193
- });
194
- }
195
-
196
- async handle(
197
- query: string,
198
- context: ExtractorSearchContext
199
- ): Promise<ExtractorInfo> {
200
- if (!isUrl(query)) {
201
- const rawSearch = await search(query);
202
- const tracks = buildTrackFromSearch(
203
- rawSearch,
204
- this.context.player,
205
- context.requestedBy
206
- );
207
- return this.createResponse(null, tracks);
208
- }
209
-
210
- if (deezerRegex.share.test(query)) {
211
- const redirect = await this.fetch(query);
212
- query = redirect.url; // follow the redirect of deezer page links
213
- }
214
- const metadata = await getData(query);
215
-
216
- if (metadata?.type === "song")
217
- return this.createResponse(null, [this.buildTrack(metadata, context)]);
218
- if (metadata?.type === "playlist" || metadata?.type === "album") {
219
- const playlist = this.buildPlaylistData(metadata, context);
220
-
221
- return this.createResponse(playlist, playlist.tracks);
222
- }
223
-
224
- throw new Error("Unable to get data from Deezer");
225
- }
226
-
227
- buildTrack(track: DeezerTrack, { requestedBy }: ExtractorSearchContext) {
228
- return new Track(this.context.player, {
229
- title: track.name,
230
- author: track.author.map((v) => v.name).join(", "),
231
- url: track.url,
232
- source: "arbitrary",
233
- thumbnail: track.thumbnail[0].url,
234
- duration: DPUtil.buildTimeCode(DPUtil.parseMS(track.duration)),
235
- requestedBy,
236
- });
237
- }
238
-
239
- async bridge(track: Track): Promise<ExtractorStreamable | null> {
240
- const deezerTrack = await searchOneTrack(
241
- `${track.author} ${track.source === "youtube" ? track.cleanTitle : track.title}`
242
- );
243
-
244
- if (!deezerTrack) return null;
245
- const dpTrack = buildTrackFromSearch(
246
- deezerTrack,
247
- this.context.player,
248
- track.requestedBy
249
- );
250
-
251
- const stream = this.stream(dpTrack[0]);
252
-
253
- return stream;
254
- }
255
-
256
- stream(info: Track): Promise<ExtractorStreamable> {
257
- return streamTrack(info, this);
258
- }
259
- }
1
+ import {
2
+ Playlist as DeezerPlaylist,
3
+ Track as DeezerTrack,
4
+ getData,
5
+ } from "@mithron/deezer-music-metadata";
6
+ import {
7
+ BaseExtractor,
8
+ Util as DPUtil,
9
+ ExtractorInfo,
10
+ ExtractorSearchContext,
11
+ ExtractorStreamable,
12
+ Playlist,
13
+ SearchQueryType,
14
+ Track,
15
+ } from "discord-player";
16
+ import { setTimeout } from "node:timers/promises";
17
+ import { BaseDecryptor } from "./Crypto/BaseDecryptor";
18
+ import {
19
+ buildTrackFromSearch,
20
+ deezerRegex,
21
+ getCrypto,
22
+ isUrl,
23
+ search,
24
+ searchOneTrack,
25
+ streamTrack,
26
+ validate,
27
+ } from "./utils/util";
28
+
29
+ /**
30
+ * -------------------------------NOTICE-------------------------------------
31
+ * STREAMING CODE IS MAINLY TAKEN FROM https://github.com/PerformanC/NodeLink
32
+ * WHICH HAS THE "BSD 2-Clause "Simplified" License"
33
+ *
34
+ * PLEASE SHOW THE ORIGINAL AUTHOR SUPPORT BY STARING HIS GITHUB REPO
35
+ * --------------------------------------------------------------------------
36
+ */
37
+
38
+ export type DeezerExtractorOptions = {
39
+ decryptionKey?: string; // needed for decrypting deezer songs
40
+ createStream?: (
41
+ track: Track,
42
+ ext: DeezerExtractor
43
+ ) => Promise<ExtractorStreamable>;
44
+ searchLimit?: number;
45
+ reloadUserInterval?: number;
46
+ priority?: number;
47
+ arl: string;
48
+ decryptor?: typeof BaseDecryptor;
49
+ };
50
+
51
+ export type DeezerUserInfo = {
52
+ cookie: string;
53
+ licenseToken: string;
54
+ csrfToken: string;
55
+ mediaUrl: string;
56
+ };
57
+
58
+ export const Warnings = {
59
+ MissingDecryption:
60
+ "Decryption Key missing! This is needed for extracting streams.",
61
+ } as const;
62
+ export type Warnings = (typeof Warnings)[keyof typeof Warnings];
63
+
64
+ function parseCookie(obj: Record<string, string>) {
65
+ let str = "";
66
+ for (const key of Object.keys(obj)) {
67
+ str += ` ${key}=${obj[key]};`;
68
+ }
69
+
70
+ return str.trim();
71
+ }
72
+
73
+ async function fetchDeezerUser(ext: DeezerExtractor): Promise<DeezerUserInfo> {
74
+ // extract deezer username
75
+ // dynamically load crypto because some might not want streaming
76
+ const crypto = await getCrypto();
77
+ const randomToken = crypto.randomBytes(16).toString("hex");
78
+ const deezerUsrDataUrl = `https://www.deezer.com/ajax/gw-light.php?method=deezer.getUserData&input=3&api_version=1.0&api_token=${randomToken}`;
79
+
80
+ const usrDataRes = await ext.fetch(deezerUsrDataUrl);
81
+ const usrData = await usrDataRes.json();
82
+
83
+ const licenseToken = usrData.results.USER.OPTIONS.license_token;
84
+ if (typeof licenseToken !== "string")
85
+ throw new Error("Unable to get licenseToken");
86
+
87
+ const csrfToken = usrData.results.checkForm;
88
+ if (typeof csrfToken !== "string")
89
+ throw new Error(
90
+ "Unable to get csrf token which is required for decryption"
91
+ );
92
+
93
+ return {
94
+ cookie: usrDataRes.headers.get("set-cookie")!,
95
+ licenseToken,
96
+ csrfToken,
97
+ mediaUrl: usrData.results.URL_MEDIA || "https://media.deezer.com",
98
+ };
99
+ }
100
+
101
+ export class DeezerExtractor extends BaseExtractor<DeezerExtractorOptions> {
102
+ static readonly identifier: string =
103
+ "com.retrouser955.discord-player.deezr-ext";
104
+ userInfo!: DeezerUserInfo;
105
+ /* tslint:disable-next-line */
106
+ __interval?: ReturnType<typeof setInterval>;
107
+
108
+ async fetch(
109
+ input: Parameters<typeof fetch>[0],
110
+ options?: Parameters<typeof fetch>[1]
111
+ ) {
112
+ if (!options) options = {};
113
+ options.headers = {
114
+ Cookie: parseCookie({ arl: this.options.arl }),
115
+ "User-Agent":
116
+ "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
117
+ DNT: "1",
118
+ Origin: "https://www.deezer.com",
119
+ Connection: "keep-alive",
120
+ Referer: "https://www.deezer.com/login",
121
+ ...options?.headers,
122
+ };
123
+ return fetch(input, options);
124
+ }
125
+
126
+ async activate(): Promise<void> {
127
+ this.protocols = ["deezer"];
128
+ if (!this.options.decryptionKey)
129
+ process.emitWarning(Warnings.MissingDecryption);
130
+ else {
131
+ this.userInfo = await fetchDeezerUser(this);
132
+
133
+ this.context.player.debug(
134
+ "USER INFO EXT: " + JSON.stringify(this.userInfo)
135
+ );
136
+ }
137
+
138
+ if (this.options.priority) {
139
+ this.priority = this.options.priority;
140
+ }
141
+
142
+ this.__interval = setInterval(async () => {
143
+ try {
144
+ this.userInfo = await fetchDeezerUser(this);
145
+ } catch {
146
+ this.context.player.debug(
147
+ "[DEEZER_EXTRACTOR_ERR]: Unable to fetch user information from Deezer. Retrying in 3 seconds ..."
148
+ );
149
+ await setTimeout(3000 /* 3 seconds */);
150
+ try {
151
+ this.userInfo = await fetchDeezerUser(this);
152
+ } catch (err) {
153
+ this.context.player.debug(
154
+ "[DEEZER_EXTRACTOR_ERR]: Retry failed. Using old user ..."
155
+ );
156
+ }
157
+ }
158
+ }, this.options.reloadUserInterval || 8.64e7 /* one day */).unref();
159
+ }
160
+
161
+ async deactivate() {
162
+ if (this.__interval) clearInterval(this.__interval);
163
+ this.protocols = [];
164
+ }
165
+
166
+ async validate(
167
+ query: string,
168
+ type: SearchQueryType & "deezer"
169
+ ): Promise<boolean> {
170
+ return validate(query) || type === "deezer" || !isUrl(query);
171
+ }
172
+
173
+ buildPlaylistData(
174
+ data: DeezerPlaylist,
175
+ handleContext: ExtractorSearchContext
176
+ ) {
177
+ const raw: string[] = data.url.split("/");
178
+ const identifier: string = raw[raw.length - 1].split("?")[0];
179
+
180
+ return new Playlist(this.context.player, {
181
+ title: data.name,
182
+ thumbnail: data.thumbnail[0].url,
183
+ author: {
184
+ name: data.artist.name,
185
+ url: data.artist.url,
186
+ },
187
+ type: data.type,
188
+ tracks: data.tracks.map((v) => this.buildTrack(v, handleContext)),
189
+ description: "",
190
+ source: "arbitrary",
191
+ id: identifier,
192
+ url: data.url,
193
+ });
194
+ }
195
+
196
+ async handle(
197
+ query: string,
198
+ context: ExtractorSearchContext
199
+ ): Promise<ExtractorInfo> {
200
+ if (!isUrl(query)) {
201
+ const rawSearch = await search(query);
202
+ const tracks = buildTrackFromSearch(
203
+ rawSearch,
204
+ this.context.player,
205
+ context.requestedBy
206
+ );
207
+ return this.createResponse(null, tracks);
208
+ }
209
+
210
+ if (deezerRegex.share.test(query)) {
211
+ const redirect = await this.fetch(query);
212
+ query = redirect.url; // follow the redirect of deezer page links
213
+ }
214
+ const metadata = await getData(query);
215
+
216
+ if (metadata?.type === "song")
217
+ return this.createResponse(null, [this.buildTrack(metadata, context)]);
218
+ if (metadata?.type === "playlist" || metadata?.type === "album") {
219
+ const playlist = this.buildPlaylistData(metadata, context);
220
+
221
+ return this.createResponse(playlist, playlist.tracks);
222
+ }
223
+
224
+ throw new Error("Unable to get data from Deezer");
225
+ }
226
+
227
+ buildTrack(track: DeezerTrack, { requestedBy }: ExtractorSearchContext) {
228
+ return new Track(this.context.player, {
229
+ title: track.name,
230
+ author: track.author.map((v) => v.name).join(", "),
231
+ url: track.url,
232
+ source: "arbitrary",
233
+ thumbnail: track.thumbnail[0].url,
234
+ duration: DPUtil.buildTimeCode(DPUtil.parseMS(track.duration * 1000)),
235
+ requestedBy,
236
+ });
237
+ }
238
+
239
+ async bridge(track: Track): Promise<ExtractorStreamable | null> {
240
+ const deezerTrack = await searchOneTrack(
241
+ `${track.author} ${track.source === "youtube" ? track.cleanTitle : track.title}`
242
+ );
243
+
244
+ if (!deezerTrack) return null;
245
+ const dpTrack = buildTrackFromSearch(
246
+ deezerTrack,
247
+ this.context.player,
248
+ track.requestedBy
249
+ );
250
+
251
+ const stream = this.stream(dpTrack[0]);
252
+
253
+ return stream;
254
+ }
255
+
256
+ stream(info: Track): Promise<ExtractorStreamable> {
257
+ return streamTrack(info, this);
258
+ }
259
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,3 @@
1
- export * from "./DeezerExtractor"
2
- export * from "./utils/util"
1
+ export * from "./DeezerExtractor"
2
+ export * from "./utils/util"
3
3
  export * from "./Crypto"