Skip to content

Commit

Permalink
ref: add some whitespaces
Browse files Browse the repository at this point in the history
  • Loading branch information
Vann-Dev committed Dec 5, 2023
1 parent 411ebe9 commit 7e6b36e
Show file tree
Hide file tree
Showing 14 changed files with 135 additions and 139 deletions.
10 changes: 5 additions & 5 deletions packages/core/src/Structures/BasePlayer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { GatewayVoiceServerUpdateDispatch, GatewayVoiceStateUpdateDispatch } from 'discord-api-types/gateway/v9';
import { Snowflake } from 'discord-api-types/globals';
import { WebsocketOpEnum } from 'lavalink-api-types';
import { KirishimaPlayerOptions, KirishimaNode, createVoiceChannelJoinPayload, Kirishima } from '../index.js';
import { GatewayVoiceServerUpdateDispatch, GatewayVoiceStateUpdateDispatch } from "discord-api-types/gateway/v9";
import { Snowflake } from "discord-api-types/globals";
import { WebsocketOpEnum } from "lavalink-api-types";
import { KirishimaPlayerOptions, KirishimaNode, createVoiceChannelJoinPayload, Kirishima } from "../index.js";

export class BasePlayer {
public get voiceState() {

Check failure on line 7 in packages/core/src/Structures/BasePlayer.ts

View workflow job for this annotation

GitHub Actions / test / lint

Missing return type on function
Expand Down Expand Up @@ -57,4 +57,4 @@ export class BasePlayer {
});
}
}
}
}
4 changes: 2 additions & 2 deletions packages/core/src/Structures/Filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
TimeScaleEqualizer,
TremoloEqualizer,
VibratoEqualizer
} from 'lavalink-api-types';
} from "lavalink-api-types";

export class KirishimaFilter {
public volume: number | null;
Expand Down Expand Up @@ -47,4 +47,4 @@ export interface KirishimaFilterOptions {
distortion: DistortionEqualizer | null;
channelMix: ChannelMixEqualizer | null;
lowPass: LowPassEqualizer | null;
}
}
58 changes: 29 additions & 29 deletions packages/core/src/Structures/Kirishima.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
import { EventEmitter } from 'node:events';
import type { KirishimaNodeOptions, KirishimaOptions, KirishimaPlayerOptions, LoadTrackResponse } from '../typings/index.js';
import crypto from 'node:crypto';
import { EventEmitter } from "node:events";
import { KirishimaNodeOptions, KirishimaOptions, KirishimaPlayerOptions, LoadTrackResponse } from "../typings/index.js";
import crypto from "node:crypto";

import { KirishimaNode } from './Node.js';
import { GatewayVoiceServerUpdateDispatch, GatewayVoiceStateUpdateDispatch } from 'discord-api-types/gateway/v9';
import { Collection } from '@discordjs/collection';
import { KirishimaPlayer } from './Player.js';
import { Structure } from './Structure.js';
import { KirishimaNode } from "./Node.js";
import { GatewayVoiceServerUpdateDispatch, GatewayVoiceStateUpdateDispatch } from "discord-api-types/gateway/v9";
import { Collection } from "@discordjs/collection";
import { KirishimaPlayer } from "./Player.js";
import { Structure } from "./Structure.js";

