Skip to content

armgit / my-yt

Public Imported from GitHub
0

A clean and minimal youtube frontend, without all the ads and whistles

JavaScript

refactor: extract api handler

Christian Fei31f77c85ba5b
diff --git a/lib/router/api.js b/lib/router/api.js
new file mode 100644
index 0000000..ad9a297
--- /dev/null
+++ b/lib/router/api.js
@@ -0,0 +1,334 @@
+import fs from 'fs'
+import { URL } from 'url'
+import querystring from 'querystring'
+import { summarizeVideo } from '../subtitles-summary.js'
+import { broadcastSSE } from '../sse.js'
+import { downloadVideo, extractIdFromUrl, isUnsupportedUrl, isYouTubeUrl } from '../youtube.js'
+import { updateAndPersistVideosForChannel } from '../update-videos.js'
+
+const llmSettings = {
+ model: process.env.AI_MODEL || 'meta-llama-3.1-8b-instruct',
+ host: process.env.AI_HOST ||'http://127.0.0.1:1234',
+ endpoint: process.env.AI_ENDPOINT ||'/v1/chat/completions',
+ apiKey: process.env.AI_APIKEY || ''
+}
+
+export default function apiHandler(req, res, repo, connections = []) {
+ const url = new URL(req.url, `http://${req.headers.host}`)
+
+ if (url.pathname === '/api/channels' && req.method === 'GET')
+ return getChannelHandler(req, res, repo, connections)
+ if (url.pathname === '/api/channels' && req.method === 'POST')
+ return addChannelHandler(req, res, repo, connections)
+ if (url.pathname === '/api/channels' && req.method === 'DELETE')
+ return deleteChannelHandler(req, res, repo, connections)
+ if (url.pathname === '/api/download-video' && req.method === 'POST')
+ return downloadVideoHandler(req, res, repo, connections)
+ if (url.pathname === '/api/summarize-video' && req.method === 'POST')
+ return summarizeVideoHandler(req, res, repo, connections, llmSettings)
+ if (url.pathname === '/api/ignore-video' && req.method === 'POST')
+ return ignoreVideoHandler(req, res, repo, connections)
+ if (url.pathname === '/api/delete-video' && req.method === 'POST')
+ return deleteVideoHandler(req, res, repo, connections)
+ if (url.pathname === '/api/videos' && req.method === 'GET')
+ return searchVideosHandler(req, res, repo, connections)
+ if (url.pathname === '/api/video-quality' && req.method === 'GET')
+ return getVideoQualityHandler(req, res, repo, connections)
+ if (url.pathname === '/api/video-quality' && req.method === 'POST')
+ return setVideoQualityHandler(req, res, repo, connections)
+ if (url.pathname === '/api/disk-usage' && req.method === 'GET')
+ return diskUsageHandler(req, res, repo, connections)
+ if (url.pathname === '/api/reclaim-disk-space' && req.method === 'POST')
+ return reclaimDiskSpaceHandler(req, res, repo, connections)
+ if (url.pathname.match(/\/api\/videos\/.*/) && req.method === 'GET')
+ return watchVideoHandler(req, res, repo)
+ if (url.pathname.match(/\/api\/captions\/.*/) && req.method === 'GET')
+ return captionsHandler(req, res, repo)
+
+ res.writeHead(404)
+ return res.end()
+}
+
+async function getChannelHandler(req, res, repo, connections = []) {
+ const channels = repo.getChannels()
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ return res.end(JSON.stringify(channels))
+}
+
+async function addChannelHandler(req, res, repo, connections = []) {
+ const body = await getBody(req)
+ let { name } = JSON.parse(body)
+ name = name.trim()
+ name = name.startsWith('@') ? name.substring(1) : name
+
+ if (repo.channelExists(name)) {
+ res.writeHead(409)
+ return res.end('Channel already added')
+ }
+
+ const videos = await updateAndPersistVideosForChannel(name, repo)
+ if (Array.isArray(videos)) {
+ repo.addChannel(name)
+ broadcastSSE(JSON.stringify({type: 'new-videos', name, videos}), connections)
+ res.writeHead(201)
+ return res.end('Channel added')
+ }
+
+ res.writeHead(404)
+ return res.end('Channel not found')
+}
+
+async function deleteChannelHandler(req, res, repo, connections = []) {
+ const body = await getBody(req)
+ let { name } = JSON.parse(body)
+ name = name.trim()
+
+ if (!repo.channelExists(name)) {
+ res.writeHead(409, { 'Content-Type': 'text/plain' })
+ return res.end('Channel does not exist')
+ }
+
+ repo.deleteChannel(name)
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ return res.end('Channel deleted')
+}
+
+async function downloadVideoHandler(req, res, repo, connections = []) {
+ const body = await getBody(req)
+ let { id, external } = JSON.parse(body)
+
+ if (isUnsupportedUrl(id)) {
+ console.log('unsupported url', id)
+ res.writeHead(400)
+ return res.end()
+ }
+ if (isYouTubeUrl(id)) id = extractIdFromUrl(id)
+
+ downloadVideo(id, repo, (line) =>
+ broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections))
+ .then(() => {
+ const video = repo.getVideo(id)
+ broadcastSSE(JSON.stringify({type: 'downloaded', videoId: id, downloaded: true, video}), connections)
+ if (external) broadcastSSE(JSON.stringify({type: 'new-videos', videos: [repo.getVideo(id)]}), connections)
+ })
+ .catch((error) =>
+ broadcastSSE(JSON.stringify({type: 'download-log-line', line: error.stderr}), connections))
+
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ res.end('Download started')
+}
+
+async function summarizeVideoHandler(req, res, repo, connections = [], llmSettings = {}) {
+ const body = await getBody(req)
+ const { id } = JSON.parse(body)
+
+ summarizeVideo(id, repo, llmSettings, (line) =>
+ broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections))
+ .then(({summary, transcript}) =>
+ broadcastSSE(JSON.stringify({type: 'summary', summary, transcript, videoId: id}), connections))
+ .catch((error) => {
+ broadcastSSE(JSON.stringify({type: 'download-log-line', line: error.message}), connections)
+ broadcastSSE(JSON.stringify({type: 'summary-error', videoId: id}), connections)
+ })
+
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ res.end('Download started')
+}
+
+async function ignoreVideoHandler(req, res, repo, connections = []) {
+ const body = await getBody(req)
+ let { id } = JSON.parse(body)
+ const ignored = repo.toggleIgnoreVideo(id)
+ broadcastSSE(JSON.stringify({type: 'ignored', videoId: id, ignored}), connections)
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ return res.end(JSON.stringify(ignored))
+}
+
+async function deleteVideoHandler(req, res, repo, connections = []) {
+ const body = await getBody(req)
+ let { id } = JSON.parse(body)
+ repo.deleteVideo(id)
+ broadcastSSE(JSON.stringify({type: 'downloaded', videoId: id, downloaded: false}), connections)
+ res.writeHead(200)
+ res.end()
+}
+
+export function searchVideosHandler(req, res, repo) {
+ const query = getQuery(req)
+ const videos = repo.getVideos(query)
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify(videos))
+}
+
+
+function getVideoQualityHandler(req, res, repo) {
+ const videoQuality = repo.getVideoQuality()
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify(videoQuality))
+}
+
+async function setVideoQualityHandler(req, res, repo) {
+ const body = await getBody(req)
+ const videoQuality = JSON.parse(body)
+
+ const newQuality = repo.setVideoQuality(videoQuality)
+ if (!newQuality) {
+ res.writeHead(400)
+ return res.end()
+ }
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify(newQuality))
+}
+
+function diskUsageHandler(req, res, repo) {
+ const onlyIgnored = getQuery(req).onlyIgnored === 'true'
+ const videos = repo.getAllVideos()
+
+ const filterFn = onlyIgnored ? video => video.downloaded && video.ignored : video => video.downloaded
+
+ const diskSpaceUsed = videos.filter(filterFn)
+ .reduce((total, video) => {
+ try {
+ const filenames = fs.readdirSync('./data/videos').filter(f => f.startsWith(video.id))
+ return total + filenames.reduce((acc, filename) => acc + fs.statSync(`./data/videos/${filename}`).size / Math.pow(10, 9), 0)
+ } catch (err) {
+ console.error(err)
+ return total
+ }
+ }, 0)
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ res.end(diskSpaceUsed.toFixed(3) + 'GB')
+}
+
+async function reclaimDiskSpaceHandler(req, res, repo) {
+ const body = await getBody(req)
+ const {onlyIgnored} = JSON.parse(body)
+ const videos = repo.getAllVideos()
+
+ const filterFn = onlyIgnored ? video => video.downloaded && video.ignored : video => video.downloaded
+
+ videos.filter(filterFn)
+ .forEach((video) => {
+ try {
+ const filenames = fs.readdirSync('./data/videos').filter(f => f.startsWith(video.id))
+ filenames.forEach(filename => {
+ fs.unlinkSync(`./data/videos/${filename}`)
+ })
+ repo.updateVideo(video.id, {downloaded: false})
+ } catch (err) {
+ console.error(err.message)
+ }
+ })
+ repo.saveVideos()
+ res.writeHead(200)
+ res.end()
+}
+
+function watchVideoHandler(req, res, repo) {
+ const id = req.url.replace('/api/videos/', '').replace(/\.(webm|mp4)$/, '')
+ const video = repo.getVideo(id)
+ const location = video.location || `./data/videos/${id}.mp4`
+ const contentType = video.format ? `video/${video.format}` : "video/mp4"
+ if (!fs.existsSync(location)) {
+ res.writeHead(404, { 'Content-Type': 'text/plain' })
+ res.end('Video not found')
+ return
+ }
+
+ // https://github.com/bootstrapping-microservices/video-streaming-example/blob/master/index.js
+ // https://blog.logrocket.com/streaming-video-in-safari/
+
+ const options = {};
+
+ let start;
+ let end;
+
+ const range = req.headers.range;
+ if (range) {
+ const bytesPrefix = "bytes=";
+ if (range.startsWith(bytesPrefix)) {
+ const bytesRange = range.substring(bytesPrefix.length);
+ const parts = bytesRange.split("-");
+ if (parts.length === 2) {
+ const rangeStart = parts[0] && parts[0].trim();
+ if (rangeStart && rangeStart.length > 0) {
+ options.start = start = parseInt(rangeStart);
+ }
+ const rangeEnd = parts[1] && parts[1].trim();
+ if (rangeEnd && rangeEnd.length > 0) {
+ options.end = end = parseInt(rangeEnd);
+ }
+ }
+ }
+ }
+
+ res.setHeader("content-type", contentType)
+
+ const stat = fs.statSync(location)
+
+ let contentLength = stat.size
+
+ if (req.method === "HEAD") {
+ res.statusCode = 200
+ res.setHeader("accept-ranges", "bytes")
+ res.setHeader("content-length", contentLength)
+ return res.end()
+ }
+ let retrievedLength = contentLength;
+ if (start !== undefined && end !== undefined) {
+ retrievedLength = end - start + 1;
+ } else if (start !== undefined) {
+ retrievedLength = contentLength - start;
+ }
+
+ res.statusCode = (start !== undefined || end !== undefined) ? 206 : 200
+
+ res.setHeader("content-length", retrievedLength)
+
+ if (range !== undefined) {
+ res.setHeader("accept-ranges", "bytes")
+ res.setHeader("content-range", `bytes ${start || 0}-${end || (contentLength-1)}/${contentLength}`)
+ }
+
+ const fileStream = fs.createReadStream(location, options)
+ fileStream.on("error", error => {
+ console.error(`Error reading file ${location}.`, error)
+ res.writeHead(500)
+ res.end()
+ })
+
+ fileStream.pipe(res)
+}
+
+function captionsHandler(req, res) {
+ const captionsPath = './data' + req.url.replace('api/captions', 'videos') + '.en.vtt'
+ if (!fs.existsSync(captionsPath)) {
+ res.writeHead(404)
+ res.end()
+ } else {
+ const fileStream = fs.createReadStream(captionsPath)
+ fileStream.pipe(res)
+ }
+}
+
+
+
+
+
+
+async function getBody (req) {
+ return new Promise((resolve, reject) => {
+ let body = ''
+ req.on('data', chunk => {
+ body += chunk.toString()
+ })
+ req.on('end', () => resolve(body))
+ req.on('error', reject)
+ })
+}
+
+function getQuery (req) {
+ return (req.url && req.url.indexOf('?') >= 0)
+ ? querystring.parse(req.url.substring(req.url.indexOf('?') + 1))
+ : {}
+}
\ No newline at end of file
diff --git a/lib/server.js b/lib/server.js
index 5e5c1de..0be2e5b 100644
--- a/lib/server.js
+++ b/lib/server.js
@@ -1,11 +1,9 @@
import http from 'http'
import { URL } from 'url'
import fs from 'fs'
-import querystring from 'querystring'
-import { summarizeVideo } from './subtitles-summary.js'
import { handleSSE, broadcastSSE } from './sse.js'
-import { downloadVideo, extractIdFromUrl, isUnsupportedUrl, isYouTubeUrl } from './youtube.js'
-import { updateAndPersistVideos, updateAndPersistVideosForChannel } from './update-videos.js'
+import { updateAndPersistVideos } from './update-videos.js'
+import apiHandler from './router/api.js'
export function createServer ({repo, state = {}, connections = [], updateVideos = true} = {}) {
if (updateVideos) {
@@ -25,48 +23,13 @@ export function createServer ({repo, state = {}, connections = [], updateVideos
}
}
- const llmSettings = {
- model: process.env.AI_MODEL || 'meta-llama-3.1-8b-instruct',
- host: process.env.AI_HOST ||'http://127.0.0.1:1234',
- endpoint: process.env.AI_ENDPOINT ||'/v1/chat/completions',
- apiKey: process.env.AI_APIKEY || ''
- }
-
return http.createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://${req.headers.host}`)
if (req.headers.accept && req.headers.accept.indexOf('text/event-stream') >= 0) return handleSSE(res, connections)
- /* api */
- if (url.pathname === '/api/channels' && req.method === 'GET')
- return getChannelHandler(req, res, repo, connections)
- if (url.pathname === '/api/channels' && req.method === 'POST')
- return addChannelHandler(req, res, repo, connections)
- if (url.pathname === '/api/channels' && req.method === 'DELETE')
- return deleteChannelHandler(req, res, repo, connections)
- if (url.pathname === '/api/download-video' && req.method === 'POST')
- return downloadVideoHandler(req, res, repo, connections)
- if (url.pathname === '/api/summarize-video' && req.method === 'POST')
- return summarizeVideoHandler(req, res, repo, connections, llmSettings)
- if (url.pathname === '/api/ignore-video' && req.method === 'POST')
- return ignoreVideoHandler(req, res, repo, connections)
- if (url.pathname === '/api/delete-video' && req.method === 'POST')
- return deleteVideoHandler(req, res, repo, connections)
- if (url.pathname === '/api/videos' && req.method === 'GET')
- return searchVideosHandler(req, res, repo, connections)
- if (url.pathname === '/api/video-quality' && req.method === 'GET')
- return getVideoQualityHandler(req, res, repo, connections)
- if (url.pathname === '/api/video-quality' && req.method === 'POST')
- return setVideoQualityHandler(req, res, repo, connections)
- if (url.pathname === '/api/disk-usage' && req.method === 'GET')
- return diskUsageHandler(req, res, repo, connections)
- if (url.pathname === '/api/reclaim-disk-space' && req.method === 'POST')
- return reclaimDiskSpaceHandler(req, res, repo, connections)
- if (url.pathname.match(/\/api\/videos\/.*/) && req.method === 'GET')
- return watchVideoHandler(req, res, repo)
- if (url.pathname.match(/\/api\/captions\/.*/) && req.method === 'GET')
- return captionsHandler(req, res, repo)
+ if (url.pathname.startsWith('/api/')) return apiHandler(req, res, repo, connections, state)
/* client */
if (url.pathname === '/main.css')
@@ -105,23 +68,6 @@ export function createServer ({repo, state = {}, connections = [], updateVideos
})
}
-async function getBody (req) {
- return new Promise((resolve, reject) => {
- let body = ''
- req.on('data', chunk => {
- body += chunk.toString()
- })
- req.on('end', () => resolve(body))
- req.on('error', reject)
- })
-}
-
-function getQuery (req) {
- return (req.url && req.url.indexOf('?') >= 0)
- ? querystring.parse(req.url.substring(req.url.indexOf('?') + 1))
- : {}
-}
-
function fileHandler (filePath, contentType) {
return (req, res) => {
res.writeHead(200, { 'Content-Type': contentType })
@@ -129,263 +75,5 @@ function fileHandler (filePath, contentType) {
}
}
-async function addChannelHandler(req, res, repo, connections = []) {
- const body = await getBody(req)
- let { name } = JSON.parse(body)
- name = name.trim()
- name = name.startsWith('@') ? name.substring(1) : name
-
- if (repo.channelExists(name)) {
- res.writeHead(409)
- return res.end('Channel already added')
- }
-
- const videos = await updateAndPersistVideosForChannel(name, repo)
- if (Array.isArray(videos)) {
- repo.addChannel(name)
- broadcastSSE(JSON.stringify({type: 'new-videos', name, videos}), connections)
- res.writeHead(201)
- return res.end('Channel added')
- }
-
- res.writeHead(404)
- return res.end('Channel not found')
-}
-
-async function deleteChannelHandler(req, res, repo, connections = []) {
- const body = await getBody(req)
- let { name } = JSON.parse(body)
- name = name.trim()
-
- if (!repo.channelExists(name)) {
- res.writeHead(409, { 'Content-Type': 'text/plain' })
- return res.end('Channel does not exist')
- }
-
- repo.deleteChannel(name)
- res.writeHead(200, { 'Content-Type': 'text/plain' })
- return res.end('Channel deleted')
-}
-
-async function getChannelHandler(req, res, repo, connections = []) {
- const channels = repo.getChannels()
- res.writeHead(200, { 'Content-Type': 'application/json' })
- return res.end(JSON.stringify(channels))
-}
-
-async function downloadVideoHandler(req, res, repo, connections = []) {
- const body = await getBody(req)
- let { id, external } = JSON.parse(body)
-
- if (isUnsupportedUrl(id)) {
- console.log('unsupported url', id)
- res.writeHead(400)
- return res.end()
- }
- if (isYouTubeUrl(id)) id = extractIdFromUrl(id)
-
- downloadVideo(id, repo, (line) =>
- broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections))
- .then(() => {
- const video = repo.getVideo(id)
- broadcastSSE(JSON.stringify({type: 'downloaded', videoId: id, downloaded: true, video}), connections)
- if (external) broadcastSSE(JSON.stringify({type: 'new-videos', videos: [repo.getVideo(id)]}), connections)
- })
- .catch((error) =>
- broadcastSSE(JSON.stringify({type: 'download-log-line', line: error.stderr}), connections))
-
- res.writeHead(200, { 'Content-Type': 'text/plain' })
- res.end('Download started')
-}
-
-async function summarizeVideoHandler(req, res, repo, connections = [], llmSettings = {}) {
- const body = await getBody(req)
- const { id } = JSON.parse(body)
-
- summarizeVideo(id, repo, llmSettings, (line) =>
- broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections))
- .then(({summary, transcript}) =>
- broadcastSSE(JSON.stringify({type: 'summary', summary, transcript, videoId: id}), connections))
- .catch((error) => {
- broadcastSSE(JSON.stringify({type: 'download-log-line', line: error.message}), connections)
- broadcastSSE(JSON.stringify({type: 'summary-error', videoId: id}), connections)
- })
-
- res.writeHead(200, { 'Content-Type': 'text/plain' })
- res.end('Download started')
-}
-
-async function ignoreVideoHandler(req, res, repo, connections = []) {
- const body = await getBody(req)
- let { id } = JSON.parse(body)
- const ignored = repo.toggleIgnoreVideo(id)
- broadcastSSE(JSON.stringify({type: 'ignored', videoId: id, ignored}), connections)
- res.writeHead(200, { 'Content-Type': 'application/json' })
- return res.end(JSON.stringify(ignored))
-}
-
-async function deleteVideoHandler(req, res, repo, connections = []) {
- const body = await getBody(req)
- let { id } = JSON.parse(body)
- repo.deleteVideo(id)
- broadcastSSE(JSON.stringify({type: 'downloaded', videoId: id, downloaded: false}), connections)
- res.writeHead(200)
- res.end()
-}
-
-function watchVideoHandler(req, res, repo) {
- const id = req.url.replace('/api/videos/', '').replace(/\.(webm|mp4)$/, '')
- const video = repo.getVideo(id)
- const location = video.location || `./data/videos/${id}.mp4`
- const contentType = video.format ? `video/${video.format}` : "video/mp4"
- if (!fs.existsSync(location)) {
- res.writeHead(404, { 'Content-Type': 'text/plain' })
- res.end('Video not found')
- return
- }
-
- // https://github.com/bootstrapping-microservices/video-streaming-example/blob/master/index.js
- // https://blog.logrocket.com/streaming-video-in-safari/
-
- const options = {};
-
- let start;
- let end;
-
- const range = req.headers.range;
- if (range) {
- const bytesPrefix = "bytes=";
- if (range.startsWith(bytesPrefix)) {
- const bytesRange = range.substring(bytesPrefix.length);
- const parts = bytesRange.split("-");
- if (parts.length === 2) {
- const rangeStart = parts[0] && parts[0].trim();
- if (rangeStart && rangeStart.length > 0) {
- options.start = start = parseInt(rangeStart);
- }
- const rangeEnd = parts[1] && parts[1].trim();
- if (rangeEnd && rangeEnd.length > 0) {
- options.end = end = parseInt(rangeEnd);
- }
- }
- }
- }
-
- res.setHeader("content-type", contentType)
-
- const stat = fs.statSync(location)
-
- let contentLength = stat.size
-
- if (req.method === "HEAD") {
- res.statusCode = 200
- res.setHeader("accept-ranges", "bytes")
- res.setHeader("content-length", contentLength)
- return res.end()
- }
- let retrievedLength = contentLength;
- if (start !== undefined && end !== undefined) {
- retrievedLength = end - start + 1;
- } else if (start !== undefined) {
- retrievedLength = contentLength - start;
- }
-
- res.statusCode = (start !== undefined || end !== undefined) ? 206 : 200
-
- res.setHeader("content-length", retrievedLength)
-
- if (range !== undefined) {
- res.setHeader("accept-ranges", "bytes")
- res.setHeader("content-range", `bytes ${start || 0}-${end || (contentLength-1)}/${contentLength}`)
- }
-
- const fileStream = fs.createReadStream(location, options)
- fileStream.on("error", error => {
- console.error(`Error reading file ${location}.`, error)
- res.writeHead(500)
- res.end()
- })
-
- fileStream.pipe(res)
-}
-
-export function searchVideosHandler(req, res, repo) {
- const query = getQuery(req)
- const videos = repo.getVideos(query)
- res.writeHead(200, { 'Content-Type': 'application/json' })
- res.end(JSON.stringify(videos))
-}
-
-function getVideoQualityHandler(req, res, repo) {
- const videoQuality = repo.getVideoQuality()
- res.writeHead(200, { 'Content-Type': 'application/json' })
- res.end(JSON.stringify(videoQuality))
-}
-
-async function setVideoQualityHandler(req, res, repo) {
- const body = await getBody(req)
- const videoQuality = JSON.parse(body)
-
- const newQuality = repo.setVideoQuality(videoQuality)
- if (!newQuality) {
- res.writeHead(400)
- return res.end()
- }
- res.writeHead(200, { 'Content-Type': 'application/json' })
- res.end(JSON.stringify(newQuality))
-}
-
-function diskUsageHandler(req, res, repo) {
- const onlyIgnored = getQuery(req).onlyIgnored === 'true'
- const videos = repo.getAllVideos()
-
- const filterFn = onlyIgnored ? video => video.downloaded && video.ignored : video => video.downloaded
-
- const diskSpaceUsed = videos.filter(filterFn)
- .reduce((total, video) => {
- try {
- const filenames = fs.readdirSync('./data/videos').filter(f => f.startsWith(video.id))
- return total + filenames.reduce((acc, filename) => acc + fs.statSync(`./data/videos/${filename}`).size / Math.pow(10, 9), 0)
- } catch (err) {
- console.error(err)
- return total
- }
- }, 0)
- res.writeHead(200, { 'Content-Type': 'text/plain' })
- res.end(diskSpaceUsed.toFixed(3) + 'GB')
-}
-
-async function reclaimDiskSpaceHandler(req, res, repo) {
- const body = await getBody(req)
- const {onlyIgnored} = JSON.parse(body)
- const videos = repo.getAllVideos()
- const filterFn = onlyIgnored ? video => video.downloaded && video.ignored : video => video.downloaded
- videos.filter(filterFn)
- .forEach((video) => {
- try {
- const filenames = fs.readdirSync('./data/videos').filter(f => f.startsWith(video.id))
- filenames.forEach(filename => {
- fs.unlinkSync(`./data/videos/${filename}`)
- })
- repo.updateVideo(video.id, {downloaded: false})
- } catch (err) {
- console.error(err.message)
- }
- })
- repo.saveVideos()
- res.writeHead(200)
- res.end()
-}
-
-function captionsHandler(req, res) {
- const captionsPath = './data' + req.url.replace('api/captions', 'videos') + '.en.vtt'
- if (!fs.existsSync(captionsPath)) {
- res.writeHead(404)
- res.end()
- } else {
- const fileStream = fs.createReadStream(captionsPath)
- fileStream.pipe(res)
- }
-}
diff --git a/test/search.test.js b/test/search.test.js
index cfc9a4f..46f69f5 100644
--- a/test/search.test.js
+++ b/test/search.test.js
@@ -1,7 +1,7 @@
import {test, describe} from 'node:test'
import fs from 'fs'
import assert from 'assert'
-import { searchVideosHandler } from '../lib/server.js'
+import { searchVideosHandler } from '../lib/router/api.js'
import Repository from '../lib/repository.js'
const req = {}