8 Commits

Author SHA1 Message Date
13869c577b wip
Some checks failed
CI / Maven unit tests (push) Failing after 12s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped
2026-09-20 20:37:56 +01:00
bd3d99e801 fix(segment-concat): out-of-bounds exception during media concat
All checks were successful
CI / Maven unit tests (push) Successful in 1m4s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped
Caused by the duration exceeding 1, which caused CommandRunner to throw.
2026-09-16 20:59:57 +01:00
7dacb7a53a feat(frontend): make markers list vertical in stream page (#46)
All checks were successful
CI / Maven unit tests (push) Successful in 13s
CI / Build and push images (push) Successful in 44s
CI / Deploy to server (push) Successful in 9s
Resolves #38

Reviewed-on: #46
2026-09-16 20:11:12 +01:00
d81202f905 fix(streaming): hitches in VoDs & Clips resulting from ffmpeg concatenation (#44)
All checks were successful
CI / Maven unit tests (push) Successful in 14s
CI / Build and push images (push) Successful in 2m8s
CI / Deploy to server (push) Successful in 17s
- Resolves #43

Reviewed-on: #44
2026-09-16 19:49:04 +01:00
9758bb296b fix(frontend): logout state not shown after JWT expires (#40)
All checks were successful
CI / Maven unit tests (push) Successful in 14s
CI / Build and push images (push) Successful in 57s
CI / Deploy to server (push) Successful in 8s
Reviewed-on: #40
2026-09-06 23:26:07 +01:00
6fa02a34a3 feat(frontend): swap dark-mode brown colours for a black palette (#39)
All checks were successful
CI / Maven unit tests (push) Successful in 13s
CI / Build and push images (push) Successful in 58s
CI / Deploy to server (push) Successful in 13s
Reviewed-on: #39
2026-09-06 19:59:13 +01:00
ccf56f767f chore: remove default vite readme
All checks were successful
CI / Maven unit tests (push) Successful in 18s
CI / Build and push images (push) Successful in 50s
CI / Deploy to server (push) Successful in 18s
2026-09-05 11:11:15 +01:00
7f58bad245 feat(frontend): add dark mode option (#34)
All checks were successful
CI / Maven unit tests (push) Successful in 13s
CI / Build and push images (push) Successful in 48s
CI / Deploy to server (push) Successful in 19s
Resolves #32

Reviewed-on: #34
2026-08-30 17:48:59 +01:00
37 changed files with 705 additions and 501 deletions

View File

@@ -20,11 +20,12 @@ services:
context: ./nginx
dockerfile: Dockerfile
container_name: vod_rtmp
network_mode: host
env_file:
- .env
extra_hosts:
- "host.docker.internal:host-gateway"
environment:
- WEB_SERVER_URL=http://localhost:8080
- WEB_SERVER_URL=http://host.docker.internal:8080
ports:
- "1935:1935"
volumes:

View File

@@ -1,54 +0,0 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default tseslint.config({
extends: [
// Remove ...tseslint.configs.recommended and replace with this
...tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
...tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
...tseslint.configs.stylisticTypeChecked,
],
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
},
})
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default tseslint.config({
plugins: {
// Add the react-x and react-dom plugins
'react-x': reactX,
'react-dom': reactDom,
},
rules: {
// other rules...
// Enable its recommended typescript rules
...reactX.configs['recommended-typescript'].rules,
...reactDom.configs.recommended.rules,
},
})
```

View File

@@ -9,6 +9,20 @@
<link href="https://fonts.googleapis.com/css2?family=Newsreader:wght@100;200;300;400;500;600;700&family=IBM+Plex+Sans:wght@100;200;300;400;500;600;700&family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script>
// Apply the stored theme before first paint so a dark session never
// flashes light. Mirrors the logic in src/theme/ThemeProvider.tsx.
(function () {
try {
var stored = localStorage.getItem("theme");
var dark = stored === "dark" ||
(stored !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.dataset.theme = dark ? "dark" : "light";
} catch (e) {
document.documentElement.dataset.theme = "light";
}
})();
</script>
<script src="/env-config.js"></script>
<title>The VoD System</title>
</head>

View File

@@ -18,6 +18,8 @@ import { GoogleOAuthProvider } from '@react-oauth/google';
import {config} from "./config.ts";
import NotFound from "./pages/NotFound.tsx";
import AuthProvider from "./auth/AuthProvider.tsx";
import ThemeProvider from "./theme/ThemeProvider.tsx";
import RequireAuth from "./auth/RequireAuth.tsx";
function App() {
@@ -27,26 +29,32 @@ function App() {
return (
<GoogleOAuthProvider clientId={config.googleClientId}>
<AuthProvider>
<Router>
<Routes>
<Route element={<MainLayout />}>
<Route path="/" element={<Home />} />
<Route path="/create" element={<ClipUpload />} />
<Route path="/create/:id" element={<ClipEdit />} />
<Route path="/my-clips" element={<MyClips />} />
<Route path="/my-vods" element={<MyVods />} />
<Route path="/video/:id" element={<MediaPlayer noun="Clip" getMediaUrl={getClipMediaUrl} fetchDetails={getClipById} />} />
<Route path="/vod/:id" element={<MediaPlayer noun="VoD" getMediaUrl={getVodMediaUrl} fetchDetails={getVodById} />} />
<Route path="/clips/:id/edit" element={<EditClip />} />
<Route path="/vods/:id/edit" element={<EditVod />} />
<Route path="/profile" element={<Profile />} />
<Route path="/stream" element={<StreamControl />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</Router>
</AuthProvider>
<ThemeProvider>
<AuthProvider>
<Router>
<Routes>
<Route element={<MainLayout />}>
<Route path="/" element={<Home />} />
<Route path="/create" element={<ClipUpload />} />
<Route path="/create/:id" element={<ClipEdit />} />
<Route element={<RequireAuth />}>
<Route path="/my-clips" element={<MyClips />} />
<Route path="/my-vods" element={<MyVods />} />
<Route path="/video/:id" element={<MediaPlayer noun="Clip" getMediaUrl={getClipMediaUrl} fetchDetails={getClipById} />} />
<Route path="/vod/:id" element={<MediaPlayer noun="VoD" getMediaUrl={getVodMediaUrl} fetchDetails={getVodById} />} />
<Route path="/clips/:id/edit" element={<EditClip />} />
<Route path="/vods/:id/edit" element={<EditVod />} />
<Route path="/profile" element={<Profile />} />
<Route path="/stream" element={<StreamControl />} />
</Route>
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</Router>
</AuthProvider>
</ThemeProvider>
</ GoogleOAuthProvider>
);
}

View File

@@ -3,6 +3,7 @@ import type { ReactNode } from "react";
import type { User } from "../utils/types.ts";
import { login as apiLogin, logout as apiLogout, getUser } from "../utils/api/users.ts";
import { AuthContext } from "./AuthContext.ts";
import {registerUnauthorizedHandler} from "../utils/api/client.ts";
/**
* Owns the single source of truth for the authenticated user. Everything that
@@ -33,7 +34,11 @@ const AuthProvider = ({ children }: { children: ReactNode }) => {
const logout = useCallback(async () => {
await apiLogout();
setUser(null);
await refresh();
}, [refresh]);
useEffect(() => {
registerUnauthorizedHandler(() => setUser(null));
}, []);
return (

View File

@@ -0,0 +1,14 @@
import { Navigate, Outlet, useLocation } from "react-router-dom";
import { useAuth } from "./useAuth";
const RequireAuth = () => {
const { user, loading } = useAuth();
const location = useLocation();
if (loading) return null;
if (!user) return <Navigate to="/" replace state={{ from: location }} />;
return <Outlet />;
};
export default RequireAuth;

View File

@@ -0,0 +1,18 @@
import type { ElementType } from "react";
type Props = {
icon: ElementType;
title: string;
accent?: "primary" | "accent";
};
const CardHeader = ({ icon: Icon, title, accent = "primary" }: Props) => (
<div className="flex items-center gap-2.5">
<div className={`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 ${accent === "primary" ? "bg-terracotta/10" : "bg-olive/10"}`}>
<Icon size={16} className={accent === "primary" ? "text-terracotta" : "text-olive"} />
</div>
<h2 className="text-xl font-heading text-text-primary">{title}</h2>
</div>
);
export default CardHeader;

View File

@@ -1,4 +1,4 @@
import { Menu, X } from 'lucide-react';
import { Menu, X, Sun, Moon } from 'lucide-react';
import { Dropdown, DropdownItem } from "./Dropdown.tsx";
import { GoogleLogin } from '@react-oauth/google';
@@ -8,6 +8,7 @@ import MenuButton from "./buttons/MenuButton.tsx";
import clsx from "clsx";
import {useNavigate} from "react-router-dom";
import { useAuth } from "../auth/useAuth.ts";
import { useTheme } from "../theme/useTheme.ts";
type props = {
@@ -25,6 +26,7 @@ const Topbar = ({
const navigate = useNavigate();
const { user, login, logout } = useAuth();
const { theme, toggleTheme } = useTheme();
const handleLogin = (response: CredentialResponse) => {
if (!response.credential) {
@@ -38,6 +40,8 @@ const Topbar = ({
});
}
const themeLabel = theme === "dark" ? "Switch to light mode" : "Switch to dark mode";
const handleLogout = () => {
logout()
.then(() => navigate("/"))
@@ -52,7 +56,16 @@ const Topbar = ({
{sidebarToggled ? <Menu size={24}/> : <X size={24}/>}
</MenuButton>
{ user ? (
<div className="flex items-center gap-1">
<MenuButton
onClick={toggleTheme}
title={themeLabel}
aria-label={themeLabel}
>
{theme === "dark" ? <Sun size={20}/> : <Moon size={20}/>}
</MenuButton>
{ user ? (
<div className={"hover:bg-hover rounded-lg p-0.5"}>
<img
className={"w-8 h-8 rounded-full inline-block"}
@@ -78,13 +91,15 @@ const Topbar = ({
className={"text-error font-medium"} />
</Dropdown>
</div>
) :
(
) :
(
<GoogleLogin
shape={"pill"}
theme={theme === "dark" ? "filled_black" : "outline"}
useOneTap={false}
onSuccess={(credentialResponse) => handleLogin(credentialResponse)} />
)}
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,173 @@
import { useState } from "react";
import { Bookmark, Plus, X } from "lucide-react";
import clsx from "clsx";
import Box from "../Box.tsx";
import CardHeader from "../CardHeader.tsx";
import PrimaryButton from "../buttons/PrimaryButton.tsx";
import type { Marker } from "../../utils/types.ts";
import { formatLocalTime } from "../../utils/utils.ts";
const inputClass = "border border-hairline bg-fields rounded-md w-full p-2 text-sm focus:outline-none focus:ring-2 focus:ring-muted transition-colors";
type RailSegment = "none" | "plain" | "lit";
const railClass = (segment: RailSegment) => clsx(
"w-px",
segment === "lit" && "bg-terracotta",
segment === "plain" && "bg-inactive-strong/60",
segment === "none" && "bg-transparent"
);
type MarkerRowProps = {
marker: Marker;
role: "start" | "end" | "between" | null;
/** Rail segments above and below the dot — "lit" inside the chosen section. */
railAbove: RailSegment;
railBelow: RailSegment;
onSelect: () => void;
onDelete: () => void;
};
const MarkerRow = ({ marker, role, railAbove, railBelow, onSelect, onDelete }: MarkerRowProps) => (
<li className="group relative flex gap-3">
{/* Timeline rail: a dot per marker, with the segment between the chosen
start and end lit so the selected section reads as one run. */}
<div className="flex w-2.5 flex-col items-center flex-shrink-0">
<span className={clsx("h-3.5 flex-shrink-0", railClass(railAbove))} />
<span className={clsx(
"h-2.5 w-2.5 rounded-full border-2 flex-shrink-0 transition-colors duration-150",
role === "start" && "border-terracotta bg-terracotta",
role === "end" && "border-olive bg-olive",
role === "between" && "border-terracotta bg-card",
role === null && "border-inactive-strong bg-card"
)} />
<span className={clsx("flex-1", railClass(railBelow))} />
</div>
{/* The rail spans the full row, so the breathing room goes on the button —
the line stays continuous while neighbouring rings no longer touch. */}
<button
onClick={onSelect}
className={clsx(
"min-w-0 flex-1 rounded-md my-0.5 py-2 pl-2.5 pr-7 text-left transition-colors duration-150",
role === "start" && "bg-selected ring-1 ring-terracotta",
role === "end" && "bg-selected ring-1 ring-olive",
(role === "between" || role === null) && "hover:bg-hover"
)}
>
<p className="truncate text-sm font-medium text-text-strong">{marker.message}</p>
<p className="font-data text-[11px] text-muted tabular-nums">
{formatLocalTime(marker.timestamp)}
{role === "start" && <span className="font-medium text-terracotta"> · start</span>}
{role === "end" && <span className="font-medium text-olive"> · end</span>}
</p>
</button>
<button
onClick={onDelete}
title="Delete marker"
aria-label={`Delete marker ${marker.message}`}
className="absolute right-1 top-2.5 flex h-5 w-5 items-center justify-center rounded-md text-muted opacity-0 transition duration-150 hover:bg-hover hover:text-error focus-visible:opacity-100 group-hover:opacity-100"
>
<X size={12} />
</button>
</li>
);
type Props = {
/** Newest first — the list renders them in the order given. */
markers: Marker[];
startMarkerId: string;
endMarkerId: string;
error: string | null;
/** Resolves true once the marker exists, so the input only clears on success. */
onAdd: (message: string) => Promise<boolean>;
onSelect: (id: number) => void;
onDelete: (id: number) => void;
className?: string;
};
const MarkerList = ({ markers, startMarkerId, endMarkerId, error, onAdd, onSelect, onDelete, className }: Props) => {
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
const handleAdd = async () => {
if (!message.trim() || busy) return;
setBusy(true);
if (await onAdd(message.trim())) setMessage("");
setBusy(false);
};
// Either of the two may have been picked first, so the lit run is bounded by
// whichever indices come first/last rather than by start/end.
const startIndex = markers.findIndex((m) => String(m.id) === startMarkerId);
const endIndex = markers.findIndex((m) => String(m.id) === endMarkerId);
const hasRange = startIndex !== -1 && endIndex !== -1;
const rangeFrom = hasRange ? Math.min(startIndex, endIndex) : -1;
const rangeTo = hasRange ? Math.max(startIndex, endIndex) : -1;
// The rail segment sitting between marker `i` and the one after it.
const railSegment = (i: number): RailSegment => {
if (i < 0 || i >= markers.length - 1) return "none";
return hasRange && i >= rangeFrom && i < rangeTo ? "lit" : "plain";
};
return (
<Box className={clsx("p-5 flex flex-col gap-4", className)}>
<div className="flex items-center justify-between gap-3">
<CardHeader icon={Bookmark} title="Markers" accent="accent" />
{markers.length > 0 && (
<span className="font-data text-[11px] text-muted tabular-nums">{markers.length}</span>
)}
</div>
<div className="flex flex-col gap-2">
<div className="flex gap-2">
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleAdd()}
placeholder="What just happened?"
className={inputClass}
/>
<PrimaryButton
onClick={handleAdd}
disabled={busy || !message.trim()}
className="flex items-center gap-1.5 px-3 whitespace-nowrap"
>
<Plus size={15} />
Add
</PrimaryButton>
</div>
{error && <p className="text-sm text-error">{error}</p>}
</div>
{markers.length === 0 ? (
<p className="text-sm text-muted">
Nothing marked yet. Markers stack up here, newest first — pick two to save the section between them.
</p>
) : (
/* py-0.5 keeps the scroll container from clipping the selection
ring on the first and last rows. */
<ul className="-mr-1 flex max-h-[26rem] flex-col overflow-y-auto py-0.5 pr-1">
{markers.map((m, i) => (
<MarkerRow
key={m.id}
marker={m}
role={String(m.id) === startMarkerId ? "start"
: String(m.id) === endMarkerId ? "end"
: hasRange && i > rangeFrom && i < rangeTo ? "between"
: null}
railAbove={railSegment(i - 1)}
railBelow={railSegment(i)}
onSelect={() => onSelect(m.id)}
onDelete={() => onDelete(m.id)}
/>
))}
</ul>
)}
</Box>
);
};
export default MarkerList;

View File

@@ -65,7 +65,7 @@ const VideoCard = ({ id, title, duration, createdAt, onEdit, onDelete, className
className="w-full aspect-video object-cover group-hover:scale-105 transition-transform duration-200"
/>
<span className="absolute top-1.5 left-1.5 bg-text-primary/75 text-on-dark px-1.5 py-0.5 rounded text-xs font-data pointer-events-none">
<span className="absolute top-1.5 left-1.5 bg-media-backdrop/75 text-on-dark px-1.5 py-0.5 rounded text-xs font-data pointer-events-none">
{formatTime(duration)}
</span>
@@ -77,7 +77,7 @@ const VideoCard = ({ id, title, duration, createdAt, onEdit, onDelete, className
>
<button
onClick={(e) => stopAndRun(e, () => { setMenuOpen(v => !v); setConfirmDelete(false); })}
className="bg-text-primary/75 hover:bg-text-primary/90 text-on-dark rounded p-0.5 transition-colors"
className="bg-media-backdrop/75 hover:bg-media-backdrop/90 text-on-dark rounded p-0.5 transition-colors"
>
<MoreVertical size={14} />
</button>

View File

@@ -1,5 +1,10 @@
@import "tailwindcss";
/* Drive the `dark:` variant off the same data-theme attribute the toggle sets,
instead of Tailwind's default prefers-color-scheme. Without this a stray
`dark:` utility would disagree with an explicit light/dark choice. */
@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));
@theme {
/* ── Fonts ───────────────────────────────────────────────────────────── */
--font-body: "IBM Plex Sans", system-ui, sans-serif;
@@ -12,6 +17,10 @@
--color-fields: #F4F0E8;
--color-dropzone: #F9F6EF;
/* Letterbox behind video. Dark in both themes — it is a cinema surface,
not an ink colour — so `text-on-dark` always reads on top of it. */
--color-media-backdrop: #2B2620;
/* ── Ink ─────────────────────────────────────────────────────────────── */
--color-text-primary: #2B2620;
--color-text-strong: #35302A;
@@ -44,6 +53,55 @@
--color-inactive-strong: #C4BAA9;
}
/* Dark mode. Only token values change here: every component already styles
itself with the semantic utilities above, so the whole UI follows from this
one block. `--color-on-dark` is deliberately absent — it is the ink on the
media backdrop, which stays dark in both themes. */
:root[data-theme="dark"] {
color-scheme: dark;
/* ── Surfaces ── near-black canvas, neutral cards lifting off it ─────── */
--color-background: #0E0E10;
--color-sidebar: #09090B;
--color-card: #17171A;
--color-fields: #121215;
--color-dropzone: #141417;
--color-media-backdrop: #000000;
/* ── Ink ─────────────────────────────────────────────────────────────── */
--color-text-primary: #F4F4F5;
--color-text-strong: #E3E3E7;
--color-text-body: #BFBFC6;
--color-text-secondary: #94949D;
--color-muted: #76767F;
--color-faint-mono: #6A6A73;
/* ── Accents ── brightened to carry on a dark canvas, so hover now lifts
rather than deepens ─────────────────────────────────────────────────── */
--color-terracotta: #E07A4C;
--color-terracotta-hover: #F08F62;
--color-terracotta-light: #F0A177;
--color-terracotta-disabled: #5E463A;
--color-olive: #A3B678;
/* ── Status ──────────────────────────────────────────────────────────── */
--color-live: #F2604A;
--color-error: #F2604A;
/* ── Ink on accent surfaces ── the accents are light here, so the ink that
sits on them flips dark ─────────────────────────────────────────────── */
--color-on-accent: #17100B;
/* ── Lines, chips, placeholders ──────────────────────────────────────── */
--color-hairline: #232327;
--color-hover: #26262B;
--color-selected: #2A1F18;
--color-ring: #33333A;
--color-inactive: #2C2C32;
--color-inactive-strong: #55555E;
}
:root {
font-family: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
line-height: 1.5;
@@ -52,6 +110,7 @@
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color-scheme: light;
}
body {
@@ -66,6 +125,16 @@ body {
color: var(--color-text-primary);
}
/* Google Identity Services renders its sign-in button in a cross-origin iframe
whose document is light-scheme with a transparent background. Left to inherit
our `color-scheme: dark`, Chrome cannot honour dark there and paints an opaque
white canvas behind it instead — framing the pill in a white box on every dark
page. Pinning the iframe back to light keeps it transparent; the button's own
colours come from the `theme` prop in Topbar.tsx. */
iframe[src*="accounts.google.com/gsi/"] {
color-scheme: light;
}
/* Clip trim slider (react-range-slider-input). Its own stylesheet ships blue
defaults; the #id beats those class selectors regardless of import order. */
#range-slider {

View File

@@ -6,13 +6,10 @@ import ClipRangeSlider from "./../components/video/ClipRangeSlider";
import ConfigBox from "../components/video/ConfigBox.tsx";
import ExportWidget from "../components/video/ExportWidget.tsx";
import { compress } from "../utils/api/media"
import { getJob } from "../utils/api/jobs"
import { getJob, downloadJob } from "../utils/api/jobs"
import type { VideoMetadata } from "../utils/types.ts";
import Box from "../components/Box.tsx";
import MetadataBox from "../components/video/MetadataBox.tsx";
import {config} from "../config.ts";
const API_URL = config.apiUrl;
const ClipEdit = () => {
const location = useLocation();
@@ -111,14 +108,14 @@ const ClipEdit = () => {
const handleDownload = async () => {
if (!uploadedId) return;
const response = await fetch(API_URL + `/api/v1/jobs/${uploadedId}/download`, { credentials: 'include' });
if (!response.ok) {
console.error('Download failed');
let blob: Blob;
try {
blob = await downloadJob(uploadedId);
} catch (err) {
console.error('Download failed', err);
return;
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -135,7 +132,7 @@ const ClipEdit = () => {
<video
ref={videoRef}
src={videoUrl}
className={"w-full rounded-lg shadow-sm bg-text-primary"}
className={"w-full rounded-lg shadow-sm bg-media-backdrop"}
onLoadedMetadata={handleVideoMetadataLoaded}
/>

View File

@@ -233,7 +233,7 @@ const MediaPlayer = ({ noun, getMediaUrl, fetchDetails }: MediaPlayerProps) => {
{/* Player */}
<div
ref={containerRef}
className="relative bg-text-primary rounded-xl overflow-hidden flex-1 min-h-0 select-none"
className="relative bg-media-backdrop rounded-xl overflow-hidden flex-1 min-h-0 select-none"
onMouseMove={showControls}
onMouseLeave={() => isPlaying && setControlsVisible(false)}
onClick={togglePlay}

View File

@@ -1,7 +1,9 @@
import { useEffect, useState } from "react";
import { Radio, Check, Bookmark, Scissors, Film, Activity, Loader2, X } from "lucide-react";
import { Radio, Check, Scissors, Film, Activity, Loader2, X } from "lucide-react";
import clsx from "clsx";
import Box from "../components/Box.tsx";
import CardHeader from "../components/CardHeader.tsx";
import MarkerList from "../components/stream/MarkerList.tsx";
import PrimaryButton from "../components/buttons/PrimaryButton.tsx";
import { useAuth } from "../auth/useAuth.ts";
import { getCurrentStream, getStreamHistory } from "../utils/api/stream.ts";
@@ -9,7 +11,7 @@ import { getMarkers, createMarker, deleteMarker } from "../utils/api/markers.ts"
import { saveSectionByMarkers, clipSection } from "../utils/api/media.ts";
import { getJob } from "../utils/api/jobs.ts";
import type { StreamStatus, StreamHistoryItem, Marker, JobResponse } from "../utils/types.ts";
import { formatTime, formatLocalDate, stringToDate } from "../utils/utils.ts";
import { formatLocalDate, stringToDate } from "../utils/utils.ts";
const inputClass = "border border-hairline bg-fields rounded-md w-full p-2 text-sm focus:outline-none focus:ring-2 focus:ring-muted transition-colors";
const labelClass = "font-data text-[11px] text-muted uppercase tracking-[0.12em]";
@@ -22,15 +24,6 @@ type TrackedJob = {
errorOutput: string | null;
};
const CardHeader = ({ icon: Icon, title, accent = "primary" }: { icon: React.ElementType; title: string; accent?: "primary" | "accent" }) => (
<div className="flex items-center gap-2.5">
<div className={clsx("w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0", accent === "primary" ? "bg-terracotta/10" : "bg-olive/10")}>
<Icon size={16} className={accent === "primary" ? "text-terracotta" : "text-olive"} />
</div>
<h2 className="text-xl font-heading text-text-primary">{title}</h2>
</div>
);
const JobStatus = ({ job }: { job: TrackedJob }) => {
if (job.state === 'FAILED') {
return (
@@ -63,11 +56,8 @@ const StreamControl = () => {
const { user } = useAuth();
const [streamStatus, setStreamStatus] = useState<StreamStatus | null>(null);
const [streamDetails, setStreamDetails] = useState<StreamHistoryItem | null>(null);
const [now, setNow] = useState(Date.now());
const [markers, setMarkers] = useState<Marker[]>([]);
const [markerMessage, setMarkerMessage] = useState("");
const [markerBusy, setMarkerBusy] = useState(false);
const [markerError, setMarkerError] = useState<string | null>(null);
const [clipDuration, setClipDuration] = useState(30);
@@ -103,16 +93,10 @@ const StreamControl = () => {
.catch(() => {});
}, [user, streamStatus?.id]);
useEffect(() => {
if (!streamDetails?.startDate) return;
const interval = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(interval);
}, [streamDetails?.startDate]);
const refreshMarkers = () => {
getMarkers()
.then((data) => setMarkers(data
.sort((a, b) => stringToDate(a.timestamp).getTime() - stringToDate(b.timestamp).getTime())))
.sort((a, b) => stringToDate(b.timestamp).getTime() - stringToDate(a.timestamp).getTime())))
.catch(() => {});
};
@@ -149,18 +133,15 @@ const StreamControl = () => {
setJobs((prev) => [{ uuid, label, progress: 0, state: 'READY', errorOutput: null }, ...prev]);
};
const handleAddMarker = async () => {
if (!markerMessage.trim() || markerBusy) return;
setMarkerBusy(true);
const handleAddMarker = async (message: string) => {
setMarkerError(null);
try {
await createMarker(markerMessage.trim());
setMarkerMessage("");
await createMarker(message);
refreshMarkers();
return true;
} catch (err) {
setMarkerError(err instanceof Error ? err.message : "Failed to add marker");
} finally {
setMarkerBusy(false);
return false;
}
};
@@ -179,7 +160,7 @@ const StreamControl = () => {
const handleSaveByMarkers = async () => {
setMarkerSaveError(null);
if (!startMarkerId || !endMarkerId) {
setMarkerSaveError("Tap two markers above to pick a start and end");
setMarkerSaveError("Pick a start and an end marker from the timeline");
return;
}
try {
@@ -210,7 +191,7 @@ const StreamControl = () => {
}
};
const handleChipClick = (id: number) => {
const handleSelectMarker = (id: number) => {
const idStr = String(id);
setMarkerSaveError(null);
if (startMarkerId === idStr) { setStartMarkerId(""); return; }
@@ -228,10 +209,6 @@ const StreamControl = () => {
);
}
const elapsed = streamDetails?.startDate
? formatTime((now - stringToDate(streamDetails.startDate).getTime()) / 1000)
: null;
const startMarker = markers.find((m) => String(m.id) === startMarkerId);
const endMarker = markers.find((m) => String(m.id) === endMarkerId);
@@ -259,97 +236,30 @@ const StreamControl = () => {
</div>
</div>
{isStreaming && elapsed ? (
<div className="text-right">
<p className="text-2xl font-data text-text-primary tabular-nums">{elapsed}</p>
<p className={labelClass}>elapsed</p>
</div>
) : (
<Radio size={28} className="text-inactive" />
)}
<Radio size={28} className={isStreaming ? "text-live" : "text-inactive"} />
</Box>
{isStreaming && (
<>
{/* Quick mark toolbar */}
<Box className="p-4 flex flex-col gap-3">
<div className="flex items-center gap-3">
<Bookmark size={18} className="text-olive flex-shrink-0" />
<input
type="text"
value={markerMessage}
onChange={(e) => setMarkerMessage(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleAddMarker()}
placeholder="What just happened?"
className={inputClass}
/>
<PrimaryButton onClick={handleAddMarker} disabled={markerBusy || !markerMessage.trim()} className="whitespace-nowrap">
Add Marker
</PrimaryButton>
</div>
{markerError && <p className="text-sm text-error">{markerError}</p>}
{markers.length > 0 && (
<div className="flex gap-2 overflow-x-auto pb-0.5 -mx-1 px-1 pt-1.5">
{markers.map((m) => {
const isStart = startMarkerId === String(m.id);
const isEnd = endMarkerId === String(m.id);
return (
<div key={m.id} className="group relative flex-shrink-0">
<button
onClick={() => handleChipClick(m.id)}
className={clsx(
"flex flex-col items-start gap-0.5 rounded-lg border px-3 py-1.5 text-left transition-colors duration-150",
isStart && "border-terracotta bg-selected ring-1 ring-terracotta",
isEnd && "border-olive bg-selected ring-1 ring-olive",
!isStart && !isEnd && "border-hairline hover:border-ring hover:bg-hover"
)}
>
<span className="text-xs font-medium text-text-strong max-w-40 truncate">{m.message}</span>
<span className="font-data text-[11px] text-muted">
{formatLocalDate(m.timestamp, { hour: "2-digit", minute: "2-digit", second: "2-digit" })}
{isStart && <span className="text-terracotta font-medium"> · start</span>}
{isEnd && <span className="text-olive font-medium"> · end</span>}
</span>
</button>
<button
onClick={(e) => { e.stopPropagation(); handleDeleteMarker(m.id); }}
title="Delete marker"
className="hidden group-hover:flex items-center justify-center absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-muted hover:bg-error text-on-accent transition-colors duration-150"
>
<X size={10} />
</button>
</div>
);
})}
</div>
)}
</Box>
<div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_20rem] gap-5 items-start">
{/* Marker timeline. First on narrow screens, where marking
something as it happens beats the action forms for urgency. */}
<MarkerList
className="lg:order-last lg:sticky lg:top-6"
markers={markers}
startMarkerId={startMarkerId}
endMarkerId={endMarkerId}
error={markerError}
onAdd={handleAddMarker}
onSelect={handleSelectMarker}
onDelete={handleDeleteMarker}
/>
{/* Forefront actions */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-5 items-stretch">
<Box className="p-6 flex flex-col gap-3">
<CardHeader icon={Scissors} title="Clip the last few seconds" />
<div className="flex flex-col gap-1.5">
<label className={labelClass}>Duration (seconds)</label>
<input
type="number"
min={1}
value={clipDuration}
onChange={(e) => setClipDuration(Number(e.target.value))}
className={inputClass}
/>
</div>
<input type="text" placeholder="Title" value={clipTitle} onChange={(e) => setClipTitle(e.target.value)} className={inputClass} />
<textarea placeholder="Description" value={clipDescription} onChange={(e) => setClipDescription(e.target.value)} rows={2} className={inputClass + " resize-none"} />
{clipError && <p className="text-sm text-error">{clipError}</p>}
<PrimaryButton onClick={handleClip} className="self-start mt-auto">Clip</PrimaryButton>
</Box>
<div className="flex flex-col gap-5">
<Box className="p-6 flex flex-col gap-3">
<CardHeader icon={Film} title="Save between two markers" accent="accent" />
{markers.length < 2 ? (
<p className="text-sm text-muted">Add at least two markers above to save a section between them.</p>
<p className="text-sm text-muted">Add at least two markers to save a section between them.</p>
) : (
<>
<div className="flex items-center gap-2 flex-wrap">
@@ -374,19 +284,37 @@ const StreamControl = () => {
)}
<PrimaryButton onClick={handleSaveByMarkers} disabled={markers.length < 2} className="self-start mt-auto">Save</PrimaryButton>
</Box>
</div>
<Box className="p-5 flex flex-col gap-3">
<CardHeader icon={Activity} title="Recent actions" />
{jobs.length === 0 ? (
<p className="text-sm text-muted">Clip and save actions will show up here.</p>
) : (
<div className="flex flex-col gap-3">
{jobs.map((job) => <JobStatus key={job.uuid} job={job} />)}
<Box className="p-6 flex flex-col gap-3">
<CardHeader icon={Scissors} title="Clip the last few seconds" />
<div className="flex flex-col gap-1.5">
<label className={labelClass}>Duration (seconds)</label>
<input
type="number"
min={1}
value={clipDuration}
onChange={(e) => setClipDuration(Number(e.target.value))}
className={inputClass}
/>
</div>
)}
</Box>
</>
<input type="text" placeholder="Title" value={clipTitle} onChange={(e) => setClipTitle(e.target.value)} className={inputClass} />
<textarea placeholder="Description" value={clipDescription} onChange={(e) => setClipDescription(e.target.value)} rows={2} className={inputClass + " resize-none"} />
{clipError && <p className="text-sm text-error">{clipError}</p>}
<PrimaryButton onClick={handleClip} className="self-start mt-auto">Clip</PrimaryButton>
</Box>
<Box className="p-5 flex flex-col gap-3">
<CardHeader icon={Activity} title="Recent actions" />
{jobs.length === 0 ? (
<p className="text-sm text-muted">Clip and save actions will show up here.</p>
) : (
<div className="flex flex-col gap-3">
{jobs.map((job) => <JobStatus key={job.uuid} job={job} />)}
</div>
)}
</Box>
</div>
</div>
)}
</div>
);

View File

@@ -0,0 +1,23 @@
import { createContext } from "react";
/** What the user chose. "system" defers to the OS setting. */
type ThemePreference = "light" | "dark" | "system";
/** The theme actually on screen, once "system" has been resolved. */
type ResolvedTheme = "light" | "dark";
type ThemeContextValue = {
/** The stored choice, which may be "system". */
preference: ThemePreference;
/** The theme currently applied to the document. */
theme: ResolvedTheme;
/** Store a new preference and apply it immediately. */
setPreference: (preference: ThemePreference) => void;
/** Flip between light and dark, pinning the result as an explicit choice. */
toggleTheme: () => void;
};
const ThemeContext = createContext<ThemeContextValue | null>(null);
export { ThemeContext };
export type { ThemeContextValue, ThemePreference, ResolvedTheme };

View File

@@ -0,0 +1,71 @@
import { useCallback, useEffect, useState } from "react";
import type { ReactNode } from "react";
import { ThemeContext } from "./ThemeContext.ts";
import type { ResolvedTheme, ThemePreference } from "./ThemeContext.ts";
/** Shared with the pre-paint script in index.html — keep the two in step. */
const STORAGE_KEY = "theme";
const DARK_QUERY = "(prefers-color-scheme: dark)";
const readPreference = (): ThemePreference => {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === "light" || stored === "dark" || stored === "system") {
return stored;
}
} catch {
// Storage blocked (private browsing, cookies disabled) — follow the OS.
}
return "system";
};
const readSystemTheme = (): ResolvedTheme =>
window.matchMedia(DARK_QUERY).matches ? "dark" : "light";
/**
* Owns the single source of truth for the active theme. Nothing reads colours
* from here: the palette lives in index.css and switches on the `data-theme`
* attribute this provider writes, so components keep using the semantic
* utilities (`bg-card`, `text-text-primary`) and follow along for free.
*/
const ThemeProvider = ({ children }: { children: ReactNode }) => {
const [preference, setPreferenceState] = useState<ThemePreference>(readPreference);
const [systemTheme, setSystemTheme] = useState<ResolvedTheme>(readSystemTheme);
// Keep following the OS while the preference is "system".
useEffect(() => {
const query = window.matchMedia(DARK_QUERY);
const onChange = (event: MediaQueryListEvent) =>
setSystemTheme(event.matches ? "dark" : "light");
query.addEventListener("change", onChange);
return () => query.removeEventListener("change", onChange);
}, []);
const theme: ResolvedTheme = preference === "system" ? systemTheme : preference;
useEffect(() => {
document.documentElement.dataset.theme = theme;
}, [theme]);
const setPreference = useCallback((next: ThemePreference) => {
setPreferenceState(next);
try {
localStorage.setItem(STORAGE_KEY, next);
} catch {
// Storage blocked — the choice still applies for this session.
}
}, []);
const toggleTheme = useCallback(() => {
setPreference(theme === "dark" ? "light" : "dark");
}, [theme, setPreference]);
return (
<ThemeContext.Provider value={{ preference, theme, setPreference, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
export default ThemeProvider;

View File

@@ -0,0 +1,14 @@
import { useContext } from "react";
import { ThemeContext } from "./ThemeContext.ts";
import type { ThemeContextValue } from "./ThemeContext.ts";
/** Access the centralised theme state. Must be used within a <ThemeProvider>. */
const useTheme = (): ThemeContextValue => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
};
export { useTheme };

View File

@@ -6,9 +6,43 @@ class AuthError extends Error {
constructor() { super("Not authenticated"); this.name = "AuthError"; }
}
const isThumbnailAvailable = async (thumbnailUrl: string): Promise<boolean> => {
const response = await fetch(thumbnailUrl, { credentials: 'include' });
return response.ok;
};
let onUnauthorized: (() => void) | null = null;
export { API_URL, AuthError, isThumbnailAvailable };
export function registerUnauthorizedHandler(handler: () => void) {
onUnauthorized = handler;
}
/**
* Performs a request against the API, sending session cookies and funnelling
* expired/missing sessions through the registered unauthorized handler so the
* UI can drop back to a logged out state. Returns the raw response so callers
* that need something other than JSON (blobs, streams) can read it themselves.
*/
async function apiFetchRaw(url: string, options: RequestInit = {}): Promise<Response> {
const response = await fetch(url, {
...options,
credentials: 'include'
});
if (response.status == 401 || response.status == 403) {
onUnauthorized?.();
throw new AuthError();
}
if (!response.ok) {
const text = await response.text();
let message = text;
try { message = JSON.parse(text).message ?? text; } catch { /* not JSON, use raw text */ }
throw new Error(message || `Request failed: ${response.status}`);
}
return response;
}
async function apiFetch<T>(url: string, options: RequestInit = {}): Promise<T> {
const response = await apiFetchRaw(url, options);
const text = await response.text();
return text ? JSON.parse(text) : (undefined as T);
}
export { API_URL, AuthError, apiFetch, apiFetchRaw };

View File

@@ -1,27 +1,17 @@
import type { APIResponse, Clip } from "../types.ts";
import { API_URL, AuthError } from "./client.ts";
import { API_URL, apiFetch } from "./client.ts";
const getClips = async (): Promise<Clip[]> => {
const response = await fetch(API_URL + '/api/v1/clips', { credentials: 'include' });
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/clips');
if (result.status === 'error') throw new Error(`Failed to fetch clips: ${result.message}`);
if (!response.ok) {
const errorResult: APIResponse = await response.json();
throw new Error(`Failed to fetch clips: ${errorResult.message}`);
}
const result: APIResponse = await response.json();
return result.data;
};
const getClipById = async (id: string): Promise<Clip | null> => {
const response = await fetch(API_URL + `/api/v1/clips/${id}`, { credentials: 'include' });
const result = await apiFetch<APIResponse>(API_URL + `/api/v1/clips/${id}`);
if (result.status === 'error') throw new Error(`Failed to fetch clip: ${result.message}`);
if (!response.ok) {
if (response.status === 401 || response.status === 403) throw new AuthError();
throw new Error(`Failed to fetch clip: ${response.status}`);
}
const result: APIResponse = await response.json();
return result.data;
};
@@ -31,31 +21,20 @@ const getClipById = async (id: string): Promise<Clip | null> => {
const getClipMediaUrl = (id: string): string => API_URL + `/api/v1/clips/${id}/media`;
const patchClip = async (id: number, data: { title?: string; description?: string }): Promise<Clip> => {
const response = await fetch(API_URL + `/api/v1/clips/${id}`, {
const result = await apiFetch<APIResponse>(API_URL + `/api/v1/clips/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(data),
});
if (!response.ok) throw new Error(`Failed to update clip: ${response.status}`);
const result: APIResponse = await response.json();
if (result.status === 'error') throw new Error(`Failed to update clip: ${result.message}`);
return result.data;
};
const deleteClip = async (id: number): Promise<void> => {
const response = await fetch(API_URL + `/api/v1/clips/${id}`, {
method: 'DELETE',
credentials: 'include',
});
if (!response.ok) throw new Error(`Failed to delete clip: ${response.status}`);
const result: APIResponse = await response.json();
if (result.status === 'error') throw new Error(`Failed to delete clip: ${result.message}`);
const result = await apiFetch<APIResponse>(API_URL + `/api/v1/clips/${id}`, { method: 'DELETE' });
if (result?.status === 'error') throw new Error(`Failed to delete clip: ${result.message}`);
};
export { getClips, getClipById, getClipMediaUrl, patchClip, deleteClip };

View File

@@ -1,15 +1,16 @@
import type { APIResponse, JobResponse } from "../types.ts";
import { API_URL } from "./client.ts";
import { API_URL, apiFetch, apiFetchRaw } from "./client.ts";
const getJob = async (uuid: string): Promise<JobResponse> => {
const response = await fetch(API_URL + `/api/v1/jobs/${uuid}`, { credentials: 'include' });
if (!response.ok) throw new Error(`Failed to fetch job: ${response.status}`);
const result: APIResponse = await response.json();
const result = await apiFetch<APIResponse>(API_URL + `/api/v1/jobs/${uuid}`);
if (result.status === 'error') throw new Error(`Failed to fetch job: ${result.message}`);
return result.data;
};
export { getJob };
const downloadJob = async (uuid: string): Promise<Blob> => {
const response = await apiFetchRaw(API_URL + `/api/v1/jobs/${uuid}/download`);
return response.blob();
};
export { getJob, downloadJob };

View File

@@ -1,40 +1,28 @@
import type { APIResponse, Marker } from "../types.ts";
import { API_URL } from "./client.ts";
import { API_URL, apiFetch } from "./client.ts";
const getMarkers = async (): Promise<Marker[]> => {
const response = await fetch(API_URL + '/api/v1/markers', { credentials: 'include' });
if (!response.ok) throw new Error(`Failed to fetch markers: ${response.status}`);
const result: APIResponse = await response.json();
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/markers');
if (result.status === 'error') throw new Error(`Failed to fetch markers: ${result.message}`);
return result.data;
};
const createMarker = async (message: string): Promise<Marker> => {
const response = await fetch(API_URL + '/api/v1/markers', {
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/markers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ message }),
});
const result: APIResponse = await response.json();
if (!response.ok || result.status === 'error') throw new Error(`Failed to add marker: ${result.message}`);
if (result.status === 'error') throw new Error(`Failed to add marker: ${result.message}`);
return result.data;
};
const deleteMarker = async (id: number): Promise<void> => {
const response = await fetch(API_URL + `/api/v1/markers/${id}`, {
method: 'DELETE',
credentials: 'include',
});
if (!response.ok) throw new Error(`Failed to delete marker: ${response.status}`);
const result: APIResponse = await response.json();
if (result.status === 'error') throw new Error(`Failed to delete marker: ${result.message}`);
const result = await apiFetch<APIResponse>(API_URL + `/api/v1/markers/${id}`, { method: 'DELETE' });
if (result?.status === 'error') throw new Error(`Failed to delete marker: ${result.message}`);
};
export { getMarkers, createMarker, deleteMarker };

