7fife-backend/controllers/song.controller.js

679 lines
21 KiB
JavaScript
Raw Permalink Normal View History

2024-03-07 13:01:44 +00:00
const Song = require('../models/song.model');
const Category = require('../models/categories.model');
const Subcategory = require('../models/subcategories.model');
const Album = require('../models/album.model');
const Artist = require('../models/artist.model')
2024-03-07 13:01:44 +00:00
const Language = require('../models/language.model')
// const createSong = async (req, res) => {
// try {
// const {
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// musicLink,
// trackerID,
// lyrics,
// languageId
// } = req.body;
// const { coverArtImage, musicFile } = req.files;
// const [category, subcategory, album, artist, language] = await Promise.all([
// Category.findById(categoryId),
// Subcategory.findById(subcategoryId),
// Album.findById(albumId),
// Artist.findById(artistId),
// Language.findById(languageId)
// ]);
// if (!category || !subcategory || !album || !artist || !language) {
// const missingEntities = [];
// if (!category) missingEntities.push('Category');
// if (!subcategory) missingEntities.push('Subcategory');
// if (!album) missingEntities.push('Album');
// if (!artist) missingEntities.push('Artist');
// if (!language) missingEntities.push('Language');
// const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
// return res.status(404).json({ error_code: 404, message: errorMessage });
// }
// const coverArtImagePath = coverArtImage[0].path;
// const musicFilePath = musicFile[0].path;
// const baseUrl = `${req.protocol}://${req.get('host')}`;
// const coverArtImageUrl = `${baseUrl}/${coverArtImagePath}`;
// const newSong = await Song.create({
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// musicLink,
// trackerID,
// lyrics,
// languageId,
// coverArtImage: {
// filename: coverArtImage[0].filename,
// fileAddress: coverArtImagePath,
// imageUrl: coverArtImageUrl
// },
// musicFile: {
// filename: musicFile[0].filename,
// fileAddress: musicFilePath
// }
// });
// return res.status(201).json({
// error_code: 200,
// message: 'Song created successfully',
// song: newSong
// });
// } catch (err) {
// console.error('Error inside createSong:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
// const createSong = async (req, res) => {
// try {
// const {
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// languageId,
// type,
// musicLink,
// trackerID,
// lyrics
// } = req.body;
// if (!type || !['1', '2'].includes(type)) {
// return res.status(400).json({ error_code: 400, message: 'Invalid or missing type parameter' });
// }
// let musicFilePath;
// let musicFileUrl; // Define a variable to store the URL of the music file
// if (type === '1') {
// if (!musicLink || !trackerID) {
// return res.status(400).json({ error_code: 400, message: 'Music link and tracker ID are required for type 1' });
// }
// } else if (type === '2') {
// if (!req.files || !req.files.musicFile) {
// return res.status(400).json({ error_code: 400, message: 'Music file is required' });
// }
// if (!Array.isArray(req.files.musicFile) || req.files.musicFile.length === 0) {
// return res.status(400).json({ error_code: 400, message: 'Invalid music file provided' });
// }
// musicFilePath = req.files.musicFile[0].path;
// musicFileUrl = `${req.protocol}://${req.get('host')}/${musicFilePath}`; // Construct the URL of the music file
// }
// const { coverArtImage } = req.files;
// const coverArtImagePath = coverArtImage[0].path;
// const coverArtImageUrl = `${req.protocol}://${req.get('host')}/${coverArtImagePath}`;
// const [category, subcategory, album, artist, language] = await Promise.all([
// Category.findById(categoryId),
// Subcategory.findById(subcategoryId),
// Album.findById(albumId),
// Artist.findById(artistId),
// Language.findById(languageId)
// ]);
// if (![category, subcategory, album, artist, language].every(entity => entity)) {
// const missingEntities = ['Category', 'Subcategory', 'Album', 'Artist', 'Language']
// .filter((entity, index) => ![category, subcategory, album, artist, language][index]);
// const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
// return res.status(404).json({ error_code: 404, message: errorMessage });
// }
// let newSong;
// if (type === '1') {
// newSong = await Song.create({
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// languageId,
// musicLink,
// trackerID,
// coverArtImage: {
// filename: coverArtImage[0].filename,
// fileAddress: coverArtImagePath,
// imageUrl: coverArtImageUrl
// },
// });
// } else if (type === '2') {
// newSong = await Song.create({
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// languageId,
// lyrics,
// coverArtImage: {
// filename: coverArtImage[0].filename,
// fileAddress: coverArtImagePath,
// imageUrl: coverArtImageUrl
// },
// musicFile: {
// filename: req.files.musicFile[0].filename,
// fileAddress: musicFilePath,
// url: musicFileUrl // Include the URL of the music file in the database
// }
// });
// }
// return res.status(201).json({
// error_code: 200,
// message: 'Song created successfully',
// song: newSong
// });
// } catch (err) {
// console.error('Error inside createSong:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
2024-03-07 13:01:44 +00:00
const createSong = async (req, res) => {
try {
console.log(req.body,"ehjyqgfe")
2024-03-07 13:01:44 +00:00
const {
categoryId,
subcategoryId,
albumId,
artistId,
2024-03-07 13:01:44 +00:00
title,
languageId,
type,
2024-03-07 13:01:44 +00:00
musicLink,
trackerID,
lyrics
2024-03-07 13:01:44 +00:00
} = req.body;
if (!type || !['1', '2'].includes(type)) {
return res.status(400).json({ error_code: 400, message: 'Invalid or missing type parameter' });
}
let musicFilePath;
let musicFileUrl;
if (type === '1') {
if (!musicLink || !trackerID) {
return res.status(400).json({ error_code: 400, message: 'Music link and tracker ID are required for type 1' });
}
} else if (type === '2') {
if (!req.files || !req.files.musicFile) {
return res.status(400).json({ error_code: 400, message: 'Music file is required' });
}
if (!Array.isArray(req.files.musicFile) || req.files.musicFile.length === 0) {
return res.status(400).json({ error_code: 400, message: 'Invalid music file provided' });
}
musicFilePath = req.files.musicFile[0].path;
musicFileUrl = `${req.protocol}://${req.get('host')}/${musicFilePath}`;
}
console.log("🚀 ~ createSong ~ musicFilePath:", musicFilePath)
const { coverArtImage } = req.files;
2024-03-07 13:01:44 +00:00
const coverArtImagePath = coverArtImage[0].path;
const coverArtImageUrl = `${req.protocol}://${req.get('host')}/${coverArtImagePath}`;
2024-03-07 13:01:44 +00:00
const [category, subcategory, album, language] = await Promise.all([
2024-03-07 13:01:44 +00:00
Category.findById(categoryId),
Subcategory.findById(subcategoryId),
Album.findById(albumId),
Language.findById(languageId)
]);
if (![category, subcategory, album, language].every(entity => entity)) {
const missingEntities = ['Category', 'Subcategory', 'Album', 'Language']
.filter((entity, index) => ![category, subcategory, album, language][index]);
2024-03-07 13:01:44 +00:00
const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
return res.status(402 ).json({ error_code: 402, message: errorMessage });
2024-03-07 13:01:44 +00:00
}
const artistIdsArray = artistId.split(',').map(id => id.trim());
console.log("🚀 ~ createSong ~ artistIdsArray:", artistIdsArray)
let newSong;
if (type === '1') {
newSong = await Song.create({
categoryId,
subcategoryId,
albumId,
artistId: artistIdsArray,
title,
languageId,
musicLink,
trackerID,
coverArtImage: {
filename: coverArtImage[0].filename,
fileAddress: coverArtImagePath,
imageUrl: coverArtImageUrl
},
});
} else if (type === '2') {
newSong = await Song.create({
categoryId,
subcategoryId,
albumId,
artistId: artistIdsArray,
title,
languageId,
lyrics,
coverArtImage: {
filename: coverArtImage[0].filename,
fileAddress: coverArtImagePath,
imageUrl: coverArtImageUrl
},
musicFile: {
filename: req.files.musicFile[0].filename,
fileAddress: musicFilePath,
url: musicFileUrl // Include the URL of the music file in the database
}
});
}
console.log("🚀 ~ createSong ~ newSong:", newSong)
2024-03-07 13:01:44 +00:00
return res.status(200).json({
2024-03-07 13:01:44 +00:00
error_code: 200,
message: 'Song created successfully',
song: newSong
});
} catch (err) {
console.error('Error inside createSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
2024-03-07 13:01:44 +00:00
};
// const updateSong = async (req, res) => {
// try {
// const { id } = req.params;
// const updatedSong = await Song.findByIdAndUpdate(id, req.body, { new: true });
// if (!updatedSong) {
// return res.status(404).json({ error_code: 404, message: 'Song not found' });
// }
// return res.status(200).json({ error_code: 200, message: 'Song updated successfully', song: updatedSong });
// } catch (err) {
// console.error('Error inside updateSong:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
2024-03-07 13:01:44 +00:00
const updateSong = async (req, res) => {
try {
console.log(req.params,"dshgudgf")
const {_id} = req.params;
// console.log("🚀 ~ updateSong ~ songId:", songId)
const song = await Song.findById(_id);
console.log("🚀 ~ updateSong ~ song:", song)
if (!song) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
const {
categoryId,
subcategoryId,
albumId,
artistId,
title,
languageId,
type,
musicLink,
trackerID,
lyrics
} = req.body;
const updates = {};
// Input validation
if (categoryId) updates.categoryId = categoryId;
if (subcategoryId) updates.subcategoryId = subcategoryId;
if (albumId) updates.albumId = albumId;
if (artistId) {
updates.artistId = artistId.split(',').map(id => id.trim());
}
if (title) updates.title = title;
if (languageId) updates.languageId = languageId;
if (type) {
if (!['1', '2'].includes(type)) {
return res.status(400).json({ error_code: 400, message: 'Invalid type parameter' });
}
updates.type = type;
if (type === '1') {
if (!musicLink || !trackerID) {
return res.status(400).json({ error_code: 400, message: 'Music link and tracker ID are required for type 1' });
}
updates.musicLink = musicLink;
updates.trackerID = trackerID;
} else if (type === '2') {
// if (!req.files || !req.files.musicFile) {
// return res.status(400).json({ error_code: 400, message: 'Music file is required' });
// }
if (req.files && req.files.musicFile) {
const musicFilePath = req.files.musicFile[0].path;
const musicFileUrl = `${req.protocol}://${req.get('host')}/uploads/${musicFilePath}`;
updates.musicFile = {
filename: req.files.musicFile[0].filename,
fileAddress: musicFilePath,
url: musicFileUrl
};
}
}
}
if (lyrics !== undefined) updates.lyrics = lyrics;
// Update cover art image if provided
if (req.files && req.files.coverArtImage) {
const coverArtImage = req.files.coverArtImage[0];
const coverArtImagePath = coverArtImage.path;
const coverArtImageUrl = `${req.protocol}://${req.get('host')}/uploads/${coverArtImagePath}`;
updates.coverArtImage = {
filename: coverArtImage.filename,
fileAddress: coverArtImagePath,
imageUrl: coverArtImageUrl
};
}
// Perform the update and return the updated song
const updatedSong = await Song.findByIdAndUpdate(_id, updates, { new: true });
2024-03-07 13:01:44 +00:00
if (!updatedSong) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({
error_code: 200,
message: 'Song updated successfully',
song: updatedSong
});
2024-03-07 13:01:44 +00:00
} catch (err) {
console.error('Error inside updateSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
2024-03-07 13:01:44 +00:00
const deleteSong = async (req, res) => {
try {
const { id } = req.params;
2024-03-07 13:01:44 +00:00
const deletedSong = await Song.findByIdAndDelete(id);
if (!deletedSong) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({ error_code: 200, message: 'Song deleted successfully' });
} catch (err) {
console.error('Error inside deleteSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
// const getSong = async (req, res) => {
// try {
// const { id } = req.params;
// const song = await Song.findById(id)
// .populate('languageId', 'name')
// .populate('artistId', 'ArtistName')
// .select('title musicLink trackerID lyrics coverArtImage');
// if (!song) {
// return res.status(404).json({ error_code: 404, message: 'Song not found' });
// }
// const { languageId, artistId, musicLink, trackerID, lyrics } = song;
// const languageName = languageId ? languageId.name : null;
// const artistName = artistId ? artistId.ArtistName : null;
// const imageUrl = song.coverArtImage ? song.coverArtImage.imageUrl : null;
// const songData = {
// languageName: languageName,
// artistName: artistName,
// musicLink: musicLink || null,
// trackerID: trackerID || null,
// lyrics: lyrics || null,
// imageUrl: imageUrl
// };
// return res.status(200).json({
// error_code: 200,
// message: 'Song retrieved successfully',
// song: songData
// });
// } catch (err) {
// console.error('Error inside getSong:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
2024-03-07 13:01:44 +00:00
const getSong = async (req, res) => {
try {
const { id } = req.params;
2024-03-07 13:01:44 +00:00
const song = await Song.findById(id)
.populate('languageId', 'name')
.populate('artistId', 'ArtistName')
.select('title musicLink trackerID lyrics coverArtImage musicFile');
2024-03-07 13:01:44 +00:00
if (!song) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
const { languageId, artistId, musicLink, trackerID, lyrics, coverArtImage, musicFile } = song;
const languageName = languageId ? languageId.name : 'Language not available';
const artistNames = artistId.map(artist => artist.ArtistName);
const imageUrl = coverArtImage ? coverArtImage.imageUrl : 'Image not available';
const url = musicFile ? musicFile.url : 'Music file not available';
const songData = {
languageName: languageName,
artistNames: artistNames,
musicLink: musicLink || 'Music link not available',
trackerID: trackerID || 'Tracker ID not available',
lyrics: lyrics || 'Lyrics not available',
imageUrl: imageUrl,
url: url
};
return res.status(200).json({
error_code: 200,
message: 'Song retrieved successfully',
song: songData
});
2024-03-07 13:01:44 +00:00
} catch (err) {
console.error('Error inside getSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
2024-03-07 13:01:44 +00:00
const changeSongStatus = async (req, res) => {
try {
const { id } = req.params;
const songData = await Song.findById(id);
if (!songData) {
return res.status(400).send({
error_code: 400,
message: 'song not found'
});
}
songData.status = songData.status === 'activate' ? 'deactivate' : 'activate';
await songData.save();
res.status(200).send({
message: `song status toggled successfully to ${songData.status}`,
songData: songData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
2024-03-07 13:01:44 +00:00
const getAllSongs = async (req, res) => {
try {
const { title, artist, category, page, limit } = req.query;
2024-03-07 13:01:44 +00:00
// Build match stage for filtering based on search fields
const matchStage = {};
['title', 'artist', 'category'].forEach(field => {
2024-03-07 13:01:44 +00:00
if (req.query[field]) {
matchStage[field] = { $regex: req.query[field], $options: 'i' };
2024-03-07 13:01:44 +00:00
}
});
const pageNumber = Math.max(1, parseInt(page) || 1);
const pageSize = Math.max(1, parseInt(limit) || 5);
const pipeline = [
{ $match: matchStage },
{
$lookup: {
from: 'categories',
localField: 'categoryId',
foreignField: '_id',
as: 'category'
}
},
{
$lookup: {
from: 'albums',
localField: 'albumId',
foreignField: '_id',
as: 'album'
}
},
{
$lookup: {
from: 'subcategories',
localField: 'subcategoryId',
foreignField: '_id',
as: 'subcategory'
}
},
{
$lookup: {
from: 'artists',
localField: 'artistId',
foreignField: '_id',
as: 'artist'
}
},
{
$project: {
title: 1,
category: { $arrayElemAt: ['$category.name', 0] },
subcategory: { $arrayElemAt: ['$subcategory.SubCategoriesName', 0] },
artist: { $arrayElemAt: ['$artist.ArtistName', 0] },
album: { $arrayElemAt: ['$album.albumName', 0] },
status: '$status'
}
},
{ $sort: { title: 1 } },
{ $skip: (pageNumber - 1) * pageSize },
{ $limit: pageSize }
];
const totalCount = await Song.countDocuments(matchStage);
const totalPages = Math.ceil(totalCount / pageSize);
2024-03-07 13:01:44 +00:00
const songs = await Song.aggregate(pipeline);
2024-03-07 13:01:44 +00:00
return res.status(200).json({
error_code: 200,
message: 'Songs retrieved successfully',
songs,
// page:pageNumber,
// limit:pageSize,
total_count:totalCount,
2024-03-07 13:01:44 +00:00
total_pages: totalPages,
current_page: pageNumber
});
} catch (err) {
console.error('Error inside getAllSongs:', err);
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
}
};
// const getAllSongs = async (req, res) => {
// try {
// const songs = await Song.find()
// .populate('languageId', 'name')
// .populate('artistId', 'ArtistName')
// .select('title musicLink trackerID lyrics coverArtImage');
// if (!songs || songs.length === 0) {
// return res.status(404).json({ error_code: 404, message: 'Songs not found' });
// }
// const songData = songs.map(song => {
// const { languageId, artistId, musicLink, trackerID, lyrics, coverArtImage } = song;
// const languageName = languageId ? languageId.name : null;
// const artistNames = artistId ? artistId.map(artist => artist.ArtistName) : null;
// const imageUrl = coverArtImage ? coverArtImage.imageUrl : null;
// return {
// languageName: languageName,
// artistNames: artistNames,
// musicLink: musicLink || null,
// trackerID: trackerID || null,
// lyrics: lyrics || null,
// imageUrl: imageUrl
// };
// });
// return res.status(200).json({
// error_code: 200,
// message: 'Songs retrieved successfully',
// songs: songData
// });
// } catch (err) {
// console.error('Error inside getAllSongs:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
2024-03-07 13:01:44 +00:00
module.exports = {
createSong,
updateSong,
deleteSong,
getSong,
getAllSongs,
changeSongStatus
};