backend/utils/auto.js

71 lines
2.4 KiB
JavaScript
Raw Normal View History

2023-03-06 16:30:44 +00:00
const fs = require('node:fs')
const upload = require('../utils/upload.js')
const ytdlp = require('../utils/ytdlp.js')
const redis = require('../utils/redis.js')
const metadata = require('../utils/metadata.js')
const websocket = require('../utils/websocket.js')
const logger = require("../utils/logger.js")
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
async function handleCheck() {
const channels = await prisma.autodownload.findMany()
2023-03-23 21:40:00 +00:00
for (c of channels) {
await handleDownload(c.channel)
2023-03-23 21:40:00 +00:00
}
}
async function handleDownload(channelId) {
logger.info({ message: `Checking ${channelId} for new videos...` })
2023-03-24 14:20:06 +00:00
const videos = await metadata.getChannelVideos(channelId)
2023-03-24 15:48:16 +00:00
if (!videos) return logger.info({ message: `Failed requesting Youtube for ${channelId}` })
for (video of videos) {
const id = video.url.match(/[?&]v=([^&]+)/)[1]
const already = await prisma.videos.findFirst({
where: {
id: id
}
})
if (already) continue
2023-03-10 19:29:19 +00:00
if (await redis.get(id)) {
logger.info({ message: `Someone is already downloading ${video.title}, ${id}` })
continue
}
await redis.set(id, 'downloading')
logger.info({ message: `Starting to download ${video.title}, ${id}` })
const download = await ytdlp.downloadVideo('https://www.youtube.com' + video.url)
if (download.fail) {
logger.info({ message: `Failed downloading ${video.title}, ${id} -> ${download.message}` })
await redis.del(id)
continue
} else {
const file = fs.readdirSync("./videos").find(f => f.includes(id))
if (file) {
fs.renameSync(`./videos/${file}`, `./videos/${id}.webm`)
logger.info({ message: `Downloaded ${video.title}, ${id}` })
const videoUrl = await upload.uploadVideo(`./videos/${id}.webm`)
logger.info({ message: `Uploaded ${video.title}, ${id}` })
fs.unlinkSync(`./videos/${id}.webm`)
await websocket.createDatabaseVideo(id, videoUrl)
2023-03-23 21:40:00 +00:00
await redis.del(id)
} else {
2023-03-23 21:40:00 +00:00
await redis.set(id, 'error')
logger.info({ message: `Couldn't find file for ${video.title}, ${id}` })
}
}
}
}
module.exports = { handleCheck }