first commit

This commit is contained in:
2026-04-26 21:27:00 +07:00
commit 3ce6f0510b
48 changed files with 9700 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+32
View File
@@ -0,0 +1,32 @@
# IPCam Orange Pi Dashboard — Architecture
## Thành phần
- IP Cameras (RTSP, H264)
- MediaMTX (proxy WebRTC + recorder + Control API)
- Backend FastAPI
- MediaMTX API wrapper
- Scheduler ghi hình theo lịch
- Recording index API + serve file video
- Lưu cấu hình (camera list + schedule)
- Frontend React
- Live grid (WebRTC)
- Playback (file list + HTML5 video)
- Settings (camera + schedule)
## Luồng dữ liệu
- Live: Camera → MediaMTX → WebRTC → Browser
- Playback: Camera → MediaMTX → fMP4 trên đĩa → Backend serve → Browser
## API hợp đồng (mức tối thiểu)
- `GET /api/health`
- `GET /api/paths` (trạng thái stream từ MediaMTX)
- `GET /api/config` (camera + schedule)
- `POST /api/recording` (bật/tắt ghi hình ngay)
- `POST /api/scheduler/enabled` (bật/tắt scheduler)
- `POST /api/scheduler/schedule` (cập nhật lịch)
- `GET /api/recordings?camera=cam1&date=YYYY-MM-DD`
- `GET /videos/<camera>/<file>.fmp4`
+41
View File
@@ -0,0 +1,41 @@
# IPCam Orange Pi Dashboard — Requirements
## Mục tiêu
Xây dựng dashboard giám sát camera IP gọn nhẹ chạy tốt trên Orange Pi, dựa trên MediaMTX để:
- Xem live WebRTC độ trễ thấp
- Phát lại file ghi (fMP4) theo camera + ngày
- Quản lý camera và lịch ghi hình
- Backend điều khiển ghi hình bằng MediaMTX Control API (không chạy AI)
## Tính năng
### Live View
- Hiển thị dạng lưới (mặc định 2x2; có thể mở rộng)
- Lazy-load stream
- Auto reconnect
- Trạng thái online/offline
- Nút fullscreen + reload
### Playback
- Chọn camera + chọn ngày
- Danh sách file theo thời gian (mới nhất trước)
- Phát file bằng HTML5 video
- Tải file (download)
### Settings
- Camera management: thêm/xóa camera (từ dashboard), đồng bộ cấu hình paths lên MediaMTX
- Recording schedule:
- Weekdays: 18:00 → 08:00
- Weekend: 24h
- Backend chạy scheduler mỗi 60 giây
## Ràng buộc
- Camera nên dùng H264 (trình duyệt không hỗ trợ H265 phổ biến)
- MediaMTX cần mở cổng: 8554 (RTSP), 8889 (WebRTC HTTP), 9997 (Control API), 8189/UDP (ICE)
+159
View File
@@ -0,0 +1,159 @@
# IPCam Orange Pi Dashboard — INSTALL
Tài liệu này hướng dẫn triển khai trên Orange Pi (Linux). Mục tiêu: MediaMTX chạy như media server, FastAPI chạy như dashboard backend, React build ra static.
## 1) Yêu cầu
- Orange Pi chạy Debian/Ubuntu
- MediaMTX đã cài và chạy được
- Python 3.9+ (khuyến nghị 3.10+)
- Node.js 20+ (để build frontend)
## 2) MediaMTX cấu hình tối thiểu
Trong file `mediamtx.yml`:
```yaml
api: yes
apiAddress: :9997
webrtc: yes
webrtcAddress: :8889
record: yes
recordFormat: fmp4
recordPath: /recordings/%path/%Y-%m-%d_%H-%M-%S-%f
recordPartDuration: 5m
```
Trong `paths`, bạn có thể để dashboard tự thêm path bằng API (Settings → Add Camera).
Tạo thư mục recordings:
```bash
sudo mkdir -p /recordings
sudo chown -R $USER:$USER /recordings
```
Mở firewall/cổng (tuỳ hệ thống):
- `8554/tcp` RTSP
- `8889/tcp` WebRTC HTTP
- `9997/tcp` MediaMTX Control API
- `8189/udp` ICE
## 3) Backend FastAPI
### 3.1 Cài dependencies
```bash
cd IPCam_OrangePi_Dashboard
python3 -m venv api/.venv
source api/.venv/bin/activate
pip install -r api/requirements.txt
```
### 3.2 Cấu hình
Chạy backend lần đầu sẽ tự tạo `api/data/config.json`.
Bạn có thể chỉnh:
- `mediamtx_api_url` (mặc định `http://127.0.0.1:9997`)
- `mediamtx_webrtc_url` (mặc định `http://127.0.0.1:8889`)
- `recordings_dir` (mặc định `/recordings`)
Nếu MediaMTX API có auth, export biến môi trường:
```bash
export MEDIAMTX_API_USER="..."
export MEDIAMTX_API_PASS="..."
```
### 3.3 Chạy backend
```bash
source api/.venv/bin/activate
uvicorn api.app.main:app --host 0.0.0.0 --port 8000
```
## 4) Frontend (build static)
### 4.1 Build
```bash
cd IPCam_OrangePi_Dashboard
npm install
npm run build
```
Output nằm ở `dist/`.
### 4.2 Serve frontend
Có 2 cách phổ biến:
1) Nginx serve `dist/` và reverse proxy `/api` + `/videos` về backend `:8000`
2) Dùng Caddy tương tự
Ví dụ Nginx server block tối thiểu:
```nginx
server {
listen 80;
server_name _;
root /opt/ipcam-dashboard/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://127.0.0.1:8000;
}
location /videos/ {
proxy_pass http://127.0.0.1:8000;
}
}
```
## 5) Systemd service (khuyến nghị)
### 5.1 Backend service
Tạo file `/etc/systemd/system/ipcam-dashboard.service`:
```ini
[Unit]
Description=IPCam Dashboard Backend
After=network.target
[Service]
WorkingDirectory=/opt/ipcam-dashboard
Environment=MEDIAMTX_API_USER=
Environment=MEDIAMTX_API_PASS=
ExecStart=/opt/ipcam-dashboard/api/.venv/bin/uvicorn api.app.main:app --host 0.0.0.0 --port 8000
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
```
Enable:
```bash
sudo systemctl daemon-reload
sudo systemctl enable --now ipcam-dashboard
sudo systemctl status ipcam-dashboard
```
## 6) Kiểm tra nhanh
- Backend: `curl http://localhost:8000/api/health`
- MediaMTX API: `curl http://localhost:9997/v3/paths/list`
- Frontend: mở `http://<orange-pi-ip>/`
+194
View File
@@ -0,0 +1,194 @@
# IPCam Orange Pi Dashboard - FastAPI Backend Skeleton
## 1. Project Structure
```
ipcam-dashboard/
├── main.py
├── mediamtx.py
├── scheduler.py
├── models.py
├── config.py
└── requirements.txt
```
---
## 2. requirements.txt
```
fastapi
uvicorn
httpx
pydantic
```
---
## 3. config.py
```python
MEDIAMTX_API = "http://127.0.0.1:9997"
CAMERAS = ["cam1", "cam2", "cam3", "cam4"]
```
---
## 4. mediamtx.py (MediaMTX API wrapper)
```python
import httpx
from config import MEDIAMTX_API, CAMERAS
async def set_recording(enabled: bool):
payload = {
"paths": {
cam: {"record": enabled}
for cam in CAMERAS
}
}
async with httpx.AsyncClient() as client:
r = await client.post(
f"{MEDIAMTX_API}/v3/config/paths/patch",
json=payload,
timeout=5
)
return r.json()
async def get_paths():
async with httpx.AsyncClient() as client:
r = await client.get(f"{MEDIAMTX_API}/v3/paths/list")
return r.json()
```
---
## 5. scheduler.py
```python
from datetime import datetime
from mediamtx import set_recording
_last_state = None
def is_record_time(now: datetime) -> bool:
day = now.weekday() # 0=Mon
hour = now.hour
# Weekend: always record
if day in (5, 6):
return True
# Weekdays: 18:00 → 08:00
return hour >= 18 or hour < 8
async def scheduler_loop():
global _last_state
while True:
now = datetime.now()
should_record = is_record_time(now)
if _last_state != should_record:
print(f"[Scheduler] Set recording = {should_record}")
await set_recording(should_record)
_last_state = should_record
import asyncio
await asyncio.sleep(60)
```
---
## 6. models.py
```python
from pydantic import BaseModel
class RecordingToggle(BaseModel):
enabled: bool
```
---
## 7. main.py
```python
from fastapi import FastAPI
import asyncio
from mediamtx import set_recording, get_paths
from scheduler import scheduler_loop
from models import RecordingToggle
app = FastAPI()
@app.on_event("startup")
async def startup():
asyncio.create_task(scheduler_loop())
@app.get("/")
async def root():
return {"status": "ok"}
@app.get("/paths")
async def list_paths():
return await get_paths()
@app.post("/recording")
async def toggle_recording(data: RecordingToggle):
return await set_recording(data.enabled)
```
---
## 8. Run Server
```
uvicorn main:app --host 0.0.0.0 --port 8000
```
---
## 9. API Endpoints
### Get stream status
```
GET /paths
```
### Enable recording
```
POST /recording
{
"enabled": true
}
```
### Disable recording
```
POST /recording
{
"enabled": false
}
```
---
## 10. Next Steps
- Add recordings API (list files)
- Serve video files (StaticFiles)
- Add camera config management (DB or JSON)
- Build frontend dashboard (WebRTC grid)
+192
View File
@@ -0,0 +1,192 @@
# IPCam Orange Pi Dashboard - Frontend UI Specification
## 1. Overview
This document describes the frontend UI/UX design for IPCam Orange Pi Dashboard.
The dashboard includes:
- Live camera monitoring (WebRTC)
- Playback system (recorded files)
- System configuration (camera + schedule)
---
## 2. Layout Structure
```
┌───────────────────────────────┐
│ Header / Navigation │
├───────────────┬───────────────┤
│ Live View │ Playback │
│ (WebRTC Grid) │ (Files list) │
├───────────────┴───────────────┤
│ Settings (modal / tab) │
└───────────────────────────────┘
```
---
## 3. Live View (WebRTC Grid)
### Features
- 4 camera grid (2x2)
- Real-time streaming via WebRTC
- Low latency
- Auto reconnect
### Layout
```
┌────────────┬────────────┐
│ cam1 │ cam2 │
│ [video] │ [video] │
├────────────┼────────────┤
│ cam3 │ cam4 │
│ [video] │ [video] │
└────────────┴────────────┘
```
### Camera Tile Components
- Video player (WebRTC)
- Camera name
- Status indicator (online/offline)
- Buttons:
- Fullscreen
- Reload
### Behavior
- Lazy load streams
- Auto reconnect on failure
- Click to fullscreen
---
## 4. Playback (Recordings)
### Layout
```
┌───────────────┬──────────────────────┐
│ Camera + Date │ File List + Player │
└───────────────┴──────────────────────┘
```
### Left Panel
- Camera selector (dropdown)
- Date picker
### Right Panel
#### File List
```
13:00:00 ▶️ ⬇️
13:05:00 ▶️ ⬇️
13:10:00 ▶️ ⬇️
```
#### Video Player
- HTML5 video player
- Load selected file
### API Integration
- GET /recordings?camera=cam1&date=YYYY-MM-DD
- /videos/<camera>/<file>
### Behavior
- Click ▶️ → play
- Click ⬇️ → download
- Auto load newest file
---
## 5. Settings
## 5.1 Camera Management
### UI
```
Camera List:
[cam1] rtsp://...
[cam2] rtsp://...
[ + Add Camera ]
```
### Add Camera Form
```
Name: camX
RTSP URL: rtsp://...
[ Save ]
```
---
## 5.2 Recording Schedule
### UI
```
Recording Schedule
[ ] Enable scheduler
Weekdays:
From: 18:00
To: 08:00
Weekend:
[x] Record all day
```
### Logic
- Controlled by backend scheduler
- Uses MediaMTX API
---
## 6. Navigation
```
[ Live ] [ Playback ] [ Settings ]
```
---
## 7. Tech Stack
- HTML / CSS / JS (or React)
- WebRTC player
- REST API integration
---
## 8. Constraints
- Requires H264 cameras (browser support)
- Requires open ports:
- 8889 (WebRTC HTTP)
- 8189/UDP (ICE)
---
## 9. Future Enhancements
- Timeline playback
- Multi-camera playback
- Mobile UI
- Authentication
---
## 10. Summary
Frontend responsibilities:
- Render WebRTC streams
- Display recordings
- Control system configuration
This UI completes the full system:
Camera → MediaMTX → Backend → Frontend
+198
View File
@@ -0,0 +1,198 @@
# IPCam Orange Pi Dashboard (Updated)
## 1. Overview
IPCam Orange Pi Dashboard is a lightweight web-based surveillance system built on top of MediaMTX.
The system is designed for:
- Orange Pi (low-resource hardware)
- Multiple IP cameras (410 cams)
- No AI processing (unlike Frigate)
- Full control via MediaMTX Control API
---
## 2. Architecture
### Components
- IP Cameras (RTSP - H264 recommended)
- MediaMTX (stream proxy + recorder + API)
- Dashboard Backend (scheduler + API)
- Dashboard Frontend (live view + playback UI)
### Data Flow
Camera → MediaMTX → WebRTC → Dashboard
Camera → MediaMTX → Recording (fMP4) → Storage → Playback UI
---
## 3. Core Features
### 3.1 Live View
- Grid layout (1 / 4 / 9 cameras)
- WebRTC streaming (low latency)
- Auto reconnect
- Lazy loading streams
### 3.2 Playback
- List recordings by:
- Camera
- Date
- Play fMP4 files via HTML5 video
- File-based playback (no timeline initially)
### 3.3 Camera Management
- Add/remove camera (update MediaMTX config)
- Reload MediaMTX if needed
### 3.4 Recording Schedule (IMPORTANT)
- Configure recording time per system:
- Weekdays: 18:00 → 08:00
- Weekend: 24h
- Implemented in Dashboard (NOT MediaMTX)
---
## 4. MediaMTX Integration
### 4.1 Endpoints
- RTSP: rtsp://<server>:8554/<path>
- WebRTC: http://<server>:8889
- API: http://<server>:9997
---
### 4.2 Control API Usage
#### Enable API
```
api: true
apiAddress: :9997
```
---
### 4.3 Toggle Recording via API
#### Enable recording
```
POST /v3/config/paths/patch
{
"paths": {
"cam1": { "record": true }
}
}
```
#### Disable recording
```
POST /v3/config/paths/patch
{
"paths": {
"cam1": { "record": false }
}
}
```
---
### 4.4 Bulk Update
```
{
"paths": {
"cam1": { "record": true },
"cam2": { "record": true },
"cam3": { "record": true },
"cam4": { "record": true }
}
}
```
---
## 5. Scheduler Design
### Logic
- Dashboard backend controls recording
- Runs every 60 seconds
### Example Logic
```
if weekend:
record = true
else:
record = (hour >= 18 or hour < 8)
```
### Implementation
- setInterval / cron job in backend
- Calls MediaMTX API
---
## 6. Storage
### Format
- fMP4 segments
### Path
```
/recordings/<camera>/<timestamp>.fmp4
```
### Notes
- Files created per segment (e.g., 5 minutes)
- Recording starts immediately when enabled
---
## 7. Technology Stack
### Backend
- Node.js (Express) or Python (FastAPI)
- Responsibilities:
- Scheduler
- MediaMTX API integration
- Recording index API
### Frontend
- HTML + JS (or React)
- WebRTC player
- Video playback UI
---
## 8. Performance Requirements
- 45 simultaneous streams
- Minimal CPU usage (no transcoding)
- Stable on Orange Pi
---
## 9. Constraints
- Browser requires H264 (NOT H265)
- WebRTC requires UDP port (8189) open
- Firewall must allow:
- 8554 (RTSP)
- 8889 (WebRTC HTTP)
- 8189/UDP (ICE)
---
## 10. Future Enhancements
- Timeline playback (merge segments)
- Multi-user authentication
- Mobile UI
- Event-based recording (optional)
---
## 11. Summary
- MediaMTX handles streaming + recording
- Dashboard handles logic + scheduling
- Recording is controlled via API (not config reload)
This architecture is optimized for simplicity, performance, and scalability on Orange Pi.
+195
View File
@@ -0,0 +1,195 @@
# IPCam Orange Pi Dashboard - Recording API & Video Serving
## 1. Overview
This module extends the backend to support:
- Listing recorded video files
- Serving video files to frontend (playback)
- Filtering by camera and date
This is REQUIRED for playback feature in dashboard.
---
## 2. Storage Structure (MediaMTX)
Assumed recording path:
```
/recordings/<camera>/<timestamp>.fmp4
```
Example:
```
/recordings/cam1/2026-04-26_13-14-00-123456.fmp4
```
---
## 3. Backend Responsibilities
Backend must:
1. Scan recording directory
2. Parse metadata (camera, timestamp)
3. Provide API for frontend
4. Serve video files via HTTP
---
## 4. Add to requirements.txt
```
python-multipart
```
---
## 5. recordings.py (new module)
```python
import os
from datetime import datetime
BASE_PATH = "/recordings"
def parse_filename(filename: str):
try:
name = filename.replace(".fmp4", "")
dt = datetime.strptime(name, "%Y-%m-%d_%H-%M-%S-%f")
return dt
except:
return None
def list_recordings(camera: str, date: str = None):
cam_path = os.path.join(BASE_PATH, camera)
if not os.path.exists(cam_path):
return []
results = []
for file in os.listdir(cam_path):
if not file.endswith(".fmp4"):
continue
dt = parse_filename(file)
if not dt:
continue
if date:
if dt.strftime("%Y-%m-%d") != date:
continue
results.append({
"camera": camera,
"filename": file,
"timestamp": dt.isoformat(),
"url": f"/videos/{camera}/{file}"
})
# sort newest first
results.sort(key=lambda x: x["timestamp"], reverse=True)
return results
```
---
## 6. Update main.py
```python
from fastapi.staticfiles import StaticFiles
from recordings import list_recordings
# mount video folder
app.mount("/videos", StaticFiles(directory="/recordings"), name="videos")
@app.get("/recordings")
async def get_recordings(camera: str, date: str = None):
return list_recordings(camera, date)
```
---
## 7. API Usage
### List recordings
```
GET /recordings?camera=cam1
```
### Filter by date
```
GET /recordings?camera=cam1&date=2026-04-26
```
---
## 8. Response Example
```json
[
{
"camera": "cam1",
"filename": "2026-04-26_13-14-00-123456.fmp4",
"timestamp": "2026-04-26T13:14:00",
"url": "/videos/cam1/2026-04-26_13-14-00-123456.fmp4"
}
]
```
---
## 9. Playback in Frontend
Use standard HTML:
```html
<video controls width="600">
<source src="http://<server>:8000/videos/cam1/file.fmp4">
</video>
```
---
## 10. Important Notes
### fMP4 compatibility
- Modern browsers support fMP4
- If issues → fallback to HLS later
### File size
- Large files → consider pagination later
### Security (future)
- Add auth before exposing /videos
---
## 11. Next Improvements
- Pagination (limit, offset)
- Thumbnail generation
- Timeline UI
- Merge segments
---
## 12. Summary
This module completes playback pipeline:
MediaMTX → Disk → Backend API → Frontend Player
Without this layer:
- You cannot build usable playback UI
This is a critical component of your system.
+60
View File
@@ -0,0 +1,60 @@
# IPCam Orange Pi Dashboard
Dashboard giám sát camera IP gọn nhẹ chạy trên Orange Pi, dựa trên MediaMTX:
- Live View (WebRTC WHEP) dạng grid, auto reconnect, lazy load
- Playback fMP4 theo camera + ngày (file list + HTML5 video)
- Settings: quản lý camera + lịch ghi hình (scheduler ở backend)
## Cấu trúc thư mục
- `src/`: frontend React
- `api/`: backend FastAPI
- `.trae/documents/`: tài liệu yêu cầu/kiến trúc
## Backend API
- `GET /api/health`
- `GET /api/config`
- `POST /api/cameras` / `DELETE /api/cameras/{name}`
- `GET /api/paths` (proxy trạng thái từ MediaMTX)
- `POST /api/recording` (bật/tắt ghi hình ngay)
- `POST /api/scheduler/enabled` / `POST /api/scheduler/schedule`
- `GET /api/recordings?camera=cam1&date=YYYY-MM-DD`
- `GET /videos/<camera>/<file>.fmp4`
## Chạy dev (máy dev)
### 1) Chạy backend
```bash
python3 -m venv api/.venv
source api/.venv/bin/activate
pip install -r api/requirements.txt
uvicorn api.app.main:app --host 0.0.0.0 --port 8000
```
### 2) Chạy frontend
```bash
npm install
npm run dev
```
Frontend dev server đã được cấu hình proxy `/api``/videos` sang `http://localhost:8000`.
## Cấu hình
Backend tự tạo file cấu hình tại `api/data/config.json` khi chạy lần đầu.
- `mediamtx_api_url`: ví dụ `http://127.0.0.1:9997`
- `mediamtx_webrtc_url`: ví dụ `http://127.0.0.1:8889`
- `recordings_dir`: ví dụ `/recordings`
- `cameras`: danh sách camera (name + rtsp_url)
- `schedule`: lịch ghi hình
Có thể override WebRTC base URL ở frontend bằng biến môi trường `VITE_MEDIAMTX_WEBRTC_URL`.
## Triển khai
Xem hướng dẫn chi tiết trong `INSTALL.md`.
+1
View File
@@ -0,0 +1 @@
+41
View File
@@ -0,0 +1,41 @@
import json
from pathlib import Path
from typing import Optional
import anyio
from .models import AppConfig
class ConfigStore:
def __init__(self, file_path: Path):
self._file_path = file_path
self._lock = anyio.Lock()
def _write_unlocked(self, cfg: AppConfig) -> None:
self._file_path.parent.mkdir(parents=True, exist_ok=True)
self._file_path.write_text(
json.dumps(cfg.model_dump(mode="json"), indent=2, ensure_ascii=False),
encoding="utf-8",
)
async def load(self) -> AppConfig:
async with self._lock:
if not self._file_path.exists():
cfg = AppConfig(cameras=[])
self._write_unlocked(cfg)
return cfg
raw = self._file_path.read_text(encoding="utf-8")
data = json.loads(raw) if raw.strip() else {}
return AppConfig.model_validate(data)
async def save(self, cfg: AppConfig) -> None:
async with self._lock:
self._write_unlocked(cfg)
def default_store(project_root: Optional[Path] = None) -> ConfigStore:
root = project_root or Path(__file__).resolve().parents[2]
return ConfigStore(root / "api" / "data" / "config.json")
+185
View File
@@ -0,0 +1,185 @@
from __future__ import annotations
import asyncio
import os
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from .config_store import default_store
from .mediamtx_client import MediaMTXClient
from .models import (
AppConfig,
Camera,
RecordingToggle,
ScheduleUpdate,
SchedulerEnabled,
)
from .recordings import list_recordings
from .scheduler import Scheduler
def _cors_origins() -> list[str]:
raw = os.getenv("CORS_ORIGINS", "http://localhost:5173")
return [x.strip() for x in raw.split(",") if x.strip()]
app = FastAPI(title="IPCam Dashboard API")
app.add_middleware(
CORSMiddleware,
allow_origins=_cors_origins(),
allow_credentials=True,
allow_methods=["*"] ,
allow_headers=["*"] ,
)
store = default_store()
async def _apply_recording(enabled: bool) -> None:
cfg = await store.load()
names = [c.name for c in cfg.cameras]
if not names:
return
client = MediaMTXClient(
api_url=cfg.mediamtx_api_url,
username=os.getenv("MEDIAMTX_API_USER"),
password=os.getenv("MEDIAMTX_API_PASS"),
)
await client.set_recording_bulk(names, enabled)
scheduler = Scheduler(apply=_apply_recording)
async def _scheduler_loop() -> None:
while True:
try:
cfg = await store.load()
await scheduler.tick(cfg.schedule)
finally:
await asyncio.sleep(60)
@app.on_event("startup")
async def _startup() -> None:
cfg = await store.load()
recordings_dir = cfg.recordings_dir
if Path(recordings_dir).exists():
app.mount("/videos", StaticFiles(directory=recordings_dir), name="videos")
asyncio.create_task(_scheduler_loop())
@app.get("/api/health")
async def health() -> dict:
return {"status": "ok"}
@app.get("/api/config")
async def get_config() -> AppConfig:
return await store.load()
@app.post("/api/cameras")
async def add_camera(camera: Camera) -> AppConfig:
cfg = await store.load()
if any(c.name == camera.name for c in cfg.cameras):
raise HTTPException(status_code=409, detail="camera_already_exists")
cfg.cameras.append(camera)
await store.save(cfg)
client = MediaMTXClient(
api_url=cfg.mediamtx_api_url,
username=os.getenv("MEDIAMTX_API_USER"),
password=os.getenv("MEDIAMTX_API_PASS"),
)
await client.upsert_paths_sources_bulk({camera.name: camera.rtsp_url})
return cfg
@app.delete("/api/cameras/{name}")
async def delete_camera(name: str) -> AppConfig:
cfg = await store.load()
before = len(cfg.cameras)
cfg.cameras = [c for c in cfg.cameras if c.name != name]
if len(cfg.cameras) == before:
raise HTTPException(status_code=404, detail="camera_not_found")
await store.save(cfg)
client = MediaMTXClient(
api_url=cfg.mediamtx_api_url,
username=os.getenv("MEDIAMTX_API_USER"),
password=os.getenv("MEDIAMTX_API_PASS"),
)
await client.delete_path(name)
return cfg
@app.get("/api/paths")
async def list_paths() -> dict:
cfg = await store.load()
client = MediaMTXClient(
api_url=cfg.mediamtx_api_url,
username=os.getenv("MEDIAMTX_API_USER"),
password=os.getenv("MEDIAMTX_API_PASS"),
)
return await client.list_paths_status()
@app.post("/api/recording")
async def toggle_recording(data: RecordingToggle) -> dict:
await _apply_recording(data.enabled)
return {"enabled": data.enabled}
@app.post("/api/scheduler/enabled")
async def set_scheduler_enabled(data: SchedulerEnabled) -> AppConfig:
cfg = await store.load()
cfg.schedule.enabled = data.enabled
await store.save(cfg)
await scheduler.tick(cfg.schedule)
return cfg
@app.post("/api/scheduler/schedule")
async def update_schedule(data: ScheduleUpdate) -> AppConfig:
cfg = await store.load()
cfg.schedule.weekdays_from = data.weekdays_from
cfg.schedule.weekdays_to = data.weekdays_to
cfg.schedule.weekend_all_day = data.weekend_all_day
await store.save(cfg)
await scheduler.tick(cfg.schedule)
return cfg
@app.get("/api/recordings")
async def recordings(
camera: str,
date: Optional[str] = None,
limit: int = 200,
offset: int = 0,
) -> list[dict]:
cfg = await store.load()
if not any(c.name == camera for c in cfg.cameras):
raise HTTPException(status_code=404, detail="camera_not_found")
if limit < 1 or limit > 2000:
raise HTTPException(status_code=400, detail="invalid_limit")
if offset < 0:
raise HTTPException(status_code=400, detail="invalid_offset")
items = list_recordings(cfg.recordings_dir, camera, date, limit, offset)
return [
{
"camera": it.camera,
"filename": it.filename,
"timestamp": it.timestamp,
"url": it.url,
}
for it in items
]
+84
View File
@@ -0,0 +1,84 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Optional
import httpx
@dataclass(frozen=True)
class MediaMTXClient:
api_url: str
username: Optional[str] = None
password: Optional[str] = None
def _auth(self) -> Optional[tuple[str, str]]:
if self.username and self.password:
return (self.username, self.password)
return None
async def list_paths_status(self) -> dict[str, Any]:
async with httpx.AsyncClient(timeout=5) as client:
r = await client.get(f"{self.api_url}/v3/paths/list", auth=self._auth())
r.raise_for_status()
return r.json()
async def set_recording_bulk(self, names: list[str], enabled: bool) -> dict[str, Any]:
payload = {"paths": {name: {"record": enabled} for name in names}}
async with httpx.AsyncClient(timeout=8) as client:
r = await client.post(
f"{self.api_url}/v3/config/paths/patch",
json=payload,
auth=self._auth(),
)
r.raise_for_status()
return r.json()
async def upsert_paths_sources_bulk(self, sources: dict[str, str]) -> dict[str, Any]:
payload = {"paths": {name: {"source": url} for name, url in sources.items()}}
async with httpx.AsyncClient(timeout=10) as client:
r = await client.post(
f"{self.api_url}/v3/config/paths/patch",
json=payload,
auth=self._auth(),
)
if r.status_code != 404:
r.raise_for_status()
return r.json()
results: dict[str, Any] = {"fallback": []}
async with httpx.AsyncClient(timeout=10) as client:
for name, url in sources.items():
rr = await client.post(
f"{self.api_url}/v3/config/paths/add/{name}",
json={"source": url},
auth=self._auth(),
)
if rr.status_code == 409:
rr = await client.patch(
f"{self.api_url}/v3/config/paths/patch/{name}",
json={"source": url},
auth=self._auth(),
)
rr.raise_for_status()
results["fallback"].append({"name": name, "status": rr.status_code})
return results
async def delete_path(self, name: str) -> None:
async with httpx.AsyncClient(timeout=8) as client:
r = await client.delete(
f"{self.api_url}/v3/config/paths/delete/{name}",
auth=self._auth(),
)
if r.status_code in (404, 410):
return
if r.status_code == 405:
rr = await client.post(
f"{self.api_url}/v3/config/paths/patch",
json={"paths": {name: {"source": ""}}},
auth=self._auth(),
)
rr.raise_for_status()
return
r.raise_for_status()
+36
View File
@@ -0,0 +1,36 @@
from pydantic import BaseModel, Field
class Camera(BaseModel):
name: str = Field(min_length=1, max_length=64, pattern=r"^[a-zA-Z0-9_\-\/]+$")
rtsp_url: str = Field(min_length=1, max_length=2048)
class Schedule(BaseModel):
enabled: bool = True
weekdays_from: str = Field(default="18:00", pattern=r"^\d{2}:\d{2}$")
weekdays_to: str = Field(default="08:00", pattern=r"^\d{2}:\d{2}$")
weekend_all_day: bool = True
class AppConfig(BaseModel):
mediamtx_api_url: str = "http://127.0.0.1:9997"
mediamtx_webrtc_url: str = "http://127.0.0.1:8889"
recordings_dir: str = "/recordings"
cameras: list[Camera] = Field(default_factory=list)
schedule: Schedule = Field(default_factory=Schedule)
class RecordingToggle(BaseModel):
enabled: bool
class SchedulerEnabled(BaseModel):
enabled: bool
class ScheduleUpdate(BaseModel):
weekdays_from: str = Field(pattern=r"^\d{2}:\d{2}$")
weekdays_to: str = Field(pattern=r"^\d{2}:\d{2}$")
weekend_all_day: bool
+64
View File
@@ -0,0 +1,64 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Optional
@dataclass(frozen=True)
class RecordingItem:
camera: str
filename: str
timestamp: str
url: str
def _parse_filename(filename: str) -> Optional[datetime]:
if not filename.endswith(".fmp4"):
return None
stem = filename[:-5]
try:
return datetime.strptime(stem, "%Y-%m-%d_%H-%M-%S-%f")
except ValueError:
return None
def list_recordings(
recordings_dir: str,
camera: str,
date: Optional[str],
limit: int,
offset: int,
) -> list[RecordingItem]:
base = Path(recordings_dir)
cam_dir = base / camera
if not cam_dir.exists() or not cam_dir.is_dir():
return []
items: list[tuple[datetime, str]] = []
for p in cam_dir.iterdir():
if not p.is_file():
continue
dt = _parse_filename(p.name)
if dt is None:
continue
if date is not None and dt.strftime("%Y-%m-%d") != date:
continue
items.append((dt, p.name))
items.sort(key=lambda x: x[0], reverse=True)
sliced = items[offset : offset + limit]
out: list[RecordingItem] = []
for dt, name in sliced:
out.append(
RecordingItem(
camera=camera,
filename=name,
timestamp=dt.isoformat(),
url=f"/videos/{camera}/{name}",
)
)
return out
+46
View File
@@ -0,0 +1,46 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, time
from typing import Awaitable, Callable, Optional
from .models import Schedule
def _parse_hhmm(value: str) -> time:
hh, mm = value.split(":")
return time(hour=int(hh), minute=int(mm))
def should_record_now(now: datetime, schedule: Schedule) -> bool:
if not schedule.enabled:
return False
weekday = now.weekday()
if weekday in (5, 6) and schedule.weekend_all_day:
return True
start = _parse_hhmm(schedule.weekdays_from)
end = _parse_hhmm(schedule.weekdays_to)
now_t = now.time().replace(second=0, microsecond=0)
if start == end:
return True
if start < end:
return start <= now_t < end
return now_t >= start or now_t < end
@dataclass
class Scheduler:
apply: Callable[[bool], Awaitable[None]]
_last_state: Optional[bool] = None
async def tick(self, schedule: Schedule) -> None:
now = datetime.now()
state = should_record_now(now, schedule)
if self._last_state != state:
await self.apply(state)
self._last_state = state
+6
View File
@@ -0,0 +1,6 @@
fastapi>=0.110
uvicorn[standard]>=0.27
httpx>=0.27
pydantic>=2.6
python-multipart>=0.0.9
+28
View File
@@ -0,0 +1,28 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
)
+24
View File
@@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Trae Project</title>
<script type="module">
if (import.meta.hot?.on) {
import.meta.hot.on('vite:error', (error) => {
if (error.err) {
console.error(
[error.err.message, error.err.frame].filter(Boolean).join('\n'),
)
}
})
}
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+6781
View File
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
{
"name": "trae-project",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"check": "tsc -b --noEmit",
"test": "node node_modules/vitest/vitest.mjs run"
},
"dependencies": {
"clsx": "^2.1.1",
"lucide-react": "^0.511.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^7.3.0",
"tailwind-merge": "^3.0.2",
"zustand": "^5.0.3"
},
"devDependencies": {
"@eslint/js": "^9.25.0",
"@types/node": "^22.15.30",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.4.1",
"autoprefixer": "^10.4.21",
"babel-plugin-react-dev-locator": "^1.0.0",
"postcss": "^8.5.3",
"tailwindcss": "^3.4.17",
"eslint": "^9.25.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^16.0.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.30.1",
"vite": "^6.3.5",
"vite-plugin-trae-solo-badge": "^1.0.0",
"vite-tsconfig-paths": "^5.1.4",
"vitest": "^2.1.9",
"jsdom": "^25.0.1",
"@testing-library/react": "^16.1.0",
"@testing-library/jest-dom": "^6.6.3"
}
}
+10
View File
@@ -0,0 +1,10 @@
/** WARNING: DON'T EDIT THIS FILE */
/** WARNING: DON'T EDIT THIS FILE */
/** WARNING: DON'T EDIT THIS FILE */
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
+4
View File
@@ -0,0 +1,4 @@
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="32" height="32" fill="#0A0B0D"/>
<path d="M26.6677 23.7149H8.38057V20.6496H5.33301V8.38159H26.6677V23.7149ZM8.38057 20.6496H23.6201V11.4482H8.38057V20.6496ZM16.0011 16.0021L13.8461 18.1705L11.6913 16.0021L13.8461 13.8337L16.0011 16.0021ZM22.0963 16.0008L19.9414 18.1691L17.7865 16.0008L19.9414 13.8324L22.0963 16.0008Z" fill="#32F08C"/>
</svg>

