54 Commits

Author SHA1 Message Date
beff49a3ef rename Box to Card
All checks were successful
CI / Maven unit tests (push) Successful in 13s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped
2026-07-29 22:21:45 +01:00
3c50d6aaf4 add cringe home message
All checks were successful
CI / Maven unit tests (push) Successful in 20s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped
2026-07-29 21:28:34 +01:00
9dcab44465 add titles to homepage
All checks were successful
CI / Maven unit tests (push) Successful in 13s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped
2026-07-29 21:23:34 +01:00
6ddffd8e2b fix sidebar spacing issues
All checks were successful
CI / Maven unit tests (push) Successful in 13s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped
2026-07-29 20:53:13 +01:00
c86e5e5568 add colour and remove topbar
All checks were successful
CI / Maven unit tests (push) Successful in 14s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped
2026-07-29 20:20:26 +01:00
2f9ddadb91 add new fonts
All checks were successful
CI / Maven unit tests (push) Successful in 14s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped
2026-07-29 19:14:20 +01:00
29bc60d417 fix(streaming): missing HLS segments in edge requests (#10)
All checks were successful
CI / Maven unit tests (push) Successful in 14s
CI / Build and push images (push) Successful in 3m0s
CI / Deploy to server (push) Successful in 16s
Reviewed-on: https://gitea.vodsystem.ddns.net/dylan/vod-system/pulls/10
2026-07-29 18:49:59 +01:00
92cecb1084 chore: remove sql logs from prod
All checks were successful
CI / Maven unit tests (push) Successful in 14s
CI / Build and push images (push) Successful in 2m7s
CI / Deploy to server (push) Successful in 12s
2026-07-25 14:31:51 +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
117 changed files with 6542 additions and 2095 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:

138
ethos.md Normal file
View File

@@ -0,0 +1,138 @@
# The VoD System — Frontend Design Reference
Warm, editorial, low-key. Soft shadows instead of borders, cream surfaces, one terracotta and one olive accent. No dark-dashboard chrome.
---
## 1. Typography
| Role | Family | Usage |
| --- | --- | --- |
| Display / headings | **Newsreader** (serif, weight 400) | Page titles, card headings, item titles, greeting, logo wordmark. Always regular weight — never bold. |
| UI / body | **IBM Plex Sans** (400, 500) | Nav, labels, buttons, body copy, table cells. 500 only for the active nav item. |
| Data / mono | **IBM Plex Mono** (400, 500) | Timecodes, stream key, ingest URL, durations, bitrates, file facts, kickers, job stages. |
Fallbacks: `system-ui, sans-serif` for Plex Sans; `serif` for Newsreader; `monospace` for Plex Mono.
### Type scale
| Element | Size | Family | Notes |
| --- | --- | --- | --- |
| Greeting (dashboard h1) | 40px | Newsreader | `letter-spacing: -0.015em` |
| Page h1 | 36px | Newsreader | -0.015em |
| Detail title | 31px | Newsreader | -0.015em |
| Drop-zone headline | 25px | Newsreader | |
| Section h2 | 23px | Newsreader | |
| Logo wordmark | 22px | Newsreader | -0.01em |
| Card heading (in-panel) | 20–22px | Newsreader | |
| Status headline | 27px | Newsreader | line-height 1.25 |
| VOD tile title | 17.5–18px | Newsreader | line-height 1.3 |
| Big metric | 21px | Plex Mono | elapsed, marker count, bitrate |
| Range length | 15px | Plex Mono | |
| Body paragraph | 14.5px | Plex Sans | line-height 1.65, `text-wrap: pretty`, max 62ch |
| Primary button | 13.5–14px | Plex Sans | |
| Field value | 13.5–14px | Plex Sans / Mono | mono for timecodes and sizes |
| Table cell | 13.5px | Plex Sans | mono for numeric columns |
| Clip tile title | 13.5px | Plex Sans | |
| Meta line | 12–13px | Plex Sans | muted ink |
| Field label | 11.5px | Plex Sans | muted ink |
| Kicker / eyebrow | 10.5–11px | Plex Mono | `letter-spacing: 0.10–0.14em`, uppercase |
| Ruler / tick caption | 10–10.5px | Plex Mono | |
---
## 2. Colour
### Surfaces
| Token | Hex | Where |
| --- | --- | --- |
| Canvas | `#F7F4EE` | Page background |
| Sidebar | `#F2EEE6` | Nav column and collapsed rail |
| Card | `#FDFBF7` | Cards, library tiles, active nav pill |
| Field well | `#F4F0E8` | Inputs, credential wells, timeline track |
| Muted panel | `#F1ECE3` / `#F1EDE4` | Secondary buttons, "how it works", clip-cutter panel |
| Drop zone (idle) | `#F9F6EF` | Upload empty state |
| Armed / selected | `#F6EFE6` | Selected marker row, filled range card |
| Live card | `#F0EBE1` | Dashboard status block when live |
| Player body | `#2B2620` | Video chrome, also the dark button |
| Player stripes | `#3A342C` / `#332E27` | Placeholder frame texture |
### Ink
| Token | Hex | Where |
| --- | --- | --- |
| Primary | `#2B2620` | Headings, metrics |
| Strong | `#35302A` | Field values, tile titles |
| Body | `#554D44` | Paragraph copy |
| Control label | `#4A423A` | Secondary button text |
| Secondary | `#6E6559` | Supporting copy |
| Table value | `#7A7166` | History rows |
| Muted | `#9A9084` | Labels, meta, kickers |
| Faint | `#A79C8E` | Mono captions, ruler ticks, hints |
| On dark | `#FBF8F2` | Text on player / dark button |
| On accent | `#FDFBF7` | Text on terracotta / olive |
### Accents
| Token | Hex | Where |
| --- | --- | --- |
| Terracotta | `#A85A38` | Logo mark, primary CTA, links, marker timecodes, playheads |
| Terracotta hover | `#94492A` | Primary button hover |
| Terracotta light | `#C87A52` | Progress bars, scrubber fill, selected marker ring |
| Terracotta disabled | `#C9AE9C` | "Waiting for a file" button |
| Olive | `#6E7A50` | Clip actions, trim in/out handles |
| Olive hover | `#5D6843` | |
| Olive light | `#8A9668` | Completed job bar |
| Live red | `#B5432E` | Live dot and "LIVE NOW" label |
### Lines, chips, placeholders
| Token | Hex | Where |
| --- | --- | --- |
| Hairline | `#F0EBE2` | Row dividers (1px) |
| Chip fill | `#EAE3D7`, `#EFE9DE`, `#E4DDD0` | Progress track, toggles, nav-hide button |
| Chip hover | `#E7E0D2`, `#DAD1C0`, `#EAE4D9` | |
| Drop-zone ring | `#E2DACB` | `inset 0 0 0 1.5px` |
| Inactive marks | `#DED7CA`, `#C4BAA9` | Unchecked boxes, unselected ticks |
| Zoom window outline | `#8E8577` | Overview strip frame |
| VOD thumbnail | `#E3DACB` / `#DAD0BF` | 135° stripes, 9px |
| Clip thumbnail | `#DFE0D2` / `#D6D8C7` | 135° stripes, 9px |
| Avatar | `#D9C9AE` on `#5C4A32` | Google account chip |
---
## 3. Elevation & shape
- **Card**: `0 1px 2px rgba(60,48,32,.05), 0 10px 26px -18px rgba(60,48,32,.35)`
- **Card hover**: `0 2px 4px rgba(60,48,32,.07), 0 18px 34px -18px rgba(60,48,32,.45)`
- **Panel (heavier)**: `0 1px 2px rgba(60,48,32,.05), 0 16px 36px -22px rgba(60,48,32,.3)`
- **Player**: `0 1px 2px rgba(60,48,32,.08), 0 22px 46px -26px rgba(60,48,32,.5)`
- **Terracotta button**: `0 1px 2px rgba(90,40,20,.2), 0 12px 22px -14px rgba(90,40,20,.55)`
- **Olive button**: `0 1px 2px rgba(50,60,30,.18), 0 10px 20px -14px rgba(50,60,30,.55)`
- **Inset ring** (used instead of borders): `inset 0 0 0 1px rgba(60,48,32,.08)`
Radii: 16px hero/status blocks · 15px panels · 13px tiles · 12px thumbnails/player · 10px inputs & dark buttons · 9px buttons, nav pills, logo mark · 8px chips and fields · 5–6px overlay badges · 50% avatars and play button.
Media ratios: 16/9 VOD thumbnails and player · 4/3 clip thumbnails · 16/7 upload drop zone.
---
## 4. Layout
- Shell: `252px` sidebar + fluid main; collapsed rail is `62px`.
- Main padding `40px 52px 72px`, content max-width `1060–1180px`.
- Library grids: 3 columns for VODs (gap 22px), 4 for clips (gap 18–20px).
- Detail and stream pages: content column + `330–340px` sticky side panel, gap 26px.
- Spacing rhythm: 26–34px between sections, 14–20px inside cards, 6–10px label-to-field. Always flex/grid with `gap`.
---
## 5. Motion & state
- `livePulse` — 2.2s ease-in-out infinite opacity/scale pulse, live dot only. Nothing else animates decoratively.
- Hover: background shifts one step darker within the same family; cards deepen their shadow. No transforms.
- Selection: `#F6EFE6` fill plus a `1.5px` terracotta inset ring.
- Progress is always a bar with a stage word and remaining time (`queued → reading source → encoding → writing file → complete`) — never a spinner.
---
## 6. Copy tone
Lowercase mono for machine facts, sentence case for everything else. Personal and specific ("Cat walks across the patch bay"), never marketing voice. Durations as `h:mm:ss`, timecodes as `hh:mm:ss`, sizes in MB/GB.

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,9 +2,14 @@
<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" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Newsreader:wght@100;200;300;400;500;600;700&family=IBM+Plex+Sans:wght@100;200;300;400;500;600;700&family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<title>The VoD System</title>
</head>
<body>
<div id="root"></div>

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,42 +0,0 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

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,14 +0,0 @@
import clsx from "clsx";
type Props = {
children: React.ReactNode;
className?: string;
};
const Box = ({ children, className }: Props) => (
<div className={clsx("bg-white border border-gray-200 shadow-sm rounded-lg", className)}>
{children}
</div>
);
export default Box;

View File

@@ -0,0 +1,14 @@
import clsx from "clsx";
type Props = {
children: React.ReactNode;
className?: string;
};
const Card = ({ children, className }: Props) => (
<div className={clsx("bg-card shadow-md rounded-lg", className)}>
{children}
</div>
);
export default Card;

View File

@@ -0,0 +1,17 @@
import {Lock} from "lucide-react";
const NoAccessPage = () => {
return (
<div className="w-full min-h-screen flex flex-col items-center justify-center gap-3 text-center px-6">
<Lock className="w-8 h-8 text-faint-mono/60 mb-1" strokeWidth={1.5} />
<h2 className="font-heading text-2xl md:text-3xl text-faint-mono">
Log in to see this page
</h2>
<p className="text-sm text-faint-mono/70 max-w-xs">
Sign in with Google to view your clips and account details.
</p>
</div>
);
}
export default NoAccessPage;

View File

@@ -1,48 +1,106 @@
import clsx from "clsx";
import SidebarButton from "./buttons/SidebarButton.tsx";
import { Plus, Film, Home, User as UserIcon } from 'lucide-react';
import type {User} from "../utils/types.ts";
import { Plus, Film, Home, Video, Radio } from 'lucide-react';
import {useAuth} from "../utils/AuthContext.tsx";
import {type CredentialResponse, GoogleLogin} from "@react-oauth/google";
import {getUser, login, logout} from "../utils/api/users.ts";
type props = {
user: User | null;
className?: string
}
const Divider = () => <hr className="my-1.5 mx-2 border-gray-100" />;
const Divider = () => <hr className="w-full my-1.5 mx-2 border-hover" />;
const Sidebar = ({ className }: props) => {
const { user, setUser } = useAuth()
const handleLogin = (response: CredentialResponse) => {
if (!response.credential) {
console.error("No credential received from Google login.");
return;
}
login(response.credential)
.then(() => {
getUser().then(userData => setUser(userData))
})
.catch((error) => {
console.error("Login failed:", error);
});
}
const handleLogout = () => {
logout()
.then(() =>
setUser(null)
)
.catch((error) => {
console.error("Logout failed:", error);
});
}
const Sidebar = ({user, className}: props) => {
return (
<aside className={clsx("h-screen flex flex-col bg-white border-r border-gray-200", className)}>
<div className="px-4 pt-5 pb-3">
<img
className="w-36 mx-auto"
src="../../public/logo.png"
alt="VoD System Logo"
/>
</div>
<nav className="flex flex-col flex-1 px-2 pb-4">
<div className="flex flex-col gap-0.5">
<aside className={clsx("h-screen flex flex-col bg-sidebar border-r border-hairline p-2 items-center gap-1", className)}>
<h2 className={"font-heading text-3xl"}>The VoD System</h2>
<nav className="flex flex-col flex-1 items-center">
<Divider />
<div className="flex flex-col gap-0.5 w-full">
<SidebarButton url="/" logo={<Home size={18}/>} label="Home" />
<SidebarButton url="/create" logo={<Plus size={18}/>} label="Create Clip" />
<SidebarButton url="/create" logo={<Plus size={18}/>} label="Upload" />
</div>
<Divider />
{user && (
<>
<Divider />
<div className="flex flex-col gap-0.5">
<div className="flex flex-col gap-0.5 w-full">
<div>
<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>
</div>
</>
)}
<div className="flex-1" />
{user && (
<>
<div className={"p-2"}>
{user ? (
<div>
<Divider />
<SidebarButton url="/profile" logo={<UserIcon size={18}/>} label="Profile" />
</>
<div className={"flex gap-2 items-center pt-1"}>
<img
className={"w-8 h-8 rounded-full inline-block"}
src={user.profilePictureUrl}
referrerPolicy="no-referrer"
alt={"Profile Picture"}
/>
<label className={"font-body text-text-strong text-sm"}>
{user.name}
</label>
<button
className={"font-body text-muted text-xs hover:bg-hover p-1 pt-1.5 rounded"}
onClick={handleLogout}
>
Sign Out
</button>
</div>
</div>
) : (
<div>
<Divider />
<GoogleLogin
shape={"pill"}
useOneTap={false}
onSuccess={
(credentialResponse) => handleLogin(credentialResponse
)}
/>
</div>
)}
</div>
</nav>
</aside>
);

View File

@@ -1,103 +0,0 @@
import { Menu, X } from 'lucide-react';
import { login, logout } from "../utils/endpoints.ts";
import { Dropdown, DropdownItem } from "./Dropdown.tsx";
import { GoogleLogin } from '@react-oauth/google';
import type { User } from "../utils/types.ts";
import type { CredentialResponse } from '@react-oauth/google';
import MenuButton from "./buttons/MenuButton.tsx";
import clsx from "clsx";
import {useNavigate} from "react-router-dom";
type props = {
sidebarToggled: boolean;
setSidebarToggled: (toggled: boolean) => void;
user: User | null;
fetchUser: () => void;
isStreaming: boolean;
className?: string;
}
const Topbar = ({
sidebarToggled,
setSidebarToggled,
user,
fetchUser,
isStreaming,
className}: props) => {
const navigate = useNavigate();
const handleLogin = (response: CredentialResponse) => {
if (!response.credential) {
console.error("No credential received from Google login.");
return;
}
login(response.credential)
.then(() => {
fetchUser();
navigate(0);
})
.catch((error) => {
console.error("Login failed:", error);
});
}
const handleLogout = () => {
logout()
.then(() => {
fetchUser();
navigate("/");
})
.catch((error) => {
console.error("Logout failed:", error);
});
}
return (
<div className={clsx(className, "flex justify-between items-center px-4 py-2 bg-white border-b border-gray-200")}>
<MenuButton onClick={() => setSidebarToggled(!sidebarToggled)}>
{sidebarToggled ? <Menu size={24}/> : <X size={24}/>}
</MenuButton>
{ user ? (
<div>
<img
className={"w-8 h-8 rounded-full inline-block"}
src={user.profilePictureUrl}
referrerPolicy="no-referrer"
/>
<Dropdown label={
<span className="flex items-center gap-1.5">
{user.name}
{isStreaming && (
<span className="relative flex h-2 w-2">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-500 opacity-75" />
<span className="relative inline-flex rounded-full h-2 w-2 bg-red-500" />
</span>
)}
</span>
}>
<DropdownItem item="Profile"
onClick={() => navigate("/profile")} />
<DropdownItem item="Logout"
onClick={() => handleLogout()}
className={"text-red-500 font-medium"} />
</Dropdown>
</div>
) :
(
<GoogleLogin
shape={"pill"}
useOneTap={false}
onSuccess={(credentialResponse) => handleLogin(credentialResponse)} />
)}
</div>
)
}
export default Topbar;

View File

@@ -1,15 +0,0 @@
import React from "react";
import clsx from "clsx";
type Props = React.ButtonHTMLAttributes<HTMLButtonElement>;
const MenuButton: React.FC<Props> = ({ className = "", ...props }) => {
return (
<button
className={clsx("p-2 rounded-md text-gray-600 hover:bg-gray-100 hover:text-gray-900 transition-colors duration-150", className)}
{...props}
/>
);
};
export default MenuButton;

View File

@@ -1,5 +1,5 @@
import MenuButton from "./MenuButton.tsx";
import { Link, useLocation } from "react-router-dom";
import React from "react";
type Props = {
url: string;
@@ -13,9 +13,15 @@ const SidebarButton = ({url, logo, label}: Props) => {
return (
<Link className="w-full" to={url}>
<MenuButton className={`flex items-center gap-2.5 w-full px-3 py-2 text-sm font-medium rounded-md ${isActive ? "bg-gray-100 text-gray-900" : "text-gray-600"}`}>
<button className={`flex items-center gap-2.5 w-full text-sm
font-body p-2 hover:bg-hover hover:text-text-strong
rounded-md
${isActive ?
"bg-card text-text-strong font-medium shadow-sm"
:
"text-text-primary"}`}>
{logo}{label}
</MenuButton>
</button>
</Link>
)
}

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

@@ -1,33 +1,27 @@
@import "tailwindcss";
@plugin "flowbite-react/plugin/tailwindcss";
@source "../.flowbite-react/class-list.json";
@theme {
--font-sans: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
/* Fonts */
/*--font-heading: "Newsreader", serif; */
--font-body: "IBM Plex Sans", sans-serif;
--font-data: "IBM Plex Mono", monospace;
/* Breakpoints */
--breakpoint-3xl: 1920px;
/* Colours */
--color-background: #F7F4EE;
--color-sidebar: #F2EEE6;
--color-card: #FDFBF7;
--color-accent: #A85A38;
--color-accent-hover: #94492A;
--color-live-card: #F0EBE1;
--color-primary: oklch(0.55 0.21 254);
--color-primary-pressed: oklch(0.45 0.21 254);
--color-secondary: oklch(0.94 0.01 250);
--color-accent: oklch(0.68 0.20 288);
--color-text: oklch(0.17 0.01 270);
--color-background: oklch(0.97 0.005 250);
--color-surface: oklch(1 0 0);
--color-border: oklch(0.91 0.008 250);
/* Easing */
--ease-fluid: cubic-bezier(0.3, 0, 0, 1);
--ease-snappy: cubic-bezier(0.2, 0, 0, 1);
}
#range-slider .range-slider__range {
background: var(--color-primary);
}
#range-slider .range-slider__thumb {
background: var(--color-primary);
/* Colour Fonts */
--color-text-primary: #2B2620;
--color-text-strong: #35302A;
--color-faint-mono: #A79C8E;
--color-muted: #9A9084;
--color-hover: #E7E0D2;
--color-hairline: #F0EBE2;
}
:root {
@@ -42,4 +36,10 @@
body {
background-color: var(--color-background);
font-family: "IBM Plex Sans", sans-serif;
}
@utility font-heading {
font-family: "Newsreader", serif;
font-weight: 400;
}

View File

@@ -1,50 +1,16 @@
// layout/MainLayout.jsx
import Sidebar from '../components/Sidebar'
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 { useState } from "react";
const MainLayout = () => {
const [sidebarToggled, setSidebarToggled] = useState(false);
const [user, setUser] = useState<null | User>(null);
const [isStreaming, setIsStreaming] = useState(false);
const fetchUser = async () => {
try {
const userData = await getUser();
setUser(userData);
} catch (error) {
console.error('Failed to fetch user:', error);
}
};
useEffect(() => {
fetchUser();
}, []);
useEffect(() => {
if (!user) return;
const poll = () => getStreamStatus().then(setIsStreaming).catch(() => {});
poll();
const interval = setInterval(poll, 10000);
return () => clearInterval(interval);
}, [user]);
const [sidebarToggled] = useState(false);
return (
<div className={`transition-all duration-300 grid h-screen ${sidebarToggled ? "grid-cols-[0px_1fr]" : "grid-cols-[240px_1fr]"} grid-rows-[auto_1fr]`}>
<div className={`transition-all duration-300 grid h-screen ${sidebarToggled ? "grid-cols-[0px_1fr]" : "grid-cols-[280px_1fr]"} grid-rows-[auto_1fr]`}>
<Sidebar
user={user}
className={`row-span-2 transition-all duration-300 overflow-hidden whitespace-nowrap ${sidebarToggled ? "-translate-x-full" : "translate-x-0"}`}/>
<Topbar
className={"transition-all duration-300"}
sidebarToggled={sidebarToggled}
setSidebarToggled={setSidebarToggled}
user={user}
fetchUser={fetchUser}
isStreaming={isStreaming}/>
<div className="overflow-auto bg-background">
<div>
<Outlet />
</div>
</div>

View File

@@ -1,10 +1,13 @@
import './index.css'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import {AuthProvider} from "./utils/AuthContext.tsx";
createRoot(document.getElementById('root')!).render(
<StrictMode>
<AuthProvider>
<App />
</AuthProvider>
</StrictMode>,
)

View File

@@ -5,9 +5,10 @@ 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 Card from "../components/Card.tsx";
import MetadataBox from "../components/video/MetadataBox.tsx";
const API_URL = import.meta.env.VITE_API_URL;
@@ -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);
});
};
@@ -123,13 +132,13 @@ const ClipEdit = () => {
onLoadedMetadata={handleVideoMetadataLoaded}
/>
<Box className={"w-4/5 h-full m-auto"}>
<Card className={"w-4/5 h-full m-auto"}>
<MetadataBox setMetadata={setOutputMetadata} />
<ConfigBox setMetadata={setOutputMetadata} />
</Box>
</Card>
{metadata &&
<Box className={"mt-4 p-5"}>
<Card className={"mt-4 p-5"}>
<Playbar
video={videoRef.current}
videoMetadata={metadata}
@@ -157,17 +166,18 @@ const ClipEdit = () => {
{error}
</div>
)}
</Box>
</Card>
}
<Box className={"flex flex-col gap-2 w-4/5 m-auto mt-4 p-5"}>
<Card className={"flex flex-col gap-2 w-4/5 m-auto mt-4 p-5"}>
<ExportWidget
dataSend={sendData}
handleDownload={handleDownload}
downloadable={downloadable}
progress={progress}
uploading={uploading}
/>
</Box>
</Card>
</div>
);
};

View File

@@ -1,7 +1,7 @@
import {useState} from "react";
import {useNavigate} from "react-router-dom";
import BlueButton from "../components/buttons/BlueButton.tsx";
import Box from "../components/Box.tsx";
import Card from "../components/Card.tsx";
const ClipUpload = () => {
const [file, setFile] = useState<File | null>(null);
@@ -18,7 +18,7 @@ const ClipUpload = () => {
return (
<div className="flex items-start justify-center p-8 min-h-full">
<Box className="flex flex-col gap-4 p-6 w-full max-w-md">
<Card className="flex flex-col gap-4 p-6 w-full max-w-md">
<h1 className="text-lg font-semibold text-gray-900">Upload Clip</h1>
<input
@@ -34,7 +34,7 @@ const ClipUpload = () => {
<BlueButton onClick={press}>Upload</BlueButton>
{error && <p className="text-sm text-red-500 text-center">{error}</p>}
</Box>
</Card>
</div>
)
};

View File

@@ -1,8 +1,8 @@
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 Box from "../components/Box.tsx";
import { getClipById, patchClip } from "../utils/api/clips.ts";
import Card from "../components/Card.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";
@@ -61,7 +61,7 @@ const EditClip = () => {
{loading ? (
<div className="text-gray-400 text-sm">Loading...</div>
) : (
<Box className="p-6 flex flex-col gap-4">
<Card 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
@@ -99,7 +99,7 @@ const EditClip = () => {
Cancel
</button>
</div>
</Box>
</Card>
)}
</div>
);

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 Card from "../components/Card.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>
) : (
<Card 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>
</Card>
)}
</div>
);
};
export default EditVod;

