mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-21 10:00:13 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c3412686c | ||
|
|
297c4903fe | ||
|
|
b7367bb129 | ||
|
|
114cdca4ee | ||
|
|
9d7b142129 | ||
|
|
91fafafeff | ||
|
|
d5b9439371 | ||
|
|
3725193e72 | ||
|
|
62c9fb46ae | ||
|
|
9b1890f57c | ||
|
|
68a8b67931 | ||
|
|
d0bda60b9f | ||
|
|
d71b0de056 | ||
|
|
8c7d4f5b72 | ||
|
|
d8793a89a2 | ||
|
|
178670fdab | ||
|
|
715b657153 | ||
|
|
c0353bb050 | ||
|
|
0c1907d868 | ||
|
|
edbf2c6001 | ||
|
|
fa319d0898 | ||
|
|
b0a595fe9c | ||
|
|
b7d250dbac |
@@ -27,12 +27,22 @@ jobs:
|
||||
username: shumaione
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
# Log in to Aliyun ACR
|
||||
- name: Log in to Aliyun ACR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com
|
||||
username: njjyl723
|
||||
password: ${{ secrets.ALI_ACR_TOKEN }}
|
||||
|
||||
# Extract metadata (tags, labels) for Docker
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: shumaione/shumai
|
||||
images: |
|
||||
shumaione/shumai
|
||||
crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=ref,event=branch
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#syntax=docker/dockerfile:1.7-labs
|
||||
# Stage 1: Builder
|
||||
FROM oven/bun:1 AS builder
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a target="_blank" href="https://shumai.one/">Website</a> | <a target="_blank" href="https://docs.shumai.one/introduction">Docs</a> | <a target="_blank" href="https://staging.shumai.one">Demo</a>
|
||||
<a target="_blank" href="https://shumai.one/">Website</a> | <a target="_blank" href="https://docs.shumai.one/introduction">Docs</a> | <a target="_blank" href="https://staging.shumai.one">Demo</a> | <a target="_blank" href="README_CN.md">中文</a>
|
||||
</p>
|
||||
|
||||

|
||||
@@ -25,11 +25,16 @@
|
||||
|
||||
#### Shumai Agent
|
||||
|
||||
- **Collaborative AI Chat**: Converse with a context-aware AI agent directly within your project workspace.
|
||||
- **Collaborative AI Chat**: Converse with a context-aware AI agent by using `@mentions` directly within the file's comments area.
|
||||
- **Custom Skills & Tools**: Extend the agent's capabilities by registering custom scripts, tools, and automation skills.
|
||||
- **Isolated Sandbox Execution**: Run agent-submitted scripts securely within a sandboxed environment.
|
||||
- **AI-Powered Metadata Autofill**: Automatically generate tags, descriptions, and custom metadata for new assets using Google Gemini.
|
||||
- **Semantic Search**: Locate assets instantly based on visual or conceptual search queries using vector embeddings.
|
||||
- **AI Metadata Autofill**: Automatically autofill custom metadata for new assets.
|
||||
- **Semantic Search**: Find assets based on visual or conceptual search queries using vector embeddings(Gemini Embedding 2).
|
||||
|
||||
> [!NOTE]
|
||||
> **Media Processing & Storage:** When uploading media, Shumai always preserves and stores your original raw file. For all media types (both images and videos), Shumai creates a 480p WebP poster image to serve as the preview in the file list view. Additionally:
|
||||
> * **For Images:** Shumai generates a high-quality WebP proxy at the exact same resolution as your original file for optimized viewing.
|
||||
> * **For Videos:** It generates at least one proxy video (depending on your transcoding settings), alongside a sprite image and a small preview video (capped at 1600 frames) to enable fast timeline scrubbing and lightning-quick previews.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
<p align="center">
|
||||
<img src="docs/logo-rounded.png" alt="Shumai Logo" width="65" />
|
||||
</p>
|
||||
|
||||
<h1 align="center">Shumai</h1>
|
||||
|
||||
<p align="center">
|
||||
<strong>为创意工作打造的开源协作平台。</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a target="_blank" href="https://shumai.one/">官方网站</a> | <a target="_blank" href="https://docs.shumai.one/introduction">文档</a> | <a target="_blank" href="https://staging.shumai.one">在线演示</a> | <a target="_blank" href="README.md">English</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
## 功能特性
|
||||
|
||||
- **兼容 S3 与本地存储**:使用本地文件系统或任何兼容 S3 的云存储(AWS S3、Cloudflare R2、阿里云 OSS 等)安全地存储和提供您的创意资产。
|
||||
- **逐帧批注与评论**:直接在视频和图像资产上使用特定帧的绘图工具和带时间戳的评论,提供精确的反馈。
|
||||
- **安全分享与合集**:创建安全的公开分享链接和媒体合集,以便与客户和团队进行协作。
|
||||
- **细粒度访问控制**:使用团队级别和项目级别的基于角色的访问控制来管理访问权限。
|
||||
- **基于 Temporal 的分布式转码**:将占用大量资源的视频转码任务部署到 Temporal Worker上。
|
||||
- **自定义资产元数据**:为媒体文件添加可搜索/编辑的自定义元数据字段。
|
||||
|
||||
#### Shumai 智能体 (Agent)
|
||||
|
||||
- **AI Agent 协作**:通过评论区和 AI 智能体进行交流。
|
||||
- **自定义技能**:通过添加自定义技能来扩展智能体的能力。
|
||||
- **隔离的沙箱执行**:在沙箱环境中安全地运行智能体提交的脚本。
|
||||
- **AI 元数据自动填充**:使用AI为资产自动生填充元数据字段。
|
||||
- **语义搜索**:基于 Gemini Embedding 2 的图片/视频内容搜索。
|
||||
|
||||
> [!NOTE]
|
||||
> **媒体处理与存储说明:** 在上传媒体文件时,Shumai 会始终完整保留并存储您的原始文件。对于所有媒体类型(图片与视频),Shumai 都会统一生成一张 480p 的 WebP 预览图,用作文件列表页预览。此外:
|
||||
> * **图片文件:** Shumai 会额外生成一个与原图分辨率完全一致的 WebP 优化版本。
|
||||
> * **视频文件:** 系统会根据您的转码设置生成至少一个预览版本mp4,同时还会生成一张雪碧图(Sprite)和一个轻量级预览视频(上限 1600 帧),以实现流畅的文件列表页面预览和文件查看页面时间轴快速预览。
|
||||
|
||||
---
|
||||
|
||||
## 安装指南
|
||||
|
||||
以下是使用本地存储运行 Shumai 的快速上手指南。如需了解高级配置(包括 S3 兼容存储配置、Temporal 工作流编排等),请参阅我们的[官方文档](https://docs.shumai.one/getting-started/overview)。
|
||||
|
||||
### 方案一:使用 Docker Compose(推荐)
|
||||
|
||||
使用 Docker Compose 是运行 Shumai 最快的方式。您无需克隆仓库,也不需要手动安装依赖包。请确保电脑上已安装 [Docker](https://docs.docker.com/get-docker/) 和 [Docker Compose](https://docs.docker.com/compose/install/),然后按照以下步骤操作:
|
||||
|
||||
1. 创建并进入一个新目录,用于存放配置文件和数据卷:
|
||||
```bash
|
||||
mkdir shumai && cd shumai
|
||||
|
||||
```
|
||||
|
||||
2. 下载 `docker-compose.yaml` 配置文件:
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose-aliyun.yaml
|
||||
|
||||
```
|
||||
|
||||
|
||||
3. 配置环境变量(可选):
|
||||
* `SHUMAI_SERVER_PORT` 用于控制 Shumai 服务监听的端口,默认值为 `3000`。
|
||||
* 默认情况下,该 Docker Compose 部署会自动启用集成的本地存储。若想切换至外部 S3 兼容存储,请将 `AWS_ENDPOINT_URL_S3` 设置为对应云厂商的 Endpoint URL,并根据需要配置相应的 AWS 凭证和存储桶(Bucket)参数:
|
||||
```
|
||||
AWS_ENDPOINT_URL_S3: S3_ENDPOINT_URL
|
||||
S3_REGION: S3_REGION
|
||||
S3_BUCKET: BUCKET_NAME
|
||||
S3_ACCESS_KEY_ID: ID
|
||||
S3_SECRET_ACCESS_KEY: KEY
|
||||
|
||||
```
|
||||
|
||||
|
||||
* 默认情况下 `AWS_ENDPOINT_URL_S3` 指向 `http://localhost:{SHUMAI_SERVER_PORT}`。如果您使用本地存储,但希望在自定义的主机名或端口上公开访问 Shumai,请务必将 `AWS_ENDPOINT_URL_S3` 修改为浏览器访问该服务时所使用的外部 URL。
|
||||
例如,如果您将 `docker-compose.yaml` 中的端口映射从 `3000:3000` 修改为了 `12345:3000`,且服务部署在 IP 为 `12.34.56.78` 的服务器上,请进行如下设置:
|
||||
```
|
||||
AWS_ENDPOINT_URL_S3: http://12.34.56.78:12345
|
||||
|
||||
```
|
||||
|
||||
|
||||
此地址必须能够从客户端浏览器正常访问,且必须包含对外暴露的实际端口号。
|
||||
|
||||
|
||||
4. 在后台启动所有服务:
|
||||
```bash
|
||||
docker compose up -d
|
||||
|
||||
```
|
||||
|
||||
|
||||
5. 打开浏览器,访问 `http://localhost:3000` 即可开始使用(若是远程部署,请访问 `http://<您的服务器IP>:3000`)。
|
||||
|
||||
### 方案二:通过 NPM / 包管理器安装
|
||||
|
||||
通过 NPM 上的 `@shumai-one/shumai` 进行安装。
|
||||
|
||||
#### 第一步:启动带 pgvector 支持的 PostgreSQL
|
||||
|
||||
Shumai 依赖支持 `pgvector` 扩展的 PostgreSQL 数据库。您可以使用 Docker 快速启动一个预配置好的数据库容器:
|
||||
|
||||
```bash
|
||||
docker run --name shumai_postgres \
|
||||
-e POSTGRES_USER=shumai \
|
||||
-e POSTGRES_PASSWORD=shumai_password \
|
||||
-e POSTGRES_DB=shumai_db \
|
||||
-p 5432:5432 \
|
||||
-d docker.m.daocloud.io/pgvector/pgvector:pg18
|
||||
|
||||
```
|
||||
|
||||
#### 第二步:创建工作区目录
|
||||
|
||||
创建一个专属目录用来存放环境配置和媒体文件(媒体文件默认会保存在 `./data` 目录下):
|
||||
|
||||
```bash
|
||||
mkdir shumai && cd shumai
|
||||
|
||||
```
|
||||
|
||||
#### 第三步:安装平台特定系统依赖
|
||||
|
||||
在安装 Shumai 之前,请确保您的宿主机上已经安装了以下系统依赖项:
|
||||
|
||||
| 依赖包 | 功能描述 | Ubuntu/Debian | Fedora | Arch | macOS |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| **ffmpeg** | 媒体转码及元数据提取 | `sudo apt install -y ffmpeg` | `sudo dnf install -y ffmpeg` | `sudo pacman -S --noconfirm ffmpeg` | `brew install ffmpeg` |
|
||||
| **bubblewrap** | 用于安全执行 AI 助手脚本的隔离沙箱环境 | `sudo apt install -y bubblewrap` | `sudo dnf install -y bubblewrap` | `sudo pacman -S --noconfirm bubblewrap` | *无需安装* |
|
||||
| **socat** | 用于沙箱网络桥接的双向套接字中继 | `sudo apt install -y socat` | `sudo dnf install -y socat` | `sudo pacman -S --noconfirm socat` | `brew install socat` |
|
||||
| **ripgrep** | 用于工作区安全策略的高效文本搜索工具 | `sudo apt install -y ripgrep` | `sudo dnf install -y ripgrep` | `sudo pacman -S --noconfirm ripgrep` | `brew install ripgrep` |
|
||||
|
||||
> [!NOTE]
|
||||
> **Ubuntu 24.04+ 用户请注意:** 这些系统版本默认限制了非特权用户命名空间(unprivileged user namespaces)。为了让 `bubblewrap` 和沙箱隔离层正常工作,需要关闭此限制:
|
||||
> ```bash
|
||||
> sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
>
|
||||
> ```
|
||||
>
|
||||
>
|
||||
> 或者,您也可以专门配置一个 AppArmor 配置文件,为相关二进制文件授予用户命名空间创建(`userns`)权限。
|
||||
|
||||
#### 第四步:全局安装 Shumai
|
||||
|
||||
使用您常用的包管理器进行全局安装:
|
||||
|
||||
```bash
|
||||
# 使用 NPM
|
||||
npm install -g @shumai-one/shumai
|
||||
|
||||
# 使用 PNPM
|
||||
pnpm add -g @shumai-one/shumai
|
||||
|
||||
# 使用 Bun
|
||||
bun add -g @shumai-one/shumai
|
||||
|
||||
```
|
||||
|
||||
#### 第五步:配置环境配置
|
||||
|
||||
在刚才创建的工作区目录(`shumai/`)下新建一个 `.env` 文件,并填入以下配置:
|
||||
|
||||
```env
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
|
||||
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
STORAGE_BACKEND=local
|
||||
SHUMAI_SERVER_PORT=3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> `SHUMAI_SERVER_PORT` 用于设置 Web 服务的启动端口,而 `AWS_ENDPOINT_URL_S3` 供浏览器端构建文件上传链接。
|
||||
> 如果您部署在远程服务器(如 `http://123.456.7.8`)并且做了端口映射(如 Docker 中的 `12345:3000`),请将 `AWS_ENDPOINT_URL_S3` 设置为 `http://123.456.7.8:12345`。
|
||||
|
||||
#### 第六步:启动 Shumai
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Bun 用户特别提示:** 由于发布的包二进制文件包含 `#!/usr/bin/env node` 头部声明(Shebang),直接在终端执行全局命令(例如 `shumai`)默认会通过 Node.js 运行。如果您是用 Bun 安装的并且希望调用 Bun 运行时,请在所有命令前加上 `bun run --bun` 前缀(例如:`bun run --bun shumai`、`bun run --bun shumai -d`、`bun run --bun shumai stop`)。
|
||||
|
||||
在您的工作区目录下执行以下命令启动应用:
|
||||
|
||||
```bash
|
||||
shumai
|
||||
|
||||
```
|
||||
|
||||
您也可以让 Shumai 在后台以守护进程(Daemon)模式运行和管理:
|
||||
|
||||
* **后台模式启动**:
|
||||
```bash
|
||||
shumai -d
|
||||
|
||||
```
|
||||
|
||||
|
||||
* **停止服务**:
|
||||
```bash
|
||||
shumai stop
|
||||
|
||||
```
|
||||
|
||||
|
||||
* **重启服务**:
|
||||
```bash
|
||||
shumai restart
|
||||
|
||||
```
|
||||
|
||||
|
||||
* **查看并跟踪实时日志**:
|
||||
```bash
|
||||
shumai logs
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
启动时,Shumai 会自动执行数据库迁移(Migration)并在 `http://localhost:3000` 拉起 Web 服务。
|
||||
|
||||
---
|
||||
|
||||
### 方案三:源码编译运行(开发环境)
|
||||
|
||||
如果您希望在本地参与 Shumai 的开发,请按以下步骤配置开发环境:
|
||||
|
||||
1. 克隆代码仓库并安装依赖项:
|
||||
```bash
|
||||
git clone [https://github.com/shumaiOne/shumai.git](https://github.com/shumaiOne/shumai.git)
|
||||
cd shumai
|
||||
bun install
|
||||
|
||||
```
|
||||
|
||||
|
||||
2. 启动 `pgvector` 数据库容器(参考**方案二中的第一步**)。
|
||||
3. 参照**方案二中的第五步**,在项目根目录下创建一个 `.env` 文件。
|
||||
4. 执行数据库结构迁移:
|
||||
```bash
|
||||
bun run db:migrate
|
||||
|
||||
```
|
||||
|
||||
|
||||
5. 启动本地开发服务器:
|
||||
```bash
|
||||
bun run dev
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 命令行工具 (CLI)
|
||||
|
||||
Shumai 自带一个功能完备的命令行工具(CLI),支持您直接在终端里高效管理项目、文件夹、资产,批量上传文件/目录,以及快速创建新版本。
|
||||
|
||||
关于 CLI 的安装与详细使用指南,请参阅 [CLI Readme](https://www.google.com/search?q=apps/cli/README.md)。
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
services:
|
||||
postgres:
|
||||
image: docker.m.daocloud.io/pgvector/pgvector:pg18
|
||||
container_name: shumai_postgres
|
||||
environment:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
ports:
|
||||
- '5432:5432'
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/18/docker
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
shumai:
|
||||
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
environment:
|
||||
# Database Configuration
|
||||
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
|
||||
|
||||
# Server Configuration
|
||||
SHUMAI_SERVER_PORT: 3000
|
||||
|
||||
# S3 Configuration
|
||||
STORAGE_BACKEND: local
|
||||
AWS_ENDPOINT_URL_S3: http://localhost:3000
|
||||
|
||||
# Better Auth
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as path from 'path'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { detectSupportedMimeType } from '@shumai/core/src/utils/mime'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
|
||||
function getMimeType(filePath: string): string {
|
||||
try {
|
||||
@@ -64,7 +65,7 @@ export function createCreateFileTool(userId: string): AgentTool<typeof createFil
|
||||
const mimeType = getMimeType(absolutePath)
|
||||
|
||||
// Generate compliant S3 key matching normal file upload format
|
||||
const s3Key = `files/${ulid()}/raw`
|
||||
const s3Key = `files/${ulid()}/${sanitizeFilename(path.basename(absolutePath))}`
|
||||
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
|
||||
|
||||
const result = await executeAgentToolWorkflow({
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as path from 'path'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { detectSupportedMimeType } from '@shumai/core/src/utils/mime'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
|
||||
function getMimeType(filePath: string): string {
|
||||
try {
|
||||
@@ -65,7 +66,7 @@ export function createCreateVersionTool(userId: string): AgentTool<typeof create
|
||||
const mimeType = getMimeType(absolutePath)
|
||||
|
||||
// Generate compliant S3 key matching normal file upload format
|
||||
const s3Key = `files/${ulid()}/raw`
|
||||
const s3Key = `files/${ulid()}/${sanitizeFilename(path.basename(absolutePath))}`
|
||||
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
|
||||
|
||||
const result = await executeAgentToolWorkflow({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -299,5 +299,32 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const files = await assetService.getDownloadLinks(req.ids)
|
||||
return c.json({ files })
|
||||
})
|
||||
.post(
|
||||
'/files/download-url',
|
||||
zValidator('json', z.object({ key: z.string().min(1), assetId: z.string().min(1) })),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
const { key, assetId } = req
|
||||
|
||||
// Validate key format
|
||||
if (!key.startsWith('files/')) {
|
||||
return c.json({ error: 'Invalid key' }, 400)
|
||||
}
|
||||
|
||||
// Verify user has read access to the asset
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
|
||||
// Verify key belongs to the asset and generate download URL
|
||||
const url = await assetService.getDownloadUrl(assetId, key)
|
||||
|
||||
return c.json({ url })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
|
||||
@@ -147,6 +147,28 @@ const route = app
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
})
|
||||
.post(
|
||||
'/shares/:shareId/files/:fileId/download-url',
|
||||
zValidator('json', z.object({ key: z.string().min(1) })),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const { key } = c.req.valid('json')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
if (!key.startsWith('files/')) {
|
||||
return c.json({ error: 'Invalid key' }, 400)
|
||||
}
|
||||
|
||||
const url = await assetService.getDownloadUrl(fileId, key)
|
||||
return c.json({ url })
|
||||
} catch (err) {
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
|
||||
+19
-11
@@ -39,7 +39,7 @@ describe('S3 API', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('GET /files/* with filename query parameter sets Content-Disposition header', async () => {
|
||||
it('GET /files/* sets Content-Disposition: attachment only when download=1 query param is present', async () => {
|
||||
// We need to capture the onFound callback from serveStatic options
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let onFoundCallback: ((path: string, c: any) => void) | undefined
|
||||
@@ -54,26 +54,34 @@ describe('S3 API', () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
// First, verify onFound is called through the mock
|
||||
await app.request('/files/b1/test.webp?filename=my-file.txt')
|
||||
await app.request('/files/b1/test.webp?download=1')
|
||||
|
||||
expect(onFoundCallback).toBeDefined()
|
||||
|
||||
// Test the callback directly
|
||||
const mockContext = {
|
||||
req: {
|
||||
query: (key: string) => (key === 'filename' ? 'my-file.txt' : undefined),
|
||||
},
|
||||
// Test with download=1
|
||||
const mockContextWithDownload = {
|
||||
req: { query: (key: string) => (key === 'download' ? '1' : undefined) },
|
||||
header: vi.fn(),
|
||||
}
|
||||
|
||||
if (onFoundCallback) {
|
||||
onFoundCallback('/files/b1/test.webp', mockContext)
|
||||
expect(mockContext.header).toHaveBeenCalledWith(
|
||||
onFoundCallback('/files/b1/test.webp', mockContextWithDownload)
|
||||
expect(mockContextWithDownload.header).toHaveBeenCalledWith(
|
||||
'Content-Disposition',
|
||||
'attachment; filename="my-file.txt"',
|
||||
'attachment',
|
||||
)
|
||||
}
|
||||
|
||||
// Test without download param
|
||||
const mockContextWithout = {
|
||||
req: { query: () => undefined },
|
||||
header: vi.fn(),
|
||||
}
|
||||
|
||||
if (onFoundCallback) {
|
||||
onFoundCallback('/files/b1/test.webp', mockContextWithout)
|
||||
expect(mockContextWithout.header).not.toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
|
||||
it('PUT /files/:bucket/:key calls s3Service.putObject', async () => {
|
||||
|
||||
@@ -9,10 +9,8 @@ const route = new Hono()
|
||||
root: './data',
|
||||
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
|
||||
onFound: (_path, c) => {
|
||||
const filename = c.req.query('filename')
|
||||
if (filename) {
|
||||
const safeFilename = filename.replace(/["\r\n]/g, '_')
|
||||
c.header('Content-Disposition', `attachment; filename="${safeFilename}"`)
|
||||
if (c.req.query('download') === '1') {
|
||||
c.header('Content-Disposition', 'attachment')
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -2222,4 +2222,103 @@ describe('AssetService — natural sort by name', () => {
|
||||
expect(childActiveDb?.status).toBe('uploaded')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDownloadUrl', () => {
|
||||
it('should return a presigned download URL for a key in the same directory', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mp4' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const url = await assetService.getDownloadUrl(
|
||||
asset.id,
|
||||
'files/01TESTULID000000000000000/test-720p.mp4',
|
||||
)
|
||||
|
||||
expect(url).toBe('http://mock-s3-url')
|
||||
})
|
||||
|
||||
it('should return a presigned download URL for the original key', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mp4' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const url = await assetService.getDownloadUrl(
|
||||
asset.id,
|
||||
'files/01TESTULID000000000000000/test.mp4',
|
||||
)
|
||||
|
||||
expect(url).toBe('http://mock-s3-url')
|
||||
})
|
||||
|
||||
it('should throw if the key does not share the same parent directory', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mp4' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
assetService.getDownloadUrl(asset.id, 'files/01OTHERULIDXXXXXXXXXX/hack.mp4'),
|
||||
).rejects.toThrow('Key does not belong to this asset')
|
||||
})
|
||||
|
||||
it('should throw if the key contains path traversal segments', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mp4' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
assetService.getDownloadUrl(
|
||||
asset.id,
|
||||
'files/01TESTULID000000000000000/../01OTHERULIDXXXXXXXXXX/secret.mp4',
|
||||
),
|
||||
).rejects.toThrow('Key does not belong to this asset')
|
||||
})
|
||||
|
||||
it('should throw if the asset does not exist', async () => {
|
||||
await expect(
|
||||
assetService.getDownloadUrl('nonexistent-id', 'files/01TESTULID000000000000000/test.mp4'),
|
||||
).rejects.toThrow('Asset not found or has no storage key')
|
||||
})
|
||||
|
||||
it('should throw if the asset has no storage key', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'folder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
assetService.getDownloadUrl(asset.id, 'files/01TESTULID000000000000000/test.mp4'),
|
||||
).rejects.toThrow('Asset not found or has no storage key')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -842,7 +842,6 @@ export class AssetService {
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
info.media.original.key,
|
||||
'GET',
|
||||
a.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1583,7 +1582,7 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
const media = latestVersion.media as PrismaJson.MediaInfo | null
|
||||
let media = latestVersion.media as PrismaJson.MediaInfo | null
|
||||
if (media && media.videoPreview?.key) {
|
||||
media.videoPreview.url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
@@ -1593,21 +1592,19 @@ export class AssetService {
|
||||
}
|
||||
|
||||
const key = latestVersion.storageKey?.key
|
||||
if (media && key) {
|
||||
const fileName =
|
||||
a.type === AssetType.version_stack && (a.name === '' || !a.name)
|
||||
? latestVersion.name
|
||||
: a.name
|
||||
if (key) {
|
||||
if (!media) {
|
||||
media = {
|
||||
original: null,
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
} as unknown as PrismaJson.MediaInfo
|
||||
}
|
||||
media.original = {
|
||||
key,
|
||||
downloadUrl: await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
fileName,
|
||||
),
|
||||
downloadUrl: await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET'),
|
||||
filesizeInBytes: latestVersion.sizeByte,
|
||||
codec: '', // TODO: extract from metadata if needed
|
||||
codec: '',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1845,12 +1842,7 @@ export class AssetService {
|
||||
const key = file.storageKeyId ? storageKeyMap.get(file.storageKeyId) : null
|
||||
if (!key) return null
|
||||
|
||||
const url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
file.name,
|
||||
)
|
||||
const url = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true)
|
||||
|
||||
return {
|
||||
id: file.id,
|
||||
@@ -1863,6 +1855,31 @@ export class AssetService {
|
||||
return downloadLinks.filter((link): link is { id: string; name: string; url: string } => !!link)
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a presigned download URL for a given key, verifying it belongs to the asset's
|
||||
* storage directory. This ensures users can only download files (original, transcodes, etc.)
|
||||
* that belong to an asset they have access to.
|
||||
*/
|
||||
async getDownloadUrl(assetId: string, key: string): Promise<string> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: { storageKey: { select: { key: true } } },
|
||||
})
|
||||
|
||||
if (!asset?.storageKey?.key) {
|
||||
throw new Error('Asset not found or has no storage key')
|
||||
}
|
||||
|
||||
// Verify the requested key shares the same parent directory as the asset's storage key
|
||||
const storageKey = asset.storageKey.key
|
||||
const assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||
if (key.includes('..') || !key.startsWith(assetDir)) {
|
||||
throw new Error('Key does not belong to this asset')
|
||||
}
|
||||
|
||||
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true)
|
||||
}
|
||||
|
||||
private async toPreviewInfo(asset: Asset | AssetWithIncludes): Promise<PreviewInfo | null> {
|
||||
if (!asset.media) return null
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { auth } from './auth'
|
||||
import { userMetadataService } from '../user-metadata/user-metadata'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
|
||||
describe('Auth Signup Locale Hook', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(teamService, 'getSignupInfo').mockResolvedValue({
|
||||
initialized: false,
|
||||
demoMode: false,
|
||||
userCount: 1,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('should save locale metadata for the user upon signup', async () => {
|
||||
const email = `signup-locale-${Date.now()}@example.com`
|
||||
|
||||
// We must use any here because 'locale' is a custom property we extract in
|
||||
// our auth hooks, but better-auth's signUpEmail typescript interface does
|
||||
// not recognize it.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const res = await (auth.api.signUpEmail as any)({
|
||||
headers: new Headers(),
|
||||
body: {
|
||||
email,
|
||||
password: 'testpassword',
|
||||
name: 'Locale Tester',
|
||||
locale: 'zh',
|
||||
},
|
||||
})
|
||||
|
||||
if (res.error) {
|
||||
console.error('SIGNUP ERROR:', res.error)
|
||||
}
|
||||
|
||||
expect(res).toBeDefined()
|
||||
expect(res.user).toBeDefined()
|
||||
expect(res.user.email).toBe(email)
|
||||
|
||||
// Check that the userMetadata record was created with key 'locale' and value 'zh'
|
||||
const teamMembers = await prisma.teamMember.findMany({
|
||||
where: { userId: res.user.id },
|
||||
})
|
||||
expect(teamMembers.length).toBeGreaterThan(0)
|
||||
|
||||
for (const member of teamMembers) {
|
||||
const meta = await userMetadataService.getMetadata(res.user.id, member.teamId, 'locale')
|
||||
expect(meta).toBeDefined()
|
||||
expect(meta?.value).toBe('zh')
|
||||
}
|
||||
})
|
||||
|
||||
it('should not save locale metadata if locale is invalid or missing', async () => {
|
||||
const email = `signup-no-locale-${Date.now()}@example.com`
|
||||
|
||||
// We must use any here because 'locale' is a custom property we extract in
|
||||
// our auth hooks, but better-auth's signUpEmail typescript interface does
|
||||
// not recognize it.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const res = await (auth.api.signUpEmail as any)({
|
||||
headers: new Headers(),
|
||||
body: {
|
||||
email,
|
||||
password: 'testpassword',
|
||||
name: 'No Locale Tester',
|
||||
locale: 'fr', // invalid locale
|
||||
},
|
||||
})
|
||||
|
||||
if (res.error) {
|
||||
console.error('SIGNUP ERROR 2:', res.error)
|
||||
}
|
||||
|
||||
expect(res).toBeDefined()
|
||||
expect(res.user).toBeDefined()
|
||||
|
||||
const teamMembers = await prisma.teamMember.findMany({
|
||||
where: { userId: res.user.id },
|
||||
})
|
||||
expect(teamMembers.length).toBeGreaterThan(0)
|
||||
|
||||
for (const member of teamMembers) {
|
||||
const meta = await userMetadataService.getMetadata(res.user.id, member.teamId, 'locale')
|
||||
expect(meta).toBeNull()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { prisma } from '@shumai/db'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { createAuthMiddleware } from 'better-auth/api'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, {
|
||||
@@ -102,6 +103,17 @@ export const auth = betterAuth({
|
||||
if (inviteCode) {
|
||||
await inviteService.consumeInvite(inviteCode, user.id)
|
||||
}
|
||||
|
||||
const locale = body?.locale
|
||||
if (locale === 'en' || locale === 'zh') {
|
||||
const joinedTeams = await prisma.teamMember.findMany({
|
||||
where: { userId: user.id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
for (const member of joinedTeams) {
|
||||
await userMetadataService.upsertMetadata(user.id, member.teamId, 'locale', locale)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Better Auth Hook] Error in after hook: ${err}`)
|
||||
}
|
||||
|
||||
@@ -117,17 +117,44 @@ describe('S3Service implementations', () => {
|
||||
delete process.env.PRESIGNED_URL_EXPIRES_IN
|
||||
})
|
||||
|
||||
it('should pass filename to presign', async () => {
|
||||
it('should not set contentDisposition for normal GET presign', async () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
await s3.presign('bucket', 'key', 'GET', 'test.txt')
|
||||
await s3.presign('bucket', 'key', 'GET')
|
||||
|
||||
expect(s3PresignSpy).toHaveBeenCalledWith(
|
||||
'key',
|
||||
expect.not.objectContaining({
|
||||
contentDisposition: expect.anything(),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should set contentDisposition attachment when download is true', async () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
await s3.presign('bucket', 'key', 'GET', true)
|
||||
|
||||
expect(s3PresignSpy).toHaveBeenCalledWith(
|
||||
'key',
|
||||
expect.objectContaining({
|
||||
contentDisposition: 'attachment; filename="test.txt"',
|
||||
contentDisposition: 'attachment',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not cache download presign URLs', async () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
|
||||
s3PresignSpy.mockClear()
|
||||
s3PresignSpy.mockReturnValueOnce('http://download-url-1')
|
||||
s3PresignSpy.mockReturnValueOnce('http://download-url-2')
|
||||
|
||||
const url1 = await s3.presign('bucket', 'key', 'GET', true)
|
||||
const url2 = await s3.presign('bucket', 'key', 'GET', true)
|
||||
|
||||
expect(url1).toBe('http://download-url-1')
|
||||
expect(url2).toBe('http://download-url-2')
|
||||
expect(s3PresignSpy).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('LocalStorageService', () => {
|
||||
@@ -182,9 +209,9 @@ describe('S3Service implementations', () => {
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt')
|
||||
})
|
||||
|
||||
it('should generate a local presign URL with filename', async () => {
|
||||
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', 'original.txt')
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt?filename=original.txt')
|
||||
it('should generate a local presign URL with download param', async () => {
|
||||
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt?download=1')
|
||||
})
|
||||
|
||||
it('should throw an error for unsupported presign methods', async () => {
|
||||
|
||||
+10
-10
@@ -54,7 +54,7 @@ export interface S3Service {
|
||||
listObjects(bucket: string, prefix: string): Promise<string[]>
|
||||
uploadFile(filePath: string, contentType: string): Promise<string>
|
||||
uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void>
|
||||
presign(bucket: string, key: string, method: string, filename?: string): Promise<string>
|
||||
presign(bucket: string, key: string, method: string, download?: boolean): Promise<string>
|
||||
}
|
||||
|
||||
export class S3StorageService implements S3Service {
|
||||
@@ -203,16 +203,16 @@ export class S3StorageService implements S3Service {
|
||||
})
|
||||
}
|
||||
|
||||
async presign(bucket: string, key: string, method: string, filename?: string): Promise<string> {
|
||||
async presign(bucket: string, key: string, method: string, download?: boolean): Promise<string> {
|
||||
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
|
||||
const expiresInSeconds = expireHours * 3600
|
||||
// Cache time is 2/3 of expire time, rounded to minute
|
||||
const cacheMinutes = Math.round((expireHours * 60 * 2) / 3)
|
||||
const cacheTtlMs = cacheMinutes * 60 * 1000
|
||||
|
||||
const cacheKey = `${bucket}:${key}:${filename || ''}`
|
||||
const cacheKey = `${bucket}:${key}`
|
||||
|
||||
if (method === 'GET') {
|
||||
if (method === 'GET' && !download) {
|
||||
const cached = this.presignCache.get(cacheKey)
|
||||
if (cached) return cached
|
||||
}
|
||||
@@ -225,13 +225,13 @@ export class S3StorageService implements S3Service {
|
||||
method: method as any,
|
||||
}
|
||||
|
||||
if (filename) {
|
||||
options.contentDisposition = `attachment; filename="${filename}"`
|
||||
if (download) {
|
||||
options.contentDisposition = 'attachment'
|
||||
}
|
||||
|
||||
const url = this.client.presign(key, options)
|
||||
|
||||
if (method === 'GET') {
|
||||
if (method === 'GET' && !download) {
|
||||
this.presignCache.set(cacheKey, url, cacheTtlMs)
|
||||
}
|
||||
|
||||
@@ -435,7 +435,7 @@ export class LocalStorageService implements S3Service {
|
||||
await fs.promises.copyFile(filePath, destPath)
|
||||
}
|
||||
|
||||
async presign(bucket: string, key: string, method: string, filename?: string): Promise<string> {
|
||||
async presign(bucket: string, key: string, method: string, download?: boolean): Promise<string> {
|
||||
if (method !== 'GET' && method !== 'PUT') {
|
||||
throw new Error(`Invalid method: ${method}`)
|
||||
}
|
||||
@@ -443,8 +443,8 @@ export class LocalStorageService implements S3Service {
|
||||
return `${this.endpoint}${signLocalUrl(bucket, key)}`
|
||||
}
|
||||
let url = `${this.endpoint}/files/${bucket}/${key}`
|
||||
if (filename) {
|
||||
url += `?filename=${encodeURIComponent(filename)}`
|
||||
if (download) {
|
||||
url += '?download=1'
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
@@ -256,7 +256,7 @@ export class TranscodeService {
|
||||
duration: number,
|
||||
): Promise<void> {
|
||||
const spriteFps = 100 / duration
|
||||
const filterComplex = `[0:v]fps=${spriteFps},scale=w=480:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:720:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
|
||||
const filterComplex = `[0:v]fps=${spriteFps},scale=w=480:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:480:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
|
||||
|
||||
const args = [
|
||||
'-i',
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { ImageTranscoder, VideoTranscoder } from '@shumai/transcode'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
|
||||
export class UploadService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
@@ -130,7 +131,7 @@ export class UploadService {
|
||||
const assetType = file.type === 'folder' ? AssetType.folder : AssetType.file
|
||||
let key: string | null = null
|
||||
if (assetType === AssetType.file) {
|
||||
key = `files/${ulid()}/raw`
|
||||
key = `files/${ulid()}/${sanitizeFilename(file.name)}`
|
||||
}
|
||||
|
||||
const newAsset = await tx.asset.create({
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { sanitizeFilename, stemFromKey } from './filename'
|
||||
|
||||
describe('sanitizeFilename', () => {
|
||||
it('returns the filename unchanged when it is already safe', () => {
|
||||
expect(sanitizeFilename('foo.mp4')).toBe('foo.mp4')
|
||||
expect(sanitizeFilename('my-video_final.mov')).toBe('my-video_final.mov')
|
||||
})
|
||||
|
||||
it('replaces slashes and backslashes with underscores', () => {
|
||||
expect(sanitizeFilename('path/to/file.mp4')).toBe('path_to_file.mp4')
|
||||
expect(sanitizeFilename('path\\to\\file.mp4')).toBe('path_to_file.mp4')
|
||||
})
|
||||
|
||||
it('replaces NUL bytes and control characters', () => {
|
||||
expect(sanitizeFilename('foo\x00bar.mp4')).toBe('foo_bar.mp4')
|
||||
expect(sanitizeFilename('foo\x01bar.mp4')).toBe('foo_bar.mp4')
|
||||
})
|
||||
|
||||
it('trims leading and trailing dots and whitespace', () => {
|
||||
expect(sanitizeFilename('.hidden')).toBe('hidden')
|
||||
expect(sanitizeFilename('...dotted...')).toBe('dotted')
|
||||
expect(sanitizeFilename(' spaced ')).toBe('spaced')
|
||||
expect(sanitizeFilename(' .mixed. ')).toBe('mixed')
|
||||
})
|
||||
|
||||
it('collapses multiple consecutive underscores', () => {
|
||||
expect(sanitizeFilename('a//b')).toBe('a_b')
|
||||
expect(sanitizeFilename('a///b')).toBe('a_b')
|
||||
})
|
||||
|
||||
it('returns "file" for empty or whitespace-only input', () => {
|
||||
expect(sanitizeFilename('')).toBe('file')
|
||||
expect(sanitizeFilename(' ')).toBe('file')
|
||||
expect(sanitizeFilename('...')).toBe('file')
|
||||
})
|
||||
|
||||
it('preserves unicode characters', () => {
|
||||
expect(sanitizeFilename('视频文件.mp4')).toBe('视频文件.mp4')
|
||||
expect(sanitizeFilename('café.png')).toBe('café.png')
|
||||
})
|
||||
|
||||
it('preserves spaces within the filename', () => {
|
||||
expect(sanitizeFilename('my video file.mp4')).toBe('my video file.mp4')
|
||||
})
|
||||
})
|
||||
|
||||
describe('stemFromKey', () => {
|
||||
it('extracts the stem from a key with extension', () => {
|
||||
expect(stemFromKey('files/01ABC/foo.mp4')).toBe('foo')
|
||||
expect(stemFromKey('files/01ABC/my-video.mov')).toBe('my-video')
|
||||
})
|
||||
|
||||
it('extracts the stem from a key without extension', () => {
|
||||
expect(stemFromKey('files/01ABC/raw')).toBe('raw')
|
||||
})
|
||||
|
||||
it('handles keys with multiple dots in filename', () => {
|
||||
expect(stemFromKey('files/01ABC/my.video.file.mp4')).toBe('my.video.file')
|
||||
})
|
||||
|
||||
it('handles keys with no directory', () => {
|
||||
expect(stemFromKey('foo.mp4')).toBe('foo')
|
||||
expect(stemFromKey('raw')).toBe('raw')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import path from 'path'
|
||||
|
||||
/**
|
||||
* Sanitize a filename for safe use as an S3 key segment.
|
||||
* - Replaces characters unsafe for S3/filesystems with '_'
|
||||
* - Trims leading/trailing whitespace and dots
|
||||
* - Falls back to 'file' if the result is empty
|
||||
*/
|
||||
export function sanitizeFilename(filename: string): string {
|
||||
// Replace NUL bytes, slashes, backslashes, and control characters
|
||||
// eslint-disable-next-line no-control-regex
|
||||
let safe = filename.replace(/[\x00-\x1f\x7f/\\]/g, '_')
|
||||
|
||||
// Trim leading/trailing whitespace and dots
|
||||
safe = safe.replace(/^[\s.]+|[\s.]+$/g, '')
|
||||
|
||||
// Collapse multiple underscores
|
||||
safe = safe.replace(/_+/g, '_')
|
||||
|
||||
if (!safe) {
|
||||
return 'file'
|
||||
}
|
||||
|
||||
return safe
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the filename stem (without extension) from a storage key.
|
||||
* e.g. 'files/01ABC.../foo.mp4' → 'foo'
|
||||
* 'files/01ABC.../raw' → 'raw'
|
||||
*/
|
||||
export function stemFromKey(key: string): string {
|
||||
const basename = path.basename(key)
|
||||
const ext = path.extname(basename)
|
||||
return ext ? basename.slice(0, -ext.length) : basename
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -279,6 +279,7 @@ export interface ImageTranscode {
|
||||
export interface VideoTranscode {
|
||||
id: string
|
||||
url: string
|
||||
key: string
|
||||
width: number
|
||||
height: number
|
||||
size: number
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -2,6 +2,7 @@ import { prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/core'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
@@ -162,7 +163,9 @@ export async function transcodeVideoActivity(
|
||||
params: VideoActivityParams,
|
||||
): Promise<PrismaJson.VideoTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const key = path.join(path.dirname(params.assetKey), `video-${params.videoSpec.height}p.mp4`)
|
||||
const stem = stemFromKey(params.assetKey)
|
||||
const res = params.videoSpec.resolution || `${params.videoSpec.height}p`
|
||||
const key = path.posix.join(path.posix.dirname(params.assetKey), `${stem}-${res}.mp4`)
|
||||
|
||||
try {
|
||||
await s3Service.headObject(bucket, key)
|
||||
@@ -172,7 +175,7 @@ export async function transcodeVideoActivity(
|
||||
}
|
||||
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const outputFile = path.join(tmpDir, `video-${params.videoSpec.height}p.mp4`)
|
||||
const outputFile = path.join(tmpDir, `${stem}-${res}.mp4`)
|
||||
|
||||
try {
|
||||
let targetFps: number | string = params.originalFps || 30
|
||||
@@ -237,7 +240,11 @@ export async function transcodeImageActivity(
|
||||
params: ImageActivityParams,
|
||||
): Promise<PrismaJson.ImageTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const key = path.join(path.dirname(params.assetKey), `image-${params.imageSpec.width}p.webp`)
|
||||
const stem = stemFromKey(params.assetKey)
|
||||
const key = path.posix.join(
|
||||
path.posix.dirname(params.assetKey),
|
||||
`${stem}-${params.imageSpec.width}p.webp`,
|
||||
)
|
||||
|
||||
try {
|
||||
await s3Service.headObject(bucket, key)
|
||||
@@ -247,7 +254,7 @@ export async function transcodeImageActivity(
|
||||
}
|
||||
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const outputFile = path.join(tmpDir, `image-${params.imageSpec.width}p.webp`)
|
||||
const outputFile = path.join(tmpDir, `${stem}-${params.imageSpec.width}p.webp`)
|
||||
|
||||
try {
|
||||
await transcodeService.transcodeImage(
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { client } from '@/ui/api/client'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuSub,
|
||||
@@ -44,6 +46,15 @@ interface BreadcrumbNavProps {
|
||||
shareId?: string
|
||||
onFolderClick?: (folderId: string) => void
|
||||
fileId?: string
|
||||
downloadInfo?: {
|
||||
originalKey?: string
|
||||
videoTranscodes?: Array<{
|
||||
key: string
|
||||
width: number
|
||||
height: number
|
||||
isRaw?: boolean
|
||||
}>
|
||||
}
|
||||
versions?: Array<{
|
||||
id: string
|
||||
version: number
|
||||
@@ -69,6 +80,8 @@ export function BreadcrumbNav({
|
||||
isPublic = false,
|
||||
onFolderClick,
|
||||
fileId,
|
||||
shareId,
|
||||
downloadInfo,
|
||||
versions,
|
||||
}: BreadcrumbNavProps) {
|
||||
const navigate = useNavigate()
|
||||
@@ -83,6 +96,33 @@ export function BreadcrumbNav({
|
||||
})
|
||||
}
|
||||
|
||||
const handleDownload = async (key: string) => {
|
||||
if (!fileId) return
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: fileId },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}
|
||||
|
||||
const hasVideoTranscodes =
|
||||
downloadInfo?.videoTranscodes && downloadInfo.videoTranscodes.filter((t) => !t.isRaw).length > 0
|
||||
|
||||
const breadcrumbs: { name: string; path?: string; id?: string; isMuted?: boolean }[] = isPublic
|
||||
? [
|
||||
{
|
||||
@@ -155,9 +195,63 @@ export function BreadcrumbNav({
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56">
|
||||
<DropdownMenuItem onClick={() => console.log('Download')}>
|
||||
Download
|
||||
</DropdownMenuItem>
|
||||
{hasVideoTranscodes ? (
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="flex items-center gap-2">
|
||||
<span>{m.download()}</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuSubContent className="w-48">
|
||||
<DropdownMenuLabel>{m.download()}</DropdownMenuLabel>
|
||||
{downloadInfo?.videoTranscodes
|
||||
?.filter((t) => !t.isRaw)
|
||||
.map((t) => {
|
||||
const longSide = Math.max(t.width, t.height)
|
||||
let resolution = `${t.height}p`
|
||||
if (longSide >= 3840) resolution = '2160p'
|
||||
else if (longSide >= 1920) resolution = '1080p'
|
||||
else if (longSide >= 1280) resolution = '720p'
|
||||
else if (longSide >= 960) resolution = '540p'
|
||||
else if (longSide >= 640) resolution = '360p'
|
||||
else if (longSide >= 320) resolution = '180p'
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={resolution}
|
||||
onClick={() => handleDownload(t.key)}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span>{resolution}</span>
|
||||
<span className="text-xs text-muted-foreground">MP4</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
{downloadInfo?.originalKey && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDownload(downloadInfo.originalKey!)}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span>Original</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{currentAsset.name?.split('.').pop()?.toUpperCase() || 'RAW'}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenuSub>
|
||||
) : (
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
downloadInfo?.originalKey && handleDownload(downloadInfo.originalKey)
|
||||
}
|
||||
disabled={!downloadInfo?.originalKey}
|
||||
>
|
||||
{m.download()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canEdit && (
|
||||
<DropdownMenuItem onClick={() => console.log('Rename')}>
|
||||
Rename
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useScreenSize } from '@/ui/hooks/useScreenSize'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { getBestTranscode } from '@/ui/lib/media'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { Check, Copy, Download, Minus, Plus } from 'lucide-react'
|
||||
@@ -19,6 +20,7 @@ type FileViewerProps = {
|
||||
onTimeUpdate?: (time: number) => void
|
||||
annotations?: Annotation[]
|
||||
startTime?: number
|
||||
shareId?: string
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
@@ -30,6 +32,7 @@ export function FileViewer({
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
shareId,
|
||||
children,
|
||||
}: FileViewerProps) {
|
||||
const { width: screenWidth } = useScreenSize()
|
||||
@@ -133,15 +136,29 @@ export function FileViewer({
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = () => {
|
||||
const url = file.media?.original?.downloadUrl
|
||||
if (!url) return
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = file.name || 'image'
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
const handleDownload = async () => {
|
||||
const key = file.media?.original?.key
|
||||
if (!key || !file.id) return
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: file.id },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: file.id },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopy = async () => {
|
||||
@@ -210,7 +227,7 @@ export function FileViewer({
|
||||
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
|
||||
<button
|
||||
onClick={handleDownload}
|
||||
disabled={!file.media?.original?.downloadUrl}
|
||||
disabled={!file.media?.original?.key}
|
||||
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
|
||||
title="Download original file"
|
||||
>
|
||||
@@ -291,7 +308,7 @@ export function FileViewer({
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDownload}
|
||||
disabled={!file.media?.original?.downloadUrl}
|
||||
disabled={!file.media?.original?.key}
|
||||
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
|
||||
title="Download original image"
|
||||
>
|
||||
@@ -311,6 +328,7 @@ export function FileViewer({
|
||||
onTimeUpdate={onTimeUpdate}
|
||||
annotations={displayAnnotations}
|
||||
startTime={startTime}
|
||||
shareId={shareId}
|
||||
>
|
||||
{children}
|
||||
</VideoPlayer>
|
||||
|
||||
@@ -350,6 +350,17 @@ export function PublicShareManager({
|
||||
isPublic: true,
|
||||
shareId,
|
||||
fileId: viewingFileId || undefined,
|
||||
downloadInfo: viewingFileData
|
||||
? {
|
||||
originalKey: viewingFileData.media?.original?.key,
|
||||
videoTranscodes: viewingFileData.media?.videoTranscodes?.map((t) => ({
|
||||
key: t.key,
|
||||
width: t.width,
|
||||
height: t.height,
|
||||
isRaw: t.isRaw,
|
||||
})),
|
||||
}
|
||||
: undefined,
|
||||
onFolderClick: handleBreadcrumbClick,
|
||||
isRightSidebarCollapsed,
|
||||
onRightSidebarToggle: () => setIsRightSidebarCollapsed((prev) => !prev),
|
||||
@@ -458,6 +469,7 @@ export function PublicShareManager({
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
shareId={shareId}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -19,6 +19,7 @@ export function TopNav() {
|
||||
currentAsset,
|
||||
isRootFolder,
|
||||
fileId,
|
||||
downloadInfo,
|
||||
versions,
|
||||
isPublic,
|
||||
shareId,
|
||||
@@ -87,6 +88,7 @@ export function TopNav() {
|
||||
isPublic={isPublic}
|
||||
shareId={shareId}
|
||||
fileId={fileId}
|
||||
downloadInfo={downloadInfo}
|
||||
versions={versions}
|
||||
onFolderClick={onFolderClick}
|
||||
/>
|
||||
|
||||
@@ -74,13 +74,6 @@ export function useFramePlayer(
|
||||
const stallThreshold = Math.max(100, 3000 / frameRate)
|
||||
const isVfcStalled = Date.now() - lastVfcTime > stallThreshold
|
||||
|
||||
// Print debug log roughly once per second during playback
|
||||
if (Math.floor(video.currentTime * frameRate + 0.45) % 30 === 0) {
|
||||
console.log(
|
||||
`[useFramePlayer] currentTime: ${video.currentTime}, isVfcStalled: ${isVfcStalled}, stallThreshold: ${stallThreshold}, totalFrames: ${totalFrames}`,
|
||||
)
|
||||
}
|
||||
|
||||
// Only update playhead via currentTime (RAF) if rVFC has stalled or isn't supported
|
||||
if (!videoWithCallback.requestVideoFrameCallback || isVfcStalled) {
|
||||
const frame = Math.floor(video.currentTime * frameRate + 0.45)
|
||||
@@ -133,8 +126,11 @@ export function useFramePlayer(
|
||||
setCurrentFrame(clamped)
|
||||
|
||||
// Snap the playhead to the center of the paused frame to align browser compositor
|
||||
const safeCenterTime = calculateFrameCenterTime(clamped, frameRate)
|
||||
video.currentTime = safeCenterTime
|
||||
// Skip snapping if the video has ended to preserve the native ended state and allow native replay
|
||||
if (!video.ended) {
|
||||
const safeCenterTime = calculateFrameCenterTime(clamped, frameRate)
|
||||
video.currentTime = safeCenterTime
|
||||
}
|
||||
}
|
||||
|
||||
video.addEventListener('play', handlePlay)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AssetInfo, VideoTranscode } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import {
|
||||
Check,
|
||||
@@ -58,6 +59,7 @@ interface VideoPlayerProps {
|
||||
onTimeUpdate?: (time: number) => void
|
||||
annotations?: Annotation[]
|
||||
startTime?: number
|
||||
shareId?: string
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
@@ -76,7 +78,7 @@ interface ControlBarProps {
|
||||
handleVolumeChange: (newVolume: number) => void
|
||||
changePlaybackRate: (rate: number) => void
|
||||
changeResolution: (res: DisplayTranscode) => void
|
||||
handleDownload: (url: string, resolution: string) => void
|
||||
handleDownload: (key: string) => void
|
||||
toggleFullScreen: () => void
|
||||
onZoomChange: (zoom: number) => void
|
||||
onZoomReset: () => void
|
||||
@@ -344,11 +346,13 @@ const ControlBar: React.FC<ControlBarProps> = ({
|
||||
{resolutions.map((res) => (
|
||||
<DropdownMenuItem
|
||||
key={res.resolution}
|
||||
onClick={() => handleDownload(res.url ?? '', res.resolution)}
|
||||
onClick={() => handleDownload(res.key ?? '')}
|
||||
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
|
||||
>
|
||||
<span>{res.resolution}</span>
|
||||
<span className="text-xs text-muted-foreground">MP4</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{res.isRaw ? data.name?.split('.').pop()?.toUpperCase() || 'RAW' : 'MP4'}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
@@ -376,6 +380,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
shareId,
|
||||
children,
|
||||
}) => {
|
||||
const localPlayerRef = useRef<Player | null>(null)
|
||||
@@ -456,12 +461,16 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
}
|
||||
|
||||
// Initial resolution setup
|
||||
const originalRes = {
|
||||
const originalRes: DisplayTranscode = {
|
||||
id: 'original',
|
||||
url: data.media.original.downloadUrl,
|
||||
key: data.media.original.key ?? '',
|
||||
width: data.media.metadata.originalWidth ?? 0,
|
||||
height: data.media.metadata.originalHeight ?? 0,
|
||||
size: 0,
|
||||
isRaw: true,
|
||||
resolution: 'Original',
|
||||
} as DisplayTranscode
|
||||
}
|
||||
|
||||
const resolutions: DisplayTranscode[] = (data.media.videoTranscodes ?? []).map((t) => {
|
||||
const longSide = Math.max(t.width, t.height)
|
||||
@@ -837,13 +846,27 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = (url: string, resolution: string) => {
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = `${data.name}-${resolution}.mp4`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
const handleDownload = async (key: string) => {
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: data.id! },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: data.id! },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for fullscreen change events (ESC key)
|
||||
|
||||
@@ -424,8 +424,8 @@
|
||||
"avatar_source": "头像来源",
|
||||
"saving": "保存中",
|
||||
|
||||
"auth_tagline": "一个工作区,管理所有创意资产。",
|
||||
"auth_description": "上传并索引您的文件,使用自定义元数据模式丰富它们,直接在媒体上绘制标注,并收集即时反馈——这一切都在一个为创作者打造的现代工作区中完成。",
|
||||
"auth_tagline": "一站式创意资产管理协作平台。",
|
||||
"auth_description": "上传您的创意资产,添加各种类型的自定义元数据,直接在图片或视频上绘制标注和添加评论,——这一切都在Shumai,一个为创作者打造的一站式平台上完成。",
|
||||
"auth_feature_uploads": "即时资产上传 & 高保真媒体播放器",
|
||||
"auth_feature_metadata": "自定义元数据模式 & 画布标注审阅",
|
||||
"auth_feature_teams": "无缝团队工作区 & 安全分享",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./index.html",
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ const en_auth_description = /** @type {(inputs: Auth_DescriptionInputs) => Local
|
||||
};
|
||||
|
||||
const zh_auth_description = /** @type {(inputs: Auth_DescriptionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`上传并索引您的文件,使用自定义元数据模式丰富它们,直接在媒体上绘制标注,并收集即时反馈——这一切都在一个为创作者打造的现代工作区中完成。`)
|
||||
return /** @type {LocalizedString} */ (`上传您的创意资产,添加各种类型的自定义元数据,直接在图片或视频上绘制标注和添加评论,——这一切都在Shumai,一个为创作者打造的一站式平台上完成。`)
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ const en_auth_tagline = /** @type {(inputs: Auth_TaglineInputs) => LocalizedStri
|
||||
};
|
||||
|
||||
const zh_auth_tagline = /** @type {(inputs: Auth_TaglineInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`一个工作区,管理所有创意资产。`)
|
||||
return /** @type {LocalizedString} */ (`一站式创意资产管理协作平台。`)
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -148,6 +148,15 @@ function FileViewPage() {
|
||||
},
|
||||
isRootFolder: false,
|
||||
fileId,
|
||||
downloadInfo: {
|
||||
originalKey: fileData.media?.original?.key,
|
||||
videoTranscodes: fileData.media?.videoTranscodes?.map((t) => ({
|
||||
key: t.key,
|
||||
width: t.width,
|
||||
height: t.height,
|
||||
isRaw: t.isRaw,
|
||||
})),
|
||||
},
|
||||
versions: versionsDataList,
|
||||
onFolderClick: (id: string) => {
|
||||
navigate({
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { AuthLayout } from '@/ui/components/auth-layout'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { ShumaiLogo } from '@/ui/components/ui/icons'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Loader2, Mail, Lock, ArrowRight, UserPlus } from 'lucide-react'
|
||||
import { signUp } from '@/ui/lib/auth-client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { getLocale, setLocale } from '@/ui/paraglide/runtime.js'
|
||||
import { useAuthStore } from '@/ui/stores/auth'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router'
|
||||
import { ArrowRight, Loader2, Lock, Mail, UserPlus } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
import { signUp } from '@/ui/lib/auth-client'
|
||||
import { useState } from 'react'
|
||||
import { ShumaiLogo } from '@/ui/components/ui/icons'
|
||||
import { AuthLayout } from '@/ui/components/auth-layout'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
const signupSchema = z.object({
|
||||
email: z.string().email(m.invalid_email_address()),
|
||||
@@ -30,6 +31,15 @@ function SignupPage() {
|
||||
const inviteCode = (search as { inviteCode?: string }).inviteCode
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [locale, setLocaleState] = useState<'en' | 'zh'>(() => {
|
||||
const activeLocale = getLocale()
|
||||
return activeLocale === 'zh' ? 'zh' : 'en'
|
||||
})
|
||||
|
||||
const handleLocaleChange = (newLocale: 'en' | 'zh') => {
|
||||
setLocaleState(newLocale)
|
||||
setLocale(newLocale)
|
||||
}
|
||||
|
||||
const { data: inviteInfo } = useQuery({
|
||||
queryKey: ['invite', inviteCode],
|
||||
@@ -71,6 +81,7 @@ function SignupPage() {
|
||||
password: data.password,
|
||||
name: data.email, // Use email as the username
|
||||
inviteCode: data.inviteCode,
|
||||
locale,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
@@ -238,14 +249,38 @@ function SignupPage() {
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-8 pt-6 border-t border-zinc-200/30 dark:border-zinc-800/30 text-center text-sm">
|
||||
<span className="text-zinc-500 dark:text-zinc-400">{m.already_have_account()}</span>
|
||||
<a
|
||||
href="/login"
|
||||
className="font-semibold text-rose-500 hover:text-rose-600 dark:text-rose-400 dark:hover:text-rose-300 transition-colors hover:underline inline-flex items-center gap-0.5"
|
||||
>
|
||||
{m.login()} <ArrowRight className="w-3.5 h-3.5" />
|
||||
</a>
|
||||
<div className="mt-12 pt-10 border-t border-zinc-200/30 dark:border-zinc-800/30 text-center text-sm flex flex justify-between gap-4">
|
||||
<div>
|
||||
<span className="text-zinc-500 dark:text-zinc-400">{m.already_have_account()} </span>
|
||||
<a
|
||||
href="/login"
|
||||
className="font-semibold text-rose-500 hover:text-rose-600 dark:text-rose-400 dark:hover:text-rose-300 transition-colors hover:underline inline-flex items-center gap-0.5"
|
||||
>
|
||||
{m.login()} <ArrowRight className="w-3.5 h-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-xs text-zinc-400 dark:text-zinc-500">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleLocaleChange('en')}
|
||||
className={`cursor-pointer hover:text-zinc-800 dark:hover:text-zinc-200 transition-colors ${
|
||||
locale === 'en' ? 'font-bold text-rose-500 dark:text-rose-400' : ''
|
||||
}`}
|
||||
>
|
||||
English
|
||||
</button>
|
||||
<span className="text-zinc-300 dark:text-zinc-850">/</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleLocaleChange('zh')}
|
||||
className={`cursor-pointer hover:text-zinc-800 dark:hover:text-zinc-200 transition-colors ${
|
||||
locale === 'zh' ? 'font-bold text-rose-500 dark:text-rose-400' : ''
|
||||
}`}
|
||||
>
|
||||
中文
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</AuthLayout>
|
||||
)
|
||||
|
||||
@@ -13,6 +13,15 @@ export interface TopNavProjectState {
|
||||
}
|
||||
isRootFolder: boolean
|
||||
fileId?: string
|
||||
downloadInfo?: {
|
||||
originalKey?: string
|
||||
videoTranscodes?: Array<{
|
||||
key: string
|
||||
width: number
|
||||
height: number
|
||||
isRaw?: boolean
|
||||
}>
|
||||
}
|
||||
versions?: Array<{
|
||||
id: string
|
||||
version: number
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const APP_VERSION = '0.1.3'
|
||||
export const APP_VERSION = '0.1.5'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
Reference in New Issue
Block a user