Document real-time TUS upload progress, transcode polling, and React integration patterns for the admin panel. Co-authored-by: Cursor <cursoragent@cursor.com>
1227 lines
36 KiB
Markdown
1227 lines
36 KiB
Markdown
# File Upload — Admin Panel Integration Guide
|
||
|
||
This guide documents how the Yimaru admin panel should upload **images, audio, PDFs, and videos** using **direct-to-storage uploads** with accurate client-side progress tracking.
|
||
|
||
**Use this guide instead of `POST /api/v1/files/upload`.** That legacy endpoint accepts `multipart/form-data` and streams the entire file through the API server. The browser cannot report true upload progress for that path in a meaningful way, and large files (especially video) add load and timeout risk on the backend.
|
||
|
||
| Media type | Recommended flow | Progress tracked on |
|
||
|------------|------------------|---------------------|
|
||
| `image` | MinIO presigned PUT | Browser → MinIO |
|
||
| `audio` | MinIO presigned PUT | Browser → MinIO |
|
||
| `pdf` | MinIO presigned PUT | Browser → MinIO |
|
||
| `video` | Vimeo TUS resumable upload | Browser → Vimeo |
|
||
|
||
---
|
||
|
||
## Table of contents
|
||
|
||
1. [Feature overview](#feature-overview)
|
||
2. [Why not `/files/upload`](#why-not-filesupload)
|
||
3. [Architecture](#architecture)
|
||
4. [Authentication & permissions](#authentication--permissions)
|
||
5. [Media routing decision tree](#media-routing-decision-tree)
|
||
6. [Progress model (admin UI)](#progress-model-admin-ui)
|
||
7. [Response envelopes](#response-envelopes)
|
||
8. [MinIO presigned upload (image / audio / pdf)](#minio-presigned-upload-image--audio--pdf)
|
||
9. [Vimeo TUS upload (video)](#vimeo-tus-upload-video)
|
||
10. [Storing upload results in content](#storing-upload-results-in-content)
|
||
11. [Download & URL refresh (MinIO)](#download--url-refresh-minio)
|
||
12. [Recommended admin UI patterns](#recommended-admin-ui-patterns)
|
||
13. [TypeScript types & upload service](#typescript-types--upload-service)
|
||
14. [React upload hook example](#react-upload-hook-example)
|
||
15. [Error handling](#error-handling)
|
||
16. [Infrastructure & CORS](#infrastructure--cors)
|
||
17. [Integration checklist](#integration-checklist)
|
||
18. [Limitations & legacy endpoints](#limitations--legacy-endpoints)
|
||
19. [Quick reference](#quick-reference)
|
||
|
||
---
|
||
|
||
## Feature overview
|
||
|
||
The admin panel uploads files when creating or editing content: lesson media, persona avatars, PDF handouts, audio prompts, video lessons, etc.
|
||
|
||
The backend exposes two **progress-friendly** upload paths:
|
||
|
||
1. **MinIO presigned upload** — three-step flow for static files stored in the Yimaru MinIO bucket.
|
||
2. **Vimeo TUS upload** — two-step flow (create slot + client TUS upload) for video hosted on Vimeo.
|
||
|
||
Both flows upload **directly from the browser to the storage provider**. The Yimaru API only:
|
||
|
||
- Authenticates the admin user
|
||
- Issues upload credentials (presigned URL or TUS upload link)
|
||
- Verifies completion (MinIO `complete-upload`) or exposes post-upload metadata (Vimeo video info / transcode status)
|
||
|
||
### Supported formats & size limits
|
||
|
||
| `media_type` | Max size | Allowed content types | Storage |
|
||
|--------------|----------|------------------------|---------|
|
||
| `image` | 10 MB | `image/jpeg`, `image/png`, `image/webp` | MinIO |
|
||
| `audio` | 50 MB | mp3, wav, ogg, m4a, aac, webm, flac (see validation below) | MinIO |
|
||
| `pdf` | 25 MB | `application/pdf` | MinIO |
|
||
| `video` | Vimeo account quota | Any `video/*` detected by browser / file | Vimeo |
|
||
|
||
Object keys for MinIO uploads follow `{media_type}/{uuid}{extension}`, e.g. `image/3fa85f64-5717-4562-b3fc-2c963f66afa6.jpg`.
|
||
|
||
Presigned PUT URLs expire in **15 minutes** (`expires_in: 900`).
|
||
|
||
---
|
||
|
||
## Why not `/files/upload`
|
||
|
||
`POST /api/v1/files/upload` still exists for backward compatibility but should **not** be used in new admin panel code.
|
||
|
||
| Topic | `/files/upload` (legacy) | Presigned MinIO + Vimeo TUS (recommended) |
|
||
|-------|--------------------------|---------------------------------------------|
|
||
| Request shape | `multipart/form-data` with file body | JSON to API; binary goes to MinIO/Vimeo |
|
||
| Upload path | Browser → API → MinIO/Vimeo | Browser → MinIO/Vimeo directly |
|
||
| Progress | Not reliable (single HTTP request to API) | `xhr.upload.onprogress` (MinIO) or TUS `onProgress` (Vimeo) |
|
||
| Large video | Buffered through API (500 MB cap in handler) | Resumable TUS to Vimeo |
|
||
| Timeouts | API server limits | Storage provider handles long uploads |
|
||
|
||
If the admin panel sends a video to `POST /files/presign-upload`, the API returns **400** with guidance to use Vimeo TUS instead.
|
||
|
||
---
|
||
|
||
## Architecture
|
||
|
||
```mermaid
|
||
flowchart TB
|
||
subgraph AdminPanel["Admin panel"]
|
||
Picker[File picker]
|
||
Progress[Progress bar]
|
||
Form[Content form save]
|
||
end
|
||
|
||
subgraph API["Yimaru API (authenticated)"]
|
||
Presign["POST /files/presign-upload"]
|
||
Complete["POST /files/complete-upload"]
|
||
TusCreate["POST /vimeo/uploads/tus"]
|
||
Transcode["GET /vimeo/videos/:id/status"]
|
||
Refresh["POST /files/refresh-url"]
|
||
end
|
||
|
||
subgraph Storage["External storage"]
|
||
MinIO[(MinIO bucket)]
|
||
Vimeo[(Vimeo TUS endpoint)]
|
||
end
|
||
|
||
Picker -->|"image/audio/pdf"| Presign
|
||
Presign -->|"upload_url + object_key"| Picker
|
||
Picker -->|"HTTP PUT + onprogress"| MinIO
|
||
Picker --> Complete
|
||
Complete --> Form
|
||
|
||
Picker -->|"video"| TusCreate
|
||
TusCreate -->|"upload_link + vimeo_id"| Picker
|
||
Picker -->|"TUS PATCH + onProgress"| Vimeo
|
||
Picker --> Transcode
|
||
Transcode --> Form
|
||
|
||
Form --> Refresh
|
||
```
|
||
|
||
**Commit reference:** MinIO presigned endpoints were added in commit `b57b306` on branch `production`.
|
||
|
||
---
|
||
|
||
## Authentication & permissions
|
||
|
||
### Obtaining a token
|
||
|
||
Use a **team member** token for the admin panel (recommended):
|
||
|
||
```http
|
||
POST /api/v1/team/login
|
||
Content-Type: application/json
|
||
```
|
||
|
||
Use the `access_token` from the response on all upload-related API calls:
|
||
|
||
```http
|
||
Authorization: Bearer <access_token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
Platform admin login (`POST /api/v1/auth/admin-login`) also works where applicable.
|
||
|
||
### Permission requirements
|
||
|
||
| Endpoint group | Auth | RBAC permission |
|
||
|----------------|------|-----------------|
|
||
| `POST /files/presign-upload` | Required | None (any authenticated user) |
|
||
| `POST /files/complete-upload` | Required | None |
|
||
| `GET /files/url` | Required | None |
|
||
| `POST /files/refresh-url` | Required | None |
|
||
| `POST /vimeo/uploads/tus` | Required | **`vimeo.uploads.tus`** |
|
||
| `GET /vimeo/videos/:video_id/status` | Required | **`vimeo.videos.status`** |
|
||
| `GET /vimeo/videos/:video_id` | Required | **`vimeo.videos.get`** |
|
||
| `GET /vimeo/videos/:video_id/embed` | Required | **`vimeo.videos.embed`** |
|
||
|
||
Default roles **`ADMIN`**, **`SUPER_ADMIN`**, and **`INSTRUCTOR`** receive all `vimeo.*` permissions after RBAC seeding. Custom roles must be assigned `vimeo.uploads.tus` (and related keys) explicitly.
|
||
|
||
### Troubleshooting 403 on video upload
|
||
|
||
If `POST /vimeo/uploads/tus` returns **403 Forbidden**:
|
||
|
||
1. Confirm the token is from a team/admin account, not a learner token.
|
||
2. In RBAC admin UI, verify the role includes **`vimeo.uploads.tus`**.
|
||
3. Re-run RBAC sync / restart API if permissions were recently added.
|
||
4. `ADMIN` / `SUPER_ADMIN` bypass permission checks in middleware.
|
||
|
||
MinIO file routes only require authentication — a 403 there usually means an invalid or expired token.
|
||
|
||
---
|
||
|
||
## Media routing decision tree
|
||
|
||
```
|
||
User selects file
|
||
│
|
||
├─ MIME starts with video/ OR extension is common video (.mp4, .mov, .webm, …)
|
||
│ └─► Vimeo TUS flow (POST /vimeo/uploads/tus → TUS upload → poll transcode)
|
||
│
|
||
├─ MIME image/jpeg|png|webp
|
||
│ └─► MinIO presign (media_type: "image")
|
||
│
|
||
├─ MIME audio/* or known audio extension
|
||
│ └─► MinIO presign (media_type: "audio")
|
||
│
|
||
├─ MIME application/pdf OR .pdf extension
|
||
│ └─► MinIO presign (media_type: "pdf")
|
||
│
|
||
└─ else
|
||
└─► Show validation error before calling API
|
||
```
|
||
|
||
Always pass the **actual file size** and **content type** to the presign/TUS create step. The backend validates both before issuing upload credentials.
|
||
|
||
---
|
||
|
||
## Progress model (admin UI)
|
||
|
||
Split progress into named phases so users see meaningful feedback:
|
||
|
||
### MinIO (image / audio / pdf)
|
||
|
||
| Phase | Weight | Source |
|
||
|-------|--------|--------|
|
||
| `presigning` | 0–5% | Waiting for `POST /files/presign-upload` |
|
||
| `uploading` | 5–92% | `xhr.upload.onprogress` on PUT to `upload_url` |
|
||
| `completing` | 92–100% | `POST /files/complete-upload` |
|
||
|
||
Formula during upload phase:
|
||
|
||
```text
|
||
overall = 5 + (loaded / total) * 87
|
||
```
|
||
|
||
### Vimeo (video)
|
||
|
||
| Phase | Weight | Source |
|
||
|-------|--------|--------|
|
||
| `creating` | 0–5% | Waiting for `POST /vimeo/uploads/tus` |
|
||
| `uploading` | 5–80% | TUS client `onProgress(bytesUploaded, bytesTotal)` |
|
||
| `processing` | 80–100% | Poll `GET /vimeo/videos/:video_id/status` until transcode complete |
|
||
|
||
During transcode polling, map Vimeo status to UI:
|
||
|
||
| `status` (transcode) | UI label |
|
||
|----------------------|----------|
|
||
| `in_progress` | "Processing video…" (animate 80–95%) |
|
||
| `complete` | Done (100%) |
|
||
| `error` | Failed — show retry |
|
||
|
||
Poll every **3–5 seconds** after TUS upload succeeds. Stop after ~30 minutes or show a "still processing" message with manual refresh.
|
||
|
||
---
|
||
|
||
## Response envelopes
|
||
|
||
Successful API responses use the standard envelope:
|
||
|
||
```json
|
||
{
|
||
"message": "Human-readable message",
|
||
"data": { },
|
||
"success": true,
|
||
"status_code": 200,
|
||
"metadata": null
|
||
}
|
||
```
|
||
|
||
Errors:
|
||
|
||
```json
|
||
{
|
||
"message": "Short error title",
|
||
"error": "Detailed reason"
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## MinIO presigned upload (image / audio / pdf)
|
||
|
||
Three steps: **presign → PUT → complete**.
|
||
|
||
### Step 1 — Create presigned upload slot
|
||
|
||
```http
|
||
POST /api/v1/files/presign-upload
|
||
Authorization: Bearer <token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
**Request body:**
|
||
|
||
```json
|
||
{
|
||
"media_type": "image",
|
||
"filename": "lesson-cover.png",
|
||
"content_type": "image/png",
|
||
"file_size": 245760
|
||
}
|
||
```
|
||
|
||
| Field | Required | Description |
|
||
|-------|----------|-------------|
|
||
| `media_type` | Yes | `image`, `audio`, or `pdf` (not `video`) |
|
||
| `filename` | Yes | Original filename (used for extension) |
|
||
| `content_type` | Yes | MIME type; must pass backend validation |
|
||
| `file_size` | Yes | File size in bytes; must be > 0 and within limit |
|
||
|
||
**Success — `201 Created`:**
|
||
|
||
```json
|
||
{
|
||
"message": "Presigned upload URL created successfully",
|
||
"data": {
|
||
"object_key": "image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png",
|
||
"upload_url": "https://minio.example.com/bucket/image/3fa85f64-....png?X-Amz-...",
|
||
"reference": "minio://image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png",
|
||
"content_type": "image/png",
|
||
"media_type": "image",
|
||
"provider": "MINIO",
|
||
"expires_in": 900
|
||
},
|
||
"success": true,
|
||
"status_code": 201
|
||
}
|
||
```
|
||
|
||
**Important:** Save `object_key`, `upload_url`, and `content_type` for the next steps. The presigned URL is bound to the exact `Content-Type` sent here.
|
||
|
||
### Step 2 — Upload file directly to MinIO (progress tracked here)
|
||
|
||
Send the raw file bytes with **HTTP PUT** to `upload_url`.
|
||
|
||
**Required headers on PUT:**
|
||
|
||
```http
|
||
Content-Type: image/png
|
||
```
|
||
|
||
Use the **same** `content_type` as step 1. Do **not** send `Authorization` — credentials are in the presigned query string.
|
||
|
||
**Do not** use `multipart/form-data` on this request.
|
||
|
||
**Success:** MinIO returns `200 OK` (empty or minimal body).
|
||
|
||
**Client example with progress (XHR):**
|
||
|
||
```typescript
|
||
function putFileWithProgress(
|
||
uploadUrl: string,
|
||
file: File,
|
||
contentType: string,
|
||
onProgress: (loaded: number, total: number) => void
|
||
): Promise<void> {
|
||
return new Promise((resolve, reject) => {
|
||
const xhr = new XMLHttpRequest();
|
||
xhr.open("PUT", uploadUrl);
|
||
xhr.setRequestHeader("Content-Type", contentType);
|
||
|
||
xhr.upload.onprogress = (e) => {
|
||
if (e.lengthComputable) onProgress(e.loaded, e.total);
|
||
};
|
||
|
||
xhr.onload = () => {
|
||
if (xhr.status >= 200 && xhr.status < 300) resolve();
|
||
else reject(new Error(`MinIO PUT failed: ${xhr.status} ${xhr.responseText}`));
|
||
};
|
||
|
||
xhr.onerror = () => reject(new Error("Network error during MinIO upload"));
|
||
xhr.send(file);
|
||
});
|
||
}
|
||
```
|
||
|
||
`fetch()` does not expose upload progress — use `XMLHttpRequest` or a library that wraps it.
|
||
|
||
### Step 3 — Complete and verify upload
|
||
|
||
Call the API after PUT succeeds so the backend confirms the object exists in MinIO and returns the canonical file metadata (same shape as legacy `/files/upload` for MinIO files).
|
||
|
||
```http
|
||
POST /api/v1/files/complete-upload
|
||
Authorization: Bearer <token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
**Request body:**
|
||
|
||
```json
|
||
{
|
||
"object_key": "image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png",
|
||
"media_type": "image",
|
||
"file_size": 245760
|
||
}
|
||
```
|
||
|
||
| Field | Required | Description |
|
||
|-------|----------|-------------|
|
||
| `object_key` | Yes | From presign response |
|
||
| `media_type` | Yes | Must match presign `media_type` and object key prefix |
|
||
| `file_size` | No | If provided, must match actual uploaded size |
|
||
|
||
**Success — `200 OK`:**
|
||
|
||
```json
|
||
{
|
||
"message": "File uploaded successfully",
|
||
"data": {
|
||
"object_key": "image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png",
|
||
"url": "https://minio.example.com/bucket/image/....png?X-Amz-...",
|
||
"content_type": "image/png",
|
||
"media_type": "image",
|
||
"provider": "MINIO"
|
||
},
|
||
"success": true,
|
||
"status_code": 200
|
||
}
|
||
```
|
||
|
||
**Store `reference` as `minio://{object_key}`** in database fields (persona `profile_picture`, lesson image URLs, etc.). The `url` field is a **short-lived presigned GET** (~1 hour) for immediate preview only.
|
||
|
||
### MinIO error cases
|
||
|
||
| HTTP | When | Admin UI action |
|
||
|------|------|-----------------|
|
||
| 400 | Invalid media type, size, or content type | Show validation message before retry |
|
||
| 400 | `media_type: video` | Route user to Vimeo flow |
|
||
| 404 | `complete-upload` before PUT finished | Retry complete after PUT succeeds |
|
||
| 400 | Size mismatch on complete | Re-upload or omit `file_size` |
|
||
| 503 | MinIO not configured | Disable upload; show ops message |
|
||
| PUT fails / CORS | Browser blocked cross-origin PUT | Fix MinIO CORS (see [Infrastructure](#infrastructure--cors)) |
|
||
|
||
If presign expires (15 min) before PUT completes, call `presign-upload` again with a **new** slot (new `object_key`).
|
||
|
||
---
|
||
|
||
## Vimeo TUS upload (video)
|
||
|
||
> **Full guide:** [Vimeo Video Upload Progress — Admin Panel Integration](./vimeo-video-upload-progress-admin-panel-integration.md) — dedicated doc for real-time progress UI, React hooks, cancel/resume, and form integration.
|
||
|
||
Two main steps from the admin panel: **create TUS slot → upload via TUS client**. Optionally poll transcode status before enabling "Save" on the form.
|
||
|
||
### Step 1 — Create TUS upload slot
|
||
|
||
```http
|
||
POST /api/v1/vimeo/uploads/tus
|
||
Authorization: Bearer <token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
**Request body:**
|
||
|
||
```json
|
||
{
|
||
"name": "Unit 3 — Listening Introduction",
|
||
"description": "Lesson intro video for admin-created content",
|
||
"file_size": 52428800
|
||
}
|
||
```
|
||
|
||
| Field | Required | Validation |
|
||
|-------|----------|------------|
|
||
| `name` | Yes | Video title shown in Vimeo |
|
||
| `description` | No | Optional description |
|
||
| `file_size` | Yes | Must be > 0 (bytes) |
|
||
|
||
**Success — `201 Created`:**
|
||
|
||
```json
|
||
{
|
||
"message": "Vimeo TUS upload created successfully",
|
||
"data": {
|
||
"vimeo_id": "123456789",
|
||
"uri": "/videos/123456789",
|
||
"link": "https://vimeo.com/123456789",
|
||
"upload_link": "https://global.upload.vimeo.com/tus/uploads/...",
|
||
"status": "in_progress"
|
||
},
|
||
"success": true,
|
||
"status_code": 201
|
||
}
|
||
```
|
||
|
||
Save **`vimeo_id`** and **`upload_link`** immediately. The upload link is single-use for this upload session.
|
||
|
||
### Step 2 — Upload file with TUS (progress tracked here)
|
||
|
||
Upload **directly to `upload_link`** using a TUS 1.0.0 client. Do not send the video bytes to the Yimaru API.
|
||
|
||
**Recommended library:** [`tus-js-client`](https://github.com/tus/tus-js-client) (browser).
|
||
|
||
**Install:**
|
||
|
||
```bash
|
||
npm install tus-js-client
|
||
```
|
||
|
||
**Example:**
|
||
|
||
```typescript
|
||
import * as tus from "tus-js-client";
|
||
|
||
export function uploadVideoToVimeo(
|
||
file: File,
|
||
uploadLink: string,
|
||
onProgress: (loaded: number, total: number) => void
|
||
): Promise<void> {
|
||
return new Promise((resolve, reject) => {
|
||
const upload = new tus.Upload(file, {
|
||
uploadUrl: uploadLink,
|
||
retryDelays: [0, 3000, 5000, 10000, 20000],
|
||
chunkSize: 5 * 1024 * 1024,
|
||
metadata: {
|
||
filename: file.name,
|
||
filetype: file.type || "video/mp4",
|
||
},
|
||
onError: (error) => reject(error),
|
||
onProgress: (bytesUploaded, bytesTotal) => onProgress(bytesUploaded, bytesTotal),
|
||
onSuccess: () => resolve(),
|
||
});
|
||
|
||
upload.start();
|
||
});
|
||
}
|
||
```
|
||
|
||
The backend server-side TUS implementation uses:
|
||
|
||
```http
|
||
PATCH <upload_link>
|
||
Tus-Resumable: 1.0.0
|
||
Upload-Offset: 0
|
||
Content-Type: application/offset+octet-stream
|
||
```
|
||
|
||
The TUS client handles offsets, retries, and resumption automatically — prefer the library over hand-rolled PATCH.
|
||
|
||
### Step 3 — Poll transcode status (optional but recommended)
|
||
|
||
After TUS `onSuccess`, the file is on Vimeo but may still be transcoding.
|
||
|
||
```http
|
||
GET /api/v1/vimeo/videos/123456789/status
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
**Success — `200 OK`:**
|
||
|
||
```json
|
||
{
|
||
"message": "Transcode status retrieved successfully",
|
||
"data": {
|
||
"video_id": "123456789",
|
||
"status": "in_progress"
|
||
},
|
||
"success": true,
|
||
"status_code": 200
|
||
}
|
||
```
|
||
|
||
Poll until `status` is `complete`. On `error`, allow retry (create a new TUS slot and re-upload).
|
||
|
||
**Embed URL for storage:**
|
||
|
||
```text
|
||
https://player.vimeo.com/video/{vimeo_id}
|
||
```
|
||
|
||
**Optional — fetch embed HTML for preview:**
|
||
|
||
```http
|
||
GET /api/v1/vimeo/videos/123456789/embed?width=640&height=360
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
Requires permission `vimeo.videos.embed`.
|
||
|
||
### Vimeo pull upload (alternative, usually not for admin file picker)
|
||
|
||
If the video is already hosted at a **public HTTPS URL**, staff with `vimeo.uploads.pull` can use:
|
||
|
||
```http
|
||
POST /api/v1/vimeo/uploads/pull
|
||
```
|
||
|
||
Body: `{ "name", "description", "source_url", "file_size" }`. Vimeo fetches the file server-side — **no browser progress** for the fetch phase. Prefer TUS for local file picker uploads.
|
||
|
||
---
|
||
|
||
## Storing upload results in content
|
||
|
||
After a successful upload, persist stable identifiers — not expiring presigned GET URLs.
|
||
|
||
### MinIO files
|
||
|
||
| Field to store | Example | Notes |
|
||
|----------------|---------|-------|
|
||
| **Preferred** | `minio://image/uuid.png` | Matches API `reference`; refresh URLs on display |
|
||
| Alternative | `image/uuid.png` | Raw `object_key`; pass to `GET /files/url?key=` or `refresh-url` |
|
||
|
||
Example persona avatar (from personas guide): set `profile_picture` to `minio://image/...` or a refreshed presigned URL when saving the form.
|
||
|
||
### Vimeo videos
|
||
|
||
| Field to store | Example |
|
||
|----------------|---------|
|
||
| Video ID | `123456789` |
|
||
| Player embed URL | `https://player.vimeo.com/video/123456789` |
|
||
| Canonical link | `https://vimeo.com/123456789` |
|
||
|
||
Many content models accept a video URL string — use **`embed_url`** / player URL for in-app players.
|
||
|
||
### Unified upload result type (admin state)
|
||
|
||
```typescript
|
||
type UploadResult =
|
||
| {
|
||
provider: "MINIO";
|
||
mediaType: "image" | "audio" | "pdf";
|
||
objectKey: string;
|
||
reference: string; // minio://...
|
||
contentType: string;
|
||
previewUrl: string; // short-lived; refresh before display if stale
|
||
}
|
||
| {
|
||
provider: "VIMEO";
|
||
mediaType: "video";
|
||
vimeoId: string;
|
||
link: string;
|
||
embedUrl: string;
|
||
transcodeStatus: string;
|
||
};
|
||
```
|
||
|
||
---
|
||
|
||
## Download & URL refresh (MinIO)
|
||
|
||
Presigned GET URLs expire (~1 hour). For admin previews and learner delivery, refresh when needed.
|
||
|
||
### By object key
|
||
|
||
```http
|
||
GET /api/v1/files/url?key=image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
**Response `data`:**
|
||
|
||
```json
|
||
{ "url": "https://minio.example.com/..." }
|
||
```
|
||
|
||
### By reference (supports `minio://`, object key, or stale URL)
|
||
|
||
```http
|
||
POST /api/v1/files/refresh-url
|
||
Authorization: Bearer <token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
```json
|
||
{
|
||
"reference": "minio://image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png"
|
||
}
|
||
```
|
||
|
||
**Response `data`:**
|
||
|
||
```json
|
||
{
|
||
"object_key": "image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png",
|
||
"url": "https://minio.example.com/...",
|
||
"expires_in": 3600
|
||
}
|
||
```
|
||
|
||
Use this in image components when a preview fails to load (expired URL).
|
||
|
||
---
|
||
|
||
## Recommended admin UI patterns
|
||
|
||
### Shared upload widget
|
||
|
||
Build one **`MediaUploadField`** component used across forms (personas, lessons, modules, FAQs with attachments, etc.):
|
||
|
||
| UI element | Behavior |
|
||
|------------|----------|
|
||
| Drop zone / file input | Accept filter by expected media types |
|
||
| Progress bar | Phase label + percentage (see [Progress model](#progress-model-admin-ui)) |
|
||
| Cancel | Abort XHR / `tus.Upload.abort()` |
|
||
| Preview | MinIO: `<img>` / `<audio>` / iframe PDF via refreshed URL; Video: Vimeo embed after transcode |
|
||
| Error toast | Show API `message` + `error` |
|
||
| Hidden form value | Store `minio://...` or `vimeo_id` / embed URL |
|
||
|
||
### Validation before API calls
|
||
|
||
Client-side checks reduce round trips:
|
||
|
||
- File size vs limits (10 / 50 / 25 MB)
|
||
- Image types: jpeg, png, webp only
|
||
- PDF extension or MIME
|
||
- Video: warn if > 2 GB (Vimeo plan limits)
|
||
|
||
### Disable save while uploading
|
||
|
||
Block form submit while `status === 'uploading' | 'completing' | 'processing'`.
|
||
|
||
---
|
||
|
||
## TypeScript types & upload service
|
||
|
||
### Types
|
||
|
||
```typescript
|
||
export type MinIOMediaType = "image" | "audio" | "pdf";
|
||
|
||
export interface ApiResponse<T> {
|
||
message: string;
|
||
data: T;
|
||
success?: boolean;
|
||
status_code?: number;
|
||
}
|
||
|
||
export interface ApiError {
|
||
message: string;
|
||
error?: string;
|
||
}
|
||
|
||
export interface PresignUploadRequest {
|
||
media_type: MinIOMediaType;
|
||
filename: string;
|
||
content_type: string;
|
||
file_size: number;
|
||
}
|
||
|
||
export interface PresignUploadData {
|
||
object_key: string;
|
||
upload_url: string;
|
||
reference: string;
|
||
content_type: string;
|
||
media_type: MinIOMediaType;
|
||
provider: "MINIO";
|
||
expires_in: number;
|
||
}
|
||
|
||
export interface CompleteUploadRequest {
|
||
object_key: string;
|
||
media_type: MinIOMediaType;
|
||
file_size?: number;
|
||
}
|
||
|
||
export interface MinIOUploadResult {
|
||
object_key: string;
|
||
url: string;
|
||
content_type: string;
|
||
media_type: MinIOMediaType;
|
||
provider: "MINIO";
|
||
}
|
||
|
||
export interface CreateTusUploadRequest {
|
||
name: string;
|
||
description?: string;
|
||
file_size: number;
|
||
}
|
||
|
||
export interface VimeoTusUploadData {
|
||
vimeo_id: string;
|
||
uri: string;
|
||
link: string;
|
||
upload_link: string;
|
||
status: string;
|
||
}
|
||
|
||
export interface VimeoTranscodeStatusData {
|
||
video_id: string;
|
||
status: string;
|
||
}
|
||
|
||
export type UploadProgressPhase =
|
||
| "idle"
|
||
| "presigning"
|
||
| "creating"
|
||
| "uploading"
|
||
| "completing"
|
||
| "processing"
|
||
| "done"
|
||
| "error";
|
||
|
||
export interface UploadProgress {
|
||
phase: UploadProgressPhase;
|
||
percent: number;
|
||
message?: string;
|
||
}
|
||
```
|
||
|
||
### API client helpers
|
||
|
||
```typescript
|
||
const API_BASE = import.meta.env.VITE_API_BASE_URL;
|
||
|
||
function authHeaders(token: string): HeadersInit {
|
||
return {
|
||
Authorization: `Bearer ${token}`,
|
||
"Content-Type": "application/json",
|
||
};
|
||
}
|
||
|
||
async function parseApiError(res: Response): Promise<never> {
|
||
const body = (await res.json().catch(() => ({}))) as ApiError;
|
||
throw new Error(body.error || body.message || `HTTP ${res.status}`);
|
||
}
|
||
|
||
export async function presignMinioUpload(
|
||
token: string,
|
||
body: PresignUploadRequest
|
||
): Promise<PresignUploadData> {
|
||
const res = await fetch(`${API_BASE}/api/v1/files/presign-upload`, {
|
||
method: "POST",
|
||
headers: authHeaders(token),
|
||
body: JSON.stringify(body),
|
||
});
|
||
if (!res.ok) await parseApiError(res);
|
||
const json: ApiResponse<PresignUploadData> = await res.json();
|
||
return json.data;
|
||
}
|
||
|
||
export async function completeMinioUpload(
|
||
token: string,
|
||
body: CompleteUploadRequest
|
||
): Promise<MinIOUploadResult> {
|
||
const res = await fetch(`${API_BASE}/api/v1/files/complete-upload`, {
|
||
method: "POST",
|
||
headers: authHeaders(token),
|
||
body: JSON.stringify(body),
|
||
});
|
||
if (!res.ok) await parseApiError(res);
|
||
const json: ApiResponse<MinIOUploadResult> = await res.json();
|
||
return json.data;
|
||
}
|
||
|
||
export async function createVimeoTusUpload(
|
||
token: string,
|
||
body: CreateTusUploadRequest
|
||
): Promise<VimeoTusUploadData> {
|
||
const res = await fetch(`${API_BASE}/api/v1/vimeo/uploads/tus`, {
|
||
method: "POST",
|
||
headers: authHeaders(token),
|
||
body: JSON.stringify(body),
|
||
});
|
||
if (!res.ok) await parseApiError(res);
|
||
const json: ApiResponse<VimeoTusUploadData> = await res.json();
|
||
return json.data;
|
||
}
|
||
|
||
export async function getVimeoTranscodeStatus(
|
||
token: string,
|
||
videoId: string
|
||
): Promise<VimeoTranscodeStatusData> {
|
||
const res = await fetch(`${API_BASE}/api/v1/vimeo/videos/${videoId}/status`, {
|
||
headers: { Authorization: `Bearer ${token}` },
|
||
});
|
||
if (!res.ok) await parseApiError(res);
|
||
const json: ApiResponse<VimeoTranscodeStatusData> = await res.json();
|
||
return json.data;
|
||
}
|
||
|
||
export async function refreshFileUrl(
|
||
token: string,
|
||
reference: string
|
||
): Promise<{ object_key: string; url: string; expires_in: number }> {
|
||
const res = await fetch(`${API_BASE}/api/v1/files/refresh-url`, {
|
||
method: "POST",
|
||
headers: authHeaders(token),
|
||
body: JSON.stringify({ reference }),
|
||
});
|
||
if (!res.ok) await parseApiError(res);
|
||
const json: ApiResponse<{ object_key: string; url: string; expires_in: number }> =
|
||
await res.json();
|
||
return json.data;
|
||
}
|
||
```
|
||
|
||
### End-to-end MinIO upload function
|
||
|
||
```typescript
|
||
export async function uploadMinioFileWithProgress(
|
||
token: string,
|
||
file: File,
|
||
mediaType: MinIOMediaType,
|
||
onProgress: (p: UploadProgress) => void
|
||
): Promise<MinIOUploadResult & { reference: string }> {
|
||
onProgress({ phase: "presigning", percent: 2, message: "Preparing upload…" });
|
||
|
||
const presign = await presignMinioUpload(token, {
|
||
media_type: mediaType,
|
||
filename: file.name,
|
||
content_type: file.type || "application/octet-stream",
|
||
file_size: file.size,
|
||
});
|
||
|
||
onProgress({ phase: "uploading", percent: 5, message: "Uploading…" });
|
||
|
||
await putFileWithProgress(presign.upload_url, file, presign.content_type, (loaded, total) => {
|
||
const ratio = total > 0 ? loaded / total : 0;
|
||
onProgress({
|
||
phase: "uploading",
|
||
percent: Math.round(5 + ratio * 87),
|
||
message: `Uploading… ${Math.round(ratio * 100)}%`,
|
||
});
|
||
});
|
||
|
||
onProgress({ phase: "completing", percent: 95, message: "Finalizing…" });
|
||
|
||
const result = await completeMinioUpload(token, {
|
||
object_key: presign.object_key,
|
||
media_type: mediaType,
|
||
file_size: file.size,
|
||
});
|
||
|
||
onProgress({ phase: "done", percent: 100, message: "Upload complete" });
|
||
|
||
return {
|
||
...result,
|
||
reference: presign.reference,
|
||
};
|
||
}
|
||
```
|
||
|
||
### End-to-end Vimeo upload function
|
||
|
||
```typescript
|
||
export async function uploadVimeoVideoWithProgress(
|
||
token: string,
|
||
file: File,
|
||
title: string,
|
||
description: string | undefined,
|
||
onProgress: (p: UploadProgress) => void
|
||
): Promise<{ vimeoId: string; link: string; embedUrl: string }> {
|
||
onProgress({ phase: "creating", percent: 2, message: "Creating Vimeo upload…" });
|
||
|
||
const slot = await createVimeoTusUpload(token, {
|
||
name: title || file.name,
|
||
description,
|
||
file_size: file.size,
|
||
});
|
||
|
||
onProgress({ phase: "uploading", percent: 5, message: "Uploading video…" });
|
||
|
||
await uploadVideoToVimeo(file, slot.upload_link, (loaded, total) => {
|
||
const ratio = total > 0 ? loaded / total : 0;
|
||
onProgress({
|
||
phase: "uploading",
|
||
percent: Math.round(5 + ratio * 75),
|
||
message: `Uploading… ${Math.round(ratio * 100)}%`,
|
||
});
|
||
});
|
||
|
||
onProgress({ phase: "processing", percent: 82, message: "Processing on Vimeo…" });
|
||
|
||
const embedUrl = `https://player.vimeo.com/video/${slot.vimeo_id}`;
|
||
let status = "in_progress";
|
||
const maxAttempts = 120;
|
||
let attempt = 0;
|
||
|
||
while (status === "in_progress" && attempt < maxAttempts) {
|
||
await new Promise((r) => setTimeout(r, 5000));
|
||
const res = await getVimeoTranscodeStatus(token, slot.vimeo_id);
|
||
status = res.status;
|
||
attempt += 1;
|
||
onProgress({
|
||
phase: "processing",
|
||
percent: Math.min(99, 82 + attempt),
|
||
message: status === "in_progress" ? "Processing video…" : status,
|
||
});
|
||
}
|
||
|
||
if (status !== "complete") {
|
||
throw new Error(`Video processing failed or timed out (status: ${status})`);
|
||
}
|
||
|
||
onProgress({ phase: "done", percent: 100, message: "Video ready" });
|
||
|
||
return {
|
||
vimeoId: slot.vimeo_id,
|
||
link: slot.link,
|
||
embedUrl,
|
||
};
|
||
}
|
||
```
|
||
|
||
### Router by file type
|
||
|
||
```typescript
|
||
export async function uploadMediaWithProgress(
|
||
token: string,
|
||
file: File,
|
||
options: { title?: string; description?: string },
|
||
onProgress: (p: UploadProgress) => void
|
||
) {
|
||
if (file.type.startsWith("video/")) {
|
||
return uploadVimeoVideoWithProgress(
|
||
token,
|
||
file,
|
||
options.title ?? file.name,
|
||
options.description,
|
||
onProgress
|
||
);
|
||
}
|
||
|
||
let mediaType: MinIOMediaType;
|
||
if (file.type.startsWith("image/")) mediaType = "image";
|
||
else if (file.type.startsWith("audio/")) mediaType = "audio";
|
||
else if (file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf")) {
|
||
mediaType = "pdf";
|
||
} else {
|
||
throw new Error("Unsupported file type");
|
||
}
|
||
|
||
return uploadMinioFileWithProgress(token, file, mediaType, onProgress);
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## React upload hook example
|
||
|
||
```typescript
|
||
import { useCallback, useState } from "react";
|
||
import type { UploadProgress } from "./upload-types";
|
||
import { uploadMediaWithProgress } from "./upload-service";
|
||
|
||
export function useMediaUpload(token: string) {
|
||
const [progress, setProgress] = useState<UploadProgress>({ phase: "idle", percent: 0 });
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [result, setResult] = useState<unknown>(null);
|
||
|
||
const upload = useCallback(
|
||
async (file: File, opts?: { title?: string; description?: string }) => {
|
||
setError(null);
|
||
setResult(null);
|
||
setProgress({ phase: "presigning", percent: 0 });
|
||
|
||
try {
|
||
const data = await uploadMediaWithProgress(token, file, opts ?? {}, setProgress);
|
||
setResult(data);
|
||
return data;
|
||
} catch (e) {
|
||
const msg = e instanceof Error ? e.message : "Upload failed";
|
||
setError(msg);
|
||
setProgress({ phase: "error", percent: 0, message: msg });
|
||
throw e;
|
||
}
|
||
},
|
||
[token]
|
||
);
|
||
|
||
const reset = useCallback(() => {
|
||
setProgress({ phase: "idle", percent: 0 });
|
||
setError(null);
|
||
setResult(null);
|
||
}, []);
|
||
|
||
return { upload, progress, error, result, reset };
|
||
}
|
||
```
|
||
|
||
**JSX sketch:**
|
||
|
||
```tsx
|
||
const { upload, progress, error, result } = useMediaUpload(token);
|
||
|
||
return (
|
||
<div>
|
||
<input
|
||
type="file"
|
||
accept="image/png,image/jpeg,image/webp,audio/*,application/pdf,video/*"
|
||
onChange={(e) => {
|
||
const file = e.target.files?.[0];
|
||
if (file) upload(file, { title: file.name });
|
||
}}
|
||
/>
|
||
{progress.phase !== "idle" && (
|
||
<div>
|
||
<progress value={progress.percent} max={100} />
|
||
<span>{progress.message ?? progress.phase}</span>
|
||
</div>
|
||
)}
|
||
{error && <p role="alert">{error}</p>}
|
||
{result && <pre>{JSON.stringify(result, null, 2)}</pre>}
|
||
</div>
|
||
);
|
||
```
|
||
|
||
---
|
||
|
||
## Error handling
|
||
|
||
| Scenario | Typical response | UI handling |
|
||
|----------|------------------|-------------|
|
||
| Expired token | 401 | Redirect to login |
|
||
| Missing `vimeo.uploads.tus` | 403 | Show RBAC help link |
|
||
| File too large | 400 `File too large` | Validate before upload |
|
||
| Wrong image MIME | 400 `only jpg, png, and webp` | Filter file input |
|
||
| Video on presign | 400 `Use Vimeo TUS for video` | Route to video flow |
|
||
| Complete before PUT | 404 `Uploaded file not found` | Wait for PUT; retry complete |
|
||
| MinIO PUT 403 / CORS | Browser network error | Fix MinIO CORS |
|
||
| Content-Type mismatch on PUT | MinIO 403 / signature error | Use exact type from presign |
|
||
| TUS network blip | tus-js-client retry | Show "Retrying…" |
|
||
| Transcode error | `status: error` | Offer re-upload |
|
||
| MinIO 503 | Service unavailable | Disable uploads |
|
||
|
||
Always surface both `message` and `error` from API JSON when present.
|
||
|
||
---
|
||
|
||
## Infrastructure & CORS
|
||
|
||
### MinIO CORS (required for browser PUT)
|
||
|
||
The admin panel origin (e.g. `https://admin.yimaru.com`) must be allowed to **`PUT`** to the MinIO endpoint host embedded in `upload_url`.
|
||
|
||
Example MinIO CORS rule (adjust origins):
|
||
|
||
```json
|
||
[
|
||
{
|
||
"AllowedOrigin": ["https://admin.yimaru.com", "http://localhost:5173"],
|
||
"AllowedMethod": ["GET", "PUT", "HEAD"],
|
||
"AllowedHeader": ["*"],
|
||
"ExposeHeader": ["ETag"],
|
||
"MaxAgeSeconds": 3000
|
||
}
|
||
]
|
||
```
|
||
|
||
Without this, step 2 fails in the browser with a CORS error even though presign succeeded.
|
||
|
||
### Vimeo TUS
|
||
|
||
Vimeo upload endpoints accept browser TUS from public origins; no Yimaru MinIO CORS applies. Ensure outbound HTTPS to `*.upload.vimeo.com` is not blocked by corporate firewalls.
|
||
|
||
### Environment variables (backend ops)
|
||
|
||
MinIO and Vimeo must be configured on the API server (`MINIO_*`, `VIMEO_ACCESS_TOKEN`). If not, endpoints return **503 Service Unavailable**.
|
||
|
||
---
|
||
|
||
## Integration checklist
|
||
|
||
### MinIO path
|
||
|
||
- [ ] Replace `POST /files/upload` for image/audio/pdf with presign → PUT → complete
|
||
- [ ] Use XHR (or equivalent) for PUT progress events
|
||
- [ ] Send matching `Content-Type` on PUT
|
||
- [ ] Store `minio://{object_key}` in form state / API payloads
|
||
- [ ] Refresh preview URLs with `POST /files/refresh-url` when expired
|
||
- [ ] Validate file size client-side before presign
|
||
- [ ] Handle presign expiry (15 min) for slow networks
|
||
|
||
### Vimeo path
|
||
|
||
- [ ] Assign `vimeo.uploads.tus` to admin roles that upload video
|
||
- [ ] Use `tus-js-client` (or equivalent) against `upload_link`
|
||
- [ ] Poll `GET /vimeo/videos/:id/status` after upload
|
||
- [ ] Store `vimeo_id` and `https://player.vimeo.com/video/{id}` in content
|
||
- [ ] Show processing state separately from byte upload progress
|
||
|
||
### Shared UX
|
||
|
||
- [ ] Single reusable upload component across admin modules
|
||
- [ ] Disable form save during active upload
|
||
- [ ] Cancel / abort support
|
||
- [ ] Clear error messages from API `message` + `error`
|
||
- [ ] QA on slow 3G throttling (progress bar moves smoothly)
|
||
|
||
### QA scenarios
|
||
|
||
- [ ] Upload 2 MB PNG → preview works → save persona/lesson with `minio://` reference
|
||
- [ ] Upload 5 MB MP3 → complete returns audio metadata
|
||
- [ ] Upload PDF at 25 MB boundary (ok) and 26 MB (rejected)
|
||
- [ ] Upload MP4 video → TUS progress → transcode → embed preview
|
||
- [ ] Attempt video via presign → 400 with helpful message
|
||
- [ ] Expired presigned GET URL → refresh-url restores preview
|
||
- [ ] User without `vimeo.uploads.tus` → 403 on video upload
|
||
|
||
---
|
||
|
||
## Limitations & legacy endpoints
|
||
|
||
| Topic | Current behavior |
|
||
|-------|------------------|
|
||
| `/files/upload` | Legacy multipart proxy — no accurate progress |
|
||
| `/files/audio` | Legacy audio-only multipart — use MinIO presign instead |
|
||
| Video via `/files/upload` | Server buffers entire file — avoid in admin panel |
|
||
| Presign expiry | 15 minutes — restart presign if expired |
|
||
| Download URL TTL | ~1 hour — use `refresh-url` |
|
||
| MinIO RBAC | Auth only — no fine-grained file permissions |
|
||
| Chunk size (TUS) | Client-controlled (tus-js-client default 5 MB) |
|
||
| Pull upload | No browser byte progress |
|
||
|
||
---
|
||
|
||
## Quick reference
|
||
|
||
### MinIO (image / audio / pdf)
|
||
|
||
| Step | Method | Path | Auth |
|
||
|------|--------|------|------|
|
||
| 1 Presign | `POST` | `/api/v1/files/presign-upload` | Bearer |
|
||
| 2 Upload | `PUT` | `{upload_url}` from step 1 | Presigned (no Bearer) |
|
||
| 3 Complete | `POST` | `/api/v1/files/complete-upload` | Bearer |
|
||
| Preview / resolve | `GET` | `/api/v1/files/url?key={object_key}` | Bearer |
|
||
| Refresh stale URL | `POST` | `/api/v1/files/refresh-url` | Bearer |
|
||
|
||
### Vimeo (video)
|
||
|
||
| Step | Method | Path | Permission |
|
||
|------|--------|------|------------|
|
||
| 1 Create slot | `POST` | `/api/v1/vimeo/uploads/tus` | `vimeo.uploads.tus` |
|
||
| 2 Upload | TUS | `{upload_link}` from step 1 | — |
|
||
| 3 Transcode | `GET` | `/api/v1/vimeo/videos/:video_id/status` | `vimeo.videos.status` |
|
||
| Embed preview | `GET` | `/api/v1/vimeo/videos/:video_id/embed` | `vimeo.videos.embed` |
|
||
|
||
### Legacy (do not use in new admin UI)
|
||
|
||
| Method | Path | Notes |
|
||
|--------|------|-------|
|
||
| `POST` | `/api/v1/files/upload` | Multipart — no progress |
|
||
| `POST` | `/api/v1/files/audio` | Multipart audio only |
|
||
|
||
### Allowed `content_type` values (presign validation)
|
||
|
||
**Image:** `image/jpeg`, `image/png`, `image/webp`
|
||
|
||
**Audio:** `audio/mpeg`, `audio/wav`, `audio/ogg`, `audio/mp4`, `audio/aac`, `audio/webm`, `audio/x-wav`, `audio/x-m4a`, `audio/flac`, and in some cases `video/ogg` / `video/webm` when detected for audio files
|
||
|
||
**PDF:** `application/pdf`
|
||
|
||
**Video:** any `video/*` — upload via Vimeo TUS only
|