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, };