discord-player-deezer 1.0.0 → 2.0.0-beta.1

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.
@@ -0,0 +1,17 @@
1
+ name: publish dp deezer
2
+ on:
3
+ release:
4
+ types: [published]
5
+
6
+ jobs:
7
+ publish-npm:
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - uses: actions/checkout@v2
11
+ - uses: actions/setup-node@v1
12
+ with:
13
+ node-version: 20
14
+ registry-url: https://registry.npmjs.org/
15
+ - run: yarn npm:publish
16
+ env:
17
+ NODE_AUTH_TOKEN: ${{secrets.npm_token}}
package/LICENSE ADDED
@@ -0,0 +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.
@@ -0,0 +1,44 @@
1
+ import { Track, ExtractorStreamable, BaseExtractor, ExtractorSearchContext, Playlist as Playlist$1, ExtractorInfo } from 'discord-player';
2
+ import { Playlist, Track as Track$1 } from '@mithron/deezer-music-metadata';
3
+ import * as crypto from 'crypto';
4
+ import { PassThrough } from 'stream';
5
+
6
+ /**
7
+ * -------------------------------NOTICE-------------------------------------
8
+ * STREAMING CODE IS MAINLY TAKEN FROM https://github.com/PerformanC/NodeLink
9
+ * WHICH HAS THE "BSD 2-Clause "Simplified" License"
10
+ *
11
+ * PLEASE SHOW THE ORIGINAL AUTHOR SUPPORT BY STARING HIS GITHUB REPO
12
+ * --------------------------------------------------------------------------
13
+ */
14
+ type DeezerExtractorOptions = {
15
+ decryptionKey?: string;
16
+ createStream?: (track: Track, ext: DeezerExtractor) => Promise<ExtractorStreamable>;
17
+ };
18
+ type DeezerUserInfo = {
19
+ cookie: string;
20
+ licenseToken: string;
21
+ csrfToken: string;
22
+ mediaUrl: string;
23
+ };
24
+ declare class DeezerExtractor extends BaseExtractor<DeezerExtractorOptions> {
25
+ static identifier: string;
26
+ userInfo: DeezerUserInfo;
27
+ activate(): Promise<void>;
28
+ validate(query: string): Promise<boolean>;
29
+ buildPlaylistData(data: Playlist, handleContext: ExtractorSearchContext): Playlist$1;
30
+ handle(query: string, context: ExtractorSearchContext): Promise<ExtractorInfo>;
31
+ buildTrack(track: Track$1, handleContext: ExtractorSearchContext): Track<unknown>;
32
+ stream(info: Track): Promise<ExtractorStreamable>;
33
+ }
34
+
35
+ declare function getCrypto(): Promise<typeof crypto>;
36
+ declare function streamTrack(track: Track, ext: DeezerExtractor): Promise<PassThrough>;
37
+ declare const deezerRegex: {
38
+ readonly track: RegExp;
39
+ readonly playlistNalbums: RegExp;
40
+ readonly share: RegExp;
41
+ };
42
+ declare function validate(query: string): boolean;
43
+
44
+ export { DeezerExtractor, type DeezerExtractorOptions, type DeezerUserInfo, deezerRegex, getCrypto, streamTrack, validate };
package/dist/index.js ADDED
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ DeezerExtractor: () => DeezerExtractor,
34
+ deezerRegex: () => deezerRegex,
35
+ getCrypto: () => getCrypto,
36
+ streamTrack: () => streamTrack,
37
+ validate: () => validate
38
+ });
39
+ module.exports = __toCommonJS(src_exports);
40
+
41
+ // src/DeezerExtractor.ts
42
+ var import_discord_player = require("discord-player");
43
+ var import_deezer_music_metadata = require("@mithron/deezer-music-metadata");
44
+
45
+ // src/utils/util.ts
46
+ var import_stream = require("stream");
47
+ var IV = Buffer.from(Array.from({ length: 8 }, (_, x) => x));
48
+ var rawCrypto;
49
+ async function getCrypto() {
50
+ if (!rawCrypto) {
51
+ rawCrypto = await import("crypto");
52
+ return rawCrypto;
53
+ }
54
+ return rawCrypto;
55
+ }
56
+ async function streamTrack(track, ext) {
57
+ const trackIdWithUrlParams = track.url.split("/").at(-1);
58
+ if (!trackIdWithUrlParams || !validate(track.url)) throw new Error("INVALID TRACK");
59
+ const decryptionKey = ext.options.decryptionKey;
60
+ if (!decryptionKey) throw new Error("MISSING DEEZER DECRYPTION KEY");
61
+ const crypto = await getCrypto();
62
+ const trackId = trackIdWithUrlParams.split("?")[0];
63
+ const trackHash = crypto.createHash("md5").update(trackId, "ascii").digest("hex");
64
+ const trackKey = Buffer.alloc(16);
65
+ for (let iter = 0; iter < 16; iter++)
66
+ trackKey.writeInt8(trackHash[iter].charCodeAt(0) ^ trackHash[iter + 16].charCodeAt(0) ^ decryptionKey[iter].charCodeAt(0), iter);
67
+ 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}`, {
68
+ method: "POST",
69
+ headers: {
70
+ Cookie: ext.userInfo.cookie,
71
+ "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
72
+ "DNT": "1"
73
+ },
74
+ body: JSON.stringify({
75
+ sng_ids: [trackId]
76
+ })
77
+ });
78
+ const trackInfo = await trackInfoRes.json();
79
+ if (Array.isArray(trackInfo.error) && trackInfo.error.length !== 0) throw new Error("Unable to extract track\n" + JSON.stringify(trackInfo.error));
80
+ if (typeof trackInfo.error === "object" && Object.keys(trackInfo.error).length !== 0) throw new Error("Unable to extract track\n" + JSON.stringify(trackInfo.error));
81
+ const info = trackInfo.data[0];
82
+ const streamInfoRes = await fetch(`${ext.userInfo.mediaUrl}/v1/get-url`, {
83
+ method: "POST",
84
+ body: JSON.stringify({
85
+ license_token: ext.userInfo.licenseToken,
86
+ media: [{
87
+ type: "FULL",
88
+ formats: [{
89
+ cipher: "BF_CBC_STRIPE",
90
+ format: "FLAC"
91
+ }, {
92
+ cipher: "BF_CBC_STRIPE",
93
+ format: "MP3_256"
94
+ }, {
95
+ cipher: "BF_CBC_STRIPE",
96
+ format: "MP3_128"
97
+ }, {
98
+ cipher: "BF_CBC_STRIPE",
99
+ format: "MP3_MISC"
100
+ }]
101
+ }],
102
+ track_tokens: [info.TRACK_TOKEN]
103
+ })
104
+ });
105
+ const streamInfo = await streamInfoRes.json();
106
+ const trackMediaUrl = streamInfo.data[0].media[0].sources[0].url;
107
+ const trackReq = await fetch(trackMediaUrl);
108
+ const readable = import_stream.Readable.fromWeb(trackReq.body);
109
+ let buffer = Buffer.alloc(0);
110
+ let i = 0;
111
+ const bufferSize = 2048;
112
+ const passThrough = new import_stream.PassThrough();
113
+ readable.on("readable", () => {
114
+ let chunk = null;
115
+ while (true) {
116
+ chunk = readable.read(bufferSize);
117
+ if (!chunk) {
118
+ if (readable.readableLength) {
119
+ chunk = readable.read(readable.readableLength);
120
+ buffer = Buffer.concat([buffer, chunk]);
121
+ }
122
+ break;
123
+ } else {
124
+ buffer = Buffer.concat([buffer, chunk]);
125
+ }
126
+ while (buffer.length >= bufferSize) {
127
+ const bufferSized = buffer.subarray(0, bufferSize);
128
+ if (i % 3 === 0) {
129
+ const decipher = crypto.createDecipheriv(
130
+ "bf-cbc",
131
+ trackKey,
132
+ IV
133
+ ).setAutoPadding(false);
134
+ passThrough.write(decipher.update(bufferSized));
135
+ passThrough.write(decipher.final());
136
+ } else {
137
+ passThrough.write(bufferSized);
138
+ }
139
+ i++;
140
+ buffer = buffer.subarray(bufferSize);
141
+ }
142
+ }
143
+ });
144
+ return passThrough;
145
+ }
146
+ var deezerRegex = {
147
+ track: /(^https:)\/\/(www\.)?deezer.com\/([a-zA-Z]+\/)?track\/[0-9]+/,
148
+ playlistNalbums: /(^https:)\/\/(www\.)?deezer.com\/[a-zA-Z]+\/(playlist|album)\/[0-9]+(\?)?(.*)/,
149
+ share: /(^https:)\/\/deezer\.page\.link\/[A-Za-z0-9]+/
150
+ };
151
+ function validate(query) {
152
+ return deezerRegex.track.test(query) ?? deezerRegex.playlistNalbums.test(query) ?? deezerRegex.share.test(query);
153
+ }
154
+
155
+ // src/DeezerExtractor.ts
156
+ var DeezerExtractor = class extends import_discord_player.BaseExtractor {
157
+ async activate() {
158
+ if (!this.options.decryptionKey) process.emitWarning("Decryption Key missing! This is needed for extracting streams.");
159
+ else {
160
+ const crypto = await getCrypto();
161
+ const randomToken = crypto.randomBytes(16).toString("hex");
162
+ const deezerUsrDataUrl = `https://www.deezer.com/ajax/gw-light.php?method=deezer.getUserData&input=3&api_version=1.0&api_token=${randomToken}`;
163
+ const usrDataRes = await fetch(deezerUsrDataUrl);
164
+ const cookie = usrDataRes.headers.get("set-cookie");
165
+ this.userInfo.cookie = cookie;
166
+ const usrData = await usrDataRes.json();
167
+ const licenseToken = usrData.results.USER.OPTIONS.license_token;
168
+ if (typeof licenseToken !== "string") throw new Error("Unable to get licenseToken");
169
+ this.userInfo.licenseToken = licenseToken;
170
+ const csrfToken = usrData.results.checkForm;
171
+ if (typeof csrfToken !== "string") throw new Error("Unable to get csrf token which is required for decryption");
172
+ this.userInfo.mediaUrl = usrData.results.URL_MEDIA || "https://media.deezer.com";
173
+ }
174
+ }
175
+ async validate(query) {
176
+ return validate(query);
177
+ }
178
+ buildPlaylistData(data, handleContext) {
179
+ const raw = data.url.split("/");
180
+ const identifier = raw[raw.length - 1].split("?")[0];
181
+ return new import_discord_player.Playlist(this.context.player, {
182
+ title: data.name,
183
+ thumbnail: data.thumbnail[0].url,
184
+ author: {
185
+ name: data.artist.name,
186
+ url: data.artist.url
187
+ },
188
+ type: data.type,
189
+ tracks: data.tracks.map((v) => this.buildTrack(v, handleContext)),
190
+ description: "",
191
+ source: "arbitrary",
192
+ id: identifier,
193
+ url: data.url
194
+ });
195
+ }
196
+ async handle(query, context) {
197
+ const metadata = await (0, import_deezer_music_metadata.getData)(query);
198
+ if (metadata?.type === "song") return this.createResponse(null, [this.buildTrack(metadata, context)]);
199
+ if (metadata?.type === "playlist" || metadata?.type === "album") {
200
+ const playlist = this.buildPlaylistData(metadata, context);
201
+ return this.createResponse(playlist, playlist.tracks);
202
+ }
203
+ throw new Error("Unable to get data from Deezer");
204
+ }
205
+ buildTrack(track, handleContext) {
206
+ return new import_discord_player.Track(this.context.player, {
207
+ title: track.name,
208
+ author: track.author.map((v) => v.name).join(", "),
209
+ url: track.url,
210
+ source: "arbitrary",
211
+ thumbnail: track.thumbnail[0].url,
212
+ duration: import_discord_player.Util.buildTimeCode(import_discord_player.Util.parseMS(track.duration)),
213
+ requestedBy: handleContext.requestedBy
214
+ });
215
+ }
216
+ stream(info) {
217
+ return streamTrack(info, this);
218
+ }
219
+ };
220
+ DeezerExtractor.identifier = "com.retrouser955.discord-player.deezr-ext";
221
+ // Annotate the CommonJS export names for ESM import in node:
222
+ 0 && (module.exports = {
223
+ DeezerExtractor,
224
+ deezerRegex,
225
+ getCrypto,
226
+ streamTrack,
227
+ validate
228
+ });
package/package.json CHANGED
@@ -1,30 +1,28 @@
1
1
  {
2
2
  "name": "discord-player-deezer",
3
- "version": "1.0.0",
3
+ "version": "2.0.0-beta.1",
4
4
  "description": "A custom extractor made for discord-player that enables you to extract from Deezer.",
5
- "main": "dist/DeezerExtractor.js",
5
+ "main": "dist/index.js",
6
6
  "author": "retro_ig",
7
7
  "license": "MIT",
8
8
  "private": false,
9
9
  "dependencies": {
10
- "@discord-player/extractor": "^4.4.4",
11
- "@mithron/deezer-music-metadata": "^1.0.3",
12
- "discord-player": "*",
13
- "soundcloud.ts": "^0.5.2",
14
- "tslint-config-prettier": "^1.18.0",
15
- "youtube-sr": "^4.3.4",
16
- "yt-stream": "^1.4.4"
10
+ "@mithron/deezer-music-metadata": "^1.0.3"
17
11
  },
18
12
  "devDependencies": {
19
- "prettier": "^2.8.4",
13
+ "@discord-player/extractor": "^4.5.1",
14
+ "cross-env": "^7.0.3",
15
+ "discord-player": "^6.7.1",
16
+ "prettier": "^3.4.2",
20
17
  "tslint": "^6.1.3",
21
- "typescript": "^4.9.5"
18
+ "tslint-config-prettier": "^1.18.0",
19
+ "tsup": "^8.3.5",
20
+ "typescript": "^5.7.2"
22
21
  },
23
22
  "scripts": {
24
- "build": "npm run lint && tsc && npm run format",
25
- "format": "prettier --write \"dist/*.js\"",
23
+ "build": "yarn lint && tsup",
26
24
  "lint": "tslint -p tsconfig.json",
27
- "npm:publish": "yarn build && npm publish --access public"
25
+ "npm:publish": "cross-env NODE_OPTIONS=--openssl-legacy-provider yarn build && npm publish --access public"
28
26
  },
29
27
  "repository": {
30
28
  "type": "git",
@@ -32,5 +30,6 @@
32
30
  },
33
31
  "bugs": {
34
32
  "url": "https://github.com/retrouser955/discord-player-deezer/issues"
35
- }
33
+ },
34
+ "packageManager": "yarn@4.5.1+sha512.341db9396b6e289fecc30cd7ab3af65060e05ebff4b3b47547b278b9e67b08f485ecd8c79006b405446262142c7a38154445ef7f17c1d5d1de7d90bf9ce7054d"
36
35
  }
package/readme.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Discord Player Deezer Extractor
2
2
 
3
- Discord Player Deezer Extractor. An unofficial extractor made for discord-player for **Deezer** support. Deezer extractor works by either making a request to the Deezer API or extracting metadata from the Deezer site. Because we cannot get streams from deezer itself, the extractor uses the extracted data to stream from youtube!
3
+ Discord Player Deezer Extractor. An extractor made for discord-player for **Deezer** support. Deezer extractor works by either making a request to the Deezer API or extracting metadata from the Deezer site. Because we cannot get streams from deezer itself, the extractor uses the extracted data to stream from youtube!
4
4
 
5
5
  ## Installing the extractor
6
6
 
@@ -40,4 +40,26 @@ player.extractors.register(DeezerExtractor)
40
40
 
41
41
  *note: be sure to register it before loading the default extractors to make sure any conflicts with discord-player's default attachment extractor is resolved!*
42
42
 
43
- That's it! See the magic happen as you bot is now able to play from Deezer URLs
43
+ That's it! See the magic happen as you bot is now able to play from Deezer URLs
44
+
45
+ # Options
46
+
47
+ DP Deezer accepts the following options.
48
+ ```ts
49
+ interface DeezerOptions {
50
+ forceEngine?: EngineType;
51
+ createStream?: () => Promise<string|Readable>;
52
+ beforeCreateStream?: () => Promise<unknown>|unknown;
53
+ }
54
+ ```
55
+ One thing to keep in mind is, while using the two functions, if you want to access track data, you must you `useTrack()` function exported by the library. For example ...
56
+
57
+ ```ts
58
+ player.extractors.register(DeezerExtractor, {
59
+ createStream: () => {
60
+ const track = useTrack()
61
+
62
+ return getStreamSomehow(track)
63
+ }
64
+ })
65
+ ```
@@ -1,167 +1,107 @@
1
- import { BaseExtractor, ExtractorInfo, ExtractorSearchContext, Playlist, SearchQueryType, Track, Util } from "discord-player"
2
- import { getData } from "@mithron/deezer-music-metadata"
3
- import { YouTube } from "youtube-sr";
4
- import { Readable } from "stream";
5
- import { stream } from "yt-stream";
6
- import { default as SoundCloud } from "soundcloud.ts"
7
-
8
- interface DeezerOptions {
9
- bridgeFrom?: "YouTube" | "SoundCloud",
10
- soundcloud?: {
11
- clientId?: string;
12
- oauthToken?: string;
13
- proxy?: string;
14
- };
15
- onBeforeCreateStream?: (track: Track) => Promise<string | Readable>
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 { getCrypto, 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>
16
17
  }
17
18
 
18
- interface DeezerRegex {
19
- track: RegExp;
20
- playlistNalbums: RegExp;
21
- share: RegExp
19
+ export type DeezerUserInfo = {
20
+ cookie: string;
21
+ licenseToken: string;
22
+ csrfToken: string;
23
+ mediaUrl: string;
22
24
  }
23
25
 
24
- export default class DeezerExtractor extends BaseExtractor<DeezerOptions> {
25
- public static identifier: string = "com.discord-player.deezerextractor" as const
26
- private _stream = stream
27
- client = new SoundCloud({
28
- clientId: this.options.soundcloud?.clientId,
29
- oauthToken: this.options.soundcloud?.oauthToken,
30
- proxy: this.options.soundcloud?.proxy
31
- })
32
-
33
- private deezerRegex: DeezerRegex = {
34
- track: /(^https:)\/\/(www\.)?deezer.com\/([a-zA-Z]+\/)?track\/[0-9]+/,
35
- playlistNalbums: /(^https:)\/\/(www\.)?deezer.com\/[a-zA-Z]+\/(playlist|album)\/[0-9]+(\?)?(.*)/,
36
- share: /(^https:)\/\/deezer\.page\.link\/[A-Za-z0-9]+/
37
- };
38
-
39
- public async activate(): Promise<void> {
40
- /* tslint:disable-next-line */
41
- if(!this.options.bridgeFrom) this.options.bridgeFrom === "YouTube"
42
- }
26
+ export class DeezerExtractor extends BaseExtractor<DeezerExtractorOptions> {
27
+ static identifier: string = "com.retrouser955.discord-player.deezr-ext"
28
+ userInfo!: DeezerUserInfo
43
29
 
44
- public async validate(query: string, _type?: SearchQueryType | null | undefined): Promise<boolean> {
45
- if (typeof query !== "string") return false
30
+ async activate(): Promise<void> {
31
+ if(!this.options.decryptionKey) process.emitWarning("Decryption Key missing! This is needed for extracting streams.")
32
+ else {
33
+ // extract deezer username
34
+ // dynamically load crypto because some might not want streaming
35
+ const crypto = await getCrypto()
36
+ const randomToken = crypto.randomBytes(16).toString("hex")
37
+ const deezerUsrDataUrl = `https://www.deezer.com/ajax/gw-light.php?method=deezer.getUserData&input=3&api_version=1.0&api_token=${randomToken}`
46
38
 
47
- return this.deezerRegex.track.test(query) || this.deezerRegex.playlistNalbums.test(query) || this.deezerRegex.share.test(query)
48
- }
39
+ const usrDataRes = await fetch(deezerUsrDataUrl)
40
+ const cookie = usrDataRes.headers.get("set-cookie")!
41
+ this.userInfo.cookie = cookie
42
+ const usrData = await usrDataRes.json()
49
43
 
50
- public async handle(query: string, context: ExtractorSearchContext): Promise<ExtractorInfo> {
51
- if(this.deezerRegex.share.test(query)) {
52
- const fetchRes = await fetch(query)
44
+ const licenseToken = usrData.results.USER.OPTIONS.license_token
45
+ if(typeof licenseToken !== "string") throw new Error("Unable to get licenseToken")
46
+ this.userInfo.licenseToken = licenseToken
53
47
 
54
- query = fetchRes.url.split("?")[0]
55
- }
56
-
57
- const data = await getData(query)
58
-
59
- if (data?.type === "song") {
60
- const returnData = {
61
- playlist: null,
62
- tracks: [
63
- new Track(this.context.player, {
64
- title: data?.name as string,
65
- raw: data,
66
- description: "",
67
- author: data.author.map((artist) => artist.name).join(" "),
68
- url: data.url,
69
- source: "arbitrary",
70
- thumbnail: data.thumbnail[0].url,
71
- duration: Util.buildTimeCode(Util.parseMS(data.duration * 1000)),
72
- views: 0,
73
- requestedBy: context.requestedBy
74
- })
75
- ]
76
- }
77
-
78
- return returnData
79
- }
48
+ const csrfToken = usrData.results.checkForm
49
+ if(typeof csrfToken !== "string") throw new Error("Unable to get csrf token which is required for decryption")
80
50
 
81
- if (data?.type === "playlist" || data?.type === "album") {
82
- const raw: string[] = data.url.split("/")
83
- const identifier: string = raw[raw.length - 1]
84
-
85
- const playlist = new Playlist(this.context.player, {
86
- title: data.name,
87
- thumbnail: data.thumbnail[0].url,
88
- author: {
89
- name: data.artist.name,
90
- url: data.artist.url
91
- },
92
- type: data.type,
93
- rawPlaylist: data,
94
- tracks: [],
95
- description: "",
96
- source: "arbitrary",
97
- id: identifier,
98
- url: data.url
99
- })
100
-
101
- const tracks = data.tracks.map(track => {
102
- return new Track(this.context.player, {
103
- title: track.name as string,
104
- raw: track,
105
- description: "",
106
- author: track.author.map((artist) => artist.name).join(" "),
107
- url: track.url,
108
- source: "arbitrary",
109
- thumbnail: track.thumbnail[0].url,
110
- duration: Util.buildTimeCode(Util.parseMS(track.duration * 1000)),
111
- views: 0,
112
- requestedBy: context.requestedBy
113
- })
114
- })
115
-
116
- playlist.tracks = tracks
117
-
118
- return {
119
- playlist,
120
- tracks
121
- }
51
+ this.userInfo.mediaUrl = usrData.results.URL_MEDIA || "https://media.deezer.com"
122
52
  }
123
-
124
- return { playlist: null, tracks: [] }
125
53
  }
126
54
 
127
- public async brdgeProvider(track: Track) {
128
- const query = this.createBridgeQuery(track)
129
-
130
- if(this.options.bridgeFrom === "YouTube") {
131
- try {
132
- const serachResults = await YouTube.search(query, {
133
- limit: 1,
134
- type: "video"
135
- })
136
-
137
- const ytStream = await this._stream(serachResults[0].url, {
138
- quality: 'high',
139
- type: 'audio',
140
- highWaterMark: 1048576 * 32
141
- })
142
-
143
- return ytStream.url
144
- } catch (error) {
145
- throw new Error(`Could not find a source to bridge from. The error is as follows.\n\n${error}`)
146
- }
147
- }
55
+ async validate(query: string): Promise<boolean> {
56
+ return validate(query)
57
+ }
148
58
 
149
- const res = await this.client.tracks.searchV2({
150
- q: query
59
+ buildPlaylistData(data: DeezerPlaylist, handleContext: ExtractorSearchContext) {
60
+ const raw: string[] = data.url.split("/")
61
+ const identifier: string = raw[raw.length - 1].split("?")[0]
62
+
63
+ return new Playlist(this.context.player, {
64
+ title: data.name,
65
+ thumbnail: data.thumbnail[0].url,
66
+ author: {
67
+ name: data.artist.name,
68
+ url: data.artist.url
69
+ },
70
+ type: data.type,
71
+ tracks: data.tracks.map((v) => this.buildTrack(v, handleContext)),
72
+ description: "",
73
+ source: "arbitrary",
74
+ id: identifier,
75
+ url: data.url
151
76
  })
77
+ }
78
+
79
+ async handle(query: string, context: ExtractorSearchContext): Promise<ExtractorInfo> {
80
+ const metadata = await getData(query)
152
81
 
153
- if(res.collection.length === 0) throw new Error("Could not find a suitable source to stream from.")
82
+ if(metadata?.type === "song") return this.createResponse(null, [this.buildTrack(metadata, context)])
83
+ if(metadata?.type === "playlist" || metadata?.type === "album") {
84
+ const playlist = this.buildPlaylistData(metadata, context)
154
85
 
155
- const str = this.client.util.streamLink(res.collection[0].permalink_url)
86
+ return this.createResponse(playlist, playlist.tracks)
87
+ }
156
88
 
157
- return str
89
+ throw new Error("Unable to get data from Deezer")
158
90
  }
159
91
 
160
- public async stream(info: Track): Promise<string | Readable> {
161
- if(this.options.onBeforeCreateStream && typeof this.options.onBeforeCreateStream === "function") {
162
- return await this.options.onBeforeCreateStream(info)
163
- }
92
+ buildTrack(track: DeezerTrack, handleContext: ExtractorSearchContext) {
93
+ return new Track(this.context.player, {
94
+ title: track.name,
95
+ author: track.author.map((v) => v.name).join(", "),
96
+ url: track.url,
97
+ source: "arbitrary",
98
+ thumbnail: track.thumbnail[0].url,
99
+ duration: DPUtil.buildTimeCode(DPUtil.parseMS(track.duration)),
100
+ requestedBy: handleContext.requestedBy
101
+ })
102
+ }
164
103
 
165
- return this.brdgeProvider(info)
104
+ stream(info: Track): Promise<ExtractorStreamable> {
105
+ return streamTrack(info, this)
166
106
  }
167
107
  }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./DeezerExtractor"
2
+ export * from "./utils/util"
@@ -0,0 +1,144 @@
1
+ import { Track } from "discord-player";
2
+ import type { DeezerExtractor } from "../DeezerExtractor";
3
+ import { Readable, PassThrough } from 'stream'
4
+ import type { BinaryLike, CipherGCMTypes, CipherKey, Decipher } from "crypto";
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 streamTrack(track: Track, ext: DeezerExtractor) {
20
+ const trackIdWithUrlParams = track.url.split("/").at(-1)
21
+ if (!trackIdWithUrlParams || !validate(track.url)) throw new Error("INVALID TRACK") // not a deezer track
22
+
23
+ const decryptionKey = ext.options.decryptionKey
24
+ if (!decryptionKey) throw new Error("MISSING DEEZER DECRYPTION KEY") // cant decrypt due to missing key
25
+
26
+ const crypto = await getCrypto()
27
+ const trackId = trackIdWithUrlParams.split("?")[0]
28
+
29
+ const trackHash = crypto.createHash("md5").update(trackId, "ascii").digest("hex")
30
+ const trackKey = Buffer.alloc(16)
31
+
32
+ for (let iter = 0; iter < 16; iter++)
33
+ /* tslint:disable-next-line no-bitwise */
34
+ trackKey.writeInt8(trackHash[iter].charCodeAt(0) ^ trackHash[iter + 16].charCodeAt(0) ^ decryptionKey[iter].charCodeAt(0), iter)
35
+
36
+ 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}`, {
37
+ method: "POST",
38
+ headers: {
39
+ Cookie: ext.userInfo.cookie,
40
+ 'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
41
+ 'DNT': '1'
42
+ },
43
+ body: JSON.stringify({
44
+ sng_ids: [trackId]
45
+ })
46
+ })
47
+
48
+ const trackInfo = await trackInfoRes.json()
49
+
50
+ // no streaming data found
51
+ if (Array.isArray(trackInfo.error) && (trackInfo.error as unknown[]).length !== 0) throw new Error("Unable to extract track\n" + JSON.stringify(trackInfo.error))
52
+ if (typeof trackInfo.error === "object" && Object.keys(trackInfo.error).length !== 0) throw new Error("Unable to extract track\n" + JSON.stringify(trackInfo.error))
53
+
54
+ const info = trackInfo.data[0]
55
+
56
+ const streamInfoRes = await fetch(`${ext.userInfo.mediaUrl}/v1/get-url`, {
57
+ method: "POST",
58
+ body: JSON.stringify({
59
+ license_token: ext.userInfo.licenseToken,
60
+ media: [{
61
+ type: 'FULL',
62
+ formats: [{
63
+ cipher: 'BF_CBC_STRIPE',
64
+ format: 'FLAC'
65
+ }, {
66
+ cipher: 'BF_CBC_STRIPE',
67
+ format: 'MP3_256'
68
+ }, {
69
+ cipher: 'BF_CBC_STRIPE',
70
+ format: 'MP3_128'
71
+ }, {
72
+ cipher: 'BF_CBC_STRIPE',
73
+ format: 'MP3_MISC'
74
+ }]
75
+ }],
76
+ track_tokens: [info.TRACK_TOKEN]
77
+ })
78
+ })
79
+
80
+ const streamInfo = await streamInfoRes.json()
81
+
82
+ const trackMediaUrl = streamInfo.data[0].media[0].sources[0].url
83
+
84
+ const trackReq = await fetch(trackMediaUrl)
85
+ // @ts-ignore
86
+ const readable = Readable.fromWeb(trackReq.body)
87
+ let buffer = Buffer.alloc(0)
88
+ let i = 0
89
+
90
+ const bufferSize = 2048 // 2mb
91
+
92
+ const passThrough = new PassThrough()
93
+
94
+ readable.on("readable", () => {
95
+ let chunk = null;
96
+ while (true) {
97
+ chunk = readable.read(bufferSize)
98
+
99
+ if (!chunk) {
100
+ if (readable.readableLength) {
101
+ chunk = readable.read(readable.readableLength)
102
+ buffer = Buffer.concat([buffer, chunk])
103
+ }
104
+ break;
105
+ } else {
106
+ buffer = Buffer.concat([buffer, chunk])
107
+ }
108
+
109
+ while (buffer.length >= bufferSize) {
110
+ const bufferSized = buffer.subarray(0, bufferSize)
111
+
112
+ if (i % 3 === 0) {
113
+ const decipher = crypto.createDecipheriv(
114
+ 'bf-cbc' as unknown as CipherGCMTypes,
115
+ trackKey as unknown as CipherKey,
116
+ IV as unknown as BinaryLike
117
+ ).setAutoPadding(false) as unknown as Decipher
118
+
119
+ // @ts-ignore
120
+ passThrough.write(decipher.update(bufferSized as unknown as ArrayBufferView))
121
+ passThrough.write(decipher.final())
122
+ } else {
123
+ passThrough.write(bufferSized)
124
+ }
125
+
126
+ i++
127
+
128
+ buffer = buffer.subarray(bufferSize)
129
+ }
130
+ }
131
+ })
132
+
133
+ return passThrough
134
+ }
135
+
136
+ export const deezerRegex = {
137
+ track: /(^https:)\/\/(www\.)?deezer.com\/([a-zA-Z]+\/)?track\/[0-9]+/,
138
+ playlistNalbums: /(^https:)\/\/(www\.)?deezer.com\/[a-zA-Z]+\/(playlist|album)\/[0-9]+(\?)?(.*)/,
139
+ share: /(^https:)\/\/deezer\.page\.link\/[A-Za-z0-9]+/
140
+ } as const;
141
+
142
+ export function validate(query: string) {
143
+ return deezerRegex.track.test(query) ?? deezerRegex.playlistNalbums.test(query) ?? deezerRegex.share.test(query)
144
+ }
package/tsconfig.json CHANGED
@@ -1,5 +1,25 @@
1
1
  {
2
- "extends": "./discord-player-ts.base.json",
3
- "include": ["./src/*.ts"],
4
- "exclude": ["dist/*.ts"]
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
+ ]
5
25
  }
package/tslint.json CHANGED
@@ -1,3 +1,3 @@
1
1
  {
2
- "extends": ["tslint:recommended", "tslint-config-prettier"]
3
- }
2
+ "extends": ["tslint:recommended", "tslint-config-prettier"]
3
+ }
package/tsup.config.ts ADDED
@@ -0,0 +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
9
+ })
package/.prettierignore DELETED
@@ -1 +0,0 @@
1
- src/
package/.prettierrc DELETED
@@ -1,5 +0,0 @@
1
- {
2
- "printWidth": 120,
3
- "trailingComma": "all",
4
- "singleQuote": true
5
- }
@@ -1,21 +0,0 @@
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
- ]
21
- }
@@ -1,25 +0,0 @@
1
- /// <reference types="node" />
2
- import { BaseExtractor, ExtractorInfo, ExtractorSearchContext, SearchQueryType, Track } from "discord-player";
3
- import { Readable } from "stream";
4
- import { default as SoundCloud } from "soundcloud.ts";
5
- interface DeezerOptions {
6
- bridgeFrom?: "YouTube" | "SoundCloud";
7
- soundcloud?: {
8
- clientId?: string;
9
- oauthToken?: string;
10
- proxy?: string;
11
- };
12
- onBeforeCreateStream?: (track: Track) => Promise<string | Readable>;
13
- }
14
- export default class DeezerExtractor extends BaseExtractor<DeezerOptions> {
15
- static identifier: string;
16
- private _stream;
17
- client: SoundCloud;
18
- private deezerRegex;
19
- activate(): Promise<void>;
20
- validate(query: string, _type?: SearchQueryType | null | undefined): Promise<boolean>;
21
- handle(query: string, context: ExtractorSearchContext): Promise<ExtractorInfo>;
22
- brdgeProvider(track: Track): Promise<string>;
23
- stream(info: Track): Promise<string | Readable>;
24
- }
25
- export {};
@@ -1,139 +0,0 @@
1
- 'use strict';
2
- var __importDefault =
3
- (this && this.__importDefault) ||
4
- function (mod) {
5
- return mod && mod.__esModule ? mod : { default: mod };
6
- };
7
- Object.defineProperty(exports, '__esModule', { value: true });
8
- const discord_player_1 = require('discord-player');
9
- const deezer_music_metadata_1 = require('@mithron/deezer-music-metadata');
10
- const youtube_sr_1 = require('youtube-sr');
11
- const yt_stream_1 = require('yt-stream');
12
- const soundcloud_ts_1 = __importDefault(require('soundcloud.ts'));
13
- class DeezerExtractor extends discord_player_1.BaseExtractor {
14
- constructor() {
15
- super(...arguments);
16
- this._stream = yt_stream_1.stream;
17
- this.client = new soundcloud_ts_1.default({
18
- clientId: this.options.soundcloud?.clientId,
19
- oauthToken: this.options.soundcloud?.oauthToken,
20
- proxy: this.options.soundcloud?.proxy,
21
- });
22
- this.deezerRegex = {
23
- track: /(^https:)\/\/(www\.)?deezer.com\/([a-zA-Z]+\/)?track\/[0-9]+/,
24
- playlistNalbums: /(^https:)\/\/(www\.)?deezer.com\/[a-zA-Z]+\/(playlist|album)\/[0-9]+(\?)?(.*)/,
25
- share: /(^https:)\/\/deezer\.page\.link\/[A-Za-z0-9]+/,
26
- };
27
- }
28
- async activate() {
29
- /* tslint:disable-next-line */
30
- if (!this.options.bridgeFrom) this.options.bridgeFrom === 'YouTube';
31
- }
32
- async validate(query, _type) {
33
- if (typeof query !== 'string') return false;
34
- return (
35
- this.deezerRegex.track.test(query) ||
36
- this.deezerRegex.playlistNalbums.test(query) ||
37
- this.deezerRegex.share.test(query)
38
- );
39
- }
40
- async handle(query, context) {
41
- if (this.deezerRegex.share.test(query)) {
42
- const fetchRes = await fetch(query);
43
- query = fetchRes.url.split('?')[0];
44
- }
45
- const data = await (0, deezer_music_metadata_1.getData)(query);
46
- if (data?.type === 'song') {
47
- const returnData = {
48
- playlist: null,
49
- tracks: [
50
- new discord_player_1.Track(this.context.player, {
51
- title: data?.name,
52
- raw: data,
53
- description: '',
54
- author: data.author.map((artist) => artist.name).join(' '),
55
- url: data.url,
56
- source: 'arbitrary',
57
- thumbnail: data.thumbnail[0].url,
58
- duration: discord_player_1.Util.buildTimeCode(discord_player_1.Util.parseMS(data.duration * 1000)),
59
- views: 0,
60
- requestedBy: context.requestedBy,
61
- }),
62
- ],
63
- };
64
- return returnData;
65
- }
66
- if (data?.type === 'playlist' || data?.type === 'album') {
67
- const raw = data.url.split('/');
68
- const identifier = raw[raw.length - 1];
69
- const playlist = new discord_player_1.Playlist(this.context.player, {
70
- title: data.name,
71
- thumbnail: data.thumbnail[0].url,
72
- author: {
73
- name: data.artist.name,
74
- url: data.artist.url,
75
- },
76
- type: data.type,
77
- rawPlaylist: data,
78
- tracks: [],
79
- description: '',
80
- source: 'arbitrary',
81
- id: identifier,
82
- url: data.url,
83
- });
84
- const tracks = data.tracks.map((track) => {
85
- return new discord_player_1.Track(this.context.player, {
86
- title: track.name,
87
- raw: track,
88
- description: '',
89
- author: track.author.map((artist) => artist.name).join(' '),
90
- url: track.url,
91
- source: 'arbitrary',
92
- thumbnail: track.thumbnail[0].url,
93
- duration: discord_player_1.Util.buildTimeCode(discord_player_1.Util.parseMS(track.duration * 1000)),
94
- views: 0,
95
- requestedBy: context.requestedBy,
96
- });
97
- });
98
- playlist.tracks = tracks;
99
- return {
100
- playlist,
101
- tracks,
102
- };
103
- }
104
- return { playlist: null, tracks: [] };
105
- }
106
- async brdgeProvider(track) {
107
- const query = this.createBridgeQuery(track);
108
- if (this.options.bridgeFrom === 'YouTube') {
109
- try {
110
- const serachResults = await youtube_sr_1.YouTube.search(query, {
111
- limit: 1,
112
- type: 'video',
113
- });
114
- const ytStream = await this._stream(serachResults[0].url, {
115
- quality: 'high',
116
- type: 'audio',
117
- highWaterMark: 1048576 * 32,
118
- });
119
- return ytStream.url;
120
- } catch (error) {
121
- throw new Error(`Could not find a source to bridge from. The error is as follows.\n\n${error}`);
122
- }
123
- }
124
- const res = await this.client.tracks.searchV2({
125
- q: query,
126
- });
127
- if (res.collection.length === 0) throw new Error('Could not find a suitable source to stream from.');
128
- const str = this.client.util.streamLink(res.collection[0].permalink_url);
129
- return str;
130
- }
131
- async stream(info) {
132
- if (this.options.onBeforeCreateStream && typeof this.options.onBeforeCreateStream === 'function') {
133
- return await this.options.onBeforeCreateStream(info);
134
- }
135
- return this.brdgeProvider(info);
136
- }
137
- }
138
- exports.default = DeezerExtractor;
139
- DeezerExtractor.identifier = 'com.discord-player.deezerextractor';