Skip to content

Commit

Permalink
Merge pull request #102 from Joniii11/v5
Browse files Browse the repository at this point in the history
Update: Node, Connection, Poru
  • Loading branch information
parasop authored Mar 29, 2024
2 parents ed44557 + a6f4891 commit a1586ea
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 63 deletions.
42 changes: 24 additions & 18 deletions src/Node/Node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export class Node {
public attempt: number;
public stats: NodeStats | null;
public options: NodeGroup;
public clientName: string;
/**
* The Node class that is used to connect to a lavalink node
* @param poru Poru
Expand Down Expand Up @@ -111,29 +112,34 @@ export class Node {
this.attempt = 0;
this.isConnected = false;
this.stats = null;
}
this.clientName = options.clientName || `${config.clientName}/${config.version}`;
};

/**
* Connects to the lavalink node
* @returns {void}
*/
public connect(): void {
if (this.ws) this.ws.close();
if (!this.poru.nodes.get(this.name)) {
this.poru.nodes.set(this.name, this)
}
const headers = {
Authorization: this.password,
"User-Id": this.poru.userId,
"Client-Name": config.clientName,
};
if (this.resumeKey) headers["Resume-Key"] = this.resumeKey;
this.ws = new WebSocket(`${this.socketURL}`, { headers });
this.ws.on("open", this.open.bind(this));
this.ws.on("error", this.error.bind(this));
this.ws.on("message", this.message.bind(this));
this.ws.on("close", this.close.bind(this));
}
public async connect(): Promise<boolean> {
return new Promise((resolve) => {
if (this.isConnected) return resolve(true);
if (this.ws) this.ws.close();
if (!this.poru.nodes.get(this.name)) {
this.poru.nodes.set(this.name, this)
}
const headers = {
Authorization: this.password,
"User-Id": this.poru.userId,
"Client-Name": this.clientName,
};
if (this.resumeKey) headers["Resume-Key"] = this.resumeKey;
this.ws = new WebSocket(`${this.socketURL}`, { headers });
this.ws.on("open", this.open.bind(this));
this.ws.on("error", this.error.bind(this));
this.ws.on("message", this.message.bind(this));
this.ws.on("close", this.close.bind(this));
resolve(true);
})
};

/**
* Handles the message event
Expand Down
2 changes: 1 addition & 1 deletion src/Player/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Player } from "./Player";
export interface IVoiceServer {
token: string;
sessionId: string;
endpoint: string;
endpoint?: string;
};

type TYear = `${number}${number}${number}${number}`;
Expand Down
16 changes: 2 additions & 14 deletions src/Player/Player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -550,20 +550,8 @@ export class Player extends EventEmitter {
* @returns {Promise<Response>} - A Promise that resolves to a Response object containing the resolved tracks.
*/
public async resolve({ query, source, requester }: ResolveOptions): Promise<Response> {
const regex = /^https?:\/\//

if (regex.test(query)) {
const response = await this.node.rest.get<LoadTrackResponse>(
`/v4/loadtracks?identifier=${encodeURIComponent(query)}`
)
return new Response(response, requester)
} else {
const track = `${source || "ytsearch"}:${query}`
const response = await this.node.rest.get<LoadTrackResponse>(
`/v4/loadtracks?identifier=${encodeURIComponent(track)}`
)
return new Response(response, requester)
}
const response = await this.node.rest.get<LoadTrackResponse>(`/v4/loadtracks?identifier=${encodeURIComponent((query.startsWith('https://') ? '' : `${source || 'ytsearch'}:`) + query)}`)
return new Response(response, requester);
};

/**
Expand Down
68 changes: 39 additions & 29 deletions src/Poru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Response, LoadTrackResponse } from "./guild/Response";
import { Plugin } from "./Plugin";
import { Track, trackData } from "./guild/Track";
import { Filters } from "./Player/Filters";
import { IVoiceServer, SetStateUpdate } from "./Player/Connection";

export type Constructor<T> = new (...args: any[]) => T;

Expand All @@ -18,6 +19,25 @@ export interface NodeGroup {
region?: string[];
}

export type Packet = PacketVoiceStateUpdate | PacketVoiceServerUpdate | AnyOtherPacket;

interface PacketVoiceStateUpdate {
op: number;
d: SetStateUpdate;
t: "VOICE_STATE_UPDATE";
};

interface PacketVoiceServerUpdate {
op: number;
d: IVoiceServer;
t: "VOICE_SERVER_UPDATE";
};

interface AnyOtherPacket {
op: number;
d: any;
t: string;
};

export interface ResolveOptions {
query: string;
Expand Down Expand Up @@ -102,6 +122,7 @@ export interface PoruOptions {
reconnectTries?: number | null;
useCustomFilters?: boolean;
send?: Function | null;
clientName?: string;
}

export interface ConnectionOptions {
Expand Down Expand Up @@ -264,7 +285,6 @@ export class Poru extends EventEmitter {
* @param {any} client - VoiceClient used for connecting to Lavalink node server.
* @param {NodeGroup[]} nodes - Array of node groups.
* @param {PoruOptions} options - Configuration options for Poru.
* @returns {Poru} The Poru instance.
*/
constructor(client: any, nodes: NodeGroup[], options: PoruOptions) {
super();
Expand All @@ -282,49 +302,48 @@ export class Poru extends EventEmitter {
/**
* Initializes Poru and adds nodes.
*/
public init() {
public async init() {
if (this.isActivated) return this;
this.userId = this.client.user.id;
this._nodes.forEach((node) => this.addNode(node));
this._nodes.forEach(async (node) => await this.addNode(node));
this.isActivated = true;

if (this.options.plugins) {
this.options.plugins.forEach((plugin) => {

plugin.load(this);
});
}
if (!this.options.library) this.options.library = "discord.js";

switch (this.options.library) {
case "discord.js": {
this.send = (packet: any) => {
this.send = (packet: Packet) => {
const guild = this.client.guilds.cache.get(packet.d.guild_id);
if (guild) guild.shard?.send(packet);
};
this.client.on("raw", async (packet: any) => {
this.client.on("raw", async (packet: Packet) => {
this.packetUpdate(packet);
});
break;
}
case "eris": {
this.send = (packet: any) => {
this.send = (packet: Packet) => {
const guild = this.client.guilds.get(packet.d.guild_id);
if (guild) guild.shard.sendWS(packet?.op, packet?.d);
};

this.client.on("rawWS", async (packet: any) => {
this.client.on("rawWS", async (packet: Packet) => {
this.packetUpdate(packet);
});
break;
}
case "oceanic": {
this.send = (packet: any) => {
this.send = (packet: Packet) => {
const guild = this.client.guilds.get(packet.d.guild_id);
if (guild) guild.shard.send(packet?.op, packet?.d);
};

this.client.on("packet", async (packet: any) => {
this.client.on("packet", async (packet: Packet) => {
this.packetUpdate(packet);
});
break;
Expand All @@ -337,16 +356,18 @@ export class Poru extends EventEmitter {
break;
}
}
}
};

/**
* Handles Voice State Update and Voice Server Update packets.
* @param {any} packet - Packet from Discord API.
* @param {Packet} packet - Packet from Discord API.
* @returns {void}
*/
public packetUpdate(packet: any): void {
public packetUpdate(packet: Packet): void {
if (!["VOICE_STATE_UPDATE", "VOICE_SERVER_UPDATE"].includes(packet.t))
return;
if (!("guild_id" in packet.d)) return;

const player = this.players.get(packet.d.guild_id);
if (!player) return;

Expand All @@ -364,10 +385,10 @@ export class Poru extends EventEmitter {
* @param {NodeGroup} options - Node group options.
* @returns {Node} The added Node instance.
*/
public addNode(options: NodeGroup): Node {
public async addNode(options: NodeGroup): Promise<Node> {
const node = new Node(this, options, this.options);
this.nodes.set(options.name, node);
node.connect();
await node.connect();
return node;
}

Expand Down Expand Up @@ -490,20 +511,9 @@ export class Poru extends EventEmitter {

if (!node) node = this.leastUsedNodes[0];
if (!node) throw new Error("No nodes are available.");
const regex = /^https?:\/\//;

if (regex.test(query)) {
let response = await node.rest.get<LoadTrackResponse>(
`/v4/loadtracks?identifier=${encodeURIComponent(query)}`
);
return new Response(response, requester);
} else {
let track = `${source || "ytsearch"}:${query}`;
let response = await node.rest.get<LoadTrackResponse>(
`/v4/loadtracks?identifier=${encodeURIComponent(track)}`
);
return new Response(response, requester);
}

const response = await node.rest.get<LoadTrackResponse>(`/v4/loadtracks?identifier=${encodeURIComponent((query.startsWith('https://') ? '' : `${source || 'ytsearch'}:`) + query)}`)
return new Response(response, requester);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export enum Config {
version = 4,
version = 5,
clientName = "Poru"
}

0 comments on commit a1586ea

Please sign in to comment.