export class Kirishima extends EventEmitter {
public nodes: Collection<string, KirishimaNode> = new Collection();
public nodes = new Collection<string, KirishimaNode>();
public players?: Collection<string, KirishimaPlayer>;
public constructor(public options: KirishimaOptions) {
super();

if (typeof options.send !== 'function') throw Error('Send function must be present and must be a function.');
if (typeof options.send !== "function") throw Error("Send function must be present and must be a function.");

if (
typeof options.spawnPlayer !== 'function' ||
(typeof options.spawnPlayer === undefined && (typeof options.fetchPlayer !== 'function' || typeof options.fetchPlayer === undefined))
typeof options.spawnPlayer !== "function" ||
(typeof options.spawnPlayer === undefined && (typeof options.fetchPlayer !== "function" || typeof options.fetchPlayer === undefined))

Check failure on line 22 in packages/core/src/Structures/Kirishima.ts

View workflow job for this annotation

GitHub Actions / test / lint

Unnecessary conditional, the types have no overlap

Check failure on line 22 in packages/core/src/Structures/Kirishima.ts

View workflow job for this annotation

GitHub Actions / test / lint

Invalid typeof comparison value

Check failure on line 22 in packages/core/src/Structures/Kirishima.ts

View workflow job for this annotation

GitHub Actions / test / lint

Unnecessary conditional, the types have no overlap
) {
this.players = new Collection();
options.spawnPlayer = this.defaultSpawnPlayerHandler.bind(this);
}

if (
typeof options.fetchPlayer !== 'function' ||
(typeof options.fetchPlayer === undefined && (typeof options.spawnPlayer !== 'function' || typeof options.spawnPlayer === undefined))
typeof options.fetchPlayer !== "function" ||
(typeof options.fetchPlayer === undefined && (typeof options.spawnPlayer !== "function" || typeof options.spawnPlayer === undefined))
) {
options.fetchPlayer = this.defaultFetchPlayerHandler.bind(this);
}

if (!options.nodes.length) throw new Error('Nodes option must not a empty array');
if (!options.nodes.length) throw new Error("Nodes option must not a empty array");
}

public async initialize(clientId?: string) {
if (!clientId && !this.options.clientId) throw new Error('Invalid clientId provided');
if (!clientId && !this.options.clientId) throw new Error("Invalid clientId provided");
if (clientId && !this.options.clientId) this.options.clientId = clientId;
if (this.options.plugins) {
for (const plugin of [...this.options.plugins.values()]) {
Expand All @@ -50,15 +50,15 @@ export class Kirishima extends EventEmitter {
const isArray = Array.isArray(nodeOrNodes);
if (isArray) {
for (const node of nodeOrNodes) {
const kirishimaNode = new (Structure.get('KirishimaNode'))(node, this);
const kirishimaNode = new (Structure.get("KirishimaNode"))(node, this);
await kirishimaNode.connect();
this.nodes.set((node.identifier ??= crypto.randomBytes(4).toString('hex')), kirishimaNode);
this.nodes.set(node.identifier ??= crypto.randomBytes(4).toString("hex"), kirishimaNode);
}
return this;
}
const kirishimaNode = new (Structure.get('KirishimaNode'))(nodeOrNodes, this);
const kirishimaNode = new (Structure.get("KirishimaNode"))(nodeOrNodes, this);
await kirishimaNode.connect();
this.nodes.set((nodeOrNodes.identifier ??= crypto.randomBytes(4).toString('hex')), kirishimaNode);
this.nodes.set(nodeOrNodes.identifier ??= crypto.randomBytes(4).toString("hex"), kirishimaNode);
return this;
}

Expand All @@ -73,16 +73,16 @@ export class Kirishima extends EventEmitter {
}

public resolveNode(identifierOrGroup?: string) {
const resolveGroupedNode = this.nodes.filter((x) => x.connected).find((x) => x.options.group?.includes(identifierOrGroup!)!);
const resolveGroupedNode = this.nodes.filter(x => x.connected).find(x => x.options.group?.includes(identifierOrGroup!)!);
if (resolveGroupedNode) return resolveGroupedNode;
const resolveIdenfitierNode = this.nodes.filter((x) => x.connected).find((x) => x.options.identifier === identifierOrGroup);
const resolveIdenfitierNode = this.nodes.filter(x => x.connected).find(x => x.options.identifier === identifierOrGroup);
if (resolveIdenfitierNode) return resolveIdenfitierNode;
return this.resolveBestNode().first();
}

public resolveBestNode() {
return this.nodes
.filter((x) => x.connected)
.filter(x => x.connected)
.sort((x, y) => {
const XLoad = x.stats?.cpu ? (x.stats.cpu.systemLoad / x.stats.cpu.cores) * 100 : 0;
const YLoad = y.stats?.cpu ? (y.stats.cpu.systemLoad / y.stats.cpu.cores) * 100 : 0;
Expand All @@ -93,7 +93,7 @@ export class Kirishima extends EventEmitter {
public async resolveTracks(options: string | { source?: string | undefined; query: string }, node?: KirishimaNode): Promise<LoadTrackResponse> {
node ??= this.resolveNode();
const resolveTracks = await node!.rest.loadTracks(options);
if (resolveTracks?.tracks.length) resolveTracks.tracks = resolveTracks.tracks.map((x) => new (Structure.get('KirishimaTrack'))(x));
if (resolveTracks.tracks.length) resolveTracks.tracks = resolveTracks.tracks.map(x => new (Structure.get("KirishimaTrack"))(x));
return resolveTracks as unknown as LoadTrackResponse;
}

Expand All @@ -113,24 +113,24 @@ export class Kirishima extends EventEmitter {
}
}

public async handleRawPacket(t: 'VOICE_SERVER_UPDATE' | 'VOICE_STATE_UPDATE', packet: unknown) {
if (t === 'VOICE_STATE_UPDATE') {
public async handleRawPacket(t: "VOICE_SERVER_UPDATE" | "VOICE_STATE_UPDATE", packet: unknown) {
if (t === "VOICE_STATE_UPDATE") {
await this.handleVoiceStateUpdate(packet as GatewayVoiceStateUpdateDispatch);
}
if (t === 'VOICE_SERVER_UPDATE') {
if (t === "VOICE_SERVER_UPDATE") {
await this.handleVoiceServerUpdate(packet as GatewayVoiceServerUpdateDispatch);
}
}

private defaultSpawnPlayerHandler(guildId: string, options: KirishimaPlayerOptions, node: KirishimaNode) {
const player = this.players!.has(guildId);
if (player) return this.players!.get(guildId)!;
const kirishimaPlayer = new (Structure.get('KirishimaPlayer'))(options, this, node);
const kirishimaPlayer = new (Structure.get("KirishimaPlayer"))(options, this, node);
this.players!.set(guildId, kirishimaPlayer);
return kirishimaPlayer;
}

private defaultFetchPlayerHandler(guildId: string) {
return this.players!.get(guildId);
}
}
}
64 changes: 32 additions & 32 deletions packages/core/src/Structures/Node.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { WebSocket } from 'ws';
import { Gateway } from '@kirishima/ws';
import { REST } from '@kirishima/rest';
import type { KirishimaNodeOptions } from '../typings/index.js';
import type { Kirishima } from './Kirishima.js';
import { GatewayVoiceServerUpdateDispatch, GatewayVoiceStateUpdateDispatch } from 'discord-api-types/gateway/v9';
import { LavalinkStatsPayload, WebsocketOpEnum } from 'lavalink-api-types';
import { BasePlayer } from './BasePlayer.js';
import { Collection } from '@discordjs/collection';
import { Snowflake } from 'discord-api-types/globals';
import { WebSocket } from "ws";
import { Gateway } from "@kirishima/ws";
import { REST } from "@kirishima/rest";
import { KirishimaNodeOptions } from "../typings/index.js";
import { Kirishima } from "./Kirishima.js";
import { GatewayVoiceServerUpdateDispatch, GatewayVoiceStateUpdateDispatch } from "discord-api-types/gateway/v9";
import { LavalinkStatsPayload, WebsocketOpEnum } from "lavalink-api-types";
import { BasePlayer } from "./BasePlayer.js";
import { Collection } from "@discordjs/collection";
import { Snowflake } from "discord-api-types/globals";

export class KirishimaNode {
public ws!: Gateway;
public rest!: REST;
public stats: LavalinkStatsPayload | undefined;
public reconnect: { attempts: number; timeout?: NodeJS.Timeout } = { attempts: 0 };
public voiceServers: Collection<Snowflake, GatewayVoiceServerUpdateDispatch['d']> = new Collection();
public voiceStates: Collection<Snowflake, GatewayVoiceStateUpdateDispatch['d']> = new Collection();
public voiceServers = new Collection<Snowflake, GatewayVoiceServerUpdateDispatch["d"]>();
public voiceStates = new Collection<Snowflake, GatewayVoiceStateUpdateDispatch["d"]>();
public constructor(public options: KirishimaNodeOptions, public kirishima: Kirishima) { }

public get connected() {
Expand All @@ -24,29 +24,29 @@ export class KirishimaNode {
}

public async connect(): Promise<KirishimaNode> {
this.rest ??= new REST(`${this.options.url.endsWith('443') || this.options.secure ? 'https' : 'http'}://${this.options.url}`, {
Authorization: (this.options.password ??= 'youshallnotpass')
this.rest ??= new REST(`${this.options.url.endsWith("443") || this.options.secure ? "https" : "http"}://${this.options.url}`, {
Authorization: this.options.password ??= "youshallnotpass"
});
if (this.connected) return this;
const headers = {
Authorization: (this.options.password ??= 'youshallnotpass'),
'User-Id': this.kirishima.options.clientId!,
'Client-Name': (this.kirishima.options.clientName ??= `Kirishima NodeJS Lavalink Client (https://github.com/kirishima-ship/core)`)
Authorization: this.options.password ??= "youshallnotpass",
"User-Id": this.kirishima.options.clientId!,
"Client-Name": this.kirishima.options.clientName ??= "Kirishima NodeJS Lavalink Client (https://github.com/kirishima-ship/core)"
};

// @ts-expect-error If you know how to fix this, please open a PR.
if (this.kirishima.options.node?.resumeKey) headers['Resume-Key'] = this.kirishima.options.node.resumeKey;
this.ws = new Gateway(`${this.options.url.endsWith('443') || this.options.secure ? 'wss' : 'ws'}://${this.options.url}`, headers);
if (this.kirishima.options.node?.resumeKey) headers["Resume-Key"] = this.kirishima.options.node.resumeKey;
this.ws = new Gateway(`${this.options.url.endsWith("443") || this.options.secure ? "wss" : "ws"}://${this.options.url}`, headers);
await this.ws.connect();
this.ws.on('open', () => this.open.bind(this));
this.ws.on('message', () => this.message.bind(this))
this.ws.on('error', () => this.error.bind(this));
this.ws.on('close', () => this.close.bind(this));
this.ws.on("open", () => this.open.bind(this));
this.ws.on("message", () => this.message.bind(this));
this.ws.on("error", () => this.error.bind(this));
this.ws.on("close", () => this.close.bind(this));
return this;
}

public disconnect() {
this.ws.connection?.close(1000, 'Disconnected by user');
this.ws.connection?.close(1000, "Disconnected by user");
if (this.reconnect.timeout) clearTimeout(this.reconnect.timeout);
}

Expand All @@ -59,35 +59,35 @@ export class KirishimaNode {
timeout: this.kirishima.options.node.resumeTimeout
});
}
this.kirishima.emit('nodeConnect', this, gateway);
this.kirishima.emit("nodeConnect", this, gateway);
}

public close(gateway: Gateway, close: number) {
this.kirishima.emit('nodeDisconnect', this, gateway, close);
this.kirishima.emit("nodeDisconnect", this, gateway, close);
if (this.kirishima.options.node && this.kirishima.options.node.reconnectOnDisconnect) {
if (this.reconnect.attempts < (this.kirishima.options.node.reconnectAttempts ?? 3)) {
this.reconnect.attempts++;
this.kirishima.emit('nodeReconnect', this, gateway, close);
this.kirishima.emit("nodeReconnect", this, gateway, close);
this.reconnect.timeout = setTimeout(() => {
void this.connect();
}, this.kirishima.options.node.reconnectInterval ?? 5000);
} else {
this.kirishima.emit('nodeReconnectFailed', this, gateway, close);
this.kirishima.emit("nodeReconnectFailed", this, gateway, close);
}
}
}

public error(gateway: Gateway, error: Error) {
this.kirishima.emit('nodeError', this, gateway, error);
this.kirishima.emit("nodeError", this, gateway, error);
}

public message(gateway: Gateway, raw: string) {
try {
const message = JSON.parse(raw);
this.kirishima.emit('nodeRaw', this, gateway, message);
this.kirishima.emit("nodeRaw", this, gateway, message);
if (message.op === WebsocketOpEnum.STATS) this.stats = message;
} catch (e) {
this.kirishima.emit('nodeError', this, gateway, e);
this.kirishima.emit("nodeError", this, gateway, e);
}
}

Expand All @@ -114,4 +114,4 @@ export class KirishimaNode {
await player.setStateUpdate(packet);
}
}
}
}
8 changes: 4 additions & 4 deletions packages/core/src/Structures/PartialTrack.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Awaitable } from '@sapphire/utilities';
import { PartialLavalinkTrack } from 'src/typings/index.js';
import { Awaitable } from "@sapphire/utilities";
import { PartialLavalinkTrack } from "src/typings/index.js";

/**
* @description Represents a unplayable track by lavalink. This is a partial track. that must be resolved later
*/
export class KirishimaPartialTrack {
public track?: string;
public info: PartialLavalinkTrack['info'];
public info: PartialLavalinkTrack["info"];
public constructor(raw: PartialLavalinkTrack) {
this.track = raw.track;
this.info = raw.info;
Expand All @@ -22,4 +22,4 @@ export class KirishimaPartialTrack {
public thumbnailURL(_size?: unknown): Awaitable<string | null> {
return null;
}
}
}
24 changes: 12 additions & 12 deletions packages/core/src/Structures/Player.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Kirishima } from './Kirishima.js';
import type { KirishimaPlayerOptions } from '../typings/index.js';
import { KirishimaNode, isTrack } from '../index.js';
import { Kirishima } from "./Kirishima.js";
import { KirishimaPlayerOptions } from "../typings/index.js";
import { KirishimaNode, isTrack } from "../index.js";

import {
ChannelMixEqualizer,
Expand All @@ -13,14 +13,14 @@ import {
TremoloEqualizer,
VibratoEqualizer,
WebsocketOpEnum
} from 'lavalink-api-types';
import { KirishimaTrack } from './Track.js';
import { KirishimaFilter, KirishimaFilterOptions } from './Filter.js';
import { Structure } from './Structure.js';
import { BasePlayer } from './BasePlayer.js';
} from "lavalink-api-types";
import { KirishimaTrack } from "./Track.js";
import { KirishimaFilter, KirishimaFilterOptions } from "./Filter.js";
import { Structure } from "./Structure.js";
import { BasePlayer } from "./BasePlayer.js";

export class KirishimaPlayer extends BasePlayer {
public filters = new (Structure.get('KirishimaFilter'))();
public filters = new (Structure.get("KirishimaFilter"))();
public paused = false;
public playing = false;

Expand Down Expand Up @@ -56,7 +56,7 @@ export class KirishimaPlayer extends BasePlayer {
}

public async setVolume(volume: number) {
if (volume < 0 || volume > 500) throw new Error('Volume must be between 0 and 500');
if (volume < 0 || volume > 500) throw new Error("Volume must be between 0 and 500");
this.filters.volume = volume / 100;
await this.node.ws.send({
op: WebsocketOpEnum.FILTERS,
Expand Down Expand Up @@ -183,6 +183,6 @@ export class KirishimaPlayer extends BasePlayer {
});
return this;
}
throw new Error('There are no playing track currently.');
throw new Error("There are no playing track currently.");
}
}
}
6 changes: 3 additions & 3 deletions packages/core/src/Structures/Plugin.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Awaitable } from '@sapphire/utilities';
import { Kirishima } from './Kirishima.js';
import { Awaitable } from "@sapphire/utilities";
import { Kirishima } from "./Kirishima.js";

export abstract class KirishimaPlugin {
public constructor(public options: { name: string }) { }
public abstract load(kirishima: Kirishima): Awaitable<unknown>;
}
}
Loading

0 comments on commit 7e6b36e

Please sign in to comment.