View File

@@ -1,78 +1,84 @@
import { Upload, Scissors, SlidersHorizontal, Radio, LayoutGrid, Play } from "lucide-react";
import {useAuth} from "../utils/AuthContext.tsx";
import NoAccessPage from "../components/NoAccessPage.tsx";
import {Link} from "react-router-dom";
import Card from "../components/Card.tsx";
const features = [
{
icon: Upload,
title: "Upload & compress",
description: "Drop in a video file, set your clip range and export settings, then compress.",
},
{
icon: Scissors,
title: "Trim",
description: "Set start and end points with a range slider. Preview as you go.",
},
{
icon: SlidersHorizontal,
title: "Export settings",
description: "Choose resolution, frame rate, and an optional file size cap.",
},
{
icon: Radio,
title: "RTMP streaming",
description: "Point OBS at your stream key and go live. Find the key in your profile.",
},
{
icon: LayoutGrid,
title: "Clip library",
description: "Browse all your clips. Watch, rename, edit the description, or delete.",
},
{
icon: Play,
title: "Built-in player",
description: "Scrub, adjust volume, go fullscreen. Runs in the browser.",
},
];
type TimeOfDay = "morning" | "afternoon" | "evening" | "night";
function getTimeOfDay(date: Date = new Date()): TimeOfDay {
const hour = date.getHours();
if (hour >= 5 && hour < 12) return "morning";
if (hour >= 12 && hour < 17) return "afternoon";
if (hour >= 17 && hour < 22) return "evening";
return "night";
}
function getGreetingSubtext(date: Date = new Date()): string {
const timeOfDay = getTimeOfDay(date);
const messages: Record<TimeOfDay, string[]> = {
morning: [
"Good morning.",
"Coffee first, then clips.",
"Here's what's waiting for you.",
],
afternoon: [
"Good afternoon.",
"A quiet moment for your clips.",
"Catching up?",
],
evening: [
"Good evening.",
"Settle in.",
"Time to unwind.",
],
night: [
"Still up?",
"Quiet night for it.",
"Good night, when you're ready.",
]
}
const options = messages[timeOfDay];
return options[Math.floor(Math.random() * options.length)];
}
const Home = () => {
const { user } = useAuth();
const now = new Date();
const formatted: string = new Intl.DateTimeFormat('en-IE', {
weekday: 'long',
day: 'numeric',
month: 'long',
}).format(now);
if (user == null) {
return (<NoAccessPage />)
}
return (
<div className="flex flex-col items-center px-8 py-12 min-h-full">
{/* Hero */}
<div className="flex flex-col items-center text-center max-w-2xl mb-14">
<img
src="/logo.png"
alt="VoD System Logo"
className="h-24 mb-6 object-contain"
/>
<h1 className="text-4xl font-semibold text-gray-900 mb-3 leading-tight">
A home for your clips.
</h1>
<p className="text-base text-gray-500 leading-relaxed">
Upload, trim, and export video clips. Stream live if you need to.
</p>
</div>
{/* Feature grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 w-full max-w-4xl mb-10">
{features.map(({ icon: Icon, title, description }) => (
<div
key={title}
className="bg-white border border-gray-200 rounded-xl p-5 flex flex-col gap-3 shadow-sm"
>
<div className="w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
<Icon size={18} className="text-primary" />
</div>
<div className={"w-10/12 m-auto pt-10"}>
<div className={"flex flex-row justify-between items-start pb-10"}>
<div>
<p className="font-semibold text-gray-900 text-sm mb-1">{title}</p>
<p className="text-sm text-gray-500 leading-relaxed">{description}</p>
</div>
</div>
))}
<p className={"font-data text-faint-mono text-sm tracking-widest"}>{formatted.toLocaleUpperCase()}</p>
<h1 className={"font-heading font text-5xl text-text-strong tracking-[-0.015em]"}>{getGreetingSubtext(new Date())}</h1>
</div>
<Link to={"/stream"} className={"bg-accent rounded-md text-hover text-sm p-2 hover:bg-accent-hover shadow-md"}>
Open Stream Panel
</Link>
</div>
<Card className={"bg-live-card pb-10"}>
<p></p>
</Card>
<div>
<h2 className={"font-heading text-2xl"}>Recent VoDs</h2>
</div>
{/* Format note */}
<p className="text-xs text-gray-400">
Supports MP4, MOV, WebM, and OGG.
</p>
</div>
);
};

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 Box from "../components/Box.tsx";
import { AuthError } from "../utils/api/client.ts";
import Card from "../components/Card.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,19 +332,19 @@ 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...
</div>
)}
<Box className="p-4 flex-shrink-0">
<p className="text-xl font-semibold text-gray-900">{clip?.title || "(No Title)"}</p>
<Card className="p-4 flex-shrink-0">
<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>
</Card>
</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 Card from "../components/Card.tsx";
import { getUser } from "../utils/api/users.ts";
import type { User } from "../utils/types.ts";
import { formatLocalDate } from "../utils/utils.ts";
@@ -33,7 +33,7 @@ const Profile = () => {
<div className="px-8 py-10 max-w-2xl mx-auto">
<h1 className="text-2xl font-semibold text-gray-900 mb-6">Profile</h1>
<Box className="p-6 mb-4 flex items-center gap-5">
<Card className="p-6 mb-4 flex items-center gap-5">
<img
src={user.profilePictureUrl}
referrerPolicy="no-referrer"
@@ -48,9 +48,9 @@ const Profile = () => {
Member since {formatLocalDate(user.createdAt)}
</p>
</div>
</Box>
</Card>
<Box className="p-6">
<Card className="p-6">
<h2 className="text-sm font-semibold text-gray-800 mb-1">Stream Key</h2>
<p className="text-sm text-gray-500 mb-4">
Use this key in OBS or any RTMP-compatible software to start streaming.
@@ -78,7 +78,7 @@ const Profile = () => {
{copied ? <Check size={16} className="text-green-600" /> : <Copy size={16} />}
</button>
</div>
</Box>
</Card>
</div>
);
};

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 Card from "../components/Card.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 */}
<Card 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" />
)}
</Card>
{isStreaming && (
<>
{/* Quick mark toolbar */}
<Card 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>
)}
</Card>
{/* Forefront actions */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-5 items-stretch">
<Card 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>
</Card>
<Card 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>
</Card>
</div>
<Card 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>
)}
</Card>
</>
)}
</div>
);
};
export default StreamControl;

View File

@@ -0,0 +1,42 @@
import React, {createContext, useContext, useState, useEffect, type ReactNode} from 'react';
import { getUser } from "./api/users.ts";
import type {User} from "./types.ts";
// for what the Auth object will look like
interface AuthContextValue {
user: User | null;
setUser: React.Dispatch<React.SetStateAction<User | null>>;
loading: boolean;
}
interface AuthProviderProps {
children: ReactNode;
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
export function AuthProvider({children}: AuthProviderProps) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
getUser()
.then(setUser)
.catch(() => setUser(null))
.finally(() => setLoading(false));
}, []);
return (
<AuthContext.Provider value={{ user, setUser, loading }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthContextValue {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}

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)

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