Skip to content

Commit

Permalink
music step 1
Browse files Browse the repository at this point in the history
  • Loading branch information
Dobrunia committed Dec 10, 2023
1 parent 747527a commit 010d58b
Show file tree
Hide file tree
Showing 11 changed files with 152 additions and 0 deletions.
138 changes: 138 additions & 0 deletions controlers/music-controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
const readFileAsync = promisify(fs.readFile);

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

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

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

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

// Создание новой папки
if (audioFile) {
fs.mkdirSync(folderPath);
}

// Создание нового имени для сохраняемых файлов
const audioFileName = `${trackName}.mp3`;
const imageFileName = `${trackName}.png`;

// Перемещение аудиофайла в нужную папку
if (audioFile) {
fs.renameSync(audioFile.path, path.join(folderPath, audioFileName));
}

// Перемещение изображения, если оно было загружено
if (imageFile) {
fs.renameSync(imageFile.path, path.join(folderPath, imageFileName));
}

// Создание текстового файла
const txtData = `trackName: ${trackName}\ntrackAuthor: ${trackAuthor}`;
fs.writeFileSync(path.join(folderPath, 'info.txt'), txtData);

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

async getAllTracks(req, res, next) {
try {
const tracksDir = 'uploads'; // Папка, где хранятся все треки
const trackFolders = fs.readdirSync(tracksDir);

// Создание массива для хранения данных о треках
const tracks = [];

// Обход всех папок (треков)
for (const folder of trackFolders) {
const folderPath = path.join(tracksDir, folder);

// Проверка, является ли элемент папкой
if (fs.lstatSync(folderPath).isDirectory()) {
// Чтение информации из текстового файла
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();
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 });
}
}

// Добавление данных о треке, изображении и аудиофайлах в массив
tracks.push({ trackName, trackAuthor, trackImage, trackAudios });
}
}

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

export const musicController = new MusicController();
8 changes: 8 additions & 0 deletions router/router.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Router } from 'express';
import { userController } from '../controlers/user-controller.js';
import { chatController } from '../controlers/chat-controller.js';
import { musicController } from '../controlers/music-controller.js';
import { messageController, multer } from '../controlers/message-controller.js';
import { checkHeader } from '../middlewares/auth.js';

Expand Down Expand Up @@ -48,3 +49,10 @@ router.get('/getMessagesByChatId/:chatId', checkHeader, chatController.getMessag
router.get('/returnActiveChats', checkHeader, chatController.returnAllUserChats);
router.get('/findCompanionsData/:chatId', checkHeader, chatController.findCompanionsData);

//musicController
import Multer from 'multer';
const upload = Multer({ dest: 'uploads/' });

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

router.get('/getAllServerTracks', checkHeader, musicController.getAllTracks);
Binary file added uploads/4 x 4_Big Baby Tape_42/4 x 4.mp3
Binary file not shown.
Binary file added uploads/4 x 4_Big Baby Tape_42/4 x 4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions uploads/4 x 4_Big Baby Tape_42/info.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
trackName: 4 x 4
trackAuthor: Big Baby Tape
Binary file added uploads/9mm_loli_42/9mm.mp3
Binary file not shown.
Binary file added uploads/9mm_loli_42/9mm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions uploads/9mm_loli_42/info.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
trackName: 9mm
trackAuthor: loli
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 not shown.
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 010d58b

Please sign in to comment.