Larger refactoring and added avoidlist

This commit is contained in:
Myx
2023-10-21 05:09:38 +02:00
parent ccf7a218fd
commit 8fd3eeae03
30 changed files with 753 additions and 213 deletions

View File

@@ -1,15 +1,17 @@
import { joinRandomChannel, nextPlayBackTime } from './../bot';
import { nextPlayBackTime } from './../bot';
import express from 'express';
import multer, { diskStorage } from 'multer';
import path from 'path';
import { LoggerColors } from '../bot';
import ytdl from 'ytdl-core';
import fs from 'fs';
import bodyParser from 'body-parser';
import ffmpeg from 'fluent-ffmpeg';
import https from 'https';
import ip from 'ip';
import { Handlers } from "./handlers/index"
import { loadAvoidList } from '../helpers/load-avoid-list';
import { LoggerColors } from '../helpers/logger-colors';
import { generateFileName } from '../helpers/generate-file-name';
const app = express();
const storage = diskStorage({
destination: 'sounds/',
@@ -48,58 +50,8 @@ app.post('/upload', upload.single('myFile'), async (req, res) => {
res.send('File uploaded successfully.');
});
/**
* Uploads a YouTube video as an mp3 file to the sounds folder.
* The video must be shorter than 10 seconds.
* @Body url - The YouTube video url.
*/
app.post('/upload-youtube', async (req, res) => {
const url = req.body.url;
if (ytdl.validateURL(url)) {
const info = await ytdl.getInfo(url);
// remove special characters from the title and white spaces
const title = info.videoDetails.title.replace(/[^a-zA-Z ]/g, "").replace(/\s+/g, '-').toLowerCase();
// Create a temporary directory to store the uploaded file so validation can be done
const tempDir = fs.mkdtempSync('temp');
const outputFilePath = path.resolve(tempDir, generateFileName(title));
const videoReadableStream = ytdl(url, { filter: 'audioonly' });
const fileWritableStream = fs.createWriteStream(outputFilePath);
videoReadableStream.pipe(fileWritableStream);
fileWritableStream.on('finish', () => {
ffmpeg.ffprobe(outputFilePath, function(err, metadata) {
if (err) {
fs.rmSync(tempDir, { recursive: true, force: true });
return res.status(500).send('Error occurred during processing.');
}
const duration = metadata.format.duration;
if (duration == undefined) {
fs.rmSync(tempDir, { recursive: true, force: true });
return res.status(400).send('Something went wrong.');
}
if (duration > 10) {
fs.rmSync(tempDir, { recursive: true, force: true });
return res.status(400).send('File is longer than 10 seconds.');
} else {
// Move the file from the temporary directory to its final destination
const finalFilePath = path.resolve(__dirname, '../sounds/', generateFileName(title));
fs.renameSync(outputFilePath, finalFilePath);
res.send('File uploaded successfully.');
}
// Remove the temporary directory and its contents once done
fs.rmSync(tempDir, { recursive: true, force: true });
});
});
} else {
res.status(400).send('Invalid url provided.');
}
await Handlers.UploadYouTubeFile(res, req);
});
/**
@@ -109,19 +61,8 @@ app.post('/upload-youtube', async (req, res) => {
*/
app.use('/sounds', express.static(path.join(__dirname, '../sounds')));
/**
* Returns a list of all sound files in the sounds directory.
* @returns string[] - An array of all sound files in the sounds directory.
*/
app.get('/sounds', (_req, res) => {
const fs = require('fs');
const directoryPath = path.join(__dirname, '../sounds');
fs.readdir(directoryPath, function (err: any, files: any[]) {
if (err) {
return console.log(LoggerColors.Red, 'Unable to scan directory: ' + err);
}
res.send(files);
});
app.get('/sounds', (_req, res: express.Response) => {
return Handlers.GetSoundFiles(res);
});
/**
@@ -132,26 +73,26 @@ app.get('/nextplaybacktime', (_req, res) => {
res.send(nextPlayBackTime);
});
/**
* Deletes a file from the sounds folder by filename
*/
app.delete('/sounds/:filename', (req, res) => {
const fs = require('fs');
const directoryPath = path.join(__dirname, '../sounds');
const filePath = directoryPath + '/' + req.params.filename;
fs.unlink(filePath, (err: any) => {
if (err) {
return console.log(LoggerColors.Red, 'Unable to delete file: ' + err);
}
res.send('File deleted successfully.');
});
app.delete('/sounds/:filename', (_req, res) => {
Handlers.DeleteSoundFile(res, _req);
});
app.use(express.static(path.join(__dirname, "web")));
app.get('/join', (_req, res) => {
joinRandomChannel();
res.send('Joining random channel.');
Handlers.JoinChannel(res);
});
app.post('/avoidlist', (req, res) => {
Handlers.AddUserToAvoidList(res, req);
});
app.delete('/avoidlist/:user', (req, res) => {
Handlers.DeleteUserFromAvoidList(res, req);
});
app.get('/avoidlist', (_req, res) => {
res.send(loadAvoidList());
});
/**
@@ -182,22 +123,4 @@ export function startServer() {
server.listen(port, () => {
console.log(`Server started at ${ssl}://${ip.address()}:${port}`);
});
}
/**
* Generates a random file name based on the provided name.
* @param name - The name to generate a file name for.
* @returns string - The generated file name.
*/
function generateFileName(name: string) {
const randomHex = [...Array(3)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
const formattedName = name
.replace(/\(.*?\)|\[.*?\]/g, '')
.split(' ')
.filter(word => /^[a-zA-Z0-9]/.test(word))
.join(' ')
.replace(/\s+/g, ' ');
return `${formattedName}-${randomHex}.mp3`;
}
}