const path = require('path'); const fs = require('fs'); const express = require('express'); const { db, DATA_DIR, THUMB_DIR, getVideo, listVideos, listChannels, recentHistory, listFavorites, recordProgress, markViewed, toggleFavorite, getHistoryForVideo, createUser, findUserByUsername, verifyPassword, createSession, getUserFromSessionToken, destroySession, migrateLegacyData, listPlaylists, createPlaylist, deletePlaylist, getPlaylistVideos, addVideoToPlaylist, removeVideoFromPlaylist, reorderPlaylist, getStats, getChannelStats, getNextVideo, } = require('./db'); const { rescan } = require('./scanner'); const ROOT_DIR = path.join(__dirname, '..'); const VIDEO_ROOT = process.env.VIDEO_ROOT || path.join(ROOT_DIR, 'demo-videos'); const PORT = parseInt(process.env.PORT || '8080', 10); const MIME = { '.mp4': 'video/mp4', '.m4v': 'video/mp4', '.mkv': 'video/x-matroska', '.webm': 'video/webm', '.mov': 'video/quicktime', '.avi': 'video/x-msvideo', '.mpg': 'video/mpeg', '.mpeg': 'video/mpeg', '.ts': 'video/mp2t', '.wmv': 'video/x-ms-wmv', }; const app = express(); app.use(express.json()); function getCookie(req, name) { const header = req.headers.cookie || ''; for (const part of header.split(';')) { const idx = part.indexOf('='); if (idx === -1) continue; if (part.slice(0, idx).trim() === name) return decodeURIComponent(part.slice(idx + 1).trim()); } return null; } function setAuthCookie(res, token) { res.setHeader('Set-Cookie', `vidhive_sid=${token}; HttpOnly; Path=/; SameSite=Lax; Max-Age=${30 * 86400}`); } function clearAuthCookie(res) { res.setHeader('Set-Cookie', 'vidhive_sid=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0'); } function requireAuth(req, res, next) { const token = getCookie(req, 'vidhive_sid'); const user = getUserFromSessionToken(token); if (!user) return res.status(401).json({ error: 'unauthorized' }); req.user = user; req.sessionToken = token; next(); } function videoAbsPath(relPath) { return path.join(VIDEO_ROOT, relPath); } app.post('/api/auth/register', (req, res) => { const username = String((req.body || {}).username || '').trim(); const password = String((req.body || {}).password || ''); if (!/^[\w.-]{3,32}$/.test(username)) { return res.status(400).json({ error: 'Username must be 3–32 characters (letters, numbers, . _ -)' }); } if (password.length < 6) { return res.status(400).json({ error: 'Password must be at least 6 characters' }); } if (findUserByUsername(username)) { return res.status(409).json({ error: 'Username already taken' }); } const user = createUser(username, password); migrateLegacyData(user.id); const token = createSession(user.id); setAuthCookie(res, token); res.json({ user: { id: user.id, username: user.username } }); }); app.post('/api/auth/login', (req, res) => { const username = String((req.body || {}).username || '').trim(); const password = String((req.body || {}).password || ''); const user = findUserByUsername(username); if (!user || !verifyPassword(user, password)) { return res.status(401).json({ error: 'Invalid username or password' }); } const token = createSession(user.id); setAuthCookie(res, token); res.json({ user: { id: user.id, username: user.username } }); }); app.post('/api/auth/logout', (req, res) => { destroySession(getCookie(req, 'vidhive_sid')); clearAuthCookie(res); res.json({ ok: true }); }); app.get('/api/auth/me', (req, res) => { const token = getCookie(req, 'vidhive_sid'); const user = getUserFromSessionToken(token); if (!user) return res.status(401).json({ error: 'unauthorized' }); res.json({ user: { id: user.id, username: user.username } }); }); app.use('/api', requireAuth); app.get('/api/videos', (req, res) => { const limit = Math.min(parseInt(req.query.limit || '24', 10) || 24, 100); const offset = parseInt(req.query.offset || '0', 10) || 0; const q = String(req.query.q || '').trim(); const channel = String(req.query.channel || '').trim() || null; const sort = String(req.query.sort || 'newest'); const { videos, total } = listVideos({ q, channel, sort, limit, offset, userId: req.user.id }); res.json({ videos, total, limit, offset }); }); app.get('/api/favorites', (req, res) => { const limit = Math.min(parseInt(req.query.limit || '24', 10) || 24, 100); const offset = parseInt(req.query.offset || '0', 10) || 0; const { videos, total } = listFavorites(req.user.id, { limit, offset }); res.json({ videos, total, limit, offset }); }); app.get('/api/channels', (req, res) => { res.json(listChannels()); }); app.get('/api/video/:id', (req, res) => { const id = parseInt(req.params.id, 10); const v = getVideo(id); if (!v) return res.status(404).json({ error: 'not found' }); const history = getHistoryForVideo(req.user.id, id); const fav = db.prepare('SELECT 1 FROM favorites WHERE user_id = ? AND video_id = ?').get(req.user.id, id) ? 1 : 0; res.json({ video: v, history, favorite: fav }); }); app.get('/api/history', (req, res) => { const limit = Math.min(parseInt(req.query.limit || '20', 10) || 20, 100); res.json(recentHistory(req.user.id, limit)); }); app.post('/api/progress', (req, res) => { const id = parseInt(req.body.video_id, 10); const position = Number(req.body.position); const duration = Number(req.body.duration); if (!id || !isFinite(position) || !isFinite(duration) || duration <= 0) { return res.status(400).json({ error: 'invalid payload' }); } const v = getVideo(id); if (!v) return res.status(404).json({ error: 'not found' }); const row = recordProgress(req.user.id, id, position, duration); res.json(row); }); app.post('/api/view', (req, res) => { const id = parseInt(req.body.video_id, 10); if (!id || !getVideo(id)) return res.status(404).json({ error: 'not found' }); markViewed(id); res.json({ views: getVideo(id).views }); }); app.post('/api/favorite', (req, res) => { const id = parseInt(req.body.video_id, 10); if (!id || !getVideo(id)) return res.status(404).json({ error: 'not found' }); res.json(toggleFavorite(req.user.id, id)); }); app.get('/api/status', (req, res) => { res.json({ lastRescanAt: lastScan ? lastScan.at : null, stats: lastScan }); }); app.get('/api/stats', (req, res) => { res.json(getStats(req.user.id)); }); app.get('/api/channel/:name/stats', (req, res) => { const channel = decodeURIComponent(req.params.name); const stats = getChannelStats(req.user.id, channel); if (stats.videos === 0 && !listChannels().some(c => c.name === channel)) return res.status(404).json({ error: 'not found' }); res.json(stats); }); app.get('/api/videos/:id/next', (req, res) => { const id = parseInt(req.params.id, 10); if (!id || !getVideo(id)) return res.status(404).json({ error: 'not found' }); const mode = String(req.query.mode || 'channel'); const next = getNextVideo(req.user.id, id, mode === 'random' ? 'random' : 'channel'); res.json({ video: next }); }); app.get('/api/playlists', (req, res) => { res.json(listPlaylists(req.user.id)); }); app.post('/api/playlists', (req, res) => { const name = String((req.body || {}).name || '').trim(); if (!name || name.length > 80) return res.status(400).json({ error: 'Playlist name required (max 80 chars)' }); try { const pl = createPlaylist(req.user.id, name); res.json(pl); } catch (err) { if (String(err).includes('UNIQUE constraint failed')) return res.status(409).json({ error: 'A playlist with that name already exists' }); throw err; } }); app.delete('/api/playlists/:id', (req, res) => { const id = parseInt(req.params.id, 10); if (!deletePlaylist(req.user.id, id)) return res.status(404).json({ error: 'not found' }); res.json({ ok: true }); }); app.get('/api/playlists/:id', (req, res) => { const id = parseInt(req.params.id, 10); const data = getPlaylistVideos(req.user.id, id); if (!data) return res.status(404).json({ error: 'not found' }); res.json(data); }); app.post('/api/playlists/:id/items', (req, res) => { const id = parseInt(req.params.id, 10); const videoId = parseInt((req.body || {}).video_id, 10); if (!videoId || !getVideo(videoId)) return res.status(400).json({ error: 'invalid payload' }); const result = addVideoToPlaylist(req.user.id, id, videoId); if (result === null) return res.status(404).json({ error: 'not found' }); res.json(result); }); app.delete('/api/playlists/:id/items/:video_id', (req, res) => { const id = parseInt(req.params.id, 10); const videoId = parseInt(req.params.video_id, 10); const result = removeVideoFromPlaylist(req.user.id, id, videoId); if (result === null) return res.status(404).json({ error: 'not found' }); res.json(result); }); app.post('/api/playlists/:id/reorder', (req, res) => { const id = parseInt(req.params.id, 10); const ids = Array.isArray((req.body || {}).video_ids) ? req.body.video_ids.map(Number) : null; if (!ids || !ids.every(n => Number.isInteger(n) && n > 0)) return res.status(400).json({ error: 'invalid payload' }); const result = reorderPlaylist(req.user.id, id, ids); if (result === null) return res.status(404).json({ error: 'not found' }); res.json(result); }); app.post('/api/rescan', async (req, res) => { try { const stats = await runRescan(); res.json({ ok: true, ...stats }); } catch (err) { console.error('Rescan failed:', err); res.status(500).json({ ok: false, error: String(err) }); } }); app.get('/thumb/:id', requireAuth, (req, res) => { const id = parseInt(req.params.id, 10); const thumbPath = path.join(THUMB_DIR, `${id}.jpg`); if (!fs.existsSync(thumbPath)) return res.status(404).end(); res.setHeader('Cache-Control', 'private, max-age=31536000, immutable'); res.sendFile(thumbPath); }); app.get('/video/:id', requireAuth, (req, res) => { const id = parseInt(req.params.id, 10); const v = getVideo(id); if (!v) return res.status(404).json({ error: 'not found' }); const absPath = videoAbsPath(v.path); if (!fs.existsSync(absPath)) return res.status(404).json({ error: 'file missing on disk' }); const ext = path.extname(absPath).toLowerCase(); res.setHeader('Content-Type', MIME[ext] || 'application/octet-stream'); res.sendFile(absPath, { maxAge: 0 }, (err) => { if (err && !res.headersSent) res.status(500).end(); }); }); app.use(express.static(path.join(ROOT_DIR, 'public'))); app.use('/api', (err, req, res, next) => { console.error('API error:', err); res.status(500).json({ error: 'internal server error' }); }); app.get('*', (req, res) => { res.sendFile(path.join(ROOT_DIR, 'public', 'index.html')); }); let lastScan = null; let rescanPromise = null; async function runRescan() { const stats = await rescan(VIDEO_ROOT); lastScan = { at: new Date().toISOString(), ...stats }; return lastScan; } function initialScan() { if (!fs.existsSync(VIDEO_ROOT)) { console.log(`Video root not found: ${VIDEO_ROOT} — create it or set VIDEO_ROOT`); return Promise.resolve(null); } rescanPromise = runRescan().then(stats => { console.log('Initial scan complete:', stats); return stats; }).catch(err => { console.error('Initial scan failed:', err); return null; }); return rescanPromise; } const RESCAN_INTERVAL = parseInt(process.env.RESCAN_INTERVAL_MINUTES || '30', 10); app.listen(PORT, () => { console.log(`Seantube listening on http://localhost:${PORT}`); console.log(`Video root: ${VIDEO_ROOT}`); initialScan(); if (RESCAN_INTERVAL > 0) { setInterval(async () => { try { const stats = await runRescan(); console.log('Scheduled rescan complete:', stats); } catch (err) { console.error('Scheduled rescan failed:', err); } }, RESCAN_INTERVAL * 60 * 1000); console.log(`Scheduled rescans every ${RESCAN_INTERVAL} minute(s)`); } }); module.exports = app;