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

+23
View File
@@ -0,0 +1,23 @@
FROM node:24-alpine AS deps
WORKDIR /app
RUN apk add --no-cache python3 make g++
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
FROM node:24-alpine
ENV NODE_ENV=production \
PORT=8080
WORKDIR /app
RUN apk add --no-cache ffmpeg && addgroup -S vidhive && adduser -S vidhive -G vidhive
COPY --from=deps /app/node_modules ./node_modules
COPY package.json ./
COPY server ./server
COPY public ./public
COPY scripts ./scripts
COPY demo-videos ./demo-videos
RUN mkdir -p /app/data && chown -R vidhive:vidhive /app/data
USER vidhive
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||8080)+'/').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
CMD ["node", "server/index.js"]
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+15
View File
@@ -0,0 +1,15 @@
{
"name": "seantube",
"version": "1.0.0",
"description": "Self-hosted YouTube alternative for local videos",
"main": "server/index.js",
"scripts": {
"start": "node server/index.js",
"rescan": "node server/scanner.js --cli",
"demo": "node scripts/generate-demo.js"
},
"dependencies": {
"express": "^4.21.2",
"better-sqlite3": "^12.2.0"
}
}
+468
View File
@@ -0,0 +1,468 @@
* { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #0f0f12;
--surface: #1a1a21;
--surface-2: #23232c;
--border: #2c2c36;
--text: #ececf1;
--muted: #9b9ba8;
--accent: #ff5252;
--accent-hover: #ff6a6a;
--green: #4ade80;
--header-bg: rgba(15, 15, 18, 0.92);
--toast-bg: #23232c;
--chip-active-bg: #ffffff;
--chip-active-text: #111111;
}
[data-theme="light"] {
--bg: #f6f6fa;
--surface: #ffffff;
--surface-2: #ececf3;
--border: #e0e0e9;
--text: #1d1d24;
--muted: #63636f;
--accent: #e03131;
--accent-hover: #c92a2a;
--green: #16a34a;
--header-bg: rgba(246, 246, 250, 0.92);
--toast-bg: #ffffff;
--chip-active-bg: #1d1d24;
--chip-active-text: #ffffff;
}
html, body { height: 100%; }
body {
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
line-height: 1.5;
}
header {
position: sticky; top: 0; z-index: 50;
display: flex; align-items: center; gap: 20px;
padding: 12px 24px;
background: var(--header-bg);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--border);
}
.logo {
display: flex; align-items: center; gap: 10px;
font-size: 20px; font-weight: 800; letter-spacing: -0.5px;
color: var(--text); text-decoration: none; white-space: nowrap;
}
.logo .mark {
width: 34px; height: 34px; border-radius: 9px;
background: linear-gradient(135deg, var(--accent), #b91c1c);
display: grid; place-items: center;
font-size: 17px; color: #fff;
}
.search {
flex: 1; max-width: 560px;
position: relative;
}
.search input {
width: 100%; padding: 9px 14px 9px 38px;
background: var(--surface); border: 1px solid var(--border);
border-radius: 999px; color: var(--text); font-size: 14px;
outline: none; transition: border-color .15s;
}
.search input:focus { border-color: var(--accent); }
.search input::placeholder { color: var(--muted); }
.search .icon {
position: absolute; left: 12px; top: 50%; transform: translateY(-50%);
color: var(--muted); pointer-events: none; font-size: 15px;
}
nav { display: flex; align-items: center; gap: 6px; }
nav a, .btn {
color: var(--text); text-decoration: none; font-size: 14px; font-weight: 600;
padding: 8px 14px; border-radius: 999px; border: none; cursor: pointer;
background: transparent; transition: background .15s;
}
nav a:hover, .btn:hover { background: var(--surface-2); }
nav a.active { background: var(--surface-2); color: #fff; }
.btn.icon-btn { padding: 8px 10px; font-size: 16px; }
main { max-width: 1440px; margin: 0 auto; padding: 24px; }
h2.section-title {
font-size: 18px; font-weight: 700; margin: 8px 0 16px;
display: flex; align-items: center; gap: 10px;
}
h2.section-title .count { color: var(--muted); font-size: 13px; font-weight: 500; }
.chips { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 10px; margin-bottom: 14px; scrollbar-width: none; }
.chips::-webkit-scrollbar { display: none; }
.chip {
white-space: nowrap; padding: 7px 16px; border-radius: 999px;
background: var(--surface); border: 1px solid var(--border);
color: var(--text); font-size: 13px; font-weight: 600; cursor: pointer;
}
.chip:hover { background: var(--surface-2); }
.chip.active { background: var(--chip-active-bg); border-color: var(--chip-active-bg); color: var(--chip-active-text); }
.toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
.toolbar .result-count { color: var(--muted); font-size: 13px; }
select.sort {
background: var(--surface); color: var(--text); border: 1px solid var(--border);
border-radius: 8px; padding: 7px 10px; font-size: 13px; cursor: pointer; outline: none;
}
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 18px; }
.card { cursor: pointer; text-decoration: none; color: inherit; display: block; }
.thumb {
position: relative; aspect-ratio: 16/9; border-radius: 12px; overflow: hidden;
background: var(--surface-2); border: 1px solid var(--border);
}
.thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
.thumb .placeholder {
width: 100%; height: 100%;
background: linear-gradient(135deg, #2a2a35, #1d1d26);
display: grid; place-items: center; color: var(--muted); font-size: 34px;
}
.thumb .play-overlay {
position: absolute; inset: 0; display: grid; place-items: center;
background: rgba(0,0,0,0.35); opacity: 0; transition: opacity .15s;
}
.card:hover .play-overlay { opacity: 1; }
.thumb .play-overlay .circle {
width: 52px; height: 52px; border-radius: 50%; background: rgba(255,82,82,0.95);
display: grid; place-items: center; color: #fff; font-size: 18px; padding-left: 3px;
}
.thumb .badge {
position: absolute; top: 8px; right: 8px;
background: rgba(0,0,0,0.75); color: #fff; font-size: 11px; font-weight: 700;
padding: 2px 7px; border-radius: 6px;
}
.thumb .progress {
position: absolute; left: 0; right: 0; bottom: 0; height: 5px; background: rgba(0,0,0,0.55);
}
.thumb .progress .fill { height: 100%; background: var(--accent); }
.thumb .progress .fill.done { background: var(--green); }
.fav-star {
position: absolute; top: 8px; left: 8px; font-size: 18px; color: #ffd54a;
filter: drop-shadow(0 1px 2px rgba(0,0,0,0.6)); pointer-events: none;
}
.card .title {
margin-top: 9px; font-size: 14px; font-weight: 600; line-height: 1.35;
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
}
.card .meta { margin-top: 3px; font-size: 12px; color: var(--muted); }
.continue-strip { display: flex; gap: 14px; overflow-x: auto; padding: 4px 2px 16px; scrollbar-width: thin; margin-bottom: 8px; }
.continue-card { min-width: 250px; max-width: 250px; cursor: pointer; }
.watch-layout { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 28px; align-items: start; }
@media (max-width: 1100px) { .watch-layout { grid-template-columns: 1fr; } }
.player-wrap { border-radius: 14px; overflow: hidden; background: #000; border: 1px solid var(--border); }
.player-wrap video { width: 100%; display: block; max-height: 72vh; background: #000; }
.player-error { padding: 48px 24px; text-align: center; color: var(--muted); }
.watch-title { font-size: 22px; font-weight: 700; margin: 18px 0 6px; letter-spacing: -0.3px; }
.watch-meta { display: flex; align-items: center; gap: 12px; color: var(--muted); font-size: 13px; flex-wrap: wrap; }
.watch-meta a { color: inherit; text-decoration: none; border-bottom: 1px dotted var(--muted); }
.watch-meta a:hover { color: #fff; }
.watch-actions { display: flex; gap: 10px; margin-top: 14px; }
.btn.primary { background: var(--accent); color: #fff; padding: 9px 18px; }
.btn.primary:hover { background: var(--accent-hover); }
.btn.ghost { background: var(--surface); border: 1px solid var(--border); }
.related h3 { font-size: 15px; color: var(--muted); font-weight: 700; text-transform: uppercase; letter-spacing: 0.6px; margin-bottom: 12px; }
.related-item { display: flex; gap: 10px; padding: 8px; border-radius: 10px; cursor: pointer; color: inherit; text-decoration: none; }
.related-item:hover { background: var(--surface); }
.related-item img, .related-item .ph {
width: 96px; height: 54px; border-radius: 8px; object-fit: cover; flex-shrink: 0;
background: linear-gradient(135deg, #2a2a35, #1d1d26); display: grid; place-items: center; color: var(--muted);
}
.related-item .t { font-size: 13px; font-weight: 600; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.related-item .m { font-size: 11px; color: var(--muted); margin-top: 4px; }
.history-row { display: flex; gap: 16px; padding: 12px; border-radius: 12px; cursor: pointer; color: inherit; text-decoration: none; border: 1px solid transparent; align-items: center; }
.history-row:hover { background: var(--surface); border-color: var(--border); }
.history-row .thumb { width: 180px; flex-shrink: 0; aspect-ratio: 16/9; }
.history-row .info { flex: 1; min-width: 0; }
.history-row .title { font-size: 14px; font-weight: 600; margin-bottom: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.history-row .meta { font-size: 12px; color: var(--muted); }
.history-row .bar { height: 6px; background: var(--surface-2); border-radius: 999px; overflow: hidden; margin-top: 8px; }
.history-row .bar .fill { height: 100%; background: var(--accent); }
.history-row .bar .fill.done { background: var(--green); }
.history-row .time { font-size: 12px; color: var(--muted); white-space: nowrap; }
.load-more { display: block; margin: 28px auto; padding: 11px 30px; background: var(--surface); border: 1px solid var(--border); border-radius: 999px; color: var(--text); font-size: 14px; font-weight: 600; cursor: pointer; }
.load-more:hover { background: var(--surface-2); }
.empty { text-align: center; padding: 70px 20px; color: var(--muted); }
.empty .big { font-size: 42px; margin-bottom: 12px; }
.empty p { max-width: 420px; margin: 0 auto; }
.toast {
position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);
background: var(--toast-bg); color: var(--text); border: 1px solid var(--border);
padding: 10px 22px; border-radius: 999px; font-size: 13px; z-index: 100;
box-shadow: 0 8px 24px rgba(0,0,0,0.4); opacity: 0; transition: opacity .25s; pointer-events: none;
}
.toast.show { opacity: 1; }
@media (max-width: 720px) {
header { padding: 10px 12px; gap: 10px; flex-wrap: wrap; }
main { padding: 14px; }
.grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 12px; }
.history-row .thumb { width: 120px; }
.continue-card { min-width: 190px; max-width: 190px; }
}
body.logged-out header { display: none; }
#user-area { display: flex; align-items: center; gap: 8px; }
#user-area .avatar {
width: 32px; height: 32px; border-radius: 50%;
background: linear-gradient(135deg, var(--accent), #b91c1c);
display: grid; place-items: center; font-weight: 700; font-size: 14px; color: #fff;
}
#user-area .uname { font-size: 13px; font-weight: 600; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fav-btn {
position: absolute; top: 8px; left: 8px; z-index: 2;
width: 34px; height: 34px; border-radius: 50%;
background: rgba(0,0,0,0.55); color: #ffd54a; font-size: 17px; line-height: 1;
border: none; cursor: pointer; display: grid; place-items: center;
transition: transform .12s, background .12s;
}
.fav-btn:hover { transform: scale(1.15); background: rgba(0,0,0,0.75); }
.fav-btn.off { color: rgba(255,255,255,0.55); }
.login-screen { min-height: 100vh; display: grid; place-items: center; padding: 24px; background: radial-gradient(1200px 600px at 50% -10%, #1d1d26, var(--bg)); }
.login-card {
width: min(400px, 100%); background: var(--surface);
border: 1px solid var(--border); border-radius: 18px; padding: 30px 28px;
box-shadow: 0 24px 60px rgba(0,0,0,0.45);
}
.login-card .logo { justify-content: center; margin-bottom: 18px; font-size: 22px; }
.login-card h1 { font-size: 20px; text-align: center; letter-spacing: -0.3px; }
.login-sub { color: var(--muted); font-size: 13px; text-align: center; margin: 6px 0 18px; }
.mode-toggle { display: flex; background: var(--surface-2); border-radius: 10px; padding: 4px; margin-bottom: 16px; }
.mode-toggle button {
flex: 1; padding: 8px; border: none; border-radius: 7px; cursor: pointer;
background: transparent; color: var(--muted); font-size: 13px; font-weight: 700;
}
.mode-toggle button.active { background: var(--chip-active-bg); color: var(--chip-active-text); }
.login-card input[type=text], .login-card input[type=password] {
width: 100%; padding: 11px 14px; margin-bottom: 10px;
background: var(--bg); border: 1px solid var(--border); border-radius: 9px;
color: var(--text); font-size: 14px; outline: none; transition: border-color .15s;
}
.login-card input:focus { border-color: var(--accent); }
.login-error { color: #ff7b7b; font-size: 13px; min-height: 18px; margin: 2px 0 8px; text-align: center; }
.login-submit { width: 100%; padding: 12px; font-size: 15px; border-radius: 10px; background: var(--accent); color: #fff; border: none; cursor: pointer; font-weight: 700; }
.login-submit:hover { background: var(--accent-hover); }
.login-submit:disabled { opacity: .6; cursor: default; }
[data-theme="light"] .thumb .placeholder,
[data-theme="light"] .related-item img,
[data-theme="light"] .related-item .ph {
background: linear-gradient(135deg, #e8e8f0, #d8d8e4);
color: #9a9aa8;
}
[data-theme="light"] .login-screen {
background: radial-gradient(1200px 600px at 50% -10%, #e3e3ee, var(--bg));
}
[data-theme="light"] .card:hover .play-overlay { background: rgba(0,0,0,0.25); }
[data-theme="light"] .player-wrap video { background: #000; }
#theme-toggle { font-size: 16px; padding: 8px 10px; }
.seg { display: flex; background: var(--surface); border: 1px solid var(--border); border-radius: 999px; padding: 3px; gap: 2px; }
.seg button { border: none; background: transparent; color: var(--muted); font-size: 12px; font-weight: 600; padding: 6px 13px; border-radius: 999px; cursor: pointer; transition: all .15s; }
.seg button.active { background: var(--chip-active-bg); color: var(--chip-active-text); }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 14px; margin-bottom: 22px; }
.stat-card { background: var(--surface); border: 1px solid var(--border); border-radius: 14px; padding: 18px; }
.stat-card .num { font-size: 26px; font-weight: 800; letter-spacing: -0.5px; color: var(--text); }
.stat-card .lbl { font-size: 12px; color: var(--muted); margin-top: 4px; text-transform: uppercase; letter-spacing: 0.6px; }
.chart-wrap { background: var(--surface); border: 1px solid var(--border); border-radius: 14px; padding: 18px; margin-bottom: 22px; }
.chart-wrap h3 { font-size: 13px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.7px; margin-bottom: 14px; }
.chart-bars { display: flex; align-items: flex-end; gap: 6px; height: 130px; }
.chart-bar { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 5px; min-width: 0; }
.chart-bar .fill { width: 100%; max-width: 34px; background: linear-gradient(180deg, var(--accent), #b91c1c); border-radius: 6px 6px 3px 3px; min-height: 4px; }
.chart-bar .day { font-size: 10px; color: var(--muted); white-space: nowrap; }
.stats-cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px; }
.stats-list { background: var(--surface); border: 1px solid var(--border); border-radius: 14px; padding: 14px 16px; }
.stats-list h3 { font-size: 13px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.7px; margin-bottom: 10px; }
.stats-item { display: flex; align-items: center; gap: 12px; padding: 8px 4px; border-bottom: 1px solid var(--border); }
.stats-item:last-child { border-bottom: none; }
.stats-item .rank { width: 22px; color: var(--muted); font-weight: 700; font-size: 13px; text-align: center; flex-shrink: 0; }
.stats-item .body { flex: 1; min-width: 0; }
.stats-item .t { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.stats-item .m { font-size: 11px; color: var(--muted); margin-top: 2px; }
.stats-item .bar { height: 5px; background: var(--surface-2); border-radius: 999px; overflow: hidden; margin-top: 6px; }
.stats-item .bar .fill { height: 100%; background: var(--accent); border-radius: 999px; }
.stats-item .secs { font-size: 12px; color: var(--muted); white-space: nowrap; flex-shrink: 0; }
.playlist-card { background: var(--surface); border: 1px solid var(--border); border-radius: 14px; padding: 16px; cursor: pointer; position: relative; transition: transform .12s, border-color .12s; }
.playlist-card:hover { transform: translateY(-2px); border-color: var(--accent); }
.playlist-card .name { font-size: 15px; font-weight: 700; word-break: break-word; padding-right: 28px; }
.playlist-card .meta { font-size: 12px; color: var(--muted); margin-top: 6px; }
.playlist-card .del-btn { position: absolute; top: 10px; right: 10px; border: none; background: transparent; color: var(--muted); cursor: pointer; font-size: 15px; padding: 4px 7px; border-radius: 7px; }
.playlist-card .del-btn:hover { color: var(--accent); background: var(--surface-2); }
.pl-row { display: flex; align-items: center; gap: 12px; padding: 10px 12px; background: var(--surface); border: 1px solid var(--border); border-radius: 12px; margin-bottom: 8px; }
.pl-row .num { width: 24px; color: var(--muted); font-weight: 700; text-align: center; flex-shrink: 0; }
.pl-row img, .pl-row .ph { width: 84px; height: 48px; border-radius: 8px; object-fit: cover; flex-shrink: 0; background: linear-gradient(135deg, #2a2a35, #1d1d26); display: grid; place-items: center; color: var(--muted); }
.pl-row .body { flex: 1; min-width: 0; cursor: pointer; }
.pl-row .t { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.pl-row .m { font-size: 11px; color: var(--muted); margin-top: 3px; }
.pl-row .actions { display: flex; gap: 4px; flex-shrink: 0; }
.pl-row .actions button { border: none; background: var(--surface-2); color: var(--muted); width: 28px; height: 28px; border-radius: 7px; cursor: pointer; font-size: 12px; }
.pl-row .actions button:hover { color: var(--text); background: var(--border); }
.new-playlist-bar { display: flex; gap: 10px; margin-bottom: 18px; }
.new-playlist-bar input { flex: 1; padding: 11px 14px; background: var(--surface); border: 1px solid var(--border); border-radius: 10px; color: var(--text); font-size: 14px; outline: none; }
.new-playlist-bar input:focus { border-color: var(--accent); }
.channel-stats { display: flex; gap: 22px; flex-wrap: wrap; margin: 10px 0 18px; font-size: 13px; color: var(--muted); }
.channel-stats .cs b { color: var(--text); font-weight: 700; }
.add-playlist-panel { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px; margin-top: 12px; max-width: 420px; }
.add-playlist-panel .pl-list { display: flex; flex-direction: column; gap: 6px; max-height: 220px; overflow-y: auto; margin-bottom: 10px; }
.add-playlist-panel .pl-item { display: flex; align-items: center; justify-content: space-between; padding: 7px 10px; border-radius: 8px; cursor: pointer; background: var(--surface-2); font-size: 13px; }
.add-playlist-panel .pl-item:hover { background: var(--border); }
.add-playlist-panel .pl-item .check { color: var(--green); font-weight: 700; }
.add-playlist-panel .new-pl { display: flex; gap: 8px; }
.add-playlist-panel .new-pl input { flex: 1; padding: 9px 12px; background: var(--bg); border: 1px solid var(--border); border-radius: 8px; color: var(--text); font-size: 13px; outline: none; }
.add-playlist-panel .new-pl button { border: none; background: var(--accent); color: #fff; padding: 9px 16px; border-radius: 8px; font-weight: 700; cursor: pointer; font-size: 13px; }
[data-theme="classic"] {
--bg: #c0c0c0;
--surface: #d4d4d4;
--surface-2: #ececec;
--border: #808080;
--text: #000000;
--muted: #333333;
--accent: #000080;
--accent-hover: #0000aa;
--green: #008000;
--header-bg: linear-gradient(180deg, #000080 0%, #1084d0 100%);
--toast-bg: #ffffe1;
--chip-active-bg: #000080;
--chip-active-text: #ffffff;
}
[data-theme="classic"] body { font-family: Arial, Helvetica, sans-serif; background: var(--bg); color: var(--text); }
[data-theme="classic"] * { border-radius: 0 !important; }
[data-theme="classic"] .play-overlay .circle,
[data-theme="classic"] .fav-btn { border-radius: 50% !important; }
[data-theme="classic"] header {
background: var(--header-bg);
border-bottom: 2px solid #ffffff;
box-shadow: none;
padding: 8px 16px;
}
[data-theme="classic"] .logo { color: #ffffff; font-weight: 900; text-transform: uppercase; letter-spacing: 1px; }
[data-theme="classic"] .logo .mark { background: #ffffff; color: #000080; border-radius: 0 !important; font-size: 16px; }
[data-theme="classic"] .search input {
background: #ffffff; color: #000000; border: 2px solid; border-color: #808080 #ffffff #ffffff #808080;
padding-left: 36px; font-family: "Courier New", monospace;
}
[data-theme="classic"] .search input::placeholder { color: #666666; }
[data-theme="classic"] .search .icon { color: #000080; font-size: 16px; }
[data-theme="classic"] nav a, [data-theme="classic"] .btn {
color: #ffffff; border: 2px solid; border-color: #ffffff #000080 #000080 #ffffff;
background: #c0c0c0; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; font-size: 12px;
}
[data-theme="classic"] nav a { padding: 6px 14px; }
[data-theme="classic"] nav a:hover, [data-theme="classic"] .btn:hover { background: #d4d4d4; color: #000080; }
[data-theme="classic"] nav a.active { background: #ffffff; border-color: #808080 #ffffff #ffffff #808080; color: #000080; }
[data-theme="classic"] .btn.icon-btn { padding: 6px 10px; font-size: 15px; }
[data-theme="classic"] .btn.primary { background: #000080; border-color: #ffffff #000040 #000040 #ffffff; color: #ffffff; }
[data-theme="classic"] .btn.primary:hover { background: #0000aa; }
[data-theme="classic"] .btn.ghost { background: #c0c0c0; border-color: #ffffff #808080 #808080 #ffffff; color: #000000; }
[data-theme="classic"] .btn:active { border-color: #808080 #ffffff #ffffff #808080; background: #b0b0b0; }
[data-theme="classic"] h2.section-title { color: #000080; text-transform: uppercase; letter-spacing: 1px; font-size: 17px; border-bottom: 2px solid #808080; padding-bottom: 6px; }
[data-theme="classic"] h2.section-title .count { color: #333333; }
[data-theme="classic"] .chip {
background: #c0c0c0; border: 2px solid; border-color: #ffffff #808080 #808080 #ffffff;
color: #000000; font-weight: 700; text-transform: uppercase; letter-spacing: 0.4px; font-size: 11px; padding: 6px 14px;
}
[data-theme="classic"] .chip:hover { background: #d4d4d4; }
[data-theme="classic"] .chip.active { background: #000080; border-color: #808080 #ffffff #ffffff #808080; color: #ffffff; }
[data-theme="classic"] select.sort, [data-theme="classic"] .new-playlist-bar input,
[data-theme="classic"] .add-playlist-panel .new-pl input {
background: #ffffff; color: #000000; border: 2px solid; border-color: #808080 #ffffff #ffffff #808080; font-family: "Courier New", monospace;
}
[data-theme="classic"] .result-count { color: #000000; font-family: "Courier New", monospace; }
[data-theme="classic"] .card .title { color: #0000ee; text-decoration: underline; }
[data-theme="classic"] .card .meta, [data-theme="classic"] .related-item .m,
[data-theme="classic"] .history-row .meta, [data-theme="classic"] .stats-item .m { color: #333333; font-family: "Courier New", monospace; }
[data-theme="classic"] .thumb { border: 2px solid #808080; background: #ffffff; }
[data-theme="classic"] .thumb .placeholder { background: repeating-linear-gradient(45deg, #ececec 0 8px, #d4d4d4 8px 16px); color: #000080; }
[data-theme="classic"] .thumb .badge { background: #000080; color: #ffffff; border-radius: 0 !important; border: 1px solid #ffffff; font-family: "Courier New", monospace; }
[data-theme="classic"] .thumb .progress { height: 8px; background: #808080; border-top: 1px solid #000000; }
[data-theme="classic"] .thumb .progress .fill { background: #000080; border-right: 2px solid #ffffff; }
[data-theme="classic"] .thumb .progress .fill.done { background: #008000; }
[data-theme="classic"] .play-overlay { background: rgba(0,0,0,0.35); }
[data-theme="classic"] .play-overlay .circle { background: #000080; border: 2px solid #ffffff; }
[data-theme="classic"] .stat-card, [data-theme="classic"] .chart-wrap, [data-theme="classic"] .stats-list,
[data-theme="classic"] .playlist-card, [data-theme="classic"] .pl-row, [data-theme="classic"] .history-row,
[data-theme="classic"] .login-card, [data-theme="classic"] .add-playlist-panel, [data-theme="classic"] .watch-actions {
background: #d4d4d4; border: 2px solid; border-color: #ffffff #808080 #808080 #ffffff; color: #000000; box-shadow: none;
}
[data-theme="classic"] .stat-card .num { color: #000080; }
[data-theme="classic"] .stat-card .lbl, [data-theme="classic"] .chart-wrap h3, [data-theme="classic"] .stats-list h3 { color: #000080; text-transform: uppercase; letter-spacing: 0.8px; }
[data-theme="classic"] .chart-bar .fill { background: repeating-linear-gradient(180deg, #000080 0 6px, #1084d0 6px 12px); border: 1px solid #000000; }
[data-theme="classic"] .stats-item .bar { height: 8px; background: #ffffff; border: 1px solid #808080; }
[data-theme="classic"] .stats-item .bar .fill { background: #000080; }
[data-theme="classic"] .playlist-card .name, [data-theme="classic"] .pl-row .t, [data-theme="classic"] .history-row .title { color: #0000ee; text-decoration: underline; }
[data-theme="classic"] .playlist-card .meta, [data-theme="classic"] .pl-row .m, [data-theme="classic"] .history-row .time,
[data-theme="classic"] .stats-item .secs, [data-theme="classic"] .channel-stats { color: #333333; font-family: "Courier New", monospace; }
[data-theme="classic"] .pl-row .actions button, [data-theme="classic"] .playlist-card .del-btn { background: #c0c0c0; border: 2px solid; border-color: #ffffff #808080 #808080 #ffffff; color: #000000; }
[data-theme="classic"] .pl-row .actions button:hover { background: #d4d4d4; }
[data-theme="classic"] .new-playlist-bar input, [data-theme="classic"] .add-playlist-panel .new-pl input { color: #000000; }
[data-theme="classic"] .login-card .logo { color: #000080; font-weight: 900; text-transform: uppercase; letter-spacing: 1px; }
[data-theme="classic"] .login-card h1 { color: #000000; }
[data-theme="classic"] .mode-toggle { background: #c0c0c0; border: 2px solid; border-color: #808080 #ffffff #ffffff #808080; padding: 4px; }
[data-theme="classic"] .mode-toggle button.active { background: #000080; color: #ffffff; }
[data-theme="classic"] .login-card input[type=text], [data-theme="classic"] .login-card input[type=password] {
background: #ffffff; color: #000000; border: 2px solid; border-color: #808080 #ffffff #ffffff #808080; font-family: "Courier New", monospace;
}
[data-theme="classic"] .login-submit { background: #000080; color: #ffffff; border: 2px solid; border-color: #ffffff #000040 #000040 #ffffff; text-transform: uppercase; letter-spacing: 1px; }
[data-theme="classic"] .login-submit:hover { background: #0000aa; }
[data-theme="classic"] .login-error { color: #b00000; font-family: "Courier New", monospace; }
[data-theme="classic"] .history-row .bar, [data-theme="classic"] .pl-row .body { background: transparent; }
[data-theme="classic"] .history-row .bar { height: 8px; background: #ffffff; border: 1px solid #808080; }
[data-theme="classic"] .history-row .bar .fill { background: #000080; }
[data-theme="classic"] .history-row .bar .fill.done { background: #008000; }
[data-theme="classic"] .history-row:hover, [data-theme="classic"] .pl-row:hover, [data-theme="classic"] .related-item:hover { background: #ececec; border-color: #000080; }
[data-theme="classic"] .continue-card .title { color: #0000ee; text-decoration: underline; }
[data-theme="classic"] .watch-meta a { color: #0000ee; text-decoration: underline; }
[data-theme="classic"] .watch-title { color: #000080; font-weight: 900; text-transform: uppercase; letter-spacing: 0.5px; }
[data-theme="classic"] .related h3 { color: #000080; }
[data-theme="classic"] .seg { background: #c0c0c0; border: 2px solid; border-color: #808080 #ffffff #ffffff #808080; padding: 4px; }
[data-theme="classic"] .seg button { color: #000000; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; font-size: 11px; }
[data-theme="classic"] .seg button.active { background: #000080; color: #ffffff; }
[data-theme="classic"] .channel-stats b { color: #000080; }
[data-theme="classic"] #user-area .uname { color: #ffffff; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
[data-theme="classic"] #user-area .avatar { background: #ffffff; color: #000080; border: 2px solid #ffffff; border-radius: 0 !important; }
[data-theme="classic"] .toast { background: #ffffe1; color: #000000; border: 2px solid; border-color: #808080 #ffffff #ffffff #808080; font-family: "Courier New", monospace; }
[data-theme="classic"] .load-more { background: #c0c0c0; border: 2px solid; border-color: #ffffff #808080 #808080 #ffffff; color: #000000; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
[data-theme="classic"] .empty { color: #333333; }
[data-theme="classic"] .empty .big { filter: none; }
[data-theme="classic"] .player-wrap video { background: #000000; border: 3px solid #808080; }
[data-theme="classic"] .watch-actions { gap: 10px; padding: 12px; }
+35
View File
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Seantube — Local Video Library</title>
<script>try{var t=localStorage.getItem('vidhive_theme');if(!t){t=window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches?'light':'dark'}document.documentElement.setAttribute('data-theme',t)}catch(e){}</script>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body class="logged-out">
<header id="app-header" style="display:none">
<a class="logo" href="#/">
<span class="mark">▶</span>
Seantube
</a>
<div class="search">
<span class="icon">⌕</span>
<input id="search-input" type="search" placeholder="Search videos or channels…" autocomplete="off" spellcheck="false">
</div>
<nav>
<a href="#/" data-nav="home">Home</a>
<a href="#/playlists" data-nav="playlists">Playlists</a>
<a href="#/favorites" data-nav="favorites">Favorites</a>
<a href="#/history" data-nav="history">History</a>
<a href="#/stats" data-nav="stats">Stats</a>
</nav>
<button class="btn icon-btn" id="rescan-btn" title="Rescan video folder">⟳</button>
<button class="btn icon-btn" id="theme-toggle" title="Toggle light/dark mode">🌙</button>
<div id="user-area"></div>
</header>
<main id="app"><div class="empty"><div class="big">…</div>Loading…</div></main>
<div class="toast" id="toast"></div>
<script src="/js/app.js"></script>
</body>
</html>
+830
View File
@@ -0,0 +1,830 @@
const app = document.getElementById('app');
const toastEl = document.getElementById('toast');
const searchInput = document.getElementById('search-input');
const body = document.body;
let toastTimer = null;
let currentUser = null;
let currentRoute = 'home';
let autoplayMode = localStorage.getItem('vidhive_autoplay') || 'off';
function setAutoplayMode(m) { autoplayMode = m; localStorage.setItem('vidhive_autoplay', m); }
let autoplayIntent = false;
const THEME_ORDER = ['dark', 'light', 'classic'];
const THEME_ICONS = { dark: '🌙', light: '☀️', classic: '🖥' };
const themeBtn = document.getElementById('theme-toggle');
function applyTheme(t) {
document.documentElement.setAttribute('data-theme', t);
if (themeBtn) {
themeBtn.textContent = THEME_ICONS[t] || '🌙';
const next = THEME_ORDER[(THEME_ORDER.indexOf(t) + 1) % THEME_ORDER.length];
themeBtn.title = `Theme: ${t} — click for ${next}`;
}
}
function initTheme() {
const stored = localStorage.getItem('vidhive_theme');
const prefersLight = window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches;
applyTheme(stored || (prefersLight ? 'light' : 'dark'));
}
if (themeBtn) themeBtn.addEventListener('click', () => {
const current = document.documentElement.getAttribute('data-theme') || 'dark';
const next = THEME_ORDER[(THEME_ORDER.indexOf(current) + 1) % THEME_ORDER.length];
localStorage.setItem('vidhive_theme', next);
applyTheme(next);
});
initTheme();
const state = {
q: '',
channel: null,
sort: 'newest',
offset: 0,
limit: 24,
total: 0,
};
function esc(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function fmtDur(sec) {
if (!sec || !isFinite(sec)) return '0:00';
sec = Math.floor(sec);
const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60;
if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
return `${m}:${String(s).padStart(2, '0')}`;
}
function fmtTime(sec) {
sec = Math.floor(sec || 0);
const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60);
if (h > 0) return `${h}h ${m}m`;
if (m > 0) return `${m} min`;
return `${sec}s`;
}
function fmtDate(ts) {
if (!ts) return '';
const d = new Date(ts * 1000);
const diff = (Date.now() - d.getTime()) / 1000;
if (diff < 60) return 'just now';
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
if (diff < 2592000) return `${Math.floor(diff / 86400)}d ago`;
return d.toLocaleDateString();
}
function fmtViews(n) {
if (!n) return '0 views';
if (n < 1000) return `${n} views`;
if (n < 1e6) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k views`;
return `${(n / 1e6).toFixed(1)}M views`;
}
async function api(path, opts) {
const res = await fetch(path, opts);
if (res.status === 401) {
showLoginScreen();
throw new Error('Unauthorized');
}
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const j = await res.json(); if (j && j.error) msg = j.error; } catch {}
throw new Error(msg);
}
return res.json();
}
function toast(msg) {
toastEl.textContent = msg;
toastEl.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toastEl.classList.remove('show'), 2600);
}
async function getMe() {
const r = await fetch('/api/auth/me');
if (!r.ok) return null;
try { const j = await r.json(); return j.user || null; } catch { return null; }
}
function showLoginScreen() {
currentUser = null;
body.classList.add('logged-out');
document.getElementById('app-header').style.display = 'none';
app.innerHTML = `
<div class="login-screen">
<form class="login-card" id="login-form">
<div class="logo" style="justify-content:center;margin-bottom:18px"><span class="mark">▶</span> Seantube</div>
<h1 id="login-title">Welcome back</h1>
<p class="login-sub" id="login-sub">Sign in to your account</p>
<div class="mode-toggle">
<button type="button" id="mode-login" class="active">Log in</button>
<button type="button" id="mode-register">Create account</button>
</div>
<input type="text" id="login-username" placeholder="Username" autocomplete="username" autocapitalize="none" spellcheck="false" required>
<input type="password" id="login-password" placeholder="Password" autocomplete="current-password" required>
<p class="login-error" id="login-error"></p>
<button type="submit" class="login-submit" id="login-submit">Log in</button>
</form>
</div>`;
let authMode = 'login';
const titleEl = document.getElementById('login-title');
const subEl = document.getElementById('login-sub');
const submitEl = document.getElementById('login-submit');
const errEl = document.getElementById('login-error');
const setMode = (mode) => {
authMode = mode;
document.getElementById('mode-login').classList.toggle('active', mode === 'login');
document.getElementById('mode-register').classList.toggle('active', mode === 'register');
if (mode === 'login') {
titleEl.textContent = 'Welcome back'; subEl.textContent = 'Sign in to your account'; submitEl.textContent = 'Log in';
document.getElementById('login-password').autocomplete = 'current-password';
} else {
titleEl.textContent = 'Create account'; subEl.textContent = 'Pick a username and password (min 6 characters)'; submitEl.textContent = 'Create account';
document.getElementById('login-password').autocomplete = 'new-password';
}
errEl.textContent = '';
};
document.getElementById('mode-login').addEventListener('click', () => setMode('login'));
document.getElementById('mode-register').addEventListener('click', () => setMode('register'));
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('login-username').value.trim();
const password = document.getElementById('login-password').value;
errEl.textContent = '';
submitEl.disabled = true;
try {
const res = await fetch(`/api/auth/${authMode === 'login' ? 'login' : 'register'}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) { errEl.textContent = data.error || 'Something went wrong'; submitEl.disabled = false; return; }
currentUser = data.user;
if (location.hash !== '#/') { location.hash = '#/'; return; }
render();
} catch (err) {
errEl.textContent = 'Network error — is the server running?';
submitEl.disabled = false;
}
});
}
async function showApp(user) {
currentUser = user;
body.classList.remove('logged-out');
document.getElementById('app-header').style.display = '';
const initial = esc((user.username || '?').charAt(0).toUpperCase());
document.getElementById('user-area').innerHTML = `
<span class="avatar">${initial}</span>
<span class="uname" title="${esc(user.username)}">${esc(user.username)}</span>
<button id="logout-btn" class="btn icon-btn" title="Log out">⏻</button>`;
document.getElementById('logout-btn').addEventListener('click', async () => {
try { await fetch('/api/auth/logout', { method: 'POST' }); } catch {}
currentUser = null;
render();
});
const status = await api('/api/status').catch(() => null);
if (status && status.lastRescanAt) {
document.getElementById('rescan-btn').title = `Rescan video folder (last: ${fmtDate(Math.floor(new Date(status.lastRescanAt).getTime() / 1000))})`;
}
}
function cardHtml(v) {
const dur = fmtDur(v.duration);
const progress = v.watched_position > 0 && v.duration > 0 ? Math.min(1, v.watched_position / v.duration) : 0;
const done = v.watch_completed || (progress >= 0.9);
return `
<div class="card" data-href="#/watch/${v.id}">
<div class="thumb">
<img src="/thumb/${v.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=placeholder>▶</div>'">
<button class="fav-btn ${v.favorite ? '' : 'off'}" data-video-id="${v.id}" title="Toggle favorite">${v.favorite ? '★' : '☆'}</button>
<span class="badge">${dur}</span>
<div class="play-overlay"><div class="circle">▶</div></div>
${progress > 0 ? `<div class="progress"><div class="fill${done ? ' done' : ''}" style="width:${(progress * 100).toFixed(1)}%"></div></div>` : ''}
</div>
<div class="title">${esc(v.title)}</div>
<div class="meta">${esc(v.channel)} · ${fmtViews(v.views)}</div>
</div>`;
}
async function loadGrid() {
let url, noun;
if (currentRoute === 'favorites') {
url = `/api/favorites?limit=${state.limit}&offset=${state.offset}`;
noun = 'videos';
} else {
const q = state.q ? `&q=${encodeURIComponent(state.q)}` : '';
const ch = state.channel ? `&channel=${encodeURIComponent(state.channel)}` : '';
url = `/api/videos?limit=${state.limit}&offset=${state.offset}&sort=${encodeURIComponent(state.sort)}${q}${ch}`;
noun = state.q ? 'results' : 'videos';
}
try {
const data = await api(url);
state.total = data.total;
const grid = document.getElementById('video-grid');
const empty = document.getElementById('empty-msg');
if (state.offset === 0) {
if (data.videos.length === 0) {
grid.innerHTML = '';
empty.style.display = 'block';
} else {
empty.style.display = 'none';
grid.innerHTML = data.videos.map(cardHtml).join('');
}
} else {
data.videos.forEach(v => grid.insertAdjacentHTML('beforeend', cardHtml(v)));
}
const loadMoreBtn = document.getElementById('load-more');
if (loadMoreBtn) {
loadMoreBtn.style.display = state.offset + data.videos.length < state.total ? 'block' : 'none';
}
const countEl = document.getElementById('result-count');
if (countEl) countEl.textContent = `${state.total} ${noun}`;
} catch (err) {
if (err.message !== 'Unauthorized') toast('Failed to load videos: ' + err.message);
}
}
function wireGridControls() {
const sortSelect = document.getElementById('sort-select');
if (sortSelect) {
sortSelect.value = state.sort;
sortSelect.addEventListener('change', () => { state.sort = sortSelect.value; state.offset = 0; loadGrid(); });
}
const loadMoreBtn = document.getElementById('load-more');
if (loadMoreBtn) {
loadMoreBtn.addEventListener('click', () => { state.offset += state.limit; loadGrid(); });
}
}
async function renderHome() {
currentRoute = 'home';
const channels = await api('/api/channels').catch(() => []);
const historyItems = await api('/api/history?limit=8').catch(() => []);
const continueWatching = historyItems.filter(h => !h.completed && h.position > 0 && (h.duration || h.watch_duration) > 0 && h.position < (h.duration || h.watch_duration) * 0.95).slice(0, 8);
app.innerHTML = `
${continueWatching.length ? `
<h2 class="section-title">Continue watching</h2>
<div class="continue-strip">
${continueWatching.map(v => {
const dur = v.duration || v.watch_duration || 0;
const p = dur > 0 ? Math.min(1, v.position / dur) : 0;
return `<div class="card continue-card" data-href="#/watch/${v.id}">
<div class="thumb">
<img src="/thumb/${v.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=placeholder>▶</div>'">
<span class="badge">${fmtDur(v.duration)}</span>
<div class="progress"><div class="fill" style="width:${(p * 100).toFixed(1)}%"></div></div>
</div>
<div class="title">${esc(v.title)}</div>
<div class="meta">${fmtDate(v.watched_at)} · ${Math.round(p * 100)}% watched</div>
</div>`;
}).join('')}
</div>` : ''}
<h2 class="section-title">${state.q ? 'Search results' : 'All videos'}</h2>
<div class="toolbar">
<span class="result-count" id="result-count"></span>
<select class="sort" id="sort-select">
<option value="newest">Newest first</option>
<option value="oldest">Oldest first</option>
<option value="views">Most viewed</option>
<option value="recent">Recently watched</option>
<option value="az">Title A–Z</option>
</select>
</div>
<div class="chips" id="channel-chips">
<button class="chip ${!state.channel ? 'active' : ''}" data-channel="">All channels</button>
${channels.map(c => `<button class="chip ${state.channel === c.name ? 'active' : ''}" data-channel="${esc(c.name)}">${esc(c.name)} <span style="opacity:.55;font-weight:500">${c.count}</span></button>`).join('')}
</div>
<div class="grid" id="video-grid"></div>
<div class="empty" id="empty-msg" style="display:none">
<div class="big">🎬</div>
<p>${state.q ? 'No videos match your search.' : 'No videos found. Drop video files into the video folder and click ⟳ to rescan.'}</p>
</div>
<button class="load-more" id="load-more" style="display:none">Load more</button>`;
wireGridControls();
document.getElementById('channel-chips').addEventListener('click', (e) => {
const btn = e.target.closest('.chip');
if (!btn) return;
state.channel = btn.dataset.channel || null;
state.offset = 0;
renderHome();
});
await loadGrid();
}
async function renderChannel(name) {
currentRoute = 'channel';
const channels = await api('/api/channels').catch(() => []);
const channel = channels.find(c => c.name === name);
const stats = await api(`/api/channel/${encodeURIComponent(name)}/stats`).catch(() => null);
searchInput.value = '';
app.innerHTML = `
<div class="toolbar">
<h2 class="section-title" style="margin:0">${esc(name)}</h2>
<select class="sort" id="sort-select">
<option value="newest">Newest first</option>
<option value="oldest">Oldest first</option>
<option value="views">Most viewed</option>
<option value="recent">Recently watched</option>
<option value="az">Title A–Z</option>
</select>
</div>
${stats ? `<div class="channel-stats">
<span class="cs"><b>${stats.videos}</b> videos</span>
<span class="cs"><b>${fmtTime(stats.totalSeconds)}</b> total</span>
<span class="cs"><b>${fmtTime(stats.watchedSeconds)}</b> watched by you</span>
<span class="cs"><b>${stats.completedCount}</b> completed</span>
</div>` : ''}
<div class="grid" id="video-grid"></div>
<div class="empty" id="empty-msg" style="display:none">
<div class="big">📺</div><p>No videos in this channel yet.</p>
</div>
<button class="load-more" id="load-more" style="display:none">Load more</button>`;
state.channel = name;
state.q = '';
state.offset = 0;
wireGridControls();
await loadGrid();
}
async function renderFavorites() {
currentRoute = 'favorites';
searchInput.value = '';
app.innerHTML = `
<h2 class="section-title">Favorites <span class="count" id="result-count"></span></h2>
<div class="grid" id="video-grid"></div>
<div class="empty" id="empty-msg" style="display:none">
<div class="big">★</div><p>No favorites yet. Click the star on any video to add it here.</p>
</div>
<button class="load-more" id="load-more" style="display:none">Load more</button>`;
state.offset = 0;
wireGridControls();
await loadGrid();
}
async function renderHistory() {
currentRoute = 'history';
const items = await api('/api/history?limit=50').catch(() => []);
app.innerHTML = `
<h2 class="section-title">Watch history <span class="count">${items.length} videos</span></h2>
${items.length ? items.map(v => {
const p = v.duration > 0 ? Math.min(1, v.position / v.duration) : 0;
return `<a class="history-row" href="#/watch/${v.id}">
<div class="thumb">
<img src="/thumb/${v.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=placeholder>▶</div>'">
</div>
<div class="info">
<div class="title">${esc(v.title)}</div>
<div class="meta">${esc(v.channel)} · ${fmtDate(v.watched_at)}</div>
<div class="bar"><div class="fill${v.completed ? ' done' : ''}" style="width:${(p * 100).toFixed(1)}%"></div></div>
</div>
<div class="time">${v.completed ? '✓ Watched' : fmtDur(v.position) + ' / ' + fmtDur(v.duration || 0)}</div>
</a>`;
}).join('') : `<div class="empty"><div class="big">🕘</div><p>Nothing watched yet. Play something and it will show up here.</p></div>`}`;
}
async function renderPlaylists() {
currentRoute = 'playlists';
searchInput.value = '';
const playlists = await api('/api/playlists').catch(() => []);
app.innerHTML = `
<h2 class="section-title">Playlists <span class="count">${playlists.length}</span></h2>
<form class="new-playlist-bar" id="new-playlist-form">
<input id="new-playlist-name" type="text" placeholder="New playlist name…" maxlength="80" required>
<button class="btn primary" type="submit">Create</button>
</form>
<div class="grid" id="playlist-grid" style="grid-template-columns:repeat(auto-fill,minmax(240px,1fr))">
${playlists.map(p => `<div class="playlist-card" data-href="#/playlists/${p.id}">
<button class="del-btn" data-delete-playlist="${p.id}" title="Delete playlist">✕</button>
<div class="name">${esc(p.name)}</div>
<div class="meta">${p.count} video${p.count === 1 ? '' : 's'} · ${fmtDate(p.created_at)}</div>
</div>`).join('') || `<div class="empty" style="grid-column:1/-1;padding:44px"><div class="big">📋</div><p>No playlists yet. Create one above, then add videos from the watch page.</p></div>`}
</div>`;
document.getElementById('new-playlist-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('new-playlist-name').value.trim();
if (!name) return;
try {
await api('/api/playlists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) });
toast(`Created "${name}"`);
renderPlaylists();
} catch (err) { toast(err.message); }
});
app.querySelectorAll('[data-delete-playlist]').forEach(btn => btn.addEventListener('click', async (e) => {
e.stopPropagation();
if (!confirm('Delete this playlist? Videos are not deleted.')) return;
try {
await api(`/api/playlists/${btn.dataset.deletePlaylist}`, { method: 'DELETE' });
renderPlaylists();
} catch (err) { toast(err.message); }
}));
}
async function renderPlaylistDetail(id) {
currentRoute = 'playlists';
const data = await api(`/api/playlists/${id}`).catch(() => null);
if (!data) {
app.innerHTML = `<div class="empty"><div class="big">🚫</div><p>Playlist not found.</p></div>`;
return;
}
const { playlist, videos } = data;
app.innerHTML = `
<a href="#/playlists" style="color:var(--muted);text-decoration:none;font-size:13px">← All playlists</a>
<h2 class="section-title" style="margin-top:10px">${esc(playlist.name)} <span class="count">${videos.length} videos</span></h2>
${videos.length ? videos.map((v, i) => `<div class="pl-row" data-id="${v.id}">
<span class="num">${i + 1}</span>
<img src="/thumb/${v.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=ph>▶</div>'">
<div class="body" data-href="#/watch/${v.id}">
<div class="t">${esc(v.title)}</div>
<div class="m">${fmtDur(v.duration)} · ${fmtViews(v.views)}</div>
</div>
<div class="actions">
<button data-move="up" title="Move up" ${i === 0 ? 'disabled' : ''}>↑</button>
<button data-move="down" title="Move down" ${i === videos.length - 1 ? 'disabled' : ''}>↓</button>
<button data-remove title="Remove from playlist">✕</button>
</div>
</div>`).join('') : `<div class="empty"><div class="big">📋</div><p>This playlist is empty. Add videos from the watch page.</p></div>`}`;
const ids = videos.map(v => v.id);
app.querySelectorAll('.pl-row').forEach(row => {
const rowId = parseInt(row.dataset.id, 10);
const upBtn = row.querySelector('[data-move="up"]');
const downBtn = row.querySelector('[data-move="down"]');
const removeBtn = row.querySelector('[data-remove]');
const idx = ids.indexOf(rowId);
const move = (dir) => {
const j = idx + dir;
if (j < 0 || j >= ids.length) return;
[ids[idx], ids[j]] = [ids[j], ids[idx]];
api(`/api/playlists/${id}/reorder`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_ids: ids }) })
.then(() => renderPlaylistDetail(id))
.catch(err => toast(err.message));
};
if (upBtn) upBtn.addEventListener('click', () => move(-1));
if (downBtn) downBtn.addEventListener('click', () => move(1));
if (removeBtn) removeBtn.addEventListener('click', async () => {
try {
await api(`/api/playlists/${id}/items/${rowId}`, { method: 'DELETE' });
renderPlaylistDetail(id);
} catch (err) { toast(err.message); }
});
});
}
async function renderStats() {
currentRoute = 'stats';
searchInput.value = '';
const s = await api('/api/stats').catch(() => null);
if (!s) {
app.innerHTML = `<div class="empty"><div class="big">📊</div><p>Unable to load stats.</p></div>`;
return;
}
const maxSec = Math.max(1, ...s.daily.map(d => d.seconds));
const days = [];
for (let i = 13; i >= 0; i--) {
const d = new Date(Date.now() - i * 86400000);
days.push({ key: d.toISOString().slice(0, 10), label: d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }), seconds: 0 });
}
const byDay = {};
s.daily.forEach(d => { byDay[d.day] = d.seconds; });
days.forEach(d => { d.seconds = byDay[d.key] || 0; });
const maxSecAll = Math.max(1, ...s.topChannels.map(c => c.seconds));
const maxVideosSec = Math.max(1, ...s.topVideos.map(v => v.seconds));
app.innerHTML = `
<h2 class="section-title">Watch stats</h2>
<div class="stats-grid">
<div class="stat-card"><div class="num">${fmtTime(s.totalSeconds)}</div><div class="lbl">Total watch time</div></div>
<div class="stat-card"><div class="num">${fmtTime(s.thisMonthSeconds)}</div><div class="lbl">This month</div></div>
<div class="stat-card"><div class="num">${s.startedCount}</div><div class="lbl">Videos started</div></div>
<div class="stat-card"><div class="num">${s.completedCount}</div><div class="lbl">Completed</div></div>
</div>
<div class="chart-wrap">
<h3>Last 14 days</h3>
<div class="chart-bars">
${days.map(d => `<div class="chart-bar" title="${d.key}: ${fmtTime(d.seconds)}">
<div class="fill" style="height:${Math.max(3, Math.round((d.seconds / maxSec) * 105))}px"></div>
<div class="day">${d.label}</div>
</div>`).join('')}
</div>
</div>
<div class="stats-cols">
<div class="stats-list">
<h3>Top channels</h3>
${s.topChannels.length ? s.topChannels.map((c, i) => `<div class="stats-item">
<span class="rank">${i + 1}</span>
<div class="body">
<div class="t">${esc(c.channel)}</div>
<div class="m">${c.videos} videos</div>
<div class="bar"><div class="fill" style="width:${((c.seconds / maxSecAll) * 100).toFixed(1)}%"></div></div>
</div>
<span class="secs">${fmtTime(c.seconds)}</span>
</div>`).join('') : '<p style="color:var(--muted);font-size:13px">No watch time yet.</p>'}
</div>
<div class="stats-list">
<h3>Top videos</h3>
${s.topVideos.length ? s.topVideos.map((v, i) => `<a class="stats-item" href="#/watch/${v.id}" style="text-decoration:none;color:inherit">
<span class="rank">${i + 1}</span>
<div class="body">
<div class="t">${esc(v.title)}</div>
<div class="m">${esc(v.channel)}</div>
<div class="bar"><div class="fill" style="width:${((v.seconds / maxVideosSec) * 100).toFixed(1)}%"></div></div>
</div>
<span class="secs">${fmtTime(v.seconds)}</span>
</a>`).join('') : '<p style="color:var(--muted);font-size:13px">No watch time yet.</p>'}
</div>
</div>`;
}
let playerCleanup = null;
async function renderWatch(id) {
currentRoute = 'watch';
const shouldAutoplay = autoplayIntent;
autoplayIntent = false;
const data = await api(`/api/video/${id}`).catch(() => null);
if (!data) {
app.innerHTML = `<div class="empty"><div class="big">🚫</div><p>Video not found or no longer in the library.</p></div>`;
return;
}
const v = data.video;
const history = data.history;
const fav = !!data.favorite;
app.innerHTML = `
<a href="#/" style="color:var(--muted);text-decoration:none;font-size:13px">← Back to library</a>
<div class="watch-layout">
<div>
<div class="player-wrap" id="player-wrap">
<video id="player" controls preload="metadata" src="/video/${v.id}"></video>
</div>
<h1 class="watch-title">${esc(v.title)}</h1>
<div class="watch-meta">
<a href="#/channel/${encodeURIComponent(v.channel)}">${esc(v.channel)}</a>
<span>${fmtViews(v.views)}</span>
<span>${fmtDur(v.duration)}</span>
</div>
<div class="watch-actions">
<button class="btn primary" id="fav-btn">${fav ? '★ Favorited' : '☆ Add to favorites'}</button>
<div class="seg" id="autoplay-seg" title="Autoplay next video">
<button data-mode="off" class="${autoplayMode === 'off' ? 'active' : ''}">Off</button>
<button data-mode="channel" class="${autoplayMode === 'channel' ? 'active' : ''}">Channel</button>
<button data-mode="random" class="${autoplayMode === 'random' ? 'active' : ''}">Random</button>
</div>
<button class="btn ghost" id="playlist-btn">+ Playlist</button>
</div>
<div class="add-playlist-panel" id="playlist-panel" style="display:none"></div>
</div>
<aside class="related">
<h3>More from ${esc(v.channel)}</h3>
<div id="related-list"></div>
</aside>
</div>`;
try { api('/api/view', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id }) }); } catch {}
const player = document.getElementById('player');
const wrap = document.getElementById('player-wrap');
let resumeAt = 0;
if (history && history.position > 5 && !history.completed && v.duration > 0 && history.position < v.duration * 0.95) {
resumeAt = history.position;
}
let lastSave = -1;
const saveProgress = (force = false) => {
if (!player.duration || !isFinite(player.duration)) return;
const pos = player.currentTime;
if (!force && Math.abs(pos - lastSave) < 1 && lastSave >= 0) return;
lastSave = pos;
api('/api/progress', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id, position: pos, duration: player.duration }) }).catch(() => {});
};
const onLoaded = () => {
if (resumeAt > 0 && !player.dataset.resumed) {
player.currentTime = resumeAt;
player.dataset.resumed = '1';
}
if (shouldAutoplay) {
player.play().catch(() => {});
}
};
player.addEventListener('loadedmetadata', onLoaded);
const interval = setInterval(saveProgress, 10000);
const onPause = () => saveProgress(true);
const startNext = async () => {
if (autoplayMode === 'off') return;
try {
const r = await api(`/api/videos/${v.id}/next?mode=${autoplayMode}`);
if (!r.video) return;
autoplayIntent = true;
location.hash = `#/watch/${r.video.id}`;
} catch {}
};
const onEnded = () => {
saveProgress(true);
api('/api/progress', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id, position: player.duration, duration: player.duration }) }).catch(() => {});
startNext();
};
const onError = () => {
wrap.innerHTML = '<div class="player-error"><p>⚠ Unable to play this video. The file may be missing or unsupported.</p></div>';
};
player.addEventListener('pause', onPause);
player.addEventListener('ended', onEnded);
player.addEventListener('error', onError);
document.getElementById('autoplay-seg').addEventListener('click', (e) => {
const btn = e.target.closest('button[data-mode]');
if (!btn) return;
setAutoplayMode(btn.dataset.mode);
document.querySelectorAll('#autoplay-seg button').forEach(b => b.classList.toggle('active', b === btn));
});
const favBtn = document.getElementById('fav-btn');
favBtn.addEventListener('click', async () => {
try {
const r = await api('/api/favorite', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id }) });
favBtn.textContent = r.favorite ? '★ Favorited' : '☆ Add to favorites';
toast(r.favorite ? 'Added to favorites' : 'Removed from favorites');
} catch (err) { if (err.message !== 'Unauthorized') toast('Error: ' + err.message); }
});
const panel = document.getElementById('playlist-panel');
const playlistBtn = document.getElementById('playlist-btn');
playlistBtn.addEventListener('click', async () => {
if (panel.style.display === 'none') {
panel.style.display = 'block';
await renderPlaylistPanel(panel, v.id);
} else {
panel.style.display = 'none';
}
});
playerCleanup = () => {
clearInterval(interval);
player.removeEventListener('loadedmetadata', onLoaded);
player.removeEventListener('pause', onPause);
player.removeEventListener('ended', onEnded);
player.removeEventListener('error', onError);
};
const related = await api(`/api/videos?channel=${encodeURIComponent(v.channel)}&sort=newest&limit=6`).catch(() => ({ videos: [] }));
const list = document.getElementById('related-list');
if (list) {
const others = related.videos.filter(x => x.id !== v.id).slice(0, 6);
list.innerHTML = others.length ? others.map(x => `
<a class="related-item" href="#/watch/${x.id}">
<img src="/thumb/${x.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=ph>▶</div>'">
<div><div class="t">${esc(x.title)}</div><div class="m">${fmtDur(x.duration)} · ${fmtViews(x.views)}</div></div>
</a>`).join('') : '<p style="color:var(--muted);font-size:13px">No other videos in this channel.</p>';
}
}
async function renderPlaylistPanel(panel, videoId) {
panel.innerHTML = '<div style="color:var(--muted);font-size:13px;padding:4px 2px">Loading playlists…</div>';
const playlists = await api('/api/playlists').catch(() => []);
const details = await Promise.all(playlists.map(async p => {
try {
const d = await api(`/api/playlists/${p.id}`);
return { ...p, videos: d.videos };
} catch { return { ...p, videos: [] }; }
}));
panel.innerHTML = `
<div class="pl-list">
${details.length ? details.map(p => `<div class="pl-item" data-playlist-id="${p.id}">
<span>${esc(p.name)} <span style="opacity:.55;font-weight:400">(${p.videos.length})</span></span>
<span class="check">${p.videos.some(x => x.id === videoId) ? '✓ In playlist' : ''}</span>
</div>`).join('') : '<p style="color:var(--muted);font-size:13px;padding:2px">No playlists yet — create one below.</p>'}
</div>
<form class="new-pl" id="panel-new-playlist">
<input type="text" id="panel-new-name" placeholder="New playlist name…" maxlength="80" required>
<button type="submit">Create</button>
</form>`;
panel.querySelectorAll('.pl-item').forEach(item => {
item.addEventListener('click', async () => {
const pid = parseInt(item.dataset.playlistId, 10);
const isMember = item.querySelector('.check').textContent.trim() !== '';
try {
if (isMember) {
await api(`/api/playlists/${pid}/items/${videoId}`, { method: 'DELETE' });
} else {
await api(`/api/playlists/${pid}/items`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: videoId }) });
}
await renderPlaylistPanel(panel, videoId);
} catch (err) { toast(err.message); }
});
});
panel.querySelector('#panel-new-playlist').addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('panel-new-name').value.trim();
if (!name) return;
try {
const r = await api('/api/playlists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) });
await api(`/api/playlists/${r.id}/items`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: videoId }) });
await renderPlaylistPanel(panel, videoId);
} catch (err) { toast(err.message); }
});
}
async function render() {
const hash = location.hash.slice(2);
if (playerCleanup) { playerCleanup(); playerCleanup = null; }
const user = await getMe();
if (!user) { showLoginScreen(); return; }
showApp(user);
document.querySelectorAll('nav a[data-nav]').forEach(a => a.classList.toggle('active',
(hash === '' || hash === '/') && a.dataset.nav === 'home' ||
hash.startsWith('/playlists') && a.dataset.nav === 'playlists' ||
hash.startsWith('/favorites') && a.dataset.nav === 'favorites' ||
hash.startsWith('/history') && a.dataset.nav === 'history' ||
hash.startsWith('/stats') && a.dataset.nav === 'stats'));
const parts = hash.split('/').filter(Boolean);
if (parts[0] === 'channel' && parts[1]) {
await renderChannel(decodeURIComponent(parts.slice(1).join('/')));
} else if (parts[0] === 'watch' && parts[1]) {
await renderWatch(parseInt(parts[1], 10));
} else if (parts[0] === 'playlists' && parts[1]) {
await renderPlaylistDetail(parseInt(parts[1], 10));
} else if (parts[0] === 'playlists') {
await renderPlaylists();
} else if (parts[0] === 'favorites') {
state.q = ''; searchInput.value = '';
await renderFavorites();
} else if (parts[0] === 'history') {
await renderHistory();
} else if (parts[0] === 'stats') {
await renderStats();
} else {
currentRoute = 'home';
state.channel = null;
await renderHome();
}
}
app.addEventListener('click', (e) => {
const favBtn = e.target.closest('.fav-btn');
if (favBtn) {
e.preventDefault();
e.stopPropagation();
toggleFavoriteButton(favBtn);
return;
}
const link = e.target.closest('[data-href]');
if (link) {
e.preventDefault();
location.hash = link.dataset.href;
}
});
async function toggleFavoriteButton(btn) {
const id = parseInt(btn.dataset.videoId, 10);
try {
const r = await api('/api/favorite', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: id }) });
btn.classList.toggle('off', !r.favorite);
btn.textContent = r.favorite ? '★' : '☆';
toast(r.favorite ? 'Added to favorites' : 'Removed from favorites');
} catch (err) { if (err.message !== 'Unauthorized') toast('Error: ' + err.message); }
}
let searchTimer = null;
searchInput.addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
state.q = searchInput.value.trim();
state.offset = 0;
if (location.hash !== '#/') {
location.hash = '#/';
} else {
renderHome();
}
}, 250);
});
document.getElementById('rescan-btn').addEventListener('click', async () => {
const btn = document.getElementById('rescan-btn');
btn.disabled = true; btn.textContent = '…';
try {
const r = await api('/api/rescan', { method: 'POST' });
toast(`Rescan done — ${r.added} added, ${r.updated} updated, ${r.removed} removed`);
render();
} catch (err) { if (err.message !== 'Unauthorized') toast('Rescan failed: ' + err.message); }
finally { btn.disabled = false; btn.textContent = '⟳'; }
});
window.addEventListener('hashchange', render);
render();
+40
View File
@@ -0,0 +1,40 @@
const { execFileSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const ROOT = path.join(__dirname, '..', 'demo-videos');
const CHANNELS = [
{ name: 'Tech Reviews', videos: ['Best Laptops of 2026', 'Phone Camera Comparison', 'Mechanical Keyboards Deep Dive', 'SSD vs HDD Speed Test'] },
{ name: 'Cooking', videos: ['Homemade Pasta Night', 'Sourdough Basics', 'Street Food Tour', 'Weeknight Dinner Ideas'] },
{ name: 'Travel Vlogs', videos: ['Lisbon in 3 Days', 'Mountain Cabin Adventure', 'City Street Food Hunt', 'Road Trip Highlights'] },
{ name: 'Music Sessions', videos: ['Acoustic Cover Practice', 'Studio Session Recap', 'Live Performance Clip'] },
{ name: 'Science Explained', videos: ['How Black Holes Form', 'The Human Brain, Visualized', 'Space Exploration Timeline', 'Quantum Computing Basics'] },
{ name: 'Fitness', videos: ['10 Minute Full Body Routine', 'Morning Stretching Flow', 'Strength Training Guide'] },
];
const COLORS = ['0x2b6cb0', '0x2f855a', '0x805ad5', '0xc05621', '0x0e7490', '0xb83280'];
let total = 0;
for (const ch of CHANNELS) {
const dir = path.join(ROOT, ch.name);
fs.mkdirSync(dir, { recursive: true });
ch.videos.forEach((title, i) => {
const file = path.join(dir, `${i + 1}. ${title}.mp4`);
if (fs.existsSync(file)) return;
const dur = 6 + ((i * 3 + ch.name.length) % 10);
const color = COLORS[(total + i) % COLORS.length];
const args = [
'-y',
'-f', 'lavfi', '-i', `testsrc2=size=640x360:rate=24:duration=${dur}`,
'-f', 'lavfi', '-i', `sine=frequency=${220 + i * 40}:duration=${dur}`,
'-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '30',
'-c:a', 'aac', '-b:a', '96k',
'-pix_fmt', 'yuv420p',
file,
];
execFileSync('ffmpeg', args, { stdio: ['ignore', 'ignore', 'pipe'] });
// overlay channel name via drawtext if available (best effort)
total++;
});
}
console.log(`Generated ${total} demo videos under ${ROOT}`);
+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 };