After

Width:  |  Height:  |  Size: 453 B

+21
View File
@@ -0,0 +1,21 @@
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import AppShell from "@/components/AppShell";
import Live from "@/pages/Live";
import Playback from "@/pages/Playback";
import Settings from "@/pages/Settings";
export default function App() {
return (
<Router>
<AppShell>
<Routes>
<Route path="/" element={<Navigate to="/live" replace />} />
<Route path="/live" element={<Live />} />
<Route path="/playback" element={<Playback />} />
<Route path="/settings" element={<Settings />} />
<Route path="*" element={<Navigate to="/live" replace />} />
</Routes>
</AppShell>
</Router>
);
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

+14
View File
@@ -0,0 +1,14 @@
import { ReactNode } from "react";
import TopNav from "@/components/TopNav";
export default function AppShell({ children }: { children: ReactNode }) {
return (
<div className="min-h-dvh bg-zinc-950 text-zinc-50">
<TopNav />
<main className="mx-auto w-full max-w-7xl px-4 py-4 md:px-6 md:py-6">
{children}
</main>
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { Maximize, RefreshCcw } from "lucide-react";
import { useWhepPlayer } from "@/hooks/useWhepPlayer";
type Props = {
name: string;
webrtcBaseUrl: string;
isOnline: boolean;
};
function StatusDot({ online }: { online: boolean }) {
return (
<span
className={[
"inline-flex h-2.5 w-2.5 rounded-full",
online ? "bg-emerald-400" : "bg-rose-400",
].join(" ")}
aria-label={online ? "online" : "offline"}
title={online ? "online" : "offline"}
/>
);
}
export default function CameraTile({ name, webrtcBaseUrl, isOnline }: Props) {
const containerRef = useRef<HTMLDivElement | null>(null);
const [visible, setVisible] = useState(false);
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const io = new IntersectionObserver(
(entries) => {
const entry = entries[0];
setVisible(Boolean(entry?.isIntersecting));
},
{ threshold: 0.2 }
);
io.observe(el);
return () => io.disconnect();
}, []);
const enabled = useMemo(() => visible, [visible]);
const player = useWhepPlayer({ enabled, webrtcBaseUrl, streamName: name });
const onFullscreen = async () => {
const v = player.videoRef.current;
if (!v) return;
const anyV = v as HTMLVideoElement & { webkitRequestFullscreen?: () => Promise<void> | void };
if (v.requestFullscreen) await v.requestFullscreen();
else if (anyV.webkitRequestFullscreen) anyV.webkitRequestFullscreen();
};
return (
<div
ref={containerRef}
className="group relative overflow-hidden rounded-lg border border-zinc-800 bg-zinc-900/30"
>
<div className="absolute left-0 top-0 z-10 flex w-full items-center justify-between gap-2 bg-gradient-to-b from-zinc-950/80 to-transparent px-3 py-2">
<div className="flex items-center gap-2">
<StatusDot online={isOnline} />
<div className="text-xs font-medium text-zinc-100">{name}</div>
<div className="text-[11px] text-zinc-400">
{player.status === "playing" ? "webrtc" : player.status}
</div>
</div>
<div className="flex items-center gap-1 opacity-100 transition md:opacity-0 md:group-hover:opacity-100">
<button
type="button"
onClick={player.restart}
className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
title="Reload"
>
<RefreshCcw className="h-4 w-4" />
</button>
<button
type="button"
onClick={onFullscreen}
className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
title="Fullscreen"
>
<Maximize className="h-4 w-4" />
</button>
</div>
</div>
<div className="aspect-video w-full bg-black">
<video
ref={player.videoRef}
className="h-full w-full object-contain"
muted
playsInline
/>
</div>
{player.status === "error" ? (
<div className="border-t border-zinc-800 px-3 py-2 text-xs text-rose-300">
{player.error ?? "error"}
</div>
) : null}
</div>
);
}
+8
View File
@@ -0,0 +1,8 @@
import { cn } from '@/lib/utils'
// Empty component
export default function Empty() {
return (
<div className={cn('flex h-full items-center justify-center')}>Empty</div>
)
}
+19
View File
@@ -0,0 +1,19 @@
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import TopNav from "@/components/TopNav";
describe("TopNav", () => {
it("renders navigation links", () => {
render(
<MemoryRouter>
<TopNav />
</MemoryRouter>
);
expect(screen.getByText("Live")).toBeInTheDocument();
expect(screen.getByText("Playback")).toBeInTheDocument();
expect(screen.getByText("Settings")).toBeInTheDocument();
});
});
+55
View File
@@ -0,0 +1,55 @@
import { NavLink } from "react-router-dom";
import { Film, Settings2, Video } from "lucide-react";
import type { ReactNode } from "react";
function NavItem({
to,
label,
icon,
}: {
to: string;
label: string;
icon: ReactNode;
}) {
return (
<NavLink
to={to}
className={({ isActive }) =>
[
"inline-flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition",
isActive
? "bg-zinc-800 text-zinc-50"
: "text-zinc-300 hover:bg-zinc-900 hover:text-zinc-50",
].join(" ")
}
>
<span className="inline-flex h-4 w-4 items-center justify-center">{icon}</span>
<span>{label}</span>
</NavLink>
);
}
export default function TopNav() {
return (
<header className="border-b border-zinc-800 bg-zinc-950/70 backdrop-blur">
<div className="mx-auto flex w-full max-w-7xl items-center justify-between gap-4 px-4 py-3 md:px-6">
<div className="flex items-center gap-3">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-zinc-900 ring-1 ring-zinc-800">
<Video className="h-5 w-5" />
</div>
<div className="leading-tight">
<div className="text-sm font-semibold">IPCam Dashboard</div>
<div className="text-xs text-zinc-400">MediaMTX + Orange Pi</div>
</div>
</div>
<nav className="flex items-center gap-1">
<NavItem to="/live" label="Live" icon={<Video className="h-4 w-4" />} />
<NavItem to="/playback" label="Playback" icon={<Film className="h-4 w-4" />} />
<NavItem to="/settings" label="Settings" icon={<Settings2 className="h-4 w-4" />} />
</nav>
</div>
</header>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { useEffect, useMemo, useState } from "react";
import { apiJson } from "@/utils/api";
import type { MediaMtxPathsListResponse } from "@/types/api";
export function usePathsStatus(pollMs: number) {
const [data, setData] = useState<MediaMtxPathsListResponse | null>(null);
useEffect(() => {
let isMounted = true;
let t: number | undefined;
const tick = async () => {
try {
const res = await apiJson<MediaMtxPathsListResponse>("/paths", { method: "GET" });
if (isMounted) setData(res);
} catch {
if (isMounted) setData(null);
} finally {
t = window.setTimeout(tick, pollMs);
}
};
tick();
return () => {
isMounted = false;
if (t) window.clearTimeout(t);
};
}, [pollMs]);
const readyByName = useMemo(() => {
const map = new Map<string, boolean>();
for (const it of data?.items ?? []) {
map.set(it.name, Boolean(it.ready));
}
return map;
}, [data]);
return { raw: data, readyByName };
}
+29
View File
@@ -0,0 +1,29 @@
import { useState, useEffect } from 'react';
type Theme = 'light' | 'dark';
export function useTheme() {
const [theme, setTheme] = useState<Theme>(() => {
const savedTheme = localStorage.getItem('theme') as Theme;
if (savedTheme) {
return savedTheme;
}
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
});
useEffect(() => {
document.documentElement.classList.remove('light', 'dark');
document.documentElement.classList.add(theme);
localStorage.setItem('theme', theme);
}, [theme]);
const toggleTheme = () => {
setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
};
return {
theme,
toggleTheme,
isDark: theme === 'dark'
};
}
+177
View File
@@ -0,0 +1,177 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
type PlayerStatus = "idle" | "connecting" | "playing" | "error";
function withNoTrailingSlash(url: string) {
return url.endsWith("/") ? url.slice(0, -1) : url;
}
async function waitForIceGatheringComplete(pc: RTCPeerConnection) {
if (pc.iceGatheringState === "complete") return;
await new Promise<void>((resolve) => {
const onState = () => {
if (pc.iceGatheringState === "complete") {
pc.removeEventListener("icegatheringstatechange", onState);
resolve();
}
};
pc.addEventListener("icegatheringstatechange", onState);
});
}
export function useWhepPlayer({
enabled,
webrtcBaseUrl,
streamName,
}: {
enabled: boolean;
webrtcBaseUrl: string;
streamName: string;
}) {
const videoRef = useRef<HTMLVideoElement | null>(null);
const pcRef = useRef<RTCPeerConnection | null>(null);
const sessionUrlRef = useRef<string | null>(null);
const abortRef = useRef<AbortController | null>(null);
const [status, setStatus] = useState<PlayerStatus>("idle");
const [error, setError] = useState<string | null>(null);
const [restartNonce, setRestartNonce] = useState(0);
const whepUrl = useMemo(() => {
return `${withNoTrailingSlash(webrtcBaseUrl)}/${encodeURIComponent(streamName)}/whep`;
}, [webrtcBaseUrl, streamName]);
const stop = useCallback(async () => {
abortRef.current?.abort();
abortRef.current = null;
const sessionUrl = sessionUrlRef.current;
sessionUrlRef.current = null;
const pc = pcRef.current;
pcRef.current = null;
if (pc) {
try {
pc.ontrack = null;
pc.onconnectionstatechange = null;
pc.oniceconnectionstatechange = null;
pc.close();
} catch {
}
}
const v = videoRef.current;
if (v) {
try {
v.srcObject = null;
v.removeAttribute("src");
} catch {
}
}
if (sessionUrl) {
try {
await fetch(sessionUrl, { method: "DELETE" });
} catch {
}
}
}, []);
const restart = useCallback(() => {
setRestartNonce((n) => n + 1);
}, []);
useEffect(() => {
let disposed = false;
const run = async () => {
await stop();
if (!enabled) {
setStatus("idle");
setError(null);
return;
}
setStatus("connecting");
setError(null);
const abort = new AbortController();
abortRef.current = abort;
try {
const videoEl = videoRef.current;
if (!videoEl) throw new Error("no_video");
const pc = new RTCPeerConnection();
pcRef.current = pc;
pc.addTransceiver("video", { direction: "recvonly" });
pc.addTransceiver("audio", { direction: "recvonly" });
pc.ontrack = (ev) => {
const stream = ev.streams?.[0];
if (!stream) return;
if (videoEl.srcObject !== stream) {
videoEl.srcObject = stream;
void videoEl.play().catch(() => undefined);
}
};
pc.onconnectionstatechange = () => {
if (pc.connectionState === "failed") {
restart();
}
};
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
await waitForIceGatheringComplete(pc);
const sdpOffer = pc.localDescription?.sdp;
if (!sdpOffer) throw new Error("no_offer");
const res = await fetch(whepUrl, {
method: "POST",
headers: {
"Content-Type": "application/sdp",
Accept: "application/sdp",
},
body: sdpOffer,
signal: abort.signal,
});
if (!res.ok) {
const t = await res.text().catch(() => "");
throw new Error(`whep_http_${res.status}${t ? `: ${t}` : ""}`);
}
const answerSdp = await res.text();
const location = res.headers.get("location") || res.headers.get("Location");
if (location) sessionUrlRef.current = location;
await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });
if (!disposed) setStatus("playing");
} catch (e) {
if (!disposed) {
setStatus("error");
setError(e instanceof Error ? e.message : "unknown_error");
}
}
};
run();
return () => {
disposed = true;
void stop();
};
}, [enabled, restartNonce, stop, whepUrl, restart]);
return {
videoRef,
status,
error,
restart,
stop,
};
}
+14
View File
@@ -0,0 +1,14 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
line-height: 1.5;
font-weight: 400;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
import './index.css'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+5
View File
@@ -0,0 +1,5 @@
import { Navigate } from "react-router-dom";
export default function Home() {
return <Navigate to="/live" replace />;
}
+86
View File
@@ -0,0 +1,86 @@
import { useEffect, useMemo, useState } from "react";
import CameraTile from "@/components/CameraTile";
import { usePathsStatus } from "@/hooks/usePathsStatus";
import { useConfigStore } from "@/stores/configStore";
import { getMediamtxWebrtcBaseUrl } from "@/utils/api";
type Grid = 1 | 4 | 9;
export default function Live() {
const { config, isLoading, error, load } = useConfigStore();
const { readyByName } = usePathsStatus(5000);
const [grid, setGrid] = useState<Grid>(4);
useEffect(() => {
if (!config) void load();
}, [config, load]);
const cams = useMemo(() => {
const list = config?.cameras ?? [];
return list.slice(0, grid);
}, [config, grid]);
const webrtcBaseUrl = useMemo(() => {
return getMediamtxWebrtcBaseUrl(config?.mediamtx_webrtc_url);
}, [config?.mediamtx_webrtc_url]);
return (
<div className="space-y-4">
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div>
<div className="text-sm font-semibold">Live View</div>
<div className="text-xs text-zinc-400">WebRTC grid (auto reconnect + lazy load)</div>
</div>
<div className="flex items-center gap-2">
<label className="text-xs text-zinc-400">Grid</label>
<select
value={grid}
onChange={(e) => setGrid(Number(e.target.value) as Grid)}
className="h-9 rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
>
<option value={1}>1</option>
<option value={4}>4</option>
<option value={9}>9</option>
</select>
</div>
</div>
{error ? (
<div className="rounded-lg border border-rose-900/60 bg-rose-950/30 px-4 py-3 text-sm text-rose-200">
{error}
</div>
) : null}
{isLoading && !config ? (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/30 px-4 py-3 text-sm text-zinc-300">
Đang tải cấu hình...
</div>
) : null}
{config && config.cameras.length === 0 ? (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/30 px-4 py-3 text-sm text-zinc-300">
Chưa camera. Thêm camera trong Settings.
</div>
) : null}
<div
className={[
"grid gap-3",
grid === 1 ? "grid-cols-1" : "grid-cols-1 md:grid-cols-2",
grid === 9 ? "lg:grid-cols-3" : "",
].join(" ")}
>
{cams.map((c) => (
<CameraTile
key={c.name}
name={c.name}
webrtcBaseUrl={webrtcBaseUrl}
isOnline={readyByName.get(c.name) ?? false}
/>
))}
</div>
</div>
);
}
+198
View File
@@ -0,0 +1,198 @@
import { Download, Play } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useConfigStore } from "@/stores/configStore";
import { apiJson } from "@/utils/api";
import type { RecordingItem } from "@/types/api";
function toLocalDateInputValue(d: Date) {
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, "0");
const dd = String(d.getDate()).padStart(2, "0");
return `${yyyy}-${mm}-${dd}`;
}
export default function Playback() {
const { config, isLoading, error, load } = useConfigStore();
const [camera, setCamera] = useState<string>("");
const [date, setDate] = useState<string>(() => toLocalDateInputValue(new Date()));
const [items, setItems] = useState<RecordingItem[]>([]);
const [selected, setSelected] = useState<RecordingItem | null>(null);
const [listError, setListError] = useState<string | null>(null);
const [listLoading, setListLoading] = useState(false);
useEffect(() => {
if (!config) void load();
}, [config, load]);
useEffect(() => {
const first = config?.cameras?.[0]?.name;
if (first && !camera) setCamera(first);
}, [config?.cameras, camera]);
const canQuery = useMemo(() => Boolean(camera), [camera]);
useEffect(() => {
let alive = true;
const run = async () => {
if (!canQuery) return;
setListLoading(true);
setListError(null);
try {
const q = new URLSearchParams();
q.set("camera", camera);
if (date) q.set("date", date);
const res = await apiJson<RecordingItem[]>(`/recordings?${q.toString()}`, {
method: "GET",
});
if (!alive) return;
setItems(res);
setSelected((prev) => {
if (prev && res.some((x) => x.filename === prev.filename)) return prev;
return res[0] ?? null;
});
} catch (e) {
if (!alive) return;
setItems([]);
setSelected(null);
if (typeof e === "object" && e && "status" in e) {
setListError(`http_${(e as { status: number }).status}`);
} else {
setListError("failed_to_load_recordings");
}
} finally {
if (alive) setListLoading(false);
}
};
void run();
return () => {
alive = false;
};
}, [camera, date, canQuery]);
return (
<div className="space-y-4">
<div>
<div className="text-sm font-semibold">Playback</div>
<div className="text-xs text-zinc-400">Chọn camera + ngày, phát file fMP4</div>
</div>
{error ? (
<div className="rounded-lg border border-rose-900/60 bg-rose-950/30 px-4 py-3 text-sm text-rose-200">
{error}
</div>
) : null}
<div className="grid gap-3 lg:grid-cols-[320px_1fr]">
<div className="rounded-lg border border-zinc-800 bg-zinc-900/20 p-3">
<div className="space-y-3">
<div>
<label className="text-xs text-zinc-400">Camera</label>
<select
value={camera}
onChange={(e) => setCamera(e.target.value)}
disabled={isLoading && !config}
className="mt-1 h-9 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
>
{(config?.cameras ?? []).map((c) => (
<option key={c.name} value={c.name}>
{c.name}
</option>
))}
</select>
</div>
<div>
<label className="text-xs text-zinc-400">Date</label>
<input
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
className="mt-1 h-9 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
/>
</div>
</div>
<div className="mt-4 border-t border-zinc-800 pt-3">
<div className="flex items-center justify-between">
<div className="text-xs font-medium text-zinc-200">Files</div>
<div className="text-xs text-zinc-400">
{listLoading ? "loading" : `${items.length}`}
</div>
</div>
{listError ? (
<div className="mt-2 text-xs text-rose-300">{listError}</div>
) : null}
<div className="mt-2 max-h-[420px] space-y-1 overflow-auto pr-1">
{items.map((it) => {
const dt = new Date(it.timestamp);
const t = dt.toLocaleTimeString();
const active = selected?.filename === it.filename;
return (
<div
key={it.filename}
className={[
"flex items-center justify-between gap-2 rounded-md border px-2 py-2",
active
? "border-zinc-700 bg-zinc-950/40"
: "border-zinc-800 bg-zinc-950/10 hover:bg-zinc-950/30",
].join(" ")}
>
<div className="min-w-0">
<div className="truncate text-xs text-zinc-100">{t}</div>
<div className="truncate text-[11px] text-zinc-500">{it.filename}</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<button
type="button"
onClick={() => setSelected(it)}
className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
title="Play"
>
<Play className="h-4 w-4" />
</button>
<a
href={it.url}
download
className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
title="Download"
>
<Download className="h-4 w-4" />
</a>
</div>
</div>
);
})}
{!listLoading && items.length === 0 ? (
<div className="rounded-md border border-zinc-800 bg-zinc-950/10 px-3 py-2 text-xs text-zinc-400">
Không file.
</div>
) : null}
</div>
</div>
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-900/20 p-3">
<div className="text-xs font-medium text-zinc-200">Player</div>
<div className="mt-2 aspect-video w-full overflow-hidden rounded-md border border-zinc-800 bg-black">
{selected ? (
<video
key={selected.filename}
className="h-full w-full"
controls
playsInline
src={selected.url}
/>
) : (
<div className="flex h-full w-full items-center justify-center text-sm text-zinc-400">
Chọn 1 file đ phát
</div>
)}
</div>
</div>
</div>
</div>
);
}
+204
View File
@@ -0,0 +1,204 @@
import { Plus, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import type { FormEvent } from "react";
import { useConfigStore } from "@/stores/configStore";
export default function Settings() {
const {
config,
isLoading,
error,
load,
addCamera,
deleteCamera,
setSchedulerEnabled,
updateSchedule,
} = useConfigStore();
const [name, setName] = useState("");
const [rtspUrl, setRtspUrl] = useState("");
const schedule = config?.schedule;
const [weekdaysFrom, setWeekdaysFrom] = useState("18:00");
const [weekdaysTo, setWeekdaysTo] = useState("08:00");
const [weekendAllDay, setWeekendAllDay] = useState(true);
useEffect(() => {
if (!config) void load();
}, [config, load]);
useEffect(() => {
if (!schedule) return;
setWeekdaysFrom(schedule.weekdays_from);
setWeekdaysTo(schedule.weekdays_to);
setWeekendAllDay(schedule.weekend_all_day);
}, [schedule]);
const canAdd = useMemo(
() => name.trim().length > 0 && rtspUrl.trim().length > 0,
[name, rtspUrl]
);
const onAdd = async (e: FormEvent) => {
e.preventDefault();
if (!canAdd) return;
await addCamera({ name: name.trim(), rtsp_url: rtspUrl.trim() });
setName("");
setRtspUrl("");
};
const onSaveSchedule = async () => {
await updateSchedule({
weekdays_from: weekdaysFrom,
weekdays_to: weekdaysTo,
weekend_all_day: weekendAllDay,
});
};
return (
<div className="space-y-4">
<div>
<div className="text-sm font-semibold">Settings</div>
<div className="text-xs text-zinc-400">Camera management + recording schedule</div>
</div>
{error ? (
<div className="rounded-lg border border-rose-900/60 bg-rose-950/30 px-4 py-3 text-sm text-rose-200">
{error}
</div>
) : null}
<div className="grid gap-3 lg:grid-cols-2">
<div className="rounded-lg border border-zinc-800 bg-zinc-900/20 p-4">
<div className="text-xs font-semibold text-zinc-200">Cameras</div>
<div className="mt-1 text-xs text-zinc-400">
Đng bộ paths lên MediaMTX thông qua Control API
</div>
<div className="mt-3 space-y-2">
{(config?.cameras ?? []).map((c) => (
<div
key={c.name}
className="flex items-center justify-between gap-3 rounded-md border border-zinc-800 bg-zinc-950/10 px-3 py-2"
>
<div className="min-w-0">
<div className="truncate text-sm text-zinc-100">{c.name}</div>
<div className="truncate text-xs text-zinc-500">{c.rtsp_url}</div>
</div>
<button
type="button"
onClick={() => void deleteCamera(c.name)}
className="inline-flex h-9 w-9 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
title="Remove"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
))}
{(config?.cameras ?? []).length === 0 ? (
<div className="rounded-md border border-zinc-800 bg-zinc-950/10 px-3 py-2 text-xs text-zinc-400">
Chưa camera.
</div>
) : null}
</div>
<form onSubmit={(e) => void onAdd(e)} className="mt-4 space-y-2">
<div className="grid gap-2 md:grid-cols-2">
<div>
<label className="text-xs text-zinc-400">Name</label>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="cam1"
className="mt-1 h-9 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
/>
</div>
<div>
<label className="text-xs text-zinc-400">RTSP URL</label>
<input
value={rtspUrl}
onChange={(e) => setRtspUrl(e.target.value)}
placeholder="rtsp://user:pass@ip:554/stream"
className="mt-1 h-9 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
/>
</div>
</div>
<button
type="submit"
disabled={!canAdd || isLoading}
className="inline-flex items-center gap-2 rounded-md border border-zinc-700 bg-zinc-950/40 px-3 py-2 text-sm text-zinc-200 transition hover:bg-zinc-900 disabled:cursor-not-allowed disabled:opacity-60"
>
<Plus className="h-4 w-4" />
Add Camera
</button>
</form>
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-900/20 p-4">
<div className="text-xs font-semibold text-zinc-200">Recording Schedule</div>
<div className="mt-1 text-xs text-zinc-400">Backend sẽ bật/tắt record mỗi 60 giây</div>
<div className="mt-4 space-y-3">
<label className="flex items-center gap-2 text-sm text-zinc-200">
<input
type="checkbox"
checked={Boolean(schedule?.enabled)}
onChange={(e) => void setSchedulerEnabled(e.target.checked)}
className="h-4 w-4 rounded border-zinc-700 bg-zinc-950"
/>
Enable scheduler
</label>
<div className="grid gap-2 md:grid-cols-2">
<div>
<label className="text-xs text-zinc-400">Weekdays from</label>
<input
type="time"
value={weekdaysFrom}
onChange={(e) => setWeekdaysFrom(e.target.value)}
className="mt-1 h-9 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
/>
</div>
<div>
<label className="text-xs text-zinc-400">Weekdays to</label>
<input
type="time"
value={weekdaysTo}
onChange={(e) => setWeekdaysTo(e.target.value)}
className="mt-1 h-9 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 text-sm text-zinc-100"
/>
</div>
</div>
<label className="flex items-center gap-2 text-sm text-zinc-200">
<input
type="checkbox"
checked={weekendAllDay}
onChange={(e) => setWeekendAllDay(e.target.checked)}
className="h-4 w-4 rounded border-zinc-700 bg-zinc-950"
/>
Weekend: record all day
</label>
<button
type="button"
onClick={() => void onSaveSchedule()}
disabled={isLoading}
className="inline-flex items-center gap-2 rounded-md border border-zinc-700 bg-zinc-950/40 px-3 py-2 text-sm text-zinc-200 transition hover:bg-zinc-900 disabled:cursor-not-allowed disabled:opacity-60"
>
Save
</button>
<div className="rounded-md border border-zinc-800 bg-zinc-950/10 px-3 py-2 text-xs text-zinc-400">
MediaMTX API: <span className="text-zinc-200">{config?.mediamtx_api_url ?? "-"}</span>
<br />
WebRTC: <span className="text-zinc-200">{config?.mediamtx_webrtc_url ?? "-"}</span>
<br />
Recordings dir: <span className="text-zinc-200">{config?.recordings_dir ?? "-"}</span>
</div>
</div>
</div>
</div>
</div>
);
}
+89
View File
@@ -0,0 +1,89 @@
import { create } from "zustand";
import { apiJson } from "@/utils/api";
import type { AppConfig, Camera, Schedule } from "@/types/api";
type ConfigState = {
config: AppConfig | null;
isLoading: boolean;
error: string | null;
load: () => Promise<void>;
addCamera: (camera: Camera) => Promise<void>;
deleteCamera: (name: string) => Promise<void>;
setSchedulerEnabled: (enabled: boolean) => Promise<void>;
updateSchedule: (schedule: Omit<Schedule, "enabled">) => Promise<void>;
};
function errToMessage(err: unknown) {
if (!err) return "unknown_error";
if (typeof err === "string") return err;
if (typeof err === "object" && err && "status" in err) {
const e = err as { status: number; bodyText?: string };
return `http_${e.status}${e.bodyText ? `: ${e.bodyText}` : ""}`;
}
return "unknown_error";
}
export const useConfigStore = create<ConfigState>((set, get) => ({
config: null,
isLoading: false,
error: null,
load: async () => {
set({ isLoading: true, error: null });
try {
const cfg = await apiJson<AppConfig>("/config", { method: "GET" });
set({ config: cfg, isLoading: false });
} catch (e) {
set({ isLoading: false, error: errToMessage(e) });
}
},
addCamera: async (camera) => {
set({ isLoading: true, error: null });
try {
const cfg = await apiJson<AppConfig>("/cameras", {
method: "POST",
body: JSON.stringify(camera),
});
set({ config: cfg, isLoading: false });
} catch (e) {
set({ isLoading: false, error: errToMessage(e) });
}
},
deleteCamera: async (name) => {
set({ isLoading: true, error: null });
try {
const cfg = await apiJson<AppConfig>(`/cameras/${encodeURIComponent(name)}`, {
method: "DELETE",
});
set({ config: cfg, isLoading: false });
} catch (e) {
set({ isLoading: false, error: errToMessage(e) });
}
},
setSchedulerEnabled: async (enabled) => {
set({ isLoading: true, error: null });
try {
const cfg = await apiJson<AppConfig>("/scheduler/enabled", {
method: "POST",
body: JSON.stringify({ enabled }),
});
set({ config: cfg, isLoading: false });
} catch (e) {
set({ isLoading: false, error: errToMessage(e) });
}
},
updateSchedule: async (schedule) => {
const cfg = get().config;
const enabled = cfg?.schedule.enabled ?? true;
set({ isLoading: true, error: null });
try {
const next = await apiJson<AppConfig>("/scheduler/schedule", {
method: "POST",
body: JSON.stringify(schedule),
});
set({ config: { ...next, schedule: { ...next.schedule, enabled } }, isLoading: false });
} catch (e) {
set({ isLoading: false, error: errToMessage(e) });
}
},
}));
+2
View File
@@ -0,0 +1,2 @@
import "@testing-library/jest-dom";
+38
View File
@@ -0,0 +1,38 @@
export type Camera = {
name: string;
rtsp_url: string;
};
export type Schedule = {
enabled: boolean;
weekdays_from: string;
weekdays_to: string;
weekend_all_day: boolean;
};
export type AppConfig = {
mediamtx_api_url: string;
mediamtx_webrtc_url: string;
recordings_dir: string;
cameras: Camera[];
schedule: Schedule;
};
export type RecordingItem = {
camera: string;
filename: string;
timestamp: string;
url: string;
};
export type MediaMtxPathsListItem = {
name: string;
ready?: boolean;
};
export type MediaMtxPathsListResponse = {
items?: MediaMtxPathsListItem[];
itemCount?: number;
pageCount?: number;
};
+36
View File
@@ -0,0 +1,36 @@
type ApiError = {
status: number;
bodyText: string;
};
function buildUrl(path: string) {
const base = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? "/api";
if (path.startsWith("http://") || path.startsWith("https://")) return path;
if (path.startsWith("/")) return `${base}${path}`;
return `${base}/${path}`;
}
export async function apiJson<T>(path: string, init?: RequestInit): Promise<T> {
const url = buildUrl(path);
const res = await fetch(url, {
...init,
headers: {
"Content-Type": "application/json",
...(init?.headers ?? {}),
},
});
if (!res.ok) {
const bodyText = await res.text().catch(() => "");
const err: ApiError = { status: res.status, bodyText };
throw err;
}
return (await res.json()) as T;
}
export function getMediamtxWebrtcBaseUrl(configUrl?: string) {
const env = import.meta.env.VITE_MEDIAMTX_WEBRTC_URL as string | undefined;
return env ?? configUrl ?? "http://localhost:8889";
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+13
View File
@@ -0,0 +1,13 @@
/** @type {import('tailwindcss').Config} */
export default {
darkMode: "class",
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
theme: {
container: {
center: true,
},
extend: {},
},
plugins: [],
};
+36
View File
@@ -0,0 +1,36 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": [
"ES2020",
"DOM",
"DOM.Iterable"
],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": false,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": false,
"noUncheckedSideEffectImports": false,
"forceConsistentCasingInFileNames": false,
"baseUrl": "./",
"paths": {
"@/*": [
"./src/*"
]
}
},
"include": [
"src",
"api"
]
}
+40
View File
@@ -0,0 +1,40 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tsconfigPaths from "vite-tsconfig-paths";
import { traeBadgePlugin } from 'vite-plugin-trae-solo-badge';
// https://vite.dev/config/
export default defineConfig({
server: {
proxy: {
"/api": "http://localhost:8000",
"/videos": "http://localhost:8000",
},
},
build: {
sourcemap: 'hidden',
},
plugins: [
react({
babel: {
plugins: [
'react-dev-locator',
],
},
}),
traeBadgePlugin({
variant: 'dark',
position: 'bottom-right',
prodOnly: true,
clickable: true,
clickUrl: 'https://www.trae.ai/solo?showJoin=1',
autoTheme: true,
autoThemeTarget: '#root'
}),
tsconfigPaths()
],
test: {
environment: "jsdom",
setupFiles: ["./src/test/setup.ts"],
},
})