Initial Commit
This commit is contained in:
commit
6d2e379a0c
41 changed files with 5064 additions and 0 deletions
71
src/commands/game/dice.js
Normal file
71
src/commands/game/dice.js
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { SlashCommandBuilder, subtext } from "discord.js";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
import { getRandomInt } from "../../features/utilities.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("dice")
|
||||
.setDescription("Lance un ou plusieurs dés")
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName("number")
|
||||
.setDescription("Nombre de dés a lancer")
|
||||
.setRequired(true)
|
||||
)
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName("faces")
|
||||
.setDescription("Nombre de faces sur le dé")
|
||||
.setRequired(true)
|
||||
),
|
||||
async execute(interaction) {
|
||||
const number = interaction.options.getInteger("number");
|
||||
const faces = interaction.options.getInteger("faces");
|
||||
var sum = 0;
|
||||
var message = "Alors du coup... 🥁\n";
|
||||
var tails = 0;
|
||||
var heads = 0;
|
||||
|
||||
if (faces === 1 || faces === 0) {
|
||||
await interaction.reply({
|
||||
content: "Ouais ouais, bien sur. Allez, bisous !",
|
||||
ephemeral: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (faces === 2) {
|
||||
message = message + subtext(`Pile = 1 et Face = 2\n`);
|
||||
}
|
||||
|
||||
await interaction.reply(message);
|
||||
|
||||
for (let i = 0; i < number; i++) {
|
||||
await setTimeout(1_500);
|
||||
let random = getRandomInt(faces) + 1;
|
||||
random === 1 ? tails++ : heads++;
|
||||
sum = sum + random;
|
||||
|
||||
message = message + `[ ${random} ] ${i === number - 1 ? "\n" : " "}`;
|
||||
interaction.editReply(message);
|
||||
}
|
||||
|
||||
if (number > 1 && faces > 2) {
|
||||
await setTimeout(1_000);
|
||||
message = message + subtext(`Soit au total : ${sum}`);
|
||||
}
|
||||
|
||||
if (number > 1 && faces === 2) {
|
||||
await setTimeout(1_000);
|
||||
message =
|
||||
message +
|
||||
subtext(
|
||||
`Soit au total : ${sum}, ou bien ${tails} piles et ${heads} faces \n`
|
||||
);
|
||||
}
|
||||
|
||||
interaction.editReply(message);
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
44
src/commands/game/maketeam.js
Normal file
44
src/commands/game/maketeam.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { SlashCommandBuilder } from "discord.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("maketeam")
|
||||
.setDescription("Crée des equipes au hasard")
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName("number")
|
||||
.setDescription("Nombre d'équipe")
|
||||
.setRequired(true)
|
||||
)
|
||||
.addStringOption((option) =>
|
||||
option
|
||||
.setName("players")
|
||||
.setDescription("Liste des joueurs, séparés par un espace")
|
||||
.setRequired(true)
|
||||
),
|
||||
async execute(interaction) {
|
||||
const teamNumber = interaction.options.getInteger("number");
|
||||
const players = interaction.options.getString("players");
|
||||
const playersArray = players.split(" ");
|
||||
|
||||
const teams = Array.from({ length: teamNumber }, () => []);
|
||||
const shuffledPlayers = [...playersArray].sort(() => Math.random() - 0.5);
|
||||
|
||||
shuffledPlayers.forEach((player, index) => {
|
||||
const teamIndex = index % teamNumber;
|
||||
teams[teamIndex].push(player);
|
||||
});
|
||||
|
||||
let message = "";
|
||||
let teamList = "";
|
||||
|
||||
teams.forEach((team, index) => {
|
||||
teamList = `${teamList}\n${index + 1}. ${team.join(", ")}`;
|
||||
});
|
||||
|
||||
message = `Yop ! Voici les équipes proposés :\n${teamList}`;
|
||||
await interaction.reply(message);
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
31
src/commands/utility/deletemsgs.js
Normal file
31
src/commands/utility/deletemsgs.js
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { SlashCommandBuilder } from "discord.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("deletemsgs")
|
||||
.setDescription("Supprime tous les messages, sauf ceux épinglés"),
|
||||
async execute(interaction) {
|
||||
let textChannel = interaction.client.channels.cache.get(
|
||||
interaction.channelId
|
||||
);
|
||||
|
||||
textChannel.messages
|
||||
.fetch({ limit: 100 })
|
||||
.then((fetched) => {
|
||||
const notPinned = fetched.filter((fetchedMsg) => !fetchedMsg.pinned);
|
||||
textChannel.bulkDelete(notPinned, true);
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] Command : Delete Messages used`
|
||||
);
|
||||
})
|
||||
.catch(console.error);
|
||||
|
||||
interaction.reply("Et voila, c'est tout propre ! 🐱").then(() => {
|
||||
setTimeout(() => {
|
||||
interaction.deleteReply();
|
||||
}, 7000);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
27
src/commands/utility/listcommand.js
Normal file
27
src/commands/utility/listcommand.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { SlashCommandBuilder } from "discord.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("listcommand")
|
||||
.setDescription("Affiche la liste des commandes disponibles"),
|
||||
async execute(interaction) {
|
||||
let message = `Voila la liste des commandes que tu peux utiliser :
|
||||
__Categorie Utililaires__ :
|
||||
\`/deletemsgs\`: Supprime les 100 derniers messages non épinglés
|
||||
|
||||
__Categorie Vocal__ :
|
||||
\`/muteall\`: Rends tout le monde muet
|
||||
\`/unmuteall\`: Rends la parole à tout le monde
|
||||
\`/deafall\`: Rends tout le monde sourd
|
||||
\`/undeafall\`: Rends l'ouïe à tout le monde
|
||||
|
||||
__Categorie Jeux__ :
|
||||
\`/dice\`: Lance un ou plusieurs dés avec un nombre de faces choisi
|
||||
\`/maketeam\`: Crée un certain nombre d'équipes en renseignant des joueurs (séparés par un espace)
|
||||
`;
|
||||
|
||||
await interaction.reply({ content: message, ephemeral: true });
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
13
src/commands/utility/ping.js
Normal file
13
src/commands/utility/ping.js
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { SlashCommandBuilder } from "discord.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("ping")
|
||||
.setDescription("Reponds avec Pong"),
|
||||
async execute(interaction) {
|
||||
console.log(interaction);
|
||||
await interaction.reply({ content: "Euh... Pong ! 🐱", ephemeral: true });
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
14
src/commands/vocal/deafall.js
Normal file
14
src/commands/vocal/deafall.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus } from "../../features/utilities.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("deafall")
|
||||
.setDescription("Deaf tout le monde dans le lounge"),
|
||||
async execute(interaction) {
|
||||
changeVoiceStatus(interaction.client, "deaf", "all");
|
||||
await interaction.reply("On n'entends plus rien ! 🐱");
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
14
src/commands/vocal/muteall.js
Normal file
14
src/commands/vocal/muteall.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus } from "../../features/utilities.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("muteall")
|
||||
.setDescription("Mute tout le monde dans le lounge"),
|
||||
async execute(interaction) {
|
||||
changeVoiceStatus(interaction.client, "mute", "all");
|
||||
await interaction.reply("Voila, tout le monde est mioute ! 🐱");
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
14
src/commands/vocal/undeafall.js
Normal file
14
src/commands/vocal/undeafall.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus } from "../../features/utilities.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("undeafall")
|
||||
.setDescription("Undeaf tout le monde dans le lounge"),
|
||||
async execute(interaction) {
|
||||
changeVoiceStatus(interaction.client, "undeaf", "all");
|
||||
await interaction.reply("Voila, les oreilles sont réparées ! 🐱");
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
14
src/commands/vocal/unmuteall.js
Normal file
14
src/commands/vocal/unmuteall.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus } from "../../features/utilities.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("unmuteall")
|
||||
.setDescription("Unmute tout le monde dans le lounge"),
|
||||
async execute(interaction) {
|
||||
changeVoiceStatus(interaction.client, "unmute", "all");
|
||||
await interaction.reply("Et.... unmioute ! 🐱");
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
49
src/config.js
Normal file
49
src/config.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
const requiredVariables = [
|
||||
"NODE_ENV",
|
||||
"LOCATION",
|
||||
"BOT_OWNER",
|
||||
"DISCORD_GUILD_ID",
|
||||
"SHINUWA_USER_ID",
|
||||
"INVITE_LINK",
|
||||
"WEB_SERVER_PORT",
|
||||
"WEB_API_KEY",
|
||||
"DISCORD_APPLICATION_ID",
|
||||
"DISCORD_TOKEN",
|
||||
"VOICE_CHANNEL_ID",
|
||||
"TEXT_CHANNEL_ID",
|
||||
"GAME_SERVERS_MESSAGE_ID",
|
||||
];
|
||||
|
||||
const missingVariables = requiredVariables.filter(
|
||||
(name) => !process.env[name]?.trim()
|
||||
);
|
||||
|
||||
if (missingVariables.length > 0) {
|
||||
throw new Error(
|
||||
`Variables d'environnement manquantes : ${missingVariables.join(", ")}`
|
||||
);
|
||||
}
|
||||
|
||||
const webServerPort = Number(process.env.WEB_SERVER_PORT);
|
||||
|
||||
if (!Number.isInteger(webServerPort) || webServerPort <= 0) {
|
||||
throw new Error("WEB_SERVER_PORT doit être un entier positif");
|
||||
}
|
||||
|
||||
const config = Object.freeze({
|
||||
environnement: process.env.NODE_ENV,
|
||||
location: process.env.LOCATION,
|
||||
botOwner: process.env.BOT_OWNER,
|
||||
discordGuildId: process.env.DISCORD_GUILD_ID,
|
||||
shinuwaUserId: process.env.SHINUWA_USER_ID,
|
||||
inviteLink: process.env.INVITE_LINK,
|
||||
webServerPort,
|
||||
webApiKey: process.env.WEB_API_KEY,
|
||||
applicationId: process.env.DISCORD_APPLICATION_ID,
|
||||
token: process.env.DISCORD_TOKEN,
|
||||
voiceChannelId: process.env.VOICE_CHANNEL_ID,
|
||||
textChannelId: process.env.TEXT_CHANNEL_ID,
|
||||
gameServersMessageId: process.env.GAME_SERVERS_MESSAGE_ID,
|
||||
});
|
||||
|
||||
export { config };
|
||||
38
src/events/interactionCreate.js
Normal file
38
src/events/interactionCreate.js
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { Events } from "discord.js";
|
||||
|
||||
const event = {
|
||||
name: Events.InteractionCreate,
|
||||
async execute(interaction) {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
|
||||
const command = interaction.client.commands.get(
|
||||
interaction.commandName
|
||||
).command;
|
||||
|
||||
if (!command) {
|
||||
console.error(
|
||||
`No command matching ${interaction.commandName} was found.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await command.execute(interaction);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
if (interaction.replied || interaction.deferred) {
|
||||
await interaction.followUp({
|
||||
content: "There was an error while executing this command!",
|
||||
ephemeral: true,
|
||||
});
|
||||
} else {
|
||||
await interaction.reply({
|
||||
content: "There was an error while executing this command!",
|
||||
ephemeral: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export { event };
|
||||
26
src/events/ready.js
Normal file
26
src/events/ready.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { Events } from "discord.js";
|
||||
import { config } from "../config.js";
|
||||
import { showGameServers } from "../features/showGameServers.js";
|
||||
import { sendMessage } from "../features/sendMessage.js";
|
||||
import { isConnectedToVoiceChannel } from "../features/utilities.js";
|
||||
|
||||
const event = {
|
||||
name: Events.ClientReady,
|
||||
once: true,
|
||||
execute(client) {
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] Logged in as ${client.user.tag}`
|
||||
);
|
||||
|
||||
showGameServers(
|
||||
client,
|
||||
config.textChannelId,
|
||||
config.gameServersMessageId,
|
||||
config.shinuwaUserId
|
||||
);
|
||||
|
||||
//sendMessage(client, 'jukebox')
|
||||
},
|
||||
};
|
||||
|
||||
export { event };
|
||||
59
src/features/sendMessage.js
Normal file
59
src/features/sendMessage.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import {
|
||||
ActionRowBuilder,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
channelMention,
|
||||
codeBlock,
|
||||
} from "discord.js";
|
||||
import { config } from "../config.js";
|
||||
|
||||
function sendMessage(client, type) {
|
||||
const channel = client.channels.cache.get(config.textChannelId);
|
||||
var message = { content: "Message réservé" };
|
||||
|
||||
if (type && type === "invitation") {
|
||||
message.content = inviteMessage();
|
||||
} else if (type && type === "jukebox") {
|
||||
message = jukeboxMessage();
|
||||
}
|
||||
|
||||
channel.send(message);
|
||||
}
|
||||
|
||||
function inviteMessage() {
|
||||
var message =
|
||||
"Pour inviter quelqu'un, il faut utiliser cette invitation temporaire !\n";
|
||||
|
||||
message = message + codeBlock(config.inviteLink);
|
||||
|
||||
message =
|
||||
message +
|
||||
"*Pour une invitation permanente, il suffit d'attribuer le role*" +
|
||||
" ***Hangaround*** " +
|
||||
"*à la personne concernée.*\n\n" +
|
||||
"";
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
function jukeboxMessage() {
|
||||
const description =
|
||||
"Yo ! 😺\n\n" +
|
||||
`J'ai installé un jukebox dans ${channelMention(config.voiceChannelId)} !\n` +
|
||||
"Tu peux le contrôler facilement via une petite interface ! 😽.\n\n" +
|
||||
"Clique sur le bouton ci-dessous pour ouvrir le tableau de bord.\n\n";
|
||||
|
||||
const buttonRow = new ActionRowBuilder().addComponents(
|
||||
new ButtonBuilder()
|
||||
.setLabel("Ouvrir le Jukebox 🎵")
|
||||
.setStyle(ButtonStyle.Link)
|
||||
.setURL("https://palico-bot.shinuwa.fr/jukebox/")
|
||||
);
|
||||
|
||||
return {
|
||||
content: description,
|
||||
components: [buttonRow],
|
||||
};
|
||||
}
|
||||
|
||||
export { sendMessage, inviteMessage, jukeboxMessage };
|
||||
64
src/features/showGameServers.js
Normal file
64
src/features/showGameServers.js
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import { config } from "../config.js";
|
||||
import { getJSONData } from "./utilities.js";
|
||||
|
||||
var currentStatus = [];
|
||||
|
||||
function checkServersStatus(client) {
|
||||
const data = getJSONData("src/static/gameservers-list.json");
|
||||
const newStatus = data.servers.map((server) => server.active);
|
||||
|
||||
if (JSON.stringify(newStatus) === JSON.stringify(currentStatus)) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateMessage(client, data);
|
||||
currentStatus = newStatus;
|
||||
return true;
|
||||
}
|
||||
|
||||
function updateMessage(client, data) {
|
||||
var newMessage = `Hello 😺 ! Voila les serveurs de jeux qu'on a chez nous :\n\n`;
|
||||
|
||||
data.servers.forEach((server) => {
|
||||
newMessage =
|
||||
newMessage +
|
||||
"```ansi\n" +
|
||||
`${server.game} : ` +
|
||||
`${server.active ? "[2;32mOnline[0m" : "[2;31mOffline[0m"}\n` +
|
||||
`${server.address}\n` +
|
||||
"```";
|
||||
});
|
||||
|
||||
newMessage =
|
||||
newMessage +
|
||||
"\nAh d'ailleurs ! Si le serveur est sécurisé, le mot de passe c'est surement **0117**.";
|
||||
newMessage =
|
||||
newMessage +
|
||||
`\nPour mettre en ligne un serveur, faut voir avec <@${config.shinuwaUserId}> , c'est lui qui gère ca !\n`;
|
||||
|
||||
const channel = client.channels.cache.get(config.textChannelId);
|
||||
|
||||
channel.messages
|
||||
.fetch(config.gameServersMessageId)
|
||||
.then((message) => {
|
||||
message
|
||||
.edit(newMessage)
|
||||
.then(
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] showGameServers: Game servers message updated`
|
||||
)
|
||||
)
|
||||
.catch(console.error);
|
||||
})
|
||||
.catch(console.error);
|
||||
}
|
||||
|
||||
function showGameServers(client) {
|
||||
const data = getJSONData("src/static/gameservers-list.json");
|
||||
currentStatus = data.servers.map((server) => server.active);
|
||||
|
||||
updateMessage(client, data);
|
||||
setInterval(checkServersStatus, 120000, client);
|
||||
}
|
||||
|
||||
export { showGameServers };
|
||||
74
src/features/utilities.js
Normal file
74
src/features/utilities.js
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import fs from "fs";
|
||||
import { config } from "../config.js";
|
||||
|
||||
function changeVoiceStatus(client, status, members) {
|
||||
const changeStatus = (type, value, members) => {
|
||||
switch (type) {
|
||||
case "mute":
|
||||
for (let member of members) {
|
||||
member[1].voice.setMute(value);
|
||||
}
|
||||
break;
|
||||
case "deaf":
|
||||
for (let member of members) {
|
||||
member[1].voice.setDeaf(value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
var voiceChannel = client.channels.cache.get(config.voiceChannelId);
|
||||
var connectedMembers = voiceChannel.members;
|
||||
|
||||
if (members == "all") {
|
||||
members = connectedMembers;
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
case "mute":
|
||||
changeStatus("mute", true, members);
|
||||
break;
|
||||
case "unmute":
|
||||
changeStatus("mute", false, members);
|
||||
break;
|
||||
case "deaf":
|
||||
changeStatus("deaf", true, members);
|
||||
break;
|
||||
case "undeaf":
|
||||
changeStatus("deaf", false, members);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function getJSONData(file) {
|
||||
const jsonFile = fs.readFileSync(file);
|
||||
const data = JSON.parse(jsonFile);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function getRandomInt(max) {
|
||||
return Math.floor(Math.random() * max);
|
||||
}
|
||||
|
||||
function isConnectedToVoiceChannel(client, userId) {
|
||||
var voiceChannel = client.channels.cache.get(config.voiceChannelId);
|
||||
var connectedMembers = voiceChannel.members;
|
||||
|
||||
var selectedMember = connectedMembers.filter(
|
||||
(member) => member.user.id === userId
|
||||
);
|
||||
|
||||
if (selectedMember.size === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export {
|
||||
changeVoiceStatus,
|
||||
getJSONData,
|
||||
getRandomInt,
|
||||
isConnectedToVoiceChannel,
|
||||
};
|
||||
370
src/music/queue.js
Normal file
370
src/music/queue.js
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
import fs from "fs";
|
||||
import { EventEmitter } from "events";
|
||||
import {
|
||||
AudioPlayerStatus,
|
||||
NoSubscriberBehavior,
|
||||
VoiceConnectionStatus,
|
||||
createAudioPlayer,
|
||||
createAudioResource,
|
||||
entersState,
|
||||
joinVoiceChannel,
|
||||
} from "@discordjs/voice";
|
||||
import { Events } from "discord.js";
|
||||
import { config } from "../config.js";
|
||||
import {
|
||||
deleteTrackFile,
|
||||
handleTrackCompletion,
|
||||
} from "../web/storage/storageManager.js";
|
||||
|
||||
const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000;
|
||||
|
||||
class MusicQueue extends EventEmitter {
|
||||
constructor(client) {
|
||||
super();
|
||||
this.client = client;
|
||||
this.queue = [];
|
||||
this.currentTrack = null;
|
||||
this.connection = null;
|
||||
this.playbackStatus = AudioPlayerStatus.Idle;
|
||||
this.idleDisconnectTimeout = null;
|
||||
this.aloneDisconnectTimeout = null;
|
||||
this.suspendedForAlone = false;
|
||||
this.audioPlayer = createAudioPlayer({
|
||||
behaviors: {
|
||||
noSubscriber: NoSubscriberBehavior.Play,
|
||||
},
|
||||
});
|
||||
this.voiceStateListener = (oldState, newState) => {
|
||||
if (
|
||||
oldState.channelId === config.voiceChannelId ||
|
||||
newState.channelId === config.voiceChannelId
|
||||
) {
|
||||
this.evaluateAloneStatus();
|
||||
}
|
||||
};
|
||||
this.client.on(Events.VoiceStateUpdate, this.voiceStateListener);
|
||||
|
||||
this.audioPlayer.on(AudioPlayerStatus.Idle, () => {
|
||||
if (this.currentTrack) {
|
||||
handleTrackCompletion(this.currentTrack);
|
||||
}
|
||||
this.currentTrack = null;
|
||||
this.playNext();
|
||||
});
|
||||
|
||||
this.audioPlayer.on("error", (error) => {
|
||||
console.error("Audio player encountered an error", error);
|
||||
this.currentTrack = null;
|
||||
this.playNext();
|
||||
});
|
||||
|
||||
this.audioPlayer.on("stateChange", (oldState, newState) => {
|
||||
this.playbackStatus = newState.status;
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
});
|
||||
}
|
||||
|
||||
snapshot() {
|
||||
return {
|
||||
current: this.currentTrack,
|
||||
upcoming: this.queue,
|
||||
status: this.playbackStatus,
|
||||
};
|
||||
}
|
||||
|
||||
async ensureConnection() {
|
||||
if (
|
||||
this.connection &&
|
||||
this.connection.joinConfig.channelId === config.voiceChannelId
|
||||
) {
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
let channel = this.client.channels.cache.get(config.voiceChannelId);
|
||||
|
||||
if (!channel) {
|
||||
try {
|
||||
channel = await this.client.channels.fetch(config.voiceChannelId);
|
||||
} catch (error) {
|
||||
console.error("Unable to fetch voice channel", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (!channel) {
|
||||
throw new Error("Voice channel configured for music playback was not found");
|
||||
}
|
||||
|
||||
const connection = joinVoiceChannel({
|
||||
channelId: channel.id,
|
||||
guildId: channel.guild.id,
|
||||
adapterCreator: channel.guild.voiceAdapterCreator,
|
||||
selfDeaf: false,
|
||||
});
|
||||
|
||||
this.connection = connection;
|
||||
connection.subscribe(this.audioPlayer);
|
||||
await entersState(connection, VoiceConnectionStatus.Ready, 30_000);
|
||||
this.evaluateAloneStatus();
|
||||
return connection;
|
||||
}
|
||||
|
||||
enqueue(track) {
|
||||
this.queue.push(track);
|
||||
this.cancelIdleDisconnect();
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
if (!this.currentTrack) {
|
||||
return this.playNext();
|
||||
}
|
||||
|
||||
return track;
|
||||
}
|
||||
|
||||
async playNext() {
|
||||
if (this.suspendedForAlone) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.queue.length === 0) {
|
||||
this.scheduleIdleDisconnect();
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
return;
|
||||
}
|
||||
this.cancelIdleDisconnect();
|
||||
|
||||
const nextTrack = this.queue.shift();
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
|
||||
try {
|
||||
await this.ensureConnection();
|
||||
} catch (error) {
|
||||
console.error("Unable to connect to the configured voice channel", error);
|
||||
deleteTrackFile(nextTrack);
|
||||
this.currentTrack = null;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const stream = fs.createReadStream(nextTrack.path);
|
||||
const resource = createAudioResource(stream, {
|
||||
inlineVolume: true,
|
||||
});
|
||||
|
||||
this.currentTrack = nextTrack;
|
||||
this.audioPlayer.play(resource);
|
||||
this.emit("trackStart", nextTrack);
|
||||
} catch (error) {
|
||||
console.error("Unable to play track", error);
|
||||
deleteTrackFile(nextTrack);
|
||||
this.currentTrack = null;
|
||||
return this.playNext();
|
||||
}
|
||||
}
|
||||
|
||||
async remove(trackId) {
|
||||
const index = this.queue.findIndex((track) => track.id === trackId);
|
||||
if (index === -1) {
|
||||
if (this.currentTrack && this.currentTrack.id === trackId) {
|
||||
this.skip();
|
||||
return this.currentTrack;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const [removed] = this.queue.splice(index, 1);
|
||||
deleteTrackFile(removed);
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
if (this.queue.length === 0 && !this.currentTrack) {
|
||||
this.scheduleIdleDisconnect();
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
move(trackId, newPosition) {
|
||||
const index = this.queue.findIndex((track) => track.id === trackId);
|
||||
if (index === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [track] = this.queue.splice(index, 1);
|
||||
const boundedPosition = Math.max(0, Math.min(newPosition, this.queue.length));
|
||||
this.queue.splice(boundedPosition, 0, track);
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
return this.snapshot();
|
||||
}
|
||||
|
||||
skip() {
|
||||
this.audioPlayer.stop(true);
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.queue.forEach((track) => deleteTrackFile(track));
|
||||
this.queue = [];
|
||||
this.audioPlayer.stop(true);
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
}
|
||||
|
||||
pause() {
|
||||
this.audioPlayer.pause(true);
|
||||
}
|
||||
|
||||
resume() {
|
||||
this.audioPlayer.unpause();
|
||||
}
|
||||
|
||||
start() {
|
||||
this.suspendedForAlone = false;
|
||||
this.cancelIdleDisconnect();
|
||||
if (!this.currentTrack) {
|
||||
return this.playNext();
|
||||
}
|
||||
return this.currentTrack;
|
||||
}
|
||||
|
||||
removeByLibraryId(libraryTrackId) {
|
||||
if (!libraryTrackId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const removed = this.queue.filter(
|
||||
(track) => track.libraryTrackId === libraryTrackId
|
||||
);
|
||||
|
||||
this.queue = this.queue.filter(
|
||||
(track) => track.libraryTrackId !== libraryTrackId
|
||||
);
|
||||
|
||||
removed.forEach((track) => deleteTrackFile(track));
|
||||
|
||||
if (
|
||||
this.currentTrack &&
|
||||
this.currentTrack.libraryTrackId === libraryTrackId
|
||||
) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
if (removed.length > 0) {
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
destroyConnection(reason, { suspend = false } = {}) {
|
||||
if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (suspend) {
|
||||
this.suspendedForAlone = true;
|
||||
}
|
||||
|
||||
this.cancelIdleDisconnect();
|
||||
this.cancelAloneDisconnect();
|
||||
|
||||
if (this.connection) {
|
||||
try {
|
||||
this.connection.destroy();
|
||||
} catch (error) {
|
||||
console.error("Failed to destroy voice connection", error);
|
||||
}
|
||||
this.connection = null;
|
||||
}
|
||||
|
||||
try {
|
||||
this.audioPlayer.stop(true);
|
||||
} catch (error) {
|
||||
console.error("Failed to stop audio player", error);
|
||||
}
|
||||
|
||||
this.currentTrack = null;
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
|
||||
);
|
||||
}
|
||||
|
||||
scheduleIdleDisconnect() {
|
||||
if (
|
||||
this.idleDisconnectTimeout ||
|
||||
this.queue.length > 0 ||
|
||||
this.currentTrack ||
|
||||
!this.connection
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.idleDisconnectTimeout = setTimeout(() => {
|
||||
this.idleDisconnectTimeout = null;
|
||||
if (!this.currentTrack && this.queue.length === 0 && this.connection) {
|
||||
this.destroyConnection("idle timeout");
|
||||
}
|
||||
}, AUTO_DISCONNECT_DELAY);
|
||||
}
|
||||
|
||||
cancelIdleDisconnect() {
|
||||
if (this.idleDisconnectTimeout) {
|
||||
clearTimeout(this.idleDisconnectTimeout);
|
||||
this.idleDisconnectTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
scheduleAloneDisconnect() {
|
||||
if (this.aloneDisconnectTimeout || !this.connection) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.aloneDisconnectTimeout = setTimeout(() => {
|
||||
this.aloneDisconnectTimeout = null;
|
||||
if (this.connection && this.isBotAlone()) {
|
||||
this.destroyConnection("alone timeout", { suspend: true });
|
||||
}
|
||||
}, AUTO_DISCONNECT_DELAY);
|
||||
}
|
||||
|
||||
cancelAloneDisconnect() {
|
||||
if (this.aloneDisconnectTimeout) {
|
||||
clearTimeout(this.aloneDisconnectTimeout);
|
||||
this.aloneDisconnectTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
evaluateAloneStatus() {
|
||||
if (!this.connection) {
|
||||
this.cancelAloneDisconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isBotAlone()) {
|
||||
this.scheduleAloneDisconnect();
|
||||
} else {
|
||||
const wasSuspended = this.suspendedForAlone;
|
||||
this.suspendedForAlone = false;
|
||||
this.cancelAloneDisconnect();
|
||||
if (wasSuspended && !this.currentTrack && this.queue.length > 0) {
|
||||
this.playNext();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
isBotAlone() {
|
||||
const channel = this.client.channels.cache.get(config.voiceChannelId);
|
||||
if (!channel) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const clientId = this.client.user?.id;
|
||||
if (!clientId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!channel.members.has(clientId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const others = channel.members.filter((member) => member.id !== clientId);
|
||||
return others.size === 0;
|
||||
}
|
||||
}
|
||||
|
||||
export { MusicQueue };
|
||||
18
src/web/middlewares/auth.js
Normal file
18
src/web/middlewares/auth.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { config } from "../../config.js";
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
if (!config.webApiKey) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const header = req.headers.authorization || "";
|
||||
const token = header.replace("Bearer ", "");
|
||||
|
||||
if (token === config.webApiKey) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(401).json({ error: "Unauthorized" });
|
||||
}
|
||||
|
||||
export { authMiddleware };
|
||||
44
src/web/routes/library.js
Normal file
44
src/web/routes/library.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { Router } from "express";
|
||||
import {
|
||||
createQueueTrackFromLibrary,
|
||||
deletePermanentTrack,
|
||||
findPermanentTrack,
|
||||
getPermanentLibrary,
|
||||
} from "../storage/storageManager.js";
|
||||
|
||||
function libraryRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
||||
router.get("/", (req, res) => {
|
||||
res.json({ tracks: getPermanentLibrary() });
|
||||
});
|
||||
|
||||
router.delete("/:libraryId", (req, res) => {
|
||||
const track = deletePermanentTrack(req.params.libraryId);
|
||||
|
||||
if (!track) {
|
||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
||||
}
|
||||
|
||||
queue.removeByLibraryId(track.id);
|
||||
res.json({ removed: track });
|
||||
});
|
||||
|
||||
router.post("/:libraryId/enqueue", (req, res) => {
|
||||
const baseTrack = findPermanentTrack(req.params.libraryId);
|
||||
if (!baseTrack) {
|
||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
||||
}
|
||||
|
||||
const queueTrack = createQueueTrackFromLibrary(
|
||||
baseTrack,
|
||||
req.body?.requestedBy
|
||||
);
|
||||
queue.enqueue(queueTrack);
|
||||
res.status(201).json({ track: queueTrack });
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export { libraryRouter };
|
||||
34
src/web/routes/player.js
Normal file
34
src/web/routes/player.js
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { Router } from "express";
|
||||
|
||||
function playerRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
||||
router.post("/play", async (req, res) => {
|
||||
await queue.start();
|
||||
res.json(queue.snapshot());
|
||||
});
|
||||
|
||||
router.post("/pause", (req, res) => {
|
||||
queue.pause();
|
||||
res.json(queue.snapshot());
|
||||
});
|
||||
|
||||
router.post("/resume", (req, res) => {
|
||||
queue.resume();
|
||||
res.json(queue.snapshot());
|
||||
});
|
||||
|
||||
router.post("/skip", (req, res) => {
|
||||
queue.skip();
|
||||
res.json(queue.snapshot());
|
||||
});
|
||||
|
||||
router.post("/stop", (req, res) => {
|
||||
queue.stop();
|
||||
res.json(queue.snapshot());
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export { playerRouter };
|
||||
56
src/web/routes/queue.js
Normal file
56
src/web/routes/queue.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { Router } from "express";
|
||||
import { createQueueTrackFromLibrary, findPermanentTrack } from "../storage/storageManager.js";
|
||||
|
||||
function queueRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
||||
router.get("/", (req, res) => {
|
||||
res.json(queue.snapshot());
|
||||
});
|
||||
|
||||
router.post("/", (req, res) => {
|
||||
const { libraryTrackId, requestedBy } = req.body;
|
||||
|
||||
if (!libraryTrackId) {
|
||||
return res.status(400).json({ error: "libraryTrackId manquant" });
|
||||
}
|
||||
|
||||
const libraryTrack = findPermanentTrack(libraryTrackId);
|
||||
|
||||
if (!libraryTrack) {
|
||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
||||
}
|
||||
|
||||
const track = createQueueTrackFromLibrary(libraryTrack, requestedBy);
|
||||
queue.enqueue(track);
|
||||
res.status(201).json({ track });
|
||||
});
|
||||
|
||||
router.delete("/:trackId", async (req, res) => {
|
||||
const removed = await queue.remove(req.params.trackId);
|
||||
if (!removed) {
|
||||
return res.status(404).json({ error: "Piste introuvable" });
|
||||
}
|
||||
|
||||
res.json({ removed });
|
||||
});
|
||||
|
||||
router.patch("/:trackId/move", (req, res) => {
|
||||
const position = Number(req.body?.position);
|
||||
if (Number.isNaN(position)) {
|
||||
return res.status(400).json({ error: "position doit être un nombre" });
|
||||
}
|
||||
|
||||
const snapshot = queue.move(req.params.trackId, position);
|
||||
|
||||
if (!snapshot) {
|
||||
return res.status(404).json({ error: "Piste introuvable" });
|
||||
}
|
||||
|
||||
res.json(snapshot);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export { queueRouter };
|
||||
40
src/web/routes/uploads.js
Normal file
40
src/web/routes/uploads.js
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { Router } from "express";
|
||||
import multer from "multer";
|
||||
import { TEMP_DIR, registerUploadedFile } from "../storage/storageManager.js";
|
||||
|
||||
const upload = multer({
|
||||
dest: TEMP_DIR,
|
||||
limits: {
|
||||
fileSize: 150 * 1024 * 1024,
|
||||
},
|
||||
});
|
||||
|
||||
function uploadsRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
||||
router.post("/", upload.single("file"), async (req, res, next) => {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: "Aucun fichier reçu" });
|
||||
}
|
||||
|
||||
const permanent = req.body?.permanent === "true";
|
||||
const enqueue = req.body?.enqueue !== "false";
|
||||
const uploader = req.body?.uploader || "web-ui";
|
||||
|
||||
try {
|
||||
const track = registerUploadedFile(req.file, { permanent, uploader });
|
||||
|
||||
if (enqueue) {
|
||||
queue.enqueue(track);
|
||||
}
|
||||
|
||||
return res.status(201).json({ track, enqueued: enqueue });
|
||||
} catch (error) {
|
||||
return next(error);
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export { uploadsRouter };
|
||||
43
src/web/server.js
Normal file
43
src/web/server.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import express from "express";
|
||||
import path from "path";
|
||||
import { config } from "../config.js";
|
||||
import { authMiddleware } from "./middlewares/auth.js";
|
||||
import { libraryRouter } from "./routes/library.js";
|
||||
import { playerRouter } from "./routes/player.js";
|
||||
import { queueRouter } from "./routes/queue.js";
|
||||
import { uploadsRouter } from "./routes/uploads.js";
|
||||
import { ensureStorageLayout } from "./storage/storageManager.js";
|
||||
|
||||
const PUBLIC_DIR = path.join(process.cwd(), "public");
|
||||
|
||||
function startWebServer(dependencies) {
|
||||
ensureStorageLayout();
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
const apiRouter = express.Router();
|
||||
apiRouter.use(authMiddleware);
|
||||
apiRouter.use("/uploads", uploadsRouter(dependencies));
|
||||
apiRouter.use("/queue", queueRouter(dependencies));
|
||||
apiRouter.use("/library", libraryRouter(dependencies));
|
||||
apiRouter.use("/player", playerRouter(dependencies));
|
||||
|
||||
app.use("/api", apiRouter);
|
||||
app.get(["/jukebox", "/jukebox/"], (_req, res) =>
|
||||
res.sendFile(path.join(PUBLIC_DIR, "jukebox.html"))
|
||||
);
|
||||
app.use(express.static(PUBLIC_DIR));
|
||||
|
||||
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] Web control server listening on port ${port}`
|
||||
);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
export { startWebServer };
|
||||
166
src/web/storage/storageManager.js
Normal file
166
src/web/storage/storageManager.js
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { v4 as uuid } from "uuid";
|
||||
|
||||
const STORAGE_ROOT = path.join(process.cwd(), "storage");
|
||||
const PERMANENT_DIR = path.join(STORAGE_ROOT, "permanent");
|
||||
const TEMP_DIR = path.join(STORAGE_ROOT, "temp");
|
||||
const LIBRARY_FILE = path.join(STORAGE_ROOT, "library.json");
|
||||
|
||||
function ensureStorageLayout() {
|
||||
if (!fs.existsSync(STORAGE_ROOT)) {
|
||||
fs.mkdirSync(STORAGE_ROOT, { recursive: true });
|
||||
}
|
||||
|
||||
if (!fs.existsSync(PERMANENT_DIR)) {
|
||||
fs.mkdirSync(PERMANENT_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
if (!fs.existsSync(TEMP_DIR)) {
|
||||
fs.mkdirSync(TEMP_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
if (!fs.existsSync(LIBRARY_FILE)) {
|
||||
fs.writeFileSync(LIBRARY_FILE, JSON.stringify([]));
|
||||
}
|
||||
}
|
||||
|
||||
function readLibrary() {
|
||||
try {
|
||||
const raw = fs.readFileSync(LIBRARY_FILE, { encoding: "utf8" });
|
||||
return JSON.parse(raw);
|
||||
} catch (error) {
|
||||
console.error("Failed to read library file", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeLibrary(entries) {
|
||||
fs.writeFileSync(LIBRARY_FILE, JSON.stringify(entries, null, 2));
|
||||
}
|
||||
|
||||
function registerUploadedFile(file, { permanent, uploader = "unknown" }) {
|
||||
ensureStorageLayout();
|
||||
const createdAt = new Date().toISOString();
|
||||
let finalPath = file.path;
|
||||
let storedName = path.basename(file.path);
|
||||
let permanentEntry = null;
|
||||
|
||||
if (permanent) {
|
||||
const extension = path.extname(file.originalname) || "";
|
||||
storedName = `${uuid()}${extension}`;
|
||||
finalPath = path.join(PERMANENT_DIR, storedName);
|
||||
fs.renameSync(file.path, finalPath);
|
||||
permanentEntry = {
|
||||
id: uuid(),
|
||||
originalName: file.originalname,
|
||||
storedName,
|
||||
path: finalPath,
|
||||
size: file.size,
|
||||
mimetype: file.mimetype,
|
||||
uploader,
|
||||
createdAt,
|
||||
};
|
||||
const library = readLibrary();
|
||||
library.push(permanentEntry);
|
||||
writeLibrary(library);
|
||||
}
|
||||
|
||||
return {
|
||||
id: uuid(),
|
||||
title: file.originalname,
|
||||
originalName: file.originalname,
|
||||
path: finalPath,
|
||||
storedName,
|
||||
size: file.size,
|
||||
mimetype: file.mimetype,
|
||||
permanent,
|
||||
uploader,
|
||||
libraryTrackId: permanentEntry ? permanentEntry.id : null,
|
||||
createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
function getPermanentLibrary() {
|
||||
ensureStorageLayout();
|
||||
return readLibrary();
|
||||
}
|
||||
|
||||
function findPermanentTrack(id) {
|
||||
return getPermanentLibrary().find((entry) => entry.id === id);
|
||||
}
|
||||
|
||||
function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
|
||||
if (!libraryTrack) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: uuid(),
|
||||
title: libraryTrack.originalName,
|
||||
originalName: libraryTrack.originalName,
|
||||
path: libraryTrack.path,
|
||||
storedName: libraryTrack.storedName,
|
||||
size: libraryTrack.size,
|
||||
mimetype: libraryTrack.mimetype,
|
||||
permanent: true,
|
||||
uploader: requestedBy,
|
||||
libraryTrackId: libraryTrack.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
function deleteFileSafe(filePath) {
|
||||
if (!filePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
fs.existsSync(filePath) && fs.unlinkSync(filePath);
|
||||
} catch (error) {
|
||||
console.error(`Failed to delete file ${filePath}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
function deletePermanentTrack(id) {
|
||||
const library = getPermanentLibrary();
|
||||
const index = library.findIndex((entry) => entry.id === id);
|
||||
if (index === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [removed] = library.splice(index, 1);
|
||||
writeLibrary(library);
|
||||
deleteFileSafe(removed.path);
|
||||
return removed;
|
||||
}
|
||||
|
||||
function handleTrackCompletion(track) {
|
||||
if (!track || track.permanent) {
|
||||
return;
|
||||
}
|
||||
deleteFileSafe(track.path);
|
||||
}
|
||||
|
||||
function deleteTrackFile(track) {
|
||||
if (!track) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!track.permanent) {
|
||||
deleteFileSafe(track.path);
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
PERMANENT_DIR,
|
||||
TEMP_DIR,
|
||||
ensureStorageLayout,
|
||||
registerUploadedFile,
|
||||
getPermanentLibrary,
|
||||
findPermanentTrack,
|
||||
createQueueTrackFromLibrary,
|
||||
deletePermanentTrack,
|
||||
handleTrackCompletion,
|
||||
deleteTrackFile,
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue