Skip to content

Commit

Permalink
getTrackByString
Browse files Browse the repository at this point in the history
  • Loading branch information
Dobrunia committed Dec 10, 2023
1 parent 010d58b commit 9e5f835
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 17 deletions.
112 changes: 96 additions & 16 deletions controlers/music-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,31 @@ import { promisify } from 'util';
const readFileAsync = promisify(fs.readFile);

class MusicController {
async saveAudio(req, res, next) {
async saveAudio(request, response, next) {
try {
// Получение данных из формы
const trackName = req.body.trackName ? req.body.trackName : 'Не указано';
const trackAuthor = req.body.trackAuthor
? req.body.trackAuthor
const trackName = request.body.trackName ? request.body.trackName : 'Не указано';
const trackAuthor = request.body.trackAuthor
? request.body.trackAuthor
: 'Не указан';

// Получение загруженных файлов
const audioFile = req.files['audioFile']
? req.files['audioFile'][0]
const audioFile = request.files['audioFile']
? request.files['audioFile'][0]
: null;
if (!audioFile) {
return res.status(400).json({ error: 'Вы не загрузили аудио' });
return response.status(400).json({ error: 'Вы не загрузили аудио' });
}

const imageFile = req.files['imageFile']
? req.files['imageFile'][0]
const imageFile = request.files['imageFile']
? request.files['imageFile'][0]
: null;

// Проверка наличия папки с требуемым именем
const folderName = `${trackName}_${trackAuthor}_${req.user.id}`;
const folderName = `${trackName}_${trackAuthor}_${request.user.id}`;
const folderPath = path.join('uploads', folderName);
if (fs.existsSync(folderPath)) {
return res.status(400).json({ error: 'Папка уже существует' });
return response.status(400).json({ error: 'Папка уже существует' });
}

// Создание новой папки
Expand All @@ -55,15 +55,15 @@ class MusicController {
fs.writeFileSync(path.join(folderPath, 'info.txt'), txtData);

// Возврат ответа с информацией о сохранении
res.status(200).json({ message: 'Файлы успешно сохранены' });
response.status(200).json({ message: 'Файлы успешно сохранены' });
} catch (error) {
// Обработка ошибок
console.error(error);
res.status(500).json({ error: 'Что-то пошло не так' });
response.status(500).json({ error: 'Что-то пошло не так' });
}
}

async getAllTracks(req, res, next) {
async getAllTracks(request, response, next) {
try {
const tracksDir = 'uploads'; // Папка, где хранятся все треки
const trackFolders = fs.readdirSync(tracksDir);
Expand Down Expand Up @@ -127,10 +127,90 @@ class MusicController {
}

// Отправка массива треков в качестве ответа
res.status(200).json(tracks);
response.status(200).json(tracks);
} catch (error) {
// Обработка ошибок
res.status(500).json({ error: 'Что-то пошло не так' });
response.status(500).json({ error: 'Что-то пошло не так' });
}
}

async getTrackByString(request, response, next) {
try {
const searchString = request.params.string.toLowerCase(); // Get the string parameter from the request and convert it to lowercase for case insensitivity

const tracksDir = 'uploads'; // Folder where the tracks are stored
const trackFolders = fs.readdirSync(tracksDir);
const tracks = [];

// Search for the track matching the string in each track folder
for (const folder of trackFolders) {
const folderPath = path.join(tracksDir, folder);

if (fs.lstatSync(folderPath).isDirectory()) {
// Read track information from the info.txt file
const txtFilePath = path.join(folderPath, 'info.txt');
const txtData = fs.readFileSync(txtFilePath, 'utf8');

const lines = txtData.split('\n');
const trackName = lines[0].split(':')[1].trim().toLowerCase(); // Get the track name and convert it to lowercase
const trackAuthor = lines[1].split(':')[1].trim();

// Поиск изображения в папке трека
const imageFiles = fs
.readdirSync(folderPath)
.filter(
(file) =>
file.endsWith('.png') ||
file.endsWith('.jpg') ||
file.endsWith('.jpeg'),
);

// Проверка наличия изображения в папке
let trackImage = null;
if (imageFiles.length > 0) {
const imageFilePath = path.join(folderPath, imageFiles[0]);
const imageData = await readFileAsync(imageFilePath);
trackImage = imageData.toString('base64');
}

// Поиск аудиофайлов mp3 в папке трека
const audioFiles = fs
.readdirSync(folderPath)
.filter((file) => file.endsWith('.mp3'));

// Проверка наличия аудиофайлов в папке
const trackAudios = [];
if (audioFiles.length > 0) {
for (const audioFile of audioFiles) {
const audioFilePath = path.join(folderPath, audioFile);
const audioData = await readFileAsync(audioFilePath);
const base64Audio = audioData.toString('base64');
const audioName = audioFile.replace('.mp3', '');
trackAudios.push({ audioName, base64Audio });
}
}

// Check if the track name contains the search string
if (trackName.includes(searchString) || trackAuthor.includes(searchString)) {
// Read track image and audio files
// ...

// Push the track information to the array of tracks
tracks.push({ trackName, trackAuthor, trackImage, trackAudios });
}
}
}

// If tracks are found, return the array of tracks
if (tracks.length > 0) {
response.status(200).json(tracks);
} else {
// If no track is found, return a response indicating that no track was found
response.status(404).json({ error: 'Track not found' });
}
} catch (error) {
// Handle errors
response.status(500).json({ error: 'Something went wrong' });
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,5 @@ const upload = Multer({ dest: 'uploads/' });

router.post('/saveMp3ToServer', checkHeader, upload.fields([{ name: 'audioFile' }, { name: 'imageFile' }]), musicController.saveAudio);

router.get('/getAllServerTracks', checkHeader, musicController.getAllTracks);
router.get('/getAllServerTracks', checkHeader, musicController.getAllTracks);
router.get('/getTrackByString/:string', checkHeader, musicController.getTrackByString);
2 changes: 2 additions & 0 deletions uploads/Слёзы_Кишлак_42/info.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
trackName: Слёзы
trackAuthor: Кишлак
Binary file added uploads/Слёзы_Кишлак_42/Слёзы.mp3
Binary file not shown.
Binary file added uploads/Слёзы_Кишлак_42/Слёзы.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 9e5f835

Please sign in to comment.