initial commit for test

This commit is contained in:
seanland committed 2026-11-24 13:22:37 -05:00
commit 8d256d259d
56 files changed
+2355

No files matched your search

+495
View File
@@ -0,0 +1,495 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const Database = require('better-sqlite3');
const ROOT_DIR = path.join(__dirname, '..');
const DATA_DIR = path.join(ROOT_DIR, 'data');
const THUMB_DIR = path.join(DATA_DIR, 'thumbnails');
fs.mkdirSync(THUMB_DIR, { recursive: true });
const db = new Database(path.join(DATA_DIR, 'vidhive.db'));
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT UNIQUE NOT NULL COLLATE NOCASE,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
created_at REAL DEFAULT (unixepoch())
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at REAL DEFAULT (unixepoch()),
expires_at REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
CREATE TABLE IF NOT EXISTS videos (
id INTEGER PRIMARY KEY,
path TEXT UNIQUE NOT NULL,
filename TEXT NOT NULL,
title TEXT NOT NULL,
channel TEXT NOT NULL,
duration REAL DEFAULT 0,
size INTEGER DEFAULT 0,
mtime REAL DEFAULT 0,
added_at REAL DEFAULT (unixepoch()),
views INTEGER DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_videos_channel ON videos(channel);
CREATE INDEX IF NOT EXISTS idx_videos_added ON videos(added_at DESC);
CREATE INDEX IF NOT EXISTS idx_videos_views ON videos(views DESC);
CREATE TABLE IF NOT EXISTS history (
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
position REAL DEFAULT 0,
duration REAL DEFAULT 0,
completed INTEGER DEFAULT 0,
watched_at REAL NOT NULL DEFAULT (unixepoch()),
last_recorded REAL DEFAULT 0,
PRIMARY KEY (user_id, video_id)
);
CREATE INDEX IF NOT EXISTS idx_history_watched ON history(watched_at DESC);
CREATE TABLE IF NOT EXISTS favorites (
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
created_at REAL DEFAULT (unixepoch()),
PRIMARY KEY (user_id, video_id)
);
CREATE INDEX IF NOT EXISTS idx_favorites_user ON favorites(user_id, created_at DESC);
CREATE TABLE IF NOT EXISTS playlists (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
created_at REAL DEFAULT (unixepoch()),
UNIQUE (user_id, name)
);
CREATE INDEX IF NOT EXISTS idx_playlists_user ON playlists(user_id);
CREATE TABLE IF NOT EXISTS playlist_items (
playlist_id INTEGER NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
position INTEGER NOT NULL DEFAULT 0,
created_at REAL DEFAULT (unixepoch()),
PRIMARY KEY (playlist_id, video_id)
);
CREATE INDEX IF NOT EXISTS idx_playlist_items_playlist ON playlist_items(playlist_id, position);
CREATE TABLE IF NOT EXISTS watch_events (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
seconds REAL NOT NULL DEFAULT 0,
watched_at REAL NOT NULL DEFAULT (unixepoch())
);
CREATE INDEX IF NOT EXISTS idx_watch_events_user_time ON watch_events(user_id, watched_at DESC);
CREATE INDEX IF NOT EXISTS idx_watch_events_video ON watch_events(user_id, video_id);
CREATE VIRTUAL TABLE IF NOT EXISTS videos_fts USING fts5(title, channel);
`);
const histCols = db.prepare('PRAGMA table_info(history)').all();
if (histCols.length && !histCols.some(c => c.name === 'user_id')) {
db.exec('DROP INDEX IF EXISTS idx_history_watched');
db.exec('ALTER TABLE history RENAME TO history_legacy');
db.exec(`CREATE TABLE history (
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
position REAL DEFAULT 0, duration REAL DEFAULT 0, completed INTEGER DEFAULT 0,
watched_at REAL NOT NULL DEFAULT (unixepoch()),
last_recorded REAL DEFAULT 0,
PRIMARY KEY (user_id, video_id)
)`);
db.exec('CREATE INDEX IF NOT EXISTS idx_history_watched ON history(watched_at DESC)');
}
const histColsFinal = db.prepare('PRAGMA table_info(history)').all();
if (histColsFinal.length && !histColsFinal.some(c => c.name === 'last_recorded')) {
db.exec('ALTER TABLE history ADD COLUMN last_recorded REAL DEFAULT 0');
}
function migrateLegacyData(userId) {
const legacy = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='history_legacy'").get();
if (legacy) {
db.prepare(`INSERT OR IGNORE INTO history (user_id, video_id, position, duration, completed, watched_at)
SELECT ?, video_id, position, duration, completed, watched_at FROM history_legacy`).run(userId);
db.exec('DROP TABLE history_legacy');
}
const videoCols = db.prepare('PRAGMA table_info(videos)').all();
if (videoCols.some(c => c.name === 'favorite')) {
db.prepare(`INSERT OR IGNORE INTO favorites (user_id, video_id) SELECT ?, id FROM videos WHERE favorite = 1`).run(userId);
try { db.exec('ALTER TABLE videos DROP COLUMN favorite'); } catch {}
}
}
function upsertVideo({ path: relPath, filename, title, channel, duration, size, mtime }) {
const existing = db.prepare('SELECT id FROM videos WHERE path = ?').get(relPath);
let id;
if (existing) {
id = existing.id;
db.prepare(`UPDATE videos SET filename=?, title=?, channel=?, duration=?, size=?, mtime=? WHERE id=?`)
.run(filename, title, channel, duration, size, mtime, id);
db.prepare('DELETE FROM videos_fts WHERE rowid = ?').run(id);
} else {
const res = db.prepare(`INSERT INTO videos (path, filename, title, channel, duration, size, mtime) VALUES (?, ?, ?, ?, ?, ?, ?)`)
.run(relPath, filename, title, channel, duration, size, mtime);
id = res.lastInsertRowid;
}
db.prepare('INSERT INTO videos_fts (rowid, title, channel) VALUES (?, ?, ?)').run(id, title, channel);
return id;
}
function deleteVideosByPaths(relPaths) {
const del = db.prepare('DELETE FROM videos WHERE path = ?');
const delFts = db.prepare('DELETE FROM videos_fts WHERE rowid = (SELECT id FROM videos WHERE path = ?)');
for (const p of relPaths) {
delFts.run(p);
del.run(p);
}
}
function getVideo(id) {
return db.prepare('SELECT * FROM videos WHERE id = ?').get(id);
}
function favoriteSet(userId) {
const rows = db.prepare('SELECT video_id FROM favorites WHERE user_id = ?').all(userId);
return new Set(rows.map(r => r.video_id));
}
function attachFavorites(rows, favs) {
for (const r of rows) r.favorite = favs.has(r.id) ? 1 : 0;
return rows;
}
function listVideos({ q, channel, sort, limit, offset, userId }) {
const conditions = [];
const whereParams = [];
if (q) {
conditions.push(`v.id IN (SELECT rowid FROM videos_fts WHERE videos_fts MATCH ?)`);
const terms = q.split(/\s+/).filter(Boolean).map(t => `"${t.replace(/"/g, '""')}"`);
whereParams.push(terms.join(' '));
}
if (channel) {
conditions.push('v.channel = ?');
whereParams.push(channel);
}
const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
let orderBy;
let sortParams = [];
if (sort === 'recent') {
orderBy = `ORDER BY COALESCE((SELECT watched_at FROM history WHERE user_id = ? AND video_id = v.id), 0) DESC`;
sortParams = [userId];
} else if (sort === 'oldest') {
orderBy = 'ORDER BY added_at ASC';
} else if (sort === 'views') {
orderBy = 'ORDER BY views DESC';
} else if (sort === 'az') {
orderBy = 'ORDER BY title COLLATE NOCASE ASC';
} else {
orderBy = 'ORDER BY added_at DESC, id DESC';
}
const total = db.prepare(`SELECT COUNT(*) AS c FROM videos v ${where}`).get(...whereParams).c;
const rows = db.prepare(`
SELECT v.*, h.position AS watched_position, h.completed AS watch_completed
FROM videos v
LEFT JOIN history h ON h.user_id = ? AND h.video_id = v.id
${where} ${orderBy} LIMIT ? OFFSET ?
`).all(userId, ...whereParams, ...sortParams, limit, offset);
return { videos: attachFavorites(rows, favoriteSet(userId)), total };
}
function listChannels() {
return db.prepare(`SELECT channel AS name, COUNT(*) AS count FROM videos GROUP BY channel ORDER BY channel COLLATE NOCASE ASC`).all();
}
function recentHistory(userId, limit = 20) {
return db.prepare(`
SELECT v.*, h.position, h.duration AS watch_duration, h.completed, h.watched_at
FROM history h JOIN videos v ON v.id = h.video_id
WHERE h.user_id = ?
ORDER BY h.watched_at DESC LIMIT ?
`).all(userId, limit);
}
function listFavorites(userId, { limit, offset }) {
const rows = db.prepare(`
SELECT v.*, h.position AS watched_position, h.completed AS watch_completed
FROM favorites f
JOIN videos v ON v.id = f.video_id
LEFT JOIN history h ON h.user_id = ? AND h.video_id = v.id
WHERE f.user_id = ?
ORDER BY f.created_at DESC, f.video_id DESC
LIMIT ? OFFSET ?
`).all(userId, userId, limit, offset);
const total = db.prepare('SELECT COUNT(*) AS c FROM favorites WHERE user_id = ?').get(userId).c;
for (const r of rows) r.favorite = 1;
return { videos: rows, total };
}
function recordProgress(userId, videoId, position, duration) {
const hist = db.prepare('SELECT last_recorded FROM history WHERE user_id = ? AND video_id = ?').get(userId, videoId);
const prev = hist ? (hist.last_recorded || 0) : 0;
let delta = 0;
if (position > prev) delta = position - prev;
else if (position < prev * 0.5) delta = Math.max(0, position);
const completed = duration > 0 && position >= duration * 0.9 ? 1 : 0;
db.prepare(`
INSERT INTO history (user_id, video_id, position, duration, completed, watched_at, last_recorded)
VALUES (?, ?, ?, ?, ?, unixepoch(), ?)
ON CONFLICT(user_id, video_id) DO UPDATE SET
position = MAX(position, excluded.position),
duration = excluded.duration,
completed = excluded.completed,
watched_at = excluded.watched_at,
last_recorded = excluded.last_recorded
`).run(userId, videoId, position, duration, completed, position);
if (delta > 0) {
db.prepare('INSERT INTO watch_events (user_id, video_id, seconds, watched_at) VALUES (?, ?, ?, unixepoch())').run(userId, videoId, delta);
}
return db.prepare('SELECT * FROM history WHERE user_id = ? AND video_id = ?').get(userId, videoId);
}
function getHistoryForVideo(userId, videoId) {
return db.prepare('SELECT * FROM history WHERE user_id = ? AND video_id = ?').get(userId, videoId) || null;
}
function markViewed(videoId) {
db.prepare('UPDATE videos SET views = views + 1 WHERE id = ?').run(videoId);
}
function toggleFavorite(userId, videoId) {
const existing = db.prepare('SELECT 1 FROM favorites WHERE user_id = ? AND video_id = ?').get(userId, videoId);
if (existing) {
db.prepare('DELETE FROM favorites WHERE user_id = ? AND video_id = ?').run(userId, videoId);
return { favorite: 0 };
}
db.prepare('INSERT INTO favorites (user_id, video_id) VALUES (?, ?)').run(userId, videoId);
return { favorite: 1 };
}
function createUser(username, password) {
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.scryptSync(password, salt, 64).toString('hex');
const res = db.prepare('INSERT INTO users (username, password_hash, salt) VALUES (?, ?, ?)').run(username, hash, salt);
return { id: res.lastInsertRowid, username };
}
function findUserByUsername(username) {
return db.prepare('SELECT * FROM users WHERE username = ? COLLATE NOCASE').get(String(username || '').trim()) || null;
}
function verifyPassword(user, password) {
const hash = crypto.scryptSync(String(password || ''), user.salt, 64).toString('hex');
return crypto.timingSafeEqual(Buffer.from(hash, 'hex'), Buffer.from(user.password_hash, 'hex'));
}
function createSession(userId) {
const token = crypto.randomBytes(32).toString('hex');
db.prepare('INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, unixepoch() + 30 * 86400)').run(token, userId);
return token;
}
function getUserFromSessionToken(token) {
if (!token) return null;
const row = db.prepare(`
SELECT u.id, u.username FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token = ? AND s.expires_at > unixepoch()
`).get(token);
return row || null;
}
function destroySession(token) {
if (token) db.prepare('DELETE FROM sessions WHERE token = ?').run(token);
}
function listPlaylists(userId) {
const rows = db.prepare(`
SELECT p.id, p.name, p.created_at, COUNT(i.video_id) AS count
FROM playlists p LEFT JOIN playlist_items i ON i.playlist_id = p.id
WHERE p.user_id = ?
GROUP BY p.id ORDER BY p.created_at DESC, p.name COLLATE NOCASE ASC
`).all(userId);
return rows;
}
function createPlaylist(userId, name) {
const res = db.prepare('INSERT INTO playlists (user_id, name) VALUES (?, ?)').run(userId, name);
return { id: res.lastInsertRowid, name };
}
function getPlaylist(userId, id) {
return db.prepare('SELECT * FROM playlists WHERE id = ? AND user_id = ?').get(id, userId) || null;
}
function deletePlaylist(userId, id) {
const res = db.prepare('DELETE FROM playlists WHERE id = ? AND user_id = ?').run(id, userId);
return res.changes > 0;
}
function getPlaylistVideos(userId, id) {
const pl = getPlaylist(userId, id);
if (!pl) return null;
const rows = db.prepare(`
SELECT v.*, i.position AS item_position, h.position AS watched_position, h.completed AS watch_completed
FROM playlist_items i
JOIN videos v ON v.id = i.video_id
LEFT JOIN history h ON h.user_id = ? AND h.video_id = v.id
WHERE i.playlist_id = ?
ORDER BY i.position ASC, i.video_id ASC
`).all(userId, id);
const favs = favoriteSet(userId);
for (const r of rows) r.favorite = favs.has(r.id) ? 1 : 0;
return { playlist: pl, videos: rows, total: rows.length };
}
function addVideoToPlaylist(userId, playlistId, videoId) {
const pl = getPlaylist(userId, playlistId);
if (!pl) return null;
const existing = db.prepare('SELECT 1 FROM playlist_items WHERE playlist_id = ? AND video_id = ?').get(playlistId, videoId);
if (existing) return { already: true };
const maxPos = db.prepare('SELECT COALESCE(MAX(position), -1) AS m FROM playlist_items WHERE playlist_id = ?').get(playlistId).m;
db.prepare('INSERT INTO playlist_items (playlist_id, video_id, position) VALUES (?, ?, ?)').run(playlistId, videoId, maxPos + 1);
return { already: false };
}
function removeVideoFromPlaylist(userId, playlistId, videoId) {
const pl = getPlaylist(userId, playlistId);
if (!pl) return null;
const res = db.prepare('DELETE FROM playlist_items WHERE playlist_id = ? AND video_id = ?').run(playlistId, videoId);
if (res.changes > 0) normalizePlaylistPositions(playlistId);
return { ok: res.changes > 0 };
}
function reorderPlaylist(userId, playlistId, orderedVideoIds) {
const pl = getPlaylist(userId, playlistId);
if (!pl) return null;
const existing = db.prepare('SELECT video_id FROM playlist_items WHERE playlist_id = ?').all(playlistId).map(r => r.video_id);
if (existing.length !== orderedVideoIds.length || !existing.every(id => orderedVideoIds.includes(id))) {
return null;
}
const tx = db.transaction(() => {
for (let i = 0; i < orderedVideoIds.length; i++) {
db.prepare('UPDATE playlist_items SET position = ? WHERE playlist_id = ? AND video_id = ?').run(i, playlistId, orderedVideoIds[i]);
}
});
tx();
return { ok: true };
}
function normalizePlaylistPositions(playlistId) {
const rows = db.prepare('SELECT video_id FROM playlist_items WHERE playlist_id = ? ORDER BY position ASC, video_id ASC').all(playlistId);
const tx = db.transaction(() => {
for (let i = 0; i < rows.length; i++) {
db.prepare('UPDATE playlist_items SET position = ? WHERE playlist_id = ? AND video_id = ?').run(i, playlistId, rows[i].video_id);
}
});
tx();
}
function getStats(userId) {
const totalSeconds = db.prepare('SELECT COALESCE(SUM(seconds), 0) AS s FROM watch_events WHERE user_id = ?').get(userId).s;
const completedCount = db.prepare('SELECT COUNT(*) AS c FROM history WHERE user_id = ? AND completed = 1').get(userId).c;
const startedCount = db.prepare('SELECT COUNT(*) AS c FROM history WHERE user_id = ?').get(userId).c;
const monthStart = Math.floor(Date.now() / 1000) - 30 * 86400;
const thisMonthSeconds = db.prepare('SELECT COALESCE(SUM(seconds), 0) AS s FROM watch_events WHERE user_id = ? AND watched_at >= ?').get(userId, monthStart).s;
const dailyRaw = db.prepare(`
SELECT date(watched_at, 'unixepoch') AS day, SUM(seconds) AS seconds
FROM watch_events WHERE user_id = ? AND watched_at >= ?
GROUP BY day ORDER BY day ASC
`).all(userId, Math.floor(Date.now() / 1000) - 14 * 86400);
const topChannels = db.prepare(`
SELECT v.channel AS channel, COALESCE(SUM(e.seconds), 0) AS seconds, COUNT(DISTINCT e.video_id) AS videos
FROM watch_events e JOIN videos v ON v.id = e.video_id
WHERE e.user_id = ?
GROUP BY v.channel ORDER BY seconds DESC LIMIT 5
`).all(userId);
const topVideos = db.prepare(`
SELECT v.id, v.title, v.channel, COALESCE(SUM(e.seconds), 0) AS seconds
FROM watch_events e JOIN videos v ON v.id = e.video_id
WHERE e.user_id = ?
GROUP BY v.id ORDER BY seconds DESC LIMIT 5
`).all(userId);
return { totalSeconds, completedCount, startedCount, thisMonthSeconds, daily: dailyRaw, topChannels, topVideos };
}
function getChannelStats(userId, channel) {
const videos = db.prepare('SELECT COUNT(*) AS c, COALESCE(SUM(duration), 0) AS total_seconds FROM videos WHERE channel = ?').get(channel);
const watchedSeconds = db.prepare(`
SELECT COALESCE(SUM(e.seconds), 0) AS s
FROM watch_events e JOIN videos v ON v.id = e.video_id
WHERE v.channel = ? AND e.user_id = ?
`).get(channel, userId).s;
const completedCount = db.prepare(`
SELECT COUNT(*) AS c FROM history h JOIN videos v ON v.id = h.video_id
WHERE v.channel = ? AND h.user_id = ? AND h.completed = 1
`).get(channel, userId).c;
return { name: channel, videos: videos.c, totalSeconds: videos.total_seconds, watchedSeconds, completedCount };
}
function getNextVideo(userId, videoId, mode) {
const current = getVideo(videoId);
if (!current) return null;
if (mode === 'random') {
const count = db.prepare('SELECT COUNT(*) AS c FROM videos WHERE id != ?').get(videoId).c;
if (count <= 0) return null;
const row = db.prepare(`SELECT v.id, v.title, v.channel, v.duration FROM videos v WHERE id != ? ORDER BY RANDOM() LIMIT 1`).get(videoId);
return row;
}
const siblings = db.prepare('SELECT id, title, channel, duration FROM videos WHERE channel = ? ORDER BY added_at DESC, id DESC').all(current.channel);
if (siblings.length <= 1) {
const count = db.prepare('SELECT COUNT(*) AS c FROM videos WHERE id != ?').get(videoId).c;
if (count <= 0) return null;
return db.prepare(`SELECT v.id, v.title, v.channel, v.duration FROM videos v WHERE id != ? ORDER BY RANDOM() LIMIT 1`).get(videoId);
}
const idx = siblings.findIndex(v => v.id === videoId);
return siblings[(idx + 1) % siblings.length];
}
module.exports = {
db,
DATA_DIR,
THUMB_DIR,
upsertVideo,
deleteVideosByPaths,
getVideo,
listVideos,
listChannels,
recentHistory,
listFavorites,
recordProgress,
getHistoryForVideo,
markViewed,
toggleFavorite,
listPlaylists,
createPlaylist,
getPlaylist,
deletePlaylist,
getPlaylistVideos,
addVideoToPlaylist,
removeVideoFromPlaylist,
reorderPlaylist,
getStats,
getChannelStats,
getNextVideo,
createUser,
findUserByUsername,
verifyPassword,
createSession,
getUserFromSessionToken,
destroySession,
migrateLegacyData,
};
+325
View File
@@ -0,0 +1,325 @@
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;
+124
View File
@@ -0,0 +1,124 @@
const fs = require('fs');
const path = require('path');
const { execFile } = require('child_process');
const { db, upsertVideo, deleteVideosByPaths, THUMB_DIR } = require('./db');
const VIDEO_EXTS = new Set(['.mp4', '.mkv', '.webm', '.mov', '.avi', '.m4v', '.mpg', '.mpeg', '.ts', '.wmv']);
function walkDir(dir, base = dir) {
const results = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...walkDir(full, base));
} else if (entry.isFile() && VIDEO_EXTS.has(path.extname(entry.name).toLowerCase())) {
const rel = path.relative(base, full);
results.push({ absPath: full, relPath: rel, filename: entry.name });
}
}
return results;
}
function channelOf(relPath) {
const parts = relPath.split(path.sep);
if (parts.length <= 1) return 'Uncategorized';
return parts[0];
}
function titleOf(filename) {
const base = filename.replace(/\.[^.]+$/, '');
return base.replace(/[._-]+/g, ' ').replace(/\s+/g, ' ').trim();
}
function probeDuration(absPath) {
return new Promise((resolve) => {
execFile('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', absPath],
{ timeout: 30000 }, (err, stdout) => {
const d = parseFloat(String(stdout || '').trim());
resolve(isFinite(d) && d > 0 ? d : 0);
});
});
}
function makeThumbnail(id, absPath, duration) {
const thumbPath = path.join(THUMB_DIR, `${id}.jpg`);
const seek = duration > 0 ? Math.min(Math.max(duration * 0.25, 0.5), 10) : 1;
return new Promise((resolve) => {
execFile('ffmpeg', ['-y', '-ss', String(seek), '-i', absPath, '-frames:v', '1', '-vf', 'scale=640:-2', thumbPath],
{ timeout: 30000 }, (err) => {
if (err) {
try { fs.unlinkSync(thumbPath); } catch {}
resolve(null);
} else {
resolve(thumbPath);
}
});
});
}
async function rescan(rootDir, { onProgress } = {}) {
const files = walkDir(rootDir);
const seen = new Set();
let added = 0, updated = 0, unchanged = 0, failed = 0;
for (const f of files) {
seen.add(f.relPath);
let stat;
try {
stat = fs.statSync(f.absPath);
} catch {
failed++;
continue;
}
const existing = db.prepare('SELECT * FROM videos WHERE path = ?').get(f.relPath);
if (existing && Math.abs(existing.size - stat.size) < 1 && Math.abs(existing.mtime - stat.mtimeMs / 1000) < 1) {
unchanged++;
continue;
}
const duration = await probeDuration(f.absPath);
if (!duration) failed++;
const channel = channelOf(f.relPath);
const title = titleOf(f.filename);
const isNew = !existing;
const id = upsertVideo({
path: f.relPath,
filename: f.filename,
title,
channel,
duration,
size: stat.size,
mtime: stat.mtimeMs / 1000,
});
if (isNew) added++; else updated++;
const thumbPath = path.join(THUMB_DIR, `${id}.jpg`);
if (!fs.existsSync(thumbPath) || isNew) {
await makeThumbnail(id, f.absPath, duration);
}
if (onProgress) onProgress({ done: added + updated + unchanged, total: files.length });
}
const stale = db.prepare('SELECT id, path FROM videos').all().filter(r => !seen.has(r.path));
if (stale.length) {
deleteVideosByPaths(stale.map(r => r.path));
for (const r of stale) {
try { fs.unlinkSync(path.join(THUMB_DIR, `${r.id}.jpg`)); } catch {}
}
}
return { total: files.length, added, updated, unchanged, failed, removed: stale.length };
}
if (require.main === module) {
const rootDir = process.argv[2] || path.join(__dirname, '..', 'demo-videos');
rescan(rootDir, { onProgress: p => process.stdout.write(`\rscanned ${p.done}/${p.total}`) })
.then(stats => {
console.log('\nRescan complete:', stats);
process.exit(0);
})
.catch(err => {
console.error('Scan failed:', err);
process.exit(1);
});
}
module.exports = { rescan, walkDir, channelOf, titleOf };