Compare commits

..
26 Commits
Author SHA1 Message Date
XingfenD 8bcef95dd4 Merge branch 'feat/docker-support' 2026-08-27 15:35:04 +08:00
XingfenD 3171866344 chore: gitignore local .env file 2026-08-27 15:32:57 +08:00
XingfenD 1f8529badc feat: add Docker deployment support
Add Dockerfile, docker-compose.yml, .dockerignore, .env.example, Makefile docker targets, and README/CHANGELOG docs.
2026-08-27 15:32:47 +08:00
XingfenD 16f20af5ae Merge branch 'feat/web-component-refactor' 2026-08-27 15:23:41 +08:00
XingfenD 5bb42a8b8a feat(web): add i18n, light/dark theme switching, and version constant
- Add i18n (English + 简体中文) with a locale store, $t() magic, and a language toggle (persisted)
- Add light/dark/system theme switching via a theme store and [data-theme] token overrides
- Set the theme before paint to avoid a flash of the wrong theme
- Add frontend version constant web/version.js (window.YDROPBX_VERSION) shown in the app footer
- Update AGENTS.md version-control convention to mention web/version.js
- Bump version to 0.1.1 across frontend, webui changelog, and backend constant
2026-08-27 15:21:21 +08:00
XingfenD d84e4dfdba feat(web): componentize frontend and replace native delete confirm
- Split monolithic app.js/style.css into Alpine.js components (icons, store, fileSection, confirm)
- Add central Alpine.store('files') as single source of truth for file lists and actions
- Replace duplicated Inbox/Outbox markup with reusable fileSection component (props: dir, canShare)
- Add shared window.Icons module to remove duplicated inline SVGs
- Replace browser-native confirm() for file deletion with a styled, accessible modal dialog
- Split CSS into design tokens, base, and component layers; modernize visuals
- Update web.go embed and server static routes for the new component/style dirs
2026-08-27 15:03:09 +08:00
XingfenD 110a8f7d9d Merge branch 'docs/initial-project-files' 2026-08-27 14:45:22 +08:00
XingfenD 4c96bf25be go mod tidy 2026-08-27 14:45:08 +08:00
XingfenD bdec081f8d docs: add project documentation files and version constant
Add AGENTS.md, docs/ (CHANGELOG, CHANGELOG_webui, README), and pkg/constant/version.go.
2026-08-27 14:44:29 +08:00
XingfenD cef31b9248 feat(web): redesign frontend UI with modern card layout, drag-drop upload, toast notifications, and responsive design 2026-08-27 00:04:03 +08:00
XingfenD 877e92cb24 chore: add Makefile 2026-08-27 00:01:03 +08:00
XingfenD 9de3b378da chore: add .gitignore 2026-08-26 23:51:57 +08:00
XingfenD d988d35881 fix: address branch review issues (json tags, share lockout, session expiry, file unlink) 2026-08-26 23:44:19 +08:00
XingfenD b7af194492 test: integration test 2026-08-26 23:40:17 +08:00
XingfenD f5a21d922d feat: assembly and main entry point 2026-08-26 23:38:13 +08:00
XingfenD c24df57882 feat: web frontend with Alpine.js 2026-08-26 23:36:27 +08:00
XingfenD c59654fcaa feat: route registration 2026-08-26 23:34:30 +08:00
XingfenD 7c10fdb50b feat: add share handlers with password protection and expiry 2026-08-26 23:31:58 +08:00
XingfenD 04d054afdc feat: file handlers (upload/list/download/delete) 2026-08-26 23:22:47 +08:00
XingfenD af6aba3d37 feat: auth handlers and session management 2026-08-26 23:16:08 +08:00
XingfenD 2852097b26 feat: scanner for directory reconciliation 2026-08-26 23:04:13 +08:00
XingfenD ee9eaf8817 feat: share CRUD with cascade delete 2026-08-26 21:49:26 +08:00
XingfenD 245497999e feat: store layer with file CRUD 2026-08-26 21:41:47 +08:00
XingfenD a547b69725 chore: project scaffolding 2026-08-26 21:39:31 +08:00
XingfenD 6c85b724d0 docs: yDropbox 实现计划 2026-08-26 21:34:44 +08:00
XingfenD bfcaf489ba docs: 项目结构调整 — 入口瘦身至 cmd/ydropbox,装配归 internal/app 2026-08-26 20:32:00 +08:00
48 changed files with 5232 additions and 3 deletions
+10
View File
@@ -0,0 +1,10 @@
.git
.gitignore
*.md
docs
tests
workspace
yDropbox
docker-compose.yml
.env
.env.example
+3
View File
@@ -0,0 +1,3 @@
# 访问令牌(必填)。请将下方示例替换为高强度随机字符串。
# Access token (required). Replace the example below with a strong random string.
YDROPBOX_TOKEN=change-me-to-a-strong-random-token
+26
View File
@@ -0,0 +1,26 @@
# Runtime data
workspace/
# Build output
yDropbox
ydropbox
# Go
*.out
coverage.html
# IDE
.idea/
.vscode/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Superpowers workspace
.superpowers/
# local env with secrets
.env
+8
View File
@@ -0,0 +1,8 @@
# AGENTS.md
## Safety Rules
- Dev branch naming: `{feat|fix|docs|chore}/{branch-name}` (e.g. `feat/file-tag-done`, `fix/tree-render`).
- Before `git commit`: run `git branch --show-current`. If on `master`, do NOT commit — ask user for a branch name (suggest one based on the changes, e.g. `docs/simplify-branch-workflow`), create it, commit there.
- General changes → `docs/CHANGELOG.md`; WebUI changes → `docs/CHANGELOG_webui.md` (files under `web/`). Higher versions on top.
ANGELOG entry format: same entry has English line then Chinese line on consecutive lines (no blank line between them); different entries are separated by a blank line.
- Version control: When bumping a version, update both the changelog and the corresponding version constant: `pkg/constant/version.go` for backend(docs/CHANGELOG.md), `web/version.js` for webui(docs/CHANGELOG_webui.md).
+19
View File
@@ -0,0 +1,19 @@
# syntax=docker/dockerfile:1
FROM golang:1.25-alpine AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/yDropbox ./cmd/ydropbox
FROM alpine:3.20
RUN adduser -D -u 10001 -s /sbin/nologin ydropbox \
&& apk add --no-cache ca-certificates tzdata
WORKDIR /app
COPY --from=build /out/yDropbox /app/yDropbox
USER ydropbox
VOLUME /app/workspace
EXPOSE 8999
ENTRYPOINT ["/app/yDropbox"]
CMD ["--addr", "0.0.0.0:8999", "--workspace", "/app/workspace"]
+28
View File
@@ -0,0 +1,28 @@
BINARY := yDropbox
PKG := ./cmd/ydropbox
.PHONY: build test run clean vet docker docker-up docker-down
build:
CGO_ENABLED=0 go build -o $(BINARY) $(PKG)
test:
go test ./...
run: build
./$(BINARY)
vet:
go vet ./...
clean:
rm -f $(BINARY)
docker:
docker build -t ydropbox .
docker-up:
docker compose up -d --build
docker-down:
docker compose down
+38
View File
@@ -0,0 +1,38 @@
package main
import (
"flag"
"log"
"os"
"path/filepath"
"yoresee_dropbox/internal/app"
)
func main() {
addr := flag.String("addr", "127.0.0.1:8999", "Listen address")
workspace := flag.String("workspace", "./workspace", "Workspace directory")
token := flag.String("token", "", "Access token")
flag.Parse()
if *token == "" {
*token = os.Getenv("YDROPBOX_TOKEN")
}
if *token == "" {
log.Fatal("Token required: --token or YDROPBOX_TOKEN env")
}
absWorkspace, _ := filepath.Abs(*workspace)
os.MkdirAll(filepath.Join(absWorkspace, "inbox"), 0755)
os.MkdirAll(filepath.Join(absWorkspace, "outbox"), 0755)
os.MkdirAll(filepath.Join(absWorkspace, ".ydropbox"), 0755)
cfg := app.Config{
Addr: *addr,
Workspace: absWorkspace,
Token: *token,
}
if err := app.Run(cfg); err != nil {
log.Fatal(err)
}
}
+15
View File
@@ -0,0 +1,15 @@
services:
ydropbox:
build: .
image: yoresee/yDropbox:latest
container_name: ydropbox
restart: unless-stopped
ports:
- "8999:8999"
environment:
YDROPBOX_TOKEN: ${YDROPBOX_TOKEN:?set YDROPBOX_TOKEN in .env}
volumes:
- ydropbox-data:/app/workspace
volumes:
ydropbox-data:
+47
View File
@@ -0,0 +1,47 @@
# Changelog / 更新日志
All notable changes to this template should be documented in this file.
本模板的重要变更建议统一记录在此文件中。
The format loosely follows Keep a Changelog and can be adapted to the team's habits.
本文档参考了 Keep a Changelog 的思路,也可以根据团队习惯调整。
## [0.1.0] - 2026-08-27
### Added / 新增
- Added Docker deployment support: `Dockerfile`, `.dockerignore`, `docker-compose.yml` and `.env.example`.
- 新增 Docker 部署支持:`Dockerfile`、`.dockerignore`、`docker-compose.yml` 与 `.env.example`。
- Added `make docker` / `make docker-up` / `make docker-down` convenience targets to the Makefile.
- 在 Makefile 中新增 `make docker` / `make docker-up` / `make docker-down` 便捷命令。
- Documented Docker deployment in `docs/README.md`.
- 在 `docs/README.md` 中补充了 Docker 部署说明。
## [0.0.1] - 2026-04-28
### Added / 新增
- Added an English project-template README in `docs/README.md`.
- 在 `docs/README.md` 中补充了英文版项目模板说明。
- Added a Chinese project-template README in `docs/README_zh.md`.
- 在 `docs/README_zh.md` 中补充了中文版项目模板说明。
- Added guidance for template users on how to rewrite the README for their own project.
- 增加了模板使用者如何把 README 改写为自己项目介绍的说明。
- Added a documented repository structure overview based on the current scaffold.
- 基于当前仓库骨架补充了目录结构说明。
- Added this changelog file for future template maintenance.
- 新增本更新日志文件,便于后续持续维护模板。
### Notes / 说明
- The repository currently provides structure and placeholder files rather than a finished implementation.
- 当前仓库主要提供目录结构和占位文件,尚不是一个已完成功能实现的成品项目。
- Future updates should record framework selection, startup steps, deployment workflow, and major documentation changes.
- 后续若补充了技术栈、启动流程、部署方式或重要文档内容,建议继续记录在本文件中。
+63
View File
@@ -0,0 +1,63 @@
# Changelog / 更新日志
All notable changes to this template should be documented in this file.
本模板的重要变更建议统一记录在此文件中。
The format loosely follows Keep a Changelog and can be adapted to the team's habits.
本文档参考了 Keep a Changelog 的思路,也可以根据团队习惯调整。
## [0.1.1] - 2026-08-27
### Added / 新增
- Added internationalization (i18n): English + 简体中文, with a `locale` store, a `$t()` magic, and a language toggle persisted to localStorage.
- 新增国际化(i18n):支持 English 与简体中文,包含 `locale` store、`$t()` 魔法函数,以及持久化到 localStorage 的语言切换按钮。
- Added light/dark/system theme switching via a `theme` store that writes `data-theme` on `<html>`; respects OS preference by default and persists the choice.
- 新增浅色/深色/跟随系统主题切换:通过 `theme` store 在 `<html>` 上写入 `data-theme`,默认跟随系统并持久化用户选择。
- Added dark-theme token overrides and a no-flash inline bootstrap script on both pages.
- 为深色模式补充了设计令牌覆盖,并在两个页面加入防止主题闪烁的内联初始化脚本。
- Added a frontend version constant (`web/version.js`, exposed as `window.YDROPBX_VERSION`) shown in the app footer, kept in sync with this changelog.
- 新增前端版本常量(`web/version.js`,暴露为 `window.YDROPBX_VERSION`)并显示在应用页脚,与本文档版本保持一致。
## [0.1.0] - 2026-08-27
### Changed / 变更
- Refactored the vanilla frontend into a component-based structure (Alpine.js components, a central state store, and a shared icon module) while keeping the no-build, Go-served static-file approach.
- 将原生前端重构为组件化结构(基于 Alpine.js 的组件、集中式状态 store、共享图标模块),同时保留由 Go 直接托管、无需构建的静态文件方案。
- Replaced the duplicated Inbox/Outbox markup with a single reusable `fileSection` component configured by props (`dir`, `canShare`).
- 用同一个可复用的 `fileSection` 组件(按属性 `dir`、`canShare` 配置)替换了原先重复的收件箱/发件箱标记。
- Split styles into design tokens, base, and component layers under `web/styles/`, and moved UI icons into a shared `window.Icons` module.
- 将样式拆分为 `web/styles/` 下的设计令牌、基础样式与组件样式三层,并把界面图标统一收敛到共享的 `window.Icons` 模块。
## [0.0.1] - 2026-04-28
### Added / 新增
- Added an English project-template README in `docs/README.md`.
- 在 `docs/README.md` 中补充了英文版项目模板说明。
- Added a Chinese project-template README in `docs/README_zh.md`.
- 在 `docs/README_zh.md` 中补充了中文版项目模板说明。
- Added guidance for template users on how to rewrite the README for their own project.
- 增加了模板使用者如何把 README 改写为自己项目介绍的说明。
- Added a documented repository structure overview based on the current scaffold.
- 基于当前仓库骨架补充了目录结构说明。
- Added this changelog file for future template maintenance.
- 新增本更新日志文件,便于后续持续维护模板。
### Notes / 说明
- The repository currently provides structure and placeholder files rather than a finished implementation.
- 当前仓库主要提供目录结构和占位文件,尚不是一个已完成功能实现的成品项目。
- Future updates should record framework selection, startup steps, deployment workflow, and major documentation changes.
- 后续若补充了技术栈、启动流程、部署方式或重要文档内容,建议继续记录在本文件中。
+132
View File
@@ -0,0 +1,132 @@
# yDropbox
yDropbox 是一个自托管的轻量级文件存储服务(灵感来自 Dropbox),使用 Go 编写,编译为单一静态二进制文件,零外部依赖。它提供一个 Web 界面用于上传、管理、下载文件,并支持通过受密码保护和可过期的分享链接将文件分享给他人。
## 特性
- **单一二进制文件**:使用 `modernc.org/sqlite`(纯 Go 实现的 SQLite),无需 CGO,无需外部数据库或运行时依赖。
- **工作区(Workspace)模型**:文件存储在工作区下的 `inbox/` 与 `outbox/` 两个目录中,文件元数据保存在 `.ydropbox/db.sqlite`。
- **磁盘扫描同步**:内置扫描器每 10 秒扫描工作区目录,将磁盘上的新增文件登记进数据库,并移除已被删除文件的元数据。这意味着你也可以直接把文件放进目录,它们会被自动纳入管理。
- **令牌认证**:服务端通过访问令牌(`--token` 或环境变量 `YDROPBOX_TOKEN`)保护,Web 端登录后使用 HttpOnly、Secure 的会话 Cookie。
- **分享链接**:可为任意文件生成公开分享链接,支持可选密码保护与过期时间。
- **基础防护**:登录与分享密码均带有失败次数限制(5 次失败后锁定 60 秒),分享密码使用 bcrypt 哈希存储。
- **现代 Web UI**:基于 Alpine.js 的前端,支持拖拽上传、Toast 提示与响应式布局。
## 构建与运行
### 前置要求
- Go 1.25+
### 构建
```bash
make build
```
该命令会生成名为 `yDropbox` 的静态二进制文件(关闭 CGO)。
### 运行
```bash
./yDropbox --addr 127.0.0.1:8999 --workspace ./workspace --token YOUR_SECRET_TOKEN
```
或使用环境变量提供令牌:
```bash
export YDROPBOX_TOKEN=YOUR_SECRET_TOKEN
./yDropbox --workspace ./workspace
```
启动时会自动创建 `workspace/inbox`、`workspace/outbox` 与 `workspace/.ydropbox` 目录。
### 其他命令
```bash
make test # 运行测试 (go test ./...)
make vet # 静态检查 (go vet ./...)
make clean # 删除二进制文件
```
## Docker 部署
项目提供了 `Dockerfile` 与 `docker-compose.yml`,将编译产物打包为单一镜像(前端资源已通过 `go:embed` 内嵌,SQLite 为纯 Go 实现,镜像无外部依赖)。
### 使用 Docker Compose(推荐)
```bash
cp .env.example .env
# 编辑 .env,设置 YDROPBOX_TOKEN 为一个高强度随机字符串
docker compose up -d --build
```
服务启动后监听 `8999` 端口,文件与数据库持久化在名为 `ydropbox-data` 的卷中。
### 仅使用 Docker
```bash
docker build -t ydropbox .
docker run -d --name ydropbox \
-p 8999:8999 \
-e YDROPBOX_TOKEN=YOUR_SECRET_TOKEN \
-v "$(pwd)/workspace:/app/workspace" \
ydropbox
```
> 注意:必须通过 `-e YDROPBOX_TOKEN=...` 或 `--token` 提供访问令牌,否则服务启动会失败(与本地运行一致)。
## 配置
| 参数 / 环境变量 | 说明 | 默认值 |
| ---------------------- | --------------------------------- | ---------------- |
| `--addr` | HTTP 监听地址 | `127.0.0.1:8999` |
| `--workspace` | 工作区目录(文件与数据库存放处) | `./workspace` |
| `--token` / `YDROPBOX_TOKEN` | 访问令牌(必填,用于登录校验) | 无(必须提供) |
## 使用
1. 在浏览器打开 `http://<addr>/`,使用启动时的令牌登录。
2. 在 `inbox` / `outbox` 面板中通过按钮或拖拽上传文件。
3. 点击下载 / 删除管理文件。
4. 点击分享生成链接;可在创建时设置密码与过期时间,链接形如 `/s/<token>`。
## HTTP API
所有受保护接口均需在请求中携带登录后获得的 `ydropbox_session` Cookie。
| 方法 | 路径 | 说明 |
| ------ | ------------------------------- | -------------------------------------- |
| POST | `/api/login` | 使用令牌登录(`{"token": "..."}`) |
| POST | `/api/logout` | 注销当前会话 |
| POST | `/api/upload` | 上传文件(`multipart/form-data` 字段 `file`) |
| GET | `/api/files?dir=inbox\|outbox` | 列出指定目录下的文件 |
| GET | `/api/files/{id}/download` | 下载指定文件 |
| DELETE | `/api/files/{id}` | 删除指定文件 |
| POST | `/api/files/{id}/share` | 创建分享链接(可选 `password`、`expires_in_hours`) |
| GET | `/api/shares` | 列出所有分享链接 |
| DELETE | `/api/shares/{id}` | 删除指定分享链接 |
| GET | `/s/{token}` | 访问分享链接(受密码保护时显示表单) |
| POST | `/s/{token}` | 提交分享链接密码 |
### 限制说明
- 单次上传文件大小上限为 **100 MiB**。
- 会话有效期为 7 天,登录失败 5 次后锁定 60 秒。
- 分享链接过期后再次访问会被自动删除。
## 项目结构
```
cmd/ydropbox/main.go # 程序入口、命令行参数解析
internal/app/ # 应用装配(数据库、扫描器、HTTP 服务)
internal/server/ # HTTP 路由、认证、文件与分享处理、中间件
internal/store/ # SQLite 存储层(文件与分享元数据)
internal/scanner/ # 工作区目录扫描与元数据同步
web/ # 前端静态资源(HTML/CSS/JS,Alpine.js)
tests/ # 集成测试
```
## 许可证
本项目仅供学习与自用部署场景,请自行负责数据安全与访问控制。
File diff suppressed because it is too large Load Diff
@@ -135,7 +135,7 @@ CREATE TABLE shares (
## 7. 部署
1. **构建**: `CGO_ENABLED=0 go build -o yDropbox .`,纯静态单文件。
1. **构建**: `CGO_ENABLED=0 go build -o yDropbox ./cmd/ydropbox`,纯静态单文件。
2. **运行**: systemd 服务,`ExecStart=/usr/local/bin/yDropbox listen --addr=127.0.0.1:8999`,`YDROPBOX_TOKEN` 经 systemd 环境或 credentials 注入;数据目录指向服务器上固定路径(如 `/var/lib/ydropbox/workspace`,`--workspace` 可配)。
3. **反代**: nginx 站点将 HTTPS 子域名反代至 `127.0.0.1:8999`,配置 `client_max_body_size 100m`,certbot 签发续期证书。
4. **DNS**: 子域名 A 记录指向反代服务器公网 IP(具体域名/IP 由部署时确定,不入仓库文档)。
@@ -144,15 +144,22 @@ CREATE TABLE shares (
```
yoresee_dropbox/
├── main.go # 入口: flag/env 解析、路由注册、启动 scanner
├── cmd/ydropbox/main.go # 入口: 仅 flag/env 解析 → app.Run(cfg)
├── go.mod / go.sum
├── internal/
│ ├── app/app.go # 装配: 开库、建路由(server.New)、起 scanner、监听
│ ├── server/
│ │ ├── server.go # New(): 路由注册
│ │ ├── auth.go # 登录/session/锁定
│ │ ├── files.go # 上传/列表/下载/删除
│ │ └── share.go # 分享创建/撤销/公开访问
│ ├── store/store.go # SQLite 层 (modernc.org/sqlite)
│ └── scanner/scanner.go # inbox+outbox 目录对账
├── web/ # go:embed:index.html, style.css, app.js, alpine.min.js(vendor)
├── web/
│ ├── web.go # //go:embed 挂载点,导出 FS
│ ├── index.html
│ ├── style.css
│ ├── app.js
│ └── alpine.min.js # vendor
└── workspace/ # 运行期生成(gitignore): inbox/, outbox/, .ydropbox/db.sqlite
```
+20
View File
@@ -0,0 +1,20 @@
module yoresee_dropbox
go 1.25.0
require (
golang.org/x/crypto v0.55.0
modernc.org/sqlite v1.57.0
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.47.0 // indirect
modernc.org/libc v1.74.4 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)
+52
View File
@@ -0,0 +1,52 @@
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k=
modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.57.0 h1:qNQP6xnx5M0ISNtlnxoOX0+cD5bJ0/gr9aMmndFczzg=
modernc.org/sqlite v1.57.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
+42
View File
@@ -0,0 +1,42 @@
package app
import (
"log"
"net/http"
"path/filepath"
"time"
"yoresee_dropbox/internal/scanner"
"yoresee_dropbox/internal/server"
"yoresee_dropbox/internal/store"
)
type Config struct {
Addr string
Workspace string
Token string
}
func NewHandler(cfg Config) (http.Handler, *store.Store, error) {
dbPath := filepath.Join(cfg.Workspace, ".ydropbox", "db.sqlite")
s, err := store.Open(dbPath)
if err != nil {
return nil, nil, err
}
sc := scanner.New(s, cfg.Workspace, 10*time.Second)
sc.Start()
srv := server.New(s, cfg.Token, cfg.Workspace)
return srv.Handler(), s, nil
}
func Run(cfg Config) error {
handler, s, err := NewHandler(cfg)
if err != nil {
return err
}
defer s.Close()
log.Printf("Listening on %s", cfg.Addr)
return http.ListenAndServe(cfg.Addr, handler)
}
+109
View File
@@ -0,0 +1,109 @@
package scanner
import (
"crypto/rand"
"encoding/hex"
"os"
"path/filepath"
"time"
"yoresee_dropbox/internal/store"
)
type Scanner struct {
store *store.Store
workspace string
interval time.Duration
stopCh chan struct{}
}
func New(s *store.Store, workspace string, interval time.Duration) *Scanner {
return &Scanner{
store: s,
workspace: workspace,
interval: interval,
stopCh: make(chan struct{}),
}
}
func (sc *Scanner) Start() {
go sc.run()
}
func (sc *Scanner) Stop() {
close(sc.stopCh)
}
func (sc *Scanner) run() {
ticker := time.NewTicker(sc.interval)
defer ticker.Stop()
sc.scan()
for {
select {
case <-sc.stopCh:
return
case <-ticker.C:
sc.scan()
}
}
}
func (sc *Scanner) scan() {
sc.scanDir("inbox")
sc.scanDir("outbox")
}
func (sc *Scanner) scanDir(dir string) {
dirPath := filepath.Join(sc.workspace, dir)
entries, err := os.ReadDir(dirPath)
if err != nil {
return
}
dbFiles, err := sc.store.FileList(dir)
if err != nil {
return
}
dbMap := make(map[string]*store.File)
for _, f := range dbFiles {
dbMap[f.StorageName] = f
}
diskMap := make(map[string]bool)
for _, entry := range entries {
if entry.IsDir() {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
diskMap[entry.Name()] = true
if _, exists := dbMap[entry.Name()]; !exists {
id := generateUUID()
f := &store.File{
ID: id,
OriginalName: entry.Name(),
StorageName: entry.Name(),
Dir: dir,
Size: info.Size(),
CreatedAt: time.Now().Unix(),
}
sc.store.FileCreate(f)
}
}
for name, f := range dbMap {
if !diskMap[name] {
sc.store.FileDelete(f.ID)
}
}
}
func generateUUID() string {
b := make([]byte, 16)
rand.Read(b)
return hex.EncodeToString(b)
}
+44
View File
@@ -0,0 +1,44 @@
package scanner
import (
"os"
"path/filepath"
"testing"
"time"
"yoresee_dropbox/internal/store"
)
func TestScannerReconciles(t *testing.T) {
dir := t.TempDir()
inbox := filepath.Join(dir, "inbox")
outbox := filepath.Join(dir, "outbox")
os.MkdirAll(inbox, 0755)
os.MkdirAll(outbox, 0755)
dbPath := filepath.Join(dir, "test.db")
s, err := store.Open(dbPath)
if err != nil {
t.Fatal(err)
}
defer s.Close()
// Create a file on disk
testFile := filepath.Join(inbox, "test.txt")
os.WriteFile(testFile, []byte("hello"), 0644)
sc := New(s, dir, 100*time.Millisecond)
sc.Start()
time.Sleep(300 * time.Millisecond)
sc.Stop()
files, err := s.FileList("inbox")
if err != nil {
t.Fatal(err)
}
if len(files) != 1 {
t.Errorf("Expected 1 file, got %d", len(files))
}
if files[0].OriginalName != "test.txt" {
t.Errorf("OriginalName = %q, want %q", files[0].OriginalName, "test.txt")
}
}
+94
View File
@@ -0,0 +1,94 @@
package server
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"time"
)
type loginRequest struct {
Token string `json:"token"`
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
s.mu.Lock()
if lockTime, locked := s.loginLockout[ip]; locked && time.Now().Before(lockTime) {
s.mu.Unlock()
http.Error(w, "Too many attempts, locked for 60s", http.StatusForbidden)
return
}
s.mu.Unlock()
var req loginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
if req.Token != s.accessToken {
s.mu.Lock()
s.loginAttempts[ip]++
if s.loginAttempts[ip] >= 5 {
s.loginLockout[ip] = time.Now().Add(60 * time.Second)
s.loginAttempts[ip] = 0
}
s.mu.Unlock()
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
s.mu.Lock()
delete(s.loginAttempts, ip)
delete(s.loginLockout, ip)
s.mu.Unlock()
sessionID := generateSessionID()
s.mu.Lock()
s.sessions[sessionID] = time.Now().Unix()
s.mu.Unlock()
http.SetCookie(w, &http.Cookie{
Name: "ydropbox_session",
Value: sessionID,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: true,
MaxAge: 7 * 24 * 60 * 60,
})
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{})
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("ydropbox_session")
if err != nil {
http.Error(w, "Not logged in", http.StatusUnauthorized)
return
}
s.mu.Lock()
delete(s.sessions, cookie.Value)
s.mu.Unlock()
http.SetCookie(w, &http.Cookie{
Name: "ydropbox_session",
Value: "",
Path: "/",
MaxAge: -1,
})
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{})
}
func generateSessionID() string {
b := make([]byte, 32)
rand.Read(b)
return hex.EncodeToString(b)
}
+50
View File
@@ -0,0 +1,50 @@
package server
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestLoginSuccess(t *testing.T) {
s := &Server{
accessToken: "secret123",
sessions: make(map[string]int64),
loginAttempts: make(map[string]int),
loginLockout: make(map[string]time.Time),
}
req := httptest.NewRequest("POST", "/api/login", bytes.NewBufferString(`{"token":"secret123"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
s.handleLogin(w, req)
if w.Code != http.StatusOK {
t.Errorf("Status = %d, want %d", w.Code, http.StatusOK)
}
if len(w.Header().Values("Set-Cookie")) == 0 {
t.Error("Expected Set-Cookie header")
}
}
func TestLoginFailure(t *testing.T) {
s := &Server{
accessToken: "secret123",
sessions: make(map[string]int64),
loginAttempts: make(map[string]int),
loginLockout: make(map[string]time.Time),
}
req := httptest.NewRequest("POST", "/api/login", bytes.NewBufferString(`{"token":"wrong"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
s.handleLogin(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("Status = %d, want %d", w.Code, http.StatusUnauthorized)
}
}
+94
View File
@@ -0,0 +1,94 @@
package server
import (
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"time"
"yoresee_dropbox/internal/store"
)
func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 100<<20)
if err := r.ParseMultipartForm(32 << 20); err != nil {
http.Error(w, "File too large", http.StatusRequestEntityTooLarge)
return
}
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "Missing file", http.StatusBadRequest)
return
}
defer file.Close()
storageName := generateUUID()
destPath := filepath.Join(s.workspace, "inbox", storageName)
dest, err := os.Create(destPath)
if err != nil {
http.Error(w, "Failed to save", http.StatusInternalServerError)
return
}
defer dest.Close()
if _, err := io.Copy(dest, file); err != nil {
http.Error(w, "Failed to save", http.StatusInternalServerError)
return
}
f := &store.File{
ID: generateUUID(),
OriginalName: header.Filename,
StorageName: storageName,
Dir: "inbox",
Size: header.Size,
CreatedAt: time.Now().Unix(),
}
if err := s.store.FileCreate(f); err != nil {
http.Error(w, "Failed to save metadata", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"file": f})
}
func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) {
dir := r.URL.Query().Get("dir")
files, err := s.store.FileList(dir)
if err != nil {
http.Error(w, "Failed to list", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]any{"files": files})
}
func (s *Server) handleDownload(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
f, err := s.store.FileGet(id)
if err != nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
path := filepath.Join(s.workspace, f.Dir, f.StorageName)
w.Header().Set("Content-Disposition", "attachment; filename="+f.OriginalName)
http.ServeFile(w, r, path)
}
func (s *Server) handleDeleteFile(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
f, err := s.store.FileGet(id)
if err != nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
if err := s.store.FileDelete(id); err != nil {
http.Error(w, "Failed to delete", http.StatusInternalServerError)
return
}
os.Remove(filepath.Join(s.workspace, f.Dir, f.StorageName))
w.WriteHeader(http.StatusNoContent)
}
+41
View File
@@ -0,0 +1,41 @@
package server
import (
"bytes"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"yoresee_dropbox/internal/store"
)
func TestUpload(t *testing.T) {
dir := t.TempDir()
workspace := filepath.Join(dir, "workspace")
os.MkdirAll(filepath.Join(workspace, "inbox"), 0755)
s, _ := store.Open(filepath.Join(dir, "test.db"))
defer s.Close()
srv := &Server{store: s, accessToken: "token", sessions: make(map[string]int64), workspace: workspace}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", "test.txt")
part.Write([]byte("hello"))
writer.Close()
req := httptest.NewRequest("POST", "/api/upload", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.AddCookie(&http.Cookie{Name: "ydropbox_session", Value: "valid"})
srv.sessions["valid"] = 1
w := httptest.NewRecorder()
srv.handleUpload(w, req)
if w.Code != http.StatusCreated {
t.Errorf("Status = %d, want %d", w.Code, http.StatusCreated)
}
}
+64
View File
@@ -0,0 +1,64 @@
package server
import (
"net/http"
"time"
)
const sessionMaxAge = 7 * 86400
func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("ydropbox_session")
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
s.mu.Lock()
createdAt, exists := s.sessions[cookie.Value]
if exists && time.Now().Unix()-createdAt > sessionMaxAge {
delete(s.sessions, cookie.Value)
exists = false
}
if exists {
s.sessions[cookie.Value] = time.Now().Unix()
}
s.mu.Unlock()
if !exists {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next(w, r)
}
}
func (s *Server) requireAuthPage(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("ydropbox_session")
if err != nil {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
s.mu.Lock()
createdAt, exists := s.sessions[cookie.Value]
if exists && time.Now().Unix()-createdAt > sessionMaxAge {
delete(s.sessions, cookie.Value)
exists = false
}
if exists {
s.sessions[cookie.Value] = time.Now().Unix()
}
s.mu.Unlock()
if !exists {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
next(w, r)
}
}
+79
View File
@@ -0,0 +1,79 @@
package server
import (
"crypto/rand"
"encoding/hex"
"net/http"
"sync"
"time"
"yoresee_dropbox/internal/store"
"yoresee_dropbox/web"
)
type Server struct {
store *store.Store
accessToken string
sessions map[string]int64
shareSessions map[string]string
loginAttempts map[string]int
loginLockout map[string]time.Time
shareAttempts map[string]int
shareLockout map[string]time.Time
mu sync.Mutex
workspace string
}
func New(store *store.Store, accessToken string, workspace string) *Server {
return &Server{
store: store,
accessToken: accessToken,
sessions: make(map[string]int64),
shareSessions: make(map[string]string),
loginAttempts: make(map[string]int),
loginLockout: make(map[string]time.Time),
shareAttempts: make(map[string]int),
shareLockout: make(map[string]time.Time),
workspace: workspace,
}
}
func generateUUID() string {
b := make([]byte, 16)
rand.Read(b)
return hex.EncodeToString(b)
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /api/login", s.handleLogin)
mux.HandleFunc("POST /api/logout", s.requireAuth(s.handleLogout))
mux.HandleFunc("POST /api/upload", s.requireAuth(s.handleUpload))
mux.HandleFunc("GET /api/files", s.requireAuth(s.handleListFiles))
mux.HandleFunc("GET /api/files/{id}/download", s.requireAuth(s.handleDownload))
mux.HandleFunc("DELETE /api/files/{id}", s.requireAuth(s.handleDeleteFile))
mux.HandleFunc("POST /api/files/{id}/share", s.requireAuth(s.handleCreateShare))
mux.HandleFunc("GET /api/shares", s.requireAuth(s.handleListShares))
mux.HandleFunc("DELETE /api/shares/{id}", s.requireAuth(s.handleDeleteShare))
mux.HandleFunc("GET /s/{token}", s.handleShareAccess)
mux.HandleFunc("POST /s/{token}", s.handleSharePassword)
mux.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) {
data, _ := web.FS.ReadFile("login.html")
w.Write(data)
})
mux.HandleFunc("GET /{$}", s.requireAuthPage(func(w http.ResponseWriter, r *http.Request) {
data, _ := web.FS.ReadFile("index.html")
w.Write(data)
}))
static := http.FileServerFS(web.FS)
mux.Handle("GET /components/", static)
mux.Handle("GET /styles/", static)
mux.Handle("GET /version.js", static)
mux.Handle("GET /alpine.min.js", static)
return mux
}
+183
View File
@@ -0,0 +1,183 @@
package server
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"net/http"
"path/filepath"
"time"
"golang.org/x/crypto/bcrypt"
"yoresee_dropbox/internal/store"
)
type createShareRequest struct {
Password string `json:"password"`
ExpiresInHours int `json:"expires_in_hours"`
}
func (s *Server) handleCreateShare(w http.ResponseWriter, r *http.Request) {
fileID := r.PathValue("id")
var req createShareRequest
json.NewDecoder(r.Body).Decode(&req)
token := generateShareToken()
share := &store.Share{
ID: generateUUID(),
FileID: fileID,
Token: token,
CreatedAt: time.Now().Unix(),
}
if req.Password != "" {
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), 10)
if err != nil {
http.Error(w, "Failed to hash password", http.StatusInternalServerError)
return
}
share.PasswordHash = string(hash)
}
if req.ExpiresInHours > 0 {
share.ExpiresAt = time.Now().Add(time.Duration(req.ExpiresInHours) * time.Hour).Unix()
}
if err := s.store.ShareCreate(share); err != nil {
http.Error(w, "Failed to create share", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{
"url": "/s/" + token,
"token": token,
})
}
func (s *Server) handleListShares(w http.ResponseWriter, r *http.Request) {
shares, err := s.store.ShareList()
if err != nil {
http.Error(w, "Failed to list", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]any{"shares": shares})
}
func (s *Server) handleDeleteShare(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if err := s.store.ShareDelete(id); err != nil {
http.Error(w, "Failed to delete", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleShareAccess(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
share, err := s.store.ShareGetByToken(token)
if err != nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
if share.ExpiresAt > 0 && time.Now().Unix() > share.ExpiresAt {
s.store.ShareDelete(share.ID)
http.Error(w, "Share expired", http.StatusGone)
return
}
if share.PasswordHash != "" {
cookie, err := r.Cookie("ydropbox_share_" + share.ID)
if err != nil || !s.verifyShareCookie(share.ID, cookie.Value) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`<!DOCTYPE html><html><body>
<form method="POST"><input type="password" name="password"><button>Submit</button></form>
</body></html>`))
return
}
}
s.serveSharedFile(w, r, share)
}
func (s *Server) handleSharePassword(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
share, err := s.store.ShareGetByToken(token)
if err != nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
key := share.ID
s.mu.Lock()
if lockTime, locked := s.shareLockout[key]; locked && time.Now().Before(lockTime) {
s.mu.Unlock()
http.Error(w, "Too many attempts, locked for 60s", http.StatusForbidden)
return
}
s.mu.Unlock()
time.Sleep(500 * time.Millisecond)
password := r.FormValue("password")
if err := bcrypt.CompareHashAndPassword([]byte(share.PasswordHash), []byte(password)); err != nil {
s.mu.Lock()
s.shareAttempts[key]++
if s.shareAttempts[key] >= 5 {
s.shareLockout[key] = time.Now().Add(60 * time.Second)
s.shareAttempts[key] = 0
}
s.mu.Unlock()
http.Error(w, "Wrong password", http.StatusForbidden)
return
}
s.mu.Lock()
delete(s.shareAttempts, key)
delete(s.shareLockout, key)
s.mu.Unlock()
cookieVal := generateSessionID()
s.mu.Lock()
if s.shareSessions == nil {
s.shareSessions = make(map[string]string)
}
s.shareSessions[cookieVal] = share.ID
s.mu.Unlock()
http.SetCookie(w, &http.Cookie{
Name: "ydropbox_share_" + share.ID,
Value: cookieVal,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
MaxAge: 3600,
})
http.Redirect(w, r, "/s/"+token, http.StatusFound)
}
func (s *Server) serveSharedFile(w http.ResponseWriter, r *http.Request, share *store.Share) {
f, err := s.store.FileGet(share.FileID)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
path := filepath.Join(s.workspace, f.Dir, f.StorageName)
w.Header().Set("Content-Disposition", "attachment; filename="+f.OriginalName)
w.Header().Set("X-Content-Type-Options", "nosniff")
http.ServeFile(w, r, path)
}
func (s *Server) verifyShareCookie(shareID, cookieVal string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.shareSessions[cookieVal] == shareID
}
func generateShareToken() string {
b := make([]byte, 24)
rand.Read(b)
return base64.URLEncoding.EncodeToString(b)
}
+100
View File
@@ -0,0 +1,100 @@
package server
import (
"bytes"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"yoresee_dropbox/internal/store"
)
func TestCreateShare(t *testing.T) {
dir := t.TempDir()
workspace := filepath.Join(dir, "workspace")
os.MkdirAll(filepath.Join(workspace, "inbox"), 0755)
s, _ := store.Open(filepath.Join(dir, "test.db"))
defer s.Close()
f := &store.File{ID: "file-1", OriginalName: "doc.pdf", StorageName: "uuid-1", Dir: "inbox", Size: 100, CreatedAt: 1750000000}
s.FileCreate(f)
srv := &Server{store: s, workspace: workspace, sessions: make(map[string]int64), shareSessions: make(map[string]string)}
body := bytes.NewBufferString(`{"file_id":"file-1"}`)
req := httptest.NewRequest("POST", "/api/files/file-1/share", body)
req.Header.Set("Content-Type", "application/json")
req.AddCookie(&http.Cookie{Name: "ydropbox_session", Value: "valid"})
srv.sessions["valid"] = 1
mux := http.NewServeMux()
mux.HandleFunc("POST /api/files/{id}/share", srv.handleCreateShare)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Errorf("Status = %d, want %d", w.Code, http.StatusCreated)
}
}
func TestShareAccessNoPassword(t *testing.T) {
dir := t.TempDir()
workspace := filepath.Join(dir, "workspace")
os.MkdirAll(filepath.Join(workspace, "inbox"), 0755)
os.WriteFile(filepath.Join(workspace, "inbox", "uuid-1"), []byte("content"), 0644)
s, _ := store.Open(filepath.Join(dir, "test.db"))
defer s.Close()
f := &store.File{ID: "file-1", OriginalName: "doc.pdf", StorageName: "uuid-1", Dir: "inbox", Size: 7, CreatedAt: 1750000000}
s.FileCreate(f)
sh := &store.Share{ID: "share-1", FileID: "file-1", Token: "tok-abc", CreatedAt: 1750000000}
s.ShareCreate(sh)
srv := &Server{store: s, workspace: workspace, sessions: make(map[string]int64), shareSessions: make(map[string]string)}
req := httptest.NewRequest("GET", "/s/tok-abc", nil)
mux := http.NewServeMux()
mux.HandleFunc("GET /s/{token}", srv.handleShareAccess)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Status = %d, want %d", w.Code, http.StatusOK)
}
}
func TestShareAccessExpired(t *testing.T) {
dir := t.TempDir()
workspace := filepath.Join(dir, "workspace")
os.MkdirAll(filepath.Join(workspace, "inbox"), 0755)
s, _ := store.Open(filepath.Join(dir, "test.db"))
defer s.Close()
f := &store.File{ID: "file-1", OriginalName: "doc.pdf", StorageName: "uuid-1", Dir: "inbox", Size: 7, CreatedAt: 1750000000}
s.FileCreate(f)
sh := &store.Share{ID: "share-1", FileID: "file-1", Token: "tok-exp", ExpiresAt: 1, CreatedAt: 1750000000}
s.ShareCreate(sh)
srv := &Server{store: s, workspace: workspace, sessions: make(map[string]int64), shareSessions: make(map[string]string)}
req := httptest.NewRequest("GET", "/s/tok-exp", nil)
mux := http.NewServeMux()
mux.HandleFunc("GET /s/{token}", srv.handleShareAccess)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != http.StatusGone {
t.Errorf("Status = %d, want %d", w.Code, http.StatusGone)
}
}
+71
View File
@@ -0,0 +1,71 @@
package store
import "database/sql"
type File struct {
ID string `json:"id"`
OriginalName string `json:"name"`
StorageName string `json:"-"`
Dir string `json:"dir"`
Size int64 `json:"size"`
CreatedAt int64 `json:"created_at"`
}
func (s *Store) FileCreate(f *File) error {
_, err := s.db.Exec(
`INSERT INTO files (id, original_name, storage_name, dir, size, created_at)
VALUES (?, ?, ?, ?, ?, ?)`,
f.ID, f.OriginalName, f.StorageName, f.Dir, f.Size, f.CreatedAt,
)
return err
}
func (s *Store) FileGet(id string) (*File, error) {
row := s.db.QueryRow(
`SELECT id, original_name, storage_name, dir, size, created_at
FROM files WHERE id = ?`, id,
)
return scanFile(row)
}
func (s *Store) FileList(dir string) ([]*File, error) {
query := `SELECT id, original_name, storage_name, dir, size, created_at FROM files`
var args []any
if dir != "" {
query += ` WHERE dir = ?`
args = []any{dir}
}
query += ` ORDER BY created_at DESC`
rows, err := s.db.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var files []*File
for rows.Next() {
f, err := scanFile(rows)
if err != nil {
return nil, err
}
files = append(files, f)
}
return files, rows.Err()
}
func (s *Store) FileDelete(id string) error {
_, err := s.db.Exec(`DELETE FROM files WHERE id = ?`, id)
return err
}
func scanFile(row interface {
Scan(dest ...any) error
}) (*File, error) {
f := &File{}
err := row.Scan(&f.ID, &f.OriginalName, &f.StorageName, &f.Dir, &f.Size, &f.CreatedAt)
if err == sql.ErrNoRows {
return nil, err
}
return f, err
}
+36
View File
@@ -0,0 +1,36 @@
package store
import (
"path/filepath"
"testing"
)
func TestFileCreate(t *testing.T) {
dir := t.TempDir()
s, err := Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
f := &File{
ID: "test-id",
OriginalName: "test.pdf",
StorageName: "storage-uuid",
Dir: "inbox",
Size: 1024,
CreatedAt: 1750000000,
}
if err := s.FileCreate(f); err != nil {
t.Fatalf("FileCreate failed: %v", err)
}
got, err := s.FileGet("test-id")
if err != nil {
t.Fatalf("FileGet failed: %v", err)
}
if got.OriginalName != "test.pdf" {
t.Errorf("OriginalName = %q, want %q", got.OriginalName, "test.pdf")
}
}
+67
View File
@@ -0,0 +1,67 @@
package store
import "database/sql"
type Share struct {
ID string
FileID string
Token string
PasswordHash string
ExpiresAt int64
CreatedAt int64
LastAccessedAt int64
}
func (s *Store) ShareCreate(sh *Share) error {
_, err := s.db.Exec(
`INSERT INTO shares (id, file_id, token, password_hash, expires_at, created_at, last_accessed_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
sh.ID, sh.FileID, sh.Token, sh.PasswordHash, sh.ExpiresAt, sh.CreatedAt, sh.LastAccessedAt,
)
return err
}
func (s *Store) ShareGetByToken(token string) (*Share, error) {
row := s.db.QueryRow(
`SELECT id, file_id, token, password_hash, expires_at, created_at, last_accessed_at
FROM shares WHERE token = ?`, token,
)
return scanShare(row)
}
func (s *Store) ShareList() ([]*Share, error) {
rows, err := s.db.Query(
`SELECT id, file_id, token, password_hash, expires_at, created_at, last_accessed_at
FROM shares ORDER BY created_at DESC`,
)
if err != nil {
return nil, err
}
defer rows.Close()
var shares []*Share
for rows.Next() {
sh, err := scanShare(rows)
if err != nil {
return nil, err
}
shares = append(shares, sh)
}
return shares, rows.Err()
}
func (s *Store) ShareDelete(id string) error {
_, err := s.db.Exec(`DELETE FROM shares WHERE id = ?`, id)
return err
}
func scanShare(row interface {
Scan(dest ...any) error
}) (*Share, error) {
sh := &Share{}
err := row.Scan(&sh.ID, &sh.FileID, &sh.Token, &sh.PasswordHash, &sh.ExpiresAt, &sh.CreatedAt, &sh.LastAccessedAt)
if err == sql.ErrNoRows {
return nil, err
}
return sh, err
}
+70
View File
@@ -0,0 +1,70 @@
package store
import (
"path/filepath"
"testing"
)
func TestShareCreate(t *testing.T) {
dir := t.TempDir()
s, err := Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
f := &File{
ID: "file-1",
OriginalName: "doc.pdf",
StorageName: "uuid-1",
Dir: "inbox",
Size: 2048,
CreatedAt: 1750000000,
}
if err := s.FileCreate(f); err != nil {
t.Fatal(err)
}
share := &Share{
ID: "share-1",
FileID: "file-1",
Token: "token-abc",
CreatedAt: 1750000000,
}
if err := s.ShareCreate(share); err != nil {
t.Fatalf("ShareCreate failed: %v", err)
}
got, err := s.ShareGetByToken("token-abc")
if err != nil {
t.Fatalf("ShareGetByToken failed: %v", err)
}
if got.FileID != "file-1" {
t.Errorf("FileID = %q, want %q", got.FileID, "file-1")
}
}
func TestFileDeleteCascadesShares(t *testing.T) {
dir := t.TempDir()
s, err := Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
f := &File{ID: "file-2", OriginalName: "x.pdf", StorageName: "uuid-2", Dir: "inbox", Size: 100, CreatedAt: 1750000000}
s.FileCreate(f)
sh := &Share{ID: "share-2", FileID: "file-2", Token: "tok-2", CreatedAt: 1750000000}
s.ShareCreate(sh)
if err := s.FileDelete("file-2"); err != nil {
t.Fatal(err)
}
_, err = s.ShareGetByToken("tok-2")
if err == nil {
t.Error("Share should be deleted after file deletion")
}
}
+58
View File
@@ -0,0 +1,58 @@
package store
import (
"database/sql"
_ "modernc.org/sqlite"
)
type Store struct {
db *sql.DB
}
func Open(dbPath string) (*Store, error) {
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return nil, err
}
if _, err := db.Exec("PRAGMA foreign_keys = ON"); err != nil {
db.Close()
return nil, err
}
if err := migrate(db); err != nil {
db.Close()
return nil, err
}
return &Store{db: db}, nil
}
func (s *Store) Close() error {
return s.db.Close()
}
func migrate(db *sql.DB) error {
schema := `
CREATE TABLE IF NOT EXISTS files (
id TEXT PRIMARY KEY,
original_name TEXT NOT NULL,
storage_name TEXT NOT NULL UNIQUE,
dir TEXT NOT NULL CHECK (dir IN ('inbox','outbox')),
size INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS shares (
id TEXT PRIMARY KEY,
file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE,
token TEXT NOT NULL UNIQUE,
password_hash TEXT,
expires_at INTEGER,
created_at INTEGER NOT NULL,
last_accessed_at INTEGER
);
`
_, err := db.Exec(schema)
return err
}
+22
View File
@@ -0,0 +1,22 @@
package store
import (
"os"
"path/filepath"
"testing"
)
func TestOpen(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db")
s, err := Open(dbPath)
if err != nil {
t.Fatalf("Open failed: %v", err)
}
defer s.Close()
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
t.Error("Database file not created")
}
}
+3
View File
@@ -0,0 +1,3 @@
package constant
const Version = "0.1.0"
+108
View File
@@ -0,0 +1,108 @@
package tests
import (
"bytes"
"encoding/json"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"yoresee_dropbox/internal/app"
)
func TestIntegration(t *testing.T) {
dir := t.TempDir()
workspace := filepath.Join(dir, "workspace")
os.MkdirAll(filepath.Join(workspace, "inbox"), 0755)
os.MkdirAll(filepath.Join(workspace, "outbox"), 0755)
os.MkdirAll(filepath.Join(workspace, ".ydropbox"), 0755)
cfg := app.Config{
Workspace: workspace,
Token: "test-token",
}
handler, store, err := app.NewHandler(cfg)
if err != nil {
t.Fatal(err)
}
defer store.Close()
ts := httptest.NewServer(handler)
defer ts.Close()
client := ts.Client()
loginBody := bytes.NewBufferString(`{"token":"test-token"}`)
loginRes, err := client.Post(ts.URL+"/api/login", "application/json", loginBody)
if err != nil || loginRes.StatusCode != 200 {
t.Fatalf("Login failed: %v, status: %d", err, loginRes.StatusCode)
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", "test.txt")
part.Write([]byte("hello world"))
writer.Close()
uploadReq, _ := http.NewRequest("POST", ts.URL+"/api/upload", body)
uploadReq.Header.Set("Content-Type", writer.FormDataContentType())
for _, cookie := range loginRes.Cookies() {
uploadReq.AddCookie(cookie)
}
uploadRes, err := client.Do(uploadReq)
if err != nil || uploadRes.StatusCode != 201 {
t.Fatalf("Upload failed: %v, status: %d", err, uploadRes.StatusCode)
}
var uploadResp map[string]any
json.NewDecoder(uploadRes.Body).Decode(&uploadResp)
file := uploadResp["file"].(map[string]any)
fileID := file["id"].(string)
listReq, _ := http.NewRequest("GET", ts.URL+"/api/files?dir=inbox", nil)
for _, cookie := range loginRes.Cookies() {
listReq.AddCookie(cookie)
}
listRes, err := client.Do(listReq)
if err != nil || listRes.StatusCode != 200 {
t.Fatalf("List failed: %v, status: %d", err, listRes.StatusCode)
}
var listResp map[string]any
json.NewDecoder(listRes.Body).Decode(&listResp)
files := listResp["files"].([]any)
if len(files) != 1 {
t.Errorf("Expected 1 file, got %d", len(files))
}
dlReq, _ := http.NewRequest("GET", ts.URL+"/api/files/"+fileID+"/download", nil)
for _, cookie := range loginRes.Cookies() {
dlReq.AddCookie(cookie)
}
dlRes, err := client.Do(dlReq)
if err != nil || dlRes.StatusCode != 200 {
t.Fatalf("Download failed: %v, status: %d", err, dlRes.StatusCode)
}
shareReq, _ := http.NewRequest("POST", ts.URL+"/api/files/"+fileID+"/share", bytes.NewBufferString(`{}`))
shareReq.Header.Set("Content-Type", "application/json")
for _, cookie := range loginRes.Cookies() {
shareReq.AddCookie(cookie)
}
shareRes, err := client.Do(shareReq)
if err != nil || shareRes.StatusCode != 201 {
t.Fatalf("Share create failed: %v, status: %d", err, shareRes.StatusCode)
}
var shareResp map[string]any
json.NewDecoder(shareRes.Body).Decode(&shareResp)
shareURL := shareResp["url"].(string)
pubRes, err := client.Get(ts.URL + shareURL)
if err != nil || pubRes.StatusCode != 200 {
t.Fatalf("Public share access failed: %v, status: %d", err, pubRes.StatusCode)
}
}
+5
View File
File diff suppressed because one or more lines are too long
+85
View File
@@ -0,0 +1,85 @@
/**
* Confirmation dialog (a promise-based modal store + UI component).
*
* Replaces the browser-native `confirm()` with a styled, accessible modal.
* Components request confirmation via `Alpine.store('confirm').show(opts)`,
* which resolves `true`/`false` when the user acts — mirroring a UI-library
* dialog API.
*/
(function () {
function register() {
Alpine.store('confirm', {
open: false,
title: '',
message: '',
danger: false,
_resolve: null,
show(opts) {
this.title = opts.title || 'Confirm';
this.message = opts.message || '';
this.danger = opts.danger || false;
this.open = true;
return new Promise((resolve) => {
this._resolve = resolve;
});
},
accept() {
this._close(true);
},
cancel() {
this._close(false);
},
_close(result) {
this.open = false;
const resolve = this._resolve;
this._resolve = null;
if (resolve) resolve(result);
},
});
Alpine.data('confirmDialog', () => ({
get store() {
return Alpine.store('confirm');
},
get open() {
return this.store.open;
},
get title() {
return this.store.title;
},
get message() {
return this.store.message;
},
get danger() {
return this.store.danger;
},
accept() {
this.store.accept();
},
cancel() {
this.store.cancel();
},
onEscape() {
if (this.open) this.cancel();
},
init() {
this.$watch('open', (visible) => {
if (visible) {
this.$nextTick(() => {
if (this.$refs.accept) this.$refs.accept.focus();
});
}
});
},
}));
}
if (window.Alpine) register();
else document.addEventListener('alpine:init', register);
})();
+44
View File
@@ -0,0 +1,44 @@
/**
* fileSection component.
*
* A single reusable component parametrized by `dir` and `canShare`. Both the
* Inbox and Outbox on the page are the same component instance with different
* props, replacing the previously copy-pasted <section> blocks.
*
* Usage:
* <section x-data="fileSection('inbox', { canShare: true })"> ... </section>
*/
(function () {
function register() {
Alpine.data('fileSection', (dir, opts = {}) => ({
dir,
canShare: opts.canShare ?? false,
dragover: false,
get files() {
return Alpine.store('files').files[dir];
},
get count() {
return this.files.length;
},
get title() {
return Alpine.store('locale').t(dir === 'inbox' ? 'inbox' : 'outbox');
},
get icon() {
return dir === 'inbox' ? window.Icons.inbox : window.Icons.outbox;
},
async onSelect(e) {
await Alpine.store('files').upload(this.dir, e.target.files);
e.target.value = '';
},
async onDrop(e) {
await Alpine.store('files').upload(this.dir, e.dataTransfer.files);
},
}));
}
if (window.Alpine) register();
else document.addEventListener('alpine:init', register);
})();
+120
View File
@@ -0,0 +1,120 @@
/**
* Internationalization (i18n).
*
* - `window.I18n` holds the message catalogs (currently English + 简体中文).
* - The `locale` store owns the active language, persists it to localStorage,
* and exposes `t(key)`.
* - `$t('key')` is registered as an Alpine magic so templates can translate
* inline (e.g. `x-text="$t('nav.logout')"`).
*
* Because `t()` reads the reactive `lang`, any string bound through it updates
* automatically when the language changes.
*/
window.I18n = {
en: {
'app.name': 'yDropbox',
'nav.logout': 'Logout',
'inbox': 'Inbox',
'outbox': 'Outbox',
'dropzone.click': 'Click to upload',
'dropzone.rest': 'or drag and drop',
'empty.inbox': 'No files in inbox',
'empty.outbox': 'No files in outbox',
'action.download': 'Download',
'action.share': 'Share',
'action.delete': 'Delete',
'toast.uploaded': 'File uploaded',
'toast.deleted': 'File deleted',
'toast.loadFailed': 'Failed to load files',
'toast.shareCopied': 'Share link copied to clipboard',
'confirm.deleteTitle': 'Delete file',
'confirm.deleteMessage': 'This file will be permanently removed. Continue?',
'confirm.cancel': 'Cancel',
'confirm.delete': 'Delete',
'confirm.confirm': 'Confirm',
'theme.light': 'Light',
'theme.dark': 'Dark',
'theme.system': 'System',
'lang.label': 'Language',
'login.subtitle': 'Enter your access token to continue',
'login.token': 'Access Token',
'login.submit': 'Sign In',
'login.error': 'Invalid token. Please try again.',
},
zh: {
'app.name': 'yDropbox',
'nav.logout': '退出登录',
'inbox': '收件箱',
'outbox': '发件箱',
'dropzone.click': '点击上传',
'dropzone.rest': '或拖拽文件到此处',
'empty.inbox': '收件箱暂无文件',
'empty.outbox': '发件箱暂无文件',
'action.download': '下载',
'action.share': '分享',
'action.delete': '删除',
'toast.uploaded': '文件已上传',
'toast.deleted': '文件已删除',
'toast.loadFailed': '文件加载失败',
'toast.shareCopied': '分享链接已复制到剪贴板',
'confirm.deleteTitle': '删除文件',
'confirm.deleteMessage': '该文件将被永久删除,是否继续?',
'confirm.cancel': '取消',
'confirm.delete': '删除',
'confirm.confirm': '确认',
'theme.light': '浅色',
'theme.dark': '深色',
'theme.system': '跟随系统',
'lang.label': '语言',
'login.subtitle': '请输入访问令牌以继续',
'login.token': '访问令牌',
'login.submit': '登录',
'login.error': '令牌无效,请重试。',
},
};
(function () {
function register() {
Alpine.store('locale', {
lang: 'en',
init() {
let saved = null;
try {
saved = localStorage.getItem('yd.locale');
} catch (e) {}
const browser = (navigator.language || 'en').toLowerCase().startsWith('zh') ? 'zh' : 'en';
this.lang = saved || browser;
this._applyLangAttr();
},
set(lang) {
this.lang = lang;
try {
localStorage.setItem('yd.locale', lang);
} catch (e) {}
this._applyLangAttr();
},
toggle() {
this.set(this.lang === 'en' ? 'zh' : 'en');
},
t(key) {
const dict = window.I18n[this.lang] || window.I18n.en;
if (dict && dict[key] != null) return dict[key];
if (window.I18n.en[key] != null) return window.I18n.en[key];
return key;
},
_applyLangAttr() {
document.documentElement.setAttribute('lang', this.lang === 'zh' ? 'zh-CN' : 'en');
},
});
Alpine.magic('t', () => (key) => Alpine.store('locale').t(key));
}
if (window.Alpine) register();
else document.addEventListener('alpine:init', register);
})();
+45
View File
@@ -0,0 +1,45 @@
/**
* Central icon set. Each entry is an inline SVG string (currentColor aware)
* injected via Alpine's x-html. Keeping icons here prevents the duplicated
* markup that previously littered every list row and header.
*/
window.Icons = {
logout:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>',
inbox:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>',
outbox:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>',
file:
'<svg viewBox="0 0 24 24" fill="none" stroke="#2563eb" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>',
download:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',
share:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>',
trash:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>',
upload:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 13v8"/><path d="m8 17 4-4 4 4"/><path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 4 16.3"/><path d="m8 17 4-4 4 4"/></svg>',
empty:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 3-4-3H2"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>',
/* Theme */
sun:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/></svg>',
moon:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>',
monitor:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>',
/* Language */
globe:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>',
};
+88
View File
@@ -0,0 +1,88 @@
/**
* Global state store (Alpine.store).
*
* Single source of truth for the file lists and shared actions, analogous to a
* Pinia/Redux store in a framework app. Components read reactive getters and
* dispatch actions here instead of owning their own duplicate state.
*/
(function () {
function register() {
Alpine.store('files', {
files: { inbox: [], outbox: [] },
toast: { show: false, message: '', _timer: null },
async init() {
await this.loadFiles();
},
async loadFiles() {
try {
const [inbox, outbox] = await Promise.all([
fetch('/api/files?dir=inbox').then((r) => r.json()),
fetch('/api/files?dir=outbox').then((r) => r.json()),
]);
this.files.inbox = inbox.files || [];
this.files.outbox = outbox.files || [];
} catch (e) {
this.showToast('toast.loadFailed');
}
},
showToast(message) {
this.toast.message = Alpine.store('locale').t(message);
this.toast.show = true;
if (this.toast._timer) clearTimeout(this.toast._timer);
this.toast._timer = setTimeout(() => {
this.toast.show = false;
}, 2500);
},
async upload(dir, fileList) {
if (!fileList || !fileList.length) return;
for (const file of fileList) {
const form = new FormData();
form.append('file', file);
form.append('dir', dir);
await fetch('/api/upload', { method: 'POST', body: form });
}
this.showToast('toast.uploaded');
await this.loadFiles();
},
download(id) {
window.location.href = '/api/files/' + id + '/download';
},
async deleteFile(id) {
const confirmed = await Alpine.store('confirm').show({
title: 'confirm.deleteTitle',
message: 'confirm.deleteMessage',
danger: true,
});
if (!confirmed) return;
await fetch('/api/files/' + id, { method: 'DELETE' });
this.showToast('toast.deleted');
await this.loadFiles();
},
async share(id) {
const res = await fetch('/api/files/' + id + '/share', { method: 'POST' });
const data = await res.json();
try {
await navigator.clipboard.writeText(data.url);
this.showToast('toast.shareCopied');
} catch (_) {
window.prompt('Share URL:', data.url);
}
},
async logout() {
await fetch('/api/logout', { method: 'POST' });
window.location.href = '/login';
},
});
}
if (window.Alpine) register();
else document.addEventListener('alpine:init', register);
})();
+64
View File
@@ -0,0 +1,64 @@
/**
* Theme manager.
*
* Supports `light` / `dark` / `system`. The resolved theme is written to the
* `data-theme` attribute on <html>, which the CSS token layer keys off of.
* The `system` mode tracks the OS preference live. The choice is persisted to
* localStorage. A tiny inline script in each page sets the initial attribute
* before paint to avoid a flash of the wrong theme.
*/
(function () {
function register() {
Alpine.store('theme', {
mode: 'system', // 'light' | 'dark' | 'system'
resolved: 'light',
init() {
let saved = null;
try {
saved = localStorage.getItem('yd.theme');
} catch (e) {}
if (saved === 'light' || saved === 'dark' || saved === 'system') {
this.mode = saved;
}
this.apply();
const mq = window.matchMedia('(prefers-color-scheme: dark)');
const onChange = () => {
if (this.mode === 'system') this.apply();
};
if (mq.addEventListener) mq.addEventListener('change', onChange);
else if (mq.addListener) mq.addListener(onChange);
},
set(mode) {
this.mode = mode;
try {
localStorage.setItem('yd.theme', mode);
} catch (e) {}
this.apply();
},
cycle() {
const order = ['light', 'dark', 'system'];
const next = order[(order.indexOf(this.mode) + 1) % order.length];
this.set(next);
},
icon() {
if (this.mode === 'system') return 'monitor';
return this.mode === 'dark' ? 'moon' : 'sun';
},
apply() {
const mq = window.matchMedia('(prefers-color-scheme: dark)');
const resolved = this.mode === 'system' ? (mq.matches ? 'dark' : 'light') : this.mode;
this.resolved = resolved;
document.documentElement.setAttribute('data-theme', resolved);
},
});
}
if (window.Alpine) register();
else document.addEventListener('alpine:init', register);
})();
+191
View File
@@ -0,0 +1,191 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>yDropbox</title>
<link rel="stylesheet" href="/styles/tokens.css">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/components.css">
<!-- Set the theme before paint to avoid a flash of the wrong theme. -->
<script>
(function () {
try {
var t = localStorage.getItem('yd.theme') || 'system';
var dark = t === 'dark' || (t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
} catch (e) {}
})();
</script>
<!-- Components register themselves on `alpine:init`; Alpine is loaded last. -->
<script defer src="/components/icons.js"></script>
<script defer src="/version.js"></script>
<script defer src="/components/i18n.js"></script>
<script defer src="/components/theme.js"></script>
<script defer src="/components/store.js"></script>
<script defer src="/components/fileSection.js"></script>
<script defer src="/components/confirm.js"></script>
<script defer src="/alpine.min.js"></script>
</head>
<body x-data>
<div class="app">
<header class="app-header">
<h1 class="brand">y<span>Dropbox</span></h1>
<div class="header-actions">
<button class="btn btn-icon" type="button"
@click="$store.locale.toggle()"
:title="$t('lang.label')" :aria-label="$t('lang.label')">
<span class="icon" x-html="Icons.globe"></span>
</button>
<button class="btn btn-icon" type="button"
@click="$store.theme.cycle()"
:title="$t('theme.' + $store.theme.mode)" :aria-label="$t('theme.' + $store.theme.mode)">
<span class="icon" x-html="Icons[$store.theme.icon()]"></span>
</button>
<button class="btn btn-ghost btn-logout" @click="$store.files.logout()">
<span class="icon" x-html="Icons.logout"></span>
<span x-text="$t('nav.logout')"></span>
</button>
</div>
</header>
<main>
<!-- Inbox -->
<section class="section" x-data="fileSection('inbox', { canShare: true })">
<div class="section-header">
<h2>
<span class="icon" x-html="icon"></span>
<span x-text="title"></span>
<span class="badge" x-text="count"></span>
</h2>
</div>
<div class="drop-zone"
:class="{ 'is-dragover': dragover }"
@dragover.prevent="dragover = true"
@dragleave.prevent="dragover = false"
@drop.prevent="dragover = false; onDrop($event)">
<input type="file" class="drop-zone-input" @change="onSelect($event)" multiple>
<div class="drop-zone-icon"><span class="icon" x-html="Icons.upload"></span></div>
<div class="drop-zone-text"><strong x-text="$t('dropzone.click')"></strong> <span x-text="$t('dropzone.rest')"></span></div>
</div>
<template x-if="count === 0">
<div class="empty-state">
<span class="empty-state-icon" x-html="Icons.empty"></span>
<div class="empty-state-text" x-text="$t('empty.' + dir)"></div>
</div>
</template>
<ul class="file-list" x-show="count > 0">
<template x-for="file in files" :key="file.id">
<li class="file-row">
<span class="file-icon" x-html="Icons.file"></span>
<div class="file-info">
<div class="file-name" x-text="file.name"></div>
</div>
<div class="file-actions">
<button class="btn btn-icon" @click="$store.files.download(file.id)" :title="$t('action.download')">
<span class="icon" x-html="Icons.download"></span>
</button>
<button class="btn btn-icon" x-show="canShare" @click="$store.files.share(file.id)" :title="$t('action.share')">
<span class="icon" x-html="Icons.share"></span>
</button>
<button class="btn btn-icon btn-danger" @click="$store.files.deleteFile(file.id)" :title="$t('action.delete')">
<span class="icon" x-html="Icons.trash"></span>
</button>
</div>
</li>
</template>
</ul>
</section>
<!-- Outbox -->
<section class="section" x-data="fileSection('outbox')">
<div class="section-header">
<h2>
<span class="icon" x-html="icon"></span>
<span x-text="title"></span>
<span class="badge" x-text="count"></span>
</h2>
</div>
<div class="drop-zone"
:class="{ 'is-dragover': dragover }"
@dragover.prevent="dragover = true"
@dragleave.prevent="dragover = false"
@drop.prevent="dragover = false; onDrop($event)">
<input type="file" class="drop-zone-input" @change="onSelect($event)" multiple>
<div class="drop-zone-icon"><span class="icon" x-html="Icons.upload"></span></div>
<div class="drop-zone-text"><strong x-text="$t('dropzone.click')"></strong> <span x-text="$t('dropzone.rest')"></span></div>
</div>
<template x-if="count === 0">
<div class="empty-state">
<span class="empty-state-icon" x-html="Icons.empty"></span>
<div class="empty-state-text" x-text="$t('empty.' + dir)"></div>
</div>
</template>
<ul class="file-list" x-show="count > 0">
<template x-for="file in files" :key="file.id">
<li class="file-row">
<span class="file-icon" x-html="Icons.file"></span>
<div class="file-info">
<div class="file-name" x-text="file.name"></div>
</div>
<div class="file-actions">
<button class="btn btn-icon" @click="$store.files.download(file.id)" :title="$t('action.download')">
<span class="icon" x-html="Icons.download"></span>
</button>
<button class="btn btn-icon btn-danger" @click="$store.files.deleteFile(file.id)" :title="$t('action.delete')">
<span class="icon" x-html="Icons.trash"></span>
</button>
</div>
</li>
</template>
</ul>
</section>
</main>
<div class="toast"
:class="{ 'show': $store.files.toast.show }"
x-text="$store.files.toast.message"></div>
<!-- Confirmation modal -->
<div class="modal-overlay"
x-data="confirmDialog()"
x-show="open"
x-cloak
x-transition.opacity
@click="cancel()"
@keydown.escape.window="onEscape()">
<div class="modal"
x-transition
@click.stop
role="dialog"
aria-modal="true"
:aria-label="$t(title)">
<h3 class="modal-title" x-text="$t(title)"></h3>
<p class="modal-body" x-text="$t(message)"></p>
<div class="modal-actions">
<button class="btn btn-ghost" type="button" @click="cancel()" x-text="$t('confirm.cancel')"></button>
<button class="btn"
:class="danger ? 'btn-danger' : 'btn-primary'"
type="button"
x-ref="accept"
@click="accept()"
x-text="$t(danger ? 'confirm.delete' : 'confirm.confirm')"></button>
</div>
</div>
</div>
<footer class="app-footer">
<span class="app-footer-brand">yDropbox</span>
<span class="app-footer-version" x-text="'v' + YDROPBX_VERSION"></span>
</footer>
</div>
</body>
</html>
+70
View File
@@ -0,0 +1,70 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>yDropbox Login</title>
<link rel="stylesheet" href="/styles/tokens.css">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/components.css">
<script>
(function () {
try {
var t = localStorage.getItem('yd.theme') || 'system';
var dark = t === 'dark' || (t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
} catch (e) {}
})();
</script>
<script defer src="/components/icons.js"></script>
<script defer src="/components/i18n.js"></script>
<script defer src="/components/theme.js"></script>
<script defer src="/alpine.min.js"></script>
</head>
<body x-data>
<div class="page-topbar">
<button class="btn btn-icon" type="button"
@click="$store.locale.toggle()"
:title="$t('lang.label')" :aria-label="$t('lang.label')">
<span class="icon" x-html="Icons.globe"></span>
</button>
<button class="btn btn-icon" type="button"
@click="$store.theme.cycle()"
:title="$t('theme.' + $store.theme.mode)" :aria-label="$t('theme.' + $store.theme.mode)">
<span class="icon" x-html="Icons[$store.theme.icon()]"></span>
</button>
</div>
<div class="login-wrap">
<div class="login-card">
<h1>y<span>Dropbox</span></h1>
<p x-text="$t('login.subtitle')"></p>
<form id="loginForm">
<input type="password" id="token" :placeholder="$t('login.token')" required autocomplete="current-password">
<div class="login-error" id="loginError" x-text="$t('login.error')"></div>
<button type="submit" class="btn btn-primary" x-text="$t('login.submit')"></button>
</form>
</div>
</div>
<script>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('loginError');
errEl.classList.remove('show');
const token = document.getElementById('token').value;
const res = await fetch('/api/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({token})
});
if (res.ok) {
window.location.href = '/';
} else {
errEl.classList.add('show');
}
});
</script>
</body>
</html>
+54
View File
@@ -0,0 +1,54 @@
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
-webkit-text-size-adjust: 100%;
}
body {
font-family: var(--font-sans);
background: var(--color-bg);
background-image: var(--color-bg-gradient);
background-attachment: fixed;
color: var(--color-text);
line-height: 1.5;
min-height: 100vh;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
button {
font-family: inherit;
}
[x-cloak] {
display: none !important;
}
a {
color: inherit;
}
:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
border-radius: var(--radius-sm);
}
/* ===== App shell ===== */
.app {
max-width: 760px;
margin: 0 auto;
padding: var(--space-8) var(--space-5) var(--space-16);
}
@media (max-width: 600px) {
.app {
padding: var(--space-5) var(--space-4) var(--space-16);
}
}
+463
View File
@@ -0,0 +1,463 @@
/* ============================================================
Components
============================================================ */
/* ----- Icon helper (x-html injected SVGs) ----- */
.icon {
display: inline-flex;
align-items: center;
justify-content: center;
line-height: 0;
}
.icon svg {
display: block;
width: 1em;
height: 1em;
}
/* ----- Header ----- */
.app-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--space-8);
}
.header-actions {
display: flex;
align-items: center;
gap: var(--space-2);
}
.brand {
font-size: var(--text-2xl);
font-weight: 700;
letter-spacing: -0.4px;
color: var(--color-text);
}
.brand span {
color: var(--color-primary);
}
/* ----- Buttons ----- */
.btn {
display: inline-flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2) var(--space-4);
font-size: var(--text-sm);
font-weight: 500;
line-height: 1;
color: var(--color-text);
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
cursor: pointer;
transition: background var(--transition-fast), border-color var(--transition-fast),
color var(--transition-fast), box-shadow var(--transition-fast), transform var(--transition-fast);
white-space: nowrap;
user-select: none;
}
.btn:hover {
background: var(--color-surface-hover);
}
.btn:active {
transform: translateY(1px);
}
.btn-primary {
background: var(--color-primary);
border-color: var(--color-primary);
color: #fff;
}
.btn-primary:hover {
background: var(--color-primary-hover);
border-color: var(--color-primary-hover);
}
.btn-danger {
color: var(--color-danger);
border-color: #fecaca;
}
.btn-danger:hover {
background: var(--color-danger-soft);
border-color: var(--color-danger);
}
.btn-ghost {
border-color: transparent;
background: transparent;
}
.btn-ghost:hover {
background: var(--color-surface-hover);
}
.btn-sm {
padding: var(--space-2) var(--space-3);
font-size: var(--text-xs);
}
.btn-logout {
color: var(--color-text-secondary);
font-size: var(--text-sm);
}
.btn-logout:hover {
color: var(--color-text);
}
/* Icon-only button */
.btn-icon {
padding: var(--space-2);
color: var(--color-text-secondary);
}
.btn-icon:hover {
color: var(--color-text);
background: var(--color-surface-hover);
}
.btn-icon.btn-danger:hover {
color: var(--color-danger);
background: var(--color-danger-soft);
}
/* ----- Section (card) ----- */
.section {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-sm);
margin-bottom: var(--space-5);
overflow: hidden;
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: var(--space-4) var(--space-5);
border-bottom: 1px solid var(--color-border);
}
.section-header h2 {
display: flex;
align-items: center;
gap: var(--space-2);
font-size: var(--text-lg);
font-weight: 600;
}
.section-header h2 .icon {
font-size: 1.05em;
color: var(--color-primary);
}
.badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 22px;
height: 22px;
padding: 0 var(--space-2);
font-size: var(--text-xs);
font-weight: 600;
color: var(--color-text-secondary);
background: var(--color-bg);
border-radius: var(--radius-full);
}
/* ----- Drop zone ----- */
.drop-zone {
position: relative;
margin: var(--space-4) var(--space-5);
padding: var(--space-8) var(--space-5);
text-align: center;
border: 2px dashed var(--color-border-strong);
border-radius: var(--radius-md);
cursor: pointer;
transition: border-color var(--transition-base), background var(--transition-base);
}
.drop-zone:hover,
.drop-zone.is-dragover {
border-color: var(--color-primary);
background: var(--color-primary-soft);
}
.drop-zone-input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
.drop-zone-icon {
font-size: 1.6rem;
color: var(--color-text-tertiary);
margin-bottom: var(--space-2);
transition: color var(--transition-base);
}
.drop-zone:hover .drop-zone-icon,
.drop-zone.is-dragover .drop-zone-icon {
color: var(--color-primary);
}
.drop-zone-text {
font-size: var(--text-sm);
color: var(--color-text-secondary);
}
.drop-zone-text strong {
color: var(--color-primary);
font-weight: 600;
}
/* ----- File list ----- */
.file-list {
list-style: none;
}
.file-row {
display: flex;
align-items: center;
gap: var(--space-3);
padding: var(--space-3) var(--space-5);
border-bottom: 1px solid var(--color-divider);
transition: background var(--transition-fast);
}
.file-row:last-child {
border-bottom: none;
}
.file-row:hover {
background: var(--color-surface-hover);
}
.file-icon {
display: flex;
align-items: center;
justify-content: center;
width: 38px;
height: 38px;
flex-shrink: 0;
font-size: 18px;
color: var(--color-primary);
background: var(--color-primary-soft);
border-radius: var(--radius-md);
}
.file-info {
flex: 1;
min-width: 0;
}
.file-name {
font-size: var(--text-sm);
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.file-actions {
display: flex;
gap: var(--space-1);
flex-shrink: 0;
opacity: 0;
transition: opacity var(--transition-fast);
}
.file-row:hover .file-actions,
.file-row:focus-within .file-actions {
opacity: 1;
}
/* ----- Empty state ----- */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-2);
padding: var(--space-10) var(--space-5);
text-align: center;
color: var(--color-text-secondary);
}
.empty-state-icon {
font-size: 2rem;
color: var(--color-text-tertiary);
opacity: 0.6;
}
.empty-state-text {
font-size: var(--text-sm);
}
/* ----- Toast ----- */
.toast {
position: fixed;
left: 50%;
bottom: var(--space-6);
transform: translateX(-50%) translateY(120%);
padding: var(--space-3) var(--space-5);
font-size: var(--text-sm);
font-weight: 500;
color: var(--color-toast-fg);
background: var(--color-toast-bg);
border-radius: var(--radius-md);
box-shadow: var(--shadow-lg);
opacity: 0;
pointer-events: none;
z-index: var(--z-toast);
transition: transform var(--transition-slow), opacity var(--transition-slow);
}
.toast.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
@media (prefers-reduced-motion: reduce) {
* {
transition-duration: 0.01ms !important;
}
}
/* ----- App footer (version) ----- */
.app-footer {
display: flex;
align-items: center;
justify-content: center;
gap: var(--space-2);
margin-top: var(--space-8);
font-size: var(--text-xs);
color: var(--color-text-tertiary);
}
.app-footer-version {
font-variant-numeric: tabular-nums;
padding: 2px 8px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-full);
}
/* ----- Modal (confirmation dialog) ----- */
.modal-overlay {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-4);
background: rgba(16, 24, 40, 0.45);
backdrop-filter: blur(2px);
z-index: var(--z-modal);
}
.modal {
width: 100%;
max-width: 380px;
padding: var(--space-6);
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-lg);
}
.modal-title {
font-size: var(--text-lg);
font-weight: 600;
margin-bottom: var(--space-2);
}
.modal-body {
font-size: var(--text-sm);
color: var(--color-text-secondary);
margin-bottom: var(--space-6);
}
.modal-actions {
display: flex;
justify-content: flex-end;
gap: var(--space-2);
}
/* ----- Login ----- */
.page-topbar {
position: fixed;
top: var(--space-4);
right: var(--space-4);
display: flex;
gap: var(--space-2);
z-index: var(--z-toast);
}
.login-wrap {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: var(--space-5);
}
.login-card {
width: 100%;
max-width: 380px;
padding: var(--space-10) var(--space-8);
text-align: center;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-lg);
}
.login-card h1 {
font-size: var(--text-2xl);
font-weight: 700;
margin-bottom: var(--space-1);
}
.login-card h1 span {
color: var(--color-primary);
}
.login-card p {
font-size: var(--text-sm);
color: var(--color-text-secondary);
margin-bottom: var(--space-6);
}
.login-card form {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.login-card input {
width: 100%;
padding: var(--space-3) var(--space-4);
font-size: var(--text-base);
color: var(--color-text);
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
outline: none;
transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
}
.login-card input:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12);
}
.login-card .btn-primary {
justify-content: center;
padding: var(--space-3);
font-size: var(--text-base);
}
.login-error {
display: none;
font-size: var(--text-sm);
color: var(--color-danger);
}
.login-error.show {
display: block;
}
/* ----- Responsive ----- */
@media (max-width: 600px) {
.section-header {
padding: var(--space-3) var(--space-4);
}
.file-row {
padding: var(--space-3) var(--space-4);
}
.file-actions {
opacity: 1;
}
.drop-zone {
margin: var(--space-3) var(--space-4);
}
.login-card {
padding: var(--space-8) var(--space-5);
}
}
+98
View File
@@ -0,0 +1,98 @@
:root {
/* ===== Color ===== */
--color-bg: #f4f5f7;
--color-bg-gradient: radial-gradient(1200px 600px at 50% -10%, #eef2ff 0%, var(--color-bg) 55%);
--color-surface: #ffffff;
--color-surface-hover: #fafbfc;
--color-border: #e6e8ec;
--color-border-strong: #d4d8df;
--color-text: #1a1d23;
--color-text-secondary: #6b7280;
--color-text-tertiary: #9aa1ad;
--color-primary: #2563eb;
--color-primary-hover: #1d4ed8;
--color-primary-soft: #eff6ff;
--color-danger: #ef4444;
--color-danger-hover: #dc2626;
--color-danger-soft: #fef2f2;
--color-success: #10b981;
/* Structural tokens */
--color-divider: #f3f4f6;
--color-toast-bg: #1a1d23;
--color-toast-fg: #ffffff;
color-scheme: light;
/* ===== Spacing (4px base) ===== */
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 0.75rem;
--space-4: 1rem;
--space-5: 1.25rem;
--space-6: 1.5rem;
--space-8: 2rem;
--space-10: 2.5rem;
--space-16: 4rem;
/* ===== Radius ===== */
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 14px;
--radius-full: 9999px;
/* ===== Shadow ===== */
--shadow-sm: 0 1px 2px rgba(16, 24, 40, 0.05);
--shadow-md: 0 4px 12px rgba(16, 24, 40, 0.08);
--shadow-lg: 0 16px 40px rgba(16, 24, 40, 0.14);
/* ===== Typography ===== */
--font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--text-xs: 0.75rem;
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.125rem;
--text-xl: 1.25rem;
--text-2xl: 1.5rem;
/* ===== Motion ===== */
--transition-fast: 150ms ease;
--transition-base: 200ms ease;
--transition-slow: 300ms ease;
/* ===== z-index ===== */
--z-toast: 1000;
--z-modal: 1100;
}
/* ===== Dark theme ===== */
[data-theme="dark"] {
--color-bg: #0f1115;
--color-bg-gradient: radial-gradient(1200px 600px at 50% -10%, #1a2030 0%, var(--color-bg) 55%);
--color-surface: #171a21;
--color-surface-hover: #1e222b;
--color-border: #262b35;
--color-border-strong: #323844;
--color-text: #e6e8ec;
--color-text-secondary: #9aa1ad;
--color-text-tertiary: #6b7280;
--color-primary: #3b82f6;
--color-primary-hover: #2f6fe0;
--color-primary-soft: #16233f;
--color-danger: #f87171;
--color-danger-hover: #ef4444;
--color-danger-soft: #2a1717;
--color-divider: #23262f;
--color-toast-bg: #e6e8ec;
--color-toast-fg: #1a1d23;
color-scheme: dark;
}
+3
View File
@@ -0,0 +1,3 @@
// Frontend version. Bump this together with the top entry in
// docs/CHANGELOG_webui.md whenever the UI changes.
window.YDROPBX_VERSION = '0.1.1';
+6
View File
@@ -0,0 +1,6 @@
package web
import "embed"
//go:embed login.html index.html alpine.min.js version.js components styles
var FS embed.FS