47 Commits

Author SHA1 Message Date
dfff51e9d8 fix incorrect hls segment handling
All checks were successful
CI / Maven unit tests (push) Successful in 15s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped
2026-07-25 19:15:42 +01:00
ae8f2f33a7 perf(api): add HTTP range requests on media sources (#9)
All checks were successful
CI / Maven unit tests (push) Successful in 20s
CI / Build and push images (push) Successful in 5m14s
CI / Deploy to server (push) Successful in 1m29s
Reviewed-on: https://gitea.vodsystem.ddns.net/dylan/vod-system/pulls/9
2026-07-25 11:06:39 +01:00
74a9d5752d feat(frontend): improve browser icon
All checks were successful
CI / Maven unit tests (push) Successful in 14s
CI / Build and push images (push) Successful in 45s
CI / Deploy to server (push) Successful in 20s
2026-07-13 23:45:56 +01:00
fe25ef05dc build(ci): improve caching efficiency in ci
All checks were successful
CI / Maven unit tests (push) Successful in 15s
CI / Build and push images (push) Successful in 25s
CI / Deploy to server (push) Successful in 5s
2026-07-13 23:39:43 +01:00
339465b417 feat(frontend): change browser icon
All checks were successful
CI / Maven unit tests (push) Successful in 15s
CI / Build and push images (push) Successful in 3m19s
CI / Deploy to server (push) Successful in 43s
2026-07-13 23:20:45 +01:00
3a46048b66 build(ci): add auto-deployment
All checks were successful
CI / Maven unit tests (push) Successful in 15s
CI / Build and push images (push) Successful in 4m1s
CI / Deploy to server (push) Successful in 44s
2026-07-13 20:35:33 +01:00
740f904d92 Merge pull request 'FFMPEG Classes Unit Testing' (#8) from test/ffmpeg-unit-tests into master
All checks were successful
Unit Tests / Maven unit tests (push) Successful in 14s
Reviewed-on: https://gitea.vodsystem.ddns.net/dylan/vod-system/pulls/8
2026-07-12 20:00:16 +01:00
e902d54a4d fix(ci): incorrect url
All checks were successful
Unit Tests / Maven unit tests (push) Successful in 2m11s
2026-07-12 19:11:09 +01:00
d621aa3d6a build(ci): unit test
Some checks failed
Unit Tests / Maven unit tests (push) Failing after 45s
2026-07-12 19:08:41 +01:00
f9b055b3b5 test(unit): improve test coverage 2026-07-12 19:06:10 +01:00
bb6f5e7823 test(unit): add Thumbnail and Remux service tests 2026-07-12 18:59:44 +01:00
2408263988 fix(media): propagate async FFmpeg results and failures 2026-07-12 18:49:20 +01:00
688ff541da test(unit): StreamActionsService tests 2026-07-12 18:11:45 +01:00
07ee112d57 refactor(stream actions): move segment logic into StreamActionsService 2026-07-08 22:17:10 +02:00
fbb5c3ab52 fix(interrupts): metadata service not setting interrupt bit 2026-07-08 11:57:01 +02:00
e1e6fe0046 fix(file size): use Long instead of float
Float only stores up to 16 million, and file size is stored in bytes. A video can easily be over 16MB (16 million bytes), therefore Long is needed.
2026-07-07 20:48:37 +02:00
a66b9898e8 test(unit): metadata unit tests 2026-07-07 20:26:23 +02:00
baaf162fee test(unit): maximum bitrate assertions 2026-07-04 14:06:32 +01:00
d7214ca1bc test(unit): compression service test 2026-07-02 20:59:13 +01:00
5bebea3f95 refactor(command): inject CommandRunner instead of static 2026-07-02 20:04:04 +01:00
947c8261fd Merge pull request 'Frontend page for controlling streaming actions' (#7) from feat/frontend-streaming-controls into master
Reviewed-on: https://gitea.vodsystem.ddns.net/dylan/vod-system/pulls/7
2026-07-02 19:46:32 +01:00
e0969a1d78 refactor(frontend): split endpoint handling 2026-07-02 19:46:19 +01:00
fe735faba8 feat(api): delete marker endpoint 2026-07-02 19:37:35 +01:00
b8b4d3b05c feat(frontend): streaming controls page 2026-07-02 19:27:23 +01:00
a051407c1e Merge pull request 'Stream Markers' (#6) from feat/stream-markers into master
Reviewed-on: https://gitea.vodsystem.ddns.net/dylan/vod-system/pulls/6
2026-07-02 19:14:43 +01:00
41fda53817 docs(docstring): other stream save method 2026-07-02 19:13:55 +01:00
1a0778d1d6 docs(bruno): save with marker endpoint 2026-07-02 19:09:25 +01:00
ba378680c6 feat(markers): add save endpoint with markers 2026-07-02 19:09:07 +01:00
2cac1770f9 feat(markers): auto-delete after 8 hours 2026-07-02 18:53:23 +01:00
dc33d1df33 feat(markers): get by id 2026-07-02 18:35:22 +01:00
62dc0b0491 docs(bruno): marker endpoints 2026-07-02 17:50:29 +01:00
18626a5db8 feat(markers): implement marker entity & service 2026-07-02 17:43:13 +01:00
3c8df9b328 fix(clips): remove redundant auth checks 2026-07-01 23:19:51 +01:00
76869c8c90 fix(clips): remove redundant Optional returns 2026-07-01 23:12:23 +01:00
e5fcf9b966 Merge pull request 'Implement VoDs in frontend and backend' (#5) from feat/full-vod-support into master
Reviewed-on: https://gitea.vodsystem.ddns.net/dylan/vod-system/pulls/5
2026-07-01 22:32:39 +01:00
4ec5080edc docs(docstrings): add clip & vod comments 2026-07-01 22:32:08 +01:00
14e8bd137b docs(bruno): add title/desc attr 2026-07-01 22:26:47 +01:00
998eebb032 feat(stream): implement description & title options 2026-07-01 22:23:49 +01:00
e2c94d0740 feat(stream): stream save now auto-persists vod 2026-07-01 22:12:32 +01:00
0b929e96da docs(bruno): implement bruno vods endpoints 2026-07-01 22:04:54 +01:00
1fff0805f6 feat(frontend): implement vods in frontend 2026-07-01 22:01:52 +01:00
48ff0eb8e5 feat(frontend): implement vods in frontend 2026-07-01 22:01:41 +01:00
83fcb44670 feat(backend): implement VoD functionality 2026-07-01 21:54:17 +01:00
913c5c8790 fix(exceptions): catch specific error instead of broad 2026-07-01 21:36:50 +01:00
a330471bec feat(frontend): add upload icon 2026-06-29 20:07:11 +01:00
d8b61b4528 docs: update readme 2026-06-26 15:49:12 +01:00
85ddd93757 fix(api): cookies not set on http connections
Frontend uses .env URL.
2026-06-26 14:47:15 +01:00
105 changed files with 5827 additions and 1706 deletions

View File

@@ -16,3 +16,5 @@ POSTGRES_DB=vodSystem
FRONTEND_URL=
BACKEND_URL=
STREAM_RING_LENGTH_SECOND=28800

118
.gitea/workflows/ci.yml Normal file
View File

@@ -0,0 +1,118 @@
name: CI
on:
push:
env:
REGISTRY: gitea.vodsystem.ddns.net
IMAGE_PREFIX: dylan/vod-system
jobs:
unit-tests:
name: Maven unit tests
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: https://github.com/actions/checkout@v4
- name: Set up Java 21
uses: https://github.com/actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
cache: maven
- name: Run unit tests
run: ./mvnw --batch-mode --no-transfer-progress test
build-and-push:
name: Build and push images
needs: unit-tests
if: gitea.ref == 'refs/heads/master'
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: https://github.com/actions/checkout@v4
- name: Set up Docker Buildx
uses: https://github.com/docker/setup-buildx-action@v3
- name: Log in to Gitea container registry
uses: https://github.com/docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ gitea.actor }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Build and push backend image
uses: https://github.com/docker/build-push-action@v6
with:
context: .
file: src/main/Dockerfile
push: true
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}-backend:latest
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}-backend:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}-backend:buildcache,mode=max
- name: Build and push frontend image
uses: https://github.com/docker/build-push-action@v6
with:
context: ./frontend
file: frontend/Dockerfile
push: true
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}-frontend:latest
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}-frontend:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}-frontend:buildcache,mode=max
- name: Build and push rtmp image
uses: https://github.com/docker/build-push-action@v6
with:
context: ./nginx
file: nginx/Dockerfile
push: true
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}-rtmp:latest
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}-rtmp:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_PREFIX }}-rtmp:buildcache,mode=max
deploy:
name: Deploy to server
needs: build-and-push
if: gitea.ref == 'refs/heads/master'
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: https://github.com/actions/checkout@v4
- name: Copy production compose file to server
uses: https://github.com/appleboy/scp-action@v0.1.7
with:
host: ${{ vars.DEPLOY_HOST }}
username: ${{ vars.DEPLOY_USER }}
port: 22
key: ${{ secrets.DEPLOY_SSH_KEY }}
source: docker-compose.prod.yml
target: ${{ vars.DEPLOY_PATH }}
strip_components: 0
- name: Pull latest images and restart containers
uses: https://github.com/appleboy/ssh-action@v1.0.3
with:
host: ${{ vars.DEPLOY_HOST }}
username: ${{ vars.DEPLOY_USER }}
port: 22
key: ${{ secrets.DEPLOY_SSH_KEY }}
envs: REGISTRY,REGISTRY_USER,REGISTRY_TOKEN,DEPLOY_PATH
script: |
set -e
echo "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
cd "$DEPLOY_PATH"
docker compose -f docker-compose.prod.yml pull
docker compose -f docker-compose.prod.yml up -d --remove-orphans
env:
REGISTRY: ${{ env.REGISTRY }}
REGISTRY_USER: ${{ gitea.actor }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
DEPLOY_PATH: ${{ vars.DEPLOY_PATH }}

1
.gitignore vendored
View File

@@ -44,4 +44,3 @@ build/
frontend/.flowbite-react
generated
.mvn

3
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip

144
README.md
View File

@@ -1,33 +1,121 @@
# Overview
The VoD System is a powerful clip management platform designed to streamline how you handle your video content. Whether you're a content creator, streamer, or educator, VoD System lets you:
# VoD System
- Upload clips effortlessly and securely.
- Edit and trim videos with intuitive controls.
- Compress files to specific file sizes.
- Organize your clips for quick access and sharing.
A self-hosted clip management and live streaming platform. Upload videos, trim and compress clips, save sections of a live stream, and organise everything through a clean web interface — all running locally under Docker.
This VoD system began as a small project back in my 5th year of secondary school, during lockdown. I wanted a quick way to send game clips to Discord, but the 8MB file size limit made it frustrating to manually tweak bitrates for every clip. To solve that, I wrote a simple Python script to automate the process. What started as a quick fix has since evolved into a full-fledged system — now built with a Spring Boot backend and a modern React/Vite frontend.
This project started in secondary school during lockdown as a Python script to squeeze game clips under Discord's 8 MB file size limit. It has since grown into a full-stack application with a Spring Boot backend, a React/Vite/TypeScript frontend, and an nginx-rtmp sidecar for live streaming.
---
## Tech Stack
| Layer | Technology |
|------------|---------------------------------------------------------|
| Backend | Java 21, Spring Boot 3.4, Spring Security, JPA, FFmpeg |
| Frontend | React 19, TypeScript, Vite, Tailwind CSS v4 |
| Database | PostgreSQL 15 |
| Streaming | nginx-rtmp |
| Auth | Google OAuth 2.0 + JWT |
| Runtime | Docker Compose |
---
## Requirements
- Docker & Docker Compose
- JDK 21+
- Node.js 16+
- FFMPEG
- Google Client keys
## Steps
1. Create your own two `.env` files based off the `example.env` files in the root and in the frontend folder
2. Spin up docker container with `docker compose up`
3. Run `./mvnw clean package` to build the jar
4. Run `./mvnw spring-boot:run` to run the backend section
5. Run `cd frontend && npm install && npm run dev` to build and run the frontend
6. Endpoints should be available at 8080 (backend) and 5173 (frontend)
# Future Plans
- **Format Handling**
- Backend conversion of non-MP4 files via FFMPEG for broader format support
- **Input Sources**
- Support for local file uploads and YouTube imports
- **Testing**
- Unit tests, including coverage for FFMPEG-related functionality
- **API Documentation**
- Comprehensive and maintainable backend API docs
- Docker and Docker Compose
- A Google Cloud project with OAuth 2.0 credentials (Client ID and Secret)
That is all. The backend, frontend, database, and RTMP server all run as containers — no local JDK, Node, or FFmpeg install required.
---
## Getting Started
### 1. Configure the environment
Copy the example file and fill in the values:
```bash
cp .env.example .env
```
Open `.env` and set the following:
```dotenv
# OAuth credentials from your Google Cloud Console project
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
# A long random string used to sign JWTs — treat it like a password
JWT_SECRET_KEY=
# Absolute paths on the host where persistent data will be stored
POSTGRES_DATA=/path/to/postgres/data
STREAM_DATA=/path/to/stream/data
MEDIA_DATA=/path/to/media/data
# Database credentials — change these from the defaults before deploying
POSTGRES_URL=jdbc:postgresql://postgres:5432/vodSystem
POSTGRES_USER=myuser
POSTGRES_PASSWORD=mypassword
POSTGRES_DB=vodSystem
# The URLs the frontend will use to reach itself and the backend
FRONTEND_URL=http://localhost:5173
BACKEND_URL=http://localhost:8080
```
### 2. Start the application
```bash
docker compose up --build
```
This builds and starts four containers: `vod_postgres`, `vod_backend`, `vod_frontend`, and `vod_rtmp`.
Once everything has started, the interfaces are available at:
- Frontend: [http://localhost:5173](http://localhost:5173)
- Backend API: [http://localhost:8080/api/v1](http://localhost:8080/api/v1)
- RTMP ingest: `rtmp://localhost:1935/live`
### 3. Authenticate
Log in through the frontend using your Google account. The backend exchanges the Google ID token for a short-lived JWT that is used on all subsequent API requests.
---
## Development Mode
For local backend or frontend development, a separate Compose file is provided that starts only the infrastructure services (PostgreSQL and the RTMP server), leaving the backend and frontend to run directly on the host:
```bash
docker compose -f docker-compose.dev.yml up
```
Then run the backend and frontend separately in your usual workflow.
- **Important**: Rootless docker should be used to avoid permission conflicts between the RTMP container and the Spring Boot host
---
## API Reference
A [Bruno](https://www.usebruno.com/) collection is included under `bruno/VoD-System/` with pre-configured requests covering all major endpoints. Import it directly into Bruno and point the `local` environment at `http://localhost:8080/api/v1`.
The collection is organised into four folders:
| Folder | Description |
|----------|--------------------------------------------------|
| Users | Google OAuth login flow, current user |
| Media | Upload, compress, clip stream, save section |
| Jobs | Poll job status, download completed output |
| Streams | Stream history |
---
## Future Plans
- **Format handling** — backend conversion of non-MP4 files via FFmpeg for broader input format support
- **Input sources** — YouTube imports and additional local upload options
- **Testing** — unit and integration test coverage, including FFmpeg-related functionality
- **API documentation** — comprehensive, auto-generated backend API docs

View File

@@ -0,0 +1,22 @@
meta {
name: Create Marker
type: http
seq: 3
}
post {
url: {{base_url}}/markers
body: json
auth: inherit
}
body:json {
{
"message": "Nice play"
}
}
settings {
encodeUrl: true
timeout: 0
}

View File

@@ -0,0 +1,16 @@
meta {
name: Delete Marker
type: http
seq: 4
}
delete {
url: {{base_url}}/markers/5
body: none
auth: inherit
}
settings {
encodeUrl: true
timeout: 0
}

View File

@@ -0,0 +1,16 @@
meta {
name: Get Marker
type: http
seq: 1
}
get {
url: {{base_url}}/markers/5
body: none
auth: inherit
}
settings {
encodeUrl: true
timeout: 0
}

View File

@@ -0,0 +1,11 @@
meta {
name: Get all markers
type: http
seq: 2
}
get {
url: {{base_url}}/markers
body: none
auth: inherit
}

View File

@@ -0,0 +1,8 @@
meta {
name: Markers
seq: 6
}
auth {
mode: inherit
}

View File

@@ -12,7 +12,9 @@ post {
body:json {
{
"duration": 60.0
"duration": 60.0,
"title": "Hello",
"description": "my clip"
}
}

View File

@@ -0,0 +1,24 @@
meta {
name: Save Stream Section By Markers
type: http
seq: 4
}
post {
url: {{base_url}}/media/save/markers
body: json
auth: inherit
}
body:json {
{
"startMarkerId": 1,
"endMarkerId": 2,
"title": "Hello",
"description": "my clip"
}
}
script:post-response {
bru.setEnvVar("uuid", res.getBody().data.uuid);
}

View File

@@ -12,8 +12,10 @@ post {
body:json {
{
"startTime": "2026-06-21T17:27:00Z",
"endTime": "2026-06-21T17:28:00Z"
"startTime": "2026-07-01T21:09:00Z",
"endTime": "2026-07-01T21:12:00Z",
"title": "Hello",
"description": "my clip"
}
}

View File

@@ -0,0 +1,16 @@
meta {
name: Delete VoD
type: http
seq: 4
}
delete {
url: {{base_url}}/vods/1
body: none
auth: inherit
}
settings {
encodeUrl: true
timeout: 0
}

View File

@@ -0,0 +1,16 @@
meta {
name: Get VoD Media
type: http
seq: 1
}
get {
url: {{base_url}}/vods/1/media
body: none
auth: inherit
}
settings {
encodeUrl: true
timeout: 0
}

View File

@@ -0,0 +1,15 @@
meta {
name: Get VoD Thumbnail
type: http
seq: 2
}
get {
url: {{base_url}}/vods/1/thumbnail
body: none
auth: inherit
}
settings {
encodeUrl: true
}

View File

@@ -0,0 +1,8 @@
meta {
name: Downloads
seq: 5
}
auth {
mode: inherit
}

View File

@@ -0,0 +1,16 @@
meta {
name: Get VoD
type: http
seq: 2
}
get {
url: {{base_url}}/vods/1
body: none
auth: inherit
}
settings {
encodeUrl: true
timeout: 0
}

View File

@@ -0,0 +1,11 @@
meta {
name: Get all vods
type: http
seq: 1
}
get {
url: {{base_url}}/vods
body: none
auth: inherit
}

View File

@@ -0,0 +1,23 @@
meta {
name: Update VoD
type: http
seq: 3
}
patch {
url: {{base_url}}/vods/1
body: json
auth: inherit
}
body:json {
{
"title": "My VoD",
"description": ""
}
}
settings {
encodeUrl: true
timeout: 0
}

View File

@@ -0,0 +1,8 @@
meta {
name: VoDs
seq: 2
}
auth {
mode: inherit
}

View File

@@ -0,0 +1,8 @@
vars {
base_url: http://http://server.tail3cd897.ts.net:8087/api/v1
uuid:
}
vars:secret [
google_client_id,
google_secret
]

View File

@@ -22,6 +22,8 @@ services:
container_name: vod_rtmp
extra_hosts:
- "host.docker.internal:host-gateway"
env_file:
- .env
environment:
- WEB_SERVER_URL=http://host.docker.internal:8080
ports:

57
docker-compose.prod.yml Normal file
View File

@@ -0,0 +1,57 @@
# Production deploy: uses pre-built images from the Gitea container registry
# instead of building locally. Populated by CI onto the server alongside .env.
# Usage: docker compose -f docker-compose.prod.yml pull && docker compose -f docker-compose.prod.yml up -d
services:
postgres:
image: postgres:15
container_name: vod_postgres
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
volumes:
- ${POSTGRES_DATA}:/var/lib/postgresql/data
restart: unless-stopped
backend:
image: gitea.vodsystem.ddns.net/dylan/vod-system-backend:latest
container_name: vod_backend
depends_on:
- postgres
env_file:
- .env
volumes:
- ${MEDIA_DATA}:/app/media
- ${STREAM_DATA}:/app/stream
ports:
- "8089:8080"
restart: unless-stopped
frontend:
image: gitea.vodsystem.ddns.net/dylan/vod-system-frontend:latest
container_name: vod_frontend
environment:
VITE_API_URL: ${BACKEND_URL}
VITE_FRONTEND_URL: ${FRONTEND_URL}
VITE_GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}
depends_on:
- backend
ports:
- "5173:5173"
restart: unless-stopped
rtmp:
image: gitea.vodsystem.ddns.net/dylan/vod-system-rtmp:latest
container_name: vod_rtmp
env_file:
- .env
environment:
- WEB_SERVER_URL=http://backend:8080
ports:
- "1935:1935"
volumes:
- ${STREAM_DATA}:/stream
restart: unless-stopped
depends_on:
- backend

View File

@@ -32,6 +32,7 @@ services:
container_name: vod_frontend
environment:
VITE_API_URL: ${BACKEND_URL}
VITE_FRONTEND_URL: ${FRONTEND_URL}
VITE_GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}
depends_on:
- backend
@@ -44,6 +45,8 @@ services:
context: ./nginx
dockerfile: Dockerfile
container_name: vod_rtmp
env_file:
- .env
environment:
- WEB_SERVER_URL=http://backend:8080
ports:

View File

@@ -2,7 +2,7 @@ FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
EXPOSE 5173

View File

@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/png" href="/small_icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,6 @@
},
"dependencies": {
"@react-oauth/google": "^0.12.2",
"@tailwindcss/vite": "^4.1.7",
"axios": "^1.11.0",
"clsx": "^2.1.1",
"dotenv": "^16.5.0",
@@ -24,11 +23,12 @@
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-range-slider-input": "^3.2.1",
"react-router-dom": "^7.8.0",
"tailwindcss": "^4.1.7"
"react-router-dom": "^7.8.0"
},
"devDependencies": {
"@eslint/js": "^9.25.0",
"@tailwindcss/vite": "^4.3.3",
"@types/node": "^26.1.1",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"@vitejs/plugin-react": "^4.4.1",
@@ -36,6 +36,7 @@
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^16.0.0",
"tailwindcss": "^4.3.3",
"typescript": "~5.8.3",
"typescript-eslint": "^8.30.1",
"vite": "^6.3.5",

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

View File

@@ -1,4 +1,4 @@
// App.jsx
// App.jsx
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import MainLayout from './layouts/MainLayout';
import ClipUpload from './pages/ClipUpload';
@@ -6,9 +6,14 @@ import ClipEdit from './pages/ClipEdit';
import Home from './pages/Home';
import {useEffect} from "react";
import MyClips from './pages/MyClips';
import VideoPlayer from "./pages/VideoPlayer.tsx";
import MyVods from './pages/MyVods';
import MediaPlayer from "./pages/MediaPlayer.tsx";
import { getVodById, getVodMediaUrl } from "./utils/api/vods.ts";
import { getClipById, getClipMediaUrl } from "./utils/api/clips.ts";
import EditClip from "./pages/EditClip.tsx";
import EditVod from "./pages/EditVod.tsx";
import Profile from "./pages/Profile.tsx";
import StreamControl from "./pages/StreamControl.tsx";
import { GoogleOAuthProvider } from '@react-oauth/google';
@@ -26,9 +31,13 @@ function App() {
<Route path="/create" element={<ClipUpload />} />
<Route path="/create/:id" element={<ClipEdit />} />
<Route path="/my-clips" element={<MyClips />} />
<Route path="/video/:id" element={<VideoPlayer />} />
<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>
</Routes>
</Router>

View File

@@ -1,6 +1,6 @@
import clsx from "clsx";
import SidebarButton from "./buttons/SidebarButton.tsx";
import { Plus, Film, Home, User as UserIcon } from 'lucide-react';
import { Plus, Film, Home, User as UserIcon, Video, Radio } from 'lucide-react';
import type {User} from "../utils/types.ts";
type props = {
@@ -30,7 +30,9 @@ const Sidebar = ({user, className}: props) => {
<>
<Divider />
<div className="flex flex-col gap-0.5">
<SidebarButton url="/stream" logo={<Radio size={18}/>} label="Stream" />
<SidebarButton url="/my-clips" logo={<Film size={18}/>} label="Clips" />
<SidebarButton url="/my-vods" logo={<Video size={18}/>} label="VoDs" />
</div>
</>
)}

View File

@@ -1,5 +1,5 @@
import { Menu, X } from 'lucide-react';
import { login, logout } from "../utils/endpoints.ts";
import { login, logout } from "../utils/api/users.ts";
import { Dropdown, DropdownItem } from "./Dropdown.tsx";
import { GoogleLogin } from '@react-oauth/google';

View File

@@ -5,15 +5,32 @@ type props = {
dataSend: React.MouseEventHandler<HTMLButtonElement>;
handleDownload: React.MouseEventHandler<HTMLButtonElement>;
downloadable: boolean;
progress: number
progress: number;
uploading: boolean;
}
const ExportWidget = ({dataSend, handleDownload, downloadable, progress}: props) => {
const Spinner = () => (
<svg
className="animate-spin h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
</svg>
);
const ExportWidget = ({dataSend, handleDownload, downloadable, progress, uploading}: props) => {
return (
<div className={"flex flex-col gap-3"}>
<BlueButton
onClick={dataSend}>
Export
onClick={dataSend}
disabled={uploading}
className={uploading ? "opacity-60 cursor-not-allowed flex items-center justify-center gap-2" : ""}
>
{uploading && <Spinner />}
{uploading ? "Uploading..." : "Export"}
</BlueButton>
<div className="h-10 flex items-center">

View File

@@ -2,7 +2,7 @@ import clsx from "clsx";
import { formatTime, stringToDate, dateToTimeAgo } from "../../utils/utils.ts";
import { Link } from "react-router-dom";
import { useEffect, useRef, useState } from "react";
import { isThumbnailAvailable } from "../../utils/endpoints.ts";
import { isThumbnailAvailable } from "../../utils/api/client.ts";
import { MoreVertical, Pencil, Trash2 } from "lucide-react";
type VideoCardProps = {
@@ -13,17 +13,21 @@ type VideoCardProps = {
onEdit?: () => void,
onDelete?: () => void,
className?: string,
mediaApiPath?: string,
playerPath?: string,
itemLabel?: string,
}
const fallbackThumbnail = "../../../public/default_thumbnail.png";
const API_URL = import.meta.env.VITE_API_URL;
const VideoCard = ({ id, title, duration, createdAt, onEdit, onDelete, className }: VideoCardProps) => {
const VideoCard = ({ id, title, duration, createdAt, onEdit, onDelete, className, mediaApiPath = '/api/v1/clips', playerPath = '/video', itemLabel = 'clip' }: VideoCardProps) => {
const [timeAgo, setTimeAgo] = useState(dateToTimeAgo(stringToDate(createdAt)));
const [thumbnailAvailable, setThumbnailAvailable] = useState(true);
const [menuOpen, setMenuOpen] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
const thumbnailUrl = `${API_URL}${mediaApiPath}/${id}/thumbnail`;
useEffect(() => {
const interval = setInterval(() => {
@@ -33,10 +37,10 @@ const VideoCard = ({ id, title, duration, createdAt, onEdit, onDelete, className
}, [createdAt]);
useEffect(() => {
isThumbnailAvailable(id)
isThumbnailAvailable(thumbnailUrl)
.then(setThumbnailAvailable)
.catch(() => setThumbnailAvailable(false));
}, []);
}, [thumbnailUrl]);
useEffect(() => {
if (!menuOpen) return;
@@ -57,11 +61,11 @@ const VideoCard = ({ id, title, duration, createdAt, onEdit, onDelete, className
};
return (
<Link to={"/video/" + id}>
<Link to={`${playerPath}/${id}`}>
<div className={clsx("flex flex-col group cursor-pointer", className)}>
<div className="relative overflow-hidden rounded-lg">
<img
src={thumbnailAvailable ? API_URL + `/api/v1/clips/${id}/thumbnail` : fallbackThumbnail}
src={thumbnailAvailable ? thumbnailUrl : fallbackThumbnail}
alt="Video Thumbnail"
className="w-full aspect-video object-cover group-hover:scale-105 transition-transform duration-200"
/>
@@ -105,7 +109,7 @@ const VideoCard = ({ id, title, duration, createdAt, onEdit, onDelete, className
</>)}
{confirmDelete && (
<div className="px-3 py-2">
<p className="text-xs text-gray-600 mb-2">Delete this clip?</p>
<p className="text-xs text-gray-600 mb-2">Delete this {itemLabel}?</p>
<div className="flex gap-1.5">
<button
onClick={(e) => stopAndRun(e, onDelete!)}

View File

@@ -4,7 +4,8 @@ import Topbar from '../components/Topbar'
import { Outlet } from 'react-router-dom';
import {useEffect, useState} from "react";
import type {User} from "../utils/types";
import { getUser, getStreamStatus } from "../utils/endpoints";
import { getUser } from "../utils/api/users";
import { getStreamStatus } from "../utils/api/stream";
const MainLayout = () => {
const [sidebarToggled, setSidebarToggled] = useState(false);

View File

@@ -5,7 +5,8 @@ import PlaybackSlider from "./../components/video/PlaybackSlider";
import ClipRangeSlider from "./../components/video/ClipRangeSlider";
import ConfigBox from "../components/video/ConfigBox.tsx";
import ExportWidget from "../components/video/ExportWidget.tsx";
import { compress, getJob } from "../utils/endpoints"
import { compress } from "../utils/api/media"
import { getJob } from "../utils/api/jobs"
import type { VideoMetadata } from "../utils/types.ts";
import Box from "../components/Box.tsx";
import MetadataBox from "../components/video/MetadataBox.tsx";
@@ -34,6 +35,7 @@ const ClipEdit = () => {
});
const [progress, setProgress] = useState(0);
const [downloadable, setDownloadable] = useState(false);
const [uploading, setUploading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
@@ -59,7 +61,10 @@ const ClipEdit = () => {
};
const sendData = async () => {
if (!localFile) return;
if (!localFile || uploading) return;
setUploading(true);
setError(null);
let jobId: string;
try {
@@ -67,6 +72,7 @@ const ClipEdit = () => {
setUploadedId(jobId);
} catch (err: unknown) {
setError(`Failed to start compression: ${err instanceof Error ? err.message : 'Unknown error'}`);
setUploading(false);
return;
}
@@ -81,14 +87,17 @@ const ClipEdit = () => {
if (job.state === 'FAILED') {
setError(`Compression failed: ${job.errorOutput ?? 'Unknown error'}`);
clearInterval(intervalId);
setUploading(false);
} else if (job.isComplete) {
clearInterval(intervalId);
setDownloadable(true);
setUploading(false);
}
})
.catch((err: Error) => {
setError(`Failed to fetch progress: ${err.message}`);
clearInterval(intervalId);
setUploading(false);
});
};
@@ -166,6 +175,7 @@ const ClipEdit = () => {
handleDownload={handleDownload}
downloadable={downloadable}
progress={progress}
uploading={uploading}
/>
</Box>
</div>

View File

@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ArrowLeft, Check } from "lucide-react";
import { getClipById, patchClip } from "../utils/endpoints.ts";
import { getClipById, patchClip } from "../utils/api/clips.ts";
import Box from "../components/Box.tsx";
import BlueButton from "../components/buttons/BlueButton.tsx";

View File

@@ -0,0 +1,108 @@
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ArrowLeft, Check } from "lucide-react";
import { getVodById, patchVod } from "../utils/api/vods.ts";
import Box from "../components/Box.tsx";
import BlueButton from "../components/buttons/BlueButton.tsx";
const inputClass = "border border-gray-300 bg-white rounded-md w-full p-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-colors";
const EditVod = () => {
const { id } = useParams();
const navigate = useNavigate();
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
getVodById(id)
.then((vod) => {
if (vod) {
setTitle(vod.title ?? "");
setDescription(vod.description ?? "");
}
})
.catch(() => setError("Failed to load vod."))
.finally(() => setLoading(false));
}, [id]);
const handleSave = async () => {
if (!id) return;
setSaving(true);
setError(null);
try {
await patchVod(Number(id), { title, description });
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to save.");
} finally {
setSaving(false);
}
};
return (
<div className="px-8 py-10 max-w-2xl mx-auto">
<button
onClick={() => navigate(-1)}
className="flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-900 mb-6 transition-colors duration-150"
>
<ArrowLeft size={16} />
Back
</button>
<h1 className="text-2xl font-semibold text-gray-900 mb-6">Edit VoD</h1>
{loading ? (
<div className="text-gray-400 text-sm">Loading...</div>
) : (
<Box className="p-6 flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-gray-700">Title</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Enter title"
className={inputClass}
/>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-gray-700">Description</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Enter description"
rows={4}
className={inputClass + " resize-none"}
/>
</div>
{error && <p className="text-sm text-red-500">{error}</p>}
<div className="flex items-center gap-3 pt-1">
<BlueButton onClick={handleSave} disabled={saving} className="w-28">
{saving ? "Saving…" : saved
? <span className="flex items-center gap-1.5 justify-center"><Check size={14} />Saved</span>
: "Save"}
</BlueButton>
<button
onClick={() => navigate(-1)}
className="text-sm text-gray-500 hover:text-gray-900 transition-colors duration-150"
>
Cancel
</button>
</div>
</Box>
)}
</div>
);
};
export default EditVod;

View File

@@ -1,12 +1,27 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ArrowLeft, Lock, Maximize, Minimize, Pause, Play, Volume1, Volume2, VolumeX } from "lucide-react";
import type { Clip } from "../utils/types";
import { AuthError, getClipById, getVideoBlob } from "../utils/endpoints.ts";
import { AuthError } from "../utils/api/client.ts";
import Box from "../components/Box.tsx";
import { dateToTimeAgo, formatTime, stringToDate } from "../utils/utils.ts";
const VideoPlayer = () => {
// Both VoDs and clips share the same on-screen shape.
type MediaItem = {
title: string,
createdAt: string,
};
type MediaPlayerProps = {
/** Human-readable name for the media, e.g. "VoD" or "clip". Used in messages. */
noun: string,
/** Builds the raw media stream URL for the given id. Loaded directly by the
* <video> element so the browser can issue HTTP Range requests. */
getMediaUrl: (id: string) => string,
/** Fetches the media metadata for the given id. */
fetchDetails: (id: string) => Promise<MediaItem | null>,
};
const MediaPlayer = ({ noun, getMediaUrl, fetchDetails }: MediaPlayerProps) => {
const { id } = useParams();
const navigate = useNavigate();
@@ -16,10 +31,11 @@ const VideoPlayer = () => {
const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Data
const [videoUrl, setVideoUrl] = useState<string | undefined>(undefined);
const mediaUrl = id ? getMediaUrl(id) : undefined;
const [mediaLoaded, setMediaLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notAuthenticated, setNotAuthenticated] = useState(false);
const [clip, setClip] = useState<Clip | null>(null);
const [item, setItem] = useState<MediaItem | null>(null);
const [timeAgo, setTimeAgo] = useState("");
// Playback
@@ -39,28 +55,28 @@ const VideoPlayer = () => {
const [isDragging, setIsDragging] = useState(false);
// ── Data loading ────────────────────────────────────────────────────────
// The video stream itself is loaded by the <video> element from `mediaUrl`,
// which lets the browser fetch it incrementally via Range requests. We only
// need to fetch the metadata here; it shares the media endpoint's auth, so a
// 401/403 here also stands in for the stream being inaccessible.
useEffect(() => {
if (!id) { setError("Clip ID is required."); return; }
if (!id) { setError(`${noun} ID is required.`); return; }
getVideoBlob(id)
.then((blob) => setVideoUrl(URL.createObjectURL(blob)))
.catch((e) => { if (e instanceof AuthError) setNotAuthenticated(true); });
getClipById(id)
.then(setClip)
fetchDetails(id)
.then(setItem)
.catch((e) => {
if (e instanceof AuthError) setNotAuthenticated(true);
else setError("Failed to load clip details.");
else setError(`Failed to load ${noun.toLowerCase()} details.`);
});
}, [id]);
}, [id, noun, fetchDetails]);
useEffect(() => {
if (!clip?.createdAt) return;
const update = () => setTimeAgo(dateToTimeAgo(stringToDate(clip.createdAt)));
if (!item?.createdAt) return;
const update = () => setTimeAgo(dateToTimeAgo(stringToDate(item.createdAt)));
update();
const interval = setInterval(update, 1000);
return () => clearInterval(interval);
}, [clip]);
}, [item]);
// ── Controls visibility ─────────────────────────────────────────────────
const scheduleHide = useCallback(() => {
@@ -191,7 +207,7 @@ const VideoPlayer = () => {
</div>
<div>
<p className="text-lg font-semibold text-gray-900">Not authenticated</p>
<p className="text-sm text-gray-500 mt-1">You don't have access to this clip.</p>
<p className="text-sm text-gray-500 mt-1">You don't have access to this {noun.toLowerCase()}.</p>
</div>
<button
onClick={() => navigate(-1)}
@@ -226,7 +242,10 @@ const VideoPlayer = () => {
<video
ref={videoRef}
className="w-full h-full object-contain"
src={videoUrl}
src={mediaUrl}
// Send auth cookies with the cross-origin Range requests.
crossOrigin="use-credentials"
preload="metadata"
onPlay={() => { setIsPlaying(true); scheduleHide(); }}
onPause={() => {
setIsPlaying(false);
@@ -234,14 +253,17 @@ const VideoPlayer = () => {
if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
}}
onTimeUpdate={handleTimeUpdate}
onLoadedMetadata={() => { if (videoRef.current) setDuration(videoRef.current.duration); }}
onLoadedMetadata={() => {
if (videoRef.current) setDuration(videoRef.current.duration);
setMediaLoaded(true);
}}
onWaiting={() => setIsWaiting(true)}
onCanPlay={() => setIsWaiting(false)}
onError={(e) => setError(e.currentTarget.error?.message || "An error occurred.")}
/>
{/* Buffering spinner */}
{isWaiting && videoUrl && (
{isWaiting && mediaUrl && (
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="w-11 h-11 rounded-full border-[3px] border-white/20 border-t-white animate-spin" />
</div>
@@ -310,7 +332,7 @@ const VideoPlayer = () => {
</div>
{error && <div className="text-red-500 text-sm mt-3">{error}</div>}
{!videoUrl && !error && (
{!mediaLoaded && !error && (
<div className="text-gray-400 text-sm mt-3 flex items-center gap-2">
<div className="w-3 h-3 rounded-full border-2 border-gray-300 border-t-gray-500 animate-spin" />
Loading video...
@@ -318,11 +340,11 @@ const VideoPlayer = () => {
)}
<Box className="p-4 flex-shrink-0">
<p className="text-xl font-semibold text-gray-900">{clip?.title || "(No Title)"}</p>
<p className="text-xl font-semibold text-gray-900">{item?.title || "(No Title)"}</p>
<p className="text-sm text-gray-500 mt-1">{timeAgo}</p>
</Box>
</div>
);
};
export default VideoPlayer;
export default MediaPlayer;

View File

@@ -1,7 +1,7 @@
import VideoCard from "../components/video/VideoCard";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { getClips, deleteClip } from "../utils/endpoints";
import { getClips, deleteClip } from "../utils/api/clips";
import type { Clip } from "../utils/types";
const MyClips = () => {

View File

@@ -0,0 +1,60 @@
import VideoCard from "../components/video/VideoCard";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { getVods, deleteVod } from "../utils/api/vods";
import type { Vod } from "../utils/types";
const MyVods = () => {
const [vods, setVods] = useState<Vod[]>([]);
const [error, setError] = useState<null | string>(null);
const navigate = useNavigate();
useEffect(() => {
getVods()
.then((data) => setVods(data.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())))
.catch((err) => setError(err instanceof Error ? err.message : "Failed to load vods"));
}, []);
const handleDelete = async (id: number) => {
try {
await deleteVod(id);
setVods(prev => prev.filter(v => v.id !== id));
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to delete vod");
}
};
return (
<div className="p-6">
<h1 className="text-2xl font-semibold text-gray-900 mb-6">My VoDs</h1>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
{vods.map((vod) => (
<VideoCard
key={vod.id}
id={vod.id}
title={vod.title}
duration={vod.duration}
createdAt={vod.createdAt}
mediaApiPath="/api/v1/vods"
playerPath="/vod"
itemLabel="vod"
onEdit={() => navigate(`/vods/${vod.id}/edit`)}
onDelete={() => handleDelete(vod.id)}
/>
))}
</div>
{vods.length === 0 && !error && (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<p className="text-base">No VoDs yet.</p>
<p className="text-sm mt-1">Your stream recordings will appear here.</p>
</div>
)}
{error && <p className="text-sm text-red-500 mt-4">{error}</p>}
</div>
);
};
export default MyVods;

View File

@@ -1,7 +1,7 @@
import { useState, useEffect } from "react";
import { Eye, EyeOff, Copy, Check } from "lucide-react";
import Box from "../components/Box.tsx";
import { getUser } from "../utils/endpoints.ts";
import { getUser } from "../utils/api/users.ts";
import type { User } from "../utils/types.ts";
import { formatLocalDate } from "../utils/utils.ts";

View File

@@ -0,0 +1,399 @@
import { useEffect, useState } from "react";
import { Radio, Check, Bookmark, Scissors, Film, Activity, Loader2, X } from "lucide-react";
import clsx from "clsx";
import Box from "../components/Box.tsx";
import BlueButton from "../components/buttons/BlueButton.tsx";
import { getUser } from "../utils/api/users.ts";
import { getCurrentStream, getStreamHistory } from "../utils/api/stream.ts";
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 { User, StreamStatus, StreamHistoryItem, Marker, JobResponse } from "../utils/types.ts";
import { formatTime, formatLocalDate, stringToDate } from "../utils/utils.ts";
const inputClass = "border border-gray-300 bg-white rounded-md w-full p-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-colors";
const labelClass = "text-xs font-medium text-gray-500 uppercase tracking-wide";
type TrackedJob = {
uuid: string;
label: string;
progress: number;
state: JobResponse['state'];
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-primary/10" : "bg-accent/10")}>
<Icon size={16} className={accent === "primary" ? "text-primary" : "text-accent"} />
</div>
<h2 className="text-sm font-semibold text-gray-800">{title}</h2>
</div>
);
const JobStatus = ({ job }: { job: TrackedJob }) => {
if (job.state === 'FAILED') {
return (
<div className="flex items-start gap-2 text-sm">
<X size={15} className="text-red-500 mt-0.5 flex-shrink-0" />
<p className="text-red-500">{job.label} failed: {job.errorOutput ?? "Unknown error"}</p>
</div>
);
}
if (job.state === 'SUCCEEDED') {
return (
<div className="flex items-center gap-2 text-sm">
<Check size={15} className="text-green-600 flex-shrink-0" />
<p className="text-gray-700">{job.label} saved</p>
</div>
);
}
return (
<div className="flex items-center gap-2">
<Loader2 size={15} className="text-primary animate-spin flex-shrink-0" />
<div className="flex-1">
<p className="text-sm text-gray-600 mb-1">{job.label}…</p>
<progress value={job.progress} className="w-full h-1.5 rounded bg-gray-200" />
</div>
</div>
);
};
const StreamControl = () => {
const [user, setUser] = useState<User | null>(null);
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);
const [clipTitle, setClipTitle] = useState("");
const [clipDescription, setClipDescription] = useState("");
const [clipError, setClipError] = useState<string | null>(null);
const [startMarkerId, setStartMarkerId] = useState<string>("");
const [endMarkerId, setEndMarkerId] = useState<string>("");
const [markerSaveTitle, setMarkerSaveTitle] = useState("");
const [markerSaveDescription, setMarkerSaveDescription] = useState("");
const [markerSaveError, setMarkerSaveError] = useState<string | null>(null);
const [jobs, setJobs] = useState<TrackedJob[]>([]);
const isStreaming = streamStatus?.isStreaming ?? false;
useEffect(() => {
getUser().then(setUser).catch(() => setUser(null));
}, []);
useEffect(() => {
if (!user) return;
const poll = () => getCurrentStream().then(setStreamStatus).catch(() => {});
poll();
const interval = setInterval(poll, 5000);
return () => clearInterval(interval);
}, [user]);
useEffect(() => {
if (!user || !streamStatus?.id) {
setStreamDetails(null);
return;
}
getStreamHistory(user.id)
.then((history) => setStreamDetails(history.find((s) => s.id === streamStatus.id) ?? null))
.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())))
.catch(() => {});
};
useEffect(() => {
if (!isStreaming) {
setMarkers([]);
return;
}
refreshMarkers();
const interval = setInterval(refreshMarkers, 5000);
return () => clearInterval(interval);
}, [isStreaming, streamStatus?.id]);
useEffect(() => {
const pending = jobs.filter((j) => j.state !== 'SUCCEEDED' && j.state !== 'FAILED');
if (pending.length === 0) return;
const interval = setInterval(() => {
pending.forEach((job) => {
getJob(job.uuid)
.then((result) => {
setJobs((prev) => prev.map((j) => j.uuid === job.uuid
? { ...j, progress: result.progress, state: result.state, errorOutput: result.errorOutput }
: j));
})
.catch(() => {});
});
}, 1000);
return () => clearInterval(interval);
}, [jobs]);
const addJob = (uuid: string, label: string) => {
setJobs((prev) => [{ uuid, label, progress: 0, state: 'READY', errorOutput: null }, ...prev]);
};
const handleAddMarker = async () => {
if (!markerMessage.trim() || markerBusy) return;
setMarkerBusy(true);
setMarkerError(null);
try {
await createMarker(markerMessage.trim());
setMarkerMessage("");
refreshMarkers();
} catch (err) {
setMarkerError(err instanceof Error ? err.message : "Failed to add marker");
} finally {
setMarkerBusy(false);
}
};
const handleClip = async () => {
setClipError(null);
try {
const uuid = await clipSection(clipDuration, clipTitle || undefined, clipDescription || undefined);
addJob(uuid, `Clip (last ${clipDuration}s)`);
setClipTitle("");
setClipDescription("");
} catch (err) {
setClipError(err instanceof Error ? err.message : "Failed to clip section");
}
};
const handleSaveByMarkers = async () => {
setMarkerSaveError(null);
if (!startMarkerId || !endMarkerId) {
setMarkerSaveError("Tap two markers above to pick a start and end");
return;
}
try {
const uuid = await saveSectionByMarkers(
Number(startMarkerId),
Number(endMarkerId),
markerSaveTitle || undefined,
markerSaveDescription || undefined
);
addJob(uuid, "Save (by markers)");
setStartMarkerId("");
setEndMarkerId("");
setMarkerSaveTitle("");
setMarkerSaveDescription("");
} catch (err) {
setMarkerSaveError(err instanceof Error ? err.message : "Failed to save section");
}
};
const handleDeleteMarker = async (id: number) => {
try {
await deleteMarker(id);
if (startMarkerId === String(id)) setStartMarkerId("");
if (endMarkerId === String(id)) setEndMarkerId("");
refreshMarkers();
} catch (err) {
setMarkerError(err instanceof Error ? err.message : "Failed to delete marker");
}
};
const handleChipClick = (id: number) => {
const idStr = String(id);
setMarkerSaveError(null);
if (startMarkerId === idStr) { setStartMarkerId(""); return; }
if (endMarkerId === idStr) { setEndMarkerId(""); return; }
if (!startMarkerId) { setStartMarkerId(idStr); return; }
if (!endMarkerId) { setEndMarkerId(idStr); return; }
setEndMarkerId(idStr);
};
if (!user) {
return (
<div className="flex justify-center items-center h-full text-gray-400 text-base">
Please log in to control your stream.
</div>
);
}
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);
return (
<div className="px-8 py-10 max-w-5xl mx-auto flex flex-col gap-5">
<h1 className="text-2xl font-semibold text-gray-900">Stream Control</h1>
{/* Hero status bar */}
<Box className={clsx(
"p-6 flex items-center justify-between gap-6 border-l-4",
isStreaming ? "border-l-red-500" : "border-l-gray-200"
)}>
<div className="flex items-center gap-3.5">
<span className="relative flex h-3.5 w-3.5">
{isStreaming && <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-500 opacity-75" />}
<span className={clsx("relative inline-flex rounded-full h-3.5 w-3.5", isStreaming ? "bg-red-500" : "bg-gray-300")} />
</span>
<div>
<p className="font-semibold text-gray-900 text-lg leading-tight">{isStreaming ? "Live" : "Offline"}</p>
{isStreaming && streamDetails?.startDate ? (
<p className="text-sm text-gray-500">Started {formatLocalDate(streamDetails.startDate)}</p>
) : !isStreaming ? (
<p className="text-sm text-gray-500">Point OBS at your stream key (see Profile) to go live.</p>
) : null}
</div>
</div>
{isStreaming && elapsed ? (
<div className="text-right">
<p className="text-2xl font-mono font-semibold text-gray-900 tabular-nums">{elapsed}</p>
<p className="text-xs text-gray-400 uppercase tracking-wide">elapsed</p>
</div>
) : (
<Radio size={28} className="text-gray-200" />
)}
</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-accent 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}
/>
<BlueButton onClick={handleAddMarker} disabled={markerBusy || !markerMessage.trim()} className="whitespace-nowrap">
Add Marker
</BlueButton>
</div>
{markerError && <p className="text-sm text-red-500">{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-primary bg-primary/5 ring-1 ring-primary",
isEnd && "border-accent bg-accent/5 ring-1 ring-accent",
!isStart && !isEnd && "border-gray-200 hover:border-gray-300 hover:bg-gray-50"
)}
>
<span className="text-xs font-medium text-gray-800 max-w-40 truncate">{m.message}</span>
<span className="text-[11px] text-gray-400">
{formatLocalDate(m.timestamp, { hour: "2-digit", minute: "2-digit", second: "2-digit" })}
{isStart && <span className="text-primary font-medium"> · start</span>}
{isEnd && <span className="text-accent 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-gray-400 hover:bg-red-500 text-white transition-colors duration-150"
>
<X size={10} />
</button>
</div>
);
})}
</div>
)}
</Box>
{/* 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-red-500">{clipError}</p>}
<BlueButton onClick={handleClip} className="self-start mt-auto">Clip</BlueButton>
</Box>
<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-gray-400">Add at least two markers above to save a section between them.</p>
) : (
<>
<div className="flex items-center gap-2 flex-wrap">
<span className={clsx(
"text-xs font-medium px-2.5 py-1 rounded-full border",
startMarker ? "border-primary text-primary bg-primary/5" : "border-dashed border-gray-300 text-gray-400"
)}>
{startMarker ? startMarker.message : "Tap a marker to set start"}
</span>
<span className="text-gray-300">→</span>
<span className={clsx(
"text-xs font-medium px-2.5 py-1 rounded-full border",
endMarker ? "border-accent text-accent bg-accent/5" : "border-dashed border-gray-300 text-gray-400"
)}>
{endMarker ? endMarker.message : "Tap a marker to set end"}
</span>
</div>
<input type="text" placeholder="Title" value={markerSaveTitle} onChange={(e) => setMarkerSaveTitle(e.target.value)} className={inputClass} />
<textarea placeholder="Description" value={markerSaveDescription} onChange={(e) => setMarkerSaveDescription(e.target.value)} rows={2} className={inputClass + " resize-none"} />
{markerSaveError && <p className="text-sm text-red-500">{markerSaveError}</p>}
</>
)}
<BlueButton onClick={handleSaveByMarkers} disabled={markers.length < 2} className="self-start mt-auto">Save</BlueButton>
</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-gray-400">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>
);
};
export default StreamControl;

View File

@@ -0,0 +1,12 @@
const API_URL = import.meta.env.VITE_API_URL;
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;
};
export { API_URL, AuthError, isThumbnailAvailable };

View File

@@ -0,0 +1,61 @@
import type { APIResponse, Clip } from "../types.ts";
import { API_URL, AuthError } from "./client.ts";
const getClips = async (): Promise<Clip[]> => {
const response = await fetch(API_URL + '/api/v1/clips', { credentials: 'include' });
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' });
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;
};
// URL for the raw media stream. The <video> element loads this directly so the
// browser can issue HTTP Range requests (progressive loading + seeking) instead
// of downloading the whole file up front.
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}`, {
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}`);
};
export { getClips, getClipById, getClipMediaUrl, patchClip, deleteClip };

View File

@@ -0,0 +1,15 @@
import type { APIResponse, JobResponse } from "../types.ts";
import { API_URL } 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();
if (result.status === 'error') throw new Error(`Failed to fetch job: ${result.message}`);
return result.data;
};
export { getJob };

View File

@@ -0,0 +1,40 @@
import type { APIResponse, Marker } from "../types.ts";
import { API_URL } 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();
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', {
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}`);
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}`);
};
export { getMarkers, createMarker, deleteMarker };

View File

@@ -0,0 +1,72 @@
import type { APIResponse, VideoMetadata } from "../types.ts";
import { API_URL } from "./client.ts";
const compress = async (file: File, options: VideoMetadata): Promise<string> => {
const formData = new FormData();
formData.append('file', file);
formData.append('title', options.title);
if (options.description) formData.append('description', options.description);
formData.append('startPoint', options.startPoint.toString());
formData.append('duration', options.duration.toString());
if (options.fps) formData.append('fps', options.fps.toString());
if (options.width) formData.append('width', options.width.toString());
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', {
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', {
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}`);
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', {
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}`);
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', {
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}`);
return result.data.uuid;
};
export { compress, saveSection, saveSectionByMarkers, clipSection };

View File

@@ -0,0 +1,31 @@
import type { APIResponse, StreamHistoryItem, StreamStatus } from "../types.ts";
import { API_URL } 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;
};
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();
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();
if (result.status === 'error') throw new Error(`Failed to fetch stream history: ${result.message}`);
return result.data;
};
export { getStreamStatus, getCurrentStream, getStreamHistory };

View File

@@ -0,0 +1,42 @@
import type { APIResponse, User } from "../types.ts";
import { API_URL } from "./client.ts";
const login = async (googleToken: string): Promise<string> => {
const response = await fetch(API_URL + '/api/v1/users/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: googleToken }),
credentials: 'include',
});
if (!response.ok) throw new Error(`Login failed: ${response.status}`);
const result: APIResponse = await response.json();
if (result.status === 'error') throw new Error(`Login failed: ${result.message}`);
return result.data.token;
};
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 getUser = async (): Promise<User | null> => {
const response = await fetch(API_URL + '/api/v1/users/me', { credentials: 'include' });
if (!response.ok) return null;
const result: APIResponse = await response.json();
if (result.status === 'error') return null;
return result.data;
};
export { login, logout, getUser };

View File

@@ -0,0 +1,61 @@
import type { APIResponse, Vod } from "../types.ts";
import { API_URL, AuthError } from "./client.ts";
const getVods = async (): Promise<Vod[]> => {
const response = await fetch(API_URL + '/api/v1/vods', { credentials: 'include' });
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' });
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;
};
// URL for the raw media stream. The <video> element loads this directly so the
// browser can issue HTTP Range requests (progressive loading + seeking) instead
// of downloading the whole file up front.
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}`, {
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}`);
};
export { getVods, getVodById, getVodMediaUrl, patchVod, deleteVod };

View File

@@ -1,172 +0,0 @@
import type { VideoMetadata, APIResponse, User, Clip, JobResponse } from "./types.ts";
const API_URL = import.meta.env.VITE_API_URL;
export class AuthError extends Error {
constructor() { super("Not authenticated"); this.name = "AuthError"; }
}
const login = async (googleToken: string): Promise<string> => {
const response = await fetch(API_URL + '/api/v1/users/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: googleToken }),
credentials: 'include',
});
if (!response.ok) throw new Error(`Login failed: ${response.status}`);
const result: APIResponse = await response.json();
if (result.status === 'error') throw new Error(`Login failed: ${result.message}`);
return result.data.token;
};
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 compress = async (file: File, options: VideoMetadata): Promise<string> => {
const formData = new FormData();
formData.append('file', file);
formData.append('title', options.title);
if (options.description) formData.append('description', options.description);
formData.append('startPoint', options.startPoint.toString());
formData.append('duration', options.duration.toString());
if (options.fps) formData.append('fps', options.fps.toString());
if (options.width) formData.append('width', options.width.toString());
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', {
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 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();
if (result.status === 'error') throw new Error(`Failed to fetch job: ${result.message}`);
return result.data;
};
const getUser = async (): Promise<User | null> => {
const response = await fetch(API_URL + '/api/v1/users/me', { credentials: 'include' });
if (!response.ok) return null;
const result: APIResponse = await response.json();
if (result.status === 'error') return null;
return result.data;
};
const getClips = async (): Promise<Clip[]> => {
const response = await fetch(API_URL + '/api/v1/clips', { credentials: 'include' });
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' });
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;
};
const getVideoBlob = async (id: string): Promise<Blob> => {
const response = await fetch(API_URL + `/api/v1/clips/${id}/media`, { credentials: 'include' });
if (!response.ok) {
if (response.status === 401 || response.status === 403) throw new AuthError();
throw new Error(`Failed to fetch video ${id}: ${response.status}`);
}
return response.blob();
};
const patchClip = async (id: number, data: { title?: string; description?: string }): Promise<Clip> => {
const response = await fetch(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 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;
};
const isThumbnailAvailable = async (id: number): Promise<boolean> => {
const response = await fetch(API_URL + `/api/v1/clips/${id}/thumbnail`, { credentials: 'include' });
return response.ok;
};
export {
login,
logout,
compress,
getJob,
getUser,
getClips,
getClipById,
getVideoBlob,
patchClip,
deleteClip,
getStreamStatus,
isThumbnailAvailable,
};

View File

@@ -16,6 +16,7 @@ type APIResponse = {
}
type User = {
id: number,
name: string,
username: string,
email: string,
@@ -33,6 +34,15 @@ type Clip = {
createdAt: string,
}
type Vod = {
id: number,
userId: number,
title: string,
description: string,
duration: number,
createdAt: string,
}
type JobResponse = {
uuid: string,
progress: number,
@@ -42,10 +52,34 @@ type JobResponse = {
createdAt: string,
};
type StreamStatus = {
isStreaming: boolean,
id: number | null,
}
type StreamHistoryItem = {
id: number,
startDate: string | null,
endDate: string | null,
lastSeen: string | null,
}
type Marker = {
id: number,
userId: number,
streamId: number,
message: string,
timestamp: string,
}
export type {
APIResponse,
VideoMetadata,
User,
Clip,
JobResponse
Vod,
JobResponse,
StreamStatus,
StreamHistoryItem,
Marker
}

View File

@@ -1,11 +1,12 @@
import { defineConfig } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import flowbiteReact from "flowbite-react/plugin/vite";
export default defineConfig(({ mode }) => { // change to function form
const env = loadEnv(mode, process.cwd(), '') // load all env vars
// https://vite.dev/config/
export default defineConfig({
return {
plugins: [react(), tailwindcss(), flowbiteReact()],
preview: {
port: 5173,
@@ -15,7 +16,8 @@ export default defineConfig({
port: 5173,
strictPort: true,
host: true,
origin: "http://0.0.0.0:5173",
origin: env.VITE_FRONTEND_URL || "http://0.0.0.0:5173", // use it here
allowedHosts: true,
proxy: {
'/api/v1': {
target: 'http://localhost:8080',
@@ -24,4 +26,5 @@ export default defineConfig({
}
}
}
}
})

50
mvnw vendored
View File

@@ -19,7 +19,7 @@
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
@@ -105,14 +105,17 @@ trim() {
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
@@ -130,7 +133,7 @@ maven-mvnd-*bin.*)
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
@@ -227,7 +230,7 @@ if [ -n "${distributionSha256Sum-}" ]; then
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
@@ -252,8 +255,41 @@ if command -v unzip >/dev/null; then
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

56
mvnw.cmd vendored
View File

@@ -19,7 +19,7 @@
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@@ -40,7 +40,7 @@
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
@@ -73,16 +73,30 @@ switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
@@ -134,7 +148,33 @@ if ($distributionSha256Sum) {
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {

View File

@@ -1,6 +1,9 @@
FROM tiangolo/nginx-rtmp
RUN apt-get update && apt-get install -y gettext-base && rm -rf /var/lib/apt/lists/*
RUN apt-get update && \
apt-get install -y --no-install-recommends gettext-base && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
COPY default.conf.template /etc/nginx/templates/default.conf.template
COPY docker-entrypoint.sh /docker-entrypoint.sh

View File

@@ -20,7 +20,7 @@ rtmp {
hls_path /stream;
hls_fragment_naming system;
hls_fragment 3;
hls_playlist_length 28800;
hls_playlist_length ${STREAM_RING_LENGTH_SECOND};
on_publish ${WEB_SERVER_URL}/api/v1/stream/start;
on_publish_done ${WEB_SERVER_URL}/api/v1/stream/stop;

View File

@@ -1,7 +1,7 @@
#!/bin/sh
# must only run on certain env files, otherwise it replaces too much
envsubst '${WEB_SERVER_URL}' \
envsubst '${WEB_SERVER_URL} ${STREAM_RING_LENGTH_SECOND}' \
< /etc/nginx/templates/default.conf.template \
> /etc/nginx/nginx.conf

View File

@@ -85,6 +85,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@@ -2,19 +2,17 @@
FROM maven:3.9.6-eclipse-temurin-21 AS builder
WORKDIR /app
COPY pom.xml .
RUN --mount=type=cache,target=/root/.m2 mvn dependency:go-offline -B
COPY src ./src
RUN mvn clean package -DskipTests
RUN --mount=type=cache,target=/root/.m2 mvn clean package -DskipTests -B
# Run stage
FROM eclipse-temurin:21-jdk
FROM eclipse-temurin:21-jre
# dependencies
RUN apt-get update && \
apt-get install -y ffmpeg && \
apt-get install -y --no-install-recommends ffmpeg && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
EXPOSE 8080

View File

@@ -12,8 +12,8 @@ import org.springframework.http.MediaTypeFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/v1/clips")
@@ -43,12 +43,8 @@ public class ClipController {
@GetMapping("/{id}")
public ResponseEntity<APIResponse<ClipResponse>> getClipById(@PathVariable Long id) {
Optional<Clip> clip = clipService.getClipById(id);
if (clip.isEmpty()) {
return ResponseEntity.notFound().build();
}
ClipResponse clipDTO = convertToDTO(clip.get());
Clip clip = clipService.getClipById(id);
ClipResponse clipDTO = convertToDTO(clip);
return ResponseEntity.ok(
new APIResponse<>(SUCCESS,
@@ -71,9 +67,7 @@ public class ClipController {
@DeleteMapping("/{id}")
public ResponseEntity<APIResponse<String>> deleteClip(@PathVariable Long id) {
if (!clipService.deleteClip(id)) {
return ResponseEntity.notFound().build();
}
clipService.deleteClip(id);
return ResponseEntity.ok(
new APIResponse<>(
@@ -84,8 +78,8 @@ public class ClipController {
);
}
@GetMapping("/{id}/media")
public ResponseEntity<Resource> downloadClip(@PathVariable Long id) {
@GetMapping(value = "/{id}/media", produces = MediaType.ALL_VALUE)
public ResponseEntity<Resource> downloadClip(@PathVariable Long id) throws IOException {
Resource resource = clipService.downloadClip(id);
if (resource == null || !resource.exists()) {
@@ -93,8 +87,11 @@ public class ClipController {
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, String.format(FILENAME_HEADER, resource.getFilename()))
.contentType(MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM))
.header(HttpHeaders.CONTENT_DISPOSITION,
String.format(FILENAME_HEADER, resource.getFilename()))
.contentType(MediaTypeFactory.getMediaType(resource)
.orElse(MediaType.APPLICATION_OCTET_STREAM))
.contentLength(resource.contentLength())
.body(resource);
}

View File

@@ -94,4 +94,46 @@ public class GlobalExceptionHandler {
APIResponse<Void> response = new APIResponse<>(ERROR, "Could not process file", null);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
@ExceptionHandler(ClipNotFound.class)
public ResponseEntity<APIResponse<Void>> handleClipNotFound(ClipNotFound ex) {
logger.error("ClipNotFound: {}", ex.getMessage());
APIResponse<Void> response = new APIResponse<>(ERROR, ex.getMessage(), null);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}
@ExceptionHandler(ClipMediaUnavailable.class)
public ResponseEntity<APIResponse<Void>> handleClipMediaUnavailable(ClipMediaUnavailable ex) {
logger.error("ClipMediaUnavailable (clip {}): {}", ex.getClipId(), ex.getMessage());
APIResponse<Void> response = new APIResponse<>(ERROR, "Clip media is currently unavailable", null);
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(response);
}
@ExceptionHandler(VodNotFound.class)
public ResponseEntity<APIResponse<Void>> handleVodNotFound(VodNotFound ex) {
logger.error("VodNotFound: {}", ex.getMessage());
APIResponse<Void> response = new APIResponse<>(ERROR, ex.getMessage(), null);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}
@ExceptionHandler(VodMediaUnavailable.class)
public ResponseEntity<APIResponse<Void>> handleVodMediaUnavailable(VodMediaUnavailable ex) {
logger.error("VodMediaUnavailable (vod {}): {}", ex.getVodId(), ex.getMessage());
APIResponse<Void> response = new APIResponse<>(ERROR, "Vod media is currently unavailable", null);
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(response);
}
@ExceptionHandler(NotStreaming.class)
public ResponseEntity<APIResponse<Void>> handleNotStreaming(NotStreaming ex) {
logger.error("NotStreaming: {}", ex.getMessage());
APIResponse<Void> response = new APIResponse<>(ERROR, ex.getMessage(), null);
return ResponseEntity.status(HttpStatus.CONFLICT).body(response);
}
@ExceptionHandler(MarkerNotFound.class)
public ResponseEntity<APIResponse<Void>> handleMarkerNotFound(MarkerNotFound ex) {
logger.error("MarkerNotFound: {}", ex.getMessage());
APIResponse<Void> response = new APIResponse<>(ERROR, ex.getMessage(), null);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}
}

View File

@@ -0,0 +1,72 @@
package com.ddf.vodsystem.controllers;
import com.ddf.vodsystem.controllers.dto.MarkerCreateRequest;
import com.ddf.vodsystem.controllers.dto.MarkerResponse;
import com.ddf.vodsystem.dto.APIResponse;
import com.ddf.vodsystem.entities.Marker;
import com.ddf.vodsystem.services.MarkerService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/markers")
public class MarkerController {
private static final String SUCCESS = "success";
private final MarkerService markerService;
public MarkerController(MarkerService markerService) {
this.markerService = markerService;
}
@GetMapping("")
public ResponseEntity<APIResponse<List<MarkerResponse>>> getMarkers() {
List<MarkerResponse> markers = markerService.getUserMarkers().stream()
.map(this::convertToDTO)
.toList();
return ResponseEntity.ok(
new APIResponse<>(SUCCESS, "Markers retrieved successfully", markers)
);
}
@GetMapping("/{id}")
public ResponseEntity<APIResponse<MarkerResponse>> getMarkerById(@PathVariable Long id) {
Marker marker = markerService.getMarkerById(id);
return ResponseEntity.ok(
new APIResponse<>(SUCCESS, "Marker retrieved successfully", convertToDTO(marker))
);
}
@PostMapping("")
public ResponseEntity<APIResponse<MarkerResponse>> createMarker(@Valid @RequestBody MarkerCreateRequest request) {
Marker marker = markerService.create(request.message());
return ResponseEntity.ok(
new APIResponse<>(SUCCESS, "Marker created successfully", convertToDTO(marker))
);
}
@DeleteMapping("/{id}")
public ResponseEntity<APIResponse<String>> deleteMarker(@PathVariable Long id) {
markerService.deleteMarker(id);
return ResponseEntity.ok(
new APIResponse<>(SUCCESS, "Marker deleted successfully", "Marker " + id + " deleted.")
);
}
private MarkerResponse convertToDTO(Marker marker) {
return new MarkerResponse(
marker.getId(),
marker.getUser().getId(),
marker.getStream().getId(),
marker.getMessage(),
marker.getTimestamp()
);
}
}

View File

@@ -1,6 +1,7 @@
package com.ddf.vodsystem.controllers;
import com.ddf.vodsystem.controllers.dto.ClipSectionRequest;
import com.ddf.vodsystem.controllers.dto.SaveSectionByMarkerRequest;
import com.ddf.vodsystem.controllers.dto.SaveSectionRequest;
import com.ddf.vodsystem.controllers.dto.UUIDResponse;
import com.ddf.vodsystem.dto.Job;
@@ -29,7 +30,7 @@ public class MediaController {
public ResponseEntity<APIResponse<UUIDResponse>> compress(
@RequestParam("file")MultipartFile file,
@Valid @ModelAttribute ClipOptions options
) throws IOException, InterruptedException {
) throws IOException {
Job job = mediaService.compress(file, options);
return ResponseEntity.ok(new APIResponse<>(
SUCCESS,
@@ -42,7 +43,26 @@ public class MediaController {
@PostMapping("/save")
public ResponseEntity<APIResponse<UUIDResponse>> save(
@RequestBody SaveSectionRequest saveSectionRequest) throws IOException {
Job job = mediaService.saveSection(saveSectionRequest.startTime(), saveSectionRequest.endTime());
Job job = mediaService.saveSection(
saveSectionRequest.startTime(),
saveSectionRequest.endTime(),
saveSectionRequest.title(),
saveSectionRequest.description());
return ResponseEntity.ok(new APIResponse<>(
SUCCESS,
"Section saving successfully started",
new UUIDResponse(job.getUuid())
));
}
@PostMapping("/save/markers")
public ResponseEntity<APIResponse<UUIDResponse>> saveByMarkers(
@Valid @RequestBody SaveSectionByMarkerRequest saveSectionByMarkerRequest) throws IOException {
Job job = mediaService.saveSection(
saveSectionByMarkerRequest.startMarkerId(),
saveSectionByMarkerRequest.endMarkerId(),
saveSectionByMarkerRequest.title(),
saveSectionByMarkerRequest.description());
return ResponseEntity.ok(new APIResponse<>(
SUCCESS,
"Section saving successfully started",
@@ -53,7 +73,11 @@ public class MediaController {
@PostMapping("/clip")
public ResponseEntity<APIResponse<UUIDResponse>> clip(
@RequestBody ClipSectionRequest clipSectionRequest) throws IOException {
Job job = mediaService.clip(clipSectionRequest.duration());
Job job = mediaService.clip(
clipSectionRequest.duration(),
clipSectionRequest.title(),
clipSectionRequest.description()
);
return ResponseEntity.ok(new APIResponse<>(
SUCCESS,
"Clipping successfully started",

View File

@@ -6,6 +6,7 @@ import com.ddf.vodsystem.entities.User;
import com.ddf.vodsystem.exceptions.NotAuthenticated;
import com.ddf.vodsystem.services.UserService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
@@ -41,14 +42,15 @@ public class UserController {
@PostMapping("/login")
public ResponseEntity<APIResponse<Token>> login(@RequestBody Token token,
HttpServletRequest request,
HttpServletResponse response) {
String jwt = userService.login(token.token());
ResponseCookie cookie = ResponseCookie.from("token", jwt)
.httpOnly(true)
.maxAge(jwtExpiration / 1000)
.sameSite("None")
.secure(true)
.sameSite(request.isSecure() ? "None" : "Lax")
.secure(request.isSecure())
.path("/")
.build();
@@ -60,12 +62,13 @@ public class UserController {
}
@PostMapping("/logout")
public ResponseEntity<APIResponse<Void>> logout(HttpServletResponse response) {
public ResponseEntity<APIResponse<Void>> logout(HttpServletResponse response,
HttpServletRequest request) {
ResponseCookie cookie = ResponseCookie.from("token", "")
.httpOnly(true)
.maxAge(0)
.sameSite("None")
.secure(true)
.sameSite(request.isSecure() ? "None" : "Lax")
.secure(request.isSecure())
.path("/")
.build();

View File

@@ -0,0 +1,99 @@
package com.ddf.vodsystem.controllers;
import com.ddf.vodsystem.controllers.dto.VodResponse;
import com.ddf.vodsystem.controllers.dto.VodUpdateRequest;
import com.ddf.vodsystem.dto.APIResponse;
import com.ddf.vodsystem.entities.Vod;
import com.ddf.vodsystem.services.VodService;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/api/v1/vods")
public class VodController {
private final VodService vodService;
private static final String SUCCESS = "success";
private static final String FILENAME_HEADER = "inline; filename=\"%s\"";
public VodController(VodService vodService) {
this.vodService = vodService;
}
@GetMapping("")
public ResponseEntity<APIResponse<List<VodResponse>>> getVods() {
List<VodResponse> vods = vodService.getUserVods().stream()
.map(this::convertToDTO)
.toList();
return ResponseEntity.ok(new APIResponse<>(SUCCESS, "Vods retrieved successfully", vods));
}
@GetMapping("/{id}")
public ResponseEntity<APIResponse<VodResponse>> getVodById(@PathVariable Long id) {
VodResponse vod = convertToDTO(vodService.getVodById(id));
return ResponseEntity.ok(new APIResponse<>(SUCCESS, "Vod retrieved successfully", vod));
}
@PatchMapping("/{id}")
public ResponseEntity<APIResponse<VodResponse>> updateVod(@PathVariable Long id,
@RequestBody VodUpdateRequest updateFields) {
VodResponse vod = convertToDTO(vodService.updateVod(id, updateFields));
return ResponseEntity.ok(new APIResponse<>(SUCCESS, "Vod updated successfully", vod));
}
@DeleteMapping("/{id}")
public ResponseEntity<APIResponse<String>> deleteVod(@PathVariable Long id) {
vodService.deleteVod(id);
return ResponseEntity.ok(new APIResponse<>(SUCCESS, "Vod deleted successfully",
"Vod with ID " + id + " has been deleted"));
}
@GetMapping(value = "/{id}/media", produces = MediaType.ALL_VALUE)
public ResponseEntity<Resource> downloadVod(@PathVariable Long id) throws IOException {
Resource resource = vodService.downloadVod(id);
if (resource == null || !resource.exists()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
String.format(FILENAME_HEADER, resource.getFilename()))
.contentType(MediaTypeFactory.getMediaType(resource)
.orElse(MediaType.APPLICATION_OCTET_STREAM))
.contentLength(resource.contentLength())
.body(resource);
}
@GetMapping("/{id}/thumbnail")
public ResponseEntity<Resource> downloadThumbnail(@PathVariable Long id) {
Resource resource = vodService.downloadThumbnail(id);
if (resource == null || !resource.exists()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, String.format(FILENAME_HEADER, resource.getFilename()))
.contentType(MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM))
.body(resource);
}
private VodResponse convertToDTO(Vod vod) {
return new VodResponse(
vod.getId(),
vod.getUser().getId(),
vod.getTitle(),
vod.getDescription(),
vod.getDuration(),
vod.getCreatedAt()
);
}
}

View File

@@ -3,5 +3,7 @@ package com.ddf.vodsystem.controllers.dto;
import jakarta.validation.constraints.NotNull;
public record ClipSectionRequest(
@NotNull float duration
@NotNull float duration,
String title,
String description
) {}

View File

@@ -0,0 +1,7 @@
package com.ddf.vodsystem.controllers.dto;
import jakarta.validation.constraints.NotBlank;
public record MarkerCreateRequest(
@NotBlank String message
) {}

View File

@@ -0,0 +1,11 @@
package com.ddf.vodsystem.controllers.dto;
import java.time.Instant;
public record MarkerResponse(
Long id,
Long userId,
Long streamId,
String message,
Instant timestamp
) {}

View File

@@ -0,0 +1,9 @@
package com.ddf.vodsystem.controllers.dto;
import jakarta.validation.constraints.NotNull;
public record SaveSectionByMarkerRequest(
@NotNull Long startMarkerId,
@NotNull Long endMarkerId,
String title,
String description) {}

View File

@@ -5,4 +5,6 @@ import jakarta.validation.constraints.NotNull;
public record SaveSectionRequest(
@NotNull Instant startTime,
@NotNull Instant endTime) {}
@NotNull Instant endTime,
String title,
String description) {}

View File

@@ -0,0 +1,12 @@
package com.ddf.vodsystem.controllers.dto;
import java.time.Instant;
public record VodResponse(
Long id,
Long userId,
String title,
String description,
Float duration,
Instant createdAt
) {}

View File

@@ -0,0 +1,6 @@
package com.ddf.vodsystem.controllers.dto;
public record VodUpdateRequest(
String title,
String description
) {}

View File

@@ -27,5 +27,5 @@ public class ClipOptions {
private Integer height;
@Positive
private Float fileSize;
private Long fileSize;
}

View File

@@ -43,7 +43,7 @@ public class Clip {
private Float duration;
@Column(name = "file_size", nullable = false)
private Float fileSize;
private Long fileSize;
@Column(name = "video_path", nullable = false, length = 255)
private String videoPath;

View File

@@ -0,0 +1,33 @@
package com.ddf.vodsystem.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Data;
import java.time.Instant;
@Entity
@Table(name = "markers")
@Data
public class Marker {
@Id
@Column(name = "id", nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnore
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnore
@JoinColumn(name = "stream_id", nullable = false)
private Stream stream;
@Column(name = "message", length = 255)
private String message;
@Column(name = "timestamp")
private Instant timestamp;
}

View File

@@ -0,0 +1,52 @@
package com.ddf.vodsystem.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Data;
import java.time.Instant;
@Entity
@Table(name = "vods")
@Data
public class Vod {
@Id
@Column(name = "id", nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnore
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(name = "title", nullable = false, length = 255)
private String title;
@Column(name = "description")
private String description;
@Column(name = "created_at")
private Instant createdAt;
@Column(name = "width", nullable = false)
private Integer width;
@Column(name = "height", nullable = false)
private Integer height;
@Column(name = "fps", nullable = false)
private Float fps;
@Column(name = "duration", nullable = false)
private Float duration;
@Column(name = "file_size", nullable = false)
private Long fileSize;
@Column(name = "video_path", nullable = false, length = 255)
private String videoPath;
@Column(name = "thumbnail_path", nullable = false, length = 255)
private String thumbnailPath;
}

View File

@@ -0,0 +1,18 @@
package com.ddf.vodsystem.exceptions;
public class ClipMediaUnavailable extends RuntimeException {
private final Long clipId;
public ClipMediaUnavailable(Long clipId, String message) {
this(clipId, message, null);
}
public ClipMediaUnavailable(Long clipId, String message, Throwable cause) {
super(message, cause);
this.clipId = clipId;
}
public Long getClipId() {
return clipId;
}
}

View File

@@ -0,0 +1,7 @@
package com.ddf.vodsystem.exceptions;
public class MarkerNotFound extends RuntimeException {
public MarkerNotFound(String message) {
super(message);
}
}

View File

@@ -0,0 +1,7 @@
package com.ddf.vodsystem.exceptions;
public class NotStreaming extends RuntimeException {
public NotStreaming(String message) {
super(message);
}
}

View File

@@ -0,0 +1,18 @@
package com.ddf.vodsystem.exceptions;
public class VodMediaUnavailable extends RuntimeException {
private final Long vodId;
public VodMediaUnavailable(Long vodId, String message) {
this(vodId, message, null);
}
public VodMediaUnavailable(Long vodId, String message, Throwable cause) {
super(message, cause);
this.vodId = vodId;
}
public Long getVodId() {
return vodId;
}
}

View File

@@ -0,0 +1,7 @@
package com.ddf.vodsystem.exceptions;
public class VodNotFound extends RuntimeException {
public VodNotFound(String message) {
super(message);
}
}

View File

@@ -0,0 +1,19 @@
package com.ddf.vodsystem.repositories;
import com.ddf.vodsystem.entities.Marker;
import com.ddf.vodsystem.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.time.Instant;
import java.util.List;
@Repository
public interface MarkerRepository extends JpaRepository<Marker, Long> {
@Query("SELECT m FROM Marker m WHERE m.user = ?1")
List<Marker> findByUser(User user);
@Query("SELECT m FROM Marker m WHERE m.timestamp <= ?1")
List<Marker> findAllBefore(Instant time);
}

View File

@@ -0,0 +1,16 @@
package com.ddf.vodsystem.repositories;
import com.ddf.vodsystem.entities.User;
import com.ddf.vodsystem.entities.Vod;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface VodRepository extends JpaRepository<Vod, Long>
{
@Query("SELECT v FROM Vod v WHERE v.user = ?1")
List<Vod> findByUser(User user);
}

View File

@@ -46,10 +46,10 @@ public class ClipService {
}
/**
* Retrieves all clips associated with the currently logged-in user.
* Returns all clips belonging to the currently authenticated user.
*
* @return a list of clips belonging to the authenticated user.
* @throws NotAuthenticated if the user is not authenticated.
* @return list of clips owned by the current user, in repository order
* @throws NotAuthenticated if no user session is present
*/
public List<Clip> getClipsByUser() {
Optional<User> user = userService.getLoggedInUser();
@@ -62,13 +62,14 @@ public class ClipService {
}
/**
* Retrieves a clip by its ID, ensuring the user is authenticated to access it.
* Returns the clip with the given ID, verifying ownership by the current user.
*
* @param id the ID of the clip to retrieve.
* @return an Optional containing the Clip if found and accessible, or empty if not found.
* @throws NotAuthenticated if the user is not authorized to access the clip.
* @param id the ID of the clip to retrieve
* @return the matching {@link Clip} entity
* @throws ClipNotFound if no clip with {@code id} exists
* @throws NotAuthenticated if the current user does not own the clip
*/
public Optional<Clip> getClipById(Long id) {
public Clip getClipById(Long id) {
Optional<Clip> clip = clipRepository.findById(id);
if (clip.isEmpty()) {
@@ -79,21 +80,22 @@ public class ClipService {
throw new NotAuthenticated("You are not authorized to access clip: " + id);
}
return clip;
return clip.get();
}
/**
* Applies a partial update to an existing clip's metadata.
* <p>
* Only non-null fields in {@code newFields} are written; null fields are left unchanged.
*
* @param id the ID of the clip to update
* @param newFields fields to overwrite; any null field is ignored
* @return the updated clip as persisted in the database
* @throws ClipNotFound if no clip with {@code id} exists
* @throws NotAuthenticated if the current user does not own the clip
*/
public Clip updateClip(Long id, ClipUpdateRequest newFields) {
Optional<Clip> possibleClip = clipRepository.findById(id);
if (possibleClip.isEmpty()) {
throw new ClipNotFound("Clip with id " + id + " not found.");
}
Clip clip = possibleClip.get();
if (!isAuthenticatedForClip(clip)) {
throw new NotAuthenticated("You are not authorized to access clip: " + id);
}
Clip clip = getClipById(id);
if (newFields.title() != null) {
clip.setTitle(newFields.title());
@@ -107,36 +109,26 @@ public class ClipService {
}
/**
* Deletes a clip by its ID, ensuring the user is authenticated to perform the deletion.
* Deletes a clip and its associated files from disk.
*
* @param id the ID of the clip to delete.
* @return true if the clip was successfully deleted, false if it was not found.
* @throws NotAuthenticated if the user is not authorized to delete the clip.
* @param id the ID of the clip to delete
* @throws ClipNotFound if no clip with {@code id} exists
* @throws NotAuthenticated if the current user does not own the clip
*/
public boolean deleteClip(Long id) {
Optional<Clip> possibleClip = getClipById(id);
if (possibleClip.isEmpty()) {
logger.warn("Clip with ID {} not found for deletion", id);
return false;
}
Clip clip = possibleClip.get();
if (!isAuthenticatedForClip(clip)) {
throw new NotAuthenticated("You are not authorized to delete this clip");
}
public void deleteClip(Long id) {
Clip clip = getClipById(id);
deleteClipFiles(clip);
clipRepository.delete(clip);
logger.info("Clip with ID {} deleted successfully", id);
return true;
}
/**
* Checks if the currently logged-in user is authenticated to access the specified clip.
* Returns whether the current user owns the given clip.
*
* @param clip the clip to check access for.
* @return true if the user is authenticated for the clip, false otherwise.
* @param clip the clip to check ownership of
* @return {@code true} if the current user's ID matches the clip's owner; {@code false} if
* {@code clip} is null or no user session exists
*/
public boolean isAuthenticatedForClip(Clip clip) {
Optional<User> user = userService.getLoggedInUser();
@@ -146,79 +138,68 @@ public class ClipService {
return user.get().getId().equals(clip.getUser().getId());
}
/**
* Returns a streamable resource for the clip's video file.
*
* @param id the ID of the clip to download
* @return a {@link Resource} pointing to the clip's video file on disk
* @throws ClipNotFound if no clip with {@code id} exists, or the video file is missing on disk
* @throws NotAuthenticated if the current user does not own the clip
*/
public Resource downloadClip(Long id) {
Optional<Clip> possibleClip = getClipById(id);
if (possibleClip.isEmpty()) {
throw new ClipNotFound("Clip " + id + " doesn't exist");
}
Clip clip = possibleClip.get();
if (!isAuthenticatedForClip(clip)) {
throw new NotAuthenticated("Not authenticated for this clip");
}
Clip clip = getClipById(id);
String path = clip.getVideoPath();
Path file = directoryService.resolvePath(path);
if (!Files.exists(file)) {
throw new JobNotFound("Clip file not found");
throw new ClipNotFound("Clip file not found");
}
return new FileSystemResource(file);
}
public Resource downloadThumbnail(Long id) {
Optional<Clip> possibleClip = getClipById(id);
if (possibleClip.isEmpty()) {
throw new ClipNotFound("Clip " + id + " doesn't exist");
}
Clip clip = possibleClip.get();
if (!isAuthenticatedForClip(clip)) {
throw new NotAuthenticated("Not authenticated for this clip thumbnail");
}
String path = clip.getThumbnailPath();
Path file = directoryService.resolvePath(path);
if (!Files.exists(file)) {
throw new JobNotFound("Thumbnail file not found");
if (!Files.isReadable(file)) {
throw new ClipMediaUnavailable(id, "Clip file is not readable");
}
return new FileSystemResource(file);
}
/**
* Persists a clip to the database
* @param options ClipOptions object of the clip metadata to save to the database. All fields required except for title, description
* @param user User to save the clip to
* @param videoPath Path of the clip
* @param thumbnailPath Path of the thumbnail
* @return Clip object saved to the database
* Returns a streamable resource for the clip's thumbnail image.
*
* @param id the ID of the clip whose thumbnail to download
* @return a {@link Resource} pointing to the thumbnail file on disk
* @throws ClipNotFound if no clip with {@code id} exists, or the thumbnail file is missing on disk
* @throws NotAuthenticated if the current user does not own the clip
*/
public Clip saveClip(ClipOptions options,
User user,
Path videoPath,
Path thumbnailPath) {
Clip clip = new Clip();
clip.setUser(user);
clip.setTitle(options.getTitle() != null ? options.getTitle() : "Untitled Clip");
clip.setDescription(options.getDescription() != null ? options.getDescription() : "");
clip.setCreatedAt(Instant.now());
clip.setWidth(options.getWidth());
clip.setHeight(options.getHeight());
clip.setFps(options.getFps());
clip.setDuration(options.getDuration() - options.getStartPoint());
clip.setFileSize(options.getFileSize());
clip.setVideoPath(directoryService.relativisePath(videoPath.toAbsolutePath()).toString());
clip.setThumbnailPath(directoryService.relativisePath(thumbnailPath.toAbsolutePath()).toString());
return clipRepository.save(clip);
public Resource downloadThumbnail(Long id) {
Clip clip = getClipById(id);
String path = clip.getThumbnailPath();
Path file = directoryService.resolvePath(path);
if (!Files.exists(file)) {
throw new ClipNotFound("Thumbnail file not found");
}
return new FileSystemResource(file);
}
/**
* Copies a processed clip file into permanent storage, generates its thumbnail, and saves
* the clip record to the database.
* <p>
* Thumbnail generation failure is non-fatal — the error is logged and the clip is saved
* without a thumbnail rather than aborting.
*
* @param title title to assign to the clip
* @param description description to assign to the clip
* @param user owner of the clip
* @param clipFile path to the processed video file (typically in the temp output directory)
* @param fileName filename used for both the permanent video file and the thumbnail
* (thumbnail is stored as {@code fileName + ".png"})
* @throws StorageException if copying the file to the clips directory fails
* @throws FFMPEGException if reading video metadata from the copied file fails
*/
public void persistClip(String title,
String description,
User user,
@@ -245,14 +226,11 @@ public class ClipService {
}
// Thumbnail generation can fail with error propagation
try {
thumbnailService.createThumbnail(newClipFile, thumbnailFile, 0.0f);
} catch (InterruptedException e) {
logger.error("Thumbnail generation interrupted for user: {}", user.getId(), e);
Thread.currentThread().interrupt();
} catch (IOException e) {
logger.error("Error generating thumbnail for user: {}", user.getId(), e);
}
thumbnailService.createThumbnail(newClipFile, thumbnailFile, 0.0f)
.exceptionally(ex -> {
logger.error("Thumbnail job for user {} failed: {}", user.getId(), ex.toString());
return null;
});
clipMetadata.setTitle(title);
clipMetadata.setDescription(description);
@@ -261,6 +239,25 @@ public class ClipService {
logger.info("Clip created successfully with ID: {}", clip.getId());
}
private Clip saveClip(ClipOptions metadata,
User user,
Path videoPath,
Path thumbnailPath) {
Clip clip = new Clip();
clip.setUser(user);
clip.setTitle(metadata.getTitle() != null ? metadata.getTitle() : "Untitled Clip");
clip.setDescription(metadata.getDescription() != null ? metadata.getDescription() : "");
clip.setCreatedAt(Instant.now());
clip.setWidth(metadata.getWidth());
clip.setHeight(metadata.getHeight());
clip.setFps(metadata.getFps());
clip.setDuration(metadata.getDuration() - metadata.getStartPoint());
clip.setFileSize(metadata.getFileSize());
clip.setVideoPath(directoryService.relativisePath(videoPath.toAbsolutePath()).toString());
clip.setThumbnailPath(directoryService.relativisePath(thumbnailPath.toAbsolutePath()).toString());
return clipRepository.save(clip);
}
private void deleteClipFiles(Clip clip) {
File clipFile = new File(clip.getVideoPath());
File thumbnailFile = new File(clip.getThumbnailPath());

View File

@@ -10,6 +10,7 @@ import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import java.nio.file.StandardCopyOption;
@@ -129,11 +130,29 @@ public class DirectoryService {
}
}
private void checkDirPermissions() {
List<Path> dirs = List.of(
Path.of(tempInputsDir),
Path.of(tempOutputsDir),
Path.of(usersDir)
);
List<Path> bad = dirs.stream()
.filter(p -> !Files.isDirectory(p) || !Files.isReadable(p) || !Files.isWritable(p))
.toList();
if (!bad.isEmpty()) {
throw new IllegalStateException("Unusable directories: " + bad);
}
}
@PostConstruct
public void createDirectoriesIfNotExist() throws IOException {
Files.createDirectories(Path.of(tempInputsDir));
Files.createDirectories(Path.of(tempOutputsDir));
Files.createDirectories(Path.of(usersDir));
checkDirPermissions();
}
@Scheduled(fixedRate = TEMP_DIR_CLEANUP_RATE)

View File

@@ -0,0 +1,87 @@
package com.ddf.vodsystem.services;
import com.ddf.vodsystem.entities.Marker;
import com.ddf.vodsystem.entities.Stream;
import com.ddf.vodsystem.entities.User;
import com.ddf.vodsystem.exceptions.MarkerNotFound;
import com.ddf.vodsystem.exceptions.NotAuthenticated;
import com.ddf.vodsystem.exceptions.NotStreaming;
import com.ddf.vodsystem.repositories.MarkerRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
@Service
public class MarkerService {
private final UserService userService;
private final StreamService streamService;
private final MarkerRepository markerRepository;
@Value("${stream.max-length}")
private Long maxStreamLength;
public MarkerService(UserService userService, StreamService streamService, MarkerRepository markerRepository) {
this.userService = userService;
this.streamService = streamService;
this.markerRepository = markerRepository;
}
public Marker getMarkerById(Long id) {
Optional<Marker> marker = markerRepository.findById(id);
if (marker.isEmpty()) {
throw new MarkerNotFound("Marker does not exist");
}
Optional<User> user = userService.getLoggedInUser();
if (user.isEmpty() || !user.get().equals(marker.get().getUser())) {
throw new NotAuthenticated("User not authenticated for this marker");
}
return marker.get();
}
public List<Marker> getUserMarkers() {
Optional<User> user = userService.getLoggedInUser();
if (user.isEmpty()) {
throw new NotAuthenticated("Must be logged in to get markers");
}
return markerRepository.findByUser(user.get());
}
public Marker create(String message) {
Optional<Stream> stream = streamService.getActiveStream();
if (stream.isEmpty()) {
throw new NotStreaming("User must be streaming to mark");
}
Marker marker = new Marker();
marker.setStream(stream.get());
marker.setUser(stream.get().getUser());
marker.setMessage(message);
marker.setTimestamp(Instant.now());
return markerRepository.saveAndFlush(marker);
}
public void deleteMarker(Long id) {
Marker marker = getMarkerById(id);
markerRepository.delete(marker);
}
@Scheduled(fixedDelay = 360_000)
@Transactional
public void deleteOldMarkers() {
Instant cutoff = Instant.now().minusSeconds(maxStreamLength);
List<Marker> stale = markerRepository.findAllBefore(cutoff);
markerRepository.deleteAllInBatch(stale);
}
}

View File

@@ -3,7 +3,9 @@ package com.ddf.vodsystem.services;
import com.ddf.vodsystem.dto.ClipOptions;
import com.ddf.vodsystem.dto.Job;
import com.ddf.vodsystem.dto.JobState;
import com.ddf.vodsystem.entities.Marker;
import com.ddf.vodsystem.entities.User;
import com.ddf.vodsystem.exceptions.MarkerNotFound;
import com.ddf.vodsystem.exceptions.NotAuthenticated;
import com.ddf.vodsystem.services.media.CompressionService;
import com.ddf.vodsystem.services.media.StreamActionsService;
@@ -11,12 +13,10 @@ import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.stream.Stream;
@Service
public class MediaService {
@@ -28,23 +28,39 @@ public class MediaService {
private final ClipService clipService;
private static final float CLIP_MAX_LENGTH = 180;
private static final int HLS_SEGMENT_LENGTH = 3;
private final StreamActionsService streamActionsService;
private final VodService vodService;
private final MarkerService markerService;
public MediaService(JobRegistryService jobRegistryService,
DirectoryService directoryService,
CompressionService compressionService,
UserService userService,
ClipService clipService, StreamActionsService streamActionsService) {
ClipService clipService, StreamActionsService streamActionsService, VodService vodService, MarkerService markerService) {
this.jobRegistryService = jobRegistryService;
this.directoryService = directoryService;
this.compressionService = compressionService;
this.userService = userService;
this.clipService = clipService;
this.streamActionsService = streamActionsService;
this.vodService = vodService;
this.markerService = markerService;
}
public Job compress(MultipartFile file, ClipOptions clipOptions) throws IOException, InterruptedException {
/**
* Submits an asynchronous compression job for the uploaded video file.
* <p>
* Saves the upload to a temporary input path, then runs the compression pipeline
* in the background according to {@code clipOptions}. If a user session exists at
* call time, the output is also persisted as a clip when the job succeeds.
*
* @param file the uploaded video file to compress
* @param clipOptions trim window, resolution, fps, and metadata for the output clip
* @return the {@link Job} tracking the compression; state transitions to
* {@link JobState#SUCCEEDED} or {@link JobState#FAILED} asynchronously
* @throws IOException if saving the upload to the temporary directory fails
*/
public Job compress(MultipartFile file, ClipOptions clipOptions) throws IOException {
Job job = jobRegistryService.generateJob();
Optional<User> user = userService.getLoggedInUser();
@@ -77,7 +93,7 @@ public class MediaService {
);
}).exceptionally(ex -> {
job.setState(JobState.FAILED);
job.setErrorOutput(ex.getMessage());
job.setErrorOutput("Compression job failed");
logger.error("Compression job with UUID {} failed due to: {}", job.getUuid(), ex.getMessage());
return null;
});
@@ -86,20 +102,29 @@ public class MediaService {
}
/**
* Saves a clip of the currently authenticated user's stream between two points in time.
* Saves a section of the currently authenticated user's live stream between two absolute timestamps.
* <p>
* Locates the recorded {@code .ts} segments overlapping the requested window, computes the
* trim offset into the first (partially-overlapping) segment and the total clip duration,
* then delegates the actual extraction to {@link StreamActionsService#saveSection}.
* Locates the recorded {@code .ts} HLS segments that overlap {@code [startTime, endTime)}, computes
* the trim offset into the first partially-overlapping segment, then delegates extraction and muxing
* to {@link StreamActionsService#saveSection}. On success, the output is persisted as a VoD via
* {@link VodService#persist}.
*
* @param startTime the inclusive start of the section to save; must be before {@code endTime}
* @param endTime the exclusive end of the section to save
* @param startTime inclusive start of the section to save; must be before {@code endTime}
* @param endTime exclusive end of the section to save
* @param title title for the saved VoD; defaults to the current timestamp if {@code null}
* @param description description for the saved VoD; defaults to an empty string if {@code null}
* @return the {@link Job} tracking the save; state transitions to
* {@link JobState#SUCCEEDED} or {@link JobState#FAILED} asynchronously
* @throws IllegalArgumentException if {@code startTime} is not before {@code endTime},
* or if no stream segments exist in the given range
* @throws NotAuthenticated if no user is currently authenticated
* @throws IOException if reading the stream directory or its segments fails
*/
public Job saveSection(Instant startTime, Instant endTime) throws IOException {
public Job saveSection(
Instant startTime,
Instant endTime,
String title,
String description) throws IOException {
if (startTime.isAfter(endTime)) {
throw new IllegalArgumentException("Start time must be before end time");
}
@@ -108,120 +133,127 @@ public class MediaService {
.orElseThrow(() -> new NotAuthenticated("User is not authenticated"));
Job job = jobRegistryService.generateJob();
Path streamDirectory = directoryService.getStreamDir(user.getStreamKey());
List<Path> fileSegments = getSegmentsInRange(streamDirectory, startTime, endTime);
if (fileSegments.isEmpty()) {
throw new IllegalArgumentException("No stream segments found in the given time range");
}
long firstSegmentMs = parseTimestampMs(fileSegments.getFirst());
float trimOffset = Math.max(0f, (startTime.toEpochMilli() - firstSegmentMs) / 1000f);
SegmentContext ctx = resolveSegments(user, startTime, endTime);
float duration = (endTime.toEpochMilli() - startTime.toEpochMilli()) / 1000f;
job.setState(JobState.PROCESSING);
Path outputFile = directoryService.getVodsDir(user.getId()).resolve(UUID.randomUUID() + ".mp4");
streamActionsService.saveSection(
fileSegments,
trimOffset,
duration,
outputFile,
job.getProgressTracker()
).thenRun(() -> {
job.setDownload(outputFile);
job.setState(JobState.SUCCEEDED);
logger.info("Stream save of job {} succeeded", job.getUuid());
}).exceptionally(ex -> {
job.setState(JobState.FAILED);
job.setErrorOutput(ex.getMessage());
logger.error("Stream section save job with UUID {} failed due to: {}", job.getUuid(), ex.getMessage());
return null;
});
return job;
return dispatchSaveJob(job, ctx, duration, outputFile, () ->
vodService.persist(
title == null ? Instant.now().toString() : title,
description == null ? "" : description,
user,
outputFile,
outputFile.getFileName().toString()
)
);
}
/**
* Saves a clip of the last {@code duration} seconds of the currently authenticated user's stream.
* Saves a section of the currently authenticated user's live stream between two markers.
* <p>
* Computes a time window ending at the current instant and beginning {@code duration} seconds
* earlier (with millisecond precision), then delegates to {@link #saveSection(Instant, Instant)}.
* Resolves {@code startMarkerId} and {@code endMarkerId} to their marker timestamps and
* delegates to {@link #saveSection(Instant, Instant, String, String)}.
*
* @param duration the length of the clip in seconds, measured back from now; must be greater
* than {@code 0} and no greater than {@link #CLIP_MAX_LENGTH}. Fractional values
* are supported and resolved to the millisecond.
* @throws IllegalArgumentException if {@code duration} is not in the range {@code (0, CLIP_MAX_LENGTH]},
* @param startMarkerId id of the marker whose timestamp begins the section to save
* @param endMarkerId id of the marker whose timestamp ends the section to save
* @param title title for the saved VoD; defaults to the current timestamp if {@code null}
* @param description description for the saved VoD; defaults to an empty string if {@code null}
* @return the {@link Job} tracking the save; state transitions to
* {@link JobState#SUCCEEDED} or {@link JobState#FAILED} asynchronously
* @throws MarkerNotFound if either marker id does not exist
* @throws NotAuthenticated if no user is currently authenticated, or the caller does not
* own one of the referenced markers
* @throws IllegalArgumentException if the start marker's timestamp is not before the end
* marker's, or if no stream segments exist in the given range
* @throws IOException if reading the stream directory or its segments fails
*/
public Job saveSection(
Long startMarkerId,
Long endMarkerId,
String title,
String description
) throws IOException {
Marker start = markerService.getMarkerById(startMarkerId);
Marker end = markerService.getMarkerById(endMarkerId);
return saveSection(start.getTimestamp(), end.getTimestamp(), title, description);
}
/**
* Saves the last {@code duration} seconds of the currently authenticated user's live stream as a clip.
* <p>
* Computes a window of {@code [now - duration, now)} with millisecond precision, locates the
* overlapping HLS {@code .ts} segments, and delegates extraction and muxing to
* {@link StreamActionsService#saveSection}. On success, the output is persisted as a clip via
* {@link ClipService#persistClip}.
*
* @param duration length of the clip in seconds measured back from now; must be in
* {@code (0, CLIP_MAX_LENGTH]}. Fractional values are supported.
* @param title title for the saved clip; defaults to the current timestamp if {@code null}
* @param description description for the saved clip; defaults to an empty string if {@code null}
* @return the {@link Job} tracking the save; state transitions to
* {@link JobState#SUCCEEDED} or {@link JobState#FAILED} asynchronously
* @throws IllegalArgumentException if {@code duration} is not in {@code (0, CLIP_MAX_LENGTH]},
* or if no stream segments exist in the computed window
* @throws NotAuthenticated if no user is currently authenticated
* @throws IOException if reading the stream directory or its segments fails
*/
public Job clip(float duration) throws IOException {
public Job clip(float duration, String title, String description) throws IOException {
if (duration <= 0 || duration > CLIP_MAX_LENGTH) {
throw new IllegalArgumentException("Clip length must be between 0 and " + CLIP_MAX_LENGTH + " seconds");
}
// minusSeconds() is possible, but only does integer seconds, not float
Instant endTime = Instant.now();
// minusSeconds() only does integer seconds, not float
Instant startTime = endTime.minus(Duration.ofMillis((long) (duration * 1000)));
User user = userService.getLoggedInUser()
.orElseThrow(() -> new NotAuthenticated("User is not authenticated"));
Job job = jobRegistryService.generateJob();
Path streamDirectory = directoryService.getStreamDir(user.getStreamKey());
List<Path> fileSegments = getSegmentsInRange(streamDirectory, startTime, endTime);
if (fileSegments.isEmpty()) {
throw new IllegalArgumentException("No stream segments found in the given time range");
}
long firstSegmentMs = parseTimestampMs(fileSegments.getFirst());
float trimOffset = Math.max(0f, (startTime.toEpochMilli() - firstSegmentMs) / 1000f);
SegmentContext ctx = resolveSegments(user, startTime, endTime);
Path outputFile = directoryService.getTempOutputDir().resolve(UUID.randomUUID() + ".mp4");
streamActionsService.saveSection(fileSegments, trimOffset, duration, outputFile, job.getProgressTracker())
.thenRun(() -> {
job.setDownload(outputFile);
job.setState(JobState.SUCCEEDED);
logger.info("Stream clip of job {} succeeded", job.getUuid());
return dispatchSaveJob(job, ctx, duration, outputFile, () ->
clipService.persistClip(
Instant.now().toString(),
"",
title == null ? Instant.now().toString() : title,
description == null ? "" : description,
user,
outputFile,
outputFile.getFileName().toString()
)
);
}
).exceptionally(ex -> {
private record SegmentContext(List<Path> segments, float trimOffset) {}
private SegmentContext resolveSegments(User user, Instant startTime, Instant endTime) throws IOException {
Path streamDir = directoryService.getStreamDir(user.getStreamKey());
List<Path> segments = streamActionsService.getSegmentsInRange(streamDir, startTime, endTime);
if (segments.isEmpty()) {
throw new IllegalArgumentException("No stream segments found in the given time range");
}
long firstMs = streamActionsService.parseTimestampMs(segments.getFirst());
float trimOffset = Math.max(0f, (startTime.toEpochMilli() - firstMs) / 1000f);
return new SegmentContext(segments, trimOffset);
}
private Job dispatchSaveJob(Job job, SegmentContext ctx, float duration, Path outputFile, Runnable onSuccess) throws IOException {
job.setState(JobState.PROCESSING);
streamActionsService.saveSection(ctx.segments(), ctx.trimOffset(), duration, outputFile, job.getProgressTracker())
.thenRun(() -> {
job.setDownload(outputFile);
job.setState(JobState.SUCCEEDED);
logger.info("Stream save job {} succeeded", job.getUuid());
onSuccess.run();
}).exceptionally(ex -> {
job.setState(JobState.FAILED);
job.setErrorOutput(ex.getMessage());
logger.error("Clip save job with UUID {} failed due to: {}", job.getUuid(), ex.getMessage());
logger.error("Stream save job {} failed: {}", job.getUuid(), ex.getMessage());
return null;
});
return job;
}
private List<Path> getSegmentsInRange(Path streamDirectory, Instant startTime, Instant endTime) throws IOException {
long startMs = startTime.toEpochMilli();
long endMs = endTime.toEpochMilli();
try (Stream<Path> files = Files.list(streamDirectory)) {
return files
.filter(p -> p.getFileName().toString().endsWith(".ts"))
.filter(p -> {
long segMs = parseTimestampMs(p);
return segMs < endMs && (segMs + HLS_SEGMENT_LENGTH * 1000) > startMs;
})
.sorted(Comparator.comparingLong(this::parseTimestampMs))
.toList();
}
}
private long parseTimestampMs(Path path) {
String name = path.getFileName().toString().replace(".ts", "");
long value = Long.parseLong(name);
// nginx hls_fragment_naming system uses seconds; convert to ms
return value < 1_000_000_000_000L ? value * 1000L : value;
}
}

View File

@@ -0,0 +1,261 @@
package com.ddf.vodsystem.services;
import com.ddf.vodsystem.controllers.dto.VodUpdateRequest;
import com.ddf.vodsystem.dto.ClipOptions;
import com.ddf.vodsystem.entities.User;
import com.ddf.vodsystem.entities.Vod;
import com.ddf.vodsystem.exceptions.*;
import com.ddf.vodsystem.repositories.VodRepository;
import com.ddf.vodsystem.services.media.MetadataService;
import com.ddf.vodsystem.services.media.ThumbnailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
@Service
public class VodService {
private static final Logger logger = LoggerFactory.getLogger(VodService.class);
private final VodRepository vodRepository;
private final DirectoryService directoryService;
private final MetadataService metadataService;
private final ThumbnailService thumbnailService;
private final UserService userService;
public VodService(VodRepository vodRepository,
DirectoryService directoryService,
MetadataService metadataService,
ThumbnailService thumbnailService,
UserService userService) {
this.vodRepository = vodRepository;
this.directoryService = directoryService;
this.metadataService = metadataService;
this.thumbnailService = thumbnailService;
this.userService = userService;
}
/**
* Returns the VoD with the given ID, verifying ownership by the current user.
*
* @param id the ID of the VoD to retrieve
* @return the matching {@link Vod} entity
* @throws VodNotFound if no VoD with {@code id} exists
* @throws NotAuthenticated if the current user does not own the VoD
*/
public Vod getVodById(Long id) {
Optional<Vod> vod = vodRepository.findById(id);
if (vod.isEmpty()) {
throw new VodNotFound("Vod ID " + id + " does not exist");
}
if (!isAuthenticatedForVod(vod.get())) {
throw new NotAuthenticated("User not authenticated");
}
return vod.get();
}
/**
* Returns all VoDs belonging to the currently authenticated user.
*
* @return list of VoDs owned by the current user, in repository order
* @throws NotAuthenticated if no user session is present
*/
public List<Vod> getUserVods() {
Optional<User> user = userService.getLoggedInUser();
if (user.isEmpty()) {
throw new NotAuthenticated("User must be logged in to retrieve vods");
}
return vodRepository.findByUser(user.get());
}
/**
* Applies a partial update to an existing VoD's metadata.
* <p>
* Only non-null fields in {@code newFields} are written; null fields are left unchanged.
*
* @param id the ID of the VoD to update
* @param newFields fields to overwrite; any null field is ignored
* @return the updated VoD as persisted in the database
* @throws VodNotFound if no VoD with {@code id} exists
* @throws NotAuthenticated if the current user does not own the VoD
*/
public Vod updateVod(Long id, VodUpdateRequest newFields) {
Vod vod = getVodById(id);
if (newFields.title() != null) {
vod.setTitle(newFields.title());
}
if (newFields.description() != null) {
vod.setDescription(newFields.description());
}
return vodRepository.saveAndFlush(vod);
}
/**
* Deletes a VoD and its associated files from disk.
*
* @param id the ID of the VoD to delete
* @throws VodNotFound if no VoD with {@code id} exists
* @throws NotAuthenticated if the current user does not own the VoD
*/
public void deleteVod(Long id) {
Vod vod = getVodById(id);
deleteVodFiles(vod);
vodRepository.delete(vod);
logger.info("Vod with ID {} deleted successfully", id);
}
/**
* Returns a streamable resource for the VoD's video file.
*
* @param id the ID of the VoD to download
* @return a {@link Resource} pointing to the VoD's video file on disk
* @throws VodNotFound if no VoD with {@code id} exists, or the video file is missing on disk
* @throws NotAuthenticated if the current user does not own the VoD
*/
public Resource downloadVod(Long id) {
Vod vod = getVodById(id);
Path file = directoryService.resolvePath(vod.getVideoPath());
if (!Files.exists(file)) {
throw new VodNotFound("Vod file not found for ID: " + id);
}
if (!Files.isReadable(file)) {
throw new VodMediaUnavailable(id, "Vod file is not readable");
}
return new FileSystemResource(file);
}
/**
* Returns a streamable resource for the VoD's thumbnail image.
*
* @param id the ID of the VoD whose thumbnail to download
* @return a {@link Resource} pointing to the thumbnail file on disk
* @throws VodNotFound if no VoD with {@code id} exists, or the thumbnail file is missing on disk
* @throws NotAuthenticated if the current user does not own the VoD
*/
public Resource downloadThumbnail(Long id) {
Vod vod = getVodById(id);
Path file = directoryService.resolvePath(vod.getThumbnailPath());
if (!Files.exists(file)) {
throw new VodNotFound("Thumbnail file not found for vod ID: " + id);
}
return new FileSystemResource(file);
}
/**
* Copies a processed VoD file into permanent storage, generates its thumbnail, and saves
* the VoD record to the database.
* <p>
* Thumbnail generation failure is non-fatal — the error is logged and the VoD is saved
* without a thumbnail rather than aborting.
*
* @param title title to assign to the VoD
* @param description description to assign to the VoD
* @param user owner of the VoD
* @param vodFile path to the processed video file to copy into permanent storage
* @param fileName filename used for both the permanent video file and the thumbnail
* (thumbnail is stored as {@code fileName + ".png"})
* @throws StorageException if copying the file to the VoDs directory fails
* @throws FFMPEGException if reading video metadata from the copied file fails
*/
public void persist(String title,
String description,
User user,
Path vodFile,
String fileName) {
Path newVodFile;
Path thumbnailFile;
try {
newVodFile = directoryService.getVodsDir(user.getId()).resolve(fileName);
thumbnailFile = directoryService.getThumbnailsDir(user.getId()).resolve(fileName + ".png");
directoryService.copyFile(vodFile, newVodFile);
} catch (IOException e) {
throw new StorageException("Failed to move vod from temporary directory to output directory", e);
}
ClipOptions vodMetadata;
try {
vodMetadata = metadataService.getVideoMetadata(newVodFile).get();
} catch (InterruptedException | ExecutionException e) {
Thread.currentThread().interrupt();
throw new FFMPEGException("Error retrieving video metadata for vod: " + e.getMessage());
}
thumbnailService.createThumbnail(newVodFile, thumbnailFile, 0.0f)
.exceptionally(ex -> {
logger.error("Thumbnail job for user {} failed: {}", user.getId(), ex.toString());
return null;
});
vodMetadata.setTitle(title);
vodMetadata.setDescription(description);
Vod vod = saveToDb(vodMetadata, user, newVodFile, thumbnailFile);
logger.info("Vod created successfully with ID: {}", vod.getId());
}
private Vod saveToDb(ClipOptions options,
User user,
Path videoPath,
Path thumbnailPath) {
Vod vod = new Vod();
vod.setUser(user);
vod.setTitle(options.getTitle() != null ? options.getTitle() : "Untitled VoD");
vod.setDescription(options.getDescription() != null ? options.getDescription() : "");
vod.setCreatedAt(Instant.now());
vod.setWidth(options.getWidth());
vod.setHeight(options.getHeight());
vod.setFps(options.getFps());
vod.setDuration(options.getDuration());
vod.setFileSize(options.getFileSize());
vod.setVideoPath(directoryService.relativisePath(videoPath.toAbsolutePath()).toString());
vod.setThumbnailPath(directoryService.relativisePath(thumbnailPath.toAbsolutePath()).toString());
return vodRepository.save(vod);
}
private void deleteVodFiles(Vod vod) {
File vodFile = new File(vod.getVideoPath());
File thumbnailFile = new File(vod.getThumbnailPath());
try {
Files.deleteIfExists(vodFile.toPath());
Files.deleteIfExists(thumbnailFile.toPath());
} catch (IOException e) {
logger.error("Could not delete vod files for vod ID: {}", vod.getId());
}
}
private boolean isAuthenticatedForVod(Vod vod) {
Optional<User> user = userService.getLoggedInUser();
if (vod == null || user.isEmpty()) {
return false;
}
return user.get().getId().equals(vod.getUser().getId());
}
}

View File

@@ -2,6 +2,7 @@ package com.ddf.vodsystem.services.media;
import com.ddf.vodsystem.dto.CommandOutput;
import com.ddf.vodsystem.dto.ProgressTracker;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
@@ -11,10 +12,11 @@ import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class CommandRunner {
private static final Pattern timePattern = Pattern.compile("out_time_ms=(\\d+)");
public static CommandOutput run(List<String> command, Consumer<String> onOutput) throws IOException, InterruptedException {
public CommandOutput run(List<String> command, Consumer<String> onOutput) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.redirectErrorStream(true);
@@ -41,19 +43,15 @@ public class CommandRunner {
return commandOutput;
}
public static CommandOutput run(List<String> command) throws IOException, InterruptedException {
public CommandOutput run(List<String> command) throws IOException, InterruptedException {
return run(command, null);
}
public static void setProgress(String line, ProgressTracker progress, float length) {
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);
}
}
private CommandRunner() {
// Private constructor to prevent instantiation
}
}

View File

@@ -13,42 +13,45 @@ import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
public class CompressionService {
private static final Logger logger = LoggerFactory.getLogger(CompressionService.class);
private final CommandRunner commandRunner;
private static final float AUDIO_RATIO = 0.15f;
private static final float MAX_AUDIO_BITRATE = 128f;
private static final float BITRATE_MULTIPLIER = 0.9f;
private final Pattern timePattern = Pattern.compile("out_time_ms=(\\d+)");
public CompressionService(CommandRunner commandRunner) {
this.commandRunner = commandRunner;
}
@Async("ffmpegTaskExecutor")
public CompletableFuture<CommandOutput> compress(Path inputFile,
Path outputFile,
ClipOptions clipOptions,
ProgressTracker progress
) throws IOException, InterruptedException {
) {
logger.info("Compressing video from {} to {}", inputFile.toAbsolutePath(), outputFile.toAbsolutePath());
try {
List<String> command = buildCommand(
inputFile,
outputFile,
clipOptions
);
CommandOutput result = CommandRunner.run(command, line -> CommandRunner.setProgress(line, progress, clipOptions.getDuration()));
CommandOutput result = commandRunner.run(command, line -> commandRunner.setProgress(line, progress, clipOptions.getDuration()));
progress.markComplete();
return CompletableFuture.completedFuture(result);
}
private 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);
} catch (IOException e) {
logger.error("IO error on compress call: {}", e.toString());
return CompletableFuture.failedFuture(e);
} catch (InterruptedException e) {
logger.error("Thread error on compress call: {}", e.toString());
Thread.currentThread().interrupt();
return CompletableFuture.failedFuture(e);
}
}
@@ -75,7 +78,7 @@ public class CompressionService {
return command;
}
private List<String> buildBitrate(Float length, Float fileSize) {
private List<String> buildBitrate(Float length, Long fileSize) {
List<String> command = new ArrayList<>();
float bitrate = ((fileSize * 8) / length) * BITRATE_MULTIPLIER;
@@ -112,7 +115,7 @@ public class CompressionService {
return command;
}
private List<String> buildCommand(Path inputFile, Path outputFile, ClipOptions clipOptions) {
protected List<String> buildCommand(Path inputFile, Path outputFile, ClipOptions clipOptions) {
List<String> command = new ArrayList<>();
command.add("ffmpeg");
command.add("-progress");

View File

@@ -14,16 +14,20 @@ import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
@Service
public class MetadataService {
private static final Logger logger = LoggerFactory.getLogger(MetadataService.class);
public final CommandRunner commandRunner;
private static final String DURATION = "duration";
public MetadataService(CommandRunner commandRunner) {
this.commandRunner = commandRunner;
}
@Async("ffmpegTaskExecutor")
public Future<ClipOptions> getVideoMetadata(Path file) {
public CompletableFuture<ClipOptions> getVideoMetadata(Path file) {
logger.info("Getting metadata for file {}", file);
List<String> command = List.of(
@@ -39,7 +43,7 @@ public class MetadataService {
StringBuilder outputBuilder = new StringBuilder();
try {
CommandOutput output = CommandRunner.run(command);
CommandOutput output = commandRunner.run(command);
for (String line : output.getOutput()) {
outputBuilder.append(line);
@@ -47,9 +51,11 @@ public class MetadataService {
JsonNode node = mapper.readTree(outputBuilder.toString());
return CompletableFuture.completedFuture(parseVideoMetadata(node));
} catch (IOException | InterruptedException e) {
} catch (IOException e) {
return CompletableFuture.failedFuture(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new FFMPEGException("Error while getting video metadata: " + e);
return CompletableFuture.failedFuture(e);
}
}
@@ -58,13 +64,12 @@ public class MetadataService {
metadata.setStartPoint(0f);
JsonNode streamNode = extractStreamNode(node);
JsonNode formatNode = extractFormatNode(node);
metadata.setDuration(extractDuration(streamNode));
metadata.setDuration(extractDuration(streamNode, formatNode));
metadata.setWidth(getWidth(streamNode));
metadata.setHeight(getHeight(streamNode));
metadata.setFps(extractFps(streamNode));
JsonNode formatNode = extractFormatNode(node);
metadata.setFileSize(extractFileSize(formatNode));
extractEndPointFromFormat(metadata, formatNode);
@@ -79,11 +84,15 @@ public class MetadataService {
return streamNode;
}
private Float extractDuration(JsonNode streamNode) {
private Float extractDuration(JsonNode streamNode, JsonNode formatNode) {
if (streamNode.has(DURATION)) {
return Float.valueOf(streamNode.get(DURATION).asText());
}
if (formatNode.has(DURATION)) {
return Float.valueOf(formatNode.get(DURATION).asText());
}
throw new FFMPEGException("ffprobe duration missing");
}
@@ -108,9 +117,9 @@ public class MetadataService {
return (formatNode != null && !formatNode.isMissingNode()) ? formatNode : null;
}
private Float extractFileSize(JsonNode formatNode) {
private Long extractFileSize(JsonNode formatNode) {
if (formatNode != null && formatNode.has("size")) {
return Float.parseFloat(formatNode.get("size").asText());
return Long.parseLong(formatNode.get("size").asText());
}
throw new FFMPEGException("ffprobe file size missing");

View File

@@ -2,6 +2,8 @@ package com.ddf.vodsystem.services.media;
import com.ddf.vodsystem.dto.CommandOutput;
import com.ddf.vodsystem.dto.ProgressTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@@ -9,19 +11,23 @@ import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
public class RemuxService {
private final Pattern timePattern = Pattern.compile("out_time_ms=(\\d+)");
private static final Logger logger = LoggerFactory.getLogger(RemuxService.class);
private final CommandRunner commandRunner;
public RemuxService(CommandRunner commandRunner) {
this.commandRunner = commandRunner;
}
@Async("ffmpegTaskExecutor")
public CompletableFuture<CommandOutput> remux(File inputFile,
File outputFile,
ProgressTracker remuxProgress,
float length
) throws IOException, InterruptedException {
) {
try {
List<String> command = List.of(
"ffmpeg",
"-progress", "pipe:1",
@@ -33,14 +39,15 @@ public class RemuxService {
outputFile.getAbsolutePath()
);
return CompletableFuture.completedFuture(CommandRunner.run(command, line -> setProgress(line, remuxProgress, length)));
}
private 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);
return CompletableFuture.completedFuture(commandRunner.run(command, line ->
commandRunner.setProgress(line, remuxProgress, length)));
} catch (IOException e) {
logger.error("IO error on remux call: {}", e.toString());
return CompletableFuture.failedFuture(e);
} catch (InterruptedException e) {
logger.error("Thread error on remux call: {}", e.toString());
Thread.currentThread().interrupt();
return CompletableFuture.failedFuture(e);
}
}
}

View File

@@ -1,5 +1,6 @@
package com.ddf.vodsystem.services.media;
import com.ddf.vodsystem.dto.CommandOutput;
import com.ddf.vodsystem.dto.ProgressTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -7,10 +8,15 @@ import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Service responsible for performing stream-related media actions, such as
@@ -24,6 +30,11 @@ import java.util.stream.Collectors;
@Service
public class StreamActionsService {
private static final Logger logger = LoggerFactory.getLogger(StreamActionsService.class);
private final CommandRunner commandRunner;
public StreamActionsService(CommandRunner commandRunner) {
this.commandRunner = commandRunner;
}
/**
* Concatenates a list of video segments and extracts a trimmed section
@@ -43,28 +54,43 @@ public class StreamActionsService {
* to extract
* @param outputFile the destination file the trimmed section will be
* written to; overwritten if it already exists
* @return a {@link CompletableFuture} that completes with
* {@code outputFile} on success, or completes exceptionally on
* failure
* @return a {@link CompletableFuture} that completes with the ffmpeg
* command output on success, or completes exceptionally on failure
*/
@Async("ffmpegTaskExecutor")
public CompletableFuture<Path> saveSection(
public CompletableFuture<CommandOutput> saveSection(
List<Path> segments,
float trimOffset,
float duration,
Path outputFile,
ProgressTracker progressTracker
) {
) throws IOException {
if (segments.isEmpty()) {
return CompletableFuture.failedFuture(new IllegalArgumentException("Segment list cannot be empty"));
}
Path firstSegment = segments.getFirst();
Path trimmedFirst = Files.createTempFile("trimmed-first-", ".ts");
try {
String concatInput = segments.stream()
// First segment must be trimmed manually due to keyframe issues with the concat protocol
List<String> trimCommand = List.of(
"ffmpeg", "-y",
"-ss", String.valueOf(trimOffset),
"-i", firstSegment.toAbsolutePath().toString(),
"-c", "copy",
trimmedFirst.toAbsolutePath().toString()
);
commandRunner.run(trimCommand);
String concatInput = Stream.concat(Stream.of(trimmedFirst), segments.stream().skip(1))
.map(p -> p.toAbsolutePath().toString())
.collect(Collectors.joining("|"));
List<String> command = List.of(
"ffmpeg",
"-y",
"-i", "concat:" + concatInput,
"-ss", String.valueOf(trimOffset),
"-i", "concat:" + concatInput,
"-t", String.valueOf(duration),
"-c", "copy",
outputFile.toAbsolutePath().toString()
@@ -72,17 +98,68 @@ public class StreamActionsService {
logger.info("Saving section with ({} segments) to '{}'",
segments.size(), outputFile);
CommandRunner.run(command, line -> CommandRunner.setProgress(line, progressTracker, duration));
progressTracker.markComplete();
CommandOutput output = commandRunner.run(command, line -> commandRunner.setProgress(line, progressTracker, duration));
return CompletableFuture.completedFuture(outputFile);
progressTracker.markComplete();
return CompletableFuture.completedFuture(output);
} catch (IOException e) {
logger.error("Failed to save section to '{}'", outputFile, e);
logger.error("IO error on saveSection call: {}", e.toString());
return CompletableFuture.failedFuture(e);
} catch (InterruptedException e) {
logger.error("Failed to save section");
logger.error("Thread error on saveSection call: {}", e.toString());
Thread.currentThread().interrupt();
return CompletableFuture.failedFuture(e);
} catch (RuntimeException e) {
logger.error("Failed to save section to '{}': {}", outputFile, e.toString());
return CompletableFuture.failedFuture(e);
} finally {
Files.deleteIfExists(trimmedFirst);
}
}
public List<Path> getSegmentsInRange(Path streamDirectory, Instant startTime, Instant endTime) throws IOException {
long startMs = startTime.toEpochMilli();
long endMs = endTime.toEpochMilli();
if (endTime.toEpochMilli() <= startTime.toEpochMilli()) {
throw new IllegalArgumentException("Start time must be before end time");
}
List<Path> results = new ArrayList<>();
try (Stream<Path> files = Files.list(streamDirectory)) {
List<Path> streamFiles = files
.filter(p -> p.getFileName().toString().endsWith(".ts"))
.filter(Files::isRegularFile)
.sorted(Comparator.comparingLong(this::parseTimestampMs))
.toList();
for (int i = 0; i < streamFiles.size(); i++) {
Path streamFile = streamFiles.get(i);
long segmentStart = parseTimestampMs(streamFile);
long segmentEnd = (i + 1 < streamFiles.size())
? parseTimestampMs(streamFiles.get(i + 1))
: Long.MAX_VALUE;
if (segmentStart < endMs && segmentEnd > startMs) {
results.add(streamFile);
}
}
}
return results;
}
public long parseTimestampMs(Path path) {
String fullName = path.getFileName().toString();
if (!fullName.endsWith(".ts")) {
throw new IllegalArgumentException("File must end in ts");
}
String name = fullName.substring(0, fullName.length() - 3);
long value = Long.parseLong(name);
// nginx hls_fragment_naming system uses seconds; convert to ms
return value < 1_000_000_000_000L ? value * 1000L : value;
}
}

View File

@@ -1,5 +1,6 @@
package com.ddf.vodsystem.services.media;
import com.ddf.vodsystem.dto.CommandOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
@@ -8,15 +9,22 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Service
public class ThumbnailService {
private static final Logger logger = LoggerFactory.getLogger(ThumbnailService.class);
private final CommandRunner commandRunner;
public ThumbnailService(CommandRunner commandRunner) {
this.commandRunner = commandRunner;
}
@Async("ffmpegTaskExecutor")
public void createThumbnail(Path inputFile, Path outputFile, Float timeInVideo) throws IOException, InterruptedException {
public CompletableFuture<CommandOutput> createThumbnail(Path inputFile, Path outputFile, Float timeInVideo) {
logger.info("Creating thumbnail at {} seconds", timeInVideo);
try {
List<String> command = List.of(
"ffmpeg",
"-ss", timeInVideo.toString(),
@@ -25,6 +33,13 @@ public class ThumbnailService {
outputFile.toAbsolutePath().toString()
);
CommandRunner.run(command);
CommandOutput output = commandRunner.run(command);
return CompletableFuture.completedFuture(output);
} catch (IOException e) {
return CompletableFuture.failedFuture(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return CompletableFuture.failedFuture(e);
}
}
}

View File

@@ -3,6 +3,7 @@ spring.application.name=vodSystem
# VODs
spring.servlet.multipart.max-file-size=2GB
spring.servlet.multipart.max-request-size=2GB
stream.max-length=${STREAM_RING_LENGTH_SECOND}
# Database
spring.datasource.url=${POSTGRES_URL}

View File

@@ -1,25 +0,0 @@
INSERT INTO users ( google_id, username, email, name)
VALUES
('google-uid-001', 'alice', 'alice@example.com', 'Alice Example'),
( 'google-uid-002', 'bob', 'bob@example.com', 'Bob Example'),
('google-uid-003', 'carol', 'carol@example.com', 'Carol Example'),
( 'google-uid-004', 'wizard42', 'gandalf@middle.earth', 'Gandalf the Grey'),
( 'google-uid-005', 'catnap', 'whiskers@meowmail.com', 'Sir Whiskers McFluff'),
( 'google-uid-006', 'robotron', 'bender@futurama.tv', 'Bender Rodriguez'),
('google-uid-007', 'unicorn', 'sparkle@rainbow.com', 'Princess Sparklehoof'),
( 'google-uid-008', 'pirate', 'blackbeard@seas.com', 'Edward Teach'),
( 'google-uid-009', 'detective', 'holmes@bakerstreet.uk', 'Sherlock Holmes'),
( 'google-uid-010', 'timey', 'docbrown@delorean.net', 'Dr. Emmett Brown');
INSERT INTO clips (user_id, title, description, width, height, fps, duration, file_size, video_path)
VALUES
(4, 'Fireworks Over Hobbiton', 'A magical display of fireworks by Gandalf.', 1920, 1080, 30, 120, 104857600, '/videos/fireworks_hobbiton.mp4'),
(5, 'Catnap Chronicles', 'Sir Whiskers McFluff naps in 12 different positions.', 1280, 720, 24, 60, 52428800, '/videos/catnap_chronicles.mp4'),
(6, 'Bite My Shiny Metal...', 'Bender shows off his new upgrades.', 1920, 1080, 60, 45, 73400320, '/videos/bender_upgrades.mp4'),
(7, 'Rainbow Dash', 'Princess Sparklehoof gallops across a double rainbow.', 1920, 1080, 30, 90, 67108864, '/videos/rainbow_dash.mp4'),
( 8, 'Pirate Karaoke Night', 'Blackbeard sings sea shanties with his crew.', 1280, 720, 25, 180, 157286400, '/videos/pirate_karaoke.mp4'),
( 9, 'The Case of the Missing Sandwich', 'Sherlock Holmes investigates a lunchtime mystery.', 1920, 1080, 30, 75, 50331648, '/videos/missing_sandwich.mp4'),
( 10, '88 Miles Per Hour', 'Doc Brown demonstrates time travel with style.', 1920, 1080, 60, 30, 41943040, '/videos/88mph.mp4'),
( 1, 'Alice in Videoland', 'Alice explores a surreal digital wonderland.', 1280, 720, 30, 150, 94371840, '/videos/alice_videoland.mp4'),
( 2, 'Bob''s Building Bonanza', 'Bob constructs a house out of cheese.', 1920, 1080, 24, 200, 209715200, '/videos/bob_cheesehouse.mp4'),
( 3, 'Carol''s Coding Catastrophe', 'Carol debugs a spaghetti codebase.', 1280, 720, 30, 100, 73400320, '/videos/carol_coding.mp4');

View File

@@ -34,8 +34,35 @@ CREATE TABLE IF NOT EXISTS clips (
height INTEGER NOT NULL,
fps FLOAT NOT NULL,
duration FLOAT NOT NULL,
file_size FLOAT NOT NULL,
file_size BIGINT NOT NULL,
video_path VARCHAR(255) NOT NULL,
thumbnail_path VARCHAR(255) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS vods (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
width INTEGER NOT NULL,
height INTEGER NOT NULL,
fps FLOAT NOT NULL,
duration FLOAT NOT NULL,
file_size BIGINT NOT NULL,
video_path VARCHAR(255) NOT NULL,
thumbnail_path VARCHAR(255) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS markers (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
stream_id BIGINT NOT NULL,
message VARCHAR(255),
timestamp TIMESTAMPTZ DEFAULT NOW(),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (stream_id) REFERENCES streams(id) ON DELETE CASCADE
);

Some files were not shown because too many files have changed in this diff Show More