import Video from '../models/Video.js'; import Playlist from '../models/Playlist.js'; import Artist from '../models/Artist.js'; import ApiError from '../controllers/ErrorController.js'; import storage from '../config/storage.js'; import uploadVideo from "../utils/uploadVideo.js"; class VideoService { async create({name, videoHQ, videoLQ, playlist, artist}) { if(!videoHQ && !videoLQ) { throw ApiError.BadRequest('Видео не загружены'); } if(videoHQ?.mimetype.indexOf('video') === -1 || videoLQ?.mimetype.indexOf('video') === -1) { throw ApiError.BadRequest('К загрузке принимаются только видео.'); } const getArtist = await Artist.findById(artist); if(!getArtist) { throw ApiError.BadRequest('Такого исполнителя не существует'); } if(playlist) { const getPlaylist = await Playlist.findById(playlist); if(!getPlaylist) { throw ApiError.BadRequest('Такого плейлиста не существует'); } } const videoHQLink = await uploadVideo(videoHQ); const videoLQLink = await uploadVideo(videoLQ); const video = await Video.create({name, videoHQ: videoHQLink.Location, videoLQ: videoLQLink.Location, playlist, artist, date: new Date()}); return {video}; } async getAll({page, search}) { const limit = page ? 10 : 0; const videos = await Video.find({name: {$regex: search || '', $options: 'i'}}).populate([{ path: 'artist', select: 'name' }, { path: 'playlist', select: 'name' }]).skip(page * limit).limit(limit).sort({_id: -1}); const count = await Video.countDocuments({name: {$regex: search || '', $options: 'i'}}); return {videos, count: Math.ceil(count/limit)}; } async getOne() { const video = await Video.aggregate([ { $sample: { size: 1 } }, { $lookup: { from: 'artists', localField: 'artist', foreignField: '_id', as : "artist" }, }, { $lookup: { from: 'playlists', localField: 'playlist', foreignField: '_id', as : "playlist" }, }, ]); if(!video) { throw ApiError.BadRequest('Видео не существует'); } const oneVideo = video[0]; return {video: oneVideo}; } async edit({id, name, videoHQ, videoLQ, playlist, artist}) { if(artist) { const getArtist = await Artist.findById(artist); if(!getArtist) { throw ApiError.BadRequest('Такого исполнителя не существует'); } } if(playlist) { const getPlaylist = await Playlist.findById(playlist); if(!getPlaylist) { throw ApiError.BadRequest('Такого плейлиста не существует'); } } const video = await Video.findByIdAndUpdate(id, {name, playlist, artist}, {returnOriginal: false}); if(!video) { throw ApiError.BadRequest('Видео не существует'); } return {video}; } async delete({id}) { const video = await Video.findByIdAndDelete(id).select(['login']); if(!video) { throw ApiError.BadRequest('Видео не существует'); } return {video}; } } export default new VideoService();