View File

@@ -1,5 +1,5 @@
import type { APIResponse, VideoMetadata } from "../types.ts";
import { API_URL } from "./client.ts";
import { API_URL, apiFetch } from "./client.ts";
const compress = async (file: File, options: VideoMetadata): Promise<string> => {
const formData = new FormData();
@@ -13,58 +13,48 @@ const compress = async (file: File, options: VideoMetadata): Promise<string> =>
if (options.height) formData.append('height', options.height.toString());
if (options.fileSize) formData.append('fileSize', options.fileSize.toString());
const response = await fetch(API_URL + '/api/v1/media/compress', {
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/media/compress', {
method: 'POST',
body: formData,
credentials: 'include',
});
if (!response.ok) throw new Error(`Compression failed: ${response.status}`);
const result: APIResponse = await response.json();
if (result.status === 'error') throw new Error(`Compression failed: ${result.message}`);
return result.data.uuid;
};
const saveSection = async (startTime: string, endTime: string, title?: string, description?: string): Promise<string> => {
const response = await fetch(API_URL + '/api/v1/media/save', {
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/media/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ startTime, endTime, title, description }),
});
const result: APIResponse = await response.json();
if (!response.ok || result.status === 'error') throw new Error(`Failed to save section: ${result.message}`);
if (result.status === 'error') throw new Error(`Failed to save section: ${result.message}`);
return result.data.uuid;
};
const saveSectionByMarkers = async (startMarkerId: number, endMarkerId: number, title?: string, description?: string): Promise<string> => {
const response = await fetch(API_URL + '/api/v1/media/save/markers', {
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/media/save/markers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ startMarkerId, endMarkerId, title, description }),
});
const result: APIResponse = await response.json();
if (!response.ok || result.status === 'error') throw new Error(`Failed to save section: ${result.message}`);
if (result.status === 'error') throw new Error(`Failed to save section: ${result.message}`);
return result.data.uuid;
};
const clipSection = async (duration: number, title?: string, description?: string): Promise<string> => {
const response = await fetch(API_URL + '/api/v1/media/clip', {
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/media/clip', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ duration, title, description }),
});
const result: APIResponse = await response.json();
if (!response.ok || result.status === 'error') throw new Error(`Failed to clip section: ${result.message}`);
if (result.status === 'error') throw new Error(`Failed to clip section: ${result.message}`);
return result.data.uuid;
};

