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: initialize module #2

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
23 changes: 20 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,27 @@

![Kirishima Banner](https://cdn.discordapp.com/attachments/891939988088975372/931079377771450388/kirishima-ship-banner.png)

# @kirishima/template
# @kirishima/redis-queue

</div>

# Instalation
```
npm install @kirishima/redis-queue @kirishima/core
```

# Features
- lorem
- ipsum
- Written in TypeScript
- Support ESM & CommonJS

# Example
```ts
import { KirishimaQueue } from "@kirishima/redis-queue";
import { Kirishima } from "@kirishima/core";

const kirishima = new Kirishima({
plugins: [
new KirishimaQueue()
]
});
```
21 changes: 15 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
{
"name": "kirishima-template",
"name": "@kirishima/redis-queue",
"author": {
"name": "KagChi"
},
"version": "0.1.0",
"license": "GPL-3.0",
"repository": {
"url": "https://github.com/kirishima-ship/kirishima-template"
"url": "https://github.com/kirishima-ship/redis-queue"
},
"bugs": {
"url": "https://github.com/kirishima-ship/kirishima-template/issues"
"url": "https://github.com/kirishima-ship/redis-queue/issues"
},
"readme": "https://github.com/kirishima-ship/kirishima-template/blob/main/README.md",
"readme": "https://github.com/kirishima-ship/redis-queue/blob/main/README.md",
"engines": {
"node": ">=14.0.0",
"node": ">=16.0.0",
"npm": ">=7.0.0"
},
"scripts": {
Expand All @@ -27,11 +27,20 @@
"@sapphire/eslint-config": "4.3.3",
"@sapphire/prettier-config": "1.4.2",
"@sapphire/ts-config": "3.3.4",
"@types/ws": "^8.5.3",
"eslint": "8.13.0",
"prettier": "2.6.2",
"rimraf": "3.0.2",
"typescript": "4.6.3",
"unbuild": "0.7.4"
},
"prettier": "@sapphire/prettier-config"
"prettier": "@sapphire/prettier-config",
"dependencies": {
"@kirishima/core": "^0.6.4",
"@kirishima/ws": "^0.2.2",
"discord-api-types": "^0.31.1",
"ioredis": "^5.0.4",
"lavalink-api-types": "^0.1.9",
"tiny-typed-emitter": "^2.1.0"
}
}
78 changes: 78 additions & 0 deletions src/Structures/KirishimaPlayer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import {
isPartialTrack,
isTrack,
Kirishima,
KirishimaNode,
KirishimaPartialTrack,
KirishimaPlayerOptions,
KirishimaTrack,
Structure
} from '@kirishima/core';
import { ConnectionState, LoopType } from '../Types';
import { KirishimaQueueTracks } from './KirishimaQueueTracks';
import { KirishimaVoiceConnection } from './KirishimaVoiceConnection';

export class KirishimaPlayer extends Structure.get('KirishimaPlayer') {
public queue: KirishimaQueueTracks;
public loopType: LoopType = LoopType.None;
public connection = new KirishimaVoiceConnection(this);

public constructor(public options: KirishimaPlayerOptions, kirishima: Kirishima, node: KirishimaNode) {
super(options, kirishima, node);
this.queue = new KirishimaQueueTracks(this, ...(options.tracks?.items ?? []));
this.queue.current = options.tracks?.current ?? null;
this.queue.previous = options.tracks?.previous ?? null;
}

public setLoop(type: LoopType) {
this.loopType = type;
return this;
}

public async connect() {
this.connection.state = ConnectionState.Connecting;
const player = await super.connect();
this.connection.state = ConnectionState.Connected;
return player;
}

public async disconnect() {
const player = await super.disconnect();
this.connection.state = ConnectionState.Disconnected;
return player;
}

public resolvePartialTrack(track: KirishimaPartialTrack) {
return this.kirishima.resolveTracks(`${track.info?.title} - ${track.info?.author ? track.info.author : ''}`);
}

public async playTrack(track?: KirishimaTrack | KirishimaPartialTrack | string) {
if (track && isTrack(track)) {
return super.playTrack(track);
}

if (this.queue.current && isTrack(this.queue.current)) {
return super.playTrack(this.queue.current);
}

if (track && isPartialTrack(track)) {
const resolved = await this.resolvePartialTrack(track);
if (resolved.tracks.length && isTrack(resolved.tracks[0])) {
return super.playTrack(resolved.tracks[0].track);
}
}

if (this.queue.current && isPartialTrack(this.queue.current)) {
const resolved = await this.resolvePartialTrack(this.queue.current);
if (resolved.tracks.length && isTrack(resolved.tracks[0])) {
return super.playTrack(resolved.tracks[0].track);
}
}

throw new Error('No track to play');
}

public get connected() {
return Boolean(this.voiceServer && this.voiceState?.channel_id && this.connection.state === ConnectionState.Connected);
}
}
150 changes: 150 additions & 0 deletions src/Structures/KirishimaQueue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { isPartialTrack, Kirishima, KirishimaNode, KirishimaPlayerOptions, KirishimaPlugin, Structure } from '@kirishima/core';
import type { Gateway } from '@kirishima/ws';
import Redis from 'ioredis';
import {
TrackEndEventPayload,
TrackExceptionEventPayload,
TrackStartEventPayload,
TrackStuckEventPayload,
WebSocketTypeEnum
} from 'lavalink-api-types';
import { QueueOptions, NodeTrackRawMessage, LoopType } from '../Types';
import { KirishimaPlayer } from './KirishimaPlayer';

export class KirishimaQueue extends KirishimaPlugin {
private redisInstance: Redis;
private kirishima!: Kirishima;
public constructor(public options: QueueOptions = { name: 'KirishimaQueue' }) {
super({
name: options.name
});
this.redisInstance = options.redis instanceof Redis ? options.redis : new Redis(options.redis!);
}

public load(kirishima: Kirishima) {
Structure.extend('KirishimaPlayer', () => KirishimaPlayer);
kirishima.options.fetchPlayer = this.defaultFetchPlayerHandler.bind(this);
kirishima.options.spawnPlayer = this.defaultSpawnPlayerHandler.bind(this);
kirishima.redisInstance = this.redisInstance;
kirishima.on('nodeRaw', (node: KirishimaNode, gateway: Gateway, message: NodeTrackRawMessage) =>
this.handleNodeRaw(node, gateway, message, kirishima)
);

this.kirishima = kirishima;
}

private handleNodeRaw(_node: KirishimaNode, _gateway: Gateway, message: NodeTrackRawMessage, kirishima: Kirishima) {
const player = kirishima.options.fetchPlayer!(message.guildId) as KirishimaPlayer | null;
if (!player) return;

if (message.type === WebSocketTypeEnum.TrackEndEvent) {
void this.trackEnd(player, message, kirishima);
}

if (message.type === WebSocketTypeEnum.TrackExceptionEvent) {
this.trackException(player, message, kirishima);
}

if (message.type === WebSocketTypeEnum.TrackStuckEvent) {
this.trackStuck(player, message, kirishima);
}

if (message.type === WebSocketTypeEnum.TrackStartEvent) {
this.trackStart(player, message, kirishima);
}
}

private async trackEnd(player: KirishimaPlayer, message: TrackEndEventPayload, kirishima: Kirishima) {
if (message.reason === 'REPLACED') return;
try {
player.playing = false;
if (player.loopType === LoopType.Track) {
if (isPartialTrack(player.queue.current) && player.queue.current) {
const track = await player.resolvePartialTrack(player.queue.current);
if (track.tracks.length) {
await player.playTrack(track.tracks[0].track);
return;
}
await player.stopTrack();
return;
}

if (player.queue.current) {
await player.playTrack(player.queue.current);
return;
}
}

if (player.queue.current && player.loopType === LoopType.Queue) {
await player.queue.add(player.queue.current);
player.queue.previous = player.queue.current;
player.queue.current = player.queue.shift() ?? null;

if (player.queue.current) {
if (isPartialTrack(player.queue.current)) {
const track = await player.resolvePartialTrack(player.queue.current);
if (track.tracks.length) {
await player.playTrack(track.tracks[0].track);
return;
}
await player.stopTrack();
return;
}

await player.playTrack(player.queue.current!);
return;
}
kirishima.emit('queueEnd', player, player);
}

player.queue.previous = player.queue.current;
player.queue.current = player.queue.shift() ?? null;

if (player.queue.current) {
if (isPartialTrack(player.queue.current)) {
const track = await player.resolvePartialTrack(player.queue.current);
if (track.tracks.length) {
await player.playTrack(track.tracks[0].track);
return;
}
await player.stopTrack();
return;
}

await player.playTrack(player.queue.current!);
return;
}
kirishima.emit('queueEnd', player, player);
} catch (e) {
kirishima.emit('playerError', player, e);
}
}

private trackException(player: KirishimaPlayer, message: TrackExceptionEventPayload, kirishima: Kirishima) {
kirishima.emit('trackException', player, player.queue.current, message);
}

private trackStuck(player: KirishimaPlayer, message: TrackStuckEventPayload, kirishima: Kirishima) {
kirishima.emit('trackStuck', player, player.queue.current, message);
}

private trackStart(player: KirishimaPlayer, message: TrackStartEventPayload, kirishima: Kirishima) {
player.playing = true;
kirishima.emit('trackStart', player, player.queue.current, message);
}

private async defaultFetchPlayerHandler(guildId: string) {
const playerCache = await this.redisInstance.hget(`${this.options.name}:${guildId}`, 'player');
const player = playerCache ? (JSON.parse(playerCache) as KirishimaPlayerOptions) : null;
if (!player) return null;
return new KirishimaPlayer(player, this.kirishima, this.kirishima.resolveNode(player!.node)!);
}

private async defaultSpawnPlayerHandler(guildId: string, options: KirishimaPlayerOptions, node: KirishimaNode) {
const player = await this.kirishima.options.fetchPlayer!(guildId);
if (player) return player;
const kirishimaPlayer = new (Structure.get('KirishimaPlayer'))(options, this.kirishima, node);
await this.redisInstance.hset(guildId, JSON.stringify({ tracks: [], voiceState: undefined, node: node.options.identifier }));
return kirishimaPlayer;
}
}
89 changes: 89 additions & 0 deletions src/Structures/KirishimaQueueTracks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { isPartialTrack, isTrack, KirishimaPartialTrack, KirishimaTrack } from '@kirishima/core';
import type { KirishimaPlayer } from './KirishimaPlayer';

export class KirishimaQueueTracks extends Array<KirishimaPartialTrack | KirishimaTrack> {
public current: KirishimaPartialTrack | KirishimaTrack | null = null;
public previous: KirishimaPartialTrack | KirishimaTrack | null = null;

public constructor(public kirishimaPlayer: KirishimaPlayer, ...items: (KirishimaPartialTrack | KirishimaTrack)[]) {
super(...items);
}

public async add(trackOrTracks: KirishimaPartialTrack | KirishimaTrack | (KirishimaPartialTrack | KirishimaTrack)[]) {
if (!ValidateValidTracks(trackOrTracks)) throw new Error('Track(s) must be a "KirishimaPartialTrack" or "KirishimaTrack".');
if (!this.current) {
if (!Array.isArray(trackOrTracks)) {
this.current = trackOrTracks;
await this.kirishimaPlayer.kirishima.redisInstance.hset(
`kirishimaQueue:${this.kirishimaPlayer.connection.guildId}`,
'track',
JSON.stringify({ current: this.current, previous: this.previous })
);
return;
}
this.current = (trackOrTracks = [...trackOrTracks]).shift()!;
await this.kirishimaPlayer.kirishima.redisInstance.hset(
`kirishimaQueue:${this.kirishimaPlayer.connection.guildId}`,
'track',
JSON.stringify({ current: this.current, previous: this.previous })
);
}

if (Array.isArray(trackOrTracks)) {
this.push(...trackOrTracks);
for (const track of trackOrTracks) {
await this.kirishimaPlayer.kirishima.redisInstance.rpush(
`kirishimaQueueTracks:${this.kirishimaPlayer.connection.guildId}`,
JSON.stringify(track)
);
}
} else {
await this.kirishimaPlayer.kirishima.redisInstance.rpush(
`kirishimaQueueTracks:${this.kirishimaPlayer.connection.guildId}`,
JSON.stringify(trackOrTracks)
);
this.push(trackOrTracks);
}
}

public get totalSize() {
return this.length + (this.current ? 1 : 0);
}

public get size() {
return this.length;
}

public async clear(clearPlayer = true) {
this.splice(0);
await this.kirishimaPlayer.kirishima.redisInstance.del(`kirishimaQueueTracks:${this.kirishimaPlayer.connection.guildId}`);
if (clearPlayer) await this.kirishimaPlayer.kirishima.redisInstance.del(`kirishimaQueue:${this.kirishimaPlayer.connection.guildId}`);
}

public async shuffle() {
const list = await this.kirishimaPlayer.kirishima.redisInstance.lrange(
`kirishimaQueueTracks:${this.kirishimaPlayer.connection.guildId}`,
0,
-1
);
for (let i = list.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[list[i], list[j]] = [list[j], list[i]];
}
await this.clear(false);
for (const track of list) {
await this.kirishimaPlayer.kirishima.redisInstance.rpush(`kirishimaQueueTracks:${this.kirishimaPlayer.connection.guildId}`, track);
}
}
}

export function ValidateValidTracks(tracks: KirishimaPartialTrack | KirishimaTrack | (KirishimaPartialTrack | KirishimaTrack)[]) {
if (Array.isArray(tracks)) {
for (const track of tracks) {
if (!(isTrack(track) || isPartialTrack(track))) return false;
}
return true;
}

return isTrack(tracks) || isPartialTrack(tracks);
}
Loading