discord-player-deezer 2.0.0 → 2.2.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.
Binary file
package/.yarnrc.yml ADDED
@@ -0,0 +1 @@
1
+ nodeLinker: node-modules
package/LICENSE CHANGED
@@ -1,121 +1,121 @@
1
- Creative Commons Legal Code
2
-
3
- CC0 1.0 Universal
4
-
5
- CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
- LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
- ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
- INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
- REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
- PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
- THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
- HEREUNDER.
13
-
14
- Statement of Purpose
15
-
16
- The laws of most jurisdictions throughout the world automatically confer
17
- exclusive Copyright and Related Rights (defined below) upon the creator
18
- and subsequent owner(s) (each and all, an "owner") of an original work of
19
- authorship and/or a database (each, a "Work").
20
-
21
- Certain owners wish to permanently relinquish those rights to a Work for
22
- the purpose of contributing to a commons of creative, cultural and
23
- scientific works ("Commons") that the public can reliably and without fear
24
- of later claims of infringement build upon, modify, incorporate in other
25
- works, reuse and redistribute as freely as possible in any form whatsoever
26
- and for any purposes, including without limitation commercial purposes.
27
- These owners may contribute to the Commons to promote the ideal of a free
28
- culture and the further production of creative, cultural and scientific
29
- works, or to gain reputation or greater distribution for their Work in
30
- part through the use and efforts of others.
31
-
32
- For these and/or other purposes and motivations, and without any
33
- expectation of additional consideration or compensation, the person
34
- associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
- is an owner of Copyright and Related Rights in the Work, voluntarily
36
- elects to apply CC0 to the Work and publicly distribute the Work under its
37
- terms, with knowledge of his or her Copyright and Related Rights in the
38
- Work and the meaning and intended legal effect of CC0 on those rights.
39
-
40
- 1. Copyright and Related Rights. A Work made available under CC0 may be
41
- protected by copyright and related or neighboring rights ("Copyright and
42
- Related Rights"). Copyright and Related Rights include, but are not
43
- limited to, the following:
44
-
45
- i. the right to reproduce, adapt, distribute, perform, display,
46
- communicate, and translate a Work;
47
- ii. moral rights retained by the original author(s) and/or performer(s);
48
- iii. publicity and privacy rights pertaining to a person's image or
49
- likeness depicted in a Work;
50
- iv. rights protecting against unfair competition in regards to a Work,
51
- subject to the limitations in paragraph 4(a), below;
52
- v. rights protecting the extraction, dissemination, use and reuse of data
53
- in a Work;
54
- vi. database rights (such as those arising under Directive 96/9/EC of the
55
- European Parliament and of the Council of 11 March 1996 on the legal
56
- protection of databases, and under any national implementation
57
- thereof, including any amended or successor version of such
58
- directive); and
59
- vii. other similar, equivalent or corresponding rights throughout the
60
- world based on applicable law or treaty, and any national
61
- implementations thereof.
62
-
63
- 2. Waiver. To the greatest extent permitted by, but not in contravention
64
- of, applicable law, Affirmer hereby overtly, fully, permanently,
65
- irrevocably and unconditionally waives, abandons, and surrenders all of
66
- Affirmer's Copyright and Related Rights and associated claims and causes
67
- of action, whether now known or unknown (including existing as well as
68
- future claims and causes of action), in the Work (i) in all territories
69
- worldwide, (ii) for the maximum duration provided by applicable law or
70
- treaty (including future time extensions), (iii) in any current or future
71
- medium and for any number of copies, and (iv) for any purpose whatsoever,
72
- including without limitation commercial, advertising or promotional
73
- purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
- member of the public at large and to the detriment of Affirmer's heirs and
75
- successors, fully intending that such Waiver shall not be subject to
76
- revocation, rescission, cancellation, termination, or any other legal or
77
- equitable action to disrupt the quiet enjoyment of the Work by the public
78
- as contemplated by Affirmer's express Statement of Purpose.
79
-
80
- 3. Public License Fallback. Should any part of the Waiver for any reason
81
- be judged legally invalid or ineffective under applicable law, then the
82
- Waiver shall be preserved to the maximum extent permitted taking into
83
- account Affirmer's express Statement of Purpose. In addition, to the
84
- extent the Waiver is so judged Affirmer hereby grants to each affected
85
- person a royalty-free, non transferable, non sublicensable, non exclusive,
86
- irrevocable and unconditional license to exercise Affirmer's Copyright and
87
- Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
- maximum duration provided by applicable law or treaty (including future
89
- time extensions), (iii) in any current or future medium and for any number
90
- of copies, and (iv) for any purpose whatsoever, including without
91
- limitation commercial, advertising or promotional purposes (the
92
- "License"). The License shall be deemed effective as of the date CC0 was
93
- applied by Affirmer to the Work. Should any part of the License for any
94
- reason be judged legally invalid or ineffective under applicable law, such
95
- partial invalidity or ineffectiveness shall not invalidate the remainder
96
- of the License, and in such case Affirmer hereby affirms that he or she
97
- will not (i) exercise any of his or her remaining Copyright and Related
98
- Rights in the Work or (ii) assert any associated claims and causes of
99
- action with respect to the Work, in either case contrary to Affirmer's
100
- express Statement of Purpose.
101
-
102
- 4. Limitations and Disclaimers.
103
-
104
- a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
- surrendered, licensed or otherwise affected by this document.
106
- b. Affirmer offers the Work as-is and makes no representations or
107
- warranties of any kind concerning the Work, express, implied,
108
- statutory or otherwise, including without limitation warranties of
109
- title, merchantability, fitness for a particular purpose, non
110
- infringement, or the absence of latent or other defects, accuracy, or
111
- the present or absence of errors, whether or not discoverable, all to
112
- the greatest extent permissible under applicable law.
113
- c. Affirmer disclaims responsibility for clearing rights of other persons
114
- that may apply to the Work or any use thereof, including without
115
- limitation any person's Copyright and Related Rights in the Work.
116
- Further, Affirmer disclaims responsibility for obtaining any necessary
117
- consents, permissions or other rights required for any use of the
118
- Work.
119
- d. Affirmer understands and acknowledges that Creative Commons is not a
120
- party to this document and has no duty or obligation with respect to
121
- this CC0 or use of the Work.
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ import { PassThrough } from 'stream';
14
14
  type DeezerExtractorOptions = {
15
15
  decryptionKey?: string;
16
16
  createStream?: (track: Track, ext: DeezerExtractor) => Promise<ExtractorStreamable>;
17
+ searchLimit?: number;
17
18
  };
18
19
  type DeezerUserInfo = {
19
20
  cookie: string;
@@ -21,6 +22,10 @@ type DeezerUserInfo = {
21
22
  csrfToken: string;
22
23
  mediaUrl: string;
23
24
  };
25
+ declare const Warnings: {
26
+ readonly MissingDecryption: "Decryption Key missing! This is needed for extracting streams.";
27
+ };
28
+ type Warnings = (typeof Warnings)[keyof typeof Warnings];
24
29
  declare class DeezerExtractor extends BaseExtractor<DeezerExtractorOptions> {
25
30
  static identifier: string;
26
31
  userInfo: DeezerUserInfo;
@@ -34,6 +39,8 @@ declare class DeezerExtractor extends BaseExtractor<DeezerExtractorOptions> {
34
39
  }
35
40
 
36
41
  declare function getCrypto(): Promise<typeof crypto>;
42
+ declare function isUrl(query: string): Promise<boolean>;
43
+ declare function search(query: string, limit?: number): Promise<DeezerSearchTrackResponse>;
37
44
  type ArrayOrObject<T> = T | T[];
38
45
  interface DeezerSearchTrackResponse {
39
46
  data: {
@@ -63,4 +70,4 @@ declare const deezerRegex: {
63
70
  };
64
71
  declare function validate(query: string): boolean;
65
72
 
66
- export { type ArrayOrObject, DeezerExtractor, type DeezerExtractorOptions, type DeezerSearchTrackResponse, type DeezerUserInfo, buildTrackFromSearch, deezerRegex, extractTrackId, getCrypto, searchOneTrack, streamTrack, validate };
73
+ export { type ArrayOrObject, DeezerExtractor, type DeezerExtractorOptions, type DeezerSearchTrackResponse, type DeezerUserInfo, Warnings, buildTrackFromSearch, deezerRegex, extractTrackId, getCrypto, isUrl, search, searchOneTrack, streamTrack, validate };
package/dist/index.js CHANGED
@@ -31,10 +31,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  DeezerExtractor: () => DeezerExtractor,
34
+ Warnings: () => Warnings,
34
35
  buildTrackFromSearch: () => buildTrackFromSearch,
35
36
  deezerRegex: () => deezerRegex,
36
37
  extractTrackId: () => extractTrackId,
37
38
  getCrypto: () => getCrypto,
39
+ isUrl: () => isUrl,
40
+ search: () => search,
38
41
  searchOneTrack: () => searchOneTrack,
39
42
  streamTrack: () => streamTrack,
40
43
  validate: () => validate
@@ -48,6 +51,7 @@ var import_deezer_music_metadata = require("@mithron/deezer-music-metadata");
48
51
  // src/utils/util.ts
49
52
  var import_discord_player = require("discord-player");
50
53
  var import_stream = require("stream");
54
+ var import_blowfish_node = __toESM(require("blowfish-node"));
51
55
  var IV = Buffer.from(Array.from({ length: 8 }, (_, x) => x));
52
56
  var rawCrypto;
53
57
  async function getCrypto() {
@@ -57,12 +61,28 @@ async function getCrypto() {
57
61
  }
58
62
  return rawCrypto;
59
63
  }
64
+ async function isUrl(query) {
65
+ try {
66
+ new URL(query);
67
+ return true;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
60
72
  var DeezerAPIRoutes = {
61
73
  searchTrack(query, limit) {
62
74
  const url = `https://api.deezer.com/search/track?q=${encodeURIComponent(query)}&${limit ? `limit=${limit}` : ""}`;
63
75
  return url;
64
76
  }
65
77
  };
78
+ async function search(query, limit = 10) {
79
+ const route = DeezerAPIRoutes.searchTrack(query, limit);
80
+ const response = await fetch(route);
81
+ if (!response.status.toString().startsWith("2")) throw new Error("Server responded with a non 2xx status.");
82
+ const jsonTrack = await response.json();
83
+ if (!jsonTrack.data || !Array.isArray(jsonTrack.data) || jsonTrack.data.length === 0) throw new Error("Unable get tracks from Deezer for the query '" + query + "'");
84
+ return jsonTrack;
85
+ }
66
86
  function buildTrackFromSearch(track, player, requestedBy) {
67
87
  const tracks = track.data.map((v) => new import_discord_player.Track(player, {
68
88
  source: "arbitrary",
@@ -155,16 +175,13 @@ async function streamTrack(track, ext) {
155
175
  } else {
156
176
  buffer = Buffer.concat([buffer, chunk]);
157
177
  }
178
+ const blowfishDecrypter = new import_blowfish_node.default(new Uint8Array(trackKey), import_blowfish_node.default.MODE.CBC, import_blowfish_node.default.PADDING.NULL);
179
+ blowfishDecrypter.setIv(new Uint8Array(IV));
158
180
  while (buffer.length >= bufferSize) {
159
181
  const bufferSized = buffer.subarray(0, bufferSize);
160
182
  if (i % 3 === 0) {
161
- const decipher = crypto.createDecipheriv(
162
- "bf-cbc",
163
- trackKey,
164
- IV
165
- ).setAutoPadding(false);
166
- passThrough.write(decipher.update(bufferSized));
167
- passThrough.write(decipher.final());
183
+ const decipher = Buffer.from(blowfishDecrypter.decode(new Uint8Array(bufferSized), import_blowfish_node.default.TYPE.UINT8_ARRAY));
184
+ passThrough.write(decipher);
168
185
  } else {
169
186
  passThrough.write(bufferSized);
170
187
  }
@@ -185,9 +202,12 @@ function validate(query) {
185
202
  }
186
203
 
187
204
  // src/DeezerExtractor.ts
205
+ var Warnings = {
206
+ MissingDecryption: "Decryption Key missing! This is needed for extracting streams."
207
+ };
188
208
  var DeezerExtractor = class extends import_discord_player2.BaseExtractor {
189
209
  async activate() {
190
- if (!this.options.decryptionKey) process.emitWarning("Decryption Key missing! This is needed for extracting streams.");
210
+ if (!this.options.decryptionKey) process.emitWarning(Warnings.MissingDecryption);
191
211
  else {
192
212
  const crypto = await getCrypto();
193
213
  const randomToken = crypto.randomBytes(16).toString("hex");
@@ -229,6 +249,18 @@ var DeezerExtractor = class extends import_discord_player2.BaseExtractor {
229
249
  });
230
250
  }
231
251
  async handle(query, context) {
252
+ if (!isUrl(query)) {
253
+ try {
254
+ const tracks = buildTrackFromSearch(await search(query, this.options.searchLimit), this.context.player, context.requestedBy);
255
+ return this.createResponse(null, tracks);
256
+ } catch {
257
+ return this.createResponse();
258
+ }
259
+ }
260
+ if (deezerRegex.share.test(query)) {
261
+ const redirect = await fetch(query);
262
+ query = redirect.url;
263
+ }
232
264
  const metadata = await (0, import_deezer_music_metadata.getData)(query);
233
265
  if (metadata?.type === "song") return this.createResponse(null, [this.buildTrack(metadata, context)]);
234
266
  if (metadata?.type === "playlist" || metadata?.type === "album") {
@@ -263,10 +295,13 @@ DeezerExtractor.identifier = "com.retrouser955.discord-player.deezr-ext";
263
295
  // Annotate the CommonJS export names for ESM import in node:
264
296
  0 && (module.exports = {
265
297
  DeezerExtractor,
298
+ Warnings,
266
299
  buildTrackFromSearch,
267
300
  deezerRegex,
268
301
  extractTrackId,
269
302
  getCrypto,
303
+ isUrl,
304
+ search,
270
305
  searchOneTrack,
271
306
  streamTrack,
272
307
  validate
package/package.json CHANGED
@@ -1,34 +1,35 @@
1
- {
2
- "name": "discord-player-deezer",
3
- "version": "2.0.0",
4
- "description": "A custom extractor made for discord-player that enables you to extract from Deezer.",
5
- "main": "dist/index.js",
6
- "author": "retro_ig",
7
- "license": "MIT",
8
- "private": false,
9
- "dependencies": {
10
- "@mithron/deezer-music-metadata": "^1.0.3"
11
- },
12
- "devDependencies": {
13
- "@discord-player/extractor": "^4.5.1",
14
- "discord-player": "^6.7.1",
15
- "prettier": "^3.4.2",
16
- "tslint": "^6.1.3",
17
- "tslint-config-prettier": "^1.18.0",
18
- "tsup": "^8.3.5",
19
- "typescript": "^5.7.2"
20
- },
21
- "scripts": {
22
- "build": "yarn lint && tsup",
23
- "lint": "tslint -p tsconfig.json",
24
- "npm:publish": "yarn build && npm publish --access public"
25
- },
26
- "repository": {
27
- "type": "git",
28
- "url": "https://github.com/retrouser955/discord-player-deezer/"
29
- },
30
- "bugs": {
31
- "url": "https://github.com/retrouser955/discord-player-deezer/issues"
32
- },
33
- "packageManager": "yarn@4.5.1+sha512.341db9396b6e289fecc30cd7ab3af65060e05ebff4b3b47547b278b9e67b08f485ecd8c79006b405446262142c7a38154445ef7f17c1d5d1de7d90bf9ce7054d"
34
- }
1
+ {
2
+ "name": "discord-player-deezer",
3
+ "version": "2.2.0-dev.0",
4
+ "description": "A custom extractor made for discord-player that enables you to extract from Deezer.",
5
+ "main": "dist/index.js",
6
+ "author": "retro_ig",
7
+ "license": "MIT",
8
+ "dependencies": {
9
+ "@mithron/deezer-music-metadata": "^1.0.3",
10
+ "blowfish-node": "^1.1.4"
11
+ },
12
+ "devDependencies": {
13
+ "@discord-player/extractor": "^4.5.1",
14
+ "discord-player": "^6.7.1",
15
+ "prettier": "^3.4.2",
16
+ "tslint": "^6.1.3",
17
+ "tslint-config-prettier": "^1.18.0",
18
+ "tsup": "^8.3.5",
19
+ "typescript": "^5.7.2"
20
+ },
21
+ "scripts": {
22
+ "build": "yarn lint && tsup",
23
+ "lint": "tslint -p tsconfig.json",
24
+ "npm:publish": "yarn build && npm publish --access public",
25
+ "prepare": "tsup"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/retrouser955/discord-player-deezer/"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/retrouser955/discord-player-deezer/issues"
33
+ },
34
+ "packageManager": "yarn@4.5.1+sha512.341db9396b6e289fecc30cd7ab3af65060e05ebff4b3b47547b278b9e67b08f485ecd8c79006b405446262142c7a38154445ef7f17c1d5d1de7d90bf9ce7054d"
35
+ }
package/readme.md CHANGED
@@ -1,43 +1,35 @@
1
- # Discord Player Deezer
2
-
3
- Discord Player Deezer is a Deezer platform plugin for discord-player
4
-
5
- # Installation
6
-
7
- ```bash
8
- $ npm install discord-player-deezer
9
- ```
10
-
11
- # Register the extractor
12
-
13
- ```ts
14
- import { DeezerExtractor } from "discord-player-deezer"
15
- import { Player } from "discord-player"
16
-
17
- const player = new Player(...)
18
-
19
- await player.extractors.register(DeezerExtractor, {})
20
- ```
21
-
22
- # Extracting Streams
23
-
24
- As Deezer sends DMCA to repositories containing the hard-coded decryption key, it is not provided. You can find this key in the code of related projects (deezer downloaders) and your client-side JavaScript code.
25
-
26
- ```ts
27
- import { DeezerExtractor } from "discord-player-deezer"
28
- import { Player } from "discord-player"
29
-
30
- const player = new Player(...)
31
-
32
- await player.extractors.register(DeezerExtractor, {
33
- decryptionKey: "master-decryption-key"
34
- })
35
- ```
36
-
37
- # Important information
38
-
39
- As Node has migrated from openssl for decryption, we must use the `--openssl-legacy-provider` flag when starting our application with stream extraction
40
-
41
- ```bash
42
- $ node --openssl-legacy-provider yourfile.js
1
+ # Discord Player Deezer
2
+
3
+ Discord Player Deezer is a Deezer platform plugin for discord-player
4
+
5
+ # Installation
6
+
7
+ ```bash
8
+ $ npm install discord-player-deezer
9
+ ```
10
+
11
+ # Register the extractor
12
+
13
+ ```ts
14
+ import { DeezerExtractor } from "discord-player-deezer"
15
+ import { Player } from "discord-player"
16
+
17
+ const player = new Player(...)
18
+
19
+ await player.extractors.register(DeezerExtractor, {})
20
+ ```
21
+
22
+ # Extracting Streams
23
+
24
+ As Deezer sends DMCA to repositories containing the hard-coded decryption key, it is not provided. You can find this key in the code of related projects (deezer downloaders) and your client-side JavaScript code.
25
+
26
+ ```ts
27
+ import { DeezerExtractor } from "discord-player-deezer"
28
+ import { Player } from "discord-player"
29
+
30
+ const player = new Player(...)
31
+
32
+ await player.extractors.register(DeezerExtractor, {
33
+ decryptionKey: "master-decryption-key"
34
+ })
43
35
  ```
@@ -0,0 +1,144 @@
1
+ import { BaseExtractor, ExtractorSearchContext, ExtractorStreamable, Track, Playlist, Util as DPUtil, ExtractorInfo } from "discord-player"
2
+ import { Playlist as DeezerPlaylist, Track as DeezerTrack, getData } from "@mithron/deezer-music-metadata";
3
+ import { buildTrackFromSearch, deezerRegex, getCrypto, isUrl, search, searchOneTrack, streamTrack, validate } from "./utils/util";
4
+
5
+ /**
6
+ * -------------------------------NOTICE-------------------------------------
7
+ * STREAMING CODE IS MAINLY TAKEN FROM https://github.com/PerformanC/NodeLink
8
+ * WHICH HAS THE "BSD 2-Clause "Simplified" License"
9
+ *
10
+ * PLEASE SHOW THE ORIGINAL AUTHOR SUPPORT BY STARING HIS GITHUB REPO
11
+ * --------------------------------------------------------------------------
12
+ */
13
+
14
+ export type DeezerExtractorOptions = {
15
+ decryptionKey?: string; // needed for decrypting deezer songs
16
+ createStream?: (track: Track, ext: DeezerExtractor) => Promise<ExtractorStreamable>;
17
+ searchLimit?: number;
18
+ }
19
+
20
+ export type DeezerUserInfo = {
21
+ cookie: string;
22
+ licenseToken: string;
23
+ csrfToken: string;
24
+ mediaUrl: string;
25
+ }
26
+
27
+ export const Warnings = {
28
+ MissingDecryption: "Decryption Key missing! This is needed for extracting streams."
29
+ } as const
30
+ export type Warnings = (typeof Warnings)[keyof typeof Warnings]
31
+
32
+ export class DeezerExtractor extends BaseExtractor<DeezerExtractorOptions> {
33
+ static identifier: string = "com.retrouser955.discord-player.deezr-ext"
34
+ userInfo!: DeezerUserInfo
35
+
36
+ async activate(): Promise<void> {
37
+ if(!this.options.decryptionKey) process.emitWarning(Warnings.MissingDecryption)
38
+ else {
39
+ // extract deezer username
40
+ // dynamically load crypto because some might not want streaming
41
+ const crypto = await getCrypto()
42
+ const randomToken = crypto.randomBytes(16).toString("hex")
43
+ const deezerUsrDataUrl = `https://www.deezer.com/ajax/gw-light.php?method=deezer.getUserData&input=3&api_version=1.0&api_token=${randomToken}`
44
+
45
+ const usrDataRes = await fetch(deezerUsrDataUrl)
46
+ const usrData = await usrDataRes.json()
47
+
48
+ const licenseToken = usrData.results.USER.OPTIONS.license_token
49
+ if(typeof licenseToken !== "string") throw new Error("Unable to get licenseToken")
50
+
51
+ const csrfToken = usrData.results.checkForm
52
+ if(typeof csrfToken !== "string") throw new Error("Unable to get csrf token which is required for decryption")
53
+
54
+ this.userInfo = {
55
+ mediaUrl: usrData.results.URL_MEDIA || "https://media.deezer.com",
56
+ cookie: usrDataRes.headers.get("set-cookie")!,
57
+ licenseToken,
58
+ csrfToken
59
+ }
60
+
61
+ this.context.player.debug('USER INFO EXT: ' + JSON.stringify(this.userInfo))
62
+ }
63
+ }
64
+
65
+ async validate(query: string): Promise<boolean> {
66
+ return validate(query)
67
+ }
68
+
69
+ buildPlaylistData(data: DeezerPlaylist, handleContext: ExtractorSearchContext) {
70
+ const raw: string[] = data.url.split("/")
71
+ const identifier: string = raw[raw.length - 1].split("?")[0]
72
+
73
+ return new Playlist(this.context.player, {
74
+ title: data.name,
75
+ thumbnail: data.thumbnail[0].url,
76
+ author: {
77
+ name: data.artist.name,
78
+ url: data.artist.url
79
+ },
80
+ type: data.type,
81
+ tracks: data.tracks.map((v) => this.buildTrack(v, handleContext)),
82
+ description: "",
83
+ source: "arbitrary",
84
+ id: identifier,
85
+ url: data.url
86
+ })
87
+ }
88
+
89
+ async handle(query: string, context: ExtractorSearchContext): Promise<ExtractorInfo> {
90
+ if(!isUrl(query)) {
91
+ // Player is using deezer protocol
92
+ try {
93
+ const tracks = buildTrackFromSearch(await search(query, this.options.searchLimit), this.context.player, context.requestedBy);
94
+
95
+ return this.createResponse(null, tracks);
96
+ } catch {
97
+ // deezer didnt return a good api response
98
+ return this.createResponse()
99
+ }
100
+ }
101
+
102
+ if (deezerRegex.share.test(query)) {
103
+ const redirect = await fetch(query);
104
+ query = redirect.url; // follow the redirect of deezer page links
105
+ }
106
+ const metadata = await getData(query)
107
+
108
+ if(metadata?.type === "song") return this.createResponse(null, [this.buildTrack(metadata, context)])
109
+ if(metadata?.type === "playlist" || metadata?.type === "album") {
110
+ const playlist = this.buildPlaylistData(metadata, context)
111
+
112
+ return this.createResponse(playlist, playlist.tracks)
113
+ }
114
+
115
+ throw new Error("Unable to get data from Deezer")
116
+ }
117
+
118
+ buildTrack(track: DeezerTrack, { requestedBy }: ExtractorSearchContext) {
119
+ return new Track(this.context.player, {
120
+ title: track.name,
121
+ author: track.author.map((v) => v.name).join(", "),
122
+ url: track.url,
123
+ source: "arbitrary",
124
+ thumbnail: track.thumbnail[0].url,
125
+ duration: DPUtil.buildTimeCode(DPUtil.parseMS(track.duration)),
126
+ requestedBy
127
+ })
128
+ }
129
+
130
+ async bridge(track: Track): Promise<ExtractorStreamable | null> {
131
+ const deezerTrack = await searchOneTrack(`${track.author} ${track.source === "youtube" ? track.cleanTitle : track.title}`)
132
+
133
+ if(!deezerTrack) return null
134
+ const dpTrack = buildTrackFromSearch(deezerTrack, this.context.player, track.requestedBy)
135
+
136
+ const stream = this.stream(dpTrack[0])
137
+
138
+ return stream
139
+ }
140
+
141
+ stream(info: Track): Promise<ExtractorStreamable> {
142
+ return streamTrack(info, this)
143
+ }
144
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./DeezerExtractor"
2
+ export * from "./utils/util"
@@ -0,0 +1,217 @@
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
+
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 async function isUrl(query: string) {
20
+ try {
21
+ /* tslint:disable-next-line */
22
+ new URL(query)
23
+ return true
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
+ for (let iter = 0; iter < 16; iter++)
115
+ /* tslint:disable-next-line no-bitwise */
116
+ trackKey.writeInt8(trackHash[iter].charCodeAt(0) ^ trackHash[iter + 16].charCodeAt(0) ^ decryptionKey[iter].charCodeAt(0), iter)
117
+
118
+ const trackInfoRes = await fetch(`https://www.deezer.com/ajax/gw-light.php?method=song.getListData&input=3&api_version=1.0&api_token=${ext.userInfo.csrfToken}`, {
119
+ method: "POST",
120
+ headers: {
121
+ Cookie: ext.userInfo.cookie,
122
+ 'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
123
+ 'DNT': '1'
124
+ },
125
+ body: JSON.stringify({
126
+ sng_ids: [trackId]
127
+ })
128
+ })
129
+
130
+ const songInfo = (await trackInfoRes.json()).results.data[0]
131
+
132
+ const streamInfoRes = await fetch('https://media.deezer.com/v1/get_url', {
133
+ method: "POST",
134
+ body: JSON.stringify({
135
+ license_token: ext.userInfo.licenseToken,
136
+ media: [{
137
+ type: 'FULL',
138
+ formats: [{
139
+ cipher: 'BF_CBC_STRIPE',
140
+ format: 'FLAC'
141
+ }, {
142
+ cipher: 'BF_CBC_STRIPE',
143
+ format: 'MP3_256'
144
+ }, {
145
+ cipher: 'BF_CBC_STRIPE',
146
+ format: 'MP3_128'
147
+ }, {
148
+ cipher: 'BF_CBC_STRIPE',
149
+ format: 'MP3_MISC'
150
+ }]
151
+ }],
152
+ track_tokens: [songInfo.TRACK_TOKEN]
153
+ })
154
+ })
155
+ const streamInfo = await streamInfoRes.json()
156
+
157
+ const trackMediaUrl = streamInfo.data[0].media[0].sources[0].url
158
+
159
+ ext.context.player.debug("DEEZER FOUND MEDIA URL " + trackMediaUrl)
160
+
161
+ const trackReq = await fetch(trackMediaUrl)
162
+ // @ts-ignore
163
+ const readable = Readable.fromWeb(trackReq.body)
164
+ let buffer = Buffer.alloc(0)
165
+ let i = 0
166
+
167
+ const bufferSize = 2048 // 2mb
168
+
169
+ const passThrough = new PassThrough()
170
+
171
+ readable.on("readable", () => {
172
+ let chunk = null;
173
+ while (true) {
174
+ chunk = readable.read(bufferSize)
175
+
176
+ if (!chunk) {
177
+ if (readable.readableLength) {
178
+ chunk = readable.read(readable.readableLength)
179
+ buffer = Buffer.concat([buffer, chunk])
180
+ }
181
+ break;
182
+ } else {
183
+ buffer = Buffer.concat([buffer, chunk])
184
+ }
185
+
186
+ const blowfishDecrypter = new Blowfish(new Uint8Array(trackKey), Blowfish.MODE.CBC, Blowfish.PADDING.NULL)
187
+ blowfishDecrypter.setIv(new Uint8Array(IV))
188
+
189
+ while (buffer.length >= bufferSize) {
190
+ const bufferSized = buffer.subarray(0, bufferSize)
191
+
192
+ if (i % 3 === 0) {
193
+ const decipher = Buffer.from(blowfishDecrypter.decode(new Uint8Array(bufferSized), Blowfish.TYPE.UINT8_ARRAY))
194
+ passThrough.write(decipher)
195
+ } else {
196
+ passThrough.write(bufferSized)
197
+ }
198
+
199
+ i++
200
+
201
+ buffer = buffer.subarray(bufferSize)
202
+ }
203
+ }
204
+ })
205
+
206
+ return passThrough
207
+ }
208
+
209
+ export const deezerRegex = {
210
+ track: /(^https:)\/\/(www\.)?deezer.com\/([a-zA-Z]+\/)?track\/[0-9]+/,
211
+ playlistNalbums: /(^https:)\/\/(www\.)?deezer.com\/[a-zA-Z]+\/(playlist|album)\/[0-9]+(\?)?(.*)/,
212
+ share: /(^https:)\/\/deezer\.page\.link\/[A-Za-z0-9]+/
213
+ } as const;
214
+
215
+ export function validate(query: string) {
216
+ return deezerRegex.track.test(query) ?? deezerRegex.playlistNalbums.test(query) ?? deezerRegex.share.test(query)
217
+ }
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
  })