import {body, param} from "express-validator"; import {getClient} from "../utils/database.js"; import jwt from "jsonwebtoken"; export const Playlist = { id: param("id").notEmpty().isNumeric().trim(), name: body("name").notEmpty().trim(), owner: body("owner").notEmpty().isNumeric().trim(), videoId: param("videoId").notEmpty().isNumeric().trim(), } export async function doPlaylistExists(req, res, next) { const id = req.params.id; const logger = req.body.logger; const client = await getClient(); try { const query = `SELECT id FROM playlists WHERE id = $1`; const result = await client.query(query, [id]); if (result.rows.length === 0) { logger.write("No playlist with id " + id, 404); res.status(404).json({error: "Playlist not found"}); return; } next(); } catch (error) { logger.write("Error checking playlist existence: " + error.message, 500); res.status(500).json({error: error}); return; } finally { client.release(); } } export async function isOwner(req, res, next) { const id = req.params.id; const token = req.headers.authorization.split(' ')[1]; const userId = jwt.decode(token)["id"]; const logger = req.body.logger; const client = await getClient(); try { const query = `SELECT owner FROM playlists WHERE id = $1`; const result = await client.query(query, [id]); if(result.rows[0].owner !== userId) { logger.write("user not the owner of the playlist with id " + id, 403); res.status(403).json({error: "You do not have permission"}); return; } next(); } finally { client.release(); } } export async function isVideoInPlaylist(req, res, next) { const id = req.params.id; const videoId = req.params.videoId; const logger = req.body.logger; const client = await getClient(); try { const query = `SELECT id FROM playlist_elements WHERE video = $1 AND playlist = $2`; const result = await client.query(query, [videoId, id]); if(result.rows.length === 0) { logger.write("video " + videoId + "not found in playlist with id " + id, 404 ); res.status(404).json({error: "Video " + videoId + "not found"}); return; } next(); } catch (error) { logger.write("Error checking video in playlist: " + error.message, 500); res.status(500).json({error: error }); return; } finally { client.release(); } }