Skip to content

Commit

Permalink
update player and api
Browse files Browse the repository at this point in the history
  • Loading branch information
appujet committed Jan 10, 2025
1 parent 1f2faa1 commit 7e3bcf4
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 62 deletions.
6 changes: 3 additions & 3 deletions src/api/Api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class Api {
async start() {
await this.fastify.register(helmet);
await this.fastify.register(cors, {
origin: "http://localhost:3000",
origin: env.NEXT_PUBLIC_BASE_URL,
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
});
Expand All @@ -34,8 +34,8 @@ export class Api {
/* user routes */
await this.fastify.register(userRoutes, {
prefix: "/user",
})
});

this.fastify.get("/", (_, reply) =>
reply.send(
`Welcome to the Lavamusic API! Listening on port ${Number(
Expand Down
5 changes: 3 additions & 2 deletions src/commands/music/Play.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
} from "discord.js";
import type { SearchResult } from "lavalink-client";
import { Command, type Context, type Lavamusic } from "../../structures/index";
import { env } from "../../env";

export default class Play extends Command {
constructor(client: Lavamusic) {
Expand Down Expand Up @@ -120,8 +121,8 @@ export default class Play extends Command {
ctx.locale("cmd.play.added_to_queue", {
title: response.tracks[0].info.title,
uri: response.tracks[0].info.uri,
}),
),
}) + "\n\n" + `[Web Player](${env.NEXT_PUBLIC_BASE_URL}/player/${ctx.guild!.id})`,
)
],
});
}
Expand Down
13 changes: 7 additions & 6 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const LavalinkNodeSchema = z.object({
authorization: z.string(),
secure: z.preprocess(
(val) => (val === "true" || val === "false" ? val === "true" : val),
z.boolean().optional(),
z.boolean().optional()
),
sessionId: z.string().optional(),
regions: z.string().array().optional(),
Expand All @@ -31,9 +31,10 @@ const envSchema = z.object({
DEFAULT_LANGUAGE: z.string().default("EnglishUS"),
PREFIX: z.string().default("!"),
API_PORT: z.string().optional().default("8080"),
NEXT_PUBLIC_BASE_URL: z.string().optional(),
OWNER_IDS: z.preprocess(
(val) => (typeof val === "string" ? JSON.parse(val) : val),
z.string().array().optional(),
z.string().array().optional()
),
GUILD_ID: z.string().optional(),
TOPGG: z.string().optional(),
Expand All @@ -47,7 +48,7 @@ const envSchema = z.object({
}
return val;
},
z.enum(["online", "idle", "dnd", "invisible"]).default("online"),
z.enum(["online", "idle", "dnd", "invisible"]).default("online")
),
BOT_ACTIVITY: z.string().default("Lavamusic"),
BOT_ACTIVITY_TYPE: z.preprocess((val) => {
Expand Down Expand Up @@ -75,11 +76,11 @@ const envSchema = z.object({
"yandex",
"jiosaavn",
])
.default("youtube"),
.default("youtube")
),
NODES: z.preprocess(
(val) => (typeof val === "string" ? JSON.parse(val) : val),
z.array(LavalinkNodeSchema),
z.array(LavalinkNodeSchema)
),
GENIUS_API: z.string().optional(),
});
Expand All @@ -91,7 +92,7 @@ export const env: Env = envSchema.parse(process.env);
for (const key in env) {
if (!(key in env)) {
throw new Error(
`Missing env variable: ${key}. Please check the .env file and try again.`,
`Missing env variable: ${key}. Please check the .env file and try again.`
);
}
}
Expand Down
10 changes: 2 additions & 8 deletions src/events/player/TrackStart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,8 @@ export default class TrackStart extends Event {
paused: player?.paused,
repeat: player?.repeatMode,
position: player?.position,
track: player?.queue?.current
? this.client.utils.formatTrack(player?.queue?.current)
: null,
queue: player?.queue?.tracks
? player?.queue?.tracks.map((track) =>
this.client.utils.formatTrack(track as Track)
)
: [],
track: player?.queue?.current,
queue: player?.queue?.tracks,
volume: player?.volume,
});
}
Expand Down
57 changes: 38 additions & 19 deletions src/structures/socket/events/player.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { Socket } from "socket.io";
import { Lavamusic } from "../..";
import { Player, Track } from "lavalink-client";
import { container } from "tsyringe";
import { kClient } from "../../../types";
import { Player } from "lavalink-client";
import { ChannelType } from "discord.js";
import { env } from "../../../env";

export default function playerEvents(socket: Socket, client: Lavamusic) {

const handleError = (socket: Socket, event: string, message: string) => {
socket.emit(`${event}:error`, { message });
};

socket.on("player:create", ({ guildId }) => {
socket.on("player:create", async ({ guildId }) => {
if (!guildId) return;
socket.join(guildId);
client.logger.info(`[Socket] Player created: ${guildId}`);
Expand Down Expand Up @@ -70,9 +69,35 @@ export default function playerEvents(socket: Socket, client: Lavamusic) {
}

if (!player.connected) await player.connect();

const textChannel = guild?.channels.cache.get(textChannelId);
if (!textChannel) return;
if (textChannel.type !== ChannelType.GuildText) return;
const embed = client.embed();
embed
.setColor(client.color.main)
.setAuthor({
name: member.user.username,
iconURL: member.user.displayAvatarURL(),
})
.setDescription(
`[Web Player] Connected to [Dashboard](${env.NEXT_PUBLIC_BASE_URL}/player/${guildId})`
);

textChannel.send({ embeds: [embed] });
}
);

socket.on("player:disconnect", ({ guildId }) => {
const player = client.manager.getPlayer(guildId);
if (!player)
return handleError(socket, "player:disconnect", "Player not found.");

player.destroy();

socket.emit("player:disconnect:success", { connected: false });
});

socket.on("player:control:playpause", ({ guildId }) => {
const player = client.manager.getPlayer(guildId);
if (!player)
Expand Down Expand Up @@ -156,15 +181,14 @@ export default function playerEvents(socket: Socket, client: Lavamusic) {
emitPlayerUpdate(socket, player);
});


socket.on("player:search", async ({ guildId, query, user }) => {
if (!guildId || query === "") return;
const player = client.manager.getPlayer(guildId);
if (!player)
return handleError(socket, "player:search", "Player not found.");

const res = await player.search(query, user);

if ((res && res.loadType === "empty") || res.loadType === "error")
return handleError(socket, "player:search", "Track not found.");
return socket.emit("player:search:success", {
Expand All @@ -179,8 +203,10 @@ export default function playerEvents(socket: Socket, client: Lavamusic) {
if (!player)
return handleError(socket, "player:playTrack", "Player not found.");

await player.play({ track: { encoded: track.encoded, requester: track.requester } });

await player.play({
track: { encoded: track.encoded, requester: track.requester },
});

emitPlayerUpdate(socket, player);
});

Expand All @@ -195,20 +221,13 @@ export default function playerEvents(socket: Socket, client: Lavamusic) {
});
}


export const emitPlayerUpdate = (socket: Socket, player: Player) => {
const client = container.resolve<Lavamusic>(kClient);
socket.emit("player:update:success", {
paused: player?.paused,
repeat: player?.repeatMode,
position: player?.position,
track: player?.queue?.current
? client.utils.formatTrack(player.queue.current)
: null,
queue:
player?.queue?.tracks.map((track) =>
client.utils.formatTrack(track as Track)
) || [],
track: player?.queue?.current,
queue: player?.queue?.tracks,
volume: player?.volume,
});
};
};
2 changes: 1 addition & 1 deletion src/structures/socket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default class SocketServer {
private readonly client: Lavamusic;
private readonly config = {
cors: {
origin: "http://localhost:3000",
origin: env.NEXT_PUBLIC_BASE_URL,
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
},
Expand Down
23 changes: 0 additions & 23 deletions src/utils/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
type TextChannel,
} from "discord.js";
import type { Context, Lavamusic } from "../structures/index";
import { Track } from "lavalink-client";

// biome-ignore lint/complexity/noStaticOnlyClass: <explanation>
export class Utils {
Expand Down Expand Up @@ -197,28 +196,6 @@ export class Utils {
await msg.edit({ embeds: [embed[page]], components: [] });
});
}

public static formatTrack(track: Track) {
if (!track?.info) return {};
return {
encoded: track.encoded,
info: {
title: track.info.title,
uri: track.info.uri,
author: track.info.author,
duration: track.info.duration,
artworkUrl: track.info.artworkUrl,
identifier: track.info.identifier,
...(track.requester !== "unknown" && {
requester: {
id: (track.requester as any).id,
username: (track.requester as any).username,
avatarUrl: (track.requester as any).avatarURL,
},
}),
},
};
}
}

/**
Expand Down

0 comments on commit 7e3bcf4

Please sign in to comment.