View File

@@ -1,28 +1,24 @@
import type { APIResponse, StreamHistoryItem, StreamStatus } from "../types.ts";
import { API_URL } from "./client.ts";
import { API_URL, apiFetch } from "./client.ts";
const getStreamStatus = async (): Promise<boolean> => {
const response = await fetch(API_URL + '/api/v1/stream/current', { credentials: 'include' });
if (!response.ok) return false;
const result: APIResponse = await response.json();
return result.status === 'success' && result.data?.isStreaming === true;
try {
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/stream/current');
return result.status === 'success' && result.data?.isStreaming === true;
} catch {
return false;
}
};
const getCurrentStream = async (): Promise<StreamStatus> => {
const response = await fetch(API_URL + '/api/v1/stream/current', { credentials: 'include' });
if (!response.ok) throw new Error(`Failed to fetch stream status: ${response.status}`);
const result: APIResponse = await response.json();
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/stream/current');
if (result.status === 'error') throw new Error(`Failed to fetch stream status: ${result.message}`);
return result.data;
};
const getStreamHistory = async (userId: number): Promise<StreamHistoryItem[]> => {
const response = await fetch(API_URL + `/api/v1/stream/history/${userId}`, { credentials: 'include' });
if (!response.ok) throw new Error(`Failed to fetch stream history: ${response.status}`);
const result: APIResponse = await response.json();
const result = await apiFetch<APIResponse>(API_URL + `/api/v1/stream/history/${userId}`);
if (result.status === 'error') throw new Error(`Failed to fetch stream history: ${result.message}`);
return result.data;

View File

@@ -1,6 +1,9 @@
import type { APIResponse, User } from "../types.ts";
import { API_URL } from "./client.ts";
import { API_URL, apiFetch } from "./client.ts";
// login and getUser deliberately use fetch directly: they run when there may be
// no session at all, and getUser is what the unauthorized handler calls to
// refresh — routing them through apiFetch would loop on a 401.
const login = async (googleToken: string): Promise<string> => {
const response = await fetch(API_URL + '/api/v1/users/login', {
method: 'POST',
@@ -18,15 +21,8 @@ const login = async (googleToken: string): Promise<string> => {
};
const logout = async (): Promise<void> => {
const response = await fetch(API_URL + '/api/v1/users/logout', {
method: 'POST',
credentials: 'include',
});
if (!response.ok) throw new Error(`Logout failed: ${response.status}`);
const result: APIResponse = await response.json();
if (result.status === 'error') throw new Error(`Logout failed: ${result.message}`);
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/users/logout', { method: 'POST' });
if (result?.status === 'error') throw new Error(`Logout failed: ${result.message}`);
};
const getUser = async (): Promise<User | null> => {

View File

@@ -1,27 +1,17 @@
import type { APIResponse, Vod } from "../types.ts";
import { API_URL, AuthError } from "./client.ts";
import { API_URL, apiFetch } from "./client.ts";
const getVods = async (): Promise<Vod[]> => {
const response = await fetch(API_URL + '/api/v1/vods', { credentials: 'include' });
const result = await apiFetch<APIResponse>(API_URL + '/api/v1/vods');
if (result.status === 'error') throw new Error(`Failed to fetch vods: ${result.message}`);
if (!response.ok) {
const errorResult: APIResponse = await response.json();
throw new Error(`Failed to fetch vods: ${errorResult.message}`);
}
const result: APIResponse = await response.json();
return result.data;
};
const getVodById = async (id: string): Promise<Vod | null> => {
const response = await fetch(API_URL + `/api/v1/vods/${id}`, { credentials: 'include' });
const result = await apiFetch<APIResponse>(API_URL + `/api/v1/vods/${id}`);
if (result.status === 'error') throw new Error(`Failed to fetch vod: ${result.message}`);
if (!response.ok) {
if (response.status === 401 || response.status === 403) throw new AuthError();
throw new Error(`Failed to fetch vod: ${response.status}`);
}
const result: APIResponse = await response.json();
return result.data;
};
@@ -31,31 +21,20 @@ const getVodById = async (id: string): Promise<Vod | null> => {
const getVodMediaUrl = (id: string): string => API_URL + `/api/v1/vods/${id}/media`;
const patchVod = async (id: number, data: { title?: string; description?: string }): Promise<Vod> => {
const response = await fetch(API_URL + `/api/v1/vods/${id}`, {
const result = await apiFetch<APIResponse>(API_URL + `/api/v1/vods/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(data),
});
if (!response.ok) throw new Error(`Failed to update vod: ${response.status}`);
const result: APIResponse = await response.json();
if (result.status === 'error') throw new Error(`Failed to update vod: ${result.message}`);
return result.data;
};
const deleteVod = async (id: number): Promise<void> => {
const response = await fetch(API_URL + `/api/v1/vods/${id}`, {
method: 'DELETE',
credentials: 'include',
});
if (!response.ok) throw new Error(`Failed to delete vod: ${response.status}`);
const result: APIResponse = await response.json();
if (result.status === 'error') throw new Error(`Failed to delete vod: ${result.message}`);
const result = await apiFetch<APIResponse>(API_URL + `/api/v1/vods/${id}`, { method: 'DELETE' });
if (result?.status === 'error') throw new Error(`Failed to delete vod: ${result.message}`);
};
export { getVods, getVodById, getVodMediaUrl, patchVod, deleteVod };

View File

@@ -21,6 +21,12 @@ function formatLocalDate(dateString: string, options?: Intl.DateTimeFormatOption
return stringToDate(dateString).toLocaleDateString(undefined, options ?? { year: "numeric", month: "long", day: "numeric" });
}
// Clock time only, no date — markers within a stream are all from the same day,
// so the date would just be noise beside them.
function formatLocalTime(dateString: string): string {
return stringToDate(dateString).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", second: "2-digit" });
}
function dateToTimeAgo(date: Date): string {
const secondsAgo = Math.floor((Date.now() - date.getTime()) / 1000);
const units: [number, string][] = [
@@ -40,4 +46,4 @@ function dateToTimeAgo(date: Date): string {
return `${s} second${s !== 1 ? 's' : ''} ago`;
}
export { formatTime, stringToDate, dateToTimeAgo, formatLocalDate };
export { formatTime, stringToDate, dateToTimeAgo, formatLocalDate, formatLocalTime };

View File

@@ -1,6 +1,6 @@
FROM tiangolo/nginx-rtmp
FROM tiangolo/nginx-rtmp:latest-2026-09-07
RUN apt-get update && \
RUN apt-get update -o Acquire::Check-Valid-Until=false && \
apt-get install -y --no-install-recommends gettext-base && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*

View File

@@ -1,7 +1,9 @@
package com.ddf.vodsystem.controllers;
import com.ddf.vodsystem.controllers.dto.StreamKey;
import com.ddf.vodsystem.dto.APIResponse;
import com.ddf.vodsystem.controllers.dto.Token;
import com.ddf.vodsystem.entities.Stream;
import com.ddf.vodsystem.entities.User;
import com.ddf.vodsystem.exceptions.NotAuthenticated;
import com.ddf.vodsystem.services.UserService;
@@ -102,4 +104,12 @@ public class UserController {
new APIResponse<>(SUCCESS, "Logged out successfully", null)
);
}
@PostMapping("/me/stream-key")
public ResponseEntity<APIResponse<StreamKey>> regenerateStreamKey() {
String streamKey = userService.regenerateStreamKey();
return ResponseEntity.ok(
new APIResponse<>(SUCCESS, "Stream key successfully", new StreamKey(streamKey))
);
}
}

View File

@@ -0,0 +1,4 @@
package com.ddf.vodsystem.controllers.dto;
public record StreamKey (String streamKey) {
}

View File

@@ -78,8 +78,8 @@ public class MarkerService {
* @return the persisted {@link Marker}
* @throws NotStreaming if the user has no active stream to mark
*/
public Marker create(String message) {
Optional<Stream> stream = streamService.getActiveStream();
public Marker create(User user, String message) {
Optional<Stream> stream = streamService.getActiveStream(user);
if (stream.isEmpty()) {
throw new NotStreaming("User must be streaming to mark");

View File

@@ -239,7 +239,7 @@ public class MediaService {
onSuccess.run();
}).exceptionally(ex -> {
job.setState(JobState.FAILED);
job.setErrorOutput(ex.getMessage());
job.setErrorOutput("FFMPEG failed to save stream segments");
logger.error("Stream save job {} failed: {}", job.getUuid(), ex.getMessage());
return null;
});

View File

@@ -90,19 +90,14 @@ public class StreamService {
}
/**
* Returns the current user's active (not-yet-ended) stream, if any.
* Returns the user's active (not-yet-ended) stream, if any.
*
* @param user the User object
* @return the active {@link Stream}, or empty if the user is not currently streaming
* @throws NotAuthenticated if no user session is present
*/
public Optional<Stream> getActiveStream() {
Optional<User> user = userService.getLoggedInUser();
if (user.isEmpty()) {
throw new NotAuthenticated("Log in to see user streams");
}
return streamRepository.findByUserAndEndDateIsNull(user.get());
public Optional<Stream> getActiveStream(User user) {
return streamRepository.findByUserAndEndDateIsNull(user);
}
/**

View File

@@ -98,6 +98,12 @@ public class UserService {
return userRepository.findByStreamKey(streamKey);
}
public String regenerateStreamKey(User user) {
user.setStreamKey(generateStreamKey());
userRepository.saveAndFlush(user);
return user.getStreamKey();
}
private User createOrUpdateUser(User user) {
Optional<User> existingUser = userRepository.findByGoogleId(user.getGoogleId());

View File

@@ -76,8 +76,9 @@ public class CommandRunner {
public void setProgress(String line, ProgressTracker progress, float length) {
Matcher matcher = timePattern.matcher(line);
if (matcher.find()) {
float timeInMs = Float.parseFloat(matcher.group(1)) / 1000000f;
progress.setProgress(timeInMs / length);
float timeInSeconds = Float.parseFloat(matcher.group(1)) / 1_000_000f;
float fraction = Math.clamp(timeInSeconds / length, 0f, 1f);
progress.setProgress(fraction);
}
}
}

View File

@@ -16,6 +16,7 @@ import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
@@ -42,13 +43,14 @@ public class StreamActionsService {
* A resolved section of a stream, ready to be muxed by {@link #saveSection}.
*
* @param segments the segments to concatenate, in playback order; never empty
* @param trimOffset seconds to trim from the start of {@code segments.getFirst()}
* so playback begins at the requested moment, or {@code 0}
* when the first segment already starts there
* @param duration seconds of footage to keep, measured from the trim point.
* When the requested start fell in a recording gap and the
* leading segment was dropped, this is measured from the
* later real start so the section still ends where requested
* @param trimOffset seconds between the start of {@code segments.getFirst()} and
* the requested start, or {@code 0} when the first segment
* already starts there. Segments are copied whole, so this is
* lead-in the section carries before the requested moment, not
* footage that gets trimmed away
* @param duration seconds of footage to keep, measured from the start of
* {@code segments.getFirst()} so the section ends at the
* requested end time with the lead-in included
*/
public record SegmentSelection(List<Path> segments, float trimOffset, float duration) {}
@@ -78,8 +80,6 @@ public class StreamActionsService {
long firstMs = parseTimestampMs(segments.getFirst());
float trimOffset = Math.max(0f, (startTime.toEpochMilli() - firstMs) / 1000f);
// A first segment shorter than the trim offset means the requested start
// lands in a gap after it; drop it and begin at the next recorded footage.
if (trimOffset > 0 && probeDurationSeconds(segments.getFirst()) < trimOffset) {
segments.removeFirst();
if (segments.isEmpty()) {
@@ -89,18 +89,19 @@ public class StreamActionsService {
trimOffset = 0f;
}
// Measure duration from where playback actually begins so a dropped
// leading segment shortens the section rather than overrunning endTime.
long effectiveStartMs = firstMs + (long) (trimOffset * 1000);
float duration = (endTime.toEpochMilli() - effectiveStartMs) / 1000f;
float duration = (endTime.toEpochMilli() - firstMs) / 1000f;
return new SegmentSelection(segments, trimOffset, duration);
}
/**
* Muxes a {@link SegmentSelection} to {@code outputFile}, trimming the leading
* segment to {@code selection.trimOffset()} and keeping {@code selection.duration()}
* seconds of footage.
* Muxes a {@link SegmentSelection} to {@code outputFile}, keeping
* {@code selection.duration()} seconds of footage.
* <p>
* Segments are concatenated byte-wise through ffmpeg's {@code concat:} protocol,
* which preserves the continuous timestamps nginx writes across fragments. The
* leading segment is copied whole rather than trimmed, so playback begins up to
* {@code selection.trimOffset()} seconds before the requested moment.
* <p>
* Runs asynchronously; failures (process-launch errors, ffmpeg failures,
* interruption) complete the returned future exceptionally rather than being
@@ -131,37 +132,19 @@ public class StreamActionsService {
"trimOffset must be >= 0 and duration must be > 0 (got " + trimOffset + ", " + duration + ")"));
}
Path headFragment = null;
Path concatList = null;
try {
// Only the first segment is trimmed, so re-encode just that fragment and
// stream-copy the rest. A zero offset means the first segment already
// starts at the requested point, so re-encoding it would be wasted work.
List<Path> fragments;
if (trimOffset > 0) {
headFragment = Files.createTempFile("reencode-section-", ".ts");
encodeHead(segments.getFirst(), trimOffset, headFragment);
fragments = new ArrayList<>();
fragments.add(headFragment);
fragments.addAll(segments.subList(1, segments.size()));
} else {
fragments = segments;
}
// The concat demuxer (unlike the concat: byte protocol) rebases each
// fragment's timestamps to run continuously across the joins, absorbing
// the discontinuity between the PTS-0 head and the copied fragments.
concatList = writeConcatList(fragments);
String concatInput = "concat:" + segments.stream()
.map(p -> p.toAbsolutePath().toString())
.collect(Collectors.joining("|"));
List<String> command = List.of(
"ffmpeg",
"-y",
"-f", "concat",
"-safe", "0",
"-i", concatList.toAbsolutePath().toString(),
"-progress", "pipe:1",
"-i", concatInput,
"-t", String.valueOf(duration),
"-c", "copy",
"-avoid_negative_ts", "make_zero",
outputFile.toAbsolutePath().toString()
);
@@ -180,9 +163,6 @@ public class StreamActionsService {
} catch (RuntimeException e) {
logger.error("Failed to save section to '{}': {}", outputFile, e.toString());
return CompletableFuture.failedFuture(e);
} finally {
deleteTempQuietly(headFragment);
deleteTempQuietly(concatList);
}
}
@@ -257,52 +237,4 @@ public class StreamActionsService {
throw new IOException("Failed to probe segment duration: " + segment, e);
}
}
private void encodeHead(Path firstSegment, float trimOffset, Path head)
throws IOException, InterruptedException {
List<String> command = List.of(
"ffmpeg",
"-y",
"-i", firstSegment.toAbsolutePath().toString(),
"-ss", String.valueOf(trimOffset),
"-c:v", "libx264",
"-preset", "veryfast",
"-crf", "20",
"-pix_fmt", "yuv420p",
"-c:a", "aac",
"-b:a", "160k",
"-muxdelay", "0",
"-muxpreload", "0",
"-f", "mpegts",
head.toAbsolutePath().toString()
);
logger.debug("Re-encoding head fragment '{}' from {}s", firstSegment, trimOffset);
commandRunner.run(command, line -> { /* head pass is short; no progress reporting */ });
if (!Files.exists(head) || Files.size(head) == 0) {
throw new IOException("Head re-encode produced no output — trimOffset " + trimOffset
+ "s may exceed the duration of " + firstSegment);
}
}
private Path writeConcatList(List<Path> fragments) throws IOException {
Path listFile = Files.createTempFile("concat-list-", ".txt");
List<String> lines = fragments.stream()
.map(p -> "file '" + p.toAbsolutePath().toString().replace("'", "'\\''") + "'")
.toList();
Files.write(listFile, lines);
return listFile;
}
private void deleteTempQuietly(Path tempFile) {
if (tempFile != null) {
try {
Files.deleteIfExists(tempFile);
} catch (IOException e) {
logger.warn("Failed to delete temp file '{}': {}", tempFile, e.toString());
}
}
}
}

View File

@@ -4,3 +4,5 @@ media.temp.inputs=./videos/inputs
media.temp.outputs=./videos/outputs
media.users=${MEDIA_DATA}
media.streams=${STREAM_DATA}
logging.level.com.ddf.vodsystem=DEBUG

View File

@@ -57,23 +57,6 @@ class StreamActionsServiceTest {
when(metadataService.getVideoMetadata(any())).thenReturn(CompletableFuture.completedFuture(meta));
}
/**
* Stubs the two-arg {@link CommandRunner#run} so the head re-encode pass
* actually writes a non-empty file at its output path — {@code encodeHead}
* verifies its output exists and is non-empty before continuing. The concat
* pass (no {@code mpegts} muxer) is left untouched. Returns {@code output}
* for both invocations.
*/
private void stubRunnerProducingHead(CommandOutput output) throws IOException, InterruptedException {
when(commandRunner.run(anyList(), any())).thenAnswer(inv -> {
List<String> cmd = inv.getArgument(0);
if (cmd.contains("mpegts")) {
Files.writeString(Path.of(cmd.getLast()), "x");
}
return output;
});
}
// ---------------------------------------------------------------
// selectSegments: missing / invalid directories
// ---------------------------------------------------------------
@@ -247,8 +230,10 @@ class StreamActionsServiceTest {
assertThat(selection.segments()).extracting(p -> p.getFileName().toString())
.containsExactly("30.ts", "33.ts");
assertThat(selection.trimOffset()).isEqualTo(1.5f);
// effective start equals the requested 31.5s, so duration runs to endTime: 40 - 31.5
assertThat(selection.duration()).isEqualTo(8.5f);
// 30.ts is copied whole, so the section starts at 30s rather than the
// requested 31.5s; duration runs from there to endTime: 40 - 30. The
// 1.5s trimOffset is carried as lead-in, not cut away.
assertThat(selection.duration()).isEqualTo(10f);
}
@Test
@@ -355,7 +340,7 @@ class StreamActionsServiceTest {
ProgressTracker progress = new ProgressTracker();
CommandOutput commandOutput = new CommandOutput();
stubRunnerProducingHead(commandOutput);
when(commandRunner.run(anyList(), any())).thenReturn(commandOutput);
var future = service.saveSection(
new StreamActionsService.SegmentSelection(List.of(segmentA, segmentB), 5.0f, 12.0f), output, progress);
@@ -363,24 +348,29 @@ class StreamActionsServiceTest {
assertThat(future.get()).isSameAs(commandOutput);
assertThat(progress.isComplete()).isTrue();
// With a non-zero trim offset saveSection issues two ffmpeg passes: the
// head re-encode (trims the first segment via -ss) followed by the
// concat-demuxer stream copy (-f concat / -t / -c copy).
// The section is one stream-copy pass over the byte-concatenated segments:
// the concat: protocol joins them without rebasing the timestamps nginx
// wrote across fragments, which is what keeps the joins seamless.
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(commandRunner, Mockito.times(2)).run(captor.capture(), any());
List<String> headCommand = captor.getAllValues().get(0);
List<String> concatCommand = captor.getAllValues().get(1);
Mockito.verify(commandRunner, Mockito.times(1)).run(captor.capture(), any());
List<String> command = captor.getValue();
assertThat(headCommand).containsSequence("-ss", "5.0");
assertThat(concatCommand).containsSequence("-f", "concat");
assertThat(concatCommand).containsSequence("-t", "12.0");
assertThat(concatCommand).containsSequence("-c", "copy");
assertThat(concatCommand).endsWith(output.toAbsolutePath().toString());
assertThat(command).containsSequence(
"-i", "concat:" + segmentA.toAbsolutePath() + "|" + segmentB.toAbsolutePath());
assertThat(command).containsSequence("-t", "12.0");
assertThat(command).containsSequence("-c", "copy");
assertThat(command).containsSequence("-avoid_negative_ts", "make_zero");
assertThat(command).endsWith(output.toAbsolutePath().toString());
// The leading segment is copied whole, so nothing seeks and the concat
// demuxer (-f concat) is deliberately not used.
assertThat(command).doesNotContain("-ss");
assertThat(command).doesNotContainSequence("-f", "concat");
}
@Test
void saveSection_zeroTrimOffset_skipsHeadReencodeAndRunsSingleConcatPass() throws Exception {
void saveSection_zeroTrimOffset_buildsTheSameSingleCopyPass() throws Exception {
Path output = Path.of("/tmp/out/clip.mp4");
ProgressTracker progress = new ProgressTracker();
CommandOutput commandOutput = new CommandOutput();
@@ -394,14 +384,14 @@ class StreamActionsServiceTest {
assertThat(future.get()).isSameAs(commandOutput);
assertThat(progress.isComplete()).isTrue();
// trimOffset 0 means the first segment already starts at the requested point:
// no head re-encode pass, just a single concat-demuxer copy (no -ss).
// trimOffset no longer changes the command shape: with or without lead-in
// the section is the same single copy pass over the joined segments.
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(commandRunner, Mockito.times(1)).run(captor.capture(), any());
List<String> command = captor.getValue();
assertThat(command).containsSequence("-f", "concat");
assertThat(command).containsSequence("-i", "concat:/tmp/a.ts|/tmp/b.ts");
assertThat(command).containsSequence("-t", "10.0");
assertThat(command).doesNotContain("-ss");
}
@@ -411,8 +401,7 @@ class StreamActionsServiceTest {
Path output = Path.of("/tmp/out/clip.mp4");
ProgressTracker progress = new ProgressTracker();
// With a non-zero trim offset the head re-encode is the first ffmpeg pass;
// its failure must surface.
// The copy pass is the only ffmpeg invocation, so its failure must surface.
when(commandRunner.run(anyList(), any())).thenThrow(new IOException("ffmpeg boom"));
var future = service.saveSection(
@@ -442,8 +431,8 @@ class StreamActionsServiceTest {
void saveSection_nullOutputFile_completesExceptionally() {
ProgressTracker progress = new ProgressTracker();
// trimOffset 0 skips the head pass; building the concat command dereferences
// the null output path, so no ffmpeg pass ever runs.
// Building the command dereferences the null output path, so no ffmpeg
// pass ever runs.
var future = service.saveSection(
new StreamActionsService.SegmentSelection(List.of(Path.of("/tmp/a.ts")), 0f, 10f), null, progress);