backend/controller/search.js

52 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-02-15 15:13:12 +00:00
const crypto = require('node:crypto')
2023-03-03 16:44:40 +00:00
const validate = require('../utils/validate.js')
2024-02-15 15:13:12 +00:00
const redis = require('../utils/redis.js')
const { RedisRateLimiter } = require('rolling-rate-limiter')
2024-01-18 18:54:35 +00:00
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
2023-03-03 16:44:40 +00:00
2024-02-15 15:13:12 +00:00
const limiter = new RedisRateLimiter({
client: redis,
namespace: 'search:',
interval: 5 * 60 * 1000,
maxInInterval: 5
})
2023-03-03 16:44:40 +00:00
exports.searchVideo = async (req, res) => {
2024-02-15 15:13:12 +00:00
const ipHash = crypto.createHash('sha256').update(req.headers['x-userip'] || '0.0.0.0').digest('hex')
const isLimited = await limiter.limit(ipHash)
if (isLimited) return res.status(429).send('error-You have been ratelimited.')
2024-01-18 18:54:35 +00:00
const id = await validate.validateVideoInput(req.query.search)
2023-03-03 16:44:40 +00:00
if (id.fail) {
2024-01-18 18:54:35 +00:00
const videos = await prisma.videos.findMany({
where: {
title: {
contains: req.query.search,
mode: 'insensitive'
}
}
})
res.json(videos)
2023-03-03 16:44:40 +00:00
} else {
2024-01-18 18:54:35 +00:00
res.send(`redirect-${process.env.FRONTEND}/watch?v=${id}`)
2023-03-03 16:44:40 +00:00
}
}
exports.searchPlaylist = async (req, res) => {
const id = await validate.validatePlaylistInput(req.query.url)
if (id.fail) {
res.status(500).send(id.message)
} else {
2024-02-15 15:13:12 +00:00
res.redirect(`${process.env.FRONTEND}/playlist?list=${id}`)
2023-03-03 16:44:40 +00:00
}
}
exports.searchChannel = async (req, res) => {
const id = await validate.validateChannelInput(req.query.url)
if (id.fail) {
res.status(500).send(id.message)
} else {
2024-02-15 15:13:12 +00:00
res.redirect(`${process.env.FRONTEND}/channel/${id}`)
2023-03-03 16:44:40 +00:00
}
}