Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support for Lavalink v4 #18

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
{
"name": "spotilink",
"version": "1.4.10",
"version": "2.0.0-beta",
"description": "Parses Spotify links into Lavalink track objects.",
"main": "dist/index",
"types": "dist/index.d.ts",
"author": "TheFloppyBanana",
"license": "MIT",
"type": "module",
"scripts": {
"build": "tsc --module esnext -p .",
"build": "tsup",
"lint": "eslint --fix --ext ts src",
"test": "eslint --ext ts src",
"prepublishOnly": "yarn build"
},
"repository": "https://github.com/insane-devs/spotilink.git",
"dependencies": {
"@types/node": "^16.11.11",
"@types/node-fetch": "^3.0.3",
"@types/ws": "^8.2.1",
"node-fetch": "^3.1.0"
"undici": "^5.22.1"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.5.0",
"@typescript-eslint/parser": "^5.5.0",
"eslint": "^8.4.0",
"typescript": "^4.5.2"
"@types/node": "^20.4.5",
"@types/node-fetch": "^3.0.3",
"@types/ws": "^8.5.5",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"eslint": "^8.46.0",
"tsup": "^7.1.0",
"typescript": "^5.1.6"
},
"files": [
"dist",
Expand Down
33 changes: 21 additions & 12 deletions src/lib/SpotifyParser.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fetch from "node-fetch";
import { fetch } from "undici";
import { URLSearchParams } from "url";

const BASE_URL = "https://api.spotify.com/v1";
const SPOTIFY_BASE_URL = "https://api.spotify.com/v1";

export interface Node {
host: string;
Expand All @@ -18,7 +18,7 @@ export interface Artist {
}

export interface LavalinkTrack {
track: string;
encoded: string;
info: {
identifier: string;
isSeekable: boolean;
Expand All @@ -31,8 +31,17 @@ export interface LavalinkTrack {
}
}

export enum LoadType {
TRACK = "track",
PLAYLIST = "playlist",
SEARCH = "search",
EMPTY = "empty",
ERROR = "error"
}

export interface LavalinkSearchResult {
tracks: LavalinkTrack[];
loadType: LoadType.SEARCH
data: LavalinkTrack[]
}

export interface SpotifyPlaylist {
Expand Down Expand Up @@ -115,7 +124,7 @@ export class SpotifyParser {
if (!id) throw new ReferenceError("The album ID was not provided");
if (typeof id !== "string") throw new TypeError(`The album ID must be a string, received type ${typeof id}`);

const { items }: Album = (await (await fetch(`${BASE_URL}/albums/${id}/tracks`, this.options)).json()) as Album;
const { items }: Album = (await (await fetch(`${SPOTIFY_BASE_URL}/albums/${id}/tracks`, this.options)).json()) as Album;

if (convert) return Promise.all(items.map(async (item) => await this.fetchTrack(item, fetchOptions)) as unknown as LavalinkTrack[]);
return items;
Expand All @@ -132,15 +141,15 @@ export class SpotifyParser {
if (!id) throw new ReferenceError("The playlist ID was not provided");
if (typeof id !== "string") throw new TypeError(`The playlist ID must be a string, received type ${typeof id}`);

const playlistInfo: SpotifyPlaylist = await (await fetch(`${BASE_URL}/playlists/${id}`, this.options)).json() as SpotifyPlaylist;
const playlistInfo: SpotifyPlaylist = await (await fetch(`${SPOTIFY_BASE_URL}/playlists/${id}`, this.options)).json() as SpotifyPlaylist;
const sets = Math.ceil(playlistInfo.tracks.total / 50);

let items: SpotifyTrack[] = [];
for (let set = 0; set < sets; set++) {
const params = new URLSearchParams();
params.set("limit", "50");
params.set("offset", String(set * 50));
const tracks = await (await fetch(`${BASE_URL}/playlists/${id}/tracks?${params}`, this.options)).json() as PlaylistItems;
const tracks = await (await fetch(`${SPOTIFY_BASE_URL}/playlists/${id}/tracks?${params}`, this.options)).json() as PlaylistItems;
items = items.concat(tracks.items.map(item => item.track));
if (set === 0) items.unshift();
}
Expand All @@ -160,7 +169,7 @@ export class SpotifyParser {
if (!id) throw new ReferenceError("The track ID was not provided");
if (typeof id !== "string") throw new TypeError(`The track ID must be a string, received type ${typeof id}`);

const track: SpotifyTrack = (await (await fetch(`${BASE_URL}/tracks/${id}`, this.options)).json()) as SpotifyTrack;
const track: SpotifyTrack = (await (await fetch(`${SPOTIFY_BASE_URL}/tracks/${id}`, this.options)).json()) as SpotifyTrack;

if (convert) return this.fetchTrack(track, fetchOptions) as unknown as LavalinkTrack;
return track;
Expand All @@ -185,23 +194,23 @@ export class SpotifyParser {
params.append("identifier", `ytsearch: ${title}`);

const { host, port, password } = this.nodes;
const { tracks } = await (await fetch(`http://${host}:${port}/loadtracks?${params}`, {
const { data } = await (await fetch(`http://${host}:${port}/v4/loadtracks?${params}`, {
headers: {
Authorization: password
}
})).json() as LavalinkSearchResult;

if (!tracks.length) return null;
if (!data.length) return null;

if (fetchOptions.prioritizeSameDuration) {
const sameDuration = tracks.filter(searchResult => (searchResult.info.length >= (track.duration_ms - 1500)) && (searchResult.info.length <= (track.duration_ms + 1500)))[0];
const sameDuration = data.filter(searchResult => (searchResult.info.length >= (track.duration_ms - 1500)) && (searchResult.info.length <= (track.duration_ms + 1500)))[0];
if (sameDuration) return sameDuration;
}

if (typeof fetchOptions.customFilter === "undefined") fetchOptions.customFilter = () => true;
if (typeof fetchOptions.customSort === "undefined") fetchOptions.customSort = () => 0;

return tracks
return data
.filter(searchResult => fetchOptions.customFilter(searchResult, track))
.sort((comparableTrack, compareToTrack) => fetchOptions.customSort(comparableTrack, compareToTrack, track))[0];
}
Expand Down
43 changes: 28 additions & 15 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"declaration": true,
"declarationMap": true,
"lib": ["esnext"],
"module": "commonjs",
"moduleResolution": "node",
"alwaysStrict": true,
"declaration": true,
"declarationMap": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"importHelpers": true,
"verbatimModuleSyntax": true,
"incremental": true,
"lib": ["ESNext"],
"module": "Node16",
"moduleResolution": "Node",
"newLine": "lf",
"noEmitHelpers": false,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"preserveConstEnums": true,
"pretty": true,
"removeComments": false,
"resolveJsonModule": true,
"rootDir": "./",
"outDir": "./dist",
"pretty": true,
"strict": true,
"target": "esnext",
"types": ["node", "node-fetch", "ws"]
"sourceMap": true,
"strict": true,
"target": "ES2020",
"useDefineForClassFields": true
},
"include": [
"./src/**/*"
],
"exclude": ["node_modules"]
}
"include": ["src"],
}
17 changes: 17 additions & 0 deletions tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { defineConfig } from "tsup";

export default defineConfig({
clean: true,
dts: false,
entry: ["src/**/*.ts", "!src/**/*.d.ts"],
format: ["cjs", "esm"],
minify: false,
skipNodeModulesBundle: true,
sourcemap: true,
target: "esnext",
tsconfig: "tsconfig.json",
bundle: false,
shims: false,
keepNames: true,
splitting: false
});
Loading