Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f698ba516d | |||
| 17c31be8b4 | |||
| 313c89483c | |||
| 5cd476e7f3 | |||
| d3b6a86753 | |||
| cf5d8bb50d | |||
| 8e3f783780 | |||
| 6c87187c6d | |||
| f628b489af | |||
| 1ab5021667 | |||
| c9f865cd85 | |||
| 38afc6c34d | |||
| 9a5be44a7f | |||
| 48722f0aab | |||
| 94cf9531fa | |||
| 60d2ea0204 | |||
| ffa2d9636b | |||
| cc91ce120d | |||
| 73bd14572d | |||
| 4eacb4cde2 | |||
| 71d9b9db7e | |||
| 01996c0445 | |||
| adb1a12dfd |
10
.env.example
@@ -9,6 +9,11 @@ WARPBOX_CLEANUP_ENABLED=true
|
||||
WARPBOX_CLEANUP_EVERY=1h
|
||||
WARPBOX_THUMBNAIL_ENABLED=true
|
||||
WARPBOX_THUMBNAIL_EVERY=1m
|
||||
WARPBOX_RESUMABLE_UPLOADS_ENABLED=true
|
||||
WARPBOX_RESUMABLE_CHUNK_MB=64
|
||||
WARPBOX_RESUMABLE_RETENTION_HOURS=1
|
||||
WARPBOX_RESUMABLE_CHUNK_MODE=same
|
||||
WARPBOX_RESUMABLE_CHUNK_PATH=
|
||||
WARPBOX_MAX_UPLOAD_SIZE_MB=16384
|
||||
WARPBOX_ANONYMOUS_UPLOADS_ENABLED=true
|
||||
WARPBOX_ANONYMOUS_MAX_UPLOAD_MB=512
|
||||
@@ -27,7 +32,8 @@ WARPBOX_SHORT_WINDOW_REQUESTS=60
|
||||
WARPBOX_SHORT_WINDOW_SECONDS=60
|
||||
WARPBOX_ANONYMOUS_STORAGE_BACKEND=local
|
||||
WARPBOX_USER_STORAGE_BACKEND=local
|
||||
WARPBOX_READ_TIMEOUT=15s
|
||||
WARPBOX_WRITE_TIMEOUT=60s
|
||||
WARPBOX_READ_HEADER_TIMEOUT=15s
|
||||
WARPBOX_READ_TIMEOUT=0s
|
||||
WARPBOX_WRITE_TIMEOUT=0s
|
||||
WARPBOX_IDLE_TIMEOUT=120s
|
||||
WARPBOX_TRUSTED_PROXIES=
|
||||
|
||||
2
.gitignore
vendored
@@ -15,3 +15,5 @@ backend/static/uploads/*
|
||||
.prod.env
|
||||
scripts/env/dev.env
|
||||
docker-compose.yml
|
||||
|
||||
.claude
|
||||
111
PLANS.md
Normal file
@@ -0,0 +1,111 @@
|
||||
# Warpbox Plans & Staged Development
|
||||
|
||||
This document captures the staged development history and roadmap for Warpbox. For day-to-day usage,
|
||||
configuration, and deployment, see [README.md](./README.md).
|
||||
|
||||
## Stage 2 — Operator Tools
|
||||
|
||||
- `/admin/login` - token-based admin login.
|
||||
- `/admin` - overview metrics: boxes, files, storage, recent uploads, protected/expired boxes.
|
||||
- `/admin/files` - recent upload table with view and delete actions.
|
||||
- Expired boxes and boxes that have reached their download limit are cleaned on startup and then
|
||||
every `WARPBOX_CLEANUP_EVERY` when `WARPBOX_CLEANUP_ENABLED=true`.
|
||||
- Missing image/video thumbnails are generated in a background worker every `WARPBOX_THUMBNAIL_EVERY`
|
||||
when `WARPBOX_THUMBNAIL_ENABLED=true`.
|
||||
|
||||
## Stage 3 — Anonymous Integrations
|
||||
|
||||
Anonymous uploads return a private management link at creation time. Keep that link secret: anyone
|
||||
with it can delete the entire upload box. The raw delete token is not stored and cannot be recovered
|
||||
later.
|
||||
|
||||
Browser uploads still show `Open box` and `Copy URL` as the primary actions, with a smaller
|
||||
`Manage or delete this upload` link in the completion panel.
|
||||
|
||||
Curl and custom uploaders can use the same endpoint:
|
||||
|
||||
```bash
|
||||
# Terminal-friendly output: one plain box URL.
|
||||
curl -F file=@./report.pdf http://localhost:8080/api/v1/upload
|
||||
|
||||
# JSON output with boxUrl, thumbnailUrl, manageUrl, deleteUrl, zipUrl, and file entries.
|
||||
curl -F sharex=@./screenshot.png \
|
||||
-H 'Accept: application/json' \
|
||||
http://localhost:8080/api/v1/upload
|
||||
```
|
||||
|
||||
The upload endpoint accepts multipart fields named `file` and `sharex`. ShareX users can start from
|
||||
`examples/sharex/warpbox-anonymous.sxcu`; update `RequestURL` to match your instance URL.
|
||||
Authenticated uploads (your account's limits) add an `Authorization: Bearer <token>` header — mint a
|
||||
token under **Account → Access tokens**. The JSON response uses ShareX placeholders `{json:boxUrl}`
|
||||
(URL), `{json:thumbnailUrl}` (thumbnail), `{json:deleteUrl}` (deletion), and `{json:error}` (error
|
||||
message).
|
||||
|
||||
### Grouping multiple files into one box (`X-Warpbox-Batch`)
|
||||
|
||||
By default every uploaded file becomes its own box. To put several files in a **single** box, send
|
||||
the opt-in `X-Warpbox-Batch` header: requests that share the same header value (scoped per account,
|
||||
or per IP for anonymous uploads) within 20s are appended to the same box. This lets a multi-file
|
||||
ShareX selection — which ShareX sends as separate back-to-back requests — land as one shareable link.
|
||||
The shipped `.sxcu` sets `X-Warpbox-Batch: sharex`; remove that header for one box per file. Requests
|
||||
without the header behave exactly as before.
|
||||
|
||||
### Resumable API flow
|
||||
|
||||
Custom clients can use the resumable JSON API for large files:
|
||||
|
||||
```bash
|
||||
# 1. Create a resumable session from file metadata.
|
||||
curl -s http://localhost:8080/api/v1/uploads/resumable \
|
||||
-H 'Accept: application/json' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"files":[{"name":"large.bin","size":1048576,"contentType":"application/octet-stream"}],"expiresMinutes":1440}'
|
||||
|
||||
# 2. Upload exact-sized chunks using the returned sessionId, file id, and chunkSize.
|
||||
dd if=./large.bin bs=8388608 count=1 skip=0 2>/dev/null | \
|
||||
curl -X PUT --data-binary @- \
|
||||
http://localhost:8080/api/v1/uploads/resumable/SESSION_ID/files/FILE_ID/chunks/0
|
||||
|
||||
# 3. Complete the session after all chunks are present.
|
||||
curl -X POST -H 'Accept: application/json' \
|
||||
http://localhost:8080/api/v1/uploads/resumable/SESSION_ID/complete
|
||||
```
|
||||
|
||||
The complete response is the same JSON shape as `POST /api/v1/upload`, including `boxUrl`,
|
||||
`manageUrl`, `deleteUrl`, and file URLs. Send `Authorization: Bearer <token>` on every resumable
|
||||
request to upload as an account.
|
||||
|
||||
Browser resumable uploads are configurable from `/admin/settings`: enabled/disabled, chunk size in
|
||||
MB, draft retention hours, and chunk staging location. The default chunk mode stores temporary draft
|
||||
chunks under `data/tmp/uploads/{session_id}`. A custom mode can point those chunks at another local
|
||||
path, such as a mounted fast SSD. Chunk staging stays local even when the completed files are later
|
||||
finalized into S3/SFTP/SMB/WebDAV storage. Completion returns the share link immediately; files may
|
||||
show as `Processing` on the download page while the background finalizer streams them to the selected
|
||||
storage backend. Cleanup removes expired uploading drafts but skips sessions already in processing.
|
||||
|
||||
## Stage 4 — Accounts + Personal Boxes
|
||||
|
||||
- `/register` bootstraps the first admin account only when no users exist.
|
||||
- `/login` and `/logout` provide cookie-based web sessions.
|
||||
- `/app` is the personal dashboard for logged-in users, showing owned boxes, storage usage, upload
|
||||
history, and flat collections. Uploading still happens from the homepage.
|
||||
- `/admin/users` lets admins create invite links, disable/reactivate users, and generate reset links.
|
||||
- Logged-in browser uploads from `/` still use `POST /api/v1/upload`, but the resulting box is stored
|
||||
with owner and optional collection metadata.
|
||||
- Admin users are exempt from the global max upload size on the homepage upload flow. Future per-user
|
||||
quotas should apply to this same upload path rather than creating a second uploader.
|
||||
- `/admin/settings` controls anonymous uploads, anonymous max upload size, daily upload caps, default
|
||||
user storage quota, and usage retention.
|
||||
- `/admin/users` shows storage/daily usage and lets admins set per-user storage quota overrides.
|
||||
- `/admin/storage` manages the built-in local file backend and S3-compatible bucket backends.
|
||||
- `/admin/bans` manages manual IP/CIDR bans and optional automatic bans for suspicious probes and
|
||||
repeated login failures. Auto-ban is off by default and configured from the admin UI.
|
||||
- Upload limits now include daily bytes, daily box counts, active box counts, short-window request
|
||||
limits, max expiration days, local storage capacity in GB, and per-user policy overrides.
|
||||
- Uploaded file content, thumbnails, and private box metadata use the selected storage backend. The
|
||||
bbolt database and JSON logs remain local under `./data/db` and `./data/logs`.
|
||||
- Anonymous uploads, ShareX uploads, unlisted public box links, password protection, expiry, delete
|
||||
tokens, thumbnails, and cleanup continue to work as before.
|
||||
|
||||
Email delivery is intentionally deferred. Invite and reset links are copyable today; future SMTP
|
||||
support will power public forgot-password and optional email delivery.
|
||||
324
README.md
@@ -1,6 +1,20 @@
|
||||
# Warpbox.dev
|
||||
|
||||
This repository contains the Go backend base for `warpbox.dev`, a self-hosted transfer-first file sharing application.
|
||||
Warpbox is a self-hosted, transfer first file sharing application written in Go. It renders
|
||||
server side templates and serves static assets directly.
|
||||
|
||||
## Features
|
||||
|
||||
- Anonymous and authenticated uploads from the browser, `curl`, or ShareX.
|
||||
- Warpbox-native resumable uploads with a JSON API for large files.
|
||||
- Upload boxes with expiry, optional download limits, password protection, and one time delete tokens.
|
||||
- User accounts with personal dashboards, collections, storage quotas, and invite based registration.
|
||||
- Admin tooling for metrics, file management, storage backends, upload policy, and IP bans.
|
||||
- Local and S3 compatible storage backends.
|
||||
- Background jobs for cleanup and thumbnail generation.
|
||||
- Emoji reaction packs loaded from the runtime data directory.
|
||||
|
||||
> Looking for the roadmap and the staged development history? See [PLANS.md](./PLANS.md).
|
||||
|
||||
## Run
|
||||
|
||||
@@ -10,11 +24,25 @@ This repository contains the Go backend base for `warpbox.dev`, a self-hosted tr
|
||||
|
||||
The default server listens on `:8080`.
|
||||
|
||||
Upload size limits are configured in megabytes through `WARPBOX_MAX_UPLOAD_SIZE_MB`.
|
||||
Fractions are supported, so `0.5Mb` is 512 KiB and `1.5Mb` is 1536 KiB.
|
||||
For one off Go commands, run them from the backend module:
|
||||
|
||||
Upload policy defaults are also configured in megabytes and can later be changed from
|
||||
`/admin/settings`:
|
||||
```bash
|
||||
cd backend
|
||||
go run ./cmd/warpbox
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
All configuration comes from environment variables. The dev script sources `scripts/env/dev.env`.
|
||||
|
||||
### Upload size
|
||||
|
||||
Upload size limits are configured in megabytes through `WARPBOX_MAX_UPLOAD_SIZE_MB`. Fractions are
|
||||
supported, so `0.5Mb` is 512 KiB and `1.5Mb` is 1536 KiB.
|
||||
|
||||
### Upload policy defaults
|
||||
|
||||
These defaults can later be changed from `/admin/settings`:
|
||||
|
||||
- `WARPBOX_ANONYMOUS_UPLOADS_ENABLED=true`
|
||||
- `WARPBOX_ANONYMOUS_MAX_UPLOAD_MB=512`
|
||||
@@ -33,35 +61,184 @@ Upload policy defaults are also configured in megabytes and can later be changed
|
||||
- `WARPBOX_SHORT_WINDOW_SECONDS=60`
|
||||
- `WARPBOX_ANONYMOUS_STORAGE_BACKEND=local`
|
||||
- `WARPBOX_USER_STORAGE_BACKEND=local`
|
||||
- `WARPBOX_TRUSTED_PROXIES=` controls whether forwarded client IP headers are accepted only from specific proxy IPs/CIDRs. See [SECURITY_PROXY.md](./SECURITY_PROXY.md).
|
||||
- `WARPBOX_RESUMABLE_UPLOADS_ENABLED=true`
|
||||
- `WARPBOX_RESUMABLE_CHUNK_MB=8`
|
||||
- `WARPBOX_RESUMABLE_RETENTION_HOURS=24`
|
||||
- `WARPBOX_RESUMABLE_CHUNK_MODE=same`
|
||||
- `WARPBOX_RESUMABLE_CHUNK_PATH=`
|
||||
- `WARPBOX_TRUSTED_PROXIES=` controls whether forwarded client IP headers are accepted only from
|
||||
specific proxy IPs/CIDRs. See [SECURITY_PROXY.md](./SECURITY_PROXY.md).
|
||||
|
||||
Resumable settings are seeded from the environment and can then be edited from `/admin/settings`.
|
||||
Saved admin settings override these env defaults. `WARPBOX_RESUMABLE_CHUNK_MODE=same` stores draft
|
||||
chunks in the normal local temp path, `data/tmp/uploads/{session_id}` under `WARPBOX_DATA_DIR`.
|
||||
`WARPBOX_RESUMABLE_CHUNK_MODE=custom` uses `WARPBOX_RESUMABLE_CHUNK_PATH` instead, for example a
|
||||
mounted fast SSD path. Chunk storage is always local temporary staging; completed files are finalized
|
||||
into the selected storage backend after all chunks arrive.
|
||||
|
||||
### Timeouts
|
||||
|
||||
Large uploads are expected to take minutes on normal home/server connections. Keep
|
||||
`WARPBOX_READ_TIMEOUT=0s` and `WARPBOX_WRITE_TIMEOUT=0s` so Go does not close the connection
|
||||
mid upload; `WARPBOX_READ_HEADER_TIMEOUT=15s` still protects header reads from slowloris style
|
||||
connections.
|
||||
|
||||
### Data directory
|
||||
|
||||
Runtime data is configured with `WARPBOX_DATA_DIR` and defaults to `./data` in the dev environment.
|
||||
The dev script resolves that path from the repository root.
|
||||
|
||||
### Background jobs
|
||||
|
||||
Background jobs are enabled with `WARPBOX_JOBS_ENABLED=true`. Individual jobs can be toggled with
|
||||
`WARPBOX_CLEANUP_ENABLED` and `WARPBOX_THUMBNAIL_ENABLED`, and their schedules are configured with
|
||||
`WARPBOX_CLEANUP_EVERY` and `WARPBOX_THUMBNAIL_EVERY`.
|
||||
|
||||
- **Cleanup**: expired boxes and boxes that have reached their download limit are cleaned on startup
|
||||
and then on schedule. Stale resumable sessions are removed after `WARPBOX_RESUMABLE_RETENTION_HOURS`.
|
||||
- **Thumbnails**: missing image/video thumbnails are generated in a background worker.
|
||||
|
||||
## First run bootstrap
|
||||
|
||||
On a fresh data directory, visit `/register` to create the first account. That first user becomes
|
||||
the instance admin and normal registration closes after bootstrap. Admins can create copyable invite
|
||||
links from `/admin/users`.
|
||||
|
||||
The env admin token still exists as emergency fallback access. Set `WARPBOX_ADMIN_TOKEN` and use it
|
||||
at `/admin/login` if you need to recover access without a user session.
|
||||
The env admin token exists as emergency fallback access. Set `WARPBOX_ADMIN_TOKEN` and use it at
|
||||
`/admin/login` if you need to recover access without a user session.
|
||||
|
||||
For one-off Go commands, run them from the backend module:
|
||||
## Uploads
|
||||
|
||||
Browser uploads use Warpbox native resumable uploads by default. Resumable behavior is configurable
|
||||
from `/admin/settings`, including enable/disable, chunk size, retention, and whether chunks use the
|
||||
default local temp path or a custom local path such as a fast SSD. When all chunks arrive, Warpbox
|
||||
returns the share link immediately and marks files as `Processing` until the background finalizer
|
||||
streams them into the selected storage backend. Draft chunks are deleted once finalization succeeds.
|
||||
Expired uploading drafts are cleaned after the configured retention window; sessions already in
|
||||
`Processing` are protected from cleanup while finalization is running.
|
||||
|
||||
### Anonymous uploads
|
||||
|
||||
Anonymous uploads return a private management link at creation time. Keep that link secret: anyone
|
||||
with it can delete the entire upload box. The raw delete token is not stored and cannot be recovered
|
||||
later. Browser uploads show `Open box` and `Copy URL` as the primary actions, with a smaller
|
||||
`Manage or delete this upload` link in the completion panel.
|
||||
|
||||
### `curl` and ShareX
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
go run ./cmd/warpbox
|
||||
# Terminal-friendly output: one plain box URL.
|
||||
curl -F file=@./report.pdf http://localhost:8080/api/v1/upload
|
||||
|
||||
# JSON output with boxUrl, thumbnailUrl, manageUrl, deleteUrl, zipUrl, and file entries.
|
||||
curl -F sharex=@./screenshot.png \
|
||||
-H 'Accept: application/json' \
|
||||
http://localhost:8080/api/v1/upload
|
||||
```
|
||||
|
||||
## Docker / Podman
|
||||
The upload endpoint accepts multipart fields named `file` and `sharex`. ShareX users can start from
|
||||
`examples/sharex/warpbox-anonymous.sxcu`; update `RequestURL` to match your instance URL.
|
||||
Authenticated uploads (your account's limits) add an `Authorization: Bearer <token>` header mint a
|
||||
token under **Account → Access tokens**. The JSON response uses ShareX placeholders `{json:boxUrl}`
|
||||
(URL), `{json:thumbnailUrl}` (thumbnail), `{json:deleteUrl}` (deletion), and `{json:error}` (error
|
||||
message).
|
||||
|
||||
### Grouping multiple files into one box (`X-Warpbox-Batch`)
|
||||
|
||||
By default every uploaded file becomes its own box. To put several files in a **single** box, send
|
||||
the opt-in `X-Warpbox-Batch` header: requests that share the same header value (scoped per account,
|
||||
or per IP for anonymous uploads) within 20s are appended to the same box. This lets a multi-file
|
||||
ShareX selection which ShareX sends as separate back-to-back requests land as one shareable link.
|
||||
The shipped `.sxcu` sets `X-Warpbox-Batch: sharex`; remove that header for one box per file. Requests
|
||||
without the header behave exactly as before.
|
||||
|
||||
### Resumable API flow
|
||||
|
||||
Custom clients can use the resumable JSON API for large files:
|
||||
|
||||
```bash
|
||||
# 1. Create a resumable session from file metadata.
|
||||
curl -s http://localhost:8080/api/v1/uploads/resumable \
|
||||
-H 'Accept: application/json' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"files":[{"name":"large.bin","size":1048576,"contentType":"application/octet-stream"}],"expiresMinutes":1440}'
|
||||
|
||||
# 2. Upload exact-sized chunks using the returned sessionId, file id, and chunkSize.
|
||||
dd if=./large.bin bs=8388608 count=1 skip=0 2>/dev/null | \
|
||||
curl -X PUT --data-binary @- \
|
||||
http://localhost:8080/api/v1/uploads/resumable/SESSION_ID/files/FILE_ID/chunks/0
|
||||
|
||||
# 3. Complete the session after all chunks are present.
|
||||
curl -X POST -H 'Accept: application/json' \
|
||||
http://localhost:8080/api/v1/uploads/resumable/SESSION_ID/complete
|
||||
```
|
||||
|
||||
The complete response is the same JSON shape as `POST /api/v1/upload`, including `boxUrl`,
|
||||
`manageUrl`, `deleteUrl`, and file URLs. Send `Authorization: Bearer <token>` on every resumable
|
||||
request to upload as an account.
|
||||
|
||||
## Accounts and admin
|
||||
|
||||
- `/register` bootstraps the first admin account only when no users exist.
|
||||
- `/login` and `/logout` provide cookie-based web sessions.
|
||||
- `/app` is the personal dashboard for logged-in users, showing owned boxes, storage usage, upload
|
||||
history, and flat collections. Uploading still happens from the homepage.
|
||||
- `/admin` shows overview metrics: boxes, files, storage, recent uploads, protected/expired boxes.
|
||||
- `/admin/files` is a recent upload table with view and delete actions.
|
||||
- `/admin/users` lets admins create invite links, disable/reactivate users, generate reset links,
|
||||
view storage/daily usage, and set per-user storage quota overrides.
|
||||
- `/admin/settings` controls anonymous uploads, anonymous max upload size, daily upload caps, default
|
||||
user storage quota, and usage retention.
|
||||
- `/admin/storage` manages the built-in local file backend and S3-compatible bucket backends.
|
||||
- `/admin/bans` manages manual IP/CIDR bans and optional automatic bans for suspicious probes and
|
||||
repeated login failures. Auto-ban is off by default and configured from the admin UI.
|
||||
|
||||
Logged-in browser uploads from `/` use `POST /api/v1/upload`, and the resulting box is stored with
|
||||
owner and optional collection metadata. Admin users are exempt from the global max upload size on the
|
||||
homepage upload flow.
|
||||
|
||||
Email delivery is intentionally deferred. Invite and reset links are copyable today; future SMTP
|
||||
support will power public forgot-password and optional email delivery.
|
||||
|
||||
## Emoji reaction packs
|
||||
|
||||
File reactions use emoji packs from the runtime data directory, not from the application code. By
|
||||
default that means `./data/emoji`; if you change `WARPBOX_DATA_DIR`, use `$WARPBOX_DATA_DIR/emoji`
|
||||
instead.
|
||||
|
||||
Each folder under `./data/emoji` becomes one emoji tab in the reaction picker. Put image files
|
||||
directly inside the pack folder:
|
||||
|
||||
```text
|
||||
data/
|
||||
├── db/
|
||||
├── files/
|
||||
├── logs/
|
||||
└── emoji/
|
||||
├── openmoji/
|
||||
│ ├── 1F600.svg
|
||||
│ ├── 1F44D.svg
|
||||
│ └── 2764.svg
|
||||
├── pixel-pack/
|
||||
│ ├── happy.webp
|
||||
│ ├── fire.webp
|
||||
│ └── star.webp
|
||||
└── custom-work/
|
||||
├── approved.png
|
||||
└── shipped.png
|
||||
```
|
||||
|
||||
In this example, the picker shows tabs named `Openmoji`, `Pixel pack`, and `Custom work`. Supported
|
||||
emoji image extensions are `.svg`, `.webp`, `.png`, `.jpg`, `.jpeg`, and `.gif`.
|
||||
|
||||
## Deployment
|
||||
|
||||
### Docker / Podman
|
||||
|
||||
Copy the example environment file and adjust values such as `WARPBOX_BASE_URL` and
|
||||
`WARPBOX_ADMIN_TOKEN` before running the container:
|
||||
|
||||
Copy the example [docker-compose.example.yml](./docker-compose.example.yml) to [docker-compose.yml](./docker-compose.yml), modify as need-be
|
||||
`WARPBOX_ADMIN_TOKEN` before running the container. Copy the example
|
||||
[docker-compose.example.yml](./docker-compose.example.yml) to
|
||||
[docker-compose.yml](./docker-compose.yml), modify as need-be:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
@@ -69,21 +246,19 @@ docker compose -f docker-compose.yml up --build
|
||||
```
|
||||
|
||||
The compose example also works with Podman compatible compose tools. Its data volume uses
|
||||
`./data:/data:Z` for SELinux relabeling, and the container overrides runtime paths to use
|
||||
`/data`, `/app/static`, and `/app/templates`.
|
||||
`./data:/data:Z` for SELinux relabeling, and the container overrides runtime paths to use `/data`,
|
||||
`/app/static`, and `/app/templates`. The image exposes the health endpoint `/health`, which Docker
|
||||
and compose healthchecks use.
|
||||
|
||||
The image exposes `/health`, `/healthz`, and `/api/v1/health`. Docker and compose healthchecks
|
||||
use `/health`.
|
||||
|
||||
## Reverse Proxy Security
|
||||
### Reverse proxy security
|
||||
|
||||
Warpbox uses the resolved client IP for anonymous limits, manual bans, and automatic bans. The
|
||||
default behavior trusts `X-Forwarded-For` and `X-Real-IP` so a normal Caddy reverse proxy works
|
||||
without extra setup. For hardened deployments where the app port might be reachable from more than
|
||||
one network, set `WARPBOX_TRUSTED_PROXIES` to trusted proxy IPs/CIDRs. See
|
||||
without extra setup. For hardened deployments where the app port might be reachable from more than one
|
||||
network, set `WARPBOX_TRUSTED_PROXIES` to trusted proxy IPs/CIDRs. See
|
||||
[SECURITY_PROXY.md](./SECURITY_PROXY.md) for Caddy examples and Docker/systemd notes.
|
||||
|
||||
## Systemd
|
||||
### Systemd
|
||||
|
||||
Build the binary on the server, create a dedicated user, and keep runtime data outside the repo:
|
||||
|
||||
@@ -106,6 +281,9 @@ WARPBOX_DATA_DIR=/var/lib/warpbox
|
||||
WARPBOX_STATIC_DIR=/opt/warpbox-dev/backend/static
|
||||
WARPBOX_TEMPLATE_DIR=/opt/warpbox-dev/backend/templates
|
||||
WARPBOX_TRUSTED_PROXIES=127.0.0.1,::1
|
||||
WARPBOX_READ_HEADER_TIMEOUT=15s
|
||||
WARPBOX_READ_TIMEOUT=0s
|
||||
WARPBOX_WRITE_TIMEOUT=0s
|
||||
```
|
||||
|
||||
Example `/etc/systemd/system/warpbox.service`:
|
||||
@@ -142,7 +320,23 @@ sudo systemctl status warpbox
|
||||
|
||||
Put Caddy in front of `127.0.0.1:6070` and keep the Warpbox port closed to the public internet.
|
||||
|
||||
## Layout
|
||||
## Runtime data
|
||||
|
||||
Warpbox keeps local runtime data under the configured data directory:
|
||||
|
||||
- `data/files/{box_id}/@each@{file_id}.ext` - uploaded file contents when the local backend is selected.
|
||||
- `data/files/{box_id}/@thumb@{file_id}.jpg` - generated previews when the local backend is selected.
|
||||
- `data/tmp/uploads/{session_id}` - temporary local chunks for unfinished resumable uploads when
|
||||
the default chunk mode is selected.
|
||||
- `data/db/warpbox.bbolt` - bbolt metadata database for boxes, file records, users, sessions,
|
||||
invites, collections, upload policy settings, daily usage records, manual bans, automatic ban
|
||||
settings, abuse counters, and malicious path rules.
|
||||
- `data/logs/{YYYY-MM-DD}.log` - JSONL logs, one event per line.
|
||||
|
||||
Uploaded file content, thumbnails, and private box metadata use the selected storage backend. The
|
||||
bbolt database and JSON logs always remain local under `./data/db` and `./data/logs`.
|
||||
|
||||
## Project layout
|
||||
|
||||
- `backend/cmd/warpbox` - main application entry point.
|
||||
- `backend/libs/config` - environment-backed configuration.
|
||||
@@ -150,7 +344,7 @@ Put Caddy in front of `127.0.0.1:6070` and keep the Warpbox port closed to the p
|
||||
- `backend/libs/handlers` - HTTP handlers for pages, API, health, static files.
|
||||
- `backend/libs/jobs` - background job registration and job loop definitions.
|
||||
- `backend/libs/middleware` - request logging, recovery, security headers, gzip, request IDs.
|
||||
- `backend/libs/services` - business logic boundaries, starting with upload limits.
|
||||
- `backend/libs/services` - business logic boundaries.
|
||||
- `backend/libs/helpers` - small reusable helpers.
|
||||
- `backend/libs/web` - Go template renderer.
|
||||
- `backend/templates` - server-rendered Go templates.
|
||||
@@ -159,79 +353,7 @@ Put Caddy in front of `127.0.0.1:6070` and keep the Warpbox port closed to the p
|
||||
- `scripts/env/dev.env.example` - tracked development environment template.
|
||||
- `scripts/env/dev.env` - local development environment, ignored by git.
|
||||
|
||||
## Stage 2 Operator Tools
|
||||
## Static asset policy
|
||||
|
||||
- `/admin/login` - token-based admin login.
|
||||
- `/admin` - overview metrics: boxes, files, storage, recent uploads, protected/expired boxes.
|
||||
- `/admin/files` - recent upload table with view and delete actions.
|
||||
- Expired boxes and boxes that have reached their download limit are cleaned on startup and then every `WARPBOX_CLEANUP_EVERY` when `WARPBOX_CLEANUP_ENABLED=true`.
|
||||
- Missing image/video thumbnails are generated in a background worker every `WARPBOX_THUMBNAIL_EVERY` when `WARPBOX_THUMBNAIL_ENABLED=true`.
|
||||
|
||||
## Stage 3 Anonymous Integrations
|
||||
|
||||
Anonymous uploads now return a private management link at creation time. Keep that link secret:
|
||||
anyone with it can delete the entire upload box. The raw delete token is not stored and cannot be
|
||||
recovered later.
|
||||
|
||||
Browser uploads still show `Open box` and `Copy URL` as the primary actions, with a smaller
|
||||
`Manage or delete this upload` link in the completion panel.
|
||||
|
||||
Curl and custom uploaders can use the same endpoint:
|
||||
|
||||
```bash
|
||||
# Terminal-friendly output: one plain box URL.
|
||||
curl -F file=@./report.pdf http://localhost:8080/api/v1/upload
|
||||
|
||||
# JSON output with boxUrl, manageUrl, deleteUrl, zipUrl, and file entries.
|
||||
curl -F sharex=@./screenshot.png \
|
||||
-H 'Accept: application/json' \
|
||||
http://localhost:8080/api/v1/upload
|
||||
```
|
||||
|
||||
The upload endpoint accepts multipart fields named `file` and `sharex`. ShareX users can start
|
||||
from `examples/sharex/warpbox-anonymous.sxcu`; update `RequestURL` to match your instance URL.
|
||||
|
||||
## Stage 4 Accounts + Personal Boxes
|
||||
|
||||
- `/register` bootstraps the first admin account only when no users exist.
|
||||
- `/login` and `/logout` provide cookie-based web sessions.
|
||||
- `/app` is the personal dashboard for logged-in users, showing owned boxes, storage usage, upload
|
||||
history, and flat collections. Uploading still happens from the homepage.
|
||||
- `/admin/users` lets admins create invite links, disable/reactivate users, and generate reset links.
|
||||
- Logged-in browser uploads from `/` still use `POST /api/v1/upload`, but the resulting box is
|
||||
stored with owner and optional collection metadata.
|
||||
- Admin users are exempt from the global max upload size on the homepage upload flow. Future
|
||||
per-user quotas should apply to this same upload path rather than creating a second uploader.
|
||||
- `/admin/settings` controls anonymous uploads, anonymous max upload size, daily upload caps, default
|
||||
user storage quota, and usage retention.
|
||||
- `/admin/users` shows storage/daily usage and lets admins set per-user storage quota overrides.
|
||||
- `/admin/storage` manages the built-in local file backend and S3-compatible bucket backends.
|
||||
- `/admin/bans` manages manual IP/CIDR bans and optional automatic bans for suspicious probes and
|
||||
repeated login failures. Auto-ban is off by default and configured from the admin UI.
|
||||
- Upload limits now include daily bytes, daily box counts, active box counts, short-window request
|
||||
limits, max expiration days, local storage capacity in GB, and per-user policy overrides.
|
||||
- Uploaded file content, thumbnails, and private box metadata use the selected storage backend.
|
||||
The bbolt database and JSON logs remain local under `./data/db` and `./data/logs`.
|
||||
- Anonymous uploads, ShareX uploads, unlisted public box links, password protection, expiry, delete
|
||||
tokens, thumbnails, and cleanup continue to work as before.
|
||||
|
||||
Email delivery is intentionally deferred. Invite and reset links are copyable today; future SMTP
|
||||
support will power public forgot-password and optional email delivery.
|
||||
|
||||
## Runtime Data
|
||||
|
||||
Warpbox keeps local runtime data under the configured data directory:
|
||||
|
||||
- `data/files/{box_id}/@each@{file_id}.ext` - uploaded file contents when the local backend is selected.
|
||||
- `data/files/{box_id}/@thumb@{file_id}.jpg` - generated previews when the local backend is selected.
|
||||
- `data/db/warpbox.bbolt` - bbolt metadata database for boxes and file records.
|
||||
- `data/db/warpbox.bbolt` also stores users, sessions, invites, and collections.
|
||||
- `data/db/warpbox.bbolt` stores upload policy settings and daily usage records keyed by plain IP
|
||||
for anonymous uploads and user ID for signed-in uploads.
|
||||
- `data/db/warpbox.bbolt` stores manual bans, automatic ban settings, abuse counters, and malicious
|
||||
path rules.
|
||||
- `data/logs/{YYYY-MM-DD}.log` - JSONL logs, one event per line.
|
||||
|
||||
## Static Asset Policy
|
||||
|
||||
The static handler sets long-lived immutable caching for images, video, audio, and fonts, shorter caching for CSS/JS, and gzip compression for compressible responses.
|
||||
The static handler sets long-lived immutable caching for images, video, audio, and fonts, shorter
|
||||
caching for CSS/JS, and gzip compression for compressible responses.
|
||||
|
||||
@@ -24,10 +24,10 @@ public internet.
|
||||
## Trusted Proxies
|
||||
|
||||
For stricter deployments, set `WARPBOX_TRUSTED_PROXIES` to the IPs or CIDR
|
||||
ranges that are allowed to provide forwarded headers:
|
||||
ranges that are allowed to provide forwarded headers. Use proxy IPs only.
|
||||
|
||||
```env
|
||||
WARPBOX_TRUSTED_PROXIES=127.0.0.1,::1,172.16.0.0/12,10.0.0.0/8
|
||||
WARPBOX_TRUSTED_PROXIES=127.0.0.1,::1,172.30.0.1
|
||||
```
|
||||
|
||||
When this value is set, Warpbox trusts `X-Forwarded-For` and `X-Real-IP` only
|
||||
@@ -37,9 +37,15 @@ directly from any other IP ignore forwarded headers and use the socket address.
|
||||
Recommended values:
|
||||
|
||||
- Same-host Caddy with systemd: `127.0.0.1,::1`
|
||||
- Docker bridge networks: add the bridge CIDR, often `172.16.0.0/12`
|
||||
- Docker/Podman bridge gateway: add the exact gateway IP, for example `172.30.0.1`
|
||||
- Docker bridge networks: use a CIDR such as `172.16.0.0/12` only if the exact gateway changes often
|
||||
- Private reverse-proxy networks: add the exact private CIDR used by the proxy
|
||||
|
||||
Warpbox prefers the first public address in `X-Forwarded-For` when a trusted
|
||||
proxy sends a chain. Loopback addresses and trusted proxy addresses are also
|
||||
protected from manual and automatic bans so a bad header setup cannot ban Caddy,
|
||||
the container gateway, or Warpbox itself.
|
||||
|
||||
## Direct Exposure
|
||||
|
||||
If you expose Warpbox directly without Caddy, either leave
|
||||
@@ -48,6 +54,24 @@ network edge, or set it to a value that does not include public clients. Direct
|
||||
public exposure is not recommended; use a reverse proxy for TLS and request
|
||||
normalization.
|
||||
|
||||
## Large Uploads
|
||||
|
||||
Multi-GB uploads must not use whole-body read/write deadlines. Keep these
|
||||
Warpbox values for production unless you intentionally want a hard wall-clock
|
||||
upload limit:
|
||||
|
||||
```env
|
||||
WARPBOX_READ_HEADER_TIMEOUT=15s
|
||||
WARPBOX_READ_TIMEOUT=0s
|
||||
WARPBOX_WRITE_TIMEOUT=0s
|
||||
```
|
||||
|
||||
`WARPBOX_READ_HEADER_TIMEOUT` protects request headers. `WARPBOX_READ_TIMEOUT`
|
||||
and `WARPBOX_WRITE_TIMEOUT` cover the whole upload/response lifetime in Go, so
|
||||
small values can cause browser errors such as `NS_ERROR_NET_INTERRUPT` during
|
||||
large transfers. Upload size, daily, storage, and box limits still enforce abuse
|
||||
controls independently of these timeout values.
|
||||
|
||||
## Ban Behavior
|
||||
|
||||
Active bans return:
|
||||
|
||||
@@ -11,26 +11,30 @@ import (
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
AppName string
|
||||
AppVersion string
|
||||
Environment string
|
||||
Addr string
|
||||
BaseURL string
|
||||
DataDir string
|
||||
AdminToken string
|
||||
StaticDir string
|
||||
TemplateDir string
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
IdleTimeout time.Duration
|
||||
TrustedProxies []string
|
||||
JobsEnabled bool
|
||||
CleanupEnabled bool
|
||||
CleanupEvery time.Duration
|
||||
ThumbnailEnabled bool
|
||||
ThumbnailEvery time.Duration
|
||||
MaxUploadSize int64
|
||||
DefaultSettings SettingsDefaults
|
||||
AppName string
|
||||
AppVersion string
|
||||
Environment string
|
||||
Addr string
|
||||
BaseURL string
|
||||
DataDir string
|
||||
AdminToken string
|
||||
StaticDir string
|
||||
TemplateDir string
|
||||
ReadHeaderTimeout time.Duration
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
IdleTimeout time.Duration
|
||||
TrustedProxies []string
|
||||
JobsEnabled bool
|
||||
CleanupEnabled bool
|
||||
CleanupEvery time.Duration
|
||||
ThumbnailEnabled bool
|
||||
ThumbnailEvery time.Duration
|
||||
ResumableUploadsEnabled bool
|
||||
ResumableChunkSize int64
|
||||
ResumableRetention time.Duration
|
||||
MaxUploadSize int64
|
||||
DefaultSettings SettingsDefaults
|
||||
}
|
||||
|
||||
type SettingsDefaults struct {
|
||||
@@ -51,29 +55,38 @@ type SettingsDefaults struct {
|
||||
ShortWindowSeconds int
|
||||
AnonymousStorageBackend string
|
||||
UserStorageBackend string
|
||||
ResumableUploadsEnabled bool
|
||||
ResumableChunkSizeMB float64
|
||||
ResumableRetentionHours int
|
||||
ResumableChunkMode string
|
||||
ResumableChunkPath string
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
cfg := Config{
|
||||
AppName: envString("WARPBOX_APP_NAME", "warpbox.dev"),
|
||||
AppVersion: envString("APP_VERSION", "dev"),
|
||||
Environment: envString("WARPBOX_ENV", "development"),
|
||||
Addr: envString("WARPBOX_ADDR", ":8080"),
|
||||
BaseURL: strings.TrimRight(envString("WARPBOX_BASE_URL", "http://localhost:8080"), "/"),
|
||||
DataDir: envString("WARPBOX_DATA_DIR", defaultPath("data")),
|
||||
AdminToken: envString("WARPBOX_ADMIN_TOKEN", ""),
|
||||
StaticDir: envString("WARPBOX_STATIC_DIR", defaultPath("static")),
|
||||
TemplateDir: envString("WARPBOX_TEMPLATE_DIR", defaultPath("templates")),
|
||||
ReadTimeout: envDuration("WARPBOX_READ_TIMEOUT", 15*time.Second),
|
||||
WriteTimeout: envDuration("WARPBOX_WRITE_TIMEOUT", 60*time.Second),
|
||||
IdleTimeout: envDuration("WARPBOX_IDLE_TIMEOUT", 120*time.Second),
|
||||
TrustedProxies: envCSV("WARPBOX_TRUSTED_PROXIES"),
|
||||
JobsEnabled: envBool("WARPBOX_JOBS_ENABLED", true),
|
||||
CleanupEnabled: envBool("WARPBOX_CLEANUP_ENABLED", true),
|
||||
CleanupEvery: envDuration("WARPBOX_CLEANUP_EVERY", time.Hour),
|
||||
ThumbnailEnabled: envBool("WARPBOX_THUMBNAIL_ENABLED", true),
|
||||
ThumbnailEvery: envDuration("WARPBOX_THUMBNAIL_EVERY", time.Minute),
|
||||
MaxUploadSize: envMegabytes("WARPBOX_MAX_UPLOAD_SIZE_MB", 2048), // 2 GiB default.
|
||||
AppName: envString("WARPBOX_APP_NAME", "warpbox.dev"),
|
||||
AppVersion: envString("APP_VERSION", "dev"),
|
||||
Environment: envString("WARPBOX_ENV", "development"),
|
||||
Addr: envString("WARPBOX_ADDR", ":8080"),
|
||||
BaseURL: strings.TrimRight(envString("WARPBOX_BASE_URL", "http://localhost:8080"), "/"),
|
||||
DataDir: envString("WARPBOX_DATA_DIR", defaultPath("data")),
|
||||
AdminToken: envString("WARPBOX_ADMIN_TOKEN", ""),
|
||||
StaticDir: envString("WARPBOX_STATIC_DIR", defaultPath("static")),
|
||||
TemplateDir: envString("WARPBOX_TEMPLATE_DIR", defaultPath("templates")),
|
||||
ReadHeaderTimeout: envDuration("WARPBOX_READ_HEADER_TIMEOUT", 15*time.Second),
|
||||
ReadTimeout: envDuration("WARPBOX_READ_TIMEOUT", 0),
|
||||
WriteTimeout: envDuration("WARPBOX_WRITE_TIMEOUT", 0),
|
||||
IdleTimeout: envDuration("WARPBOX_IDLE_TIMEOUT", 120*time.Second),
|
||||
TrustedProxies: envCSV("WARPBOX_TRUSTED_PROXIES"),
|
||||
JobsEnabled: envBool("WARPBOX_JOBS_ENABLED", true),
|
||||
CleanupEnabled: envBool("WARPBOX_CLEANUP_ENABLED", true),
|
||||
CleanupEvery: envDuration("WARPBOX_CLEANUP_EVERY", time.Hour),
|
||||
ThumbnailEnabled: envBool("WARPBOX_THUMBNAIL_ENABLED", true),
|
||||
ThumbnailEvery: envDuration("WARPBOX_THUMBNAIL_EVERY", time.Minute),
|
||||
ResumableUploadsEnabled: envBool("WARPBOX_RESUMABLE_UPLOADS_ENABLED", true),
|
||||
ResumableChunkSize: envMegabytes("WARPBOX_RESUMABLE_CHUNK_MB", 8),
|
||||
ResumableRetention: time.Duration(envInt("WARPBOX_RESUMABLE_RETENTION_HOURS", 24)) * time.Hour,
|
||||
MaxUploadSize: envMegabytes("WARPBOX_MAX_UPLOAD_SIZE_MB", 2048), // 2 GiB default.
|
||||
DefaultSettings: SettingsDefaults{
|
||||
AnonymousUploadsEnabled: envBool("WARPBOX_ANONYMOUS_UPLOADS_ENABLED", true),
|
||||
AnonymousMaxUploadMB: envMegabytesLimitFloat("WARPBOX_ANONYMOUS_MAX_UPLOAD_MB", 512),
|
||||
@@ -92,8 +105,13 @@ func Load() (Config, error) {
|
||||
ShortWindowSeconds: envInt("WARPBOX_SHORT_WINDOW_SECONDS", 60),
|
||||
AnonymousStorageBackend: envString("WARPBOX_ANONYMOUS_STORAGE_BACKEND", "local"),
|
||||
UserStorageBackend: envString("WARPBOX_USER_STORAGE_BACKEND", "local"),
|
||||
ResumableChunkMode: envString("WARPBOX_RESUMABLE_CHUNK_MODE", "same"),
|
||||
ResumableChunkPath: envString("WARPBOX_RESUMABLE_CHUNK_PATH", ""),
|
||||
},
|
||||
}
|
||||
cfg.DefaultSettings.ResumableUploadsEnabled = cfg.ResumableUploadsEnabled
|
||||
cfg.DefaultSettings.ResumableChunkSizeMB = float64(cfg.ResumableChunkSize) / 1024 / 1024
|
||||
cfg.DefaultSettings.ResumableRetentionHours = int(cfg.ResumableRetention / time.Hour)
|
||||
|
||||
if cfg.BaseURL == "" {
|
||||
return Config{}, fmt.Errorf("WARPBOX_BASE_URL cannot be empty")
|
||||
@@ -101,6 +119,12 @@ func Load() (Config, error) {
|
||||
if cfg.MaxUploadSize <= 0 {
|
||||
return Config{}, fmt.Errorf("WARPBOX_MAX_UPLOAD_SIZE_MB must be positive")
|
||||
}
|
||||
if cfg.ResumableChunkSize <= 0 {
|
||||
return Config{}, fmt.Errorf("WARPBOX_RESUMABLE_CHUNK_MB must be positive")
|
||||
}
|
||||
if cfg.ResumableRetention <= 0 {
|
||||
return Config{}, fmt.Errorf("WARPBOX_RESUMABLE_RETENTION_HOURS must be positive")
|
||||
}
|
||||
if !validUnlimitedMegabyteLimit(cfg.DefaultSettings.AnonymousMaxUploadMB) ||
|
||||
!validUnlimitedMegabyteLimit(cfg.DefaultSettings.AnonymousDailyUploadMB) ||
|
||||
!validUnlimitedMegabyteLimit(cfg.DefaultSettings.UserDailyUploadMB) ||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseMegabytes(t *testing.T) {
|
||||
tests := map[string]int64{
|
||||
@@ -49,3 +52,29 @@ func TestEnvBool(t *testing.T) {
|
||||
t.Fatalf("envBool() did not fall back to true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadDefaultsUseLargeUploadFriendlyTimeouts(t *testing.T) {
|
||||
t.Setenv("WARPBOX_BASE_URL", "http://example.test")
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load returned error: %v", err)
|
||||
}
|
||||
if cfg.ReadHeaderTimeout != 15*time.Second {
|
||||
t.Fatalf("ReadHeaderTimeout = %s, want 15s", cfg.ReadHeaderTimeout)
|
||||
}
|
||||
if cfg.ReadTimeout != 0 {
|
||||
t.Fatalf("ReadTimeout = %s, want 0 for long uploads", cfg.ReadTimeout)
|
||||
}
|
||||
if cfg.WriteTimeout != 0 {
|
||||
t.Fatalf("WriteTimeout = %s, want 0 for long uploads", cfg.WriteTimeout)
|
||||
}
|
||||
if !cfg.ResumableUploadsEnabled {
|
||||
t.Fatalf("ResumableUploadsEnabled = false, want true")
|
||||
}
|
||||
if cfg.ResumableChunkSize != 8*1024*1024 {
|
||||
t.Fatalf("ResumableChunkSize = %d, want 8 MiB", cfg.ResumableChunkSize)
|
||||
}
|
||||
if cfg.ResumableRetention != 24*time.Hour {
|
||||
t.Fatalf("ResumableRetention = %s, want 24h", cfg.ResumableRetention)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -414,6 +415,80 @@ func TestLayeredUploadLimits(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchedUploadAppendBypassesDailyBoxCreationCap(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
policy := testPolicy(t, app)
|
||||
policy.AnonymousDailyBoxes = 1
|
||||
policy.AnonymousActiveBoxes = 10
|
||||
if err := app.settingsService.UpdateUploadPolicy(policy); err != nil {
|
||||
t.Fatalf("UpdateUploadPolicy returned error: %v", err)
|
||||
}
|
||||
|
||||
first := multipartUploadRequest(t, "/api/v1/upload", "file", "first.txt", "hello")
|
||||
first.Header.Set("Accept", "application/json")
|
||||
first.Header.Set(uploadBatchHeader, "sharex-test")
|
||||
firstResponse := httptest.NewRecorder()
|
||||
app.Upload(firstResponse, first)
|
||||
if firstResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("first batched status = %d, body = %s", firstResponse.Code, firstResponse.Body.String())
|
||||
}
|
||||
|
||||
second := multipartUploadRequest(t, "/api/v1/upload", "file", "second.txt", "hello")
|
||||
second.Header.Set("Accept", "application/json")
|
||||
second.Header.Set(uploadBatchHeader, "sharex-test")
|
||||
secondResponse := httptest.NewRecorder()
|
||||
app.Upload(secondResponse, second)
|
||||
if secondResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("second batched status = %d, body = %s", secondResponse.Code, secondResponse.Body.String())
|
||||
}
|
||||
|
||||
third := multipartUploadRequest(t, "/api/v1/upload", "file", "third.txt", "hello")
|
||||
third.Header.Set("Accept", "application/json")
|
||||
thirdResponse := httptest.NewRecorder()
|
||||
app.Upload(thirdResponse, third)
|
||||
if thirdResponse.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("non-batched status = %d, body = %s", thirdResponse.Code, thirdResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchedUploadAppendBypassesActiveBoxCreationCap(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
policy := testPolicy(t, app)
|
||||
policy.AnonymousDailyBoxes = 10
|
||||
policy.AnonymousActiveBoxes = 1
|
||||
if err := app.settingsService.UpdateUploadPolicy(policy); err != nil {
|
||||
t.Fatalf("UpdateUploadPolicy returned error: %v", err)
|
||||
}
|
||||
|
||||
first := multipartUploadRequest(t, "/api/v1/upload", "file", "first.txt", "hello")
|
||||
first.Header.Set("Accept", "application/json")
|
||||
first.Header.Set(uploadBatchHeader, "active-cap")
|
||||
firstResponse := httptest.NewRecorder()
|
||||
app.Upload(firstResponse, first)
|
||||
if firstResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("first batched status = %d, body = %s", firstResponse.Code, firstResponse.Body.String())
|
||||
}
|
||||
|
||||
second := multipartUploadRequest(t, "/api/v1/upload", "file", "second.txt", "hello")
|
||||
second.Header.Set("Accept", "application/json")
|
||||
second.Header.Set(uploadBatchHeader, "active-cap")
|
||||
secondResponse := httptest.NewRecorder()
|
||||
app.Upload(secondResponse, second)
|
||||
if secondResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("second batched status = %d, body = %s", secondResponse.Code, secondResponse.Body.String())
|
||||
}
|
||||
|
||||
third := multipartUploadRequest(t, "/api/v1/upload", "file", "third.txt", "hello")
|
||||
third.Header.Set("Accept", "application/json")
|
||||
thirdResponse := httptest.NewRecorder()
|
||||
app.Upload(thirdResponse, third)
|
||||
if thirdResponse.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("non-batched status = %d, body = %s", thirdResponse.Code, thirdResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserPolicyOverrideChangesUploadEnforcement(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
@@ -620,6 +695,108 @@ func TestAPIDocsHeaderReflectsLoggedOutUser(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOverviewChartsUseZeroAndFullHeights(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
today := time.Date(now.Year(), now.Month(), now.Day(), 12, 0, 0, 0, time.UTC)
|
||||
overview := buildAdminOverview([]services.AdminBox{{
|
||||
ID: "box1",
|
||||
CreatedAt: today,
|
||||
TotalSize: 1024,
|
||||
}}, services.AdminStats{TotalBoxes: 1, TotalFiles: 1, TotalSize: 1024})
|
||||
|
||||
for i, bar := range overview.UploadDays {
|
||||
want := 0
|
||||
if i == len(overview.UploadDays)-1 {
|
||||
want = 150
|
||||
}
|
||||
if bar.HeightPx != want {
|
||||
t.Fatalf("upload bar %d height = %d, want %d", i, bar.HeightPx, want)
|
||||
}
|
||||
}
|
||||
for i, bar := range overview.StorageDays {
|
||||
want := 0
|
||||
if i == len(overview.StorageDays)-1 {
|
||||
want = 150
|
||||
}
|
||||
if bar.HeightPx != want {
|
||||
t.Fatalf("storage bar %d height = %d, want %d", i, bar.HeightPx, want)
|
||||
}
|
||||
}
|
||||
if overview.StatusBars[0].WidthPercent != 100 {
|
||||
t.Fatalf("active status width = %d, want 100", overview.StatusBars[0].WidthPercent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOverviewChartsScaleRelativeToVisibleRange(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
today := time.Date(now.Year(), now.Month(), now.Day(), 12, 0, 0, 0, time.UTC)
|
||||
yesterday := today.AddDate(0, 0, -1)
|
||||
twoDaysAgo := today.AddDate(0, 0, -2)
|
||||
boxes := []services.AdminBox{
|
||||
{ID: "today-1", CreatedAt: today, TotalSize: 30},
|
||||
{ID: "today-2", CreatedAt: today, TotalSize: 30},
|
||||
{ID: "today-3", CreatedAt: today, TotalSize: 30},
|
||||
{ID: "yesterday-1", CreatedAt: yesterday, TotalSize: 20},
|
||||
{ID: "yesterday-2", CreatedAt: yesterday, TotalSize: 20},
|
||||
{ID: "two-days-ago", CreatedAt: twoDaysAgo, TotalSize: 10},
|
||||
}
|
||||
overview := buildAdminOverview(boxes, services.AdminStats{TotalBoxes: 6, ExpiredBoxes: 2, ProtectedBoxes: 1})
|
||||
|
||||
last := len(overview.UploadDays) - 1
|
||||
if overview.UploadDays[last].HeightPx != 150 {
|
||||
t.Fatalf("3-upload day height = %d, want 150", overview.UploadDays[last].HeightPx)
|
||||
}
|
||||
if overview.UploadDays[last-1].HeightPx != 100 {
|
||||
t.Fatalf("2-upload day height = %d, want 100", overview.UploadDays[last-1].HeightPx)
|
||||
}
|
||||
if overview.UploadDays[last-2].HeightPx != 50 {
|
||||
t.Fatalf("1-upload day height = %d, want 50", overview.UploadDays[last-2].HeightPx)
|
||||
}
|
||||
if overview.StorageDays[last].HeightPx != 150 || overview.StorageDays[last-1].HeightPx != 66 || overview.StorageDays[last-2].HeightPx != 16 {
|
||||
t.Fatalf("storage heights = %d/%d/%d, want 150/66/16", overview.StorageDays[last].HeightPx, overview.StorageDays[last-1].HeightPx, overview.StorageDays[last-2].HeightPx)
|
||||
}
|
||||
if overview.StatusBars[0].WidthPercent != 100 || overview.StatusBars[1].WidthPercent != 50 || overview.StatusBars[2].WidthPercent != 25 {
|
||||
t.Fatalf("status widths = %d/%d/%d, want 100/50/25", overview.StatusBars[0].WidthPercent, overview.StatusBars[1].WidthPercent, overview.StatusBars[2].WidthPercent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOverviewRendersInlineBarDimensions(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
adminToken := createAdminSession(t, app)
|
||||
uploadThroughApp(t, app)
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/admin", nil)
|
||||
request.AddCookie(&http.Cookie{Name: userSessionCookieName, Value: adminToken})
|
||||
response := httptest.NewRecorder()
|
||||
app.AdminDashboard(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("AdminDashboard status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
body := response.Body.String()
|
||||
if !strings.Contains(body, `style="height: 150px"`) {
|
||||
t.Fatalf("admin overview did not render a full-height pixel bar: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, `data-height-px="150"`) || !strings.Contains(body, `data-chart-value=`) {
|
||||
t.Fatalf("admin overview did not render chart fallback data attributes: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, `style="height: 0px"`) {
|
||||
t.Fatalf("admin overview did not render zero pixel bars: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, `style="width: 100%"`) {
|
||||
t.Fatalf("admin overview did not render a full-width status bar: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, `data-width-percent="100"`) || !strings.Contains(body, `data-stat-value=`) {
|
||||
t.Fatalf("admin overview did not render status fallback data attributes: %s", body)
|
||||
}
|
||||
if strings.Contains(body, "--bar-height") {
|
||||
t.Fatalf("admin overview still uses css variable bar heights: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, "/static/js/25-admin-charts.js?version=test") {
|
||||
t.Fatalf("admin overview did not load chart fallback script: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminStorageProviderPagesOnlyRenderRelevantFields(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
@@ -731,6 +908,101 @@ func TestAdminStorageJobRoutesRequireAdminAndCSRF(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminStorageDeleteAction(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
adminToken := createAdminSession(t, app)
|
||||
cfg, err := app.uploadService.Storage().CreateBackend(services.StorageBackendConfig{
|
||||
Provider: services.StorageProviderWebDAV,
|
||||
Name: "DAV",
|
||||
Endpoint: "https://dav.example.test",
|
||||
Username: "warpbox",
|
||||
Password: "secret",
|
||||
RemotePath: "/warpbox",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateBackend returned error: %v", err)
|
||||
}
|
||||
|
||||
deleteRequest := httptest.NewRequest(http.MethodPost, "/admin/storage/"+cfg.ID+"/delete", strings.NewReader("csrf_token=test-csrf"))
|
||||
deleteRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
deleteRequest.AddCookie(&http.Cookie{Name: userSessionCookieName, Value: adminToken})
|
||||
deleteRequest.AddCookie(&http.Cookie{Name: csrfCookieName, Value: "test-csrf"})
|
||||
deleteRequest.SetPathValue("backendID", cfg.ID)
|
||||
deleteResponse := httptest.NewRecorder()
|
||||
app.AdminDeleteStorage(deleteResponse, deleteRequest)
|
||||
if deleteResponse.Code != http.StatusSeeOther {
|
||||
t.Fatalf("AdminDeleteStorage status = %d, body = %s", deleteResponse.Code, deleteResponse.Body.String())
|
||||
}
|
||||
if _, err := app.uploadService.Storage().BackendConfig(cfg.ID); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("BackendConfig after delete = %v, want not exist", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminStorageDeleteResetsDefaultsAndUserOverrides(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
adminToken := createAdminSession(t, app)
|
||||
user, err := app.authService.UserByEmail("admin@example.test")
|
||||
if err != nil {
|
||||
t.Fatalf("UserByEmail returned error: %v", err)
|
||||
}
|
||||
cfg, err := app.uploadService.Storage().CreateBackend(services.StorageBackendConfig{
|
||||
Provider: services.StorageProviderWebDAV,
|
||||
Name: "DAV",
|
||||
Endpoint: "https://dav.example.test",
|
||||
Username: "warpbox",
|
||||
Password: "secret",
|
||||
RemotePath: "/warpbox",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateBackend returned error: %v", err)
|
||||
}
|
||||
settings, err := app.settingsService.UploadPolicy()
|
||||
if err != nil {
|
||||
t.Fatalf("UploadPolicy returned error: %v", err)
|
||||
}
|
||||
settings.UserStorageBackend = cfg.ID
|
||||
if err := app.settingsService.UpdateUploadPolicy(settings); err != nil {
|
||||
t.Fatalf("UpdateUploadPolicy returned error: %v", err)
|
||||
}
|
||||
if err := app.authService.SetUserStorageBackend(user.ID, cfg.ID); err != nil {
|
||||
t.Fatalf("SetUserStorageBackend returned error: %v", err)
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodPost, "/admin/storage/"+cfg.ID+"/delete", strings.NewReader("csrf_token=test-csrf"))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.AddCookie(&http.Cookie{Name: userSessionCookieName, Value: adminToken})
|
||||
request.AddCookie(&http.Cookie{Name: csrfCookieName, Value: "test-csrf"})
|
||||
request.SetPathValue("backendID", cfg.ID)
|
||||
response := httptest.NewRecorder()
|
||||
app.AdminDeleteStorage(response, request)
|
||||
if response.Code != http.StatusSeeOther {
|
||||
t.Fatalf("AdminDeleteStorage status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
location := response.Header().Get("Location")
|
||||
if !strings.Contains(location, "Storage+backend+deleted") || !strings.Contains(location, "cleared+1+user+overrides") {
|
||||
t.Fatalf("delete redirect did not include cascade notice: %s", location)
|
||||
}
|
||||
if _, err := app.uploadService.Storage().BackendConfig(cfg.ID); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("BackendConfig after delete = %v, want not exist", err)
|
||||
}
|
||||
nextSettings, err := app.settingsService.UploadPolicy()
|
||||
if err != nil {
|
||||
t.Fatalf("UploadPolicy returned error: %v", err)
|
||||
}
|
||||
if nextSettings.UserStorageBackend != services.StorageBackendLocal {
|
||||
t.Fatalf("UserStorageBackend = %q, want local", nextSettings.UserStorageBackend)
|
||||
}
|
||||
nextUser, err := app.authService.UserByID(user.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("UserByID returned error: %v", err)
|
||||
}
|
||||
if nextUser.Policy.StorageBackendID != nil {
|
||||
t.Fatalf("user storage override was not cleared: %+v", nextUser.Policy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminStorageSpeedTestStartsBackgroundJob(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
@@ -814,8 +1086,13 @@ func TestAdminLogsAndBansPagesRender(t *testing.T) {
|
||||
t.Fatalf("MkdirAll returned error: %v", err)
|
||||
}
|
||||
logPath := filepath.Join(logDir, "2026-05-31.log")
|
||||
line := `{"date":"2026-05-31","time":"12:34:56","source":"user-upload","severity":"user_activity","code":2001,"log":"upload response sent","ip":"127.0.0.1","box_id":"box123"}` + "\n"
|
||||
if err := os.WriteFile(logPath, []byte(line), 0o644); err != nil {
|
||||
lines := strings.Join([]string{
|
||||
`{"date":"2026-05-31","time":"12:34:56","source":"user-upload","severity":"user_activity","code":2001,"log":"upload response sent","ip":"127.0.0.1","box_id":"box123"}`,
|
||||
`{"date":"2026-05-31","time":"12:35:56","source":"http","severity":"dev","code":200,"log":"http request","remote_addr":"172.30.0.1:48358","box_id":"box456"}`,
|
||||
`{"date":"2026-05-31","time":"12:36:56","source":"http","severity":"dev","code":200,"log":"http request","method":"GET","path":"/health","ip":"127.0.0.1","user_agent":"Wget"}`,
|
||||
"",
|
||||
}, "\n")
|
||||
if err := os.WriteFile(logPath, []byte(lines), 0o644); err != nil {
|
||||
t.Fatalf("WriteFile returned error: %v", err)
|
||||
}
|
||||
|
||||
@@ -830,6 +1107,19 @@ func TestAdminLogsAndBansPagesRender(t *testing.T) {
|
||||
if !strings.Contains(logsBody, "upload response sent") || !strings.Contains(logsBody, "box123") {
|
||||
t.Fatalf("AdminLogs missing expected log entry: %s", logsBody)
|
||||
}
|
||||
if strings.Contains(logsBody, "172.30.0.1:48358") {
|
||||
t.Fatalf("AdminLogs rendered remote address with port: %s", logsBody)
|
||||
}
|
||||
healthRequest := httptest.NewRequest(http.MethodGet, "/admin/logs", nil)
|
||||
healthRequest.AddCookie(&http.Cookie{Name: userSessionCookieName, Value: adminToken})
|
||||
healthResponse := httptest.NewRecorder()
|
||||
app.AdminLogs(healthResponse, healthRequest)
|
||||
if healthResponse.Code != http.StatusOK {
|
||||
t.Fatalf("AdminLogs health status = %d, body = %s", healthResponse.Code, healthResponse.Body.String())
|
||||
}
|
||||
if strings.Contains(healthResponse.Body.String(), "/health") || strings.Contains(healthResponse.Body.String(), "Wget") {
|
||||
t.Fatalf("AdminLogs rendered container health ping: %s", healthResponse.Body.String())
|
||||
}
|
||||
|
||||
bansRequest := httptest.NewRequest(http.MethodGet, "/admin/bans", nil)
|
||||
bansRequest.AddCookie(&http.Cookie{Name: userSessionCookieName, Value: adminToken})
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"warpbox.dev/backend/libs/helpers"
|
||||
"warpbox.dev/backend/libs/jobs"
|
||||
"warpbox.dev/backend/libs/services"
|
||||
"warpbox.dev/backend/libs/web"
|
||||
@@ -36,6 +37,7 @@ type adminPageData struct {
|
||||
StorageTypes []adminStorageProviderView
|
||||
Logs adminLogsView
|
||||
Bans adminBansView
|
||||
Overview adminOverview
|
||||
Section string
|
||||
PageTitle string
|
||||
LastInviteURL string
|
||||
@@ -44,16 +46,32 @@ type adminPageData struct {
|
||||
}
|
||||
|
||||
type adminLogsView struct {
|
||||
Entries []adminLogEntry
|
||||
Dates []string
|
||||
Date string
|
||||
Severity string
|
||||
Source string
|
||||
Query string
|
||||
Sort string
|
||||
TotalShown int
|
||||
Entries []adminLogEntry
|
||||
Dates []string
|
||||
Date string
|
||||
Severity string
|
||||
Source string
|
||||
Query string
|
||||
Sort string
|
||||
TotalShown int
|
||||
Total int
|
||||
Page int
|
||||
PerPage int
|
||||
PerPageOptions []int
|
||||
TotalPages int
|
||||
RangeFrom int
|
||||
RangeTo int
|
||||
PageLinks []adminFilesPageLink
|
||||
HasPrev bool
|
||||
HasNext bool
|
||||
PrevHref string
|
||||
NextHref string
|
||||
}
|
||||
|
||||
var adminLogsPageSizes = []int{50, 100, 250, 500}
|
||||
|
||||
const adminLogsDefaultPageSize = 100
|
||||
|
||||
type adminLogEntry struct {
|
||||
Date string
|
||||
Time string
|
||||
@@ -134,6 +152,26 @@ type adminStorageProviderView struct {
|
||||
Icon string
|
||||
}
|
||||
|
||||
type adminOverview struct {
|
||||
UploadDays []adminChartBar
|
||||
StorageDays []adminChartBar
|
||||
StatusBars []adminStatBar
|
||||
}
|
||||
|
||||
type adminChartBar struct {
|
||||
Label string
|
||||
Value string
|
||||
HeightPx int
|
||||
RawValue int64
|
||||
}
|
||||
|
||||
type adminStatBar struct {
|
||||
Label string
|
||||
Value string
|
||||
RawValue int
|
||||
WidthPercent int
|
||||
}
|
||||
|
||||
type adminBoxView struct {
|
||||
ID string
|
||||
Owner string
|
||||
@@ -248,52 +286,157 @@ func (a *App) AdminDashboard(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "unable to load admin stats", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
boxes, err := a.adminBoxes(8)
|
||||
allBoxes, err := a.uploadService.AdminBoxes(0)
|
||||
if err != nil {
|
||||
http.Error(w, "unable to load recent boxes", http.StatusInternalServerError)
|
||||
http.Error(w, "unable to load boxes", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
overview := buildAdminOverview(allBoxes, stats)
|
||||
recent := a.recentBoxViews(allBoxes, 8)
|
||||
|
||||
a.renderPage(w, r, http.StatusOK, "admin.html", web.PageData{
|
||||
Title: "Admin overview",
|
||||
Description: "Warpbox admin overview.",
|
||||
CurrentUser: a.currentPublicUser(r),
|
||||
Data: adminPageData{
|
||||
Stats: stats,
|
||||
Boxes: boxes,
|
||||
Boxes: recent,
|
||||
Overview: overview,
|
||||
Section: "overview",
|
||||
PageTitle: "Admin overview",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) AdminFiles(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.requireAdmin(w, r) {
|
||||
return
|
||||
// recentBoxViews renders the newest boxes (already sorted newest-first by the
|
||||
// service) into display rows, resolving owner labels.
|
||||
func (a *App) recentBoxViews(boxes []services.AdminBox, limit int) []adminBoxView {
|
||||
if limit > 0 && len(boxes) > limit {
|
||||
boxes = boxes[:limit]
|
||||
}
|
||||
cache := map[string]string{}
|
||||
rows := make([]adminBoxView, 0, len(boxes))
|
||||
for _, box := range boxes {
|
||||
rows = append(rows, adminBoxView{
|
||||
ID: box.ID,
|
||||
Owner: a.boxOwnerLabel(box.OwnerID, cache),
|
||||
CreatedAt: box.CreatedAt.Format("Jan 2, 2006 15:04"),
|
||||
ExpiresAt: boxExpiryLabel(box.ExpiresAt, "Jan 2, 2006 15:04"),
|
||||
FileCount: box.FileCount,
|
||||
TotalSizeLabel: box.TotalSizeLabel,
|
||||
DownloadCount: box.DownloadCount,
|
||||
MaxDownloads: box.MaxDownloads,
|
||||
Protected: box.Protected,
|
||||
Expired: box.Expired,
|
||||
})
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// buildAdminOverview computes the last-14-day upload/storage series plus a few
|
||||
// status distributions for the overview dashboard.
|
||||
func buildAdminOverview(boxes []services.AdminBox, stats services.AdminStats) adminOverview {
|
||||
const days = 14
|
||||
const chartMaxHeightPx = 150
|
||||
now := time.Now().UTC()
|
||||
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
|
||||
|
||||
counts := make([]int, days)
|
||||
bytes := make([]int64, days)
|
||||
labels := make([]string, days)
|
||||
for i := 0; i < days; i++ {
|
||||
day := today.AddDate(0, 0, -(days - 1 - i))
|
||||
labels[i] = day.Format("Jan 2")
|
||||
}
|
||||
|
||||
stats, err := a.uploadService.AdminStats()
|
||||
if err != nil {
|
||||
http.Error(w, "unable to load admin stats", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
boxes, err := a.adminBoxes(100)
|
||||
if err != nil {
|
||||
http.Error(w, "unable to load boxes", http.StatusInternalServerError)
|
||||
return
|
||||
for _, box := range boxes {
|
||||
created := box.CreatedAt.UTC()
|
||||
day := time.Date(created.Year(), created.Month(), created.Day(), 0, 0, 0, 0, time.UTC)
|
||||
offset := int(today.Sub(day).Hours() / 24)
|
||||
idx := days - 1 - offset
|
||||
if idx < 0 || idx >= days {
|
||||
continue
|
||||
}
|
||||
counts[idx]++
|
||||
bytes[idx] += box.TotalSize
|
||||
}
|
||||
|
||||
a.renderPage(w, r, http.StatusOK, "admin.html", web.PageData{
|
||||
Title: "Admin files",
|
||||
Description: "Manage Warpbox uploads.",
|
||||
CurrentUser: a.currentPublicUser(r),
|
||||
Data: adminPageData{
|
||||
Stats: stats,
|
||||
Boxes: boxes,
|
||||
Section: "files",
|
||||
PageTitle: "Admin files",
|
||||
},
|
||||
})
|
||||
maxCount := 0
|
||||
var maxBytes int64
|
||||
for i := 0; i < days; i++ {
|
||||
if counts[i] > maxCount {
|
||||
maxCount = counts[i]
|
||||
}
|
||||
if bytes[i] > maxBytes {
|
||||
maxBytes = bytes[i]
|
||||
}
|
||||
}
|
||||
|
||||
uploadDays := make([]adminChartBar, days)
|
||||
storageDays := make([]adminChartBar, days)
|
||||
for i := 0; i < days; i++ {
|
||||
uploadDays[i] = adminChartBar{
|
||||
Label: labels[i],
|
||||
Value: strconv.Itoa(counts[i]),
|
||||
HeightPx: scaleHeightPx(int64(counts[i]), int64(maxCount), chartMaxHeightPx),
|
||||
RawValue: int64(counts[i]),
|
||||
}
|
||||
storageDays[i] = adminChartBar{
|
||||
Label: labels[i],
|
||||
Value: helpers.FormatBytes(bytes[i]),
|
||||
HeightPx: scaleHeightPx(bytes[i], maxBytes, chartMaxHeightPx),
|
||||
RawValue: bytes[i],
|
||||
}
|
||||
}
|
||||
|
||||
activeBoxes := stats.TotalBoxes - stats.ExpiredBoxes
|
||||
if activeBoxes < 0 {
|
||||
activeBoxes = 0
|
||||
}
|
||||
maxStatusValue := maxInt(activeBoxes, stats.ExpiredBoxes, stats.ProtectedBoxes)
|
||||
statusBars := []adminStatBar{
|
||||
{Label: "Active", Value: strconv.Itoa(activeBoxes), RawValue: activeBoxes, WidthPercent: percentOf(activeBoxes, maxStatusValue)},
|
||||
{Label: "Expired", Value: strconv.Itoa(stats.ExpiredBoxes), RawValue: stats.ExpiredBoxes, WidthPercent: percentOf(stats.ExpiredBoxes, maxStatusValue)},
|
||||
{Label: "Password-protected", Value: strconv.Itoa(stats.ProtectedBoxes), RawValue: stats.ProtectedBoxes, WidthPercent: percentOf(stats.ProtectedBoxes, maxStatusValue)},
|
||||
}
|
||||
|
||||
return adminOverview{
|
||||
UploadDays: uploadDays,
|
||||
StorageDays: storageDays,
|
||||
StatusBars: statusBars,
|
||||
}
|
||||
}
|
||||
|
||||
func scaleHeightPx(value, max int64, maxHeightPx int) int {
|
||||
if max <= 0 || value <= 0 {
|
||||
return 0
|
||||
}
|
||||
height := int(value * int64(maxHeightPx) / max)
|
||||
if height < 8 {
|
||||
height = 8
|
||||
}
|
||||
if height > maxHeightPx {
|
||||
return maxHeightPx
|
||||
}
|
||||
return height
|
||||
}
|
||||
|
||||
func percentOf(value, total int) int {
|
||||
if total <= 0 || value <= 0 {
|
||||
return 0
|
||||
}
|
||||
return value * 100 / total
|
||||
}
|
||||
|
||||
func maxInt(values ...int) int {
|
||||
max := 0
|
||||
for _, value := range values {
|
||||
if value > max {
|
||||
max = value
|
||||
}
|
||||
}
|
||||
return max
|
||||
}
|
||||
|
||||
func (a *App) AdminUsers(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -431,6 +574,7 @@ func (a *App) AdminSettingsPost(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
settings.AnonymousUploadsEnabled = r.FormValue("anonymous_uploads_enabled") == "on"
|
||||
settings.ResumableUploadsEnabled = r.FormValue("resumable_uploads_enabled") == "on"
|
||||
if value := parsePositiveInt(r.FormValue("usage_retention_days")); value > 0 {
|
||||
settings.UsageRetentionDays = value
|
||||
}
|
||||
@@ -461,6 +605,16 @@ func (a *App) AdminSettingsPost(w http.ResponseWriter, r *http.Request) {
|
||||
if value := parsePositiveInt(r.FormValue("short_window_seconds")); value > 0 {
|
||||
settings.ShortWindowSeconds = value
|
||||
}
|
||||
if value := parsePositiveFloat(r.FormValue("resumable_chunk_size_mb")); value > 0 {
|
||||
settings.ResumableChunkSizeMB = value
|
||||
}
|
||||
if value := parsePositiveInt(r.FormValue("resumable_retention_hours")); value > 0 {
|
||||
settings.ResumableRetentionHours = value
|
||||
}
|
||||
if value := strings.TrimSpace(r.FormValue("resumable_chunk_mode")); value != "" {
|
||||
settings.ResumableChunkMode = value
|
||||
}
|
||||
settings.ResumableChunkPath = strings.TrimSpace(r.FormValue("resumable_chunk_path"))
|
||||
if value := r.FormValue("anonymous_storage_backend"); value != "" {
|
||||
settings.AnonymousStorageBackend = value
|
||||
}
|
||||
@@ -564,6 +718,10 @@ func (a *App) AdminCreateBan(w http.ResponseWriter, r *http.Request) {
|
||||
if user, ok := a.currentUser(r); ok {
|
||||
createdBy = user.ID
|
||||
}
|
||||
if services.ProtectedBanTarget(r.FormValue("target"), a.cfg.TrustedProxies) {
|
||||
http.Redirect(w, r, "/admin/bans?error="+url.QueryEscape("Refusing to ban loopback or trusted proxy addresses."), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
ban, err := a.banService.CreateManualBan(r.FormValue("target"), r.FormValue("reason"), createdBy, expiresAt.UTC())
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/admin/bans?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
||||
@@ -883,32 +1041,45 @@ func (a *App) AdminStartStorageSpeedTest(w http.ResponseWriter, r *http.Request)
|
||||
http.Redirect(w, r, "/admin/storage/"+r.PathValue("backendID")+"/tests?notice="+url.QueryEscape("Storage speed test started in the background."), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (a *App) AdminDisableStorage(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.requireAdmin(w, r) || !a.validateCSRF(w, r) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("backendID")
|
||||
inUse, _ := a.storageBackendInUse(id)
|
||||
if err := a.uploadService.Storage().DisableBackend(id, inUse); err != nil {
|
||||
http.Redirect(w, r, "/admin/storage?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
a.logger.Info("storage backend disabled", "source", "admin", "severity", "user_activity", "code", 2324, "ip", uploadClientIP(r), "backend_id", id)
|
||||
http.Redirect(w, r, "/admin/storage", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (a *App) AdminDeleteStorage(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.requireAdmin(w, r) || !a.validateCSRF(w, r) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("backendID")
|
||||
inUse, _ := a.storageBackendInUse(id)
|
||||
if err := a.uploadService.Storage().DeleteBackend(id, inUse); err != nil {
|
||||
cfg, err := a.uploadService.Storage().BackendConfig(id)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/admin/storage?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if cfg.ID == services.StorageBackendLocal {
|
||||
http.Redirect(w, r, "/admin/storage?error="+url.QueryEscape("local storage cannot be deleted"), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
deletedBoxes, err := a.uploadService.DeleteBoxesForStorageBackend(id, "storage-delete")
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/admin/storage?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
resetAnonymous, resetUsersDefault, err := a.settingsService.ResetStorageBackend(id)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/admin/storage?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
clearedUsers, err := a.authService.ClearStorageBackendOverrides(id)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/admin/storage?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if err := a.uploadService.Storage().DeleteBackend(id, false); err != nil {
|
||||
http.Redirect(w, r, "/admin/storage?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
notice := fmt.Sprintf("Storage backend deleted. Removed %d related boxes and cleared %d user overrides.", deletedBoxes, clearedUsers)
|
||||
if resetAnonymous || resetUsersDefault {
|
||||
notice += " Global storage defaults were reset to local."
|
||||
}
|
||||
a.logger.Info("storage backend deleted", "source", "admin", "severity", "user_activity", "code", 2325, "ip", uploadClientIP(r), "backend_id", id)
|
||||
http.Redirect(w, r, "/admin/storage", http.StatusSeeOther)
|
||||
http.Redirect(w, r, "/admin/storage?notice="+url.QueryEscape(notice), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (a *App) AdminRunStorageCleanup(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -1004,10 +1175,10 @@ func (a *App) AdminUpdateUserPolicy(w http.ResponseWriter, r *http.Request) {
|
||||
MaxUploadMB: optionalMB(r.FormValue("max_upload_mb")),
|
||||
DailyUploadMB: optionalMB(r.FormValue("daily_upload_mb")),
|
||||
StorageQuotaMB: optionalMBAllowZero(r.FormValue("storage_quota_mb")),
|
||||
MaxDays: optionalInt(r.FormValue("max_days")),
|
||||
DailyBoxes: optionalInt(r.FormValue("daily_boxes")),
|
||||
ActiveBoxes: optionalInt(r.FormValue("active_boxes")),
|
||||
ShortWindowRequests: optionalInt(r.FormValue("short_window_requests")),
|
||||
MaxDays: optionalIntAllowUnlimited(r.FormValue("max_days")),
|
||||
DailyBoxes: optionalIntAllowUnlimited(r.FormValue("daily_boxes")),
|
||||
ActiveBoxes: optionalIntAllowUnlimited(r.FormValue("active_boxes")),
|
||||
ShortWindowRequests: optionalIntAllowUnlimited(r.FormValue("short_window_requests")),
|
||||
}
|
||||
if backendID := r.FormValue("storage_backend_id"); backendID != "" {
|
||||
if _, err := a.uploadService.Storage().BackendConfig(backendID); err != nil {
|
||||
@@ -1036,10 +1207,10 @@ func (a *App) AdminUpdateUser(w http.ResponseWriter, r *http.Request) {
|
||||
MaxUploadMB: optionalMB(r.FormValue("max_upload_mb")),
|
||||
DailyUploadMB: optionalMB(r.FormValue("daily_upload_mb")),
|
||||
StorageQuotaMB: optionalMBAllowZero(r.FormValue("storage_quota_mb")),
|
||||
MaxDays: optionalInt(r.FormValue("max_days")),
|
||||
DailyBoxes: optionalInt(r.FormValue("daily_boxes")),
|
||||
ActiveBoxes: optionalInt(r.FormValue("active_boxes")),
|
||||
ShortWindowRequests: optionalInt(r.FormValue("short_window_requests")),
|
||||
MaxDays: optionalIntAllowUnlimited(r.FormValue("max_days")),
|
||||
DailyBoxes: optionalIntAllowUnlimited(r.FormValue("daily_boxes")),
|
||||
ActiveBoxes: optionalIntAllowUnlimited(r.FormValue("active_boxes")),
|
||||
ShortWindowRequests: optionalIntAllowUnlimited(r.FormValue("short_window_requests")),
|
||||
}
|
||||
if backendID := r.FormValue("storage_backend_id"); backendID != "" {
|
||||
if _, err := a.uploadService.Storage().BackendConfig(backendID); err != nil {
|
||||
@@ -1186,38 +1357,6 @@ func (a *App) renderAdminLogin(w http.ResponseWriter, r *http.Request, status in
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) adminBoxes(limit int) ([]adminBoxView, error) {
|
||||
boxes, err := a.uploadService.AdminBoxes(limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows := make([]adminBoxView, 0, len(boxes))
|
||||
for _, box := range boxes {
|
||||
owner := "Anonymous"
|
||||
if box.OwnerID != "" {
|
||||
if user, err := a.authService.UserByID(box.OwnerID); err == nil {
|
||||
owner = user.Email
|
||||
} else {
|
||||
owner = "User"
|
||||
}
|
||||
}
|
||||
rows = append(rows, adminBoxView{
|
||||
ID: box.ID,
|
||||
Owner: owner,
|
||||
CreatedAt: box.CreatedAt.Format("Jan 2 15:04"),
|
||||
ExpiresAt: box.ExpiresAt.Format("Jan 2 15:04"),
|
||||
FileCount: box.FileCount,
|
||||
TotalSizeLabel: box.TotalSizeLabel,
|
||||
DownloadCount: box.DownloadCount,
|
||||
MaxDownloads: box.MaxDownloads,
|
||||
Protected: box.Protected,
|
||||
Expired: box.Expired,
|
||||
})
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (a *App) requireAdmin(w http.ResponseWriter, r *http.Request) bool {
|
||||
if a.isAdmin(r) {
|
||||
return true
|
||||
@@ -1296,7 +1435,8 @@ func optionalMBAllowZero(value string) *float64 {
|
||||
return nil
|
||||
}
|
||||
parsed, err := strconv.ParseFloat(value, 64)
|
||||
if err != nil || parsed < 0 {
|
||||
// 0 and -1 both mean unlimited; reject other negatives.
|
||||
if err != nil || (parsed < 0 && parsed != -1) {
|
||||
return nil
|
||||
}
|
||||
return &parsed
|
||||
@@ -1313,6 +1453,18 @@ func optionalInt(value string) *int {
|
||||
return &parsed
|
||||
}
|
||||
|
||||
// optionalIntAllowUnlimited is like optionalInt but also accepts -1 (unlimited).
|
||||
func optionalIntAllowUnlimited(value string) *int {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || (parsed <= 0 && parsed != -1) {
|
||||
return nil
|
||||
}
|
||||
return &parsed
|
||||
}
|
||||
|
||||
func formatMB(value float64) string {
|
||||
return strconv.FormatFloat(value, 'f', -1, 64) + " MB"
|
||||
}
|
||||
@@ -1464,21 +1616,111 @@ func (a *App) adminLogsView(r *http.Request) (adminLogsView, error) {
|
||||
}
|
||||
return left > right
|
||||
})
|
||||
if len(entries) > 500 {
|
||||
entries = entries[:500]
|
||||
|
||||
perPage := normalizePageSize(r.URL.Query().Get("per"), adminLogsDefaultPageSize, adminLogsPageSizes)
|
||||
total := len(entries)
|
||||
totalPages := (total + perPage - 1) / perPage
|
||||
if totalPages < 1 {
|
||||
totalPages = 1
|
||||
}
|
||||
page := 1
|
||||
if parsed, err := strconv.Atoi(r.URL.Query().Get("page")); err == nil && parsed > 1 {
|
||||
page = parsed
|
||||
}
|
||||
if page > totalPages {
|
||||
page = totalPages
|
||||
}
|
||||
start := (page - 1) * perPage
|
||||
if start > total {
|
||||
start = total
|
||||
}
|
||||
end := start + perPage
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
rangeFrom := 0
|
||||
if total > 0 {
|
||||
rangeFrom = start + 1
|
||||
}
|
||||
|
||||
state := adminLogsQuery{
|
||||
Date: selectedDate,
|
||||
Severity: severity,
|
||||
Source: source,
|
||||
Query: r.URL.Query().Get("q"),
|
||||
Sort: sortOrder,
|
||||
Per: perPage,
|
||||
}
|
||||
links := make([]adminFilesPageLink, 0, 5)
|
||||
for p := page - 2; p <= page+2; p++ {
|
||||
if p < 1 || p > totalPages {
|
||||
continue
|
||||
}
|
||||
links = append(links, adminFilesPageLink{Page: p, Href: adminLogsHref(state, p), Active: p == page})
|
||||
}
|
||||
|
||||
return adminLogsView{
|
||||
Entries: entries,
|
||||
Dates: dates,
|
||||
Date: selectedDate,
|
||||
Severity: severity,
|
||||
Source: source,
|
||||
Query: r.URL.Query().Get("q"),
|
||||
Sort: sortOrder,
|
||||
TotalShown: len(entries),
|
||||
Entries: entries[start:end],
|
||||
Dates: dates,
|
||||
Date: selectedDate,
|
||||
Severity: severity,
|
||||
Source: source,
|
||||
Query: r.URL.Query().Get("q"),
|
||||
Sort: sortOrder,
|
||||
TotalShown: end - start,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PerPage: perPage,
|
||||
PerPageOptions: adminLogsPageSizes,
|
||||
TotalPages: totalPages,
|
||||
RangeFrom: rangeFrom,
|
||||
RangeTo: end,
|
||||
PageLinks: links,
|
||||
HasPrev: page > 1,
|
||||
HasNext: page < totalPages,
|
||||
PrevHref: adminLogsHref(state, page-1),
|
||||
NextHref: adminLogsHref(state, page+1),
|
||||
}, nil
|
||||
}
|
||||
|
||||
type adminLogsQuery struct {
|
||||
Date string
|
||||
Severity string
|
||||
Source string
|
||||
Query string
|
||||
Sort string
|
||||
Per int
|
||||
}
|
||||
|
||||
func adminLogsHref(state adminLogsQuery, page int) string {
|
||||
values := url.Values{}
|
||||
if state.Date != "" {
|
||||
values.Set("date", state.Date)
|
||||
}
|
||||
if state.Severity != "" {
|
||||
values.Set("severity", state.Severity)
|
||||
}
|
||||
if state.Source != "" {
|
||||
values.Set("source", state.Source)
|
||||
}
|
||||
if state.Query != "" {
|
||||
values.Set("q", state.Query)
|
||||
}
|
||||
if state.Sort != "" && state.Sort != "desc" {
|
||||
values.Set("sort", state.Sort)
|
||||
}
|
||||
if state.Per > 0 && state.Per != adminLogsDefaultPageSize {
|
||||
values.Set("per", strconv.Itoa(state.Per))
|
||||
}
|
||||
if page > 1 {
|
||||
values.Set("page", strconv.Itoa(page))
|
||||
}
|
||||
if len(values) == 0 {
|
||||
return "/admin/logs"
|
||||
}
|
||||
return "/admin/logs?" + values.Encode()
|
||||
}
|
||||
|
||||
func availableLogDates(logDir string) ([]string, error) {
|
||||
matches, err := filepath.Glob(filepath.Join(logDir, "*.log"))
|
||||
if err != nil {
|
||||
@@ -1519,11 +1761,29 @@ func readLogEntries(file string) ([]adminLogEntry, error) {
|
||||
if err := json.Unmarshal(line, &raw); err != nil {
|
||||
continue
|
||||
}
|
||||
if isHealthCheckLogEntry(raw) {
|
||||
continue
|
||||
}
|
||||
entries = append(entries, logEntryFromMap(raw))
|
||||
}
|
||||
return entries, scanner.Err()
|
||||
}
|
||||
|
||||
func isHealthCheckLogEntry(raw map[string]any) bool {
|
||||
path := strings.TrimSpace(firstLogString(raw, "path", "route"))
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
fields := strings.Fields(path)
|
||||
if len(fields) > 0 {
|
||||
path = fields[len(fields)-1]
|
||||
}
|
||||
if idx := strings.IndexByte(path, '?'); idx >= 0 {
|
||||
path = path[:idx]
|
||||
}
|
||||
return path == "/health"
|
||||
}
|
||||
|
||||
func logEntryFromMap(raw map[string]any) adminLogEntry {
|
||||
entry := adminLogEntry{
|
||||
Date: logString(raw, "date"),
|
||||
@@ -1535,7 +1795,7 @@ func logEntryFromMap(raw map[string]any) adminLogEntry {
|
||||
Method: logString(raw, "method"),
|
||||
Path: logString(raw, "path"),
|
||||
Status: logAnyString(raw["status"]),
|
||||
IP: firstLogString(raw, "ip", "client_ip", "remote_addr"),
|
||||
IP: services.IPOnly(firstLogString(raw, "ip", "client_ip", "remote_addr")),
|
||||
UserID: logString(raw, "user_id"),
|
||||
}
|
||||
entry.Details = logDetails(raw)
|
||||
@@ -1754,13 +2014,14 @@ func (a *App) storageBackendViews() ([]services.StorageBackendView, error) {
|
||||
usage, _ = concrete.Usage(context.Background())
|
||||
}
|
||||
}
|
||||
inUse, _ := a.storageBackendInUse(cfg.ID)
|
||||
inUse, inUseReason, _ := a.storageBackendUseReason(cfg.ID)
|
||||
speedTests, _ := a.uploadService.Storage().ListSpeedTests(cfg.ID, 25)
|
||||
views = append(views, services.StorageBackendView{
|
||||
Config: cfg,
|
||||
UsageBytes: usage,
|
||||
UsageLabel: services.FormatMegabytesFromBytes(usage),
|
||||
InUse: inUse,
|
||||
InUseReason: inUseReason,
|
||||
SpeedTests: speedTests,
|
||||
CanSpeedTest: cfg.LastTestSuccess,
|
||||
})
|
||||
@@ -1809,32 +2070,40 @@ func (a *App) adminUserEdit(user services.User, settings services.UploadPolicySe
|
||||
}
|
||||
|
||||
func (a *App) storageBackendInUse(id string) (bool, error) {
|
||||
inUse, _, err := a.storageBackendUseReason(id)
|
||||
return inUse, err
|
||||
}
|
||||
|
||||
func (a *App) storageBackendUseReason(id string) (bool, string, error) {
|
||||
settings, err := a.settingsService.UploadPolicy()
|
||||
if err != nil {
|
||||
return false, err
|
||||
return false, "", err
|
||||
}
|
||||
if settings.AnonymousStorageBackend == id || settings.UserStorageBackend == id {
|
||||
return true, nil
|
||||
if settings.AnonymousStorageBackend == id {
|
||||
return true, "selected as the global anonymous storage backend", nil
|
||||
}
|
||||
if settings.UserStorageBackend == id {
|
||||
return true, "selected as the global user storage backend", nil
|
||||
}
|
||||
boxes, err := a.uploadService.ListBoxes(0)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return false, "", err
|
||||
}
|
||||
for _, box := range boxes {
|
||||
if a.uploadService.BoxStorageBackendID(box) == id {
|
||||
return true, nil
|
||||
return true, "used by existing boxes", nil
|
||||
}
|
||||
}
|
||||
users, err := a.authService.ListUsers()
|
||||
if err != nil {
|
||||
return false, err
|
||||
return false, "", err
|
||||
}
|
||||
for _, user := range users {
|
||||
if user.Policy.StorageBackendID != nil && *user.Policy.StorageBackendID == id {
|
||||
return true, nil
|
||||
return true, "assigned to one or more users", nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
return false, "", nil
|
||||
}
|
||||
|
||||
func floatPtrString(value *float64) string {
|
||||
|
||||
492
backend/libs/handlers/admin_files.go
Normal file
@@ -0,0 +1,492 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"warpbox.dev/backend/libs/helpers"
|
||||
"warpbox.dev/backend/libs/services"
|
||||
"warpbox.dev/backend/libs/web"
|
||||
)
|
||||
|
||||
const adminFilesDefaultPageSize = 50
|
||||
|
||||
var adminFilesPageSizes = []int{25, 50, 100, 200}
|
||||
|
||||
type adminFilesData struct {
|
||||
Stats services.AdminStats
|
||||
Section string
|
||||
PageTitle string
|
||||
Boxes []adminBoxView
|
||||
Query string
|
||||
Sort string
|
||||
Dir string
|
||||
Page int
|
||||
PerPage int
|
||||
PerPageOptions []int
|
||||
TotalPages int
|
||||
Total int
|
||||
RangeFrom int
|
||||
RangeTo int
|
||||
Columns []adminFilesColumn
|
||||
PageLinks []adminFilesPageLink
|
||||
HasPrev bool
|
||||
HasNext bool
|
||||
PrevHref string
|
||||
NextHref string
|
||||
}
|
||||
|
||||
// adminFilesQuery captures the listing state that every paginated link must
|
||||
// preserve.
|
||||
type adminFilesQuery struct {
|
||||
Query string
|
||||
Sort string
|
||||
Dir string
|
||||
Per int
|
||||
}
|
||||
|
||||
type adminFilesColumn struct {
|
||||
Label string
|
||||
Href string
|
||||
Sorted bool
|
||||
Ascending bool
|
||||
}
|
||||
|
||||
type adminFilesPageLink struct {
|
||||
Page int
|
||||
Href string
|
||||
Active bool
|
||||
}
|
||||
|
||||
type adminBoxEditData struct {
|
||||
Section string
|
||||
PageTitle string
|
||||
Box adminBoxDetail
|
||||
Files []adminBoxEditFile
|
||||
Notice string
|
||||
Error string
|
||||
}
|
||||
|
||||
type adminBoxDetail struct {
|
||||
ID string
|
||||
Owner string
|
||||
CreatedAt string
|
||||
ExpiresLabel string
|
||||
ExpiresInput string
|
||||
NeverExpires bool
|
||||
MaxDownloads int
|
||||
DownloadCount int
|
||||
FileCount int
|
||||
TotalSize string
|
||||
BackendID string
|
||||
Protected bool
|
||||
Obfuscated bool
|
||||
}
|
||||
|
||||
type adminBoxEditFile struct {
|
||||
ID string
|
||||
Name string
|
||||
Size string
|
||||
ContentType string
|
||||
ThumbnailURL string
|
||||
DownloadURL string
|
||||
HasPreview bool
|
||||
}
|
||||
|
||||
// adminFileRow is the sortable/filterable representation of a box.
|
||||
type adminFileRow struct {
|
||||
ID string
|
||||
Owner string
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
FileCount int
|
||||
DownloadCount int
|
||||
MaxDownloads int
|
||||
TotalSize int64
|
||||
TotalSizeLabel string
|
||||
Protected bool
|
||||
Expired bool
|
||||
}
|
||||
|
||||
func (a *App) AdminFiles(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.requireAdmin(w, r) {
|
||||
return
|
||||
}
|
||||
|
||||
stats, err := a.uploadService.AdminStats()
|
||||
if err != nil {
|
||||
http.Error(w, "unable to load admin stats", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
boxes, err := a.uploadService.AdminBoxes(0)
|
||||
if err != nil {
|
||||
http.Error(w, "unable to load boxes", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
ownerCache := map[string]string{}
|
||||
rows := make([]adminFileRow, 0, len(boxes))
|
||||
for _, box := range boxes {
|
||||
rows = append(rows, adminFileRow{
|
||||
ID: box.ID,
|
||||
Owner: a.boxOwnerLabel(box.OwnerID, ownerCache),
|
||||
CreatedAt: box.CreatedAt,
|
||||
ExpiresAt: box.ExpiresAt,
|
||||
FileCount: box.FileCount,
|
||||
DownloadCount: box.DownloadCount,
|
||||
MaxDownloads: box.MaxDownloads,
|
||||
TotalSize: box.TotalSize,
|
||||
TotalSizeLabel: box.TotalSizeLabel,
|
||||
Protected: box.Protected,
|
||||
Expired: box.Expired,
|
||||
})
|
||||
}
|
||||
|
||||
query := strings.TrimSpace(r.URL.Query().Get("q"))
|
||||
if query != "" {
|
||||
needle := strings.ToLower(query)
|
||||
filtered := rows[:0:0]
|
||||
for _, row := range rows {
|
||||
if strings.Contains(strings.ToLower(row.ID), needle) || strings.Contains(strings.ToLower(row.Owner), needle) {
|
||||
filtered = append(filtered, row)
|
||||
}
|
||||
}
|
||||
rows = filtered
|
||||
}
|
||||
|
||||
sortKey := adminFilesSortKey(r.URL.Query().Get("sort"))
|
||||
dir := r.URL.Query().Get("dir")
|
||||
if dir != "asc" {
|
||||
dir = "desc"
|
||||
}
|
||||
sortAdminFileRows(rows, sortKey, dir)
|
||||
|
||||
perPage := normalizePageSize(r.URL.Query().Get("per"), adminFilesDefaultPageSize, adminFilesPageSizes)
|
||||
state := adminFilesQuery{Query: query, Sort: sortKey, Dir: dir, Per: perPage}
|
||||
|
||||
total := len(rows)
|
||||
totalPages := (total + perPage - 1) / perPage
|
||||
if totalPages < 1 {
|
||||
totalPages = 1
|
||||
}
|
||||
page := 1
|
||||
if parsed, err := strconv.Atoi(r.URL.Query().Get("page")); err == nil && parsed > 1 {
|
||||
page = parsed
|
||||
}
|
||||
if page > totalPages {
|
||||
page = totalPages
|
||||
}
|
||||
start := (page - 1) * perPage
|
||||
if start > total {
|
||||
start = total
|
||||
}
|
||||
end := start + perPage
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
|
||||
views := make([]adminBoxView, 0, end-start)
|
||||
for _, row := range rows[start:end] {
|
||||
views = append(views, adminBoxView{
|
||||
ID: row.ID,
|
||||
Owner: row.Owner,
|
||||
CreatedAt: row.CreatedAt.Format("Jan 2, 2006 15:04"),
|
||||
ExpiresAt: boxExpiryLabel(row.ExpiresAt, "Jan 2, 2006 15:04"),
|
||||
FileCount: row.FileCount,
|
||||
TotalSizeLabel: row.TotalSizeLabel,
|
||||
DownloadCount: row.DownloadCount,
|
||||
MaxDownloads: row.MaxDownloads,
|
||||
Protected: row.Protected,
|
||||
Expired: row.Expired,
|
||||
})
|
||||
}
|
||||
|
||||
rangeFrom := 0
|
||||
if total > 0 {
|
||||
rangeFrom = start + 1
|
||||
}
|
||||
|
||||
a.renderPage(w, r, http.StatusOK, "admin_files.html", web.PageData{
|
||||
Title: "Admin files",
|
||||
Description: "Manage Warpbox uploads.",
|
||||
CurrentUser: a.currentPublicUser(r),
|
||||
Data: adminFilesData{
|
||||
Stats: stats,
|
||||
Section: "files",
|
||||
PageTitle: "Files",
|
||||
Boxes: views,
|
||||
Query: query,
|
||||
Sort: sortKey,
|
||||
Dir: dir,
|
||||
Page: page,
|
||||
PerPage: perPage,
|
||||
PerPageOptions: adminFilesPageSizes,
|
||||
TotalPages: totalPages,
|
||||
Total: total,
|
||||
RangeFrom: rangeFrom,
|
||||
RangeTo: end,
|
||||
Columns: adminFilesColumns(state, sortKey, dir),
|
||||
PageLinks: adminFilesPageLinks(state, page, totalPages),
|
||||
HasPrev: page > 1,
|
||||
HasNext: page < totalPages,
|
||||
PrevHref: adminFilesHref(state, page-1),
|
||||
NextHref: adminFilesHref(state, page+1),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) boxOwnerLabel(ownerID string, cache map[string]string) string {
|
||||
if ownerID == "" {
|
||||
return "Anonymous"
|
||||
}
|
||||
if label, ok := cache[ownerID]; ok {
|
||||
return label
|
||||
}
|
||||
label := "User"
|
||||
if user, err := a.authService.UserByID(ownerID); err == nil {
|
||||
label = user.Email
|
||||
}
|
||||
cache[ownerID] = label
|
||||
return label
|
||||
}
|
||||
|
||||
func adminFilesSortKey(value string) string {
|
||||
switch value {
|
||||
case "id", "owner", "files", "size", "downloads", "expires", "created":
|
||||
return value
|
||||
default:
|
||||
return "created"
|
||||
}
|
||||
}
|
||||
|
||||
func sortAdminFileRows(rows []adminFileRow, sortKey, dir string) {
|
||||
less := func(i, j int) bool {
|
||||
a, b := rows[i], rows[j]
|
||||
switch sortKey {
|
||||
case "id":
|
||||
return strings.ToLower(a.ID) < strings.ToLower(b.ID)
|
||||
case "owner":
|
||||
return strings.ToLower(a.Owner) < strings.ToLower(b.Owner)
|
||||
case "files":
|
||||
return a.FileCount < b.FileCount
|
||||
case "size":
|
||||
return a.TotalSize < b.TotalSize
|
||||
case "downloads":
|
||||
return a.DownloadCount < b.DownloadCount
|
||||
case "expires":
|
||||
return a.ExpiresAt.Before(b.ExpiresAt)
|
||||
default:
|
||||
return a.CreatedAt.Before(b.CreatedAt)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(rows, func(i, j int) bool {
|
||||
if dir == "desc" {
|
||||
return less(j, i)
|
||||
}
|
||||
return less(i, j)
|
||||
})
|
||||
}
|
||||
|
||||
func adminFilesColumns(state adminFilesQuery, sortKey, dir string) []adminFilesColumn {
|
||||
defs := []struct{ Key, Label string }{
|
||||
{"id", "Box"},
|
||||
{"owner", "Owner"},
|
||||
{"files", "Files"},
|
||||
{"size", "Size"},
|
||||
{"downloads", "Downloads"},
|
||||
{"created", "Created"},
|
||||
{"expires", "Expires"},
|
||||
}
|
||||
columns := make([]adminFilesColumn, 0, len(defs))
|
||||
for _, def := range defs {
|
||||
sorted := sortKey == def.Key
|
||||
nextDir := "asc"
|
||||
if sorted && dir == "asc" {
|
||||
nextDir = "desc"
|
||||
}
|
||||
colState := state
|
||||
colState.Sort = def.Key
|
||||
colState.Dir = nextDir
|
||||
columns = append(columns, adminFilesColumn{
|
||||
Label: def.Label,
|
||||
Href: adminFilesHref(colState, 1),
|
||||
Sorted: sorted,
|
||||
Ascending: dir == "asc",
|
||||
})
|
||||
}
|
||||
return columns
|
||||
}
|
||||
|
||||
func adminFilesPageLinks(state adminFilesQuery, page, totalPages int) []adminFilesPageLink {
|
||||
links := make([]adminFilesPageLink, 0, 5)
|
||||
const window = 2
|
||||
for p := page - window; p <= page+window; p++ {
|
||||
if p < 1 || p > totalPages {
|
||||
continue
|
||||
}
|
||||
links = append(links, adminFilesPageLink{
|
||||
Page: p,
|
||||
Href: adminFilesHref(state, p),
|
||||
Active: p == page,
|
||||
})
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
func adminFilesHref(state adminFilesQuery, page int) string {
|
||||
values := url.Values{}
|
||||
if state.Query != "" {
|
||||
values.Set("q", state.Query)
|
||||
}
|
||||
if state.Sort != "" && state.Sort != "created" {
|
||||
values.Set("sort", state.Sort)
|
||||
}
|
||||
if state.Dir != "" && state.Dir != "desc" {
|
||||
values.Set("dir", state.Dir)
|
||||
}
|
||||
if state.Per > 0 && state.Per != adminFilesDefaultPageSize {
|
||||
values.Set("per", strconv.Itoa(state.Per))
|
||||
}
|
||||
if page > 1 {
|
||||
values.Set("page", strconv.Itoa(page))
|
||||
}
|
||||
if len(values) == 0 {
|
||||
return "/admin/files"
|
||||
}
|
||||
return "/admin/files?" + values.Encode()
|
||||
}
|
||||
|
||||
// normalizePageSize parses a requested page size, falling back to def when the
|
||||
// value is missing or not one of the allowed sizes.
|
||||
func normalizePageSize(raw string, def int, allowed []int) int {
|
||||
parsed, err := strconv.Atoi(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
for _, size := range allowed {
|
||||
if size == parsed {
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func (a *App) AdminEditBox(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.requireAdmin(w, r) {
|
||||
return
|
||||
}
|
||||
box, err := a.uploadService.GetBox(r.PathValue("boxID"))
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
var totalSize int64
|
||||
files := make([]adminBoxEditFile, 0, len(box.Files))
|
||||
for _, file := range box.Files {
|
||||
totalSize += file.Size
|
||||
files = append(files, adminBoxEditFile{
|
||||
ID: file.ID,
|
||||
Name: file.Name,
|
||||
Size: helpers.FormatBytes(file.Size),
|
||||
ContentType: file.ContentType,
|
||||
ThumbnailURL: fmt.Sprintf("/d/%s/thumb/%s", box.ID, file.ID),
|
||||
DownloadURL: fmt.Sprintf("/d/%s/f/%s", box.ID, file.ID),
|
||||
HasPreview: file.PreviewKind == "image" || file.PreviewKind == "video",
|
||||
})
|
||||
}
|
||||
|
||||
never := neverExpires(box.ExpiresAt)
|
||||
expiresInput := ""
|
||||
if !never {
|
||||
expiresInput = box.ExpiresAt.UTC().Format("2006-01-02T15:04")
|
||||
}
|
||||
|
||||
cache := map[string]string{}
|
||||
a.renderPage(w, r, http.StatusOK, "admin_box_edit.html", web.PageData{
|
||||
Title: "Edit box",
|
||||
Description: "Edit a Warpbox upload.",
|
||||
CurrentUser: a.currentPublicUser(r),
|
||||
Data: adminBoxEditData{
|
||||
Section: "files",
|
||||
PageTitle: "Edit box",
|
||||
Notice: r.URL.Query().Get("notice"),
|
||||
Error: r.URL.Query().Get("error"),
|
||||
Files: files,
|
||||
Box: adminBoxDetail{
|
||||
ID: box.ID,
|
||||
Owner: a.boxOwnerLabel(box.OwnerID, cache),
|
||||
CreatedAt: box.CreatedAt.Format("Jan 2, 2006 15:04 MST"),
|
||||
ExpiresLabel: boxExpiryLabel(box.ExpiresAt, "Jan 2, 2006 15:04 MST"),
|
||||
ExpiresInput: expiresInput,
|
||||
NeverExpires: never,
|
||||
MaxDownloads: box.MaxDownloads,
|
||||
DownloadCount: box.DownloadCount,
|
||||
FileCount: len(box.Files),
|
||||
TotalSize: helpers.FormatBytes(totalSize),
|
||||
BackendID: a.uploadService.BoxStorageBackendID(box),
|
||||
Protected: a.uploadService.IsProtected(box),
|
||||
Obfuscated: box.Obfuscate,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) AdminUpdateBox(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.requireAdmin(w, r) || !a.validateCSRF(w, r) {
|
||||
return
|
||||
}
|
||||
boxID := r.PathValue("boxID")
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Redirect(w, r, "/admin/boxes/"+boxID+"/edit?error=Could+not+read+form", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
var expiresAt time.Time
|
||||
if r.FormValue("never_expires") == "on" {
|
||||
expiresAt = time.Now().UTC().AddDate(100, 0, 0)
|
||||
} else {
|
||||
parsed, err := time.Parse("2006-01-02T15:04", strings.TrimSpace(r.FormValue("expires_at")))
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/admin/boxes/"+boxID+"/edit?error=Invalid+expiration+date", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
expiresAt = parsed.UTC()
|
||||
}
|
||||
|
||||
maxDownloads := parsePositiveInt(r.FormValue("max_downloads"))
|
||||
removePassword := r.FormValue("remove_password") == "on"
|
||||
|
||||
if err := a.uploadService.AdminUpdateBox(boxID, expiresAt, maxDownloads, removePassword); err != nil {
|
||||
a.logger.Warn("admin box update failed", "source", "admin", "severity", "warn", "code", 4306, "box_id", boxID, "error", err.Error())
|
||||
http.Redirect(w, r, "/admin/boxes/"+boxID+"/edit?error=Could+not+save+changes", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
a.logger.Info("admin box updated", "source", "admin", "severity", "user_activity", "code", 2306, "ip", uploadClientIP(r), "box_id", boxID)
|
||||
http.Redirect(w, r, "/admin/boxes/"+boxID+"/edit?notice=Changes+saved", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (a *App) AdminDeleteBoxFile(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.requireAdmin(w, r) || !a.validateCSRF(w, r) {
|
||||
return
|
||||
}
|
||||
boxID := r.PathValue("boxID")
|
||||
fileID := r.PathValue("fileID")
|
||||
boxDeleted, err := a.uploadService.RemoveFileFromBox(boxID, fileID)
|
||||
if err != nil {
|
||||
a.logger.Warn("admin file delete failed", "source", "admin", "severity", "warn", "code", 4305, "box_id", boxID, "file_id", fileID, "error", err.Error())
|
||||
http.Redirect(w, r, "/admin/boxes/"+boxID+"/edit?error=Could+not+remove+file", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
a.logger.Info("admin removed box file", "source", "admin", "severity", "user_activity", "code", 2305, "ip", uploadClientIP(r), "box_id", boxID, "file_id", fileID)
|
||||
if boxDeleted {
|
||||
http.Redirect(w, r, "/admin/files?notice=Box+deleted+(last+file+removed)", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/admin/boxes/"+boxID+"/edit?notice=File+removed", http.StatusSeeOther)
|
||||
}
|
||||
@@ -10,29 +10,41 @@ import (
|
||||
type apiDocsData struct {
|
||||
BaseURL string
|
||||
UploadURL string
|
||||
HealthURL string
|
||||
RequestSchemaURL string
|
||||
ResponseSchemaURL string
|
||||
ShareXExamplePath string
|
||||
ShareXExampleURL string
|
||||
ShareXDownloadURL string
|
||||
ShareXFileFieldName string
|
||||
ShareXGroupWindow string
|
||||
}
|
||||
|
||||
func (a *App) APIDocs(w http.ResponseWriter, r *http.Request) {
|
||||
user, loggedIn := a.currentUser(r)
|
||||
actor := "anonymous"
|
||||
if loggedIn {
|
||||
actor = "user"
|
||||
}
|
||||
a.logger.Info("api docs viewed", withRequestLogAttrs(r,
|
||||
"source", "page",
|
||||
"severity", "user_activity",
|
||||
"code", 2501,
|
||||
"actor", actor,
|
||||
"user_id", user.ID,
|
||||
)...)
|
||||
a.renderPage(w, r, http.StatusOK, "api.html", web.PageData{
|
||||
Title: "API documentation",
|
||||
Description: "Curl and ShareX upload examples for Warpbox.",
|
||||
Data: apiDocsData{
|
||||
BaseURL: a.cfg.BaseURL,
|
||||
UploadURL: a.cfg.BaseURL + "/api/v1/upload",
|
||||
HealthURL: a.cfg.BaseURL + "/api/v1/health",
|
||||
RequestSchemaURL: a.cfg.BaseURL + "/api/v1/schemas/upload-request.json",
|
||||
ResponseSchemaURL: a.cfg.BaseURL + "/api/v1/schemas/upload-response.json",
|
||||
ShareXExamplePath: "examples/sharex/warpbox-anonymous.sxcu",
|
||||
ShareXExampleURL: a.cfg.BaseURL + "/api/v1/upload",
|
||||
ShareXDownloadURL: a.cfg.BaseURL + "/api/v1/sharex/warpbox-anonymous.sxcu",
|
||||
ShareXFileFieldName: "sharex",
|
||||
ShareXGroupWindow: uploadGroupWindow.String(),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -47,11 +59,16 @@ func (a *App) ShareXAnonymousConfig(w http.ResponseWriter, r *http.Request) {
|
||||
"RequestURL": a.cfg.BaseURL + "/api/v1/upload",
|
||||
"Headers": map[string]string{
|
||||
"Accept": "application/json",
|
||||
// Group a multi-file selection (sent as back-to-back requests) into
|
||||
// one box. Remove this header for one box per file.
|
||||
uploadBatchHeader: "sharex",
|
||||
},
|
||||
"Body": "MultipartFormData",
|
||||
"FileFormName": "sharex",
|
||||
"URL": "$json:boxUrl$",
|
||||
"DeletionURL": "$json:manageUrl$",
|
||||
"URL": "{json:boxUrl}",
|
||||
"ThumbnailURL": "{json:thumbnailUrl}",
|
||||
"DeletionURL": "{json:deleteUrl}",
|
||||
"ErrorMessage": "{json:error}",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -109,22 +126,24 @@ func (a *App) UploadResponseSchema(w http.ResponseWriter, r *http.Request) {
|
||||
"type": "object",
|
||||
"required": []string{"boxId", "boxUrl", "zipUrl", "manageUrl", "deleteUrl", "expiresAt", "files"},
|
||||
"properties": map[string]any{
|
||||
"boxId": map[string]any{"type": "string"},
|
||||
"boxUrl": map[string]any{"type": "string", "format": "uri"},
|
||||
"zipUrl": map[string]any{"type": "string", "format": "uri"},
|
||||
"manageUrl": map[string]any{"type": "string", "format": "uri", "description": "Private bearer URL for managing/deleting this upload. Returned only at upload time."},
|
||||
"deleteUrl": map[string]any{"type": "string", "format": "uri", "description": "Private bearer POST URL for deleting this upload. Returned only at upload time."},
|
||||
"expiresAt": map[string]any{"type": "string", "format": "date-time"},
|
||||
"boxId": map[string]any{"type": "string"},
|
||||
"boxUrl": map[string]any{"type": "string", "format": "uri"},
|
||||
"zipUrl": map[string]any{"type": "string", "format": "uri"},
|
||||
"thumbnailUrl": map[string]any{"type": "string", "format": "uri", "description": "Thumbnail of the most recently uploaded file (placeholder until generated)."},
|
||||
"manageUrl": map[string]any{"type": "string", "format": "uri", "description": "Private bearer URL for managing/deleting this upload. Returned only at upload time."},
|
||||
"deleteUrl": map[string]any{"type": "string", "format": "uri", "description": "Private bearer URL for deleting this upload (GET or POST). Returned only at upload time."},
|
||||
"expiresAt": map[string]any{"type": "string", "format": "date-time"},
|
||||
"files": map[string]any{
|
||||
"type": "array",
|
||||
"items": map[string]any{
|
||||
"type": "object",
|
||||
"required": []string{"id", "name", "size", "url"},
|
||||
"properties": map[string]any{
|
||||
"id": map[string]any{"type": "string"},
|
||||
"name": map[string]any{"type": "string"},
|
||||
"size": map[string]any{"type": "string"},
|
||||
"url": map[string]any{"type": "string", "format": "uri"},
|
||||
"id": map[string]any{"type": "string"},
|
||||
"name": map[string]any{"type": "string"},
|
||||
"size": map[string]any{"type": "string"},
|
||||
"url": map[string]any{"type": "string", "format": "uri"},
|
||||
"thumbnailUrl": map[string]any{"type": "string", "format": "uri"},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -16,11 +16,18 @@ type App struct {
|
||||
uploadService *services.UploadService
|
||||
authService *services.AuthService
|
||||
settingsService *services.SettingsService
|
||||
reactionService *services.ReactionService
|
||||
banService *services.BanService
|
||||
rateLimiter *rateLimiter
|
||||
uploadGroups *uploadGrouper
|
||||
fileIcons *fileIconSet
|
||||
}
|
||||
|
||||
func NewApp(cfg config.Config, logger *slog.Logger, renderer *web.Renderer, uploadService *services.UploadService, authService *services.AuthService, settingsService *services.SettingsService, banService *services.BanService) *App {
|
||||
func NewApp(cfg config.Config, logger *slog.Logger, renderer *web.Renderer, uploadService *services.UploadService, authService *services.AuthService, settingsService *services.SettingsService, reactionService *services.ReactionService, banService *services.BanService) *App {
|
||||
fileIcons, err := loadFileIcons(cfg.StaticDir)
|
||||
if err != nil {
|
||||
logger.Warn("failed to load file icon map", "source", "handlers", "severity", "warn", "error", err.Error())
|
||||
}
|
||||
return &App{
|
||||
cfg: cfg,
|
||||
logger: logger,
|
||||
@@ -28,8 +35,11 @@ func NewApp(cfg config.Config, logger *slog.Logger, renderer *web.Renderer, uplo
|
||||
uploadService: uploadService,
|
||||
authService: authService,
|
||||
settingsService: settingsService,
|
||||
reactionService: reactionService,
|
||||
banService: banService,
|
||||
rateLimiter: newRateLimiter(),
|
||||
uploadGroups: newUploadGrouper(),
|
||||
fileIcons: fileIcons,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +104,6 @@ func (a *App) RegisterRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /admin/storage/{backendID}/edit", a.AdminEditStorage)
|
||||
mux.HandleFunc("POST /admin/storage/{backendID}/test", a.AdminTestStorage)
|
||||
mux.HandleFunc("POST /admin/storage/{backendID}/speed-test", a.AdminStartStorageSpeedTest)
|
||||
mux.HandleFunc("POST /admin/storage/{backendID}/disable", a.AdminDisableStorage)
|
||||
mux.HandleFunc("POST /admin/storage/{backendID}/delete", a.AdminDeleteStorage)
|
||||
mux.HandleFunc("POST /admin/storage/jobs/cleanup", a.AdminRunStorageCleanup)
|
||||
mux.HandleFunc("POST /admin/storage/jobs/thumbnails", a.AdminRunStorageThumbnails)
|
||||
@@ -107,23 +116,42 @@ func (a *App) RegisterRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /admin/users/{userID}/policy", a.AdminUpdateUserPolicy)
|
||||
mux.HandleFunc("POST /admin/users/{userID}/storage", a.AdminUpdateUserStorage)
|
||||
mux.HandleFunc("GET /admin/boxes/{boxID}/view", a.AdminViewBox)
|
||||
mux.HandleFunc("GET /admin/boxes/{boxID}/edit", a.AdminEditBox)
|
||||
mux.HandleFunc("POST /admin/boxes/{boxID}/edit", a.AdminUpdateBox)
|
||||
mux.HandleFunc("POST /admin/boxes/{boxID}/files/{fileID}/delete", a.AdminDeleteBoxFile)
|
||||
mux.HandleFunc("POST /admin/boxes/{boxID}/delete", a.AdminDeleteBox)
|
||||
mux.HandleFunc("GET /d/{boxID}", a.DownloadPage)
|
||||
mux.HandleFunc("GET /d/{boxID}/deleted", a.ManageDeleted)
|
||||
mux.HandleFunc("GET /d/{boxID}/manage/{token}", a.ManageBox)
|
||||
mux.HandleFunc("POST /d/{boxID}/manage/{token}/delete", a.ManageDeleteBox)
|
||||
// GET variant so ShareX (which issues a GET to the configured DeletionURL)
|
||||
// can delete a box via its secret one-time delete token.
|
||||
mux.HandleFunc("GET /d/{boxID}/manage/{token}/delete", a.ManageDeleteBox)
|
||||
mux.HandleFunc("POST /d/{boxID}/unlock", a.UnlockBox)
|
||||
mux.HandleFunc("GET /d/{boxID}/zip", a.DownloadZip)
|
||||
mux.HandleFunc("POST /d/{boxID}/f/{fileID}/react", a.ReactToFile)
|
||||
mux.HandleFunc("GET /d/{boxID}/f/{fileID}", a.DownloadFile)
|
||||
mux.HandleFunc("GET /d/{boxID}/f/{fileID}/download", a.DownloadFileContent)
|
||||
mux.HandleFunc("GET /d/{boxID}/thumb/{fileID}", a.Thumbnail)
|
||||
mux.HandleFunc("GET /d/{boxID}/og-image.jpg", a.BoxOGImage)
|
||||
mux.HandleFunc("GET /health", a.Health)
|
||||
mux.HandleFunc("GET /healthz", a.Health)
|
||||
mux.HandleFunc("GET /api/v1/health", a.Health)
|
||||
mux.HandleFunc("GET /healthz", notFound)
|
||||
mux.HandleFunc("GET /api/v1/health", notFound)
|
||||
mux.HandleFunc("GET /api/v1/sharex/warpbox-anonymous.sxcu", a.ShareXAnonymousConfig)
|
||||
mux.HandleFunc("GET /api/v1/schemas/upload-request.json", a.UploadRequestSchema)
|
||||
mux.HandleFunc("GET /api/v1/schemas/upload-response.json", a.UploadResponseSchema)
|
||||
mux.HandleFunc("POST /api/v1/upload", a.Upload)
|
||||
mux.HandleFunc("POST /api/v1/uploads/resumable", a.CreateResumableUpload)
|
||||
mux.HandleFunc("GET /api/v1/uploads/resumable/{sessionID}", a.ResumableUploadStatus)
|
||||
mux.HandleFunc("POST /api/v1/uploads/resumable/{sessionID}/files", a.AddResumableFiles)
|
||||
mux.HandleFunc("PUT /api/v1/uploads/resumable/{sessionID}/files/{fileID}/chunks/{index}", a.PutResumableChunk)
|
||||
mux.HandleFunc("POST /api/v1/uploads/resumable/{sessionID}/complete", a.CompleteResumableUpload)
|
||||
mux.HandleFunc("POST /api/v1/uploads/resumable/{sessionID}/complete-uploaded", a.CompleteUploadedResumableUpload)
|
||||
mux.HandleFunc("DELETE /api/v1/uploads/resumable/{sessionID}", a.CancelResumableUpload)
|
||||
mux.HandleFunc("GET /emoji/{pack}/{file}", a.EmojiAsset)
|
||||
mux.Handle("GET /static/", a.Static())
|
||||
}
|
||||
|
||||
func notFound(w http.ResponseWriter, r *http.Request) {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ func (a *App) Register(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (a *App) RegisterPost(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.rateLimiter.Allow("register:"+uploadClientIP(r), 10, time.Minute, time.Now().UTC()) {
|
||||
a.logger.Warn("registration rate limited", "source", "auth", "severity", "warn", "code", 4291, "ip", uploadClientIP(r))
|
||||
a.logger.Warn("registration rate limited", withRequestLogAttrs(r, "source", "auth", "severity", "warn", "code", 4291)...)
|
||||
a.renderAuth(w, r, http.StatusTooManyRequests, authPageData{Mode: "register", Error: "Too many registration attempts."})
|
||||
return
|
||||
}
|
||||
@@ -45,11 +45,11 @@ func (a *App) RegisterPost(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
user, err := a.authService.CreateBootstrapUser(r.FormValue("username"), r.FormValue("email"), r.FormValue("password"))
|
||||
if err != nil {
|
||||
a.logger.Warn("bootstrap registration failed", "source", "auth", "severity", "warn", "code", 4400, "ip", uploadClientIP(r), "email", r.FormValue("email"), "error", err.Error())
|
||||
a.logger.Warn("bootstrap registration failed", withRequestLogAttrs(r, "source", "auth", "severity", "warn", "code", 4400, "email", r.FormValue("email"), "error", err.Error())...)
|
||||
a.renderAuth(w, r, http.StatusBadRequest, authPageData{Mode: "register", Error: err.Error()})
|
||||
return
|
||||
}
|
||||
a.logger.Info("first admin created", "source", "auth", "severity", "user_activity", "code", 2401, "user_id", user.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Info("first admin created", withRequestLogAttrs(r, "source", "auth", "severity", "user_activity", "code", 2401, "user_id", user.ID)...)
|
||||
a.loginAndRedirect(w, r, user.Email, r.FormValue("password"), "/app")
|
||||
}
|
||||
|
||||
@@ -58,12 +58,13 @@ func (a *App) Login(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/app", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
a.logger.Info("login page viewed", withRequestLogAttrs(r, "source", "page", "severity", "user_activity", "code", 2503, "actor", "anonymous")...)
|
||||
a.renderAuth(w, r, http.StatusOK, authPageData{Mode: "login", ReturnPath: r.URL.Query().Get("next")})
|
||||
}
|
||||
|
||||
func (a *App) LoginPost(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.rateLimiter.Allow("login:"+uploadClientIP(r), 10, time.Minute, time.Now().UTC()) {
|
||||
a.logger.Warn("login rate limited", "source", "auth", "severity", "warn", "code", 4292, "ip", uploadClientIP(r), "email", r.FormValue("email"))
|
||||
a.logger.Warn("login rate limited", withRequestLogAttrs(r, "source", "auth", "severity", "warn", "code", 4292, "email", r.FormValue("email"))...)
|
||||
a.renderAuth(w, r, http.StatusTooManyRequests, authPageData{Mode: "login", Error: "Too many login attempts."})
|
||||
return
|
||||
}
|
||||
@@ -77,13 +78,13 @@ func (a *App) LoginPost(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
user, token, err := a.authService.Login(r.FormValue("email"), r.FormValue("password"))
|
||||
if err != nil {
|
||||
a.logger.Warn("login failed", "source", "auth", "severity", "warn", "code", 4401, "email", r.FormValue("email"), "ip", uploadClientIP(r))
|
||||
a.logger.Warn("login failed", withRequestLogAttrs(r, "source", "auth", "severity", "warn", "code", 4401, "email", r.FormValue("email"))...)
|
||||
a.recordLoginAbuse(r, services.AbuseKindUserLogin, "user login failed")
|
||||
a.renderAuth(w, r, http.StatusUnauthorized, authPageData{Mode: "login", Error: "Invalid email or password.", ReturnPath: next})
|
||||
return
|
||||
}
|
||||
a.setUserSessionCookie(w, r, token)
|
||||
a.logger.Info("user login", "source", "auth", "severity", "user_activity", "code", 2402, "user_id", user.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Info("user login", withRequestLogAttrs(r, "source", "auth", "severity", "user_activity", "code", 2402, "user_id", user.ID)...)
|
||||
http.Redirect(w, r, safeReturnPath(next), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -92,7 +93,7 @@ func (a *App) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if user, ok := a.currentUser(r); ok {
|
||||
a.logger.Info("user logout", "source", "auth", "severity", "user_activity", "code", 2405, "user_id", user.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Info("user logout", withRequestLogAttrs(r, "source", "auth", "severity", "user_activity", "code", 2405, "user_id", user.ID)...)
|
||||
}
|
||||
if cookie, err := r.Cookie(userSessionCookieName); err == nil {
|
||||
_ = a.authService.Logout(cookie.Value)
|
||||
@@ -107,6 +108,7 @@ func (a *App) Invite(w http.ResponseWriter, r *http.Request) {
|
||||
a.renderAuth(w, r, http.StatusNotFound, authPageData{Mode: "invite", Error: "This invite is invalid or expired."})
|
||||
return
|
||||
}
|
||||
a.logger.Info("invite page viewed", withRequestLogAttrs(r, "source", "page", "severity", "user_activity", "code", 2504, "invite_email", invite.Email, "reset", invite.UserID != "")...)
|
||||
a.renderAuth(w, r, http.StatusOK, authPageData{Mode: "invite", Token: r.PathValue("token"), Email: invite.Email, IsReset: invite.UserID != ""})
|
||||
}
|
||||
|
||||
@@ -114,7 +116,7 @@ func (a *App) InvitePost(w http.ResponseWriter, r *http.Request) {
|
||||
token := r.PathValue("token")
|
||||
invite, err := a.authService.InviteByToken(token)
|
||||
if err != nil {
|
||||
a.logger.Warn("invite accept invalid", "source", "auth", "severity", "warn", "code", 4404, "ip", uploadClientIP(r))
|
||||
a.logger.Warn("invite accept invalid", withRequestLogAttrs(r, "source", "auth", "severity", "warn", "code", 4404)...)
|
||||
a.renderAuth(w, r, http.StatusNotFound, authPageData{Mode: "invite", Error: "This invite is invalid or expired."})
|
||||
return
|
||||
}
|
||||
@@ -124,11 +126,11 @@ func (a *App) InvitePost(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
user, err := a.authService.AcceptInvite(token, r.FormValue("username"), r.FormValue("password"))
|
||||
if err != nil {
|
||||
a.logger.Warn("invite accept failed", "source", "auth", "severity", "warn", "code", 4405, "ip", uploadClientIP(r), "invite_email", invite.Email, "error", err.Error())
|
||||
a.logger.Warn("invite accept failed", withRequestLogAttrs(r, "source", "auth", "severity", "warn", "code", 4405, "invite_email", invite.Email, "error", err.Error())...)
|
||||
a.renderAuth(w, r, http.StatusBadRequest, authPageData{Mode: "invite", Token: token, Email: invite.Email, IsReset: invite.UserID != "", Error: err.Error()})
|
||||
return
|
||||
}
|
||||
a.logger.Info("invite accepted", "source", "auth", "severity", "user_activity", "code", 2403, "user_id", user.ID, "ip", uploadClientIP(r), "invite_email", invite.Email)
|
||||
a.logger.Info("invite accepted", withRequestLogAttrs(r, "source", "auth", "severity", "user_activity", "code", 2403, "user_id", user.ID, "invite_email", invite.Email)...)
|
||||
a.loginAndRedirect(w, r, user.Email, r.FormValue("password"), "/app")
|
||||
}
|
||||
|
||||
@@ -153,6 +155,7 @@ func (a *App) AccountSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
a.logger.Info("account settings viewed", withRequestLogAttrs(r, "source", "page", "severity", "user_activity", "code", 2505, "user_id", user.ID)...)
|
||||
a.renderAccount(w, r, http.StatusOK, user, accountData{})
|
||||
}
|
||||
|
||||
@@ -170,11 +173,11 @@ func (a *App) CreateUserToken(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
result, err := a.authService.CreateAPIToken(user.ID, r.FormValue("name"))
|
||||
if err != nil {
|
||||
a.logger.Warn("api token create failed", "source", "user_activity", "severity", "warn", "code", 4420, "user_id", user.ID, "error", err.Error())
|
||||
a.logger.Warn("api token create failed", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4420, "user_id", user.ID, "error", err.Error())...)
|
||||
a.renderAccount(w, r, http.StatusBadRequest, user, accountData{Error: "Could not create token."})
|
||||
return
|
||||
}
|
||||
a.logger.Info("api token created", "source", "user_activity", "severity", "user_activity", "code", 2420, "user_id", user.ID, "token_id", result.Token.ID)
|
||||
a.logger.Info("api token created", withRequestLogAttrs(r, "source", "user_activity", "severity", "user_activity", "code", 2420, "user_id", user.ID, "token_id", result.Token.ID)...)
|
||||
a.renderAccount(w, r, http.StatusOK, user, accountData{NewToken: result.Plaintext})
|
||||
}
|
||||
|
||||
@@ -184,9 +187,9 @@ func (a *App) DeleteUserToken(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if err := a.authService.DeleteAPIToken(user.ID, r.PathValue("tokenID")); err != nil {
|
||||
a.logger.Warn("api token delete failed", "source", "user_activity", "severity", "warn", "code", 4421, "user_id", user.ID, "error", err.Error())
|
||||
a.logger.Warn("api token delete failed", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4421, "user_id", user.ID, "error", err.Error())...)
|
||||
} else {
|
||||
a.logger.Info("api token deleted", "source", "user_activity", "severity", "user_activity", "code", 2421, "user_id", user.ID, "token_id", r.PathValue("tokenID"))
|
||||
a.logger.Info("api token deleted", withRequestLogAttrs(r, "source", "user_activity", "severity", "user_activity", "code", 2421, "user_id", user.ID, "token_id", r.PathValue("tokenID"))...)
|
||||
}
|
||||
http.Redirect(w, r, "/account/settings", http.StatusSeeOther)
|
||||
}
|
||||
@@ -233,16 +236,16 @@ func (a *App) ChangePassword(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if !services.VerifyPasswordHash(user.PasswordHash, r.FormValue("current_password")) {
|
||||
a.logger.Warn("password change failed current password", "source", "user_activity", "severity", "warn", "code", 4422, "user_id", user.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Warn("password change failed current password", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4422, "user_id", user.ID)...)
|
||||
http.Redirect(w, r, "/account/settings", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if err := a.authService.SetPassword(user.ID, r.FormValue("new_password")); err != nil {
|
||||
a.logger.Warn("password change failed", "source", "user_activity", "severity", "warn", "code", 4423, "user_id", user.ID, "error", err.Error())
|
||||
a.logger.Warn("password change failed", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4423, "user_id", user.ID, "error", err.Error())...)
|
||||
http.Redirect(w, r, "/account/settings", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
a.logger.Info("password changed", "source", "user_activity", "severity", "user_activity", "code", 2422, "user_id", user.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Info("password changed", withRequestLogAttrs(r, "source", "user_activity", "severity", "user_activity", "code", 2422, "user_id", user.ID)...)
|
||||
http.Redirect(w, r, "/account/settings", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,12 @@ func (a *App) Dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
a.logger.Info("user dashboard viewed", withRequestLogAttrs(r,
|
||||
"source", "page",
|
||||
"severity", "user_activity",
|
||||
"code", 2502,
|
||||
"user_id", user.ID,
|
||||
)...)
|
||||
collections, err := a.authService.ListCollections(user.ID)
|
||||
if err != nil {
|
||||
http.Error(w, "unable to load collections", http.StatusInternalServerError)
|
||||
@@ -82,7 +88,7 @@ func (a *App) Dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
FileCount: len(row.Box.Files),
|
||||
Size: row.TotalSizeLabel,
|
||||
CreatedAt: row.Box.CreatedAt.Format("Jan 2 15:04"),
|
||||
ExpiresAt: row.Box.ExpiresAt.Format("Jan 2 15:04"),
|
||||
ExpiresAt: boxExpiryLabel(row.Box.ExpiresAt, "Jan 2 15:04"),
|
||||
URL: "/d/" + row.Box.ID,
|
||||
})
|
||||
}
|
||||
@@ -112,9 +118,9 @@ func (a *App) CreateCollection(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if _, err := a.authService.CreateCollection(user.ID, r.FormValue("name")); err != nil {
|
||||
a.logger.Warn("collection create failed", "source", "user_activity", "severity", "warn", "code", 4410, "user_id", user.ID, "error", err.Error())
|
||||
a.logger.Warn("collection create failed", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4410, "user_id", user.ID, "error", err.Error())...)
|
||||
} else {
|
||||
a.logger.Info("collection created", "source", "user_activity", "severity", "user_activity", "code", 2410, "user_id", user.ID, "name", r.FormValue("name"))
|
||||
a.logger.Info("collection created", withRequestLogAttrs(r, "source", "user_activity", "severity", "user_activity", "code", 2410, "user_id", user.ID, "name", r.FormValue("name"))...)
|
||||
}
|
||||
http.Redirect(w, r, "/app", http.StatusSeeOther)
|
||||
}
|
||||
@@ -129,11 +135,11 @@ func (a *App) RenameUserBox(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if err := a.uploadService.RenameOwnedBox(r.PathValue("boxID"), user.ID, r.FormValue("title")); err != nil {
|
||||
a.logger.Warn("owned box rename failed", "source", "user_activity", "severity", "warn", "code", 4411, "user_id", user.ID, "box_id", r.PathValue("boxID"), "error", err.Error())
|
||||
a.logger.Warn("owned box rename failed", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4411, "user_id", user.ID, "box_id", r.PathValue("boxID"), "error", err.Error())...)
|
||||
a.handleUserBoxError(w, r, err)
|
||||
return
|
||||
}
|
||||
a.logger.Info("owned box renamed", "source", "user_activity", "severity", "user_activity", "code", 2411, "user_id", user.ID, "box_id", r.PathValue("boxID"))
|
||||
a.logger.Info("owned box renamed", withRequestLogAttrs(r, "source", "user_activity", "severity", "user_activity", "code", 2411, "user_id", user.ID, "box_id", r.PathValue("boxID"))...)
|
||||
http.Redirect(w, r, "/app", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -148,16 +154,16 @@ func (a *App) MoveUserBox(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
collectionID := r.FormValue("collection_id")
|
||||
if !a.authService.CollectionOwnedBy(collectionID, user.ID) {
|
||||
a.logger.Warn("owned box move invalid collection", "source", "user_activity", "severity", "warn", "code", 4412, "user_id", user.ID, "box_id", r.PathValue("boxID"), "collection_id", collectionID)
|
||||
a.logger.Warn("owned box move invalid collection", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4412, "user_id", user.ID, "box_id", r.PathValue("boxID"), "collection_id", collectionID)...)
|
||||
http.Error(w, "collection not found", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if err := a.uploadService.MoveOwnedBox(r.PathValue("boxID"), user.ID, collectionID); err != nil {
|
||||
a.logger.Warn("owned box move failed", "source", "user_activity", "severity", "warn", "code", 4413, "user_id", user.ID, "box_id", r.PathValue("boxID"), "error", err.Error())
|
||||
a.logger.Warn("owned box move failed", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4413, "user_id", user.ID, "box_id", r.PathValue("boxID"), "error", err.Error())...)
|
||||
a.handleUserBoxError(w, r, err)
|
||||
return
|
||||
}
|
||||
a.logger.Info("owned box moved", "source", "user_activity", "severity", "user_activity", "code", 2412, "user_id", user.ID, "box_id", r.PathValue("boxID"), "collection_id", collectionID)
|
||||
a.logger.Info("owned box moved", withRequestLogAttrs(r, "source", "user_activity", "severity", "user_activity", "code", 2412, "user_id", user.ID, "box_id", r.PathValue("boxID"), "collection_id", collectionID)...)
|
||||
http.Redirect(w, r, "/app", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -167,11 +173,11 @@ func (a *App) DeleteUserBox(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if err := a.uploadService.DeleteOwnedBox(r.PathValue("boxID"), user.ID); err != nil {
|
||||
a.logger.Warn("owned box delete failed", "source", "user_activity", "severity", "warn", "code", 4414, "user_id", user.ID, "box_id", r.PathValue("boxID"), "error", err.Error())
|
||||
a.logger.Warn("owned box delete failed", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4414, "user_id", user.ID, "box_id", r.PathValue("boxID"), "error", err.Error())...)
|
||||
a.handleUserBoxError(w, r, err)
|
||||
return
|
||||
}
|
||||
a.logger.Info("owned box deleted", "source", "user_activity", "severity", "user_activity", "code", 2413, "user_id", user.ID, "box_id", r.PathValue("boxID"))
|
||||
a.logger.Info("owned box deleted", withRequestLogAttrs(r, "source", "user_activity", "severity", "user_activity", "code", 2413, "user_id", user.ID, "box_id", r.PathValue("boxID"))...)
|
||||
http.Redirect(w, r, "/app", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,15 @@ package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -26,6 +29,7 @@ type downloadPageData struct {
|
||||
DownloadCount int
|
||||
MaxDownloads int
|
||||
ExpiresLabel string
|
||||
EmojiTabs []emojiTabView
|
||||
}
|
||||
|
||||
type boxView struct {
|
||||
@@ -41,6 +45,34 @@ type fileView struct {
|
||||
URL string
|
||||
DownloadURL string
|
||||
ThumbnailURL string
|
||||
HasThumbnail bool
|
||||
IconURL string
|
||||
IconRetroURL string
|
||||
ReactURL string
|
||||
Reactions []reactionView
|
||||
ReactionMore int
|
||||
Reacted bool
|
||||
Processing bool
|
||||
}
|
||||
|
||||
type reactionView struct {
|
||||
EmojiID string `json:"emojiId"`
|
||||
URL string `json:"url"`
|
||||
Label string `json:"label"`
|
||||
Count int `json:"count"`
|
||||
Visible bool `json:"visible"`
|
||||
}
|
||||
|
||||
type emojiTabView struct {
|
||||
ID string
|
||||
Label string
|
||||
Emojis []emojiOptionView
|
||||
}
|
||||
|
||||
type emojiOptionView struct {
|
||||
ID string `json:"id"`
|
||||
URL string `json:"url"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
type previewPageData struct {
|
||||
@@ -53,12 +85,12 @@ type previewPageData struct {
|
||||
func (a *App) DownloadPage(w http.ResponseWriter, r *http.Request) {
|
||||
box, err := a.uploadService.GetBox(r.PathValue("boxID"))
|
||||
if err != nil {
|
||||
a.logger.Warn("download page missing box", "source", "download", "severity", "warn", "code", 4040, "box_id", r.PathValue("boxID"), "ip", uploadClientIP(r))
|
||||
a.logger.Warn("download page missing box", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", 4040, "box_id", r.PathValue("boxID"))...)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := a.uploadService.CanDownload(box); err != nil {
|
||||
a.logger.Warn("download page unavailable", "source", "download", "severity", "warn", "code", statusForDownloadError(err), "box_id", box.ID, "ip", uploadClientIP(r), "error", err.Error())
|
||||
a.logger.Warn("download page unavailable", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", statusForDownloadError(err), "box_id", box.ID, "error", err.Error())...)
|
||||
a.renderPage(w, r, http.StatusForbidden, "download.html", web.PageData{
|
||||
Title: "Download unavailable",
|
||||
Description: "This Warpbox link is no longer available.",
|
||||
@@ -70,15 +102,33 @@ func (a *App) DownloadPage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
locked := a.uploadService.IsProtected(box) && !a.isBoxUnlocked(r, box)
|
||||
if isSocialPreviewBot(r) && !locked && len(box.Files) == 1 {
|
||||
if box.Files[0].Processing {
|
||||
http.Error(w, "file is still processing", http.StatusAccepted)
|
||||
return
|
||||
}
|
||||
a.serveFileContent(w, r, box, box.Files[0], false)
|
||||
a.logger.Info("single-file box served inline for social preview", withRequestLogAttrs(r, "source", "download", "severity", "user_activity", "code", 2008, "box_id", box.ID, "file_id", box.Files[0].ID)...)
|
||||
return
|
||||
}
|
||||
visitorID := a.reactionVisitorID(w, r)
|
||||
reactionsByFile, reactedByFile, err := a.reactionService.SummaryForBox(box.ID, visitorID)
|
||||
if err != nil {
|
||||
a.logger.Warn("failed to load file reactions", withRequestLogAttrs(r, "source", "reactions", "severity", "warn", "code", 4300, "box_id", box.ID, "error", err.Error())...)
|
||||
}
|
||||
|
||||
files := make([]fileView, 0, len(box.Files))
|
||||
if !(locked && box.Obfuscate) {
|
||||
for _, file := range box.Files {
|
||||
files = append(files, a.fileView(box, file))
|
||||
files = append(files, a.fileViewWithReactions(box, file, reactionsByFile[file.ID], reactedByFile[file.ID]))
|
||||
}
|
||||
}
|
||||
emojiTabs, err := a.emojiTabs()
|
||||
if err != nil {
|
||||
a.logger.Warn("failed to load emoji tabs", withRequestLogAttrs(r, "source", "reactions", "severity", "warn", "code", 4301, "box_id", box.ID, "error", err.Error())...)
|
||||
}
|
||||
|
||||
expiresLabel := box.ExpiresAt.Format("Jan 2, 2006 15:04 MST")
|
||||
expiresLabel := boxExpiryLabel(box.ExpiresAt, "Jan 2, 2006 15:04 MST")
|
||||
title := "Shared files on Warpbox"
|
||||
description := fmt.Sprintf("%d file%s shared via Warpbox · expires %s", len(box.Files), plural(len(box.Files)), expiresLabel)
|
||||
if locked && box.Obfuscate {
|
||||
@@ -99,9 +149,10 @@ func (a *App) DownloadPage(w http.ResponseWriter, r *http.Request) {
|
||||
DownloadCount: box.DownloadCount,
|
||||
MaxDownloads: box.MaxDownloads,
|
||||
ExpiresLabel: expiresLabel,
|
||||
EmojiTabs: emojiTabs,
|
||||
},
|
||||
})
|
||||
a.logger.Info("download page viewed", "source", "download", "severity", "user_activity", "code", 2003, "box_id", box.ID, "ip", uploadClientIP(r), "locked", locked)
|
||||
a.logger.Info("download page viewed", withRequestLogAttrs(r, "source", "download", "severity", "user_activity", "code", 2003, "box_id", box.ID, "locked", locked)...)
|
||||
}
|
||||
|
||||
func plural(n int) string {
|
||||
@@ -118,6 +169,15 @@ func (a *App) DownloadFile(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
locked := a.uploadService.IsProtected(box) && !a.isBoxUnlocked(r, box)
|
||||
if isSocialPreviewBot(r) && !locked {
|
||||
if file.Processing {
|
||||
http.Error(w, "file is still processing", http.StatusAccepted)
|
||||
return
|
||||
}
|
||||
a.serveFileContent(w, r, box, file, false)
|
||||
a.logger.Info("file served inline for social preview", withRequestLogAttrs(r, "source", "download", "severity", "user_activity", "code", 2009, "box_id", box.ID, "file_id", file.ID)...)
|
||||
return
|
||||
}
|
||||
view := a.fileView(box, file)
|
||||
title := file.Name
|
||||
description := fmt.Sprintf("%s shared via Warpbox", helpers.FormatBytes(file.Size))
|
||||
@@ -139,7 +199,7 @@ func (a *App) DownloadFile(w http.ResponseWriter, r *http.Request) {
|
||||
DownloadURL: view.DownloadURL,
|
||||
},
|
||||
})
|
||||
a.logger.Info("file preview page viewed", "source", "download", "severity", "user_activity", "code", 2004, "box_id", box.ID, "file_id", file.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Info("file preview page viewed", withRequestLogAttrs(r, "source", "download", "severity", "user_activity", "code", 2004, "box_id", box.ID, "file_id", file.ID)...)
|
||||
}
|
||||
|
||||
func (a *App) DownloadFileContent(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -148,13 +208,17 @@ func (a *App) DownloadFileContent(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if a.uploadService.IsProtected(box) && !a.isBoxUnlocked(r, box) {
|
||||
a.logger.Warn("protected file download blocked", "source", "download", "severity", "warn", "code", 4013, "box_id", box.ID, "file_id", file.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Warn("protected file download blocked", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", 4013, "box_id", box.ID, "file_id", file.ID)...)
|
||||
http.Error(w, "password required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if file.Processing {
|
||||
http.Error(w, "file is still processing", http.StatusAccepted)
|
||||
return
|
||||
}
|
||||
|
||||
a.serveFileContent(w, r, box, file, r.URL.Query().Get("inline") != "1")
|
||||
a.logger.Info("file content served", "source", "download", "severity", "user_activity", "code", 2005, "box_id", box.ID, "file_id", file.ID, "ip", uploadClientIP(r), "attachment", r.URL.Query().Get("inline") != "1")
|
||||
a.logger.Info("file content served", withRequestLogAttrs(r, "source", "download", "severity", "user_activity", "code", 2005, "box_id", box.ID, "file_id", file.ID, "attachment", r.URL.Query().Get("inline") != "1")...)
|
||||
}
|
||||
|
||||
func (a *App) Thumbnail(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -202,7 +266,7 @@ func (a *App) UnlockBox(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if !a.uploadService.VerifyPassword(box, r.FormValue("password")) {
|
||||
a.logger.Warn("box unlock failed", "source", "user_activity", "severity", "warn", "code", 4011, "box_id", box.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Warn("box unlock failed", withRequestLogAttrs(r, "source", "user_activity", "severity", "warn", "code", 4011, "box_id", box.ID)...)
|
||||
http.Redirect(w, r, fmt.Sprintf("/d/%s", box.ID), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
@@ -215,26 +279,26 @@ func (a *App) UnlockBox(w http.ResponseWriter, r *http.Request) {
|
||||
Secure: r.TLS != nil,
|
||||
Expires: box.ExpiresAt,
|
||||
})
|
||||
a.logger.Info("box unlocked", "source", "user_activity", "severity", "user_activity", "code", 2002, "box_id", box.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Info("box unlocked", withRequestLogAttrs(r, "source", "user_activity", "severity", "user_activity", "code", 2002, "box_id", box.ID)...)
|
||||
http.Redirect(w, r, fmt.Sprintf("/d/%s", box.ID), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (a *App) loadFileForRequest(w http.ResponseWriter, r *http.Request) (services.Box, services.File, bool) {
|
||||
box, err := a.uploadService.GetBox(r.PathValue("boxID"))
|
||||
if err != nil {
|
||||
a.logger.Warn("file request missing box", "source", "download", "severity", "warn", "code", 4041, "box_id", r.PathValue("boxID"), "file_id", r.PathValue("fileID"), "ip", uploadClientIP(r))
|
||||
a.logger.Warn("file request missing box", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", 4041, "box_id", r.PathValue("boxID"), "file_id", r.PathValue("fileID"))...)
|
||||
http.NotFound(w, r)
|
||||
return services.Box{}, services.File{}, false
|
||||
}
|
||||
if err := a.uploadService.CanDownload(box); err != nil {
|
||||
a.logger.Warn("file request unavailable", "source", "download", "severity", "warn", "code", statusForDownloadError(err), "box_id", box.ID, "file_id", r.PathValue("fileID"), "ip", uploadClientIP(r), "error", err.Error())
|
||||
a.logger.Warn("file request unavailable", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", statusForDownloadError(err), "box_id", box.ID, "file_id", r.PathValue("fileID"), "error", err.Error())...)
|
||||
http.Error(w, err.Error(), statusForDownloadError(err))
|
||||
return services.Box{}, services.File{}, false
|
||||
}
|
||||
|
||||
file, err := a.uploadService.FindFile(box, r.PathValue("fileID"))
|
||||
if err != nil {
|
||||
a.logger.Warn("file request missing file", "source", "download", "severity", "warn", "code", 4042, "box_id", box.ID, "file_id", r.PathValue("fileID"), "ip", uploadClientIP(r))
|
||||
a.logger.Warn("file request missing file", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", 4042, "box_id", box.ID, "file_id", r.PathValue("fileID"))...)
|
||||
http.NotFound(w, r)
|
||||
return services.Box{}, services.File{}, false
|
||||
}
|
||||
@@ -244,7 +308,7 @@ func (a *App) loadFileForRequest(w http.ResponseWriter, r *http.Request) (servic
|
||||
func (a *App) serveFileContent(w http.ResponseWriter, r *http.Request, box services.Box, file services.File, attachment bool) {
|
||||
object, err := a.uploadService.OpenFileObject(r.Context(), box, file)
|
||||
if err != nil {
|
||||
a.logger.Warn("file object missing", "source", "download", "severity", "warn", "code", 4043, "box_id", box.ID, "file_id", file.ID, "ip", uploadClientIP(r), "error", err.Error())
|
||||
a.logger.Warn("file object missing", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", 4043, "box_id", box.ID, "file_id", file.ID, "error", err.Error())...)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
@@ -280,17 +344,17 @@ func readSeekCloser(source io.ReadCloser) io.ReadSeeker {
|
||||
func (a *App) DownloadZip(w http.ResponseWriter, r *http.Request) {
|
||||
box, err := a.uploadService.GetBox(r.PathValue("boxID"))
|
||||
if err != nil {
|
||||
a.logger.Warn("zip request missing box", "source", "download", "severity", "warn", "code", 4044, "box_id", r.PathValue("boxID"), "ip", uploadClientIP(r))
|
||||
a.logger.Warn("zip request missing box", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", 4044, "box_id", r.PathValue("boxID"))...)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := a.uploadService.CanDownload(box); err != nil {
|
||||
a.logger.Warn("zip request unavailable", "source", "download", "severity", "warn", "code", statusForDownloadError(err), "box_id", box.ID, "ip", uploadClientIP(r), "error", err.Error())
|
||||
a.logger.Warn("zip request unavailable", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", statusForDownloadError(err), "box_id", box.ID, "error", err.Error())...)
|
||||
http.Error(w, err.Error(), statusForDownloadError(err))
|
||||
return
|
||||
}
|
||||
if a.uploadService.IsProtected(box) && !a.isBoxUnlocked(r, box) {
|
||||
a.logger.Warn("protected zip download blocked", "source", "download", "severity", "warn", "code", 4014, "box_id", box.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Warn("protected zip download blocked", withRequestLogAttrs(r, "source", "download", "severity", "warn", "code", 4014, "box_id", box.ID)...)
|
||||
http.Error(w, "password required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
@@ -306,10 +370,16 @@ func (a *App) DownloadZip(w http.ResponseWriter, r *http.Request) {
|
||||
if err := a.uploadService.RecordDownload(box.ID); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
a.logger.Warn("failed to record zip download", "source", "download", "severity", "warn", "code", 4003, "box_id", box.ID, "error", err.Error())
|
||||
}
|
||||
a.logger.Info("zip downloaded", "source", "download", "severity", "user_activity", "code", 2006, "box_id", box.ID, "ip", uploadClientIP(r), "files", len(box.Files))
|
||||
a.logger.Info("zip downloaded", withRequestLogAttrs(r, "source", "download", "severity", "user_activity", "code", 2006, "box_id", box.ID, "files", len(box.Files))...)
|
||||
}
|
||||
|
||||
func (a *App) fileView(box services.Box, file services.File) fileView {
|
||||
return a.fileViewWithReactions(box, file, nil, false)
|
||||
}
|
||||
|
||||
func (a *App) fileViewWithReactions(box services.Box, file services.File, reactions []services.ReactionSummary, reacted bool) fileView {
|
||||
icon := a.fileIcons.lookup(file.Name, file.ContentType)
|
||||
reactionViews := a.reactionViews(reactions)
|
||||
return fileView{
|
||||
ID: file.ID,
|
||||
Name: file.Name,
|
||||
@@ -319,9 +389,184 @@ func (a *App) fileView(box services.Box, file services.File) fileView {
|
||||
URL: fmt.Sprintf("/d/%s/f/%s", box.ID, file.ID),
|
||||
DownloadURL: fmt.Sprintf("/d/%s/f/%s/download", box.ID, file.ID),
|
||||
ThumbnailURL: fmt.Sprintf("/d/%s/thumb/%s", box.ID, file.ID),
|
||||
HasThumbnail: file.Thumbnail != "",
|
||||
IconURL: fileIconURL("standard", icon.Standard),
|
||||
IconRetroURL: fileIconURL("retro", icon.Retro),
|
||||
ReactURL: fmt.Sprintf("/d/%s/f/%s/react", box.ID, file.ID),
|
||||
Reactions: reactionViews,
|
||||
ReactionMore: reactionOverflowCount(reactionViews),
|
||||
Reacted: reacted,
|
||||
Processing: file.Processing,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) ReactToFile(w http.ResponseWriter, r *http.Request) {
|
||||
box, file, ok := a.loadFileForRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if a.uploadService.IsProtected(box) && !a.isBoxUnlocked(r, box) {
|
||||
http.Error(w, "password required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid reaction", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
emojiID := strings.TrimSpace(r.FormValue("emoji_id"))
|
||||
if !a.validEmojiID(emojiID) {
|
||||
http.Error(w, "unknown emoji", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
visitorID := a.reactionVisitorID(w, r)
|
||||
reactions, err := a.reactionService.Add(box.ID, file.ID, visitorID, emojiID)
|
||||
if errors.Is(err, os.ErrExist) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": "already reacted"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Warn("file reaction failed", withRequestLogAttrs(r, "source", "reactions", "severity", "warn", "code", 4302, "box_id", box.ID, "file_id", file.ID, "error", err.Error())...)
|
||||
http.Error(w, "could not save reaction", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
a.logger.Info("file reaction added", withRequestLogAttrs(r, "source", "reactions", "severity", "user_activity", "code", 2301, "box_id", box.ID, "file_id", file.ID, "emoji_id", emojiID)...)
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"reactions": a.reactionViews(reactions),
|
||||
"reacted": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) reactionViews(reactions []services.ReactionSummary) []reactionView {
|
||||
views := make([]reactionView, 0, len(reactions))
|
||||
for index, reaction := range reactions {
|
||||
views = append(views, reactionView{
|
||||
EmojiID: reaction.EmojiID,
|
||||
URL: emojiURL(reaction.EmojiID),
|
||||
Label: emojiLabel(reaction.EmojiID),
|
||||
Count: reaction.Count,
|
||||
Visible: index < 2,
|
||||
})
|
||||
}
|
||||
return views
|
||||
}
|
||||
|
||||
func reactionOverflowCount(reactions []reactionView) int {
|
||||
if len(reactions) <= 2 {
|
||||
return 0
|
||||
}
|
||||
return len(reactions) - 2
|
||||
}
|
||||
|
||||
func (a *App) emojiTabs() ([]emojiTabView, error) {
|
||||
root := a.emojiRoot()
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
tabs := make([]emojiTabView, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
tabID := entry.Name()
|
||||
files, err := os.ReadDir(filepath.Join(root, tabID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tab := emojiTabView{ID: tabID, Label: emojiTabLabel(tabID)}
|
||||
for _, file := range files {
|
||||
if file.IsDir() || !isEmojiFile(file.Name()) {
|
||||
continue
|
||||
}
|
||||
emojiID := tabID + "/" + file.Name()
|
||||
tab.Emojis = append(tab.Emojis, emojiOptionView{
|
||||
ID: emojiID,
|
||||
URL: emojiURL(emojiID),
|
||||
Label: emojiLabel(emojiID),
|
||||
})
|
||||
}
|
||||
sort.Slice(tab.Emojis, func(i, j int) bool { return tab.Emojis[i].ID < tab.Emojis[j].ID })
|
||||
if len(tab.Emojis) > 0 {
|
||||
tabs = append(tabs, tab)
|
||||
}
|
||||
}
|
||||
sort.Slice(tabs, func(i, j int) bool { return tabs[i].ID < tabs[j].ID })
|
||||
return tabs, nil
|
||||
}
|
||||
|
||||
func (a *App) validEmojiID(id string) bool {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" || strings.Contains(id, "\\") || strings.Contains(id, "..") || strings.HasPrefix(id, "/") {
|
||||
return false
|
||||
}
|
||||
parts := strings.Split(id, "/")
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" || !isEmojiFile(parts[1]) {
|
||||
return false
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(a.emojiRoot(), parts[0], parts[1]))
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
|
||||
func (a *App) emojiRoot() string {
|
||||
return filepath.Join(a.cfg.DataDir, "emoji")
|
||||
}
|
||||
|
||||
func (a *App) reactionVisitorID(w http.ResponseWriter, r *http.Request) string {
|
||||
const cookieName = "warpbox_reactor"
|
||||
if cookie, err := r.Cookie(cookieName); err == nil && strings.TrimSpace(cookie.Value) != "" {
|
||||
return cookie.Value
|
||||
}
|
||||
visitorID := services.RandomPublicToken(32)
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: visitorID,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Secure: r.TLS != nil,
|
||||
Expires: time.Now().AddDate(1, 0, 0),
|
||||
})
|
||||
return visitorID
|
||||
}
|
||||
|
||||
func isEmojiFile(name string) bool {
|
||||
ext := strings.ToLower(filepath.Ext(name))
|
||||
return ext == ".svg" || ext == ".webp" || ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif"
|
||||
}
|
||||
|
||||
func emojiTabLabel(id string) string {
|
||||
label := strings.NewReplacer("-", " ", "_", " ").Replace(id)
|
||||
if label == "" {
|
||||
return "Emoji"
|
||||
}
|
||||
return strings.ToUpper(label[:1]) + label[1:]
|
||||
}
|
||||
|
||||
func emojiLabel(id string) string {
|
||||
base := strings.TrimSuffix(filepath.Base(id), filepath.Ext(id))
|
||||
return strings.ReplaceAll(base, "-", " ")
|
||||
}
|
||||
|
||||
func emojiURL(id string) string {
|
||||
parts := strings.Split(id, "/")
|
||||
if len(parts) != 2 {
|
||||
return ""
|
||||
}
|
||||
return "/emoji/" + url.PathEscape(parts[0]) + "/" + url.PathEscape(parts[1])
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func (a *App) isBoxUnlocked(r *http.Request, box services.Box) bool {
|
||||
if !a.uploadService.IsProtected(box) {
|
||||
return true
|
||||
@@ -337,6 +582,21 @@ func unlockCookieName(boxID string) string {
|
||||
return "warpbox_unlock_" + strings.NewReplacer("-", "_", ".", "_").Replace(boxID)
|
||||
}
|
||||
|
||||
// neverExpires reports whether a box's expiry is far enough out to be treated as
|
||||
// "forever" (set via the unlimited / -1 expiry option).
|
||||
func neverExpires(t time.Time) bool {
|
||||
return time.Until(t) > 50*365*24*time.Hour
|
||||
}
|
||||
|
||||
// boxExpiryLabel formats a box's expiry with the given layout, rendering
|
||||
// "forever" boxes as "Never" instead of a meaningless far-future date.
|
||||
func boxExpiryLabel(t time.Time, layout string) string {
|
||||
if neverExpires(t) {
|
||||
return "Never"
|
||||
}
|
||||
return t.Format(layout)
|
||||
}
|
||||
|
||||
func absoluteURL(r *http.Request, path string) string {
|
||||
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
|
||||
return path
|
||||
@@ -347,3 +607,31 @@ func absoluteURL(r *http.Request, path string) string {
|
||||
}
|
||||
return fmt.Sprintf("%s://%s%s", scheme, r.Host, path)
|
||||
}
|
||||
|
||||
func isSocialPreviewBot(r *http.Request) bool {
|
||||
agent := strings.ToLower(r.UserAgent())
|
||||
if agent == "" {
|
||||
return false
|
||||
}
|
||||
bots := []string{
|
||||
"discordbot",
|
||||
"twitterbot",
|
||||
"facebookexternalhit",
|
||||
"telegrambot",
|
||||
"whatsapp",
|
||||
"slackbot",
|
||||
"linkedinbot",
|
||||
"skypeuripreview",
|
||||
"embedly",
|
||||
"pinterest",
|
||||
"vkshare",
|
||||
"mattermost",
|
||||
"mastodon",
|
||||
}
|
||||
for _, bot := range bots {
|
||||
if strings.Contains(agent, bot) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@ type healthResponse struct {
|
||||
}
|
||||
|
||||
func (a *App) Health(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/health" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
helpers.WriteJSON(w, http.StatusOK, healthResponse{
|
||||
Status: "ok",
|
||||
Time: time.Now().UTC().Format(time.RFC3339),
|
||||
|
||||
@@ -13,16 +13,20 @@ func TestHealthRoutes(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
app.RegisterRoutes(mux)
|
||||
|
||||
for _, path := range []string{"/health", "/healthz", "/api/v1/health"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
response := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/health", nil)
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
mux.ServeHTTP(response, request)
|
||||
mux.ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
})
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
for _, path := range []string{"/healthz", "/api/v1/health"} {
|
||||
request := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
response := httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf("%s status = %d, want 404", path, response.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
152
backend/libs/handlers/icons.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// fileIcon holds the two icon filenames for a file type: the standard (modern)
|
||||
// icon and the retro (Win98) icon. The filenames are resolved against
|
||||
// static/file-icons/standard and static/file-icons/retro respectively.
|
||||
type fileIcon struct {
|
||||
Standard string `json:"standard"`
|
||||
Retro string `json:"retro"`
|
||||
}
|
||||
|
||||
type iconType struct {
|
||||
Mime string `json:"mime"`
|
||||
Standard string `json:"standard"`
|
||||
Retro string `json:"retro"`
|
||||
Extensions []string `json:"extensions"`
|
||||
}
|
||||
|
||||
type iconMapFile struct {
|
||||
Default iconType `json:"default"`
|
||||
Types []iconType `json:"types"`
|
||||
}
|
||||
|
||||
type mimeRule struct {
|
||||
pattern string // exact mime ("application/pdf") or major prefix ("image/")
|
||||
prefix bool
|
||||
icon fileIcon
|
||||
}
|
||||
|
||||
// fileIconSet is the loaded icon map: an extension lookup plus content-type
|
||||
// rules and a fallback. It is built once at startup from icon-map.json.
|
||||
type fileIconSet struct {
|
||||
byExt map[string]fileIcon
|
||||
byMime []mimeRule
|
||||
fallback fileIcon
|
||||
}
|
||||
|
||||
// loadFileIcons reads static/file-icons/icon-map.json and indexes it by
|
||||
// extension and content type so icons can be assigned at render time.
|
||||
func loadFileIcons(staticDir string) (*fileIconSet, error) {
|
||||
data, err := os.ReadFile(filepath.Join(staticDir, "file-icons", "icon-map.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var raw iconMapFile
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
set := &fileIconSet{
|
||||
byExt: make(map[string]fileIcon),
|
||||
fallback: fileIcon{Standard: raw.Default.Standard, Retro: raw.Default.Retro},
|
||||
}
|
||||
if err := validateFileIcon(staticDir, set.fallback); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, t := range raw.Types {
|
||||
icon := fileIcon{Standard: t.Standard, Retro: t.Retro}
|
||||
if err := validateFileIcon(staticDir, icon); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, ext := range t.Extensions {
|
||||
set.byExt[strings.ToLower(strings.TrimPrefix(ext, "."))] = icon
|
||||
}
|
||||
if t.Mime == "" {
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(t.Mime, "/*") {
|
||||
set.byMime = append(set.byMime, mimeRule{pattern: strings.TrimSuffix(t.Mime, "*"), prefix: true, icon: icon})
|
||||
} else {
|
||||
set.byMime = append(set.byMime, mimeRule{pattern: strings.ToLower(t.Mime), icon: icon})
|
||||
}
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
func validateFileIcon(staticDir string, icon fileIcon) error {
|
||||
if icon.Standard != "" {
|
||||
if err := validateFileIconPath(staticDir, "standard", icon.Standard); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if icon.Retro != "" {
|
||||
if err := validateFileIconPath(staticDir, "retro", icon.Retro); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateFileIconPath(staticDir, theme, name string) error {
|
||||
if strings.Contains(name, "/") || strings.Contains(name, "\\") || strings.Contains(name, "..") {
|
||||
return fmt.Errorf("invalid %s file icon path %q", theme, name)
|
||||
}
|
||||
path := filepath.Join(staticDir, "file-icons", theme, name)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("missing %s file icon %q: %w", theme, name, err)
|
||||
}
|
||||
if info.IsDir() {
|
||||
return fmt.Errorf("%s file icon %q is a directory", theme, name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lookup resolves a file's icon from its name (extension) first, falling back to
|
||||
// its content type, then to the default icon. Extension wins because stored
|
||||
// content types are often the generic application/octet-stream.
|
||||
func (s *fileIconSet) lookup(name, contentType string) fileIcon {
|
||||
if s == nil {
|
||||
return fileIcon{}
|
||||
}
|
||||
if ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(name), ".")); ext != "" {
|
||||
if icon, ok := s.byExt[ext]; ok {
|
||||
return icon
|
||||
}
|
||||
}
|
||||
|
||||
ct := strings.ToLower(strings.TrimSpace(contentType))
|
||||
if i := strings.IndexByte(ct, ';'); i >= 0 {
|
||||
ct = strings.TrimSpace(ct[:i])
|
||||
}
|
||||
if ct != "" && ct != "application/octet-stream" {
|
||||
for _, rule := range s.byMime { // exact matches first
|
||||
if !rule.prefix && rule.pattern == ct {
|
||||
return rule.icon
|
||||
}
|
||||
}
|
||||
for _, rule := range s.byMime { // then major-type prefixes
|
||||
if rule.prefix && strings.HasPrefix(ct, rule.pattern) {
|
||||
return rule.icon
|
||||
}
|
||||
}
|
||||
}
|
||||
return s.fallback
|
||||
}
|
||||
|
||||
// fileIconURL builds the /static URL for an icon filename in the given theme
|
||||
// directory ("standard" or "retro").
|
||||
func fileIconURL(theme, name string) string {
|
||||
if name == "" {
|
||||
return ""
|
||||
}
|
||||
return "/static/file-icons/" + theme + "/" + name
|
||||
}
|
||||
54
backend/libs/handlers/icons_test.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFileIconMapLoadsAndResolvesCommonTypes(t *testing.T) {
|
||||
icons, err := loadFileIcons(filepath.Join("..", "..", "static"))
|
||||
if err != nil {
|
||||
t.Fatalf("loadFileIcons returned error: %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
wantStandard string
|
||||
wantRetro string
|
||||
}{
|
||||
{
|
||||
name: "photo.jpg",
|
||||
contentType: "application/octet-stream",
|
||||
wantStandard: "image-document-svgrepo-com.svg",
|
||||
wantRetro: "shimgvw.dll_14_1-2.png",
|
||||
},
|
||||
{
|
||||
name: "movie.mkv",
|
||||
contentType: "",
|
||||
wantStandard: "video-document-svgrepo-com.svg",
|
||||
wantRetro: "wmploc.dll_14_504-2.png",
|
||||
},
|
||||
{
|
||||
name: "archive.7z",
|
||||
contentType: "",
|
||||
wantStandard: "zip-document-svgrepo-com.svg",
|
||||
wantRetro: "zipfldr.dll_14_101-2.png",
|
||||
},
|
||||
{
|
||||
name: "unknown.bin",
|
||||
contentType: "application/octet-stream",
|
||||
wantStandard: "txt-document-svgrepo-com.svg",
|
||||
wantRetro: "shell32.dll_14_152-2.png",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := icons.lookup(tt.name, tt.contentType)
|
||||
if got.Standard != tt.wantStandard || got.Retro != tt.wantRetro {
|
||||
t.Fatalf("lookup returned %+v, want standard=%q retro=%q", got, tt.wantStandard, tt.wantRetro)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
29
backend/libs/handlers/logging.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"warpbox.dev/backend/libs/middleware"
|
||||
)
|
||||
|
||||
func requestLogAttrs(r *http.Request) []any {
|
||||
attrs := []any{
|
||||
"ip", uploadClientIP(r),
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
}
|
||||
if requestID := middleware.RequestIDFromContext(r.Context()); requestID != "" {
|
||||
attrs = append(attrs, "request_id", requestID)
|
||||
}
|
||||
if userAgent := r.UserAgent(); userAgent != "" {
|
||||
attrs = append(attrs, "user_agent", userAgent)
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
func withRequestLogAttrs(r *http.Request, attrs ...any) []any {
|
||||
out := make([]any, 0, len(attrs)+8)
|
||||
out = append(out, attrs...)
|
||||
out = append(out, requestLogAttrs(r)...)
|
||||
return out
|
||||
}
|
||||
@@ -31,7 +31,7 @@ func (a *App) ManageBox(w http.ResponseWriter, r *http.Request) {
|
||||
Description: "Delete this anonymous Warpbox upload.",
|
||||
Data: a.managePageData(box, r.PathValue("token")),
|
||||
})
|
||||
a.logger.Info("anonymous manage page viewed", "source", "anonymous-delete", "severity", "user_activity", "code", 2102, "box_id", box.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Info("anonymous manage page viewed", withRequestLogAttrs(r, "source", "anonymous-delete", "severity", "user_activity", "code", 2102, "box_id", box.ID)...)
|
||||
}
|
||||
|
||||
func (a *App) ManageDeleteBox(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -41,11 +41,11 @@ func (a *App) ManageDeleteBox(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if err := a.uploadService.DeleteBoxWithToken(box.ID, r.PathValue("token")); err != nil {
|
||||
a.logger.Warn("anonymous delete failed", "source", "anonymous-delete", "severity", "warn", "code", 4102, "box_id", box.ID, "ip", uploadClientIP(r), "error", err.Error())
|
||||
a.logger.Warn("anonymous delete failed", withRequestLogAttrs(r, "source", "anonymous-delete", "severity", "warn", "code", 4102, "box_id", box.ID, "error", err.Error())...)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
a.logger.Info("anonymous box deleted", "source", "anonymous-delete", "severity", "user_activity", "code", 2103, "box_id", box.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Info("anonymous box deleted", withRequestLogAttrs(r, "source", "anonymous-delete", "severity", "user_activity", "code", 2103, "box_id", box.ID)...)
|
||||
http.Redirect(w, r, "/d/"+box.ID+"/deleted", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -60,12 +60,12 @@ func (a *App) ManageDeleted(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *App) loadManagedBox(w http.ResponseWriter, r *http.Request) (services.Box, bool) {
|
||||
box, err := a.uploadService.GetBox(r.PathValue("boxID"))
|
||||
if err != nil {
|
||||
a.logger.Warn("anonymous manage missing box", "source", "anonymous-delete", "severity", "warn", "code", 4103, "box_id", r.PathValue("boxID"), "ip", uploadClientIP(r))
|
||||
a.logger.Warn("anonymous manage missing box", withRequestLogAttrs(r, "source", "anonymous-delete", "severity", "warn", "code", 4103, "box_id", r.PathValue("boxID"))...)
|
||||
http.NotFound(w, r)
|
||||
return services.Box{}, false
|
||||
}
|
||||
if !a.uploadService.VerifyDeleteToken(box, r.PathValue("token")) {
|
||||
a.logger.Warn("anonymous manage invalid token", "source", "anonymous-delete", "severity", "warn", "code", 4104, "box_id", box.ID, "ip", uploadClientIP(r))
|
||||
a.logger.Warn("anonymous manage invalid token", withRequestLogAttrs(r, "source", "anonymous-delete", "severity", "warn", "code", 4104, "box_id", box.ID)...)
|
||||
http.NotFound(w, r)
|
||||
return services.Box{}, false
|
||||
}
|
||||
@@ -82,7 +82,7 @@ func (a *App) managePageData(box services.Box, token string) managePageData {
|
||||
Token: token,
|
||||
FileCount: len(box.Files),
|
||||
TotalSize: helpers.FormatBytes(totalSize),
|
||||
ExpiresLabel: box.ExpiresAt.Format("Jan 2, 2006 15:04 MST"),
|
||||
ExpiresLabel: boxExpiryLabel(box.ExpiresAt, "Jan 2, 2006 15:04 MST"),
|
||||
DownloadCount: box.DownloadCount,
|
||||
MaxDownloads: box.MaxDownloads,
|
||||
Protected: a.uploadService.IsProtected(box),
|
||||
|
||||
@@ -46,6 +46,17 @@ func (a *App) Home(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "unable to load upload policy", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
actor := "anonymous"
|
||||
if loggedIn {
|
||||
actor = "user"
|
||||
}
|
||||
a.logger.Info("upload page viewed", withRequestLogAttrs(r,
|
||||
"source", "page",
|
||||
"severity", "user_activity",
|
||||
"code", 2500,
|
||||
"actor", actor,
|
||||
"user_id", user.ID,
|
||||
)...)
|
||||
maxUploadSize, limitSummary := a.homeUploadPolicyLabels(settings, user, loggedIn, isAdmin)
|
||||
expiryOptions, defaultExpiry := a.homeExpiryOptions(settings, user, loggedIn, isAdmin)
|
||||
a.renderPage(w, r, http.StatusOK, "home.html", web.PageData{
|
||||
@@ -75,12 +86,16 @@ func (a *App) homeExpiryOptions(settings services.UploadPolicySettings, user ser
|
||||
unlimited = true
|
||||
case loggedIn:
|
||||
maxDays = a.settingsService.EffectivePolicyForUser(settings, user).MaxDays
|
||||
// A negative per-user MaxDays override means unlimited retention.
|
||||
if maxDays < 0 {
|
||||
unlimited = true
|
||||
}
|
||||
}
|
||||
return buildExpiryOptions(maxDays, unlimited)
|
||||
}
|
||||
|
||||
func buildExpiryOptions(maxDays int, unlimited bool) ([]expiryOption, int) {
|
||||
ladder := []int{60, 720, 1440, 2880, 4320, 7200, 10080, 14400, 20160, 43200, 86400, 129600, 259200, 525600}
|
||||
ladder := []int{60, 360, 720, 1440, 2880, 4320, 7200, 10080, 14400, 20160, 43200, 86400, 129600, 259200, 525600}
|
||||
|
||||
capMinutes := maxDays * 24 * 60
|
||||
if unlimited || capMinutes <= 0 {
|
||||
@@ -103,6 +118,10 @@ func buildExpiryOptions(maxDays int, unlimited bool) ([]expiryOption, int) {
|
||||
if len(options) == 0 {
|
||||
options = append(options, expiryOption{Minutes: capMinutes, Label: expiryLabel(capMinutes)})
|
||||
}
|
||||
// Unlimited uploaders can pick "never expires" (sentinel -1) after the ladder.
|
||||
if unlimited {
|
||||
options = append(options, expiryOption{Minutes: -1, Label: "Unlimited (never expires)"})
|
||||
}
|
||||
|
||||
// Default to 24h when available, otherwise the smallest option offered.
|
||||
defaultMinutes := options[0].Minutes
|
||||
@@ -154,5 +173,9 @@ func (a *App) homeUploadPolicyLabels(settings services.UploadPolicySettings, use
|
||||
if policy.StorageQuotaSet {
|
||||
quota = services.FormatMegabytesLabel(policy.StorageQuotaMB)
|
||||
}
|
||||
return maxUpload, "Daily cap: " + services.FormatMegabytesLabel(policy.DailyUploadMB) + " · Storage quota: " + quota + " · " + strconv.Itoa(policy.MaxDays) + " day max."
|
||||
expiryLimit := strconv.Itoa(policy.MaxDays) + " day max."
|
||||
if policy.MaxDays < 0 {
|
||||
expiryLimit = "no expiry limit."
|
||||
}
|
||||
return maxUpload, "Daily cap: " + services.FormatMegabytesLabel(policy.DailyUploadMB) + " · Storage quota: " + quota + " · " + expiryLimit
|
||||
}
|
||||
|
||||
427
backend/libs/handlers/resumable.go
Normal file
@@ -0,0 +1,427 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"warpbox.dev/backend/libs/helpers"
|
||||
"warpbox.dev/backend/libs/jobs"
|
||||
"warpbox.dev/backend/libs/services"
|
||||
)
|
||||
|
||||
type resumableCreateRequest struct {
|
||||
Files []services.ResumableFileInput `json:"files"`
|
||||
MaxDays int `json:"maxDays"`
|
||||
ExpiresMinutes int `json:"expiresMinutes"`
|
||||
MaxDownloads int `json:"maxDownloads"`
|
||||
Password string `json:"password"`
|
||||
ObfuscateMetadata bool `json:"obfuscateMetadata"`
|
||||
CollectionID string `json:"collectionId"`
|
||||
}
|
||||
|
||||
type resumableSessionResponse struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
ResumeToken string `json:"resumeToken,omitempty"`
|
||||
ChunkSize int64 `json:"chunkSize"`
|
||||
Status string `json:"status"`
|
||||
BoxID string `json:"boxId,omitempty"`
|
||||
ExpiresAt string `json:"expiresAt"`
|
||||
Files []services.ResumableFile `json:"files"`
|
||||
}
|
||||
|
||||
func (a *App) CreateResumableUpload(w http.ResponseWriter, r *http.Request) {
|
||||
user, loggedIn, authErr := a.currentUserWithAuthError(r)
|
||||
if authErr != nil {
|
||||
a.logger.Warn("resumable upload rejected invalid bearer token", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4011)...)
|
||||
helpers.WriteJSONError(w, http.StatusUnauthorized, "invalid bearer token")
|
||||
return
|
||||
}
|
||||
isAdminUpload := loggedIn && user.Role == services.UserRoleAdmin
|
||||
settings, policy, ok := a.loadUploadPolicyForAPI(w, r, user, loggedIn)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !settings.ResumableUploadsEnabled {
|
||||
helpers.WriteJSONError(w, http.StatusForbidden, "resumable uploads are disabled")
|
||||
return
|
||||
}
|
||||
if !loggedIn && !settings.AnonymousUploadsEnabled {
|
||||
a.logger.Warn("resumable anonymous upload rejected disabled", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4013)...)
|
||||
helpers.WriteJSONError(w, http.StatusForbidden, "anonymous uploads are disabled")
|
||||
return
|
||||
}
|
||||
rateKey := uploadRateKey(r, user, loggedIn)
|
||||
if !isAdminUpload && policy.ShortRequests > 0 && !a.rateLimiter.Allow("upload:"+rateKey, policy.ShortRequests, policy.ShortWindow, time.Now().UTC()) {
|
||||
a.logger.Warn("resumable upload rate limited", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4291, "user_id", user.ID)...)
|
||||
helpers.WriteJSONError(w, http.StatusTooManyRequests, "too many upload requests, please slow down")
|
||||
return
|
||||
}
|
||||
|
||||
var payload resumableCreateRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, "upload session request could not be read")
|
||||
return
|
||||
}
|
||||
fileSizes := make([]int64, 0, len(payload.Files))
|
||||
var totalBytes int64
|
||||
for _, file := range payload.Files {
|
||||
fileSizes = append(fileSizes, file.Size)
|
||||
totalBytes += file.Size
|
||||
}
|
||||
if !isAdminUpload {
|
||||
if status, message := a.checkUploadPolicyForSizes(r, user, loggedIn, settings, policy, fileSizes, totalBytes); message != "" {
|
||||
a.logger.Warn("resumable upload rejected by policy", withRequestLogAttrs(r, "source", "quota", "severity", "warn", "code", status, "user_id", user.ID, "message", message, "bytes", totalBytes, "files", len(payload.Files))...)
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
if status, message := a.checkBoxCreationPolicy(r, user, loggedIn, policy); message != "" {
|
||||
a.logger.Warn("resumable upload rejected by box policy", withRequestLogAttrs(r, "source", "quota", "severity", "warn", "code", status, "user_id", user.ID, "message", message, "bytes", totalBytes, "files", len(payload.Files))...)
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
opts, err := a.resumableUploadOptions(r, payload, user, loggedIn, isAdminUpload, policy)
|
||||
if err != nil {
|
||||
helpers.WriteJSONError(w, http.StatusRequestEntityTooLarge, err.Error())
|
||||
return
|
||||
}
|
||||
chunkSize := int64(settings.ResumableChunkSizeMB * 1024 * 1024)
|
||||
retention := time.Duration(settings.ResumableRetentionHours) * time.Hour
|
||||
session, err := a.uploadService.CreateResumableSession(payload.Files, opts, chunkSize, retention, resumableChunkRoot(settings))
|
||||
if err != nil {
|
||||
a.logger.Warn("resumable session create failed", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4002, "user_id", user.ID, "error", err.Error())...)
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
a.logger.Info("resumable upload session created", withRequestLogAttrs(r, "source", "user-upload", "severity", "user_activity", "code", 2002, "user_id", user.ID, "session_id", session.ID, "files", len(session.Files), "bytes", totalBytes, "anonymous", !loggedIn)...)
|
||||
helpers.WriteJSON(w, http.StatusCreated, resumableResponse(session))
|
||||
}
|
||||
|
||||
func (a *App) ResumableUploadStatus(w http.ResponseWriter, r *http.Request) {
|
||||
session, ok := a.authorizedResumableSession(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
helpers.WriteJSON(w, http.StatusOK, resumableResponse(session))
|
||||
}
|
||||
|
||||
func (a *App) AddResumableFiles(w http.ResponseWriter, r *http.Request) {
|
||||
session, ok := a.authorizedResumableSession(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
user, loggedIn, _ := a.currentUserWithAuthError(r)
|
||||
isAdminUpload := loggedIn && user.Role == services.UserRoleAdmin
|
||||
settings, policy, ok := a.loadUploadPolicyForAPI(w, r, user, loggedIn)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var payload struct {
|
||||
Files []services.ResumableFileInput `json:"files"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, "upload files request could not be read")
|
||||
return
|
||||
}
|
||||
fileSizes := make([]int64, 0, len(session.Files)+len(payload.Files))
|
||||
var totalBytes int64
|
||||
for _, file := range session.Files {
|
||||
fileSizes = append(fileSizes, file.Size)
|
||||
totalBytes += file.Size
|
||||
}
|
||||
for _, file := range payload.Files {
|
||||
fileSizes = append(fileSizes, file.Size)
|
||||
totalBytes += file.Size
|
||||
}
|
||||
if !isAdminUpload {
|
||||
if status, message := a.checkUploadPolicyForSizes(r, user, loggedIn, settings, policy, fileSizes, totalBytes); message != "" {
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
}
|
||||
updated, err := a.uploadService.AddResumableFiles(session.ID, payload.Files)
|
||||
if err != nil {
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
a.logger.Info("resumable upload files added", withRequestLogAttrs(r, "source", "user-upload", "severity", "user_activity", "code", 2006, "session_id", session.ID, "added", len(updated.Files)-len(session.Files), "files", len(updated.Files))...)
|
||||
helpers.WriteJSON(w, http.StatusOK, resumableResponse(updated))
|
||||
}
|
||||
|
||||
func (a *App) PutResumableChunk(w http.ResponseWriter, r *http.Request) {
|
||||
session, ok := a.authorizedResumableSession(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
fileID := r.PathValue("fileID")
|
||||
index, err := strconv.Atoi(r.PathValue("index"))
|
||||
if err != nil {
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, "chunk index is invalid")
|
||||
return
|
||||
}
|
||||
updated, err := a.uploadService.PutResumableChunk(r.Context(), session.ID, fileID, index, r.Body)
|
||||
if err != nil {
|
||||
a.logger.Warn("resumable chunk failed", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4003, "session_id", session.ID, "file_id", fileID, "chunk", index, "error", err.Error())...)
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
a.logger.Info("resumable chunk uploaded", withRequestLogAttrs(r, "source", "user-upload", "severity", "user_activity", "code", 2003, "session_id", session.ID, "file_id", fileID, "chunk", index)...)
|
||||
helpers.WriteJSON(w, http.StatusOK, resumableResponse(updated))
|
||||
}
|
||||
|
||||
func (a *App) CompleteResumableUpload(w http.ResponseWriter, r *http.Request) {
|
||||
session, ok := a.authorizedResumableSession(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if session.Status == services.ResumableStatusCompleted || session.Status == services.ResumableStatusProcessing {
|
||||
result, completed, err := a.uploadService.CompleteResumableSession(r.Context(), session.ID)
|
||||
if err != nil {
|
||||
a.logger.Warn("resumable upload completion replay failed", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4004, "session_id", session.ID, "error", err.Error())...)
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
a.logger.Info("resumable upload completion replayed", withRequestLogAttrs(r, "source", "user-upload", "severity", "user_activity", "code", 2004, "session_id", completed.ID, "box_id", result.BoxID, "files", len(result.Files))...)
|
||||
helpers.WriteJSON(w, http.StatusOK, result)
|
||||
return
|
||||
}
|
||||
user, loggedIn, _ := a.currentUserWithAuthError(r)
|
||||
isAdminUpload := loggedIn && user.Role == services.UserRoleAdmin
|
||||
settings, policy, ok := a.loadUploadPolicyForAPI(w, r, user, loggedIn)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
fileSizes := make([]int64, 0, len(session.Files))
|
||||
var totalBytes int64
|
||||
for _, file := range session.Files {
|
||||
fileSizes = append(fileSizes, file.Size)
|
||||
totalBytes += file.Size
|
||||
}
|
||||
if !isAdminUpload {
|
||||
if status, message := a.checkUploadPolicyForSizes(r, user, loggedIn, settings, policy, fileSizes, totalBytes); message != "" {
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
if status, message := a.checkBoxCreationPolicy(r, user, loggedIn, policy); message != "" {
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
if status, message := a.checkStorageBackendCapacity(session.Options.StorageBackendID, settings, totalBytes); message != "" {
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
}
|
||||
result, completed, err := a.uploadService.CreateProcessingBoxFromResumable(session.ID)
|
||||
if err != nil {
|
||||
a.logger.Warn("resumable upload complete failed", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4004, "session_id", session.ID, "error", err.Error())...)
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if !isAdminUpload {
|
||||
if err := a.recordUploadUsage(r, user, loggedIn, totalBytes, 1); err != nil {
|
||||
a.logger.Warn("failed to record resumable upload usage", "source", "quota", "severity", "warn", "code", 4404, "error", err.Error())
|
||||
}
|
||||
if err := a.settingsService.CleanupUsage(time.Now().UTC(), settings.UsageRetentionDays); err != nil {
|
||||
a.logger.Warn("failed to cleanup upload usage", "source", "quota", "severity", "warn", "code", 4405, "error", err.Error())
|
||||
}
|
||||
}
|
||||
a.finalizeResumableUploadAsync(completed.ID, result.BoxID)
|
||||
a.logger.Info("resumable upload queued for processing", withRequestLogAttrs(r, "source", "user-upload", "severity", "user_activity", "code", 2004, "user_id", user.ID, "session_id", completed.ID, "box_id", result.BoxID, "files", len(result.Files), "bytes", totalBytes, "admin", isAdminUpload, "anonymous", !loggedIn)...)
|
||||
helpers.WriteJSON(w, http.StatusCreated, result)
|
||||
}
|
||||
|
||||
func (a *App) CompleteUploadedResumableUpload(w http.ResponseWriter, r *http.Request) {
|
||||
session, ok := a.authorizedResumableSession(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
user, loggedIn, _ := a.currentUserWithAuthError(r)
|
||||
isAdminUpload := loggedIn && user.Role == services.UserRoleAdmin
|
||||
settings, policy, ok := a.loadUploadPolicyForAPI(w, r, user, loggedIn)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
fileSizes := make([]int64, 0, len(session.Files))
|
||||
var totalBytes int64
|
||||
var completeCount int
|
||||
for _, file := range session.Files {
|
||||
if len(file.UploadedChunks) != file.ChunkCount {
|
||||
continue
|
||||
}
|
||||
fileSizes = append(fileSizes, file.Size)
|
||||
totalBytes += file.Size
|
||||
completeCount++
|
||||
}
|
||||
if completeCount == 0 {
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, "no fully uploaded files to finish")
|
||||
return
|
||||
}
|
||||
if !isAdminUpload {
|
||||
if status, message := a.checkUploadPolicyForSizes(r, user, loggedIn, settings, policy, fileSizes, totalBytes); message != "" {
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
if status, message := a.checkBoxCreationPolicy(r, user, loggedIn, policy); message != "" {
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
if status, message := a.checkStorageBackendCapacity(session.Options.StorageBackendID, settings, totalBytes); message != "" {
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
}
|
||||
result, completed, err := a.uploadService.CompleteUploadedResumableSession(r.Context(), session.ID)
|
||||
if err != nil {
|
||||
a.logger.Warn("resumable partial complete failed", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4005, "session_id", session.ID, "error", err.Error())...)
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if !isAdminUpload {
|
||||
if err := a.recordUploadUsage(r, user, loggedIn, totalBytes, 1); err != nil {
|
||||
a.logger.Warn("failed to record partial resumable upload usage", "source", "quota", "severity", "warn", "code", 4406, "error", err.Error())
|
||||
}
|
||||
if err := a.settingsService.CleanupUsage(time.Now().UTC(), settings.UsageRetentionDays); err != nil {
|
||||
a.logger.Warn("failed to cleanup upload usage", "source", "quota", "severity", "warn", "code", 4405, "error", err.Error())
|
||||
}
|
||||
}
|
||||
jobs.GenerateThumbnailsForBoxAsync(a.uploadService, a.logger, result.BoxID)
|
||||
a.logger.Info("resumable uploaded files completed", withRequestLogAttrs(r, "source", "user-upload", "severity", "user_activity", "code", 2007, "user_id", user.ID, "session_id", completed.ID, "box_id", result.BoxID, "files", len(result.Files), "bytes", totalBytes, "admin", isAdminUpload, "anonymous", !loggedIn)...)
|
||||
helpers.WriteJSON(w, http.StatusCreated, result)
|
||||
}
|
||||
|
||||
func (a *App) finalizeResumableUploadAsync(sessionID, boxID string) {
|
||||
go func() {
|
||||
a.logger.Info("resumable upload processing started", "source", "user-upload", "severity", "user_activity", "code", 2009, "session_id", sessionID, "box_id", boxID)
|
||||
result, err := a.uploadService.FinalizeProcessingResumableSession(context.Background(), sessionID)
|
||||
if err != nil {
|
||||
a.logger.Warn("resumable upload processing failed", "source", "user-upload", "severity", "warn", "code", 4010, "session_id", sessionID, "box_id", boxID, "error", err.Error())
|
||||
return
|
||||
}
|
||||
jobs.GenerateThumbnailsForBoxAsync(a.uploadService, a.logger, result.BoxID)
|
||||
a.logger.Info("resumable upload processing completed", "source", "user-upload", "severity", "user_activity", "code", 2010, "session_id", sessionID, "box_id", result.BoxID, "files", len(result.Files))
|
||||
}()
|
||||
}
|
||||
|
||||
func resumableChunkRoot(settings services.UploadPolicySettings) string {
|
||||
if settings.ResumableChunkMode != "custom" {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(settings.ResumableChunkPath)
|
||||
}
|
||||
|
||||
func (a *App) CancelResumableUpload(w http.ResponseWriter, r *http.Request) {
|
||||
session, ok := a.authorizedResumableSession(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := a.uploadService.CancelResumableSession(session.ID); err != nil {
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
a.logger.Info("resumable upload cancelled", withRequestLogAttrs(r, "source", "user-upload", "severity", "user_activity", "code", 2005, "session_id", session.ID)...)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (a *App) authorizedResumableSession(w http.ResponseWriter, r *http.Request) (services.ResumableSession, bool) {
|
||||
user, loggedIn, authErr := a.currentUserWithAuthError(r)
|
||||
if authErr != nil {
|
||||
helpers.WriteJSONError(w, http.StatusUnauthorized, "invalid bearer token")
|
||||
return services.ResumableSession{}, false
|
||||
}
|
||||
session, err := a.uploadService.GetResumableSession(r.PathValue("sessionID"))
|
||||
if err != nil {
|
||||
helpers.WriteJSONError(w, http.StatusNotFound, "upload session not found")
|
||||
return services.ResumableSession{}, false
|
||||
}
|
||||
if !a.uploadService.VerifyResumableToken(session, r.Header.Get("X-Warpbox-Resume-Token")) {
|
||||
helpers.WriteJSONError(w, http.StatusUnauthorized, "upload session not found")
|
||||
return services.ResumableSession{}, false
|
||||
}
|
||||
if loggedIn {
|
||||
if session.Options.OwnerID != user.ID {
|
||||
helpers.WriteJSONError(w, http.StatusForbidden, "upload session not found")
|
||||
return services.ResumableSession{}, false
|
||||
}
|
||||
return session, true
|
||||
}
|
||||
if session.Options.OwnerID != "" || session.Options.CreatorIP != uploadClientIP(r) {
|
||||
helpers.WriteJSONError(w, http.StatusForbidden, "upload session not found")
|
||||
return services.ResumableSession{}, false
|
||||
}
|
||||
return session, true
|
||||
}
|
||||
|
||||
func (a *App) loadUploadPolicyForAPI(w http.ResponseWriter, r *http.Request, user services.User, loggedIn bool) (services.UploadPolicySettings, services.EffectiveUploadPolicy, bool) {
|
||||
settings, err := a.settingsService.UploadPolicy()
|
||||
if err != nil {
|
||||
a.logger.Error("failed to load upload policy", "source", "settings", "severity", "error", "code", 5006, "error", err.Error())
|
||||
helpers.WriteJSONError(w, http.StatusInternalServerError, "upload policy could not be loaded")
|
||||
return services.UploadPolicySettings{}, services.EffectiveUploadPolicy{}, false
|
||||
}
|
||||
return settings, a.effectiveUploadPolicy(settings, user, loggedIn), true
|
||||
}
|
||||
|
||||
func (a *App) resumableUploadOptions(r *http.Request, payload resumableCreateRequest, user services.User, loggedIn, isAdminUpload bool, policy services.EffectiveUploadPolicy) (services.UploadOptions, error) {
|
||||
var ownerID string
|
||||
var collectionID string
|
||||
if loggedIn {
|
||||
ownerID = user.ID
|
||||
collectionID = strings.TrimSpace(payload.CollectionID)
|
||||
if !a.authService.CollectionOwnedBy(collectionID, user.ID) {
|
||||
return services.UploadOptions{}, fmt.Errorf("collection not found")
|
||||
}
|
||||
}
|
||||
unlimitedExpiry := isAdminUpload || policy.MaxDays < 0
|
||||
rawMaxDays := payload.MaxDays
|
||||
maxDays := rawMaxDays
|
||||
if maxDays <= 0 {
|
||||
maxDays = 7
|
||||
if policy.MaxDays > 0 && policy.MaxDays < maxDays {
|
||||
maxDays = policy.MaxDays
|
||||
}
|
||||
}
|
||||
expiresMinutes := payload.ExpiresMinutes
|
||||
if expiresMinutes < 0 || rawMaxDays < 0 {
|
||||
if !unlimitedExpiry {
|
||||
return services.UploadOptions{}, fmt.Errorf("expiration cannot exceed %d days", policy.MaxDays)
|
||||
}
|
||||
expiresMinutes = -1
|
||||
} else if !unlimitedExpiry {
|
||||
if maxDays > policy.MaxDays {
|
||||
return services.UploadOptions{}, fmt.Errorf("expiration cannot exceed %d days", policy.MaxDays)
|
||||
}
|
||||
if expiresMinutes > 0 && expiresMinutes > policy.MaxDays*24*60 {
|
||||
return services.UploadOptions{}, fmt.Errorf("expiration cannot exceed %d days", policy.MaxDays)
|
||||
}
|
||||
}
|
||||
return services.UploadOptions{
|
||||
MaxDays: maxDays,
|
||||
ExpiresInMinutes: expiresMinutes,
|
||||
MaxDownloads: payload.MaxDownloads,
|
||||
Password: payload.Password,
|
||||
ObfuscateMetadata: payload.ObfuscateMetadata,
|
||||
OwnerID: ownerID,
|
||||
CollectionID: collectionID,
|
||||
SkipSizeLimit: isAdminUpload || policy.MaxUploadMB < 0,
|
||||
CreatorIP: uploadClientIP(r),
|
||||
StorageBackendID: policy.StorageBackendID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func resumableResponse(session services.ResumableSession) resumableSessionResponse {
|
||||
return resumableSessionResponse{
|
||||
SessionID: session.ID,
|
||||
ResumeToken: session.ResumeToken,
|
||||
ChunkSize: session.ChunkSize,
|
||||
Status: session.Status,
|
||||
BoxID: session.BoxID,
|
||||
ExpiresAt: session.ExpiresAt.Format(time.RFC3339),
|
||||
Files: session.Files,
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
@@ -15,6 +16,24 @@ func (a *App) Static() http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) EmojiAsset(w http.ResponseWriter, r *http.Request) {
|
||||
pack := strings.TrimSpace(r.PathValue("pack"))
|
||||
file := strings.TrimSpace(r.PathValue("file"))
|
||||
if pack == "" || file == "" || strings.Contains(pack, "/") || strings.Contains(pack, "\\") || strings.Contains(pack, "..") || strings.Contains(file, "/") || strings.Contains(file, "\\") || strings.Contains(file, "..") || !isEmojiFile(file) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
path := filepath.Join(a.emojiRoot(), pack, file)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.IsDir() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
setStaticCacheHeaders(w, r.URL.Path)
|
||||
http.ServeFile(w, r, path)
|
||||
}
|
||||
|
||||
func setStaticCacheHeaders(w http.ResponseWriter, path string) {
|
||||
ext := strings.ToLower(filepath.Ext(path))
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
func (a *App) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
user, loggedIn, authErr := a.currentUserWithAuthError(r)
|
||||
if authErr != nil {
|
||||
a.logger.Warn("upload rejected invalid bearer token", "source", "user-upload", "severity", "warn", "code", 4010, "ip", uploadClientIP(r), "user_agent", r.UserAgent())
|
||||
a.logger.Warn("upload rejected invalid bearer token", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4010)...)
|
||||
helpers.WriteJSONError(w, http.StatusUnauthorized, "invalid bearer token")
|
||||
return
|
||||
}
|
||||
@@ -30,14 +30,14 @@ func (a *App) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if !loggedIn && !settings.AnonymousUploadsEnabled {
|
||||
a.logger.Warn("anonymous upload rejected disabled", "source", "user-upload", "severity", "warn", "code", 4012, "ip", uploadClientIP(r))
|
||||
a.logger.Warn("anonymous upload rejected disabled", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4012)...)
|
||||
helpers.WriteJSONError(w, http.StatusForbidden, "anonymous uploads are disabled")
|
||||
return
|
||||
}
|
||||
effectivePolicy := a.effectiveUploadPolicy(settings, user, loggedIn)
|
||||
rateKey := uploadRateKey(r, user, loggedIn)
|
||||
if !isAdminUpload && !a.rateLimiter.Allow("upload:"+rateKey, effectivePolicy.ShortRequests, effectivePolicy.ShortWindow, time.Now().UTC()) {
|
||||
a.logger.Warn("upload rate limited", "source", "user-upload", "severity", "warn", "code", 4290, "ip", uploadClientIP(r), "user_id", user.ID)
|
||||
if !isAdminUpload && effectivePolicy.ShortRequests > 0 && !a.rateLimiter.Allow("upload:"+rateKey, effectivePolicy.ShortRequests, effectivePolicy.ShortWindow, time.Now().UTC()) {
|
||||
a.logger.Warn("upload rate limited", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4290, "user_id", user.ID)...)
|
||||
helpers.WriteJSONError(w, http.StatusTooManyRequests, "too many upload requests, please slow down")
|
||||
return
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func (a *App) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
parseLimit = 32 << 20
|
||||
}
|
||||
if err := r.ParseMultipartForm(parseLimit); err != nil {
|
||||
a.logger.Warn("upload form parse failed", "source", "user-upload", "severity", "warn", "code", 4000, "ip", uploadClientIP(r), "user_id", user.ID, "error", err.Error())
|
||||
a.logger.Warn("upload form parse failed", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4000, "user_id", user.ID, "error", err.Error())...)
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, "upload form could not be read")
|
||||
return
|
||||
}
|
||||
@@ -65,34 +65,51 @@ func (a *App) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
ownerID = user.ID
|
||||
collectionID = r.FormValue("collection_id")
|
||||
if !a.authService.CollectionOwnedBy(collectionID, user.ID) {
|
||||
a.logger.Warn("upload rejected invalid collection", "source", "user-upload", "severity", "warn", "code", 4030, "user_id", user.ID, "collection_id", collectionID)
|
||||
a.logger.Warn("upload rejected invalid collection", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4030, "user_id", user.ID, "collection_id", collectionID)...)
|
||||
helpers.WriteJSONError(w, http.StatusForbidden, "collection not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
if !isAdminUpload {
|
||||
if status, message := a.checkUploadPolicy(r, user, loggedIn, settings, effectivePolicy, files, totalBytes); message != "" {
|
||||
a.logger.Warn("upload rejected by policy", "source", "quota", "severity", "warn", "code", status, "ip", uploadClientIP(r), "user_id", user.ID, "message", message, "bytes", totalBytes, "files", len(files))
|
||||
a.logger.Warn("upload rejected by policy", withRequestLogAttrs(r, "source", "quota", "severity", "warn", "code", status, "user_id", user.ID, "message", message, "bytes", totalBytes, "files", len(files))...)
|
||||
helpers.WriteJSONError(w, status, message)
|
||||
return
|
||||
}
|
||||
}
|
||||
maxDays := parseInt(r.FormValue("max_days"))
|
||||
// Unlimited expiry: admins, or users whose effective MaxDays is negative.
|
||||
unlimitedExpiry := isAdminUpload || effectivePolicy.MaxDays < 0
|
||||
|
||||
rawMaxDays := parseInt(r.FormValue("max_days"))
|
||||
maxDays := rawMaxDays
|
||||
if maxDays <= 0 {
|
||||
maxDays = min(7, effectivePolicy.MaxDays)
|
||||
maxDays = 7
|
||||
if effectivePolicy.MaxDays > 0 && effectivePolicy.MaxDays < maxDays {
|
||||
maxDays = effectivePolicy.MaxDays
|
||||
}
|
||||
}
|
||||
if !isAdminUpload && maxDays > effectivePolicy.MaxDays {
|
||||
a.logger.Warn("upload rejected expiration days", "source", "user-upload", "severity", "warn", "code", 4131, "ip", uploadClientIP(r), "user_id", user.ID, "requested_days", maxDays, "max_days", effectivePolicy.MaxDays)
|
||||
if !unlimitedExpiry && maxDays > effectivePolicy.MaxDays {
|
||||
a.logger.Warn("upload rejected expiration days", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4131, "user_id", user.ID, "requested_days", maxDays, "max_days", effectivePolicy.MaxDays)...)
|
||||
helpers.WriteJSONError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("expiration cannot exceed %d days", effectivePolicy.MaxDays))
|
||||
return
|
||||
}
|
||||
|
||||
expiresMinutes := parseInt(r.FormValue("expires_minutes"))
|
||||
if expiresMinutes > 0 && !isAdminUpload && expiresMinutes > effectivePolicy.MaxDays*24*60 {
|
||||
a.logger.Warn("upload rejected expiration minutes", "source", "user-upload", "severity", "warn", "code", 4132, "ip", uploadClientIP(r), "user_id", user.ID, "requested_minutes", expiresMinutes, "max_days", effectivePolicy.MaxDays)
|
||||
// A negative expires_minutes (or max_days) is the "never expires" request.
|
||||
// Only honour it for unlimited uploaders; otherwise it's an invalid value.
|
||||
if expiresMinutes < 0 || rawMaxDays < 0 {
|
||||
if !unlimitedExpiry {
|
||||
a.logger.Warn("upload rejected unlimited expiration", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4133, "user_id", user.ID)...)
|
||||
helpers.WriteJSONError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("expiration cannot exceed %d days", effectivePolicy.MaxDays))
|
||||
return
|
||||
}
|
||||
expiresMinutes = -1
|
||||
} else if expiresMinutes > 0 && !unlimitedExpiry && expiresMinutes > effectivePolicy.MaxDays*24*60 {
|
||||
a.logger.Warn("upload rejected expiration minutes", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4132, "user_id", user.ID, "requested_minutes", expiresMinutes, "max_days", effectivePolicy.MaxDays)...)
|
||||
helpers.WriteJSONError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("expiration cannot exceed %d days", effectivePolicy.MaxDays))
|
||||
return
|
||||
}
|
||||
result, err := a.uploadService.CreateBox(files, services.UploadOptions{
|
||||
opts := services.UploadOptions{
|
||||
MaxDays: maxDays,
|
||||
ExpiresInMinutes: expiresMinutes,
|
||||
MaxDownloads: parseInt(r.FormValue("max_downloads")),
|
||||
@@ -103,14 +120,20 @@ func (a *App) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
SkipSizeLimit: isAdminUpload || effectivePolicy.MaxUploadMB < 0,
|
||||
CreatorIP: uploadClientIP(r),
|
||||
StorageBackendID: effectivePolicy.StorageBackendID,
|
||||
})
|
||||
}
|
||||
result, boxesAdded, status, policyMessage, err := a.createOrAppendBox(r, user, loggedIn, effectivePolicy, files, opts, !isAdminUpload)
|
||||
if policyMessage != "" {
|
||||
a.logger.Warn("upload rejected by policy", withRequestLogAttrs(r, "source", "quota", "severity", "warn", "code", status, "user_id", user.ID, "message", policyMessage, "bytes", totalBytes, "files", len(files))...)
|
||||
helpers.WriteJSONError(w, status, policyMessage)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Warn("upload failed", "source", "user-upload", "severity", "warn", "code", 4001, "ip", uploadClientIP(r), "user_id", user.ID, "error", err.Error())
|
||||
a.logger.Warn("upload failed", withRequestLogAttrs(r, "source", "user-upload", "severity", "warn", "code", 4001, "user_id", user.ID, "error", err.Error())...)
|
||||
helpers.WriteJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if !isAdminUpload {
|
||||
if err := a.recordUploadUsage(r, user, loggedIn, totalBytes, 1); err != nil {
|
||||
if err := a.recordUploadUsage(r, user, loggedIn, totalBytes, boxesAdded); err != nil {
|
||||
a.logger.Warn("failed to record upload usage", "source", "quota", "severity", "warn", "code", 4402, "error", err.Error())
|
||||
}
|
||||
if err := a.settingsService.CleanupUsage(time.Now().UTC(), settings.UsageRetentionDays); err != nil {
|
||||
@@ -118,7 +141,7 @@ func (a *App) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
jobs.GenerateThumbnailsForBoxAsync(a.uploadService, a.logger, result.BoxID)
|
||||
a.logger.Info("upload response sent", "source", "user-upload", "severity", "user_activity", "code", 2001, "ip", uploadClientIP(r), "user_id", user.ID, "box_id", result.BoxID, "files", len(files), "bytes", totalBytes, "admin", isAdminUpload)
|
||||
a.logger.Info("box uploaded", withRequestLogAttrs(r, "source", "user-upload", "severity", "user_activity", "code", 2001, "user_id", user.ID, "box_id", result.BoxID, "files", len(files), "bytes", totalBytes, "admin", isAdminUpload, "anonymous", !loggedIn)...)
|
||||
|
||||
if wantsJSON(r) {
|
||||
helpers.WriteJSON(w, http.StatusCreated, result)
|
||||
@@ -130,15 +153,97 @@ func (a *App) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = fmt.Fprintln(w, result.BoxURL)
|
||||
}
|
||||
|
||||
// createOrAppendBox creates a new box. It only ever appends to an existing box
|
||||
// when the request opts in via the X-Warpbox-Batch header: requests sharing the
|
||||
// same batch value (per account, or per IP for anonymous) within
|
||||
// uploadGroupWindow are folded into one box. Without the header the behaviour is
|
||||
// identical to creating a fresh box every time. Returns the result and how many
|
||||
// boxes were created (1 for a new box, 0 for an append) for usage accounting.
|
||||
func (a *App) createOrAppendBox(r *http.Request, user services.User, loggedIn bool, policy services.EffectiveUploadPolicy, files []*multipart.FileHeader, opts services.UploadOptions, enforceBoxLimits bool) (services.UploadResult, int, int, string, error) {
|
||||
batch := strings.TrimSpace(r.Header.Get(uploadBatchHeader))
|
||||
if batch == "" {
|
||||
if enforceBoxLimits {
|
||||
if status, message := a.checkBoxCreationPolicy(r, user, loggedIn, policy); message != "" {
|
||||
return services.UploadResult{}, 0, status, message, nil
|
||||
}
|
||||
}
|
||||
result, err := a.uploadService.CreateBox(files, opts)
|
||||
if err != nil {
|
||||
return services.UploadResult{}, 0, 0, "", err
|
||||
}
|
||||
return result, 1, 0, "", nil
|
||||
}
|
||||
|
||||
// Group key is scoped to the uploader so batches never cross accounts/IPs.
|
||||
identity := "ip:" + uploadClientIP(r)
|
||||
if loggedIn {
|
||||
identity = "user:" + user.ID
|
||||
}
|
||||
entry := a.uploadGroups.entryFor(identity + "|" + batch)
|
||||
|
||||
// Hold the per-key lock across the whole create/append so concurrent batched
|
||||
// uploads serialise into the same box instead of racing.
|
||||
entry.mu.Lock()
|
||||
defer entry.mu.Unlock()
|
||||
|
||||
if entry.boxID != "" && time.Since(entry.at) < uploadGroupWindow {
|
||||
if box, err := a.uploadService.GetBox(entry.boxID); err == nil && a.batchBoxMatches(box, user, loggedIn, r) && a.uploadService.CanDownload(box) == nil {
|
||||
if result, err := a.uploadService.AppendFiles(entry.boxID, files, opts); err == nil {
|
||||
// Re-attach the manage/delete URLs from the box's creation so every
|
||||
// upload in the batch returns a working deletion URL.
|
||||
result.ManageURL = entry.manageURL
|
||||
result.DeleteURL = entry.deleteURL
|
||||
entry.at = time.Now()
|
||||
return result, 0, 0, "", nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if enforceBoxLimits {
|
||||
if status, message := a.checkBoxCreationPolicy(r, user, loggedIn, policy); message != "" {
|
||||
return services.UploadResult{}, 0, status, message, nil
|
||||
}
|
||||
}
|
||||
result, err := a.uploadService.CreateBox(files, opts)
|
||||
if err != nil {
|
||||
return services.UploadResult{}, 0, 0, "", err
|
||||
}
|
||||
entry.boxID = result.BoxID
|
||||
entry.manageURL = result.ManageURL
|
||||
entry.deleteURL = result.DeleteURL
|
||||
entry.at = time.Now()
|
||||
return result, 1, 0, "", nil
|
||||
}
|
||||
|
||||
// batchBoxMatches guards that a batched append only ever touches a box owned by
|
||||
// the same uploader (account for logged-in users, creator IP for anonymous).
|
||||
func (a *App) batchBoxMatches(box services.Box, user services.User, loggedIn bool, r *http.Request) bool {
|
||||
if loggedIn {
|
||||
return box.OwnerID == user.ID
|
||||
}
|
||||
return box.OwnerID == "" && box.CreatorIP == uploadClientIP(r)
|
||||
}
|
||||
|
||||
func (a *App) checkUploadPolicy(r *http.Request, user services.User, loggedIn bool, settings services.UploadPolicySettings, policy services.EffectiveUploadPolicy, files []*multipart.FileHeader, totalBytes int64) (int, string) {
|
||||
if len(files) == 0 {
|
||||
return 0, ""
|
||||
}
|
||||
sizes := make([]int64, 0, len(files))
|
||||
for _, file := range files {
|
||||
sizes = append(sizes, file.Size)
|
||||
}
|
||||
return a.checkUploadPolicyForSizes(r, user, loggedIn, settings, policy, sizes, totalBytes)
|
||||
}
|
||||
|
||||
func (a *App) checkUploadPolicyForSizes(r *http.Request, user services.User, loggedIn bool, settings services.UploadPolicySettings, policy services.EffectiveUploadPolicy, fileSizes []int64, totalBytes int64) (int, string) {
|
||||
if len(fileSizes) == 0 {
|
||||
return 0, ""
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if policy.MaxUploadMB > 0 {
|
||||
maxBytes := services.MegabytesToBytes(policy.MaxUploadMB)
|
||||
for _, file := range files {
|
||||
if file.Size > maxBytes {
|
||||
for _, fileSize := range fileSizes {
|
||||
if fileSize > maxBytes {
|
||||
return http.StatusRequestEntityTooLarge, "file exceeds upload size limit"
|
||||
}
|
||||
}
|
||||
@@ -151,16 +256,6 @@ func (a *App) checkUploadPolicy(r *http.Request, user services.User, loggedIn bo
|
||||
if policy.DailyUploadMB > 0 && usage.UploadedBytes+totalBytes > services.MegabytesToBytes(policy.DailyUploadMB) {
|
||||
return http.StatusTooManyRequests, "anonymous daily upload limit reached"
|
||||
}
|
||||
if usage.UploadedBoxes+1 > policy.DailyBoxes {
|
||||
return http.StatusTooManyRequests, "anonymous daily box limit reached"
|
||||
}
|
||||
activeBoxes, err := a.uploadService.ActiveBoxCountForIP(uploadClientIP(r))
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, "active box limit could not be checked"
|
||||
}
|
||||
if activeBoxes+1 > policy.ActiveBoxes {
|
||||
return http.StatusTooManyRequests, "anonymous active box limit reached"
|
||||
}
|
||||
if status, message := a.checkStorageBackendCapacity(policy.StorageBackendID, settings, totalBytes); message != "" {
|
||||
return status, message
|
||||
}
|
||||
@@ -174,16 +269,6 @@ func (a *App) checkUploadPolicy(r *http.Request, user services.User, loggedIn bo
|
||||
if policy.DailyUploadMB > 0 && usage.UploadedBytes+totalBytes > services.MegabytesToBytes(policy.DailyUploadMB) {
|
||||
return http.StatusTooManyRequests, "daily upload limit reached"
|
||||
}
|
||||
if usage.UploadedBoxes+1 > policy.DailyBoxes {
|
||||
return http.StatusTooManyRequests, "daily box limit reached"
|
||||
}
|
||||
activeBoxes, err := a.uploadService.ActiveBoxCountForUser(user.ID)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, "active box limit could not be checked"
|
||||
}
|
||||
if activeBoxes+1 > policy.ActiveBoxes {
|
||||
return http.StatusTooManyRequests, "active box limit reached"
|
||||
}
|
||||
activeStorage, err := a.uploadService.UserActiveStorageUsed(user.ID)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, "storage quota could not be checked"
|
||||
@@ -197,6 +282,42 @@ func (a *App) checkUploadPolicy(r *http.Request, user services.User, loggedIn bo
|
||||
return 0, ""
|
||||
}
|
||||
|
||||
func (a *App) checkBoxCreationPolicy(r *http.Request, user services.User, loggedIn bool, policy services.EffectiveUploadPolicy) (int, string) {
|
||||
now := time.Now().UTC()
|
||||
if !loggedIn {
|
||||
usage, err := a.settingsService.UsageForIP(uploadClientIP(r), now)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, "upload usage could not be checked"
|
||||
}
|
||||
if policy.DailyBoxes > 0 && usage.UploadedBoxes+1 > policy.DailyBoxes {
|
||||
return http.StatusTooManyRequests, "anonymous daily box limit reached"
|
||||
}
|
||||
activeBoxes, err := a.uploadService.ActiveBoxCountForIP(uploadClientIP(r))
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, "active box limit could not be checked"
|
||||
}
|
||||
if policy.ActiveBoxes > 0 && activeBoxes+1 > policy.ActiveBoxes {
|
||||
return http.StatusTooManyRequests, "anonymous active box limit reached"
|
||||
}
|
||||
return 0, ""
|
||||
}
|
||||
usage, err := a.settingsService.UsageForUser(user.ID, now)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, "upload usage could not be checked"
|
||||
}
|
||||
if policy.DailyBoxes > 0 && usage.UploadedBoxes+1 > policy.DailyBoxes {
|
||||
return http.StatusTooManyRequests, "daily box limit reached"
|
||||
}
|
||||
activeBoxes, err := a.uploadService.ActiveBoxCountForUser(user.ID)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, "active box limit could not be checked"
|
||||
}
|
||||
if policy.ActiveBoxes > 0 && activeBoxes+1 > policy.ActiveBoxes {
|
||||
return http.StatusTooManyRequests, "active box limit reached"
|
||||
}
|
||||
return 0, ""
|
||||
}
|
||||
|
||||
func (a *App) recordUploadUsage(r *http.Request, user services.User, loggedIn bool, totalBytes int64, boxes int) error {
|
||||
now := time.Now().UTC()
|
||||
if loggedIn {
|
||||
|
||||
76
backend/libs/handlers/upload_group.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// uploadGroupWindow is how long after a batched upload a follow-up upload with
|
||||
// the same X-Warpbox-Batch value (and same account/IP) is folded into the same
|
||||
// box. ShareX sends a multi-file selection as separate back-to-back requests;
|
||||
// the batch header lets it land them in one box.
|
||||
const uploadGroupWindow = 20 * time.Second
|
||||
|
||||
// uploadBatchHeader is the opt-in request header. Without it, uploads behave
|
||||
// exactly as before (one box per request). With it, requests sharing the same
|
||||
// value (per account/IP) within uploadGroupWindow are grouped into one box.
|
||||
const uploadBatchHeader = "X-Warpbox-Batch"
|
||||
|
||||
// uploadGroupPruneInterval is how often entryFor drops stale entries so the map
|
||||
// can't grow without bound (one key per account/IP + batch value otherwise).
|
||||
const uploadGroupPruneInterval = 5 * time.Minute
|
||||
|
||||
// uploadGrouper tracks the most recent box per batch key so opt-in batched
|
||||
// uploads land in a single box. Each key has its own lock, which also serialises
|
||||
// that key's concurrent uploads so they append to the same box instead of racing
|
||||
// to create several.
|
||||
type uploadGrouper struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]*uploadGroupEntry
|
||||
lastPrune time.Time
|
||||
}
|
||||
|
||||
type uploadGroupEntry struct {
|
||||
mu sync.Mutex
|
||||
boxID string
|
||||
manageURL string
|
||||
deleteURL string
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func newUploadGrouper() *uploadGrouper {
|
||||
return &uploadGrouper{entries: make(map[string]*uploadGroupEntry)}
|
||||
}
|
||||
|
||||
func (g *uploadGrouper) entryFor(key string) *uploadGroupEntry {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
g.pruneLocked(time.Now())
|
||||
entry, ok := g.entries[key]
|
||||
if !ok {
|
||||
entry = &uploadGroupEntry{at: time.Now()}
|
||||
g.entries[key] = entry
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
// pruneLocked drops entries whose last use is well past the grouping window so
|
||||
// the map stays bounded to recently-active keys. Callers must hold g.mu. Entries
|
||||
// currently in use are kept to avoid removing one a request is about to
|
||||
// populate.
|
||||
func (g *uploadGrouper) pruneLocked(now time.Time) {
|
||||
if now.Sub(g.lastPrune) < uploadGroupPruneInterval {
|
||||
return
|
||||
}
|
||||
g.lastPrune = now
|
||||
for key, entry := range g.entries {
|
||||
if !entry.mu.TryLock() {
|
||||
continue
|
||||
}
|
||||
stale := now.Sub(entry.at) > 2*uploadGroupWindow
|
||||
entry.mu.Unlock()
|
||||
if stale {
|
||||
delete(g.entries, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
24
backend/libs/handlers/upload_group_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestUploadGroupPrunesFailedEntries(t *testing.T) {
|
||||
g := newUploadGrouper()
|
||||
entry := g.entryFor("ip:203.0.113.1|failed")
|
||||
entry.mu.Lock()
|
||||
entry.at = time.Now().Add(-3 * uploadGroupWindow)
|
||||
entry.mu.Unlock()
|
||||
g.lastPrune = time.Now().Add(-uploadGroupPruneInterval)
|
||||
|
||||
_ = g.entryFor("ip:203.0.113.1|next")
|
||||
|
||||
if _, ok := g.entries["ip:203.0.113.1|failed"]; ok {
|
||||
t.Fatalf("stale failed entry was not pruned")
|
||||
}
|
||||
if _, ok := g.entries["ip:203.0.113.1|next"]; !ok {
|
||||
t.Fatalf("new entry was not created")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
@@ -10,8 +11,10 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"warpbox.dev/backend/libs/config"
|
||||
"warpbox.dev/backend/libs/services"
|
||||
@@ -46,6 +49,42 @@ func TestUploadJSONIncludesManageURLsAndAcceptsShareXField(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileReactionCanBeAddedOncePerVisitor(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
|
||||
payload := uploadThroughApp(t, app)
|
||||
if len(payload.Files) != 1 {
|
||||
t.Fatalf("uploaded files = %d", len(payload.Files))
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodPost, "/d/"+payload.BoxID+"/f/"+payload.Files[0].ID+"/react", strings.NewReader("emoji_id=openmoji/1F600.svg"))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.SetPathValue("boxID", payload.BoxID)
|
||||
request.SetPathValue("fileID", payload.Files[0].ID)
|
||||
response := httptest.NewRecorder()
|
||||
app.ReactToFile(response, request)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("first reaction status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
if !strings.Contains(response.Body.String(), `"count":1`) {
|
||||
t.Fatalf("reaction response missing count: %s", response.Body.String())
|
||||
}
|
||||
|
||||
retry := httptest.NewRequest(http.MethodPost, "/d/"+payload.BoxID+"/f/"+payload.Files[0].ID+"/react", strings.NewReader("emoji_id=openmoji/1F600.svg"))
|
||||
retry.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
retry.SetPathValue("boxID", payload.BoxID)
|
||||
retry.SetPathValue("fileID", payload.Files[0].ID)
|
||||
for _, cookie := range response.Result().Cookies() {
|
||||
retry.AddCookie(cookie)
|
||||
}
|
||||
retryResponse := httptest.NewRecorder()
|
||||
app.ReactToFile(retryResponse, retry)
|
||||
if retryResponse.Code != http.StatusConflict {
|
||||
t.Fatalf("second reaction status = %d, body = %s", retryResponse.Code, retryResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadTextResponseReturnsOnlyBoxURL(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
@@ -67,6 +106,385 @@ func TestUploadTextResponseReturnsOnlyBoxURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialPreviewBotGetsRawSingleFileBox(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
payload := uploadThroughApp(t, app)
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/d/"+payload.BoxID, nil)
|
||||
request.Header.Set("User-Agent", "Discordbot/2.0")
|
||||
request.SetPathValue("boxID", payload.BoxID)
|
||||
response := httptest.NewRecorder()
|
||||
app.DownloadPage(response, request)
|
||||
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "Shared files on Warpbox") {
|
||||
t.Fatalf("social preview bot received HTML download page")
|
||||
}
|
||||
if response.Body.String() != "hello" {
|
||||
t.Fatalf("social preview body = %q", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialPreviewBotGetsRawFilePreview(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
payload := uploadThroughApp(t, app)
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/d/"+payload.BoxID+"/f/"+payload.Files[0].ID, nil)
|
||||
request.Header.Set("User-Agent", "TelegramBot")
|
||||
request.SetPathValue("boxID", payload.BoxID)
|
||||
request.SetPathValue("fileID", payload.Files[0].ID)
|
||||
response := httptest.NewRecorder()
|
||||
app.DownloadFile(response, request)
|
||||
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "preview-title") {
|
||||
t.Fatalf("social preview bot received HTML preview page")
|
||||
}
|
||||
if response.Body.String() != "hello" {
|
||||
t.Fatalf("social preview body = %q", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumableUploadFlowCreatesNormalBox(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
|
||||
createBody := `{"files":[{"name":"note.txt","size":11,"contentType":"text/plain"}],"expiresMinutes":60}`
|
||||
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable", strings.NewReader(createBody))
|
||||
createRequest.Header.Set("Accept", "application/json")
|
||||
createResponse := httptest.NewRecorder()
|
||||
app.CreateResumableUpload(createResponse, createRequest)
|
||||
if createResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, body = %s", createResponse.Code, createResponse.Body.String())
|
||||
}
|
||||
var session struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
ResumeToken string `json:"resumeToken"`
|
||||
ChunkSize int64 `json:"chunkSize"`
|
||||
Files []struct {
|
||||
ID string `json:"id"`
|
||||
ChunkCount int `json:"chunkCount"`
|
||||
UploadedChunks []int `json:"uploadedChunks"`
|
||||
} `json:"files"`
|
||||
}
|
||||
if err := json.Unmarshal(createResponse.Body.Bytes(), &session); err != nil {
|
||||
t.Fatalf("json.Unmarshal session returned error: %v", err)
|
||||
}
|
||||
if session.SessionID == "" || session.ResumeToken == "" || session.ChunkSize != 4 || len(session.Files) != 1 || session.Files[0].ChunkCount != 3 {
|
||||
t.Fatalf("unexpected session response: %+v", session)
|
||||
}
|
||||
|
||||
chunks := map[int]string{1: "o wo", 0: "hell", 2: "rld"}
|
||||
for index, body := range chunks {
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/uploads/resumable/"+session.SessionID+"/files/"+session.Files[0].ID+"/chunks/"+strconv.Itoa(index), strings.NewReader(body))
|
||||
request.SetPathValue("sessionID", session.SessionID)
|
||||
request.SetPathValue("fileID", session.Files[0].ID)
|
||||
request.SetPathValue("index", strconv.Itoa(index))
|
||||
request.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
response := httptest.NewRecorder()
|
||||
app.PutResumableChunk(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("chunk %d status = %d, body = %s", index, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
completeRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable/"+session.SessionID+"/complete", nil)
|
||||
completeRequest.SetPathValue("sessionID", session.SessionID)
|
||||
completeRequest.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
completeResponse := httptest.NewRecorder()
|
||||
app.CompleteResumableUpload(completeResponse, completeRequest)
|
||||
if completeResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("complete status = %d, body = %s", completeResponse.Code, completeResponse.Body.String())
|
||||
}
|
||||
var payload services.UploadResult
|
||||
if err := json.Unmarshal(completeResponse.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("json.Unmarshal result returned error: %v", err)
|
||||
}
|
||||
replayRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable/"+session.SessionID+"/complete", nil)
|
||||
replayRequest.SetPathValue("sessionID", session.SessionID)
|
||||
replayRequest.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
replayResponse := httptest.NewRecorder()
|
||||
app.CompleteResumableUpload(replayResponse, replayRequest)
|
||||
if replayResponse.Code != http.StatusOK {
|
||||
t.Fatalf("complete replay status = %d, body = %s", replayResponse.Code, replayResponse.Body.String())
|
||||
}
|
||||
var replayPayload services.UploadResult
|
||||
if err := json.Unmarshal(replayResponse.Body.Bytes(), &replayPayload); err != nil {
|
||||
t.Fatalf("json.Unmarshal replay result returned error: %v", err)
|
||||
}
|
||||
if replayPayload.BoxID != payload.BoxID || replayPayload.BoxURL == "" {
|
||||
t.Fatalf("unexpected replay result: %+v, original: %+v", replayPayload, payload)
|
||||
}
|
||||
box := waitForProcessedBox(t, app, payload.BoxID)
|
||||
if len(box.Files) != 1 || box.Files[0].Name != "note.txt" || box.Files[0].Size != 11 {
|
||||
t.Fatalf("unexpected box files: %+v", box.Files)
|
||||
}
|
||||
object, err := app.uploadService.OpenFileObject(context.Background(), box, box.Files[0])
|
||||
if err != nil {
|
||||
t.Fatalf("OpenFileObject returned error: %v", err)
|
||||
}
|
||||
data, err := io.ReadAll(object.Body)
|
||||
object.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAll returned error: %v", err)
|
||||
}
|
||||
if string(data) != "hello world" {
|
||||
t.Fatalf("uploaded body = %q", string(data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumableUploadRequiresAllChunks(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
|
||||
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable", strings.NewReader(`{"files":[{"name":"note.txt","size":8,"contentType":"text/plain"}]}`))
|
||||
createResponse := httptest.NewRecorder()
|
||||
app.CreateResumableUpload(createResponse, createRequest)
|
||||
if createResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, body = %s", createResponse.Code, createResponse.Body.String())
|
||||
}
|
||||
var session struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
ResumeToken string `json:"resumeToken"`
|
||||
Files []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"files"`
|
||||
}
|
||||
if err := json.Unmarshal(createResponse.Body.Bytes(), &session); err != nil {
|
||||
t.Fatalf("json.Unmarshal session returned error: %v", err)
|
||||
}
|
||||
chunkRequest := httptest.NewRequest(http.MethodPut, "/api/v1/uploads/resumable/"+session.SessionID+"/files/"+session.Files[0].ID+"/chunks/0", strings.NewReader("hell"))
|
||||
chunkRequest.SetPathValue("sessionID", session.SessionID)
|
||||
chunkRequest.SetPathValue("fileID", session.Files[0].ID)
|
||||
chunkRequest.SetPathValue("index", "0")
|
||||
chunkRequest.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
chunkResponse := httptest.NewRecorder()
|
||||
app.PutResumableChunk(chunkResponse, chunkRequest)
|
||||
if chunkResponse.Code != http.StatusOK {
|
||||
t.Fatalf("chunk status = %d, body = %s", chunkResponse.Code, chunkResponse.Body.String())
|
||||
}
|
||||
|
||||
completeRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable/"+session.SessionID+"/complete", nil)
|
||||
completeRequest.SetPathValue("sessionID", session.SessionID)
|
||||
completeRequest.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
completeResponse := httptest.NewRecorder()
|
||||
app.CompleteResumableUpload(completeResponse, completeRequest)
|
||||
if completeResponse.Code != http.StatusBadRequest {
|
||||
t.Fatalf("complete status = %d, body = %s", completeResponse.Code, completeResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumableStatusRequiresResumeToken(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
|
||||
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable", strings.NewReader(`{"files":[{"name":"note.txt","size":4,"contentType":"text/plain"}]}`))
|
||||
createResponse := httptest.NewRecorder()
|
||||
app.CreateResumableUpload(createResponse, createRequest)
|
||||
if createResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, body = %s", createResponse.Code, createResponse.Body.String())
|
||||
}
|
||||
var session struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
ResumeToken string `json:"resumeToken"`
|
||||
}
|
||||
if err := json.Unmarshal(createResponse.Body.Bytes(), &session); err != nil {
|
||||
t.Fatalf("json.Unmarshal session returned error: %v", err)
|
||||
}
|
||||
|
||||
missing := httptest.NewRequest(http.MethodGet, "/api/v1/uploads/resumable/"+session.SessionID, nil)
|
||||
missing.SetPathValue("sessionID", session.SessionID)
|
||||
missingResponse := httptest.NewRecorder()
|
||||
app.ResumableUploadStatus(missingResponse, missing)
|
||||
if missingResponse.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("missing token status = %d, body = %s", missingResponse.Code, missingResponse.Body.String())
|
||||
}
|
||||
|
||||
wrong := httptest.NewRequest(http.MethodGet, "/api/v1/uploads/resumable/"+session.SessionID, nil)
|
||||
wrong.SetPathValue("sessionID", session.SessionID)
|
||||
wrong.Header.Set("X-Warpbox-Resume-Token", "wrong")
|
||||
wrongResponse := httptest.NewRecorder()
|
||||
app.ResumableUploadStatus(wrongResponse, wrong)
|
||||
if wrongResponse.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("wrong token status = %d, body = %s", wrongResponse.Code, wrongResponse.Body.String())
|
||||
}
|
||||
|
||||
valid := httptest.NewRequest(http.MethodGet, "/api/v1/uploads/resumable/"+session.SessionID, nil)
|
||||
valid.SetPathValue("sessionID", session.SessionID)
|
||||
valid.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
validResponse := httptest.NewRecorder()
|
||||
app.ResumableUploadStatus(validResponse, valid)
|
||||
if validResponse.Code != http.StatusOK {
|
||||
t.Fatalf("valid token status = %d, body = %s", validResponse.Code, validResponse.Body.String())
|
||||
}
|
||||
if strings.Contains(validResponse.Body.String(), "resumeTokenHash") {
|
||||
t.Fatalf("status response leaked token hash: %s", validResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumableUploadCanAddFilesToExistingSession(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
|
||||
createBody := `{"files":[{"name":"one.txt","size":4,"contentType":"text/plain","fingerprint":"one"}],"expiresMinutes":60}`
|
||||
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable", strings.NewReader(createBody))
|
||||
createResponse := httptest.NewRecorder()
|
||||
app.CreateResumableUpload(createResponse, createRequest)
|
||||
if createResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, body = %s", createResponse.Code, createResponse.Body.String())
|
||||
}
|
||||
var session struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
ResumeToken string `json:"resumeToken"`
|
||||
Files []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"files"`
|
||||
}
|
||||
if err := json.Unmarshal(createResponse.Body.Bytes(), &session); err != nil {
|
||||
t.Fatalf("json.Unmarshal session returned error: %v", err)
|
||||
}
|
||||
firstChunk := httptest.NewRequest(http.MethodPut, "/api/v1/uploads/resumable/"+session.SessionID+"/files/"+session.Files[0].ID+"/chunks/0", strings.NewReader("one!"))
|
||||
firstChunk.SetPathValue("sessionID", session.SessionID)
|
||||
firstChunk.SetPathValue("fileID", session.Files[0].ID)
|
||||
firstChunk.SetPathValue("index", "0")
|
||||
firstChunk.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
firstChunkResponse := httptest.NewRecorder()
|
||||
app.PutResumableChunk(firstChunkResponse, firstChunk)
|
||||
if firstChunkResponse.Code != http.StatusOK {
|
||||
t.Fatalf("first chunk status = %d, body = %s", firstChunkResponse.Code, firstChunkResponse.Body.String())
|
||||
}
|
||||
|
||||
addRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable/"+session.SessionID+"/files", strings.NewReader(`{"files":[{"name":"two.txt","size":4,"contentType":"text/plain","fingerprint":"two"}]}`))
|
||||
addRequest.SetPathValue("sessionID", session.SessionID)
|
||||
addRequest.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
addResponse := httptest.NewRecorder()
|
||||
app.AddResumableFiles(addResponse, addRequest)
|
||||
if addResponse.Code != http.StatusOK {
|
||||
t.Fatalf("add status = %d, body = %s", addResponse.Code, addResponse.Body.String())
|
||||
}
|
||||
var updated struct {
|
||||
Files []struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
UploadedChunks []int `json:"uploadedChunks"`
|
||||
} `json:"files"`
|
||||
}
|
||||
if err := json.Unmarshal(addResponse.Body.Bytes(), &updated); err != nil {
|
||||
t.Fatalf("json.Unmarshal updated returned error: %v", err)
|
||||
}
|
||||
if len(updated.Files) != 2 || len(updated.Files[0].UploadedChunks) != 1 {
|
||||
t.Fatalf("unexpected updated session: %+v", updated)
|
||||
}
|
||||
secondChunk := httptest.NewRequest(http.MethodPut, "/api/v1/uploads/resumable/"+session.SessionID+"/files/"+updated.Files[1].ID+"/chunks/0", strings.NewReader("two!"))
|
||||
secondChunk.SetPathValue("sessionID", session.SessionID)
|
||||
secondChunk.SetPathValue("fileID", updated.Files[1].ID)
|
||||
secondChunk.SetPathValue("index", "0")
|
||||
secondChunk.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
secondChunkResponse := httptest.NewRecorder()
|
||||
app.PutResumableChunk(secondChunkResponse, secondChunk)
|
||||
if secondChunkResponse.Code != http.StatusOK {
|
||||
t.Fatalf("second chunk status = %d, body = %s", secondChunkResponse.Code, secondChunkResponse.Body.String())
|
||||
}
|
||||
completeRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable/"+session.SessionID+"/complete", nil)
|
||||
completeRequest.SetPathValue("sessionID", session.SessionID)
|
||||
completeRequest.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
completeResponse := httptest.NewRecorder()
|
||||
app.CompleteResumableUpload(completeResponse, completeRequest)
|
||||
if completeResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("complete status = %d, body = %s", completeResponse.Code, completeResponse.Body.String())
|
||||
}
|
||||
var payload services.UploadResult
|
||||
if err := json.Unmarshal(completeResponse.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("json.Unmarshal result returned error: %v", err)
|
||||
}
|
||||
box, err := app.uploadService.GetBox(payload.BoxID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBox returned error: %v", err)
|
||||
}
|
||||
if len(box.Files) != 2 {
|
||||
t.Fatalf("box file count = %d, want 2", len(box.Files))
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumableCompleteUploadedRequiresTokenAndKeepsFinishedFiles(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
|
||||
createBody := `{"files":[{"name":"done.txt","size":4,"contentType":"text/plain","fingerprint":"done"},{"name":"partial.txt","size":8,"contentType":"text/plain","fingerprint":"partial"}],"expiresMinutes":60}`
|
||||
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable", strings.NewReader(createBody))
|
||||
createResponse := httptest.NewRecorder()
|
||||
app.CreateResumableUpload(createResponse, createRequest)
|
||||
if createResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, body = %s", createResponse.Code, createResponse.Body.String())
|
||||
}
|
||||
var session struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
ResumeToken string `json:"resumeToken"`
|
||||
Files []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"files"`
|
||||
}
|
||||
if err := json.Unmarshal(createResponse.Body.Bytes(), &session); err != nil {
|
||||
t.Fatalf("json.Unmarshal session returned error: %v", err)
|
||||
}
|
||||
for _, chunk := range []struct {
|
||||
fileIndex int
|
||||
index string
|
||||
body string
|
||||
}{
|
||||
{fileIndex: 0, index: "0", body: "done"},
|
||||
{fileIndex: 1, index: "0", body: "part"},
|
||||
} {
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/uploads/resumable/"+session.SessionID+"/files/"+session.Files[chunk.fileIndex].ID+"/chunks/"+chunk.index, strings.NewReader(chunk.body))
|
||||
request.SetPathValue("sessionID", session.SessionID)
|
||||
request.SetPathValue("fileID", session.Files[chunk.fileIndex].ID)
|
||||
request.SetPathValue("index", chunk.index)
|
||||
request.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
response := httptest.NewRecorder()
|
||||
app.PutResumableChunk(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("chunk status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
missing := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable/"+session.SessionID+"/complete-uploaded", nil)
|
||||
missing.SetPathValue("sessionID", session.SessionID)
|
||||
missingResponse := httptest.NewRecorder()
|
||||
app.CompleteUploadedResumableUpload(missingResponse, missing)
|
||||
if missingResponse.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("missing token status = %d, body = %s", missingResponse.Code, missingResponse.Body.String())
|
||||
}
|
||||
|
||||
complete := httptest.NewRequest(http.MethodPost, "/api/v1/uploads/resumable/"+session.SessionID+"/complete-uploaded", nil)
|
||||
complete.SetPathValue("sessionID", session.SessionID)
|
||||
complete.Header.Set("X-Warpbox-Resume-Token", session.ResumeToken)
|
||||
completeResponse := httptest.NewRecorder()
|
||||
app.CompleteUploadedResumableUpload(completeResponse, complete)
|
||||
if completeResponse.Code != http.StatusCreated {
|
||||
t.Fatalf("complete-uploaded status = %d, body = %s", completeResponse.Code, completeResponse.Body.String())
|
||||
}
|
||||
var payload services.UploadResult
|
||||
if err := json.Unmarshal(completeResponse.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("json.Unmarshal result returned error: %v", err)
|
||||
}
|
||||
box, err := app.uploadService.GetBox(payload.BoxID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBox returned error: %v", err)
|
||||
}
|
||||
if len(box.Files) != 1 || box.Files[0].Name != "done.txt" {
|
||||
t.Fatalf("complete-uploaded box files = %+v", box.Files)
|
||||
}
|
||||
if _, err := app.uploadService.GetResumableSession(session.SessionID); !os.IsNotExist(err) {
|
||||
t.Fatalf("GetResumableSession after complete-uploaded error = %v, want os.ErrNotExist", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManageBoxAndDeleteFlow(t *testing.T) {
|
||||
app, cleanup := newTestApp(t)
|
||||
defer cleanup()
|
||||
@@ -178,13 +596,16 @@ func newTestApp(t *testing.T) (*App, func()) {
|
||||
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
cfg := config.Config{
|
||||
AppName: "warpbox.dev",
|
||||
AppVersion: "test",
|
||||
BaseURL: "http://example.test",
|
||||
DataDir: filepath.Join(root, "data"),
|
||||
StaticDir: staticDir,
|
||||
TemplateDir: templateDir,
|
||||
MaxUploadSize: 1024 * 1024,
|
||||
AppName: "warpbox.dev",
|
||||
AppVersion: "test",
|
||||
BaseURL: "http://example.test",
|
||||
DataDir: filepath.Join(root, "data"),
|
||||
StaticDir: staticDir,
|
||||
TemplateDir: templateDir,
|
||||
MaxUploadSize: 1024 * 1024,
|
||||
ResumableUploadsEnabled: true,
|
||||
ResumableChunkSize: 4,
|
||||
ResumableRetention: time.Hour,
|
||||
DefaultSettings: config.SettingsDefaults{
|
||||
AnonymousUploadsEnabled: true,
|
||||
AnonymousMaxUploadMB: 1,
|
||||
@@ -192,12 +613,24 @@ func newTestApp(t *testing.T) (*App, func()) {
|
||||
UserDailyUploadMB: 8,
|
||||
DefaultUserStorageMB: 16,
|
||||
UsageRetentionDays: 30,
|
||||
ResumableUploadsEnabled: true,
|
||||
ResumableChunkSizeMB: 0.000003814697265625,
|
||||
ResumableRetentionHours: 1,
|
||||
ResumableChunkMode: "same",
|
||||
},
|
||||
}
|
||||
service, err := services.NewUploadService(cfg.MaxUploadSize, cfg.DataDir, cfg.BaseURL, logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewUploadService returned error: %v", err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(cfg.DataDir, "emoji", "openmoji"), 0o755); err != nil {
|
||||
service.Close()
|
||||
t.Fatalf("create emoji test dir: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(cfg.DataDir, "emoji", "openmoji", "1F600.svg"), []byte(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>`), 0o644); err != nil {
|
||||
service.Close()
|
||||
t.Fatalf("write emoji test file: %v", err)
|
||||
}
|
||||
renderer, err := web.NewRenderer(cfg.TemplateDir, cfg.AppName, cfg.AppVersion, cfg.BaseURL)
|
||||
if err != nil {
|
||||
service.Close()
|
||||
@@ -213,12 +646,17 @@ func newTestApp(t *testing.T) (*App, func()) {
|
||||
service.Close()
|
||||
t.Fatalf("NewSettingsService returned error: %v", err)
|
||||
}
|
||||
reactionService, err := services.NewReactionService(service.DB())
|
||||
if err != nil {
|
||||
service.Close()
|
||||
t.Fatalf("NewReactionService returned error: %v", err)
|
||||
}
|
||||
banService, err := services.NewBanService(service.DB())
|
||||
if err != nil {
|
||||
service.Close()
|
||||
t.Fatalf("NewBanService returned error: %v", err)
|
||||
}
|
||||
return NewApp(cfg, logger, renderer, service, authService, settingsService, banService), func() {
|
||||
return NewApp(cfg, logger, renderer, service, authService, settingsService, reactionService, banService), func() {
|
||||
if err := service.Close(); err != nil {
|
||||
t.Fatalf("Close returned error: %v", err)
|
||||
}
|
||||
@@ -293,6 +731,31 @@ func tokenFromURL(t *testing.T, value string) string {
|
||||
return parts[len(parts)-1]
|
||||
}
|
||||
|
||||
func waitForProcessedBox(t *testing.T, app *App, boxID string) services.Box {
|
||||
t.Helper()
|
||||
var box services.Box
|
||||
for i := 0; i < 50; i++ {
|
||||
next, err := app.uploadService.GetBox(boxID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBox returned error: %v", err)
|
||||
}
|
||||
box = next
|
||||
processing := false
|
||||
for _, file := range box.Files {
|
||||
if file.Processing {
|
||||
processing = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !processing {
|
||||
return box
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("box %s was still processing: %+v", boxID, box.Files)
|
||||
return box
|
||||
}
|
||||
|
||||
func copyDir(src, dst string) error {
|
||||
return filepath.WalkDir(src, func(path string, d os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
|
||||
@@ -32,13 +32,18 @@ func New(cfg config.Config, logger *slog.Logger) (*http.Server, error) {
|
||||
uploadService.Close()
|
||||
return nil, err
|
||||
}
|
||||
reactionService, err := services.NewReactionService(uploadService.DB())
|
||||
if err != nil {
|
||||
uploadService.Close()
|
||||
return nil, err
|
||||
}
|
||||
banService, err := services.NewBanService(uploadService.DB())
|
||||
if err != nil {
|
||||
uploadService.Close()
|
||||
return nil, err
|
||||
}
|
||||
stopJobs := jobs.StartAll(cfg, logger, uploadService, banService)
|
||||
app := handlers.NewApp(cfg, logger, renderer, uploadService, authService, settingsService, banService)
|
||||
app := handlers.NewApp(cfg, logger, renderer, uploadService, authService, settingsService, reactionService, banService)
|
||||
|
||||
router := http.NewServeMux()
|
||||
app.RegisterRoutes(router)
|
||||
@@ -49,16 +54,17 @@ func New(cfg config.Config, logger *slog.Logger) (*http.Server, error) {
|
||||
middleware.RequestID,
|
||||
middleware.SecurityHeaders,
|
||||
middleware.Gzip,
|
||||
middleware.Logger(logger),
|
||||
middleware.ClientIP(cfg.TrustedProxies),
|
||||
middleware.Bans(logger, banService, cfg.TrustedProxies),
|
||||
)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: cfg.Addr,
|
||||
Handler: handler,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
IdleTimeout: cfg.IdleTimeout,
|
||||
Addr: cfg.Addr,
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: cfg.ReadHeaderTimeout,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
IdleTimeout: cfg.IdleTimeout,
|
||||
}
|
||||
server.RegisterOnShutdown(func() {
|
||||
stopJobs()
|
||||
|
||||
@@ -22,6 +22,14 @@ func newCleanupJob(cfg config.Config, logger *slog.Logger, uploadService *servic
|
||||
if cleaned > 0 {
|
||||
logger.Info("cleanup job complete", "source", "housekeeping", "severity", "user_activity", "code", 2202, "cleaned", cleaned)
|
||||
}
|
||||
cleanedUploads, err := uploadService.CleanupExpiredResumableSessions(time.Now().UTC())
|
||||
if err != nil {
|
||||
logger.Warn("resumable upload cleanup failed", "source", "housekeeping", "severity", "warn", "code", 4204, "error", err.Error())
|
||||
return
|
||||
}
|
||||
if cleanedUploads > 0 {
|
||||
logger.Info("resumable uploads cleaned", "source", "housekeeping", "severity", "user_activity", "code", 2204, "cleaned", cleanedUploads)
|
||||
}
|
||||
if banService != nil {
|
||||
cleanedEvents, err := banService.CleanupAbuseEvents(time.Now().UTC())
|
||||
if err != nil {
|
||||
@@ -37,7 +45,12 @@ func newCleanupJob(cfg config.Config, logger *slog.Logger, uploadService *servic
|
||||
}
|
||||
|
||||
func RunCleanupNow(uploadService *services.UploadService, logger *slog.Logger) (int, error) {
|
||||
return cleanupUnavailableBoxes(uploadService, logger)
|
||||
cleaned, err := cleanupUnavailableBoxes(uploadService, logger)
|
||||
if err != nil {
|
||||
return cleaned, err
|
||||
}
|
||||
cleanedUploads, err := uploadService.CleanupExpiredResumableSessions(time.Now().UTC())
|
||||
return cleaned + cleanedUploads, err
|
||||
}
|
||||
|
||||
func cleanupUnavailableBoxes(uploadService *services.UploadService, logger *slog.Logger) (int, error) {
|
||||
|
||||
@@ -11,11 +11,15 @@ import (
|
||||
func Bans(logger *slog.Logger, bans *services.BanService, trustedProxies []string) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ip := services.ClientIP(r.RemoteAddr, r.Header.Get("X-Forwarded-For"), r.Header.Get("X-Real-IP"), trustedProxies)
|
||||
r = services.WithClientIP(r, ip)
|
||||
ip, ok := services.ClientIPFromContext(r)
|
||||
if !ok {
|
||||
ip = services.ClientIP(r.RemoteAddr, r.Header.Get("X-Forwarded-For"), r.Header.Get("X-Real-IP"), trustedProxies)
|
||||
r = services.WithClientIP(r, ip)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
protectedProxy := services.IsProtectedProxyIP(ip, trustedProxies)
|
||||
|
||||
if bans != nil {
|
||||
if bans != nil && !protectedProxy {
|
||||
if matched, ok, err := bans.Match(ip, now); err != nil {
|
||||
logger.Error("ban match failed", "source", "ban", "severity", "error", "code", 5001, "ip", ip, "error", err.Error())
|
||||
} else if ok {
|
||||
@@ -26,10 +30,20 @@ func Bans(logger *slog.Logger, bans *services.BanService, trustedProxies []strin
|
||||
return
|
||||
}
|
||||
|
||||
settings, err := bans.Settings()
|
||||
if err != nil {
|
||||
logger.Error("ban settings load failed", "source", "ban", "severity", "error", "code", 5004, "ip", ip, "error", err.Error())
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if !settings.AutoBanEnabled {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if pattern, err := bans.MaliciousPattern(r.URL.Path); err != nil {
|
||||
logger.Error("malicious path check failed", "source", "ban", "severity", "error", "code", 5002, "ip", ip, "error", err.Error())
|
||||
} else if pattern != "" {
|
||||
if result, err := bans.RecordAbuse(ip, services.AbuseKindMaliciousPath, r.URL.Path, banThreshold(bans, services.AbuseKindMaliciousPath), now); err != nil {
|
||||
if result, err := bans.RecordAbuse(ip, services.AbuseKindMaliciousPath, r.URL.Path, settings.MaliciousPathThreshold, now); err != nil {
|
||||
logger.Error("malicious path event failed", "source", "ban", "severity", "error", "code", 5003, "ip", ip, "path", r.URL.Path, "error", err.Error())
|
||||
} else if result.Enabled {
|
||||
logger.Warn("malicious path requested", "source", "ban", "severity", "warn", "code", 4302, "ip", ip, "path", r.URL.Path, "pattern", pattern, "count", result.Event.Count)
|
||||
@@ -48,18 +62,3 @@ func Bans(logger *slog.Logger, bans *services.BanService, trustedProxies []strin
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func banThreshold(bans *services.BanService, kind string) int {
|
||||
settings, err := bans.Settings()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
switch kind {
|
||||
case services.AbuseKindAdminLogin:
|
||||
return settings.AdminLoginFailureThreshold
|
||||
case services.AbuseKindUserLogin:
|
||||
return settings.UserLoginFailureThreshold
|
||||
default:
|
||||
return settings.MaliciousPathThreshold
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +79,75 @@ func TestBansMiddlewareAutoBansMaliciousPaths(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBansMiddlewareSkipsAutoBanWhenDisabled(t *testing.T) {
|
||||
bans := newMiddlewareBanService(t)
|
||||
handler := Chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.NotFound(w, r)
|
||||
}), Bans(slog.New(slog.NewTextHandler(io.Discard, nil)), bans, nil))
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
request := httptest.NewRequest(http.MethodGet, "/.env", nil)
|
||||
request.RemoteAddr = "203.0.113.23:6070"
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code == http.StatusForbidden {
|
||||
t.Fatalf("request %d was blocked while auto-ban disabled", i+1)
|
||||
}
|
||||
}
|
||||
if _, ok, err := bans.Match("203.0.113.23", time.Now().UTC()); err != nil || ok {
|
||||
t.Fatalf("disabled auto-ban Match = %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBansMiddlewareDoesNotBlockProtectedProxyIP(t *testing.T) {
|
||||
bans := newMiddlewareBanService(t)
|
||||
if _, err := bans.CreateManualBan("127.0.0.1", "bad historical ban", "admin", time.Now().UTC().Add(time.Hour)); err != nil {
|
||||
t.Fatalf("CreateManualBan returned error: %v", err)
|
||||
}
|
||||
called := false
|
||||
handler := Chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
called = true
|
||||
_, _ = io.WriteString(w, "ok")
|
||||
}), Bans(slog.New(slog.NewTextHandler(io.Discard, nil)), bans, []string{"127.0.0.1"}))
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
request.RemoteAddr = "127.0.0.1:6070"
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
|
||||
if !called || response.Code != http.StatusOK {
|
||||
t.Fatalf("protected proxy response = called %v code %d", called, response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBansMiddlewareDoesNotAutoBanProtectedProxyIP(t *testing.T) {
|
||||
bans := newMiddlewareBanService(t)
|
||||
settings, err := bans.Settings()
|
||||
if err != nil {
|
||||
t.Fatalf("Settings returned error: %v", err)
|
||||
}
|
||||
settings.AutoBanEnabled = true
|
||||
settings.MaliciousPathThreshold = 1
|
||||
if err := bans.UpdateSettings(settings); err != nil {
|
||||
t.Fatalf("UpdateSettings returned error: %v", err)
|
||||
}
|
||||
handler := Chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.NotFound(w, r)
|
||||
}), Bans(slog.New(slog.NewTextHandler(io.Discard, nil)), bans, []string{"127.0.0.1"}))
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/.env", nil)
|
||||
request.RemoteAddr = "127.0.0.1:6070"
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
|
||||
if response.Code == http.StatusForbidden {
|
||||
t.Fatalf("protected proxy was auto-banned")
|
||||
}
|
||||
if _, ok, err := bans.Match("127.0.0.1", time.Now().UTC()); err != nil || ok {
|
||||
t.Fatalf("protected proxy Match = %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func newMiddlewareBanService(t *testing.T) *services.BanService {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
|
||||
16
backend/libs/middleware/client_ip.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"warpbox.dev/backend/libs/services"
|
||||
)
|
||||
|
||||
func ClientIP(trustedProxies []string) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ip := services.ClientIP(r.RemoteAddr, r.Header.Get("X-Forwarded-For"), r.Header.Get("X-Real-IP"), trustedProxies)
|
||||
next.ServeHTTP(w, services.WithClientIP(r, ip))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(status int) {
|
||||
r.status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (r *statusRecorder) Write(data []byte) (int, error) {
|
||||
if r.status == 0 {
|
||||
r.status = http.StatusOK
|
||||
}
|
||||
n, err := r.ResponseWriter.Write(data)
|
||||
r.bytes += n
|
||||
return n, err
|
||||
}
|
||||
|
||||
func Logger(logger *slog.Logger) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
recorder := &statusRecorder{ResponseWriter: w}
|
||||
|
||||
next.ServeHTTP(recorder, r)
|
||||
|
||||
status := recorder.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
|
||||
logger.Info("http request",
|
||||
"source", "http",
|
||||
"severity", "dev",
|
||||
"code", status,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", status,
|
||||
"bytes", recorder.bytes,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"request_id", RequestIDFromContext(r.Context()),
|
||||
"remote_addr", r.RemoteAddr,
|
||||
"user_agent", r.UserAgent(),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -574,6 +574,38 @@ func (s *AuthService) SetUserStorageBackend(userID, backendID string) error {
|
||||
return s.saveUser(user)
|
||||
}
|
||||
|
||||
func (s *AuthService) ClearStorageBackendOverrides(backendID string) (int, error) {
|
||||
backendID = strings.TrimSpace(backendID)
|
||||
if backendID == "" {
|
||||
return 0, nil
|
||||
}
|
||||
cleared := 0
|
||||
err := s.db.Update(func(tx *bbolt.Tx) error {
|
||||
users := tx.Bucket(usersBucket)
|
||||
return users.ForEach(func(key, value []byte) error {
|
||||
var user User
|
||||
if err := json.Unmarshal(value, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.Policy.StorageBackendID == nil || *user.Policy.StorageBackendID != backendID {
|
||||
return nil
|
||||
}
|
||||
user.Policy.StorageBackendID = nil
|
||||
user.UpdatedAt = time.Now().UTC()
|
||||
next, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := users.Put(key, next); err != nil {
|
||||
return err
|
||||
}
|
||||
cleared++
|
||||
return nil
|
||||
})
|
||||
})
|
||||
return cleared, err
|
||||
}
|
||||
|
||||
func (s *AuthService) UpdateUserAdminFields(userID, username, email, role, status string, policy UserPolicy) (User, error) {
|
||||
if err := validateUserPolicy(policy); err != nil {
|
||||
return User{}, err
|
||||
@@ -862,20 +894,20 @@ func validateUserPolicy(policy UserPolicy) error {
|
||||
if policy.DailyUploadMB != nil && ((*policy.DailyUploadMB < 0 && *policy.DailyUploadMB != -1) || *policy.DailyUploadMB == 0) {
|
||||
return fmt.Errorf("daily upload override must be positive or -1 for unlimited")
|
||||
}
|
||||
if policy.StorageQuotaMB != nil && *policy.StorageQuotaMB < 0 {
|
||||
return fmt.Errorf("storage quota override cannot be negative")
|
||||
if policy.StorageQuotaMB != nil && *policy.StorageQuotaMB < 0 && *policy.StorageQuotaMB != -1 {
|
||||
return fmt.Errorf("storage quota override must be 0/positive or -1 for unlimited")
|
||||
}
|
||||
if policy.MaxDays != nil && *policy.MaxDays <= 0 {
|
||||
return fmt.Errorf("expiration override must be positive")
|
||||
if policy.MaxDays != nil && *policy.MaxDays <= 0 && *policy.MaxDays != -1 {
|
||||
return fmt.Errorf("expiration override must be positive or -1 for unlimited")
|
||||
}
|
||||
if policy.DailyBoxes != nil && *policy.DailyBoxes <= 0 {
|
||||
return fmt.Errorf("daily box override must be positive")
|
||||
if policy.DailyBoxes != nil && *policy.DailyBoxes <= 0 && *policy.DailyBoxes != -1 {
|
||||
return fmt.Errorf("daily box override must be positive or -1 for unlimited")
|
||||
}
|
||||
if policy.ActiveBoxes != nil && *policy.ActiveBoxes <= 0 {
|
||||
return fmt.Errorf("active box override must be positive")
|
||||
if policy.ActiveBoxes != nil && *policy.ActiveBoxes <= 0 && *policy.ActiveBoxes != -1 {
|
||||
return fmt.Errorf("active box override must be positive or -1 for unlimited")
|
||||
}
|
||||
if policy.ShortWindowRequests != nil && *policy.ShortWindowRequests <= 0 {
|
||||
return fmt.Errorf("short-window request override must be positive")
|
||||
if policy.ShortWindowRequests != nil && *policy.ShortWindowRequests <= 0 && *policy.ShortWindowRequests != -1 {
|
||||
return fmt.Errorf("short-window request override must be positive or -1 for unlimited")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -312,7 +312,11 @@ func (s *BanService) Match(ip string, now time.Time) (MatchedBan, bool, error) {
|
||||
}
|
||||
now = now.UTC()
|
||||
var matched BanRecord
|
||||
err := s.db.Update(func(tx *bbolt.Tx) error {
|
||||
var matchedKey []byte
|
||||
// Read-only scan first: the common case (no match) only takes a concurrent
|
||||
// read transaction, instead of grabbing the single bbolt write lock on every
|
||||
// request that flows through the ban middleware.
|
||||
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||
bucket := tx.Bucket(bansBucket)
|
||||
return bucket.ForEach(func(key, value []byte) error {
|
||||
if matched.ID != "" {
|
||||
@@ -325,20 +329,37 @@ func (s *BanService) Match(ip string, now time.Time) (MatchedBan, bool, error) {
|
||||
if !record.Active(now) || !banTargetMatches(record.Normalized, parsed) {
|
||||
return nil
|
||||
}
|
||||
record.LastMatchedAt = &now
|
||||
record.UpdatedAt = now
|
||||
next, err := json.Marshal(record)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := bucket.Put(key, next); err != nil {
|
||||
return err
|
||||
}
|
||||
matched = record
|
||||
matchedKey = append([]byte(nil), key...) // key bytes are only valid within the txn
|
||||
return nil
|
||||
})
|
||||
})
|
||||
return MatchedBan{Ban: matched, IP: ip}, matched.ID != "", err
|
||||
if err != nil || matched.ID == "" {
|
||||
return MatchedBan{Ban: matched, IP: ip}, matched.ID != "", err
|
||||
}
|
||||
|
||||
// On a hit, record the match time in a short write transaction.
|
||||
matched.LastMatchedAt = &now
|
||||
matched.UpdatedAt = now
|
||||
_ = s.db.Update(func(tx *bbolt.Tx) error {
|
||||
bucket := tx.Bucket(bansBucket)
|
||||
data := bucket.Get(matchedKey)
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
var record BanRecord
|
||||
if err := json.Unmarshal(data, &record); err != nil {
|
||||
return nil
|
||||
}
|
||||
record.LastMatchedAt = &now
|
||||
record.UpdatedAt = now
|
||||
next, err := json.Marshal(record)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return bucket.Put(matchedKey, next)
|
||||
})
|
||||
return MatchedBan{Ban: matched, IP: ip}, true, nil
|
||||
}
|
||||
|
||||
func (r BanRecord) Active(now time.Time) bool {
|
||||
@@ -451,7 +472,7 @@ func (s *BanService) MaliciousPattern(path string) (string, error) {
|
||||
}
|
||||
|
||||
func shouldSkipMaliciousPath(path string) bool {
|
||||
return path == "/health" || path == "/healthz" || path == "/api/v1/health" || strings.HasPrefix(path, "/static/")
|
||||
return path == "/health" || strings.HasPrefix(path, "/static/")
|
||||
}
|
||||
|
||||
func (s *BanService) RecordAbuse(ip, kind, detail string, threshold int, now time.Time) (AbuseResult, error) {
|
||||
@@ -498,6 +519,11 @@ func (s *BanService) RecordAbuse(ip, kind, detail string, threshold int, now tim
|
||||
if err != nil || !triggered {
|
||||
return AbuseResult{Event: event, Triggered: false, Enabled: true}, err
|
||||
}
|
||||
if matched, ok, err := s.Match(ip, now); err != nil {
|
||||
return AbuseResult{}, err
|
||||
} else if ok {
|
||||
return AbuseResult{Event: event, Ban: matched.Ban, Triggered: true, Enabled: true}, nil
|
||||
}
|
||||
reason := fmt.Sprintf("%s threshold reached: %s", strings.ReplaceAll(kind, "_", " "), detail)
|
||||
ban, err = s.createBan(ip, reason, BanSourceAuto, "", now.Add(time.Duration(settings.AutoBanDurationHours)*time.Hour), now)
|
||||
if err != nil {
|
||||
|
||||
@@ -79,6 +79,17 @@ func TestBanServiceAutoBanThresholdsAndDisabled(t *testing.T) {
|
||||
if err != nil || !result.Triggered || result.Ban.ID == "" {
|
||||
t.Fatalf("RecordAbuse threshold = %+v, %v", result, err)
|
||||
}
|
||||
again, err := bans.RecordAbuse("203.0.113.8", AbuseKindMaliciousPath, "/.env", 3, now.Add(4*time.Minute))
|
||||
if err != nil || !again.Triggered || again.Ban.ID != result.Ban.ID {
|
||||
t.Fatalf("RecordAbuse duplicate = %+v, %v", again, err)
|
||||
}
|
||||
records, err := bans.ListBans()
|
||||
if err != nil {
|
||||
t.Fatalf("ListBans returned error: %v", err)
|
||||
}
|
||||
if len(records) != 1 {
|
||||
t.Fatalf("ban count = %d, want 1", len(records))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBanServiceMaliciousPathRules(t *testing.T) {
|
||||
|
||||
@@ -21,19 +21,19 @@ func ClientIPFromContext(r *http.Request) (string, bool) {
|
||||
// ClientIP resolves the effective client IP. When trustedProxies is empty,
|
||||
// forwarded headers are trusted for easy reverse-proxy/container defaults.
|
||||
func ClientIP(remoteAddr, forwardedFor, realIP string, trustedProxies []string) string {
|
||||
remoteIP := remoteIPOnly(remoteAddr)
|
||||
remoteIP := IPOnly(remoteAddr)
|
||||
if len(trustedProxies) == 0 || remoteTrusted(remoteIP, trustedProxies) {
|
||||
if ip := firstForwardedIP(forwardedFor); ip != "" {
|
||||
return ip
|
||||
return IPOnly(ip)
|
||||
}
|
||||
if ip := strings.TrimSpace(realIP); ip != "" {
|
||||
return ip
|
||||
return IPOnly(ip)
|
||||
}
|
||||
}
|
||||
return remoteIP
|
||||
}
|
||||
|
||||
func remoteIPOnly(remoteAddr string) string {
|
||||
func IPOnly(remoteAddr string) string {
|
||||
host := strings.TrimSpace(remoteAddr)
|
||||
if splitHost, _, err := net.SplitHostPort(remoteAddr); err == nil {
|
||||
host = splitHost
|
||||
@@ -41,14 +41,65 @@ func remoteIPOnly(remoteAddr string) string {
|
||||
return strings.Trim(host, "[]")
|
||||
}
|
||||
|
||||
func firstForwardedIP(forwardedFor string) string {
|
||||
for _, part := range strings.Split(forwardedFor, ",") {
|
||||
ip := strings.TrimSpace(part)
|
||||
if ip != "" {
|
||||
return strings.Trim(ip, "[]")
|
||||
func IsProtectedProxyIP(ip string, trustedProxies []string) bool {
|
||||
parsed := net.ParseIP(IPOnly(ip))
|
||||
if parsed == nil {
|
||||
return false
|
||||
}
|
||||
if parsed.IsLoopback() {
|
||||
return true
|
||||
}
|
||||
return remoteTrusted(parsed.String(), trustedProxies)
|
||||
}
|
||||
|
||||
func ProtectedBanTarget(target string, trustedProxies []string) bool {
|
||||
normalized, err := NormalizeBanTarget(target)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if !strings.Contains(normalized, "/") {
|
||||
return IsProtectedProxyIP(normalized, trustedProxies)
|
||||
}
|
||||
_, targetNet, err := net.ParseCIDR(normalized)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if targetNet.Contains(net.ParseIP("127.0.0.1")) || targetNet.Contains(net.ParseIP("::1")) {
|
||||
return true
|
||||
}
|
||||
for _, trusted := range trustedProxies {
|
||||
trusted = strings.TrimSpace(trusted)
|
||||
if trusted == "" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(trusted, "/") {
|
||||
if _, trustedNet, err := net.ParseCIDR(trusted); err == nil && networksOverlap(targetNet, trustedNet) {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if ip := net.ParseIP(IPOnly(trusted)); ip != nil && targetNet.Contains(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return ""
|
||||
return false
|
||||
}
|
||||
|
||||
func firstForwardedIP(forwardedFor string) string {
|
||||
var fallback string
|
||||
for _, part := range strings.Split(forwardedFor, ",") {
|
||||
ip := IPOnly(part)
|
||||
if net.ParseIP(ip) == nil {
|
||||
continue
|
||||
}
|
||||
if fallback == "" {
|
||||
fallback = ip
|
||||
}
|
||||
if isExternalIP(ip) {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func remoteTrusted(remoteIP string, trustedProxies []string) bool {
|
||||
@@ -73,3 +124,17 @@ func remoteTrusted(remoteIP string, trustedProxies []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isExternalIP(ip string) bool {
|
||||
parsed := net.ParseIP(IPOnly(ip))
|
||||
return parsed != nil &&
|
||||
!parsed.IsLoopback() &&
|
||||
!parsed.IsPrivate() &&
|
||||
!parsed.IsLinkLocalUnicast() &&
|
||||
!parsed.IsLinkLocalMulticast() &&
|
||||
!parsed.IsUnspecified()
|
||||
}
|
||||
|
||||
func networksOverlap(a, b *net.IPNet) bool {
|
||||
return a.Contains(b.IP) || b.Contains(a.IP)
|
||||
}
|
||||
|
||||
@@ -27,3 +27,48 @@ func TestClientIPFallsBackToRealIP(t *testing.T) {
|
||||
t.Fatalf("ClientIP = %q, want real IP", ip)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientIPStripsPortsFromForwardedHeaders(t *testing.T) {
|
||||
ip := ClientIP("127.0.0.1:6070", "203.0.113.15:49152", "", nil)
|
||||
if ip != "203.0.113.15" {
|
||||
t.Fatalf("ClientIP = %q, want forwarded IP without port", ip)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientIPPrefersExternalForwardedAddress(t *testing.T) {
|
||||
ip := ClientIP("127.0.0.1:6070", "172.30.0.1, 198.51.100.30", "", nil)
|
||||
if ip != "198.51.100.30" {
|
||||
t.Fatalf("ClientIP = %q, want public forwarded IP", ip)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPOnlyHandlesIPv6HostPort(t *testing.T) {
|
||||
ip := IPOnly("[2001:db8::1]:6070")
|
||||
if ip != "2001:db8::1" {
|
||||
t.Fatalf("IPOnly = %q, want IPv6 address without port", ip)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtectedProxyIP(t *testing.T) {
|
||||
trusted := []string{"127.0.0.1", "172.30.0.1", "10.88.0.0/16"}
|
||||
for _, ip := range []string{"127.0.0.1:48122", "172.30.0.1", "10.88.0.12"} {
|
||||
if !IsProtectedProxyIP(ip, trusted) {
|
||||
t.Fatalf("IsProtectedProxyIP(%q) = false, want true", ip)
|
||||
}
|
||||
}
|
||||
if IsProtectedProxyIP("203.0.113.50", trusted) {
|
||||
t.Fatalf("external IP treated as protected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtectedBanTarget(t *testing.T) {
|
||||
trusted := []string{"172.30.0.1", "10.88.0.0/16"}
|
||||
for _, target := range []string{"127.0.0.1", "172.30.0.1", "172.30.0.0/24", "10.88.12.0/24"} {
|
||||
if !ProtectedBanTarget(target, trusted) {
|
||||
t.Fatalf("ProtectedBanTarget(%q) = false, want true", target)
|
||||
}
|
||||
}
|
||||
if ProtectedBanTarget("203.0.113.0/24", trusted) {
|
||||
t.Fatalf("external target treated as protected")
|
||||
}
|
||||
}
|
||||
|
||||
166
backend/libs/services/reactions.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.etcd.io/bbolt"
|
||||
)
|
||||
|
||||
var reactionsBucket = []byte("file_reactions")
|
||||
|
||||
type ReactionService struct {
|
||||
db *bbolt.DB
|
||||
}
|
||||
|
||||
type FileReaction struct {
|
||||
BoxID string `json:"boxId"`
|
||||
FileID string `json:"fileId"`
|
||||
EmojiID string `json:"emojiId"`
|
||||
VisitorHash string `json:"visitorHash"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type ReactionSummary struct {
|
||||
EmojiID string `json:"emojiId"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
func NewReactionService(db *bbolt.DB) (*ReactionService, error) {
|
||||
if err := db.Update(func(tx *bbolt.Tx) error {
|
||||
_, err := tx.CreateBucketIfNotExists(reactionsBucket)
|
||||
return err
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ReactionService{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *ReactionService) Add(boxID, fileID, visitorID, emojiID string) ([]ReactionSummary, error) {
|
||||
boxID = strings.TrimSpace(boxID)
|
||||
fileID = strings.TrimSpace(fileID)
|
||||
visitorHash := reactionVisitorHash(visitorID)
|
||||
emojiID = strings.TrimSpace(emojiID)
|
||||
if boxID == "" || fileID == "" || visitorHash == "" || emojiID == "" {
|
||||
return nil, errors.New("missing reaction data")
|
||||
}
|
||||
|
||||
reaction := FileReaction{
|
||||
BoxID: boxID,
|
||||
FileID: fileID,
|
||||
EmojiID: emojiID,
|
||||
VisitorHash: visitorHash,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
data, err := json.Marshal(reaction)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
key := reactionKey(boxID, fileID, visitorHash)
|
||||
if err := s.db.Update(func(tx *bbolt.Tx) error {
|
||||
bucket := tx.Bucket(reactionsBucket)
|
||||
if bucket.Get([]byte(key)) != nil {
|
||||
return os.ErrExist
|
||||
}
|
||||
return bucket.Put([]byte(key), data)
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.SummaryForFile(boxID, fileID)
|
||||
}
|
||||
|
||||
func (s *ReactionService) SummaryForBox(boxID, visitorID string) (map[string][]ReactionSummary, map[string]bool, error) {
|
||||
visitorHash := reactionVisitorHash(visitorID)
|
||||
summaries := make(map[string]map[string]int)
|
||||
viewerReacted := make(map[string]bool)
|
||||
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||
bucket := tx.Bucket(reactionsBucket)
|
||||
if bucket == nil {
|
||||
return nil
|
||||
}
|
||||
return bucket.ForEach(func(_, data []byte) error {
|
||||
var reaction FileReaction
|
||||
if err := json.Unmarshal(data, &reaction); err != nil {
|
||||
return err
|
||||
}
|
||||
if reaction.BoxID != boxID {
|
||||
return nil
|
||||
}
|
||||
if summaries[reaction.FileID] == nil {
|
||||
summaries[reaction.FileID] = make(map[string]int)
|
||||
}
|
||||
summaries[reaction.FileID][reaction.EmojiID]++
|
||||
if visitorHash != "" && reaction.VisitorHash == visitorHash {
|
||||
viewerReacted[reaction.FileID] = true
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
result := make(map[string][]ReactionSummary, len(summaries))
|
||||
for fileID, counts := range summaries {
|
||||
result[fileID] = reactionCountsToSummaries(counts)
|
||||
}
|
||||
return result, viewerReacted, nil
|
||||
}
|
||||
|
||||
func (s *ReactionService) SummaryForFile(boxID, fileID string) ([]ReactionSummary, error) {
|
||||
counts := make(map[string]int)
|
||||
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||
bucket := tx.Bucket(reactionsBucket)
|
||||
if bucket == nil {
|
||||
return nil
|
||||
}
|
||||
return bucket.ForEach(func(_, data []byte) error {
|
||||
var reaction FileReaction
|
||||
if err := json.Unmarshal(data, &reaction); err != nil {
|
||||
return err
|
||||
}
|
||||
if reaction.BoxID == boxID && reaction.FileID == fileID {
|
||||
counts[reaction.EmojiID]++
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return reactionCountsToSummaries(counts), nil
|
||||
}
|
||||
|
||||
func reactionCountsToSummaries(counts map[string]int) []ReactionSummary {
|
||||
summaries := make([]ReactionSummary, 0, len(counts))
|
||||
for emojiID, count := range counts {
|
||||
summaries = append(summaries, ReactionSummary{EmojiID: emojiID, Count: count})
|
||||
}
|
||||
sort.Slice(summaries, func(i, j int) bool {
|
||||
if summaries[i].Count == summaries[j].Count {
|
||||
return summaries[i].EmojiID < summaries[j].EmojiID
|
||||
}
|
||||
return summaries[i].Count > summaries[j].Count
|
||||
})
|
||||
return summaries
|
||||
}
|
||||
|
||||
func reactionKey(boxID, fileID, visitorHash string) string {
|
||||
return boxID + "\x00" + fileID + "\x00" + visitorHash
|
||||
}
|
||||
|
||||
func reactionVisitorHash(visitorID string) string {
|
||||
visitorID = strings.TrimSpace(visitorID)
|
||||
if visitorID == "" {
|
||||
return ""
|
||||
}
|
||||
sum := sha256.Sum256([]byte(visitorID))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
735
backend/libs/services/resumable.go
Normal file
@@ -0,0 +1,735 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.etcd.io/bbolt"
|
||||
)
|
||||
|
||||
var resumableUploadsBucket = []byte("resumable_uploads")
|
||||
|
||||
const (
|
||||
ResumableStatusUploading = "uploading"
|
||||
ResumableStatusProcessing = "processing"
|
||||
ResumableStatusCompleted = "completed"
|
||||
ResumableStatusCancelled = "cancelled"
|
||||
)
|
||||
|
||||
type ResumableFileInput struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
ContentType string `json:"contentType"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
type ResumableSession struct {
|
||||
ID string `json:"id"`
|
||||
Options UploadOptions `json:"options"`
|
||||
Files []ResumableFile `json:"files"`
|
||||
ChunkSize int64 `json:"chunkSize"`
|
||||
Status string `json:"status"`
|
||||
BoxID string `json:"boxId,omitempty"`
|
||||
ResumeTokenHash string `json:"resumeTokenHash,omitempty"`
|
||||
ResumeToken string `json:"-"`
|
||||
ChunkRoot string `json:"chunkRoot,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
}
|
||||
|
||||
type ResumableFile struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
ContentType string `json:"contentType"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
ChunkCount int `json:"chunkCount"`
|
||||
UploadedChunks []int `json:"uploadedChunks"`
|
||||
}
|
||||
|
||||
func (s *UploadService) ensureResumableBucket() error {
|
||||
return s.db.Update(func(tx *bbolt.Tx) error {
|
||||
_, err := tx.CreateBucketIfNotExists(resumableUploadsBucket)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func (s *UploadService) CreateResumableSession(files []ResumableFileInput, opts UploadOptions, chunkSize int64, retention time.Duration, chunkRoot string) (ResumableSession, error) {
|
||||
if len(files) == 0 {
|
||||
return ResumableSession{}, fmt.Errorf("no files were uploaded")
|
||||
}
|
||||
if chunkSize <= 0 {
|
||||
return ResumableSession{}, fmt.Errorf("chunk size must be positive")
|
||||
}
|
||||
if retention <= 0 {
|
||||
return ResumableSession{}, fmt.Errorf("retention must be positive")
|
||||
}
|
||||
if strings.TrimSpace(opts.Password) != "" {
|
||||
opts.PasswordSalt, opts.PasswordHash = hashPassword(opts.Password)
|
||||
opts.Password = ""
|
||||
}
|
||||
sessionFiles, err := s.resumableFilesFromInput(files, opts, chunkSize, nil)
|
||||
if err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
resumeToken := randomID(32)
|
||||
sessionID := randomID(12)
|
||||
session := ResumableSession{
|
||||
ID: sessionID,
|
||||
Options: opts,
|
||||
Files: sessionFiles,
|
||||
ChunkSize: chunkSize,
|
||||
Status: ResumableStatusUploading,
|
||||
ResumeTokenHash: resumableTokenHash(sessionID, resumeToken),
|
||||
ResumeToken: resumeToken,
|
||||
ChunkRoot: strings.TrimSpace(chunkRoot),
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
ExpiresAt: now.Add(retention),
|
||||
}
|
||||
if err := s.saveResumableSession(session); err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *UploadService) VerifyResumableToken(session ResumableSession, token string) bool {
|
||||
if session.ResumeTokenHash == "" || strings.TrimSpace(token) == "" {
|
||||
return false
|
||||
}
|
||||
hash := resumableTokenHash(session.ID, token)
|
||||
return subtle.ConstantTimeCompare([]byte(hash), []byte(session.ResumeTokenHash)) == 1
|
||||
}
|
||||
|
||||
func (s *UploadService) AddResumableFiles(sessionID string, files []ResumableFileInput) (ResumableSession, error) {
|
||||
if len(files) == 0 {
|
||||
return s.GetResumableSession(sessionID)
|
||||
}
|
||||
session, err := s.GetResumableSession(sessionID)
|
||||
if err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
if err := resumableSessionWritable(session); err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
existing := make(map[string]bool)
|
||||
for _, file := range session.Files {
|
||||
existing[resumableFileKey(file.Name, file.Size, file.Fingerprint)] = true
|
||||
}
|
||||
newFiles, err := s.resumableFilesFromInput(files, session.Options, session.ChunkSize, existing)
|
||||
if err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
if len(newFiles) == 0 {
|
||||
return session, nil
|
||||
}
|
||||
session.Files = append(session.Files, newFiles...)
|
||||
session.UpdatedAt = time.Now().UTC()
|
||||
if err := s.saveResumableSession(session); err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *UploadService) GetResumableSession(id string) (ResumableSession, error) {
|
||||
var session ResumableSession
|
||||
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||
bucket := tx.Bucket(resumableUploadsBucket)
|
||||
if bucket == nil {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
data := bucket.Get([]byte(id))
|
||||
if data == nil {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
return json.Unmarshal(data, &session)
|
||||
})
|
||||
if err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *UploadService) PutResumableChunk(ctx context.Context, sessionID, fileID string, index int, body io.Reader) (ResumableSession, error) {
|
||||
session, err := s.GetResumableSession(sessionID)
|
||||
if err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
if err := resumableSessionWritable(session); err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
fileIndex := -1
|
||||
for i, file := range session.Files {
|
||||
if file.ID == fileID {
|
||||
fileIndex = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if fileIndex < 0 {
|
||||
return ResumableSession{}, os.ErrNotExist
|
||||
}
|
||||
file := session.Files[fileIndex]
|
||||
if index < 0 || index >= file.ChunkCount {
|
||||
return ResumableSession{}, fmt.Errorf("chunk index is invalid")
|
||||
}
|
||||
expectedSize := expectedChunkSize(file.Size, session.ChunkSize, index)
|
||||
chunkDir := s.resumableFileDirFor(session, file.ID)
|
||||
if err := os.MkdirAll(chunkDir, 0o755); err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
chunkPath := s.resumableChunkPathFor(session, file.ID, index)
|
||||
tempPath := chunkPath + ".tmp"
|
||||
target, err := os.OpenFile(tempPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
written, copyErr := io.Copy(target, io.LimitReader(body, expectedSize+1))
|
||||
closeErr := target.Close()
|
||||
if copyErr != nil {
|
||||
_ = os.Remove(tempPath)
|
||||
return ResumableSession{}, copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
_ = os.Remove(tempPath)
|
||||
return ResumableSession{}, closeErr
|
||||
}
|
||||
if written != expectedSize {
|
||||
_ = os.Remove(tempPath)
|
||||
return ResumableSession{}, fmt.Errorf("chunk size mismatch")
|
||||
}
|
||||
if err := os.Rename(tempPath, chunkPath); err != nil {
|
||||
_ = os.Remove(tempPath)
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
session.Files[fileIndex].UploadedChunks = addChunkIndex(session.Files[fileIndex].UploadedChunks, index)
|
||||
session.UpdatedAt = time.Now().UTC()
|
||||
if err := s.saveResumableSession(session); err != nil {
|
||||
return ResumableSession{}, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *UploadService) CompleteResumableSession(ctx context.Context, sessionID string) (UploadResult, ResumableSession, error) {
|
||||
session, err := s.GetResumableSession(sessionID)
|
||||
if err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
if (session.Status == ResumableStatusCompleted || session.Status == ResumableStatusProcessing) && session.BoxID != "" {
|
||||
box, err := s.GetBox(session.BoxID)
|
||||
if err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
return s.resultForBox(box, ""), session, nil
|
||||
}
|
||||
if err := resumableSessionWritable(session); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
staged, err := s.resumableIncomingFiles(session)
|
||||
if err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
|
||||
result, err := s.CreateBoxFromIncomingContext(ctx, staged, session.Options)
|
||||
if err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
if err := os.RemoveAll(s.resumableSessionDirFor(session)); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
session.Status = ResumableStatusCompleted
|
||||
session.BoxID = result.BoxID
|
||||
session.UpdatedAt = time.Now().UTC()
|
||||
if err := s.saveResumableSession(session); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
return result, session, nil
|
||||
}
|
||||
|
||||
func (s *UploadService) CreateProcessingBoxFromResumable(sessionID string) (UploadResult, ResumableSession, error) {
|
||||
session, err := s.GetResumableSession(sessionID)
|
||||
if err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
if (session.Status == ResumableStatusCompleted || session.Status == ResumableStatusProcessing) && session.BoxID != "" {
|
||||
box, err := s.GetBox(session.BoxID)
|
||||
if err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
return s.resultForBox(box, ""), session, nil
|
||||
}
|
||||
if err := resumableSessionWritable(session); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
if _, err := s.resumableIncomingFiles(session); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
expiresAt := now.AddDate(0, 0, 7)
|
||||
if session.Options.ExpiresInMinutes < 0 || session.Options.MaxDays < 0 {
|
||||
expiresAt = now.AddDate(100, 0, 0)
|
||||
} else if session.Options.ExpiresInMinutes > 0 {
|
||||
expiresAt = now.Add(time.Duration(session.Options.ExpiresInMinutes) * time.Minute)
|
||||
} else if session.Options.MaxDays > 0 {
|
||||
expiresAt = now.Add(time.Duration(session.Options.MaxDays) * 24 * time.Hour)
|
||||
}
|
||||
|
||||
box := Box{
|
||||
ID: randomID(10),
|
||||
OwnerID: strings.TrimSpace(session.Options.OwnerID),
|
||||
CollectionID: strings.TrimSpace(session.Options.CollectionID),
|
||||
CreatorIP: strings.TrimSpace(session.Options.CreatorIP),
|
||||
StorageBackendID: normalizeBackendID(session.Options.StorageBackendID),
|
||||
CreatedAt: now,
|
||||
ExpiresAt: expiresAt,
|
||||
MaxDownloads: session.Options.MaxDownloads,
|
||||
Obfuscate: session.Options.ObfuscateMetadata && (strings.TrimSpace(session.Options.Password) != "" || strings.TrimSpace(session.Options.PasswordHash) != ""),
|
||||
Files: make([]File, 0, len(session.Files)),
|
||||
}
|
||||
deleteToken := randomID(32)
|
||||
box.DeleteTokenHash = deleteTokenHash(box.ID, deleteToken)
|
||||
if strings.TrimSpace(session.Options.PasswordHash) != "" {
|
||||
box.PasswordSalt = session.Options.PasswordSalt
|
||||
box.PasswordHash = session.Options.PasswordHash
|
||||
} else if strings.TrimSpace(session.Options.Password) != "" {
|
||||
salt, hash := hashPassword(session.Options.Password)
|
||||
box.PasswordSalt = salt
|
||||
box.PasswordHash = hash
|
||||
}
|
||||
|
||||
for _, incoming := range session.Files {
|
||||
fileID := randomID(8)
|
||||
storedName := "@each@" + fileID + strings.ToLower(filepath.Ext(incoming.Name))
|
||||
objectKey := boxObjectKey(box.ID, storedName)
|
||||
contentType := incoming.ContentType
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
box.Files = append(box.Files, File{
|
||||
ID: fileID,
|
||||
Name: filepath.Base(incoming.Name),
|
||||
StoredName: storedName,
|
||||
Size: incoming.Size,
|
||||
ContentType: contentType,
|
||||
PreviewKind: previewKind(contentType),
|
||||
ObjectKey: objectKey,
|
||||
Processing: true,
|
||||
UploadedAt: now,
|
||||
})
|
||||
}
|
||||
if err := s.saveBoxRecord(box); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
session.Status = ResumableStatusProcessing
|
||||
session.BoxID = box.ID
|
||||
session.UpdatedAt = time.Now().UTC()
|
||||
if err := s.saveResumableSession(session); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
return s.resultForBox(box, deleteToken), session, nil
|
||||
}
|
||||
|
||||
func (s *UploadService) FinalizeProcessingResumableSession(ctx context.Context, sessionID string) (UploadResult, error) {
|
||||
session, err := s.GetResumableSession(sessionID)
|
||||
if err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
if session.Status == ResumableStatusCompleted && session.BoxID != "" {
|
||||
box, err := s.GetBox(session.BoxID)
|
||||
if err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
return s.resultForBox(box, ""), nil
|
||||
}
|
||||
if session.Status != ResumableStatusProcessing || session.BoxID == "" {
|
||||
return UploadResult{}, fmt.Errorf("upload session is not processing")
|
||||
}
|
||||
box, err := s.GetBox(session.BoxID)
|
||||
if err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
staged, err := s.resumableIncomingFiles(session)
|
||||
if err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
if len(staged) != len(box.Files) {
|
||||
return UploadResult{}, fmt.Errorf("processing file count mismatch")
|
||||
}
|
||||
backend, err := s.storage.Backend(box.StorageBackendID)
|
||||
if err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
for i, incoming := range staged {
|
||||
source, err := incoming.Open()
|
||||
if err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
file := box.Files[i]
|
||||
if err := s.writeUploadedObject(ctx, backend, file.ObjectKey, source, incoming.Size(), 0, incoming.ContentType()); err != nil {
|
||||
source.Close()
|
||||
_ = backend.Delete(context.Background(), file.ObjectKey)
|
||||
box.Files[i].ProcessingError = err.Error()
|
||||
_ = s.saveBoxRecord(box)
|
||||
return UploadResult{}, err
|
||||
}
|
||||
source.Close()
|
||||
box.Files[i].Processing = false
|
||||
box.Files[i].ProcessingError = ""
|
||||
box.Files[i].UploadedAt = time.Now().UTC()
|
||||
if err := s.saveBoxRecord(box); err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
}
|
||||
if err := s.writeBoxMetadata(box); err != nil {
|
||||
s.logger.Warn("box metadata write failed after resumable processing", "source", "storage", "severity", "warn", "code", 4020, "box_id", box.ID, "error", err.Error())
|
||||
}
|
||||
if err := os.RemoveAll(s.resumableSessionDirFor(session)); err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
session.Status = ResumableStatusCompleted
|
||||
session.UpdatedAt = time.Now().UTC()
|
||||
if err := s.saveResumableSession(session); err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
return s.resultForBox(box, ""), nil
|
||||
}
|
||||
|
||||
func (s *UploadService) CompleteUploadedResumableSession(ctx context.Context, sessionID string) (UploadResult, ResumableSession, error) {
|
||||
session, err := s.GetResumableSession(sessionID)
|
||||
if err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
if err := resumableSessionWritable(session); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
completeFiles := make([]ResumableFile, 0, len(session.Files))
|
||||
for _, file := range session.Files {
|
||||
if resumableFileComplete(file) {
|
||||
completeFiles = append(completeFiles, file)
|
||||
}
|
||||
}
|
||||
if len(completeFiles) == 0 {
|
||||
return UploadResult{}, ResumableSession{}, fmt.Errorf("no fully uploaded files to finish")
|
||||
}
|
||||
partial := session
|
||||
partial.Files = completeFiles
|
||||
staged, err := s.resumableIncomingFiles(partial)
|
||||
if err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
|
||||
result, err := s.CreateBoxFromIncomingContext(ctx, staged, session.Options)
|
||||
if err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
if err := os.RemoveAll(s.resumableSessionDirFor(session)); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
session.Status = ResumableStatusCompleted
|
||||
session.BoxID = result.BoxID
|
||||
session.Files = completeFiles
|
||||
session.UpdatedAt = time.Now().UTC()
|
||||
if err := s.deleteResumableSession(session.ID); err != nil {
|
||||
return UploadResult{}, ResumableSession{}, err
|
||||
}
|
||||
return result, session, nil
|
||||
}
|
||||
|
||||
func (s *UploadService) CancelResumableSession(sessionID string) error {
|
||||
session, err := s.GetResumableSession(sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.RemoveAll(s.resumableSessionDirFor(session)); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.deleteResumableSession(session.ID)
|
||||
}
|
||||
|
||||
func (s *UploadService) CleanupExpiredResumableSessions(now time.Time) (int, error) {
|
||||
candidates := make([]ResumableSession, 0)
|
||||
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||
bucket := tx.Bucket(resumableUploadsBucket)
|
||||
if bucket == nil {
|
||||
return nil
|
||||
}
|
||||
return bucket.ForEach(func(_, value []byte) error {
|
||||
var session ResumableSession
|
||||
if err := json.Unmarshal(value, &session); err != nil {
|
||||
return err
|
||||
}
|
||||
if session.Status == ResumableStatusCompleted ||
|
||||
session.Status == ResumableStatusCancelled ||
|
||||
(session.Status == ResumableStatusUploading && !session.ExpiresAt.After(now)) {
|
||||
candidates = append(candidates, session)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for _, session := range candidates {
|
||||
if err := os.RemoveAll(s.resumableSessionDirFor(session)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
err = s.db.Update(func(tx *bbolt.Tx) error {
|
||||
bucket := tx.Bucket(resumableUploadsBucket)
|
||||
if bucket == nil {
|
||||
return nil
|
||||
}
|
||||
for _, session := range candidates {
|
||||
if err := bucket.Delete([]byte(session.ID)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return len(candidates), err
|
||||
}
|
||||
|
||||
func (s *UploadService) deleteResumableSession(sessionID string) error {
|
||||
return s.db.Update(func(tx *bbolt.Tx) error {
|
||||
bucket := tx.Bucket(resumableUploadsBucket)
|
||||
if bucket == nil {
|
||||
return nil
|
||||
}
|
||||
return bucket.Delete([]byte(sessionID))
|
||||
})
|
||||
}
|
||||
|
||||
func (s *UploadService) saveResumableSession(session ResumableSession) error {
|
||||
if err := s.ensureResumableBucket(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.db.Update(func(tx *bbolt.Tx) error {
|
||||
data, err := json.Marshal(session)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Bucket(resumableUploadsBucket).Put([]byte(session.ID), data)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *UploadService) resumableFilesFromInput(files []ResumableFileInput, opts UploadOptions, chunkSize int64, existing map[string]bool) ([]ResumableFile, error) {
|
||||
sessionFiles := make([]ResumableFile, 0, len(files))
|
||||
for _, file := range files {
|
||||
file.Name = filepath.Base(strings.TrimSpace(file.Name))
|
||||
if file.Name == "." || file.Name == "" {
|
||||
return nil, fmt.Errorf("file name is required")
|
||||
}
|
||||
if file.Size < 0 {
|
||||
return nil, fmt.Errorf("file size is invalid")
|
||||
}
|
||||
fingerprint := strings.TrimSpace(file.Fingerprint)
|
||||
key := resumableFileKey(file.Name, file.Size, fingerprint)
|
||||
if existing != nil && existing[key] {
|
||||
continue
|
||||
}
|
||||
if !opts.SkipSizeLimit {
|
||||
if err := s.ValidateSize(file.Size); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
chunks := int((file.Size + chunkSize - 1) / chunkSize)
|
||||
if chunks == 0 {
|
||||
chunks = 1
|
||||
}
|
||||
sessionFiles = append(sessionFiles, ResumableFile{
|
||||
ID: randomID(8),
|
||||
Name: file.Name,
|
||||
Size: file.Size,
|
||||
ContentType: strings.TrimSpace(file.ContentType),
|
||||
Fingerprint: fingerprint,
|
||||
ChunkCount: chunks,
|
||||
})
|
||||
if existing != nil {
|
||||
existing[key] = true
|
||||
}
|
||||
}
|
||||
return sessionFiles, nil
|
||||
}
|
||||
|
||||
func resumableFileKey(name string, size int64, fingerprint string) string {
|
||||
return strings.TrimSpace(fingerprint) + "|" + filepath.Base(strings.TrimSpace(name)) + "|" + fmt.Sprintf("%d", size)
|
||||
}
|
||||
|
||||
type resumableIncomingFile struct {
|
||||
service *UploadService
|
||||
session ResumableSession
|
||||
file ResumableFile
|
||||
}
|
||||
|
||||
func (f resumableIncomingFile) Name() string {
|
||||
return f.file.Name
|
||||
}
|
||||
|
||||
func (f resumableIncomingFile) Size() int64 {
|
||||
return f.file.Size
|
||||
}
|
||||
|
||||
func (f resumableIncomingFile) ContentType() string {
|
||||
return f.file.ContentType
|
||||
}
|
||||
|
||||
func (f resumableIncomingFile) Open() (io.ReadCloser, error) {
|
||||
return &resumableChunkReader{
|
||||
service: f.service,
|
||||
session: f.session,
|
||||
file: f.file,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type resumableChunkReader struct {
|
||||
service *UploadService
|
||||
session ResumableSession
|
||||
file ResumableFile
|
||||
index int
|
||||
current *os.File
|
||||
}
|
||||
|
||||
func (r *resumableChunkReader) Read(p []byte) (int, error) {
|
||||
for {
|
||||
if r.current == nil {
|
||||
if r.index >= r.file.ChunkCount {
|
||||
return 0, io.EOF
|
||||
}
|
||||
chunk, err := os.Open(r.service.resumableChunkPathFor(r.session, r.file.ID, r.index))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
r.current = chunk
|
||||
}
|
||||
n, err := r.current.Read(p)
|
||||
if err == io.EOF {
|
||||
if closeErr := r.current.Close(); closeErr != nil {
|
||||
r.current = nil
|
||||
return n, closeErr
|
||||
}
|
||||
r.current = nil
|
||||
r.index++
|
||||
if n > 0 {
|
||||
return n, nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
|
||||
func (r *resumableChunkReader) Close() error {
|
||||
if r.current == nil {
|
||||
return nil
|
||||
}
|
||||
err := r.current.Close()
|
||||
r.current = nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *UploadService) resumableIncomingFiles(session ResumableSession) ([]IncomingFile, error) {
|
||||
staged := make([]IncomingFile, 0, len(session.Files))
|
||||
for _, file := range session.Files {
|
||||
if len(file.UploadedChunks) != file.ChunkCount {
|
||||
return nil, fmt.Errorf("file %s is missing chunks", file.Name)
|
||||
}
|
||||
var written int64
|
||||
for i := 0; i < file.ChunkCount; i++ {
|
||||
info, err := os.Stat(s.resumableChunkPathFor(session, file.ID, i))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("file %s is missing chunks", file.Name)
|
||||
}
|
||||
written += info.Size()
|
||||
}
|
||||
if written != file.Size {
|
||||
return nil, fmt.Errorf("chunk size total mismatch")
|
||||
}
|
||||
staged = append(staged, resumableIncomingFile{
|
||||
service: s,
|
||||
session: session,
|
||||
file: file,
|
||||
})
|
||||
}
|
||||
return staged, nil
|
||||
}
|
||||
|
||||
func resumableSessionWritable(session ResumableSession) error {
|
||||
if session.Status != ResumableStatusUploading {
|
||||
return fmt.Errorf("upload session is not active")
|
||||
}
|
||||
if !session.ExpiresAt.After(time.Now().UTC()) {
|
||||
return fmt.Errorf("upload session expired")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func resumableFileComplete(file ResumableFile) bool {
|
||||
return file.ChunkCount > 0 && len(file.UploadedChunks) == file.ChunkCount
|
||||
}
|
||||
|
||||
func expectedChunkSize(fileSize, chunkSize int64, index int) int64 {
|
||||
offset := int64(index) * chunkSize
|
||||
remaining := fileSize - offset
|
||||
if remaining < 0 {
|
||||
return 0
|
||||
}
|
||||
if remaining > chunkSize {
|
||||
return chunkSize
|
||||
}
|
||||
return remaining
|
||||
}
|
||||
|
||||
func addChunkIndex(chunks []int, index int) []int {
|
||||
for _, chunk := range chunks {
|
||||
if chunk == index {
|
||||
return chunks
|
||||
}
|
||||
}
|
||||
chunks = append(chunks, index)
|
||||
sort.Ints(chunks)
|
||||
return chunks
|
||||
}
|
||||
|
||||
func resumableTokenHash(sessionID, token string) string {
|
||||
sum := sha256.Sum256([]byte("warpbox-resumable:" + sessionID + ":" + token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *UploadService) resumableSessionDir(sessionID string) string {
|
||||
return filepath.Join(s.dataDir, "tmp", "uploads", sessionID)
|
||||
}
|
||||
|
||||
func (s *UploadService) resumableSessionDirFor(session ResumableSession) string {
|
||||
if strings.TrimSpace(session.ChunkRoot) != "" {
|
||||
return filepath.Join(session.ChunkRoot, session.ID)
|
||||
}
|
||||
return s.resumableSessionDir(session.ID)
|
||||
}
|
||||
|
||||
func (s *UploadService) resumableFileDir(sessionID, fileID string) string {
|
||||
return filepath.Join(s.resumableSessionDir(sessionID), fileID)
|
||||
}
|
||||
|
||||
func (s *UploadService) resumableFileDirFor(session ResumableSession, fileID string) string {
|
||||
return filepath.Join(s.resumableSessionDirFor(session), fileID)
|
||||
}
|
||||
|
||||
func (s *UploadService) resumableChunkPath(sessionID, fileID string, index int) string {
|
||||
return filepath.Join(s.resumableFileDir(sessionID, fileID), fmt.Sprintf("%06d.part", index))
|
||||
}
|
||||
|
||||
func (s *UploadService) resumableChunkPathFor(session ResumableSession, fileID string, index int) string {
|
||||
return filepath.Join(s.resumableFileDirFor(session, fileID), fmt.Sprintf("%06d.part", index))
|
||||
}
|
||||
@@ -37,6 +37,11 @@ type UploadPolicySettings struct {
|
||||
ShortWindowSeconds int `json:"shortWindowSeconds"`
|
||||
AnonymousStorageBackend string `json:"anonymousStorageBackend"`
|
||||
UserStorageBackend string `json:"userStorageBackend"`
|
||||
ResumableUploadsEnabled bool `json:"resumableUploadsEnabled"`
|
||||
ResumableChunkSizeMB float64 `json:"resumableChunkSizeMb"`
|
||||
ResumableRetentionHours int `json:"resumableRetentionHours"`
|
||||
ResumableChunkMode string `json:"resumableChunkMode"`
|
||||
ResumableChunkPath string `json:"resumableChunkPath"`
|
||||
}
|
||||
|
||||
type UsageRecord struct {
|
||||
@@ -89,6 +94,11 @@ func NewSettingsService(db *bbolt.DB, defaults config.SettingsDefaults) (*Settin
|
||||
ShortWindowSeconds: defaults.ShortWindowSeconds,
|
||||
AnonymousStorageBackend: defaults.AnonymousStorageBackend,
|
||||
UserStorageBackend: defaults.UserStorageBackend,
|
||||
ResumableUploadsEnabled: defaults.ResumableUploadsEnabled,
|
||||
ResumableChunkSizeMB: defaults.ResumableChunkSizeMB,
|
||||
ResumableRetentionHours: defaults.ResumableRetentionHours,
|
||||
ResumableChunkMode: defaults.ResumableChunkMode,
|
||||
ResumableChunkPath: defaults.ResumableChunkPath,
|
||||
},
|
||||
}
|
||||
service.defaults = service.withBuiltinDefaultGaps(service.defaults)
|
||||
@@ -143,6 +153,15 @@ func (s *SettingsService) withBuiltinDefaultGaps(settings UploadPolicySettings)
|
||||
if strings.TrimSpace(settings.UserStorageBackend) == "" {
|
||||
settings.UserStorageBackend = StorageBackendLocal
|
||||
}
|
||||
if settings.ResumableChunkSizeMB <= 0 {
|
||||
settings.ResumableChunkSizeMB = 8
|
||||
}
|
||||
if settings.ResumableRetentionHours <= 0 {
|
||||
settings.ResumableRetentionHours = 24
|
||||
}
|
||||
if strings.TrimSpace(settings.ResumableChunkMode) == "" {
|
||||
settings.ResumableChunkMode = "same"
|
||||
}
|
||||
return settings
|
||||
}
|
||||
|
||||
@@ -156,6 +175,13 @@ func (s *SettingsService) UploadPolicy() (UploadPolicySettings, error) {
|
||||
if err := json.Unmarshal(data, &settings); err != nil {
|
||||
return err
|
||||
}
|
||||
var raw map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, ok := raw["resumableUploadsEnabled"]; !ok {
|
||||
settings.ResumableUploadsEnabled = s.defaults.ResumableUploadsEnabled
|
||||
}
|
||||
settings = s.withDefaultGaps(settings)
|
||||
return nil
|
||||
})
|
||||
@@ -217,6 +243,15 @@ func (s *SettingsService) withDefaultGaps(settings UploadPolicySettings) UploadP
|
||||
if strings.TrimSpace(settings.UserStorageBackend) == "" {
|
||||
settings.UserStorageBackend = s.defaults.UserStorageBackend
|
||||
}
|
||||
if settings.ResumableChunkSizeMB <= 0 {
|
||||
settings.ResumableChunkSizeMB = s.defaults.ResumableChunkSizeMB
|
||||
}
|
||||
if settings.ResumableRetentionHours <= 0 {
|
||||
settings.ResumableRetentionHours = s.defaults.ResumableRetentionHours
|
||||
}
|
||||
if strings.TrimSpace(settings.ResumableChunkMode) == "" {
|
||||
settings.ResumableChunkMode = s.defaults.ResumableChunkMode
|
||||
}
|
||||
return settings
|
||||
}
|
||||
|
||||
@@ -233,6 +268,29 @@ func (s *SettingsService) UpdateUploadPolicy(settings UploadPolicySettings) erro
|
||||
})
|
||||
}
|
||||
|
||||
func (s *SettingsService) ResetStorageBackend(backendID string) (bool, bool, error) {
|
||||
backendID = strings.TrimSpace(backendID)
|
||||
if backendID == "" || backendID == StorageBackendLocal {
|
||||
return false, false, nil
|
||||
}
|
||||
settings, err := s.UploadPolicy()
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
resetAnonymous := settings.AnonymousStorageBackend == backendID
|
||||
resetUser := settings.UserStorageBackend == backendID
|
||||
if !resetAnonymous && !resetUser {
|
||||
return false, false, nil
|
||||
}
|
||||
if resetAnonymous {
|
||||
settings.AnonymousStorageBackend = StorageBackendLocal
|
||||
}
|
||||
if resetUser {
|
||||
settings.UserStorageBackend = StorageBackendLocal
|
||||
}
|
||||
return resetAnonymous, resetUser, s.UpdateUploadPolicy(settings)
|
||||
}
|
||||
|
||||
func (s *SettingsService) Usage(subjectType, subject string, now time.Time) (UsageRecord, error) {
|
||||
key := usageKey(subjectType, subject, now)
|
||||
var record UsageRecord
|
||||
@@ -399,6 +457,18 @@ func (s *SettingsService) validate(settings UploadPolicySettings) error {
|
||||
if settings.ShortWindowRequests <= 0 || settings.ShortWindowSeconds <= 0 {
|
||||
return fmt.Errorf("short-window rate limits must be positive")
|
||||
}
|
||||
if settings.ResumableChunkSizeMB <= 0 {
|
||||
return fmt.Errorf("resumable chunk size must be positive")
|
||||
}
|
||||
if settings.ResumableRetentionHours <= 0 {
|
||||
return fmt.Errorf("resumable retention must be positive")
|
||||
}
|
||||
if settings.ResumableChunkMode != "same" && settings.ResumableChunkMode != "custom" {
|
||||
return fmt.Errorf("resumable chunk storage mode is invalid")
|
||||
}
|
||||
if settings.ResumableChunkMode == "custom" && strings.TrimSpace(settings.ResumableChunkPath) == "" {
|
||||
return fmt.Errorf("custom resumable chunk path is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -86,6 +86,7 @@ type StorageBackendView struct {
|
||||
UsageBytes int64
|
||||
UsageLabel string
|
||||
InUse bool
|
||||
InUseReason string
|
||||
SpeedTests []StorageSpeedTest
|
||||
CanSpeedTest bool
|
||||
}
|
||||
@@ -132,6 +133,14 @@ func (s *StorageService) Backend(id string) (StorageBackend, error) {
|
||||
return s.backendFromConfig(cfg)
|
||||
}
|
||||
|
||||
func (s *StorageService) BackendForMaintenance(id string) (StorageBackend, error) {
|
||||
cfg, err := s.BackendConfig(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.backendFromConfig(cfg)
|
||||
}
|
||||
|
||||
func (s *StorageService) BackendConfig(id string) (StorageBackendConfig, error) {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" || id == StorageBackendLocal {
|
||||
@@ -340,21 +349,6 @@ func (s *StorageService) SaveBackendConfig(cfg StorageBackendConfig) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StorageService) DisableBackend(id string, inUse bool) error {
|
||||
if id == "" || id == StorageBackendLocal {
|
||||
return fmt.Errorf("local storage cannot be disabled")
|
||||
}
|
||||
if inUse {
|
||||
return fmt.Errorf("storage backend is in use")
|
||||
}
|
||||
cfg, err := s.BackendConfig(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Enabled = false
|
||||
return s.SaveBackendConfig(cfg)
|
||||
}
|
||||
|
||||
func (s *StorageService) DeleteBackend(id string, inUse bool) error {
|
||||
if id == "" || id == StorageBackendLocal {
|
||||
return fmt.Errorf("local storage cannot be deleted")
|
||||
|
||||
@@ -42,6 +42,8 @@ type UploadOptions struct {
|
||||
ExpiresInMinutes int
|
||||
MaxDownloads int
|
||||
Password string
|
||||
PasswordSalt string
|
||||
PasswordHash string
|
||||
ObfuscateMetadata bool
|
||||
OwnerID string
|
||||
CollectionID string
|
||||
@@ -50,6 +52,56 @@ type UploadOptions struct {
|
||||
StorageBackendID string
|
||||
}
|
||||
|
||||
type IncomingFile interface {
|
||||
Name() string
|
||||
Size() int64
|
||||
ContentType() string
|
||||
Open() (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
type multipartIncomingFile struct {
|
||||
header *multipart.FileHeader
|
||||
}
|
||||
|
||||
func (f multipartIncomingFile) Name() string {
|
||||
return f.header.Filename
|
||||
}
|
||||
|
||||
func (f multipartIncomingFile) Size() int64 {
|
||||
return f.header.Size
|
||||
}
|
||||
|
||||
func (f multipartIncomingFile) ContentType() string {
|
||||
return f.header.Header.Get("Content-Type")
|
||||
}
|
||||
|
||||
func (f multipartIncomingFile) Open() (io.ReadCloser, error) {
|
||||
return f.header.Open()
|
||||
}
|
||||
|
||||
type StagedUploadFile struct {
|
||||
Filename string
|
||||
FileSize int64
|
||||
MIMEType string
|
||||
Path string
|
||||
}
|
||||
|
||||
func (f StagedUploadFile) Name() string {
|
||||
return f.Filename
|
||||
}
|
||||
|
||||
func (f StagedUploadFile) Size() int64 {
|
||||
return f.FileSize
|
||||
}
|
||||
|
||||
func (f StagedUploadFile) ContentType() string {
|
||||
return f.MIMEType
|
||||
}
|
||||
|
||||
func (f StagedUploadFile) Open() (io.ReadCloser, error) {
|
||||
return os.Open(f.Path)
|
||||
}
|
||||
|
||||
type Box struct {
|
||||
ID string `json:"id"`
|
||||
OwnerID string `json:"ownerId,omitempty"`
|
||||
@@ -78,24 +130,29 @@ type File struct {
|
||||
Thumbnail string `json:"thumbnail,omitempty"`
|
||||
ObjectKey string `json:"objectKey,omitempty"`
|
||||
ThumbnailObjectKey string `json:"thumbnailObjectKey,omitempty"`
|
||||
Processing bool `json:"processing,omitempty"`
|
||||
ProcessingError string `json:"processingError,omitempty"`
|
||||
UploadedAt time.Time `json:"uploadedAt"`
|
||||
}
|
||||
|
||||
type UploadResult struct {
|
||||
BoxID string `json:"boxId"`
|
||||
BoxURL string `json:"boxUrl"`
|
||||
ZipURL string `json:"zipUrl"`
|
||||
ManageURL string `json:"manageUrl"`
|
||||
DeleteURL string `json:"deleteUrl"`
|
||||
ExpiresAt string `json:"expiresAt"`
|
||||
Files []ResultFile `json:"files"`
|
||||
BoxID string `json:"boxId"`
|
||||
BoxURL string `json:"boxUrl"`
|
||||
ZipURL string `json:"zipUrl"`
|
||||
ThumbnailURL string `json:"thumbnailUrl"`
|
||||
ManageURL string `json:"manageUrl"`
|
||||
DeleteURL string `json:"deleteUrl"`
|
||||
ExpiresAt string `json:"expiresAt"`
|
||||
Files []ResultFile `json:"files"`
|
||||
}
|
||||
|
||||
type ResultFile struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Size string `json:"size"`
|
||||
URL string `json:"url"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Size string `json:"size"`
|
||||
URL string `json:"url"`
|
||||
ThumbnailURL string `json:"thumbnailUrl"`
|
||||
Processing bool `json:"processing,omitempty"`
|
||||
}
|
||||
|
||||
type AdminStats struct {
|
||||
@@ -135,6 +192,9 @@ func NewUploadService(maxUploadSize int64, dataDir, baseURL string, logger *slog
|
||||
if err := os.MkdirAll(dbDir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(dataDir, "emoji"), 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
db, err := bbolt.Open(filepath.Join(dbDir, "warpbox.bbolt"), 0o600, &bbolt.Options{Timeout: time.Second})
|
||||
if err != nil {
|
||||
@@ -193,17 +253,32 @@ func (s *UploadService) ValidateSize(size int64) error {
|
||||
}
|
||||
|
||||
func (s *UploadService) CreateBox(files []*multipart.FileHeader, opts UploadOptions) (UploadResult, error) {
|
||||
return s.CreateBoxFromIncoming(multipartIncomingFiles(files), opts)
|
||||
}
|
||||
|
||||
func (s *UploadService) CreateBoxFromIncoming(files []IncomingFile, opts UploadOptions) (UploadResult, error) {
|
||||
return s.CreateBoxFromIncomingContext(context.Background(), files, opts)
|
||||
}
|
||||
|
||||
func (s *UploadService) CreateBoxFromIncomingContext(ctx context.Context, files []IncomingFile, opts UploadOptions) (UploadResult, error) {
|
||||
if len(files) == 0 {
|
||||
return UploadResult{}, fmt.Errorf("no files were uploaded")
|
||||
}
|
||||
if opts.MaxDays <= 0 {
|
||||
opts.MaxDays = 7
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
expiresAt := now.Add(time.Duration(opts.MaxDays) * 24 * time.Hour)
|
||||
if opts.ExpiresInMinutes > 0 {
|
||||
var expiresAt time.Time
|
||||
switch {
|
||||
case opts.ExpiresInMinutes < 0 || opts.MaxDays < 0:
|
||||
// "Forever" — a date far enough out that the box effectively never
|
||||
// expires. No schema change; CanDownload/cleanup keep working as-is.
|
||||
expiresAt = now.AddDate(100, 0, 0)
|
||||
case opts.ExpiresInMinutes > 0:
|
||||
expiresAt = now.Add(time.Duration(opts.ExpiresInMinutes) * time.Minute)
|
||||
default:
|
||||
days := opts.MaxDays
|
||||
if days <= 0 {
|
||||
days = 7
|
||||
}
|
||||
expiresAt = now.Add(time.Duration(days) * 24 * time.Hour)
|
||||
}
|
||||
|
||||
box := Box{
|
||||
@@ -220,65 +295,19 @@ func (s *UploadService) CreateBox(files []*multipart.FileHeader, opts UploadOpti
|
||||
}
|
||||
deleteToken := randomID(32)
|
||||
box.DeleteTokenHash = deleteTokenHash(box.ID, deleteToken)
|
||||
if strings.TrimSpace(opts.Password) != "" {
|
||||
if strings.TrimSpace(opts.PasswordHash) != "" {
|
||||
box.PasswordSalt = opts.PasswordSalt
|
||||
box.PasswordHash = opts.PasswordHash
|
||||
} else if strings.TrimSpace(opts.Password) != "" {
|
||||
salt, hash := hashPassword(opts.Password)
|
||||
box.PasswordSalt = salt
|
||||
box.PasswordHash = hash
|
||||
}
|
||||
|
||||
backend, err := s.storage.Backend(box.StorageBackendID)
|
||||
if err != nil {
|
||||
if err := s.writeIncomingFilesToBox(ctx, &box, files, opts); err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
|
||||
for _, header := range files {
|
||||
if !opts.SkipSizeLimit {
|
||||
if err := s.ValidateSize(header.Size); err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
}
|
||||
|
||||
maxSize := s.maxUploadSize
|
||||
if opts.SkipSizeLimit {
|
||||
maxSize = 0
|
||||
}
|
||||
|
||||
file, err := header.Open()
|
||||
if err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
|
||||
fileID := randomID(8)
|
||||
storedName := "@each@" + fileID + strings.ToLower(filepath.Ext(header.Filename))
|
||||
objectKey := boxObjectKey(box.ID, storedName)
|
||||
contentType := header.Header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
buffer := make([]byte, 512)
|
||||
n, _ := file.Read(buffer)
|
||||
contentType = http.DetectContentType(buffer[:n])
|
||||
if seeker, ok := file.(io.Seeker); ok {
|
||||
_, _ = seeker.Seek(0, io.SeekStart)
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.writeUploadedObject(context.Background(), backend, objectKey, file, header.Size, maxSize, contentType); err != nil {
|
||||
file.Close()
|
||||
return UploadResult{}, err
|
||||
}
|
||||
file.Close()
|
||||
|
||||
box.Files = append(box.Files, File{
|
||||
ID: fileID,
|
||||
Name: filepath.Base(header.Filename),
|
||||
StoredName: storedName,
|
||||
Size: header.Size,
|
||||
ContentType: contentType,
|
||||
PreviewKind: previewKind(contentType),
|
||||
ObjectKey: objectKey,
|
||||
UploadedAt: time.Now().UTC(),
|
||||
})
|
||||
}
|
||||
|
||||
if err := s.SaveBox(box); err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
@@ -294,6 +323,110 @@ func (s *UploadService) CreateBox(files []*multipart.FileHeader, opts UploadOpti
|
||||
return s.resultForBox(box, deleteToken), nil
|
||||
}
|
||||
|
||||
// AppendFiles adds files to an existing box (used to group a ShareX multi-file
|
||||
// selection into a single box). The box keeps its original expiry, password and
|
||||
// other settings; only the new files are written.
|
||||
func (s *UploadService) AppendFiles(boxID string, files []*multipart.FileHeader, opts UploadOptions) (UploadResult, error) {
|
||||
return s.AppendIncomingFiles(boxID, multipartIncomingFiles(files), opts)
|
||||
}
|
||||
|
||||
func (s *UploadService) AppendIncomingFiles(boxID string, files []IncomingFile, opts UploadOptions) (UploadResult, error) {
|
||||
if len(files) == 0 {
|
||||
return UploadResult{}, fmt.Errorf("no files were uploaded")
|
||||
}
|
||||
box, err := s.GetBox(boxID)
|
||||
if err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
if err := s.writeIncomingFilesToBox(context.Background(), &box, files, opts); err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
if err := s.SaveBox(box); err != nil {
|
||||
return UploadResult{}, err
|
||||
}
|
||||
s.logger.Info("upload appended",
|
||||
"source", "user-upload",
|
||||
"severity", "user_activity",
|
||||
"code", 2001,
|
||||
"box_id", box.ID,
|
||||
"added", len(files),
|
||||
"file_count", len(box.Files),
|
||||
)
|
||||
return s.resultForBox(box, ""), nil
|
||||
}
|
||||
|
||||
// writeFilesToBox streams each uploaded file into the box's storage backend and
|
||||
// appends the file metadata to box.Files. The box's StorageBackendID determines
|
||||
// where files land, so it works for both new and existing boxes.
|
||||
func (s *UploadService) writeFilesToBox(box *Box, files []*multipart.FileHeader, opts UploadOptions) error {
|
||||
return s.writeIncomingFilesToBox(context.Background(), box, multipartIncomingFiles(files), opts)
|
||||
}
|
||||
|
||||
func multipartIncomingFiles(files []*multipart.FileHeader) []IncomingFile {
|
||||
incoming := make([]IncomingFile, 0, len(files))
|
||||
for _, file := range files {
|
||||
incoming = append(incoming, multipartIncomingFile{header: file})
|
||||
}
|
||||
return incoming
|
||||
}
|
||||
|
||||
func (s *UploadService) writeIncomingFilesToBox(ctx context.Context, box *Box, files []IncomingFile, opts UploadOptions) error {
|
||||
backend, err := s.storage.Backend(box.StorageBackendID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, incoming := range files {
|
||||
if !opts.SkipSizeLimit {
|
||||
if err := s.ValidateSize(incoming.Size()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
maxSize := s.maxUploadSize
|
||||
if opts.SkipSizeLimit {
|
||||
maxSize = 0
|
||||
}
|
||||
|
||||
file, err := incoming.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fileID := randomID(8)
|
||||
storedName := "@each@" + fileID + strings.ToLower(filepath.Ext(incoming.Name()))
|
||||
objectKey := boxObjectKey(box.ID, storedName)
|
||||
contentType := incoming.ContentType()
|
||||
if contentType == "" {
|
||||
buffer := make([]byte, 512)
|
||||
n, _ := file.Read(buffer)
|
||||
contentType = http.DetectContentType(buffer[:n])
|
||||
if seeker, ok := file.(io.Seeker); ok {
|
||||
_, _ = seeker.Seek(0, io.SeekStart)
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.writeUploadedObject(ctx, backend, objectKey, file, incoming.Size(), maxSize, contentType); err != nil {
|
||||
file.Close()
|
||||
_ = backend.Delete(context.Background(), objectKey)
|
||||
return err
|
||||
}
|
||||
file.Close()
|
||||
|
||||
box.Files = append(box.Files, File{
|
||||
ID: fileID,
|
||||
Name: filepath.Base(incoming.Name()),
|
||||
StoredName: storedName,
|
||||
Size: incoming.Size(),
|
||||
ContentType: contentType,
|
||||
PreviewKind: previewKind(contentType),
|
||||
ObjectKey: objectKey,
|
||||
UploadedAt: time.Now().UTC(),
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *UploadService) GetBox(id string) (Box, error) {
|
||||
var box Box
|
||||
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||
@@ -506,6 +639,28 @@ func (s *UploadService) DeleteBox(boxID string) error {
|
||||
return s.DeleteBoxWithSource(boxID, "admin")
|
||||
}
|
||||
|
||||
func (s *UploadService) DeleteBoxesForStorageBackend(backendID, source string) (int, error) {
|
||||
backendID = normalizeBackendID(backendID)
|
||||
if backendID == StorageBackendLocal {
|
||||
return 0, fmt.Errorf("local storage cannot be deleted")
|
||||
}
|
||||
boxes, err := s.ListBoxes(0)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
deleted := 0
|
||||
for _, box := range boxes {
|
||||
if s.BoxStorageBackendID(box) != backendID {
|
||||
continue
|
||||
}
|
||||
if err := s.DeleteBoxWithSource(box.ID, source); err != nil {
|
||||
return deleted, err
|
||||
}
|
||||
deleted++
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
func (s *UploadService) DeleteBoxWithToken(boxID, token string) error {
|
||||
box, err := s.GetBox(boxID)
|
||||
if err != nil {
|
||||
@@ -525,7 +680,12 @@ func (s *UploadService) DeleteBoxWithSource(boxID, source string) error {
|
||||
return err
|
||||
}
|
||||
if box.ID != "" {
|
||||
if backend, err := s.storage.Backend(s.BoxStorageBackendID(box)); err == nil {
|
||||
backendID := s.BoxStorageBackendID(box)
|
||||
backend, err := s.storage.Backend(backendID)
|
||||
if err != nil {
|
||||
backend, err = s.storage.BackendForMaintenance(backendID)
|
||||
}
|
||||
if err == nil {
|
||||
if err := backend.DeletePrefix(context.Background(), box.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -539,6 +699,80 @@ func (s *UploadService) DeleteBoxWithSource(boxID, source string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveFileFromBox deletes a single file's stored objects (and thumbnail) and
|
||||
// removes it from the box. If it was the box's last file, the whole box is
|
||||
// deleted. Returns whether the box itself was removed.
|
||||
func (s *UploadService) RemoveFileFromBox(boxID, fileID string) (bool, error) {
|
||||
box, err := s.GetBox(boxID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
index := -1
|
||||
for i, file := range box.Files {
|
||||
if file.ID == fileID {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if index < 0 {
|
||||
return false, os.ErrNotExist
|
||||
}
|
||||
file := box.Files[index]
|
||||
|
||||
backendID := s.BoxStorageBackendID(box)
|
||||
backend, err := s.storage.Backend(backendID)
|
||||
if err != nil {
|
||||
backend, err = s.storage.BackendForMaintenance(backendID)
|
||||
}
|
||||
if err == nil {
|
||||
if key := s.FileObjectKey(box, file); key != "" {
|
||||
_ = backend.Delete(context.Background(), key)
|
||||
}
|
||||
if key := s.ThumbnailObjectKey(box, file); key != "" {
|
||||
_ = backend.Delete(context.Background(), key)
|
||||
}
|
||||
}
|
||||
|
||||
box.Files = append(box.Files[:index], box.Files[index+1:]...)
|
||||
if len(box.Files) == 0 {
|
||||
if err := s.DeleteBoxWithSource(box.ID, "admin"); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
if err := s.SaveBox(box); err != nil {
|
||||
return false, err
|
||||
}
|
||||
s.logger.Info("admin removed file", "source", "admin", "severity", "user_activity", "code", 2305, "box_id", box.ID, "file_id", fileID)
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// AdminUpdateBox lets an admin change a box's expiry, download limit, and
|
||||
// optionally clear password protection.
|
||||
func (s *UploadService) AdminUpdateBox(boxID string, expiresAt time.Time, maxDownloads int, removePassword bool) error {
|
||||
box, err := s.GetBox(boxID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !expiresAt.IsZero() {
|
||||
box.ExpiresAt = expiresAt.UTC()
|
||||
}
|
||||
if maxDownloads < 0 {
|
||||
maxDownloads = 0
|
||||
}
|
||||
box.MaxDownloads = maxDownloads
|
||||
if removePassword {
|
||||
box.PasswordHash = ""
|
||||
box.PasswordSalt = ""
|
||||
box.Obfuscate = false
|
||||
}
|
||||
if err := s.SaveBox(box); err != nil {
|
||||
return err
|
||||
}
|
||||
s.logger.Info("admin updated box", "source", "admin", "severity", "user_activity", "code", 2306, "box_id", box.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *UploadService) FindFile(box Box, fileID string) (File, error) {
|
||||
for _, file := range box.Files {
|
||||
if file.ID == fileID {
|
||||
@@ -585,6 +819,9 @@ func (s *UploadService) ThumbnailObjectKey(box Box, file File) string {
|
||||
}
|
||||
|
||||
func (s *UploadService) OpenFileObject(ctx context.Context, box Box, file File) (StorageObject, error) {
|
||||
if file.Processing {
|
||||
return StorageObject{}, fmt.Errorf("file is still processing")
|
||||
}
|
||||
backend, err := s.storage.Backend(s.BoxStorageBackendID(box))
|
||||
if err != nil {
|
||||
return StorageObject{}, err
|
||||
@@ -706,6 +943,13 @@ func (s *UploadService) WriteZip(w io.Writer, box Box) error {
|
||||
}
|
||||
|
||||
func (s *UploadService) SaveBox(box Box) error {
|
||||
if err := s.saveBoxRecord(box); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.writeBoxMetadata(box)
|
||||
}
|
||||
|
||||
func (s *UploadService) saveBoxRecord(box Box) error {
|
||||
if box.StorageBackendID == "" {
|
||||
box.StorageBackendID = StorageBackendLocal
|
||||
}
|
||||
@@ -715,10 +959,7 @@ func (s *UploadService) SaveBox(box Box) error {
|
||||
}
|
||||
|
||||
return s.db.Update(func(tx *bbolt.Tx) error {
|
||||
if err := tx.Bucket(boxesBucket).Put([]byte(box.ID), data); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.writeBoxMetadata(box)
|
||||
return tx.Bucket(boxesBucket).Put([]byte(box.ID), data)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -726,19 +967,29 @@ func (s *UploadService) resultForBox(box Box, deleteToken string) UploadResult {
|
||||
files := make([]ResultFile, 0, len(box.Files))
|
||||
for _, file := range box.Files {
|
||||
files = append(files, ResultFile{
|
||||
ID: file.ID,
|
||||
Name: file.Name,
|
||||
Size: helpers.FormatBytes(file.Size),
|
||||
URL: fmt.Sprintf("%s/d/%s/f/%s", s.baseURL, box.ID, file.ID),
|
||||
ID: file.ID,
|
||||
Name: file.Name,
|
||||
Size: helpers.FormatBytes(file.Size),
|
||||
URL: fmt.Sprintf("%s/d/%s/f/%s", s.baseURL, box.ID, file.ID),
|
||||
ThumbnailURL: fmt.Sprintf("%s/d/%s/thumb/%s", s.baseURL, box.ID, file.ID),
|
||||
Processing: file.Processing,
|
||||
})
|
||||
}
|
||||
|
||||
// The box-level thumbnail points at the most recently added file, so a
|
||||
// per-file ShareX upload previews the file it just sent.
|
||||
thumbnailURL := fmt.Sprintf("%s/d/%s/og-image.jpg", s.baseURL, box.ID)
|
||||
if len(files) > 0 {
|
||||
thumbnailURL = files[len(files)-1].ThumbnailURL
|
||||
}
|
||||
|
||||
result := UploadResult{
|
||||
BoxID: box.ID,
|
||||
BoxURL: fmt.Sprintf("%s/d/%s", s.baseURL, box.ID),
|
||||
ZipURL: fmt.Sprintf("%s/d/%s/zip", s.baseURL, box.ID),
|
||||
ExpiresAt: box.ExpiresAt.Format(time.RFC3339),
|
||||
Files: files,
|
||||
BoxID: box.ID,
|
||||
BoxURL: fmt.Sprintf("%s/d/%s", s.baseURL, box.ID),
|
||||
ZipURL: fmt.Sprintf("%s/d/%s/zip", s.baseURL, box.ID),
|
||||
ThumbnailURL: thumbnailURL,
|
||||
ExpiresAt: box.ExpiresAt.Format(time.RFC3339),
|
||||
Files: files,
|
||||
}
|
||||
if deleteToken != "" {
|
||||
result.ManageURL = fmt.Sprintf("%s/d/%s/manage/%s", s.baseURL, box.ID, deleteToken)
|
||||
@@ -771,21 +1022,34 @@ func writeUploadedFile(path string, source multipart.File, maxSize int64) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *UploadService) writeUploadedObject(ctx context.Context, backend StorageBackend, key string, source multipart.File, size, maxSize int64, contentType string) error {
|
||||
func (s *UploadService) writeUploadedObject(ctx context.Context, backend StorageBackend, key string, source io.Reader, size, maxSize int64, contentType string) error {
|
||||
var reader io.Reader = source
|
||||
putSize := size
|
||||
if maxSize > 0 {
|
||||
reader = io.LimitReader(source, maxSize+1)
|
||||
var buffer bytes.Buffer
|
||||
written, err := io.Copy(&buffer, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if written > maxSize {
|
||||
if size > maxSize {
|
||||
return fmt.Errorf("file exceeds max upload size")
|
||||
}
|
||||
return backend.Put(ctx, key, bytes.NewReader(buffer.Bytes()), written, contentType)
|
||||
reader = io.LimitReader(source, maxSize)
|
||||
putSize = size
|
||||
}
|
||||
if ctx != nil {
|
||||
reader = contextReader{ctx: ctx, reader: reader}
|
||||
}
|
||||
return backend.Put(ctx, key, reader, putSize, contentType)
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func (r contextReader) Read(p []byte) (int, error) {
|
||||
select {
|
||||
case <-r.ctx.Done():
|
||||
return 0, r.ctx.Err()
|
||||
default:
|
||||
return r.reader.Read(p)
|
||||
}
|
||||
return backend.Put(ctx, key, reader, size, contentType)
|
||||
}
|
||||
|
||||
func boxObjectKey(boxID, name string) string {
|
||||
@@ -800,6 +1064,10 @@ func randomID(byteCount int) string {
|
||||
return base64.RawURLEncoding.EncodeToString(data)
|
||||
}
|
||||
|
||||
func RandomPublicToken(byteCount int) string {
|
||||
return randomID(byteCount)
|
||||
}
|
||||
|
||||
func hashPassword(password string) (string, string) {
|
||||
salt := randomID(18)
|
||||
return salt, passwordHash(salt, password)
|
||||
|
||||
@@ -126,6 +126,262 @@ func TestLocalStorageBackendAndLegacyFallback(t *testing.T) {
|
||||
object.Body.Close()
|
||||
}
|
||||
|
||||
func TestResumableSessionUploadOutOfOrderAndComplete(t *testing.T) {
|
||||
service := newTestUploadService(t)
|
||||
session, err := service.CreateResumableSession([]ResumableFileInput{{
|
||||
Name: "note.txt",
|
||||
Size: 11,
|
||||
ContentType: "text/plain",
|
||||
Fingerprint: "sha256:first-chunk",
|
||||
}}, UploadOptions{MaxDays: 1, Password: "secret"}, 4, time.Hour, "")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateResumableSession returned error: %v", err)
|
||||
}
|
||||
if session.ResumeToken == "" || session.ResumeTokenHash == "" {
|
||||
t.Fatalf("resumable session did not create resume token: %+v", session)
|
||||
}
|
||||
if !service.VerifyResumableToken(session, session.ResumeToken) {
|
||||
t.Fatalf("VerifyResumableToken rejected correct token")
|
||||
}
|
||||
if service.VerifyResumableToken(session, "wrong-token") {
|
||||
t.Fatalf("VerifyResumableToken accepted wrong token")
|
||||
}
|
||||
stored, err := service.GetResumableSession(session.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetResumableSession returned error: %v", err)
|
||||
}
|
||||
if stored.ResumeToken != "" {
|
||||
t.Fatalf("stored session leaked raw resume token")
|
||||
}
|
||||
if strings.Contains(stored.ResumeTokenHash, session.ResumeToken) {
|
||||
t.Fatalf("stored token hash contains raw token")
|
||||
}
|
||||
if !service.VerifyResumableToken(stored, session.ResumeToken) {
|
||||
t.Fatalf("stored session rejected correct token")
|
||||
}
|
||||
if session.Options.Password != "" || session.Options.PasswordHash == "" || session.Options.PasswordSalt == "" {
|
||||
t.Fatalf("resumable session did not hash password before storage: %+v", session.Options)
|
||||
}
|
||||
if session.Files[0].ChunkCount != 3 {
|
||||
t.Fatalf("ChunkCount = %d, want 3", session.Files[0].ChunkCount)
|
||||
}
|
||||
if session.Files[0].Fingerprint != "sha256:first-chunk" {
|
||||
t.Fatalf("Fingerprint = %q", session.Files[0].Fingerprint)
|
||||
}
|
||||
for index, body := range map[int]string{2: "rld", 0: "hell", 1: "o wo"} {
|
||||
updated, err := service.PutResumableChunk(testContext(), session.ID, session.Files[0].ID, index, strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatalf("PutResumableChunk(%d) returned error: %v", index, err)
|
||||
}
|
||||
if len(updated.Files[0].UploadedChunks) == 0 {
|
||||
t.Fatalf("UploadedChunks was not updated")
|
||||
}
|
||||
}
|
||||
result, completed, err := service.CompleteResumableSession(testContext(), session.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteResumableSession returned error: %v", err)
|
||||
}
|
||||
if completed.Status != ResumableStatusCompleted || completed.BoxID != result.BoxID {
|
||||
t.Fatalf("completed session = %+v, result = %+v", completed, result)
|
||||
}
|
||||
box := getTestBox(t, service, result.BoxID)
|
||||
if box.PasswordHash == "" || box.PasswordSalt == "" || box.PasswordHash != session.Options.PasswordHash {
|
||||
t.Fatalf("completed box did not preserve hashed password")
|
||||
}
|
||||
object, err := service.OpenFileObject(testContext(), box, box.Files[0])
|
||||
if err != nil {
|
||||
t.Fatalf("OpenFileObject returned error: %v", err)
|
||||
}
|
||||
data, err := io.ReadAll(object.Body)
|
||||
object.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAll returned error: %v", err)
|
||||
}
|
||||
if string(data) != "hello world" {
|
||||
t.Fatalf("object body = %q", string(data))
|
||||
}
|
||||
if _, err := os.Stat(service.resumableSessionDir(session.ID)); !os.IsNotExist(err) {
|
||||
t.Fatalf("resumable temp dir after complete error = %v, want os.ErrNotExist", err)
|
||||
}
|
||||
replayed, replayedSession, err := service.CompleteResumableSession(testContext(), session.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteResumableSession replay returned error: %v", err)
|
||||
}
|
||||
if replayed.BoxID != result.BoxID || replayedSession.Status != ResumableStatusCompleted {
|
||||
t.Fatalf("replayed result = %+v, session = %+v, want box %s completed", replayed, replayedSession, result.BoxID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumableCompleteRejectsMissingChunks(t *testing.T) {
|
||||
service := newTestUploadService(t)
|
||||
session, err := service.CreateResumableSession([]ResumableFileInput{{
|
||||
Name: "note.txt",
|
||||
Size: 8,
|
||||
ContentType: "text/plain",
|
||||
}}, UploadOptions{MaxDays: 1}, 4, time.Hour, "")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateResumableSession returned error: %v", err)
|
||||
}
|
||||
if _, err := service.PutResumableChunk(testContext(), session.ID, session.Files[0].ID, 0, strings.NewReader("hell")); err != nil {
|
||||
t.Fatalf("PutResumableChunk returned error: %v", err)
|
||||
}
|
||||
if _, _, err := service.CompleteResumableSession(testContext(), session.ID); err == nil {
|
||||
t.Fatalf("CompleteResumableSession accepted missing chunks")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumablePartialCompleteKeepsOnlyFinishedFiles(t *testing.T) {
|
||||
service := newTestUploadService(t)
|
||||
session, err := service.CreateResumableSession([]ResumableFileInput{
|
||||
{Name: "done.txt", Size: 4, ContentType: "text/plain", Fingerprint: "done"},
|
||||
{Name: "partial.txt", Size: 8, ContentType: "text/plain", Fingerprint: "partial"},
|
||||
}, UploadOptions{MaxDays: 1}, 4, time.Hour, "")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateResumableSession returned error: %v", err)
|
||||
}
|
||||
if _, err := service.PutResumableChunk(testContext(), session.ID, session.Files[0].ID, 0, strings.NewReader("done")); err != nil {
|
||||
t.Fatalf("PutResumableChunk done returned error: %v", err)
|
||||
}
|
||||
if _, err := service.PutResumableChunk(testContext(), session.ID, session.Files[1].ID, 0, strings.NewReader("part")); err != nil {
|
||||
t.Fatalf("PutResumableChunk partial returned error: %v", err)
|
||||
}
|
||||
result, completed, err := service.CompleteUploadedResumableSession(testContext(), session.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteUploadedResumableSession returned error: %v", err)
|
||||
}
|
||||
if completed.Status != ResumableStatusCompleted || completed.BoxID != result.BoxID || len(completed.Files) != 1 {
|
||||
t.Fatalf("completed session = %+v, result = %+v", completed, result)
|
||||
}
|
||||
box := getTestBox(t, service, result.BoxID)
|
||||
if len(box.Files) != 1 || box.Files[0].Name != "done.txt" {
|
||||
t.Fatalf("partial completion box files = %+v", box.Files)
|
||||
}
|
||||
object, err := service.OpenFileObject(testContext(), box, box.Files[0])
|
||||
if err != nil {
|
||||
t.Fatalf("OpenFileObject returned error: %v", err)
|
||||
}
|
||||
data, err := io.ReadAll(object.Body)
|
||||
object.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAll returned error: %v", err)
|
||||
}
|
||||
if string(data) != "done" {
|
||||
t.Fatalf("partial completion object = %q", string(data))
|
||||
}
|
||||
if _, err := service.GetResumableSession(session.ID); !os.IsNotExist(err) {
|
||||
t.Fatalf("GetResumableSession after partial complete error = %v, want os.ErrNotExist", err)
|
||||
}
|
||||
if _, err := os.Stat(service.resumableSessionDir(session.ID)); !os.IsNotExist(err) {
|
||||
t.Fatalf("resumable temp dir after partial complete error = %v, want os.ErrNotExist", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumablePartialCompleteRejectsNoFinishedFiles(t *testing.T) {
|
||||
service := newTestUploadService(t)
|
||||
session, err := service.CreateResumableSession([]ResumableFileInput{{
|
||||
Name: "partial.txt",
|
||||
Size: 8,
|
||||
ContentType: "text/plain",
|
||||
}}, UploadOptions{MaxDays: 1}, 4, time.Hour, "")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateResumableSession returned error: %v", err)
|
||||
}
|
||||
if _, err := service.PutResumableChunk(testContext(), session.ID, session.Files[0].ID, 0, strings.NewReader("part")); err != nil {
|
||||
t.Fatalf("PutResumableChunk returned error: %v", err)
|
||||
}
|
||||
if _, _, err := service.CompleteUploadedResumableSession(testContext(), session.ID); err == nil {
|
||||
t.Fatalf("CompleteUploadedResumableSession accepted no completed files")
|
||||
}
|
||||
if _, err := service.GetResumableSession(session.ID); err != nil {
|
||||
t.Fatalf("GetResumableSession after failed partial complete returned error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumableSessionCanAddFilesBeforeComplete(t *testing.T) {
|
||||
service := newTestUploadService(t)
|
||||
session, err := service.CreateResumableSession([]ResumableFileInput{{
|
||||
Name: "one.txt",
|
||||
Size: 4,
|
||||
ContentType: "text/plain",
|
||||
Fingerprint: "one",
|
||||
}}, UploadOptions{MaxDays: 1}, 4, time.Hour, "")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateResumableSession returned error: %v", err)
|
||||
}
|
||||
if _, err := service.PutResumableChunk(testContext(), session.ID, session.Files[0].ID, 0, strings.NewReader("one!")); err != nil {
|
||||
t.Fatalf("PutResumableChunk one returned error: %v", err)
|
||||
}
|
||||
updated, err := service.AddResumableFiles(session.ID, []ResumableFileInput{{
|
||||
Name: "two.txt",
|
||||
Size: 4,
|
||||
ContentType: "text/plain",
|
||||
Fingerprint: "two",
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("AddResumableFiles returned error: %v", err)
|
||||
}
|
||||
if len(updated.Files) != 2 {
|
||||
t.Fatalf("files after add = %d, want 2", len(updated.Files))
|
||||
}
|
||||
if updated.Files[0].UploadedChunks[0] != 0 {
|
||||
t.Fatalf("existing uploaded chunk was not preserved: %+v", updated.Files[0])
|
||||
}
|
||||
if _, err := service.AddResumableFiles(session.ID, []ResumableFileInput{{
|
||||
Name: "two.txt",
|
||||
Size: 4,
|
||||
ContentType: "text/plain",
|
||||
Fingerprint: "two",
|
||||
}}); err != nil {
|
||||
t.Fatalf("duplicate AddResumableFiles returned error: %v", err)
|
||||
}
|
||||
updated, err = service.GetResumableSession(session.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetResumableSession returned error: %v", err)
|
||||
}
|
||||
if len(updated.Files) != 2 {
|
||||
t.Fatalf("duplicate add changed file count to %d", len(updated.Files))
|
||||
}
|
||||
if _, err := service.PutResumableChunk(testContext(), session.ID, updated.Files[1].ID, 0, strings.NewReader("two!")); err != nil {
|
||||
t.Fatalf("PutResumableChunk two returned error: %v", err)
|
||||
}
|
||||
result, _, err := service.CompleteResumableSession(testContext(), session.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteResumableSession returned error: %v", err)
|
||||
}
|
||||
box := getTestBox(t, service, result.BoxID)
|
||||
if len(box.Files) != 2 {
|
||||
t.Fatalf("completed box file count = %d, want 2", len(box.Files))
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumableCleanupRemovesExpiredSessionsAndChunks(t *testing.T) {
|
||||
service := newTestUploadService(t)
|
||||
session, err := service.CreateResumableSession([]ResumableFileInput{{
|
||||
Name: "note.txt",
|
||||
Size: 4,
|
||||
ContentType: "text/plain",
|
||||
}}, UploadOptions{MaxDays: 1}, 4, time.Hour, "")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateResumableSession returned error: %v", err)
|
||||
}
|
||||
if _, err := service.PutResumableChunk(testContext(), session.ID, session.Files[0].ID, 0, strings.NewReader("hell")); err != nil {
|
||||
t.Fatalf("PutResumableChunk returned error: %v", err)
|
||||
}
|
||||
cleaned, err := service.CleanupExpiredResumableSessions(session.ExpiresAt.Add(time.Second))
|
||||
if err != nil {
|
||||
t.Fatalf("CleanupExpiredResumableSessions returned error: %v", err)
|
||||
}
|
||||
if cleaned != 1 {
|
||||
t.Fatalf("cleaned = %d, want 1", cleaned)
|
||||
}
|
||||
if _, err := service.GetResumableSession(session.ID); !os.IsNotExist(err) {
|
||||
t.Fatalf("GetResumableSession after cleanup error = %v, want os.ErrNotExist", err)
|
||||
}
|
||||
if _, err := os.Stat(service.resumableSessionDir(session.ID)); !os.IsNotExist(err) {
|
||||
t.Fatalf("resumable temp dir after cleanup error = %v, want os.ErrNotExist", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContaboStorageConfigAllowsDisplayNamesWithSpaces(t *testing.T) {
|
||||
service := newTestUploadService(t)
|
||||
cfg, err := service.Storage().CreateS3Backend(StorageBackendConfig{
|
||||
|
||||
BIN
backend/static/WarpBoxLogo.png
Normal file
|
After Width: | Height: | Size: 423 B |
@@ -58,6 +58,69 @@
|
||||
--surface-2: rgba(39, 39, 42, 0.28);
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] {
|
||||
color-scheme: dark;
|
||||
--background: #1d2021;
|
||||
--foreground: #ebdbb2;
|
||||
--card: #282828;
|
||||
--card-foreground: #ebdbb2;
|
||||
--muted: #32302f;
|
||||
--muted-foreground: #bdae93;
|
||||
--accent: #3c3836;
|
||||
--accent-foreground: #fbf1c7;
|
||||
--border: rgba(235, 219, 178, 0.18);
|
||||
--input: rgba(235, 219, 178, 0.24);
|
||||
--primary: #d79921;
|
||||
--primary-foreground: #1d2021;
|
||||
--primary-hover: #fabd2f;
|
||||
--ring: #fe8019;
|
||||
--success: #b8bb26;
|
||||
--danger: #fb4934;
|
||||
--radius: 0.65rem;
|
||||
--shadow: 0 24px 70px rgba(0, 0, 0, 0.42);
|
||||
--font-sans: "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--header-bg: rgba(29, 32, 33, 0.86);
|
||||
--body-bg:
|
||||
radial-gradient(circle at 20% -8%, rgba(215, 153, 33, 0.2), transparent 28rem),
|
||||
radial-gradient(circle at 85% 8%, rgba(184, 187, 38, 0.12), transparent 26rem),
|
||||
linear-gradient(180deg, #1d2021 0%, #181a1b 100%);
|
||||
--surface-1: rgba(235, 219, 178, 0.06);
|
||||
--surface-1-hover: rgba(235, 219, 178, 0.11);
|
||||
--surface-2: rgba(251, 241, 199, 0.04);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] {
|
||||
color-scheme: dark;
|
||||
--background: #08070d;
|
||||
--foreground: #fff36f;
|
||||
--card: #16131f;
|
||||
--card-foreground: #fff36f;
|
||||
--muted: #251d34;
|
||||
--muted-foreground: #9bfaff;
|
||||
--accent: #332246;
|
||||
--accent-foreground: #fff36f;
|
||||
--border: rgba(255, 242, 0, 0.24);
|
||||
--input: rgba(0, 240, 255, 0.34);
|
||||
--primary: #fff200;
|
||||
--primary-foreground: #08070d;
|
||||
--primary-hover: #00f0ff;
|
||||
--ring: #ff2a6d;
|
||||
--success: #00ff9f;
|
||||
--danger: #ff2a6d;
|
||||
--radius: 0.35rem;
|
||||
--shadow: 0 24px 70px rgba(255, 42, 109, 0.16), 0 0 34px rgba(0, 240, 255, 0.12);
|
||||
--font-sans: "Inter", "Rajdhani", "Orbitron", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--header-bg: rgba(8, 7, 13, 0.86);
|
||||
--body-bg:
|
||||
radial-gradient(circle at 10% -10%, rgba(255, 242, 0, 0.2), transparent 26rem),
|
||||
radial-gradient(circle at 90% 8%, rgba(0, 240, 255, 0.18), transparent 26rem),
|
||||
radial-gradient(circle at 45% 110%, rgba(255, 42, 109, 0.18), transparent 30rem),
|
||||
linear-gradient(180deg, #08070d 0%, #120b1a 100%);
|
||||
--surface-1: rgba(0, 240, 255, 0.07);
|
||||
--surface-1-hover: rgba(255, 242, 0, 0.12);
|
||||
--surface-2: rgba(255, 42, 109, 0.06);
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] {
|
||||
color-scheme: light;
|
||||
--background: #ffffff;
|
||||
@@ -98,6 +161,7 @@ html {
|
||||
font-family: var(--font-sans);
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
overflow-x: clip;
|
||||
}
|
||||
|
||||
body {
|
||||
@@ -107,12 +171,27 @@ body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--body-bg);
|
||||
overflow-x: clip;
|
||||
}
|
||||
|
||||
@supports not (overflow-x: clip) {
|
||||
html,
|
||||
body {
|
||||
overflow-x: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
img,
|
||||
video,
|
||||
canvas,
|
||||
iframe {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
svg {
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
@@ -176,10 +255,18 @@ svg {
|
||||
}
|
||||
|
||||
.brand {
|
||||
min-width: 0;
|
||||
font-weight: 650;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.brand > span:last-child {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
@@ -312,12 +399,15 @@ label span {
|
||||
|
||||
input,
|
||||
select,
|
||||
textarea,
|
||||
button {
|
||||
font: inherit;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
select,
|
||||
textarea {
|
||||
width: 100%;
|
||||
min-height: 2.25rem;
|
||||
border: 1px solid var(--input);
|
||||
@@ -354,6 +444,8 @@ input:disabled {
|
||||
|
||||
.button,
|
||||
button {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 2.25rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -372,6 +464,14 @@ button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.button > span,
|
||||
button > span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.button-primary {
|
||||
background: var(--primary);
|
||||
color: var(--primary-foreground);
|
||||
@@ -433,6 +533,8 @@ pre code {
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 1.5rem;
|
||||
border-radius: 999px;
|
||||
background: var(--muted);
|
||||
@@ -440,6 +542,9 @@ pre code {
|
||||
padding: 0.2rem 0.6rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
.app-shell {
|
||||
width: min(86rem, calc(100% - 2rem));
|
||||
max-width: 100%;
|
||||
margin: 0 auto;
|
||||
padding: 2rem 0;
|
||||
display: grid;
|
||||
@@ -8,6 +9,7 @@
|
||||
}
|
||||
|
||||
.app-sidebar {
|
||||
min-width: 0;
|
||||
position: sticky;
|
||||
top: 5rem;
|
||||
align-self: start;
|
||||
@@ -20,6 +22,7 @@
|
||||
}
|
||||
|
||||
.sidebar-link {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
@@ -30,6 +33,13 @@
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.sidebar-link span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sidebar-link:hover,
|
||||
.sidebar-link.is-active {
|
||||
border-color: var(--border);
|
||||
@@ -100,7 +110,7 @@
|
||||
|
||||
.inline-controls input,
|
||||
.inline-controls select {
|
||||
min-width: 15rem;
|
||||
min-width: min(15rem, 100%);
|
||||
}
|
||||
|
||||
.compact-input {
|
||||
@@ -108,10 +118,18 @@
|
||||
}
|
||||
|
||||
.settings-form {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.settings-form > *,
|
||||
.settings-section > *,
|
||||
.tabs-bar > *,
|
||||
.tab-list > * {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.settings-form-narrow {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.9rem;
|
||||
@@ -207,6 +225,7 @@
|
||||
top: calc(100% + 0.5rem);
|
||||
z-index: 10;
|
||||
width: 15rem;
|
||||
max-width: min(15rem, calc(100vw - 2rem));
|
||||
padding: 1rem;
|
||||
background: color-mix(in srgb, var(--card) 97%, #000);
|
||||
border: 1px solid var(--border);
|
||||
@@ -226,6 +245,7 @@
|
||||
/* Copyable URL field */
|
||||
.copy-field {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
margin-top: 0.75rem;
|
||||
|
||||
@@ -2,19 +2,19 @@
|
||||
* Revamp ("Aurora glass") flourishes.
|
||||
*
|
||||
* These rules only apply to the default/revamp theme. They are scoped to
|
||||
* :root:not([data-theme="classic"]):not([data-theme="retro"]) so they cover both the explicit
|
||||
* data-theme="revamp" attribute AND the no-JS default (no attribute), while
|
||||
* never touching the classic theme. Token colours live in 00-base.css; this
|
||||
* file adds the things a flat token swap can't: the animated aurora backdrop,
|
||||
* frosted glass, gradient accents, glow and motion.
|
||||
* :root exclusions so they cover both the explicit data-theme="revamp"
|
||||
* attribute AND the no-JS default (no attribute), while never touching the
|
||||
* alternate themes. Token colours live in 00-base.css; this file adds the
|
||||
* things a flat token swap can't: the animated aurora backdrop, frosted glass,
|
||||
* gradient accents, glow and motion.
|
||||
*/
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
/* Animated aurora backdrop ------------------------------------------------ */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) body::before {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) body::before {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: -20vmax;
|
||||
@@ -29,7 +29,7 @@
|
||||
animation: aurora-drift 26s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) body::after {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) body::after {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
@@ -52,13 +52,13 @@
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) body::before {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) body::before {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Frosted glass cards ----------------------------------------------------- */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .card {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .card {
|
||||
background: linear-gradient(
|
||||
155deg,
|
||||
color-mix(in srgb, var(--card) 78%, transparent),
|
||||
@@ -70,20 +70,20 @@
|
||||
}
|
||||
|
||||
/* Sticky header gets the same glassy treatment */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .site-header {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .site-header {
|
||||
backdrop-filter: blur(20px) saturate(150%);
|
||||
-webkit-backdrop-filter: blur(20px) saturate(150%);
|
||||
}
|
||||
|
||||
/* Brand mark glows */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .brand-mark {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .brand-mark {
|
||||
background: linear-gradient(135deg, #8b5cf6, #6366f1 55%, #22d3ee);
|
||||
color: #fff;
|
||||
box-shadow: 0 6px 18px rgba(124, 58, 237, 0.45);
|
||||
}
|
||||
|
||||
/* Headings get a soft gradient sheen */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) h1 {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) h1 {
|
||||
background: linear-gradient(120deg, #f5f3ff 0%, #c4b5fd 60%, #67e8f9 100%);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
@@ -91,8 +91,8 @@
|
||||
}
|
||||
|
||||
/* Gradient primary buttons ------------------------------------------------ */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .button-primary,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .button.is-active {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .button-primary,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .button.is-active {
|
||||
background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 55%, #22d3ee 130%);
|
||||
color: #fff;
|
||||
border-color: transparent;
|
||||
@@ -100,43 +100,43 @@
|
||||
transition: transform 140ms ease, box-shadow 160ms ease, filter 160ms ease;
|
||||
}
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .button-primary:hover {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .button-primary:hover {
|
||||
background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 55%, #22d3ee 130%);
|
||||
filter: brightness(1.08);
|
||||
box-shadow: 0 12px 30px rgba(99, 102, 241, 0.5);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .button-primary:active {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .button-primary:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
/* Outline / ghost buttons get a subtle lift on hover */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .button-outline,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .button-ghost {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .button-outline,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .button-ghost {
|
||||
transition: background 140ms ease, border-color 140ms ease, transform 140ms ease;
|
||||
}
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .button-outline:hover,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .button-ghost:hover {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .button-outline:hover,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .button-ghost:hover {
|
||||
border-color: rgba(168, 150, 255, 0.4);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
/* Glow focus rings -------------------------------------------------------- */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) :focus-visible {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) :focus-visible {
|
||||
outline: 2px solid transparent;
|
||||
box-shadow: 0 0 0 2px var(--background), 0 0 0 4px var(--ring), 0 0 16px rgba(167, 139, 250, 0.55);
|
||||
}
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) input:focus,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) select:focus {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) input:focus,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) select:focus {
|
||||
border-color: var(--ring);
|
||||
box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.22);
|
||||
}
|
||||
|
||||
/* Drop zone: animated, glowing -------------------------------------------- */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .drop-zone {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .drop-zone {
|
||||
border-color: rgba(168, 150, 255, 0.3);
|
||||
background:
|
||||
radial-gradient(120% 90% at 50% 0%, rgba(139, 92, 246, 0.1), transparent 70%),
|
||||
@@ -144,18 +144,18 @@
|
||||
transition: border-color 180ms ease, background 180ms ease, transform 180ms ease, box-shadow 180ms ease;
|
||||
}
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .drop-zone:hover,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .drop-zone.is-dragging {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .drop-zone:hover,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .drop-zone.is-dragging {
|
||||
border-color: #a78bfa;
|
||||
box-shadow: 0 0 0 1px rgba(167, 139, 250, 0.4), 0 18px 50px rgba(99, 102, 241, 0.28);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .drop-icon {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .drop-icon {
|
||||
color: #c4b5fd;
|
||||
}
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .drop-zone.is-dragging .drop-icon {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .drop-zone.is-dragging .drop-icon {
|
||||
animation: drop-bounce 700ms ease infinite;
|
||||
}
|
||||
|
||||
@@ -165,34 +165,34 @@
|
||||
}
|
||||
|
||||
/* Badges pick up a tinted glass look */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .badge {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .badge {
|
||||
background: rgba(139, 92, 246, 0.14);
|
||||
color: #d6ccff;
|
||||
border: 1px solid rgba(168, 150, 255, 0.22);
|
||||
}
|
||||
|
||||
/* File / result rows lift on hover */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .download-item,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .result-item {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .download-item,
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .result-item {
|
||||
background: color-mix(in srgb, var(--card) 60%, transparent);
|
||||
border-color: rgba(168, 150, 255, 0.14);
|
||||
transition: border-color 140ms ease, transform 140ms ease, background 140ms ease;
|
||||
}
|
||||
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .download-item:hover {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .download-item:hover {
|
||||
border-color: rgba(168, 150, 255, 0.34);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
/* Thumbnails on the download page */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) .file-emblem {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) .file-emblem {
|
||||
background: linear-gradient(135deg, rgba(139, 92, 246, 0.25), rgba(34, 211, 238, 0.18));
|
||||
color: #d6ccff;
|
||||
border: 1px solid rgba(168, 150, 255, 0.22);
|
||||
}
|
||||
|
||||
/* Gentle entrance for primary content cards */
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) main > * {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) main > * {
|
||||
animation: rise-in 420ms ease both;
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]) main > * {
|
||||
:root:not([data-theme="classic"]):not([data-theme="retro"]):not([data-theme="gruvbox"]):not([data-theme="cyberpunk"]) main > * {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,16 +152,16 @@
|
||||
|
||||
/* Links: classic blue, underlined, purple when visited. Sidebar links and tabs
|
||||
are styled as their own Win98 controls below, so they're excluded here. */
|
||||
:root[data-theme="retro"] a:not(.button):not(.brand):not(.sidebar-link):not(.tab) {
|
||||
:root[data-theme="retro"] a:not(.button):not(.brand):not(.sidebar-link):not(.tab):not(.sort-link) {
|
||||
color: #0000ee;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] a:not(.button):not(.brand):not(.sidebar-link):not(.tab):visited {
|
||||
:root[data-theme="retro"] a:not(.button):not(.brand):not(.sidebar-link):not(.tab):not(.sort-link):visited {
|
||||
color: #551a8b;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] a:not(.button):not(.brand):not(.sidebar-link):not(.tab):hover {
|
||||
:root[data-theme="retro"] a:not(.button):not(.brand):not(.sidebar-link):not(.tab):not(.sort-link):hover {
|
||||
color: #ee0000;
|
||||
}
|
||||
|
||||
@@ -592,31 +592,152 @@
|
||||
content: "\23F1 ";
|
||||
}
|
||||
|
||||
/* List / Thumbnails / Preview images = a Win98 toolbar (menubar) of flat
|
||||
buttons that raise on hover and depress when active. */
|
||||
/* The file browser becomes a Win98 Explorer window: blue titlebar, grey
|
||||
toolbar, sunken content pane and flat rows. */
|
||||
:root[data-theme="retro"] .file-browser-window {
|
||||
border: 1px solid #000000;
|
||||
border-radius: 0;
|
||||
background: #c0c0c0;
|
||||
box-shadow: inset -1px -1px 0 #404040, inset 1px 1px 0 #ffffff, inset -2px -2px 0 #808080, inset 2px 2px 0 #dfdfdf;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser-titlebar {
|
||||
min-height: 1.8rem;
|
||||
margin: 3px 3px 0;
|
||||
padding: 0.2rem 0.45rem;
|
||||
border: 0;
|
||||
background: linear-gradient(to right, #000078 0%, #000078 80%, #0f80cd 100%);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser-titlebar strong,
|
||||
:root[data-theme="retro"] .file-browser-titlebar span {
|
||||
color: #ffffff;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser-window-actions {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser-toolbar {
|
||||
justify-content: space-between;
|
||||
margin: 0 3px;
|
||||
padding: 3px;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #808080;
|
||||
background: #c0c0c0;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .view-toolbar {
|
||||
justify-content: flex-start;
|
||||
gap: 2px;
|
||||
margin-top: 1rem;
|
||||
padding: 3px;
|
||||
margin-top: 0;
|
||||
padding: 0;
|
||||
background: #c0c0c0;
|
||||
border: 1px solid #000000;
|
||||
box-shadow: inset 1px 1px 0 #ffffff, inset -1px -1px 0 #808080;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .view-toolbar .button {
|
||||
:root[data-theme="retro"] .view-toolbar .button,
|
||||
:root[data-theme="retro"] .file-browser-toolbar > .button {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
box-shadow: none;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .view-toolbar .button:hover {
|
||||
:root[data-theme="retro"] .view-toolbar .icon-button {
|
||||
width: 2.2rem;
|
||||
height: 2rem;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .view-toolbar .icon-button svg {
|
||||
margin: 0;
|
||||
display: block;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .view-toolbar .button:hover,
|
||||
:root[data-theme="retro"] .file-browser-toolbar > .button:hover {
|
||||
background: #c0c0c0;
|
||||
box-shadow: inset -1px -1px 0 #808080, inset 1px 1px 0 #ffffff;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .view-toolbar .button.is-active {
|
||||
:root[data-theme="retro"] .view-toolbar .button.is-active,
|
||||
:root[data-theme="retro"] .file-browser-toolbar > .button.is-active {
|
||||
background: #d4d0c8;
|
||||
box-shadow: inset 1px 1px 0 #808080, inset -1px -1px 0 #ffffff;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser-head {
|
||||
margin: 0 3px;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #808080;
|
||||
background: #c0c0c0;
|
||||
color: #000000;
|
||||
text-transform: none;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser {
|
||||
margin: 0 3px 3px;
|
||||
border: 1px solid #000000;
|
||||
background: #ffffff;
|
||||
box-shadow: inset 1px 1px 0 #808080, inset -1px -1px 0 #ffffff;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .download-item {
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-open {
|
||||
border-radius: 0;
|
||||
color: #000000;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-open:hover,
|
||||
:root[data-theme="retro"] .file-open:focus-visible {
|
||||
background: transparent;
|
||||
color: #000000;
|
||||
outline: 2px solid #000078;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser.is-list .file-card:hover,
|
||||
:root[data-theme="retro"] .file-browser.is-list .file-card:focus-within {
|
||||
background: transparent;
|
||||
outline: 2px solid #000078;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser.is-list .file-card:hover .file-open,
|
||||
:root[data-theme="retro"] .file-browser.is-list .file-card:focus-within .file-open {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-media {
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser.is-thumbs .file-open {
|
||||
align-content: start;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-browser.is-thumbs .file-media {
|
||||
justify-self: center;
|
||||
align-self: start;
|
||||
}
|
||||
|
||||
:root[data-theme="retro"] .file-type,
|
||||
:root[data-theme="retro"] .file-size,
|
||||
:root[data-theme="retro"] .file-main small {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
88
backend/static/css/17-gruvbox.css
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Gruvbox theme polish.
|
||||
*
|
||||
* Core colour tokens live in 00-base.css. This file adds the warmer, grounded
|
||||
* Gruvbox-specific surface treatment without changing layout behavior.
|
||||
*/
|
||||
|
||||
:root[data-theme="gruvbox"] .site-header {
|
||||
border-bottom-color: rgba(250, 189, 47, 0.2);
|
||||
backdrop-filter: blur(16px) saturate(130%);
|
||||
-webkit-backdrop-filter: blur(16px) saturate(130%);
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .brand-mark {
|
||||
background: linear-gradient(135deg, #d79921, #fe8019);
|
||||
color: #1d2021;
|
||||
box-shadow: 0 8px 22px rgba(254, 128, 25, 0.22);
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .card,
|
||||
:root[data-theme="gruvbox"] .app-sidebar,
|
||||
:root[data-theme="gruvbox"] .storage-card,
|
||||
:root[data-theme="gruvbox"] .storage-op-card,
|
||||
:root[data-theme="gruvbox"] .metric-card,
|
||||
:root[data-theme="gruvbox"] .logs-filter-card {
|
||||
background: color-mix(in srgb, var(--card) 92%, #1d2021);
|
||||
border-color: rgba(235, 219, 178, 0.16);
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .admin-shell .app-sidebar {
|
||||
border-color: rgba(250, 189, 47, 0.32);
|
||||
background: linear-gradient(180deg, rgba(215, 153, 33, 0.12), rgba(40, 40, 40, 0.94));
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .admin-shell .sidebar-link.is-active {
|
||||
border-color: rgba(250, 189, 47, 0.36);
|
||||
background: rgba(215, 153, 33, 0.14);
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .admin-shell .kicker,
|
||||
:root[data-theme="gruvbox"] .kicker {
|
||||
color: #fabd2f;
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] h1 {
|
||||
color: #fbf1c7;
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .button-primary,
|
||||
:root[data-theme="gruvbox"] .button.is-active {
|
||||
border-color: rgba(250, 189, 47, 0.3);
|
||||
background: linear-gradient(135deg, #d79921, #fabd2f);
|
||||
color: #1d2021;
|
||||
box-shadow: 0 10px 24px rgba(215, 153, 33, 0.2);
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .button-primary:hover {
|
||||
background: linear-gradient(135deg, #fabd2f, #fe8019);
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .button-outline,
|
||||
:root[data-theme="gruvbox"] .button-ghost:hover,
|
||||
:root[data-theme="gruvbox"] .button-outline:hover {
|
||||
border-color: rgba(235, 219, 178, 0.2);
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .badge-active,
|
||||
:root[data-theme="gruvbox"] .storage-detail-test.is-ok > span:last-child {
|
||||
color: #b8bb26;
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] .badge-disabled,
|
||||
:root[data-theme="gruvbox"] .storage-detail-test.is-err > span:last-child,
|
||||
:root[data-theme="gruvbox"] .form-error {
|
||||
color: #fb4934;
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] input:focus,
|
||||
:root[data-theme="gruvbox"] select:focus,
|
||||
:root[data-theme="gruvbox"] textarea:focus {
|
||||
border-color: #fe8019;
|
||||
box-shadow: 0 0 0 3px rgba(254, 128, 25, 0.18);
|
||||
}
|
||||
|
||||
:root[data-theme="gruvbox"] ::selection {
|
||||
background: #d79921;
|
||||
color: #1d2021;
|
||||
}
|
||||
196
backend/static/css/18-cyberpunk.css
Normal file
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
* CyberPunk theme polish.
|
||||
*
|
||||
* Inspired by neon Cyberpunk 2077 UI treatments: warning yellow surfaces,
|
||||
* cyan/magenta light, hard edges, scanlines, and high-contrast panels.
|
||||
*/
|
||||
|
||||
:root[data-theme="cyberpunk"] body::before {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
pointer-events: none;
|
||||
background:
|
||||
linear-gradient(rgba(255, 242, 0, 0.035) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(0, 240, 255, 0.03) 1px, transparent 1px);
|
||||
background-size: 100% 3px, 3rem 100%;
|
||||
mix-blend-mode: screen;
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] body::after {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
pointer-events: none;
|
||||
background:
|
||||
linear-gradient(115deg, transparent 0 18%, rgba(255, 242, 0, 0.06) 18% 19%, transparent 19% 100%),
|
||||
linear-gradient(245deg, transparent 0 76%, rgba(255, 42, 109, 0.08) 76% 77%, transparent 77% 100%);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .site-header {
|
||||
border-bottom-color: rgba(255, 242, 0, 0.32);
|
||||
box-shadow: 0 0 22px rgba(0, 240, 255, 0.12);
|
||||
backdrop-filter: blur(12px) saturate(150%);
|
||||
-webkit-backdrop-filter: blur(12px) saturate(150%);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .brand {
|
||||
text-transform: lowercase;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .brand-mark {
|
||||
background: #fff200;
|
||||
color: #08070d;
|
||||
box-shadow: 0 0 0 1px rgba(0, 240, 255, 0.45), 0 0 18px rgba(255, 242, 0, 0.42);
|
||||
clip-path: polygon(0 0, 100% 0, 100% 72%, 78% 100%, 0 100%);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] h1 {
|
||||
color: #fff200;
|
||||
text-shadow: 2px 0 0 rgba(255, 42, 109, 0.58), -2px 0 0 rgba(0, 240, 255, 0.46);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .card,
|
||||
:root[data-theme="cyberpunk"] .app-sidebar,
|
||||
:root[data-theme="cyberpunk"] .storage-card,
|
||||
:root[data-theme="cyberpunk"] .storage-op-card,
|
||||
:root[data-theme="cyberpunk"] .metric-card,
|
||||
:root[data-theme="cyberpunk"] .logs-filter-card,
|
||||
:root[data-theme="cyberpunk"] .advanced-options {
|
||||
position: relative;
|
||||
background:
|
||||
linear-gradient(145deg, rgba(22, 19, 31, 0.96), rgba(13, 10, 20, 0.96)),
|
||||
linear-gradient(90deg, rgba(255, 242, 0, 0.16), rgba(0, 240, 255, 0.08));
|
||||
border-color: rgba(255, 242, 0, 0.28);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .card::before,
|
||||
:root[data-theme="cyberpunk"] .storage-card::before,
|
||||
:root[data-theme="cyberpunk"] .metric-card::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
border-top: 1px solid rgba(0, 240, 255, 0.4);
|
||||
clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .admin-shell .app-sidebar {
|
||||
border-color: rgba(255, 42, 109, 0.38);
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255, 42, 109, 0.16), rgba(8, 7, 13, 0.94)),
|
||||
#16131f;
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .sidebar-link:hover,
|
||||
:root[data-theme="cyberpunk"] .sidebar-link.is-active,
|
||||
:root[data-theme="cyberpunk"] .admin-shell .sidebar-link.is-active {
|
||||
border-color: rgba(255, 242, 0, 0.42);
|
||||
background: linear-gradient(90deg, rgba(255, 242, 0, 0.2), rgba(0, 240, 255, 0.08));
|
||||
color: #fff200;
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .kicker,
|
||||
:root[data-theme="cyberpunk"] .admin-shell .kicker {
|
||||
color: #00f0ff;
|
||||
text-shadow: 0 0 12px rgba(0, 240, 255, 0.36);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .button-primary,
|
||||
:root[data-theme="cyberpunk"] .button.is-active {
|
||||
border-color: #fff200;
|
||||
background: #fff200;
|
||||
color: #08070d;
|
||||
box-shadow: 4px 4px 0 rgba(255, 42, 109, 0.7), 0 0 18px rgba(255, 242, 0, 0.3);
|
||||
clip-path: polygon(0 0, calc(100% - 0.7rem) 0, 100% 0.7rem, 100% 100%, 0.7rem 100%, 0 calc(100% - 0.7rem));
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .button-primary:hover,
|
||||
:root[data-theme="cyberpunk"] .button.is-active:hover {
|
||||
background: #00f0ff;
|
||||
border-color: #00f0ff;
|
||||
color: #08070d;
|
||||
box-shadow: 4px 4px 0 rgba(255, 42, 109, 0.78), 0 0 22px rgba(0, 240, 255, 0.42);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .button-outline,
|
||||
:root[data-theme="cyberpunk"] .button-ghost {
|
||||
border-color: rgba(0, 240, 255, 0.28);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .button-outline:hover,
|
||||
:root[data-theme="cyberpunk"] .button-ghost:hover {
|
||||
border-color: rgba(255, 242, 0, 0.46);
|
||||
background: rgba(255, 242, 0, 0.1);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] input,
|
||||
:root[data-theme="cyberpunk"] select,
|
||||
:root[data-theme="cyberpunk"] textarea {
|
||||
background: rgba(8, 7, 13, 0.92);
|
||||
border-color: rgba(0, 240, 255, 0.34);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] input:focus,
|
||||
:root[data-theme="cyberpunk"] select:focus,
|
||||
:root[data-theme="cyberpunk"] textarea:focus {
|
||||
border-color: #fff200;
|
||||
box-shadow: 0 0 0 3px rgba(255, 242, 0, 0.16), 0 0 22px rgba(0, 240, 255, 0.18);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .badge {
|
||||
border: 1px solid rgba(0, 240, 255, 0.22);
|
||||
background: rgba(0, 240, 255, 0.08);
|
||||
color: #9bfaff;
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .badge-active,
|
||||
:root[data-theme="cyberpunk"] .storage-detail-test.is-ok > span:last-child {
|
||||
color: #00ff9f;
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .badge-disabled,
|
||||
:root[data-theme="cyberpunk"] .storage-detail-test.is-err > span:last-child,
|
||||
:root[data-theme="cyberpunk"] .form-error {
|
||||
color: #ff2a6d;
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .drop-zone {
|
||||
border-color: rgba(255, 242, 0, 0.34);
|
||||
background:
|
||||
linear-gradient(145deg, rgba(255, 242, 0, 0.08), transparent 38%),
|
||||
rgba(8, 7, 13, 0.76);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] .drop-zone:hover,
|
||||
:root[data-theme="cyberpunk"] .drop-zone.is-dragging {
|
||||
border-color: #00f0ff;
|
||||
background:
|
||||
linear-gradient(145deg, rgba(0, 240, 255, 0.14), transparent 42%),
|
||||
rgba(8, 7, 13, 0.82);
|
||||
}
|
||||
|
||||
:root[data-theme="cyberpunk"] ::selection {
|
||||
background: #ff2a6d;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
:root[data-theme="cyberpunk"] .brand-mark,
|
||||
:root[data-theme="cyberpunk"] h1 {
|
||||
animation: cyberpunk-pulse 4s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes cyberpunk-pulse {
|
||||
0%, 100% {
|
||||
filter: none;
|
||||
}
|
||||
50% {
|
||||
filter: drop-shadow(0 0 0.45rem rgba(0, 240, 255, 0.28));
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,14 @@
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.upload-options .form-footer .upload-new-button {
|
||||
margin-top: -0.25rem;
|
||||
}
|
||||
|
||||
.upload-options .form-footer .upload-new-button[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.hero-copy {
|
||||
text-align: center;
|
||||
}
|
||||
@@ -335,10 +343,13 @@ button {
|
||||
.file-progress-side {
|
||||
width: min(10rem, 32vw);
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 0.35rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.file-progress-percent {
|
||||
grid-column: 1 / -1;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.75rem;
|
||||
text-align: right;
|
||||
@@ -349,6 +360,81 @@ button {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.upload-file-remove {
|
||||
width: 1.65rem;
|
||||
height: 1.65rem;
|
||||
min-height: 1.65rem;
|
||||
padding: 0;
|
||||
border-color: var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--muted-foreground);
|
||||
background: var(--surface-1);
|
||||
font-size: 1rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.upload-file-remove:hover {
|
||||
color: var(--foreground);
|
||||
border-color: var(--primary);
|
||||
background: var(--surface-1-hover);
|
||||
}
|
||||
|
||||
.upload-file-waiting {
|
||||
border-color: color-mix(in srgb, var(--primary) 42%, var(--border));
|
||||
background: color-mix(in srgb, var(--primary) 8%, var(--background));
|
||||
}
|
||||
|
||||
.upload-file-complete .file-progress span {
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
.upload-file-state {
|
||||
grid-column: 1 / -1;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.72rem;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.upload-recovery-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 80;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 1rem;
|
||||
background: color-mix(in srgb, var(--background) 72%, transparent);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.upload-recovery-modal {
|
||||
width: min(34rem, 100%);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
.upload-recovery-modal h2 {
|
||||
margin: 0 0 0.65rem;
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
|
||||
.upload-recovery-modal p {
|
||||
margin: 0;
|
||||
color: var(--muted-foreground);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.upload-recovery-actions {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.7rem;
|
||||
margin-top: 1.25rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.upload-recovery-actions {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.result-item small,
|
||||
.download-item small,
|
||||
.result-item code,
|
||||
|
||||
@@ -46,35 +46,23 @@
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.view-toolbar {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.button.is-active {
|
||||
background: var(--primary);
|
||||
color: var(--primary-foreground);
|
||||
}
|
||||
|
||||
.file-browser {
|
||||
transition: opacity 160ms ease;
|
||||
}
|
||||
|
||||
.file-card {
|
||||
position: relative;
|
||||
.upload-processing-alert {
|
||||
margin: 1rem 0;
|
||||
padding: .85rem 1rem;
|
||||
border: 1px solid color-mix(in srgb, var(--primary) 45%, transparent);
|
||||
border-radius: var(--radius);
|
||||
background: color-mix(in srgb, var(--primary) 12%, transparent);
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.thumb-link {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
flex: 0 0 4.75rem;
|
||||
width: 4.75rem;
|
||||
aspect-ratio: 16 / 10;
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: calc(var(--radius) - 0.125rem);
|
||||
border-radius: calc(var(--radius) - 0.2rem);
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
@@ -85,58 +73,619 @@
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.button.is-active {
|
||||
background: var(--primary);
|
||||
color: var(--primary-foreground);
|
||||
}
|
||||
|
||||
.file-browser-window {
|
||||
overflow: hidden;
|
||||
margin-top: 1.25rem;
|
||||
border: 1px solid color-mix(in srgb, var(--border) 78%, var(--primary));
|
||||
border-radius: var(--radius);
|
||||
background:
|
||||
linear-gradient(180deg, color-mix(in srgb, var(--card) 94%, transparent), color-mix(in srgb, var(--background) 92%, transparent));
|
||||
box-shadow: 0 18px 54px rgba(0, 0, 0, 0.24);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.file-browser-titlebar {
|
||||
min-height: 3rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.75rem 0.9rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--muted) 62%, transparent);
|
||||
}
|
||||
|
||||
.file-browser-titlebar > div:first-child {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.file-browser-titlebar strong {
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.file-browser-titlebar span {
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.78rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.file-browser-window-actions {
|
||||
display: inline-flex;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.file-browser-window-actions span {
|
||||
width: 0.72rem;
|
||||
height: 0.72rem;
|
||||
border: 1px solid color-mix(in srgb, var(--border) 75%, var(--foreground));
|
||||
border-radius: 999px;
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.file-browser-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
padding: 0.65rem 0.75rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--card) 74%, transparent);
|
||||
}
|
||||
|
||||
.view-toolbar {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.view-toolbar .button,
|
||||
.file-browser-toolbar > .button {
|
||||
min-height: 2rem;
|
||||
padding: 0.35rem 0.65rem;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.view-toolbar .icon-button {
|
||||
width: 2.25rem;
|
||||
padding-inline: 0;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.view-toolbar svg {
|
||||
width: 0.95rem;
|
||||
height: 0.95rem;
|
||||
}
|
||||
|
||||
.file-browser-head {
|
||||
display: grid;
|
||||
grid-template-columns: 3rem minmax(0, 1fr) minmax(8rem, 0.38fr) minmax(5rem, 0.18fr) minmax(8rem, 0.32fr);
|
||||
gap: 0.75rem;
|
||||
padding: 0.42rem 1rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--muted-foreground);
|
||||
background: color-mix(in srgb, var(--background) 78%, transparent);
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.file-browser-head span:first-child {
|
||||
grid-column: 2;
|
||||
}
|
||||
|
||||
.file-browser {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
padding: 0.35rem;
|
||||
transition: opacity 160ms ease;
|
||||
}
|
||||
|
||||
.file-browser .download-item {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
border-radius: calc(var(--radius) - 0.25rem);
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
padding: 0;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.file-browser .download-item:hover {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.file-card {
|
||||
position: relative;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.file-card.is-processing {
|
||||
opacity: .62;
|
||||
filter: grayscale(.25);
|
||||
}
|
||||
|
||||
.file-card.is-processing .file-open {
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.file-reaction-dock {
|
||||
position: static;
|
||||
z-index: 2;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
gap: 0.35rem;
|
||||
pointer-events: none;
|
||||
padding-right: 0.65rem;
|
||||
}
|
||||
|
||||
.file-reactions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
min-width: 0;
|
||||
gap: 0.25rem;
|
||||
flex-wrap: nowrap;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.reaction-pill {
|
||||
appearance: none;
|
||||
flex: 0 0 auto;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
min-height: 1.6rem;
|
||||
padding: 0.16rem 0.38rem;
|
||||
border: 1px solid color-mix(in srgb, var(--border) 84%, var(--primary));
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--card) 88%, #000);
|
||||
color: var(--foreground);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.24);
|
||||
pointer-events: auto;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.reaction-pill.is-hidden-summary {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.reaction-pill img {
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.reaction-more {
|
||||
appearance: none;
|
||||
flex: 0 0 auto;
|
||||
min-height: 1.6rem;
|
||||
padding: 0.16rem 0.45rem;
|
||||
border: 1px solid color-mix(in srgb, var(--border) 84%, var(--primary));
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--card) 88%, #000);
|
||||
color: var(--foreground);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 800;
|
||||
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.24);
|
||||
pointer-events: auto;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.reaction-pill:hover,
|
||||
.reaction-pill:focus-visible,
|
||||
.reaction-more:hover,
|
||||
.reaction-more:focus-visible {
|
||||
border-color: var(--primary);
|
||||
background: var(--primary);
|
||||
color: var(--primary-foreground);
|
||||
}
|
||||
|
||||
.reaction-button {
|
||||
width: 2.1rem;
|
||||
height: 2.1rem;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--card) 92%, #000);
|
||||
color: var(--foreground);
|
||||
opacity: 0;
|
||||
transform: translateY(0.3rem) scale(0.94);
|
||||
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.32);
|
||||
transition: opacity 150ms ease, transform 150ms ease, border-color 150ms ease, background 150ms ease;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.reaction-button svg {
|
||||
width: 1.15rem;
|
||||
height: 1.15rem;
|
||||
fill: none;
|
||||
stroke: currentColor;
|
||||
stroke-width: 1.9;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
.file-card:hover .reaction-button,
|
||||
.file-card:focus-within .reaction-button,
|
||||
.reaction-button:focus-visible {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
|
||||
.reaction-button:hover,
|
||||
.reaction-button:focus-visible {
|
||||
border-color: var(--primary);
|
||||
background: var(--primary);
|
||||
color: var(--primary-foreground);
|
||||
}
|
||||
|
||||
.reaction-picker {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 70;
|
||||
width: min(21rem, calc(100vw - 1rem));
|
||||
}
|
||||
|
||||
html.reaction-picker-open,
|
||||
html.reaction-picker-open body {
|
||||
overflow: hidden;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.reaction-picker[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.reaction-picker.is-mobile {
|
||||
inset: 0;
|
||||
width: auto;
|
||||
height: 100dvh;
|
||||
display: grid;
|
||||
place-items: end center;
|
||||
overflow: hidden;
|
||||
padding: 0.75rem 0.75rem max(1.5rem, env(safe-area-inset-bottom));
|
||||
background: rgba(0, 0, 0, 0.54);
|
||||
}
|
||||
|
||||
.reaction-picker-panel {
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: color-mix(in srgb, var(--card) 97%, #000);
|
||||
box-shadow: 0 26px 70px rgba(0, 0, 0, 0.52);
|
||||
}
|
||||
|
||||
.reaction-picker.is-mobile .reaction-picker-panel {
|
||||
width: min(100%, 34rem);
|
||||
height: 75dvh;
|
||||
max-height: 75dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.reaction-picker-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
padding: 0.7rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.reaction-picker-close {
|
||||
min-height: 2rem;
|
||||
padding: 0.3rem 0.55rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.reaction-existing {
|
||||
padding: 0.55rem 0.7rem 0;
|
||||
}
|
||||
|
||||
.reaction-existing small,
|
||||
.reaction-readonly-note {
|
||||
display: block;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.74rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.reaction-existing-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
margin-top: 0.4rem;
|
||||
}
|
||||
|
||||
.reaction-readonly-note {
|
||||
margin: 0;
|
||||
padding: 0.55rem 0.7rem 0.7rem;
|
||||
}
|
||||
|
||||
.reaction-picker-tabs {
|
||||
display: flex;
|
||||
gap: 0.35rem;
|
||||
overflow-x: auto;
|
||||
padding: 0.55rem 0.7rem 0;
|
||||
}
|
||||
|
||||
.reaction-tab {
|
||||
flex: 0 0 auto;
|
||||
min-height: 1.8rem;
|
||||
padding: 0.25rem 0.55rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--muted);
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.reaction-tab.is-active {
|
||||
border-color: var(--primary);
|
||||
background: var(--primary);
|
||||
color: var(--primary-foreground);
|
||||
}
|
||||
|
||||
.reaction-search {
|
||||
display: block;
|
||||
padding: 0.55rem 0.7rem;
|
||||
}
|
||||
|
||||
.reaction-search input {
|
||||
width: 100%;
|
||||
min-height: 2.15rem;
|
||||
padding: 0.35rem 0.55rem;
|
||||
}
|
||||
|
||||
.reaction-grid-wrap {
|
||||
max-height: 18rem;
|
||||
overflow: auto;
|
||||
padding: 0 0.7rem 0.7rem;
|
||||
}
|
||||
|
||||
.reaction-picker.is-mobile .reaction-grid-wrap {
|
||||
max-height: none;
|
||||
flex: 1;
|
||||
overscroll-behavior: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.reaction-grid {
|
||||
display: none;
|
||||
grid-template-columns: repeat(8, minmax(0, 1fr));
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.reaction-grid.is-active {
|
||||
display: grid;
|
||||
}
|
||||
|
||||
.reaction-picker.is-mobile .reaction-grid {
|
||||
grid-template-columns: repeat(6, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.reaction-emoji {
|
||||
aspect-ratio: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-width: 0;
|
||||
padding: 0.18rem;
|
||||
border: 1px solid transparent;
|
||||
border-radius: calc(var(--radius) - 0.25rem);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.reaction-emoji:hover,
|
||||
.reaction-emoji:focus-visible {
|
||||
border-color: var(--border);
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.reaction-emoji[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.reaction-emoji img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
/* A file row behaves like an entry in a desktop file explorer: a small
|
||||
thumbnail/icon followed by the name and metadata. The whole row is the click
|
||||
target (raw view of the file). */
|
||||
.file-open {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
display: grid;
|
||||
grid-template-columns: 3rem minmax(0, 1fr) minmax(8rem, 0.38fr) minmax(5rem, 0.18fr);
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
color: var(--foreground);
|
||||
text-decoration: none;
|
||||
padding: 0.55rem 0.65rem;
|
||||
border-radius: calc(var(--radius) - 0.25rem);
|
||||
}
|
||||
|
||||
.file-open:hover,
|
||||
.file-open:focus-visible {
|
||||
background: var(--surface-1-hover);
|
||||
}
|
||||
|
||||
.file-media {
|
||||
flex: 0 0 3rem;
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: calc(var(--radius) - 0.125rem);
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.file-thumb {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.file-icon {
|
||||
width: 2.1rem;
|
||||
height: 2.1rem;
|
||||
display: block;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
/* Retro (Win98) icons are tiny pixel art — keep them crisp and swap them in
|
||||
only when the retro theme is active. */
|
||||
.file-icon-retro {
|
||||
display: none;
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
|
||||
[data-theme="retro"] .file-icon-standard {
|
||||
display: none;
|
||||
}
|
||||
|
||||
[data-theme="retro"] .file-icon-retro {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.file-main {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
flex: 1;
|
||||
color: var(--foreground);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.file-actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
.file-name {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.preview-action [hidden] {
|
||||
display: none;
|
||||
.file-main small {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.file-type,
|
||||
.file-size {
|
||||
overflow: hidden;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.78rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.file-size {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs {
|
||||
grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem;
|
||||
grid-template-columns: repeat(auto-fill, minmax(8.75rem, 1fr));
|
||||
}
|
||||
|
||||
.file-browser-window.is-icon-view .file-browser-head {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .file-card {
|
||||
display: grid;
|
||||
min-height: 13.75rem;
|
||||
min-width: 0;
|
||||
align-content: start;
|
||||
gap: 0.7rem;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.file-browser.is-list .file-card {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(8rem, 0.32fr);
|
||||
align-items: center;
|
||||
min-height: 4.25rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.file-browser.is-list .file-card:hover,
|
||||
.file-browser.is-list .file-card:focus-within {
|
||||
background: var(--surface-1-hover);
|
||||
}
|
||||
|
||||
.file-browser.is-list .file-card:hover .file-open,
|
||||
.file-browser.is-list .file-card:focus-within .file-open {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .file-open {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-rows: 6.75rem auto;
|
||||
gap: 1rem;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding: 0.65rem 0.65rem 3.05rem;
|
||||
text-align: center;
|
||||
justify-items: center;
|
||||
align-content: start;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .file-media {
|
||||
width: min(6.75rem, 76%);
|
||||
height: 6.75rem;
|
||||
flex-basis: auto;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .file-icon {
|
||||
width: 64%;
|
||||
height: 64%;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .file-main {
|
||||
width: 100%;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0.25rem;
|
||||
align-self: start;
|
||||
padding-top: 0.25rem;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .thumb-link {
|
||||
width: 100%;
|
||||
flex-basis: auto;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .file-actions {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.file-browser.images-only .file-card:not([data-kind="image"]) {
|
||||
.file-browser.is-thumbs .file-type,
|
||||
.file-browser.is-thumbs .file-size {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .file-reaction-dock {
|
||||
position: absolute;
|
||||
right: 0.6rem;
|
||||
bottom: 0.65rem;
|
||||
max-width: calc(100% - 1.2rem);
|
||||
padding-right: 0;
|
||||
}
|
||||
|
||||
.context-menu {
|
||||
position: fixed;
|
||||
z-index: 30;
|
||||
|
||||
@@ -36,6 +36,22 @@
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.docs-card h3 {
|
||||
margin: 1.35rem 0 0;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 650;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
/* Highlights where the API token goes in the ShareX config snippet. */
|
||||
.sxcu-highlight {
|
||||
background: #fde047;
|
||||
color: #1a1a1a;
|
||||
font-weight: 700;
|
||||
padding: 0 0.2rem;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.docs-card p {
|
||||
margin: 0.65rem 0 0;
|
||||
color: var(--muted-foreground);
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
.admin-header,
|
||||
.table-header {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.admin-header > *,
|
||||
.table-header > *,
|
||||
.admin-grid-two > *,
|
||||
.logs-filter-card > * {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.kicker {
|
||||
margin: 0 0 0.4rem;
|
||||
color: var(--muted-foreground);
|
||||
@@ -54,7 +62,8 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.user-edit-metrics {
|
||||
.user-edit-metrics,
|
||||
.metric-grid-4 {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
@@ -72,12 +81,15 @@
|
||||
}
|
||||
|
||||
.admin-table-wrap {
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
margin-top: 1rem;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.admin-table {
|
||||
width: 100%;
|
||||
min-width: 46rem;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
@@ -95,6 +107,204 @@
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.sort-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
color: var(--muted-foreground);
|
||||
font-weight: 650;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.sort-link:hover,
|
||||
.sort-link.is-sorted {
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.sort-arrow {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.pagination {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.pagination-summary {
|
||||
margin: 0.6rem 0 0;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.pagination-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.pagination-bar .pagination {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.per-page-control {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
margin: 0;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.per-page-control select {
|
||||
width: auto;
|
||||
min-width: 4.5rem;
|
||||
min-height: 2rem;
|
||||
padding: 0.2rem 0.5rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.button.is-disabled {
|
||||
pointer-events: none;
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
/* Overview charts */
|
||||
.admin-charts {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr;
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.chart-card {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.chart-card h2 {
|
||||
margin: 0;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.chart-card .muted-copy {
|
||||
margin: 0.3rem 0 0;
|
||||
}
|
||||
|
||||
.bar-chart {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(14, minmax(0, 1fr));
|
||||
align-items: end;
|
||||
gap: 0.4rem;
|
||||
min-height: 13rem;
|
||||
margin-top: 1.25rem;
|
||||
padding-top: 0.5rem;
|
||||
}
|
||||
|
||||
.bar-chart-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
align-items: stretch;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.bar-chart-track {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
flex: 1 1 auto;
|
||||
width: 100%;
|
||||
max-width: 1.8rem;
|
||||
height: 150px;
|
||||
margin: 0 auto;
|
||||
border-bottom: 2px solid color-mix(in srgb, var(--primary, #8b5cf6) 75%, transparent);
|
||||
border-radius: 0.45rem 0.45rem 0 0;
|
||||
background: linear-gradient(180deg, transparent, color-mix(in srgb, var(--border) 55%, transparent));
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bar-chart-bar {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
border-radius: 6px 6px 0 0;
|
||||
background: linear-gradient(180deg, var(--primary-hover, #7c3aed), var(--primary, #8b5cf6));
|
||||
box-shadow: 0 0 18px color-mix(in srgb, var(--primary, #8b5cf6) 35%, transparent);
|
||||
}
|
||||
|
||||
.bar-chart-value {
|
||||
min-height: 1rem;
|
||||
overflow: hidden;
|
||||
color: var(--foreground);
|
||||
font-size: 0.72rem;
|
||||
font-weight: 650;
|
||||
line-height: 1;
|
||||
text-align: center;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bar-chart-label {
|
||||
overflow: hidden;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.66rem;
|
||||
text-align: center;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.stat-bars {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
margin-top: 1.25rem;
|
||||
}
|
||||
|
||||
.stat-bar span {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.stat-bar span strong {
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.stat-bar-track {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 0.35rem;
|
||||
height: 0.55rem;
|
||||
border-radius: 999px;
|
||||
background: var(--border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.stat-bar-fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
border-radius: 999px;
|
||||
background: var(--primary, #8b5cf6);
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.admin-charts {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 620px) {
|
||||
.metric-grid-4 {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
.table-actions {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
@@ -204,6 +414,7 @@
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 0.4rem;
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
|
||||
.storage-card-header {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
@@ -56,6 +57,10 @@
|
||||
|
||||
.storage-card-name {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 650;
|
||||
color: var(--foreground);
|
||||
@@ -82,9 +87,15 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.storage-card-actions form {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* View-mode summary */
|
||||
.storage-card-summary {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
gap: 0 1.75rem;
|
||||
padding: 0.65rem 1.1rem 0.9rem;
|
||||
@@ -96,6 +107,7 @@
|
||||
flex-direction: column;
|
||||
gap: 0.15rem;
|
||||
min-width: 8rem;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.storage-detail > span:first-child,
|
||||
@@ -137,6 +149,14 @@
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
.storage-card-fields > *,
|
||||
.storage-ops-grid > *,
|
||||
.storage-result-row,
|
||||
.storage-result-row summary > *,
|
||||
.storage-result-detail > * {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.storage-card-fields label {
|
||||
display: grid;
|
||||
gap: 0.28rem;
|
||||
|
||||
@@ -1,12 +1,34 @@
|
||||
@media (max-width: 720px) {
|
||||
.nav-links {
|
||||
display: inline-flex;
|
||||
.nav {
|
||||
width: min(72rem, calc(100% - 1rem));
|
||||
min-height: auto;
|
||||
padding: 0.55rem 0;
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.brand {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: stretch;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.nav-links .button {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
padding-inline: 0.55rem;
|
||||
}
|
||||
|
||||
.upload-view,
|
||||
.download-view {
|
||||
width: min(100%, calc(100% - 1rem));
|
||||
min-height: auto;
|
||||
padding: 2rem 0;
|
||||
}
|
||||
@@ -37,6 +59,23 @@
|
||||
|
||||
.app-sidebar {
|
||||
position: static;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.sidebar-nav {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.sidebar-link {
|
||||
justify-content: flex-start;
|
||||
padding-inline: 0.65rem;
|
||||
}
|
||||
|
||||
.sidebar-logout .button {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.endpoint-list div {
|
||||
@@ -56,6 +95,41 @@
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.file-browser-toolbar {
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.file-browser-toolbar,
|
||||
.file-browser-toolbar .view-toolbar {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.file-browser-toolbar .view-toolbar .button,
|
||||
.file-browser-toolbar > .button {
|
||||
flex: 1 1 auto;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.file-browser-toolbar .view-toolbar .icon-button {
|
||||
flex: 0 0 2.5rem;
|
||||
}
|
||||
|
||||
.file-browser-head {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.file-open {
|
||||
grid-template-columns: 3rem minmax(0, 1fr) auto;
|
||||
}
|
||||
|
||||
.file-type {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.file-browser.is-list .file-card {
|
||||
grid-template-columns: minmax(0, 1fr) minmax(7rem, auto);
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.65rem;
|
||||
}
|
||||
@@ -86,9 +160,59 @@
|
||||
.new-collection-body {
|
||||
position: static;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
margin-top: 0.5rem;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.inline-controls {
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.inline-controls label,
|
||||
.inline-controls input,
|
||||
.inline-controls select,
|
||||
.compact-input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.copy-field,
|
||||
.token-reveal-row,
|
||||
.storage-card-edit-bar {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.copy-field .button,
|
||||
.token-reveal-row .button,
|
||||
.storage-card-edit-bar .button {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.storage-card-header,
|
||||
.storage-card-actions {
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.storage-card-header {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.storage-card-actions,
|
||||
.storage-card-actions form,
|
||||
.storage-card-actions .button,
|
||||
.storage-card-actions button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.storage-card-summary {
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.storage-detail {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
@@ -96,3 +220,119 @@
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.app-shell {
|
||||
width: min(100%, calc(100% - 1rem));
|
||||
padding: 1rem 0;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.card-content {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.metric-grid,
|
||||
.user-edit-metrics {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.storage-type-grid,
|
||||
.storage-ops-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.result-item,
|
||||
.download-item {
|
||||
align-items: stretch;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.file-browser-titlebar {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.file-browser-titlebar > div:first-child {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0.1rem;
|
||||
}
|
||||
|
||||
.file-browser {
|
||||
padding: 0.25rem;
|
||||
}
|
||||
|
||||
.file-open {
|
||||
grid-template-columns: 2.65rem minmax(0, 1fr);
|
||||
gap: 0.55rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.file-media {
|
||||
width: 2.65rem;
|
||||
height: 2.65rem;
|
||||
}
|
||||
|
||||
.file-size {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.file-browser.is-list .file-card {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.file-browser.is-list .file-reaction-dock {
|
||||
justify-content: flex-end;
|
||||
padding: 0 0.5rem 0.5rem;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.file-browser.is-thumbs .file-open {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.file-actions,
|
||||
.file-browser.is-thumbs .file-actions {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.file-reaction-dock {
|
||||
right: 0.5rem;
|
||||
bottom: 0.45rem;
|
||||
}
|
||||
|
||||
.reaction-button {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.file-progress-side {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.site-footer {
|
||||
width: min(100%, calc(100% - 1rem));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 380px) {
|
||||
.sidebar-nav {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.badge-row .badge {
|
||||
flex: 1 1 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.nav-links .button {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
112
backend/static/file-icons/icon-map.json
Normal file
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"_comment": "Maps a file's type (resolved from its extension / content type) to a file-type icon. 'standard' icons live in file-icons/standard, 'retro' (Win98) icons in file-icons/retro. The server reads this at startup and picks the icon per file; thumbnails always win over icons when present.",
|
||||
"default": {
|
||||
"mime": "application/octet-stream",
|
||||
"standard": "txt-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_152-2.png"
|
||||
},
|
||||
"types": [
|
||||
{
|
||||
"mime": "image/*",
|
||||
"standard": "image-document-svgrepo-com.svg",
|
||||
"retro": "shimgvw.dll_14_1-2.png",
|
||||
"extensions": ["png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "ico", "tif", "tiff", "heic", "heif", "avif", "jfif"]
|
||||
},
|
||||
{
|
||||
"mime": "image/vnd.adobe.photoshop",
|
||||
"standard": "psd-document-svgrepo-com.svg",
|
||||
"retro": "shimgvw.dll_14_1-2.png",
|
||||
"extensions": ["psd"]
|
||||
},
|
||||
{
|
||||
"mime": "audio/*",
|
||||
"standard": "audio-document-svgrepo-com.svg",
|
||||
"retro": "wmploc.dll_14_610-2.png",
|
||||
"extensions": ["mp3", "wav", "flac", "aac", "ogg", "oga", "m4a", "wma", "opus", "aiff", "aif", "mid", "midi"]
|
||||
},
|
||||
{
|
||||
"mime": "video/mp4",
|
||||
"standard": "mp4-document-svgrepo-com.svg",
|
||||
"retro": "wmploc.dll_14_504-2.png",
|
||||
"extensions": ["mp4", "m4v"]
|
||||
},
|
||||
{
|
||||
"mime": "video/*",
|
||||
"standard": "video-document-svgrepo-com.svg",
|
||||
"retro": "wmploc.dll_14_504-2.png",
|
||||
"extensions": ["mkv", "mov", "avi", "webm", "wmv", "flv", "mpg", "mpeg", "3gp", "ogv", "ts", "m2ts"]
|
||||
},
|
||||
{
|
||||
"mime": "application/zip",
|
||||
"standard": "zip-document-svgrepo-com.svg",
|
||||
"retro": "zipfldr.dll_14_101-2.png",
|
||||
"extensions": ["zip", "rar", "7z", "gz", "tar", "bz2", "xz", "tgz", "zst", "lz", "lzma", "cab", "iso"]
|
||||
},
|
||||
{
|
||||
"mime": "application/pdf",
|
||||
"standard": "pdf-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_152-2.png",
|
||||
"extensions": ["pdf"]
|
||||
},
|
||||
{
|
||||
"mime": "text/html",
|
||||
"standard": "html-document-svgrepo-com.svg",
|
||||
"retro": "mshtml.dll_14_2660-2.png",
|
||||
"extensions": ["html", "htm", "xhtml", "mhtml"]
|
||||
},
|
||||
{
|
||||
"mime": "application/x-shockwave-flash",
|
||||
"standard": "flash-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_152-2.png",
|
||||
"extensions": ["swf", "fla"]
|
||||
},
|
||||
{
|
||||
"mime": "application/vnd.ms-excel",
|
||||
"standard": "excel-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_151-2.png",
|
||||
"extensions": ["xls", "xlsx", "xlsm", "ods"]
|
||||
},
|
||||
{
|
||||
"mime": "text/csv",
|
||||
"standard": "csv-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_151-2.png",
|
||||
"extensions": ["csv", "tsv"]
|
||||
},
|
||||
{
|
||||
"mime": "application/msword",
|
||||
"standard": "word-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_2-0.png",
|
||||
"extensions": ["doc", "docx", "odt"]
|
||||
},
|
||||
{
|
||||
"mime": "application/rtf",
|
||||
"standard": "rtf-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_2-0.png",
|
||||
"extensions": ["rtf"]
|
||||
},
|
||||
{
|
||||
"mime": "application/vnd.apple.pages",
|
||||
"standard": "pages-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_2-0.png",
|
||||
"extensions": ["pages"]
|
||||
},
|
||||
{
|
||||
"mime": "application/vnd.visio",
|
||||
"standard": "visio-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_152-2.png",
|
||||
"extensions": ["vsd", "vsdx"]
|
||||
},
|
||||
{
|
||||
"mime": "application/x-msdownload",
|
||||
"standard": "exe-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_3-0.png",
|
||||
"extensions": ["exe", "msi", "bat", "cmd", "com", "app", "dmg", "apk", "deb", "rpm", "appimage"]
|
||||
},
|
||||
{
|
||||
"mime": "text/plain",
|
||||
"standard": "txt-document-svgrepo-com.svg",
|
||||
"retro": "shell32.dll_14_151-2.png",
|
||||
"extensions": ["txt", "text", "log", "md", "markdown", "ini", "cfg", "conf", "json", "xml", "yaml", "yml", "toml", "js", "ts", "jsx", "tsx", "go", "py", "rb", "php", "java", "c", "h", "cpp", "cc", "cs", "rs", "sh", "bash", "css", "scss", "sql"]
|
||||
}
|
||||
]
|
||||
}
|
||||
BIN
backend/static/file-icons/retro/mshtml.dll_14_2660-2.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
backend/static/file-icons/retro/shell32.dll_14_151-2.png
Normal file
|
After Width: | Height: | Size: 386 B |
BIN
backend/static/file-icons/retro/shell32.dll_14_152-2.png
Normal file
|
After Width: | Height: | Size: 2.1 KiB |
BIN
backend/static/file-icons/retro/shell32.dll_14_2-0.png
Normal file
|
After Width: | Height: | Size: 553 B |
BIN
backend/static/file-icons/retro/shell32.dll_14_3-0.png
Normal file
|
After Width: | Height: | Size: 378 B |
BIN
backend/static/file-icons/retro/shimgvw.dll_14_1-2.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
backend/static/file-icons/retro/wmploc.dll_14_504-2.png
Normal file
|
After Width: | Height: | Size: 594 B |
BIN
backend/static/file-icons/retro/wmploc.dll_14_610-2.png
Normal file
|
After Width: | Height: | Size: 621 B |
BIN
backend/static/file-icons/retro/zipfldr.dll_14_101-2.png
Normal file
|
After Width: | Height: | Size: 598 B |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M5.151.012c-2.802 0-5.073 2.272-5.073 5.073v53.842c0 2.802 2.272 5.073 5.073 5.073h45.774c2.803 0 5.075-2.271 5.075-5.073v-38.606l-18.903-20.309h-31.946z" fill="#379FD3"/>
|
||||
|
||||
<path d="M56 20.357v1h-12.8s-6.312-1.26-6.128-6.707c0 0 .208 5.707 6.003 5.707h12.925z" fill="#2987C8"/>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.106 0c-2.802 0-5.073 2.272-5.073 5.074v53.841c0 2.803 2.271 5.074 5.073 5.074h45.774c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.903-20.31h-31.945z" fill-rule="evenodd" clip-rule="evenodd" fill="#45B058"/>
|
||||
|
||||
<path d="M20.306 43.197c.126.144.198.324.198.522 0 .378-.306.72-.703.72-.18 0-.378-.072-.504-.234-.702-.846-1.891-1.387-3.007-1.387-2.629 0-4.627 2.017-4.627 4.88 0 2.845 1.999 4.879 4.627 4.879 1.134 0 2.25-.486 3.007-1.369.125-.144.324-.233.504-.233.415 0 .703.359.703.738 0 .18-.072.36-.198.504-.937.972-2.215 1.693-4.015 1.693-3.457 0-6.176-2.521-6.176-6.212s2.719-6.212 6.176-6.212c1.8.001 3.096.721 4.015 1.711zm6.802 10.714c-1.782 0-3.187-.594-4.213-1.495-.162-.144-.234-.342-.234-.54 0-.361.27-.757.702-.757.144 0 .306.036.432.144.828.739 1.98 1.314 3.367 1.314 2.143 0 2.827-1.152 2.827-2.071 0-3.097-7.112-1.386-7.112-5.672 0-1.98 1.764-3.331 4.123-3.331 1.548 0 2.881.467 3.853 1.278.162.144.252.342.252.54 0 .36-.306.72-.703.72-.144 0-.306-.054-.432-.162-.882-.72-1.98-1.044-3.079-1.044-1.44 0-2.467.774-2.467 1.909 0 2.701 7.112 1.152 7.112 5.636.001 1.748-1.187 3.531-4.428 3.531zm16.994-11.254l-4.159 10.335c-.198.486-.685.81-1.188.81h-.036c-.522 0-1.008-.324-1.207-.81l-4.142-10.335c-.036-.09-.054-.18-.054-.288 0-.36.323-.793.81-.793.306 0 .594.18.72.486l3.889 9.992 3.889-9.992c.108-.288.396-.486.72-.486.468 0 .81.378.81.793.001.09-.017.198-.052.288z" fill="#ffffff"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
After Width: | Height: | Size: 1.9 KiB |
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg"><path d="M5.112.006c-2.802 0-5.073 2.273-5.073 5.074v53.841c0 2.803 2.271 5.074 5.073 5.074h45.774c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.902-20.31h-31.946z" fill-rule="evenodd" clip-rule="evenodd" fill="#45B058"/><path d="M19.429 53.938c-.216 0-.415-.09-.54-.27l-3.728-4.97-3.745 4.97c-.126.18-.324.27-.54.27-.396 0-.72-.306-.72-.72 0-.144.035-.306.144-.432l3.89-5.131-3.619-4.826c-.09-.126-.145-.27-.145-.414 0-.342.288-.72.721-.72.216 0 .432.108.576.288l3.438 4.628 3.438-4.646c.127-.18.324-.27.541-.27.378 0 .738.306.738.72 0 .144-.036.288-.127.414l-3.619 4.808 3.891 5.149c.09.126.125.27.125.414 0 .396-.324.738-.719.738zm9.989-.126h-5.455c-.595 0-1.081-.486-1.081-1.08v-10.317c0-.396.324-.72.774-.72.396 0 .721.324.721.72v10.065h5.041c.359 0 .648.288.648.648 0 .396-.289.684-.648.684zm6.982.216c-1.782 0-3.188-.594-4.213-1.495-.162-.144-.234-.342-.234-.54 0-.36.27-.756.702-.756.144 0 .306.036.433.144.828.738 1.98 1.314 3.367 1.314 2.143 0 2.826-1.152 2.826-2.071 0-3.097-7.111-1.386-7.111-5.672 0-1.98 1.764-3.331 4.123-3.331 1.548 0 2.881.468 3.853 1.278.162.144.253.342.253.54 0 .36-.307.72-.703.72-.145 0-.307-.054-.432-.162-.883-.72-1.98-1.044-3.079-1.044-1.44 0-2.467.774-2.467 1.909 0 2.701 7.112 1.152 7.112 5.636 0 1.748-1.188 3.53-4.43 3.53z" fill="#ffffff"/><path d="M55.953 20.352v1h-12.801s-6.312-1.26-6.127-6.707c0 0 .207 5.707 6.002 5.707h12.926z" fill-rule="evenodd" clip-rule="evenodd" fill="#349C42"/><path d="M37.049 0v14.561c0 1.656 1.104 5.791 6.104 5.791h12.801l-18.905-20.352z" opacity=".5" fill-rule="evenodd" clip-rule="evenodd" fill="#ffffff"/></svg>
|
||||
|
After Width: | Height: | Size: 1.8 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.112.025c-2.802 0-5.073 2.272-5.073 5.074v53.841c0 2.803 2.271 5.074 5.073 5.074h45.774c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.902-20.31h-31.946z" fill-rule="evenodd" clip-rule="evenodd" fill="#8199AF"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M55.961 20.377v1h-12.799s-6.312-1.26-6.129-6.708c0 0 .208 5.708 6.004 5.708h12.924z" fill="#617F9B"/>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.112.009c-2.802 0-5.073 2.273-5.073 5.074v53.841c0 2.803 2.271 5.074 5.073 5.074h45.775c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.904-20.31h-31.945z" fill-rule="evenodd" clip-rule="evenodd" fill="#E53C3C"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M55.961 20.346v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#DE2D2D"/>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.135.008c-2.803 0-5.074 2.272-5.074 5.074v53.84c0 2.803 2.271 5.074 5.074 5.074h45.775c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.903-20.309h-31.946z" fill-rule="evenodd" clip-rule="evenodd" fill="#F7622C"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M55.976 20.352v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#F54921"/>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M5.125.042c-2.801 0-5.072 2.273-5.072 5.074v53.841c0 2.803 2.271 5.073 5.072 5.073h45.775c2.801 0 5.074-2.271 5.074-5.073v-38.604l-18.904-20.311h-31.945z" fill="#49C9A7"/>
|
||||
|
||||
<path d="M55.977 20.352v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#37BB91"/>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M5.116.006c-2.801 0-5.072 2.272-5.072 5.074v53.841c0 2.803 2.271 5.074 5.072 5.074h45.775c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.903-20.31h-31.946z" fill="#9B64B2"/>
|
||||
|
||||
<path d="M55.977 20.352v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#824B9E"/>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.111-.006c-2.801 0-5.072 2.272-5.072 5.074v53.841c0 2.803 2.271 5.074 5.072 5.074h45.775c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.903-20.31h-31.946z" fill-rule="evenodd" clip-rule="evenodd" fill="#6A6AE2"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M55.976 20.352v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#4F4FDA"/>
|
||||
|
After Width: | Height: | Size: 1.9 KiB |
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg"
|
||||
width="800px" height="800px" viewBox="0 0 56 64" enable-background="new 0 0 56 64" xml:space="preserve">
|
||||
<g>
|
||||
<path fill="#8C181A" d="M5.1,0C2.3,0,0,2.3,0,5.1v53.8C0,61.7,2.3,64,5.1,64h45.8c2.8,0,5.1-2.3,5.1-5.1V20.3L37.1,0H5.1z"/>
|
||||
<path fill="#6B0D12" d="M56,20.4v1H43.2c0,0-6.3-1.3-6.1-6.7c0,0,0.2,5.7,6,5.7H56z"/>
|
||||
<path opacity="0.5" fill="#FFFFFF" enable-background="new " d="M37.1,0v14.6c0,1.7,1.1,5.8,6.1,5.8H56L37.1,0z"/>
|
||||
</g>
|
||||
<path fill="#FFFFFF" d="M14.9,49h-3.3v4.1c0,0.4-0.3,0.7-0.8,0.7c-0.4,0-0.7-0.3-0.7-0.7V42.9c0-0.6,0.5-1.1,1.1-1.1h3.7
|
||||
c2.4,0,3.8,1.7,3.8,3.6C18.7,47.4,17.3,49,14.9,49z M14.8,43.1h-3.2v4.6h3.2c1.4,0,2.4-0.9,2.4-2.3C17.2,44,16.2,43.1,14.8,43.1z
|
||||
M25.2,53.8h-3c-0.6,0-1.1-0.5-1.1-1.1v-9.8c0-0.6,0.5-1.1,1.1-1.1h3c3.7,0,6.2,2.6,6.2,6C31.4,51.2,29,53.8,25.2,53.8z M25.2,43.1
|
||||
h-2.6v9.3h2.6c2.9,0,4.6-2.1,4.6-4.7C29.9,45.2,28.2,43.1,25.2,43.1z M41.5,43.1h-5.8V47h5.7c0.4,0,0.6,0.3,0.6,0.7
|
||||
s-0.3,0.6-0.6,0.6h-5.7v4.8c0,0.4-0.3,0.7-0.8,0.7c-0.4,0-0.7-0.3-0.7-0.7V42.9c0-0.6,0.5-1.1,1.1-1.1h6.2c0.4,0,0.6,0.3,0.6,0.7
|
||||
C42.2,42.8,41.9,43.1,41.5,43.1z"/>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.112.051c-2.802 0-5.073 2.273-5.073 5.075v53.841c0 2.802 2.271 5.073 5.073 5.073h45.775c2.801 0 5.074-2.271 5.074-5.073v-38.606l-18.903-20.31h-31.946z" fill-rule="evenodd" clip-rule="evenodd" fill="#0C77C6"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M55.977 20.352v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#0959B7"/>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.113.006c-2.803 0-5.074 2.273-5.074 5.074v53.841c0 2.803 2.271 5.074 5.074 5.074h45.774c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.903-20.31h-31.945z" fill-rule="evenodd" clip-rule="evenodd" fill="#00A1EE"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M55.977 20.352v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#0089E9"/>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.151-.036c-2.803 0-5.074 2.272-5.074 5.074v53.841c0 2.803 2.271 5.074 5.074 5.074h45.774c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.902-20.31h-31.946z" fill-rule="evenodd" clip-rule="evenodd" fill="#F9CA06"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M56.008 20.316v1h-12.799s-6.312-1.26-6.129-6.708c0 0 .208 5.708 6.004 5.708h12.924z" fill="#F7BC04"/>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.15.011c-2.801 0-5.072 2.272-5.072 5.074v53.841c0 2.803 2.272 5.074 5.072 5.074h45.775c2.802 0 5.075-2.271 5.075-5.074v-38.606l-18.904-20.309h-31.946z" fill-rule="evenodd" clip-rule="evenodd" fill="#8E4C9E"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M55.977 20.352v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#713985"/>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.111.006c-2.801 0-5.072 2.272-5.072 5.074v53.841c0 2.803 2.271 5.074 5.072 5.074h45.775c2.801 0 5.074-2.271 5.074-5.074v-38.606l-18.903-20.309h-31.946z" fill-rule="evenodd" clip-rule="evenodd" fill="#496AB3"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M55.977 20.352v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#374FA0"/>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<g fill-rule="evenodd">
|
||||
|
||||
<path d="m5.11 0a5.07 5.07 0 0 0 -5.11 5v53.88a5.07 5.07 0 0 0 5.11 5.12h45.78a5.07 5.07 0 0 0 5.11-5.12v-38.6l-18.94-20.28z" fill="#107cad"/>
|
||||
|
||||
<path d="m56 20.35v1h-12.82s-6.31-1.26-6.13-6.71c0 0 .21 5.71 6 5.71z" fill="#084968"/>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="-4 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<path d="M5.113-.026c-2.803 0-5.074 2.272-5.074 5.074v53.841c0 2.803 2.271 5.074 5.074 5.074h45.773c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.901-20.31h-31.946z" fill-rule="evenodd" clip-rule="evenodd" fill="#8199AF"/>
|
||||
|
||||
<g fill-rule="evenodd" clip-rule="evenodd">
|
||||
|
||||
<path d="M55.977 20.352v1h-12.799s-6.312-1.26-6.129-6.707c0 0 .208 5.707 6.004 5.707h12.924z" fill="#617F9B"/>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -5,6 +5,17 @@
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
};
|
||||
|
||||
window.Warpbox.absoluteURL = function absoluteURL(url) {
|
||||
if (!url) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return new URL(url, window.location.origin).href;
|
||||
} catch (_) {
|
||||
return url;
|
||||
}
|
||||
};
|
||||
|
||||
window.Warpbox.writeClipboard = async function writeClipboard(text) {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
@@ -26,6 +37,9 @@
|
||||
if (!text || !button) {
|
||||
return;
|
||||
}
|
||||
if (typeof text === "string" && (text.startsWith("/") || /^https?:\/\//i.test(text))) {
|
||||
text = window.Warpbox.absoluteURL(text);
|
||||
}
|
||||
await window.Warpbox.writeClipboard(text);
|
||||
const previous = button.textContent;
|
||||
button.textContent = copiedLabel;
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
*/
|
||||
(function () {
|
||||
var STORAGE_KEY = "warpbox-theme";
|
||||
var THEMES = ["revamp", "classic", "retro"];
|
||||
var THEMES = ["revamp", "classic", "retro", "gruvbox", "cyberpunk"];
|
||||
|
||||
function stored() {
|
||||
try {
|
||||
|
||||
@@ -1,33 +1,50 @@
|
||||
(function () {
|
||||
const fileBrowser = document.querySelector("[data-file-browser]");
|
||||
const viewButtons = document.querySelectorAll("[data-view-button]");
|
||||
const previewImages = document.querySelector("[data-preview-images]");
|
||||
const previewActions = document.querySelectorAll("[data-preview-action]");
|
||||
const fileContextMenu = document.querySelector("[data-file-context-menu]");
|
||||
const fileBrowserWindow = document.querySelector("[data-file-browser-window]");
|
||||
|
||||
let ctrlCopyMode = false;
|
||||
let contextFile = null;
|
||||
const contextMenuCloseDistance = 80;
|
||||
const viewStorageKey = "warpbox.fileBrowser.view";
|
||||
|
||||
if (fileBrowser) {
|
||||
applySavedFileBrowserPreferences();
|
||||
|
||||
viewButtons.forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
const view = button.getAttribute("data-view-button");
|
||||
fileBrowser.classList.toggle("is-list", view === "list");
|
||||
fileBrowser.classList.toggle("is-thumbs", view === "thumbs");
|
||||
viewButtons.forEach((item) => item.classList.toggle("is-active", item === button));
|
||||
setFileBrowserView(view);
|
||||
savePreference(viewStorageKey, view);
|
||||
});
|
||||
});
|
||||
|
||||
if (previewImages) {
|
||||
previewImages.addEventListener("click", () => {
|
||||
fileBrowser.classList.toggle("images-only");
|
||||
previewImages.classList.toggle("is-active");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (fileBrowser && fileContextMenu) {
|
||||
document.body.appendChild(fileContextMenu);
|
||||
|
||||
fileBrowser.addEventListener("click", (event) => {
|
||||
if (!fileBrowser.classList.contains("is-list")) {
|
||||
return;
|
||||
}
|
||||
if (event.target.closest("a, button, input, select, textarea")) {
|
||||
return;
|
||||
}
|
||||
const card = event.target.closest("[data-file-context]");
|
||||
const link = card ? card.querySelector(".file-open") : null;
|
||||
if (!link) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
if (link.target === "_blank") {
|
||||
window.Warpbox.openInNewTab(link.href);
|
||||
return;
|
||||
}
|
||||
window.location.href = link.href;
|
||||
});
|
||||
|
||||
fileBrowser.addEventListener("contextmenu", (event) => {
|
||||
const card = event.target.closest("[data-file-context]");
|
||||
if (!card) {
|
||||
@@ -107,7 +124,7 @@
|
||||
}
|
||||
|
||||
async function copyPreviewLink(button) {
|
||||
await window.Warpbox.writeClipboard(button.href);
|
||||
await window.Warpbox.writeClipboard(window.Warpbox.absoluteURL(button.href));
|
||||
const label = button.querySelector("[data-preview-label]");
|
||||
if (!label) {
|
||||
return;
|
||||
@@ -147,11 +164,11 @@
|
||||
return true;
|
||||
}
|
||||
if (action === "copy-preview") {
|
||||
await window.Warpbox.writeClipboard(file.previewURL);
|
||||
await window.Warpbox.writeClipboard(window.Warpbox.absoluteURL(file.previewURL));
|
||||
return true;
|
||||
}
|
||||
if (action === "copy-download") {
|
||||
await window.Warpbox.writeClipboard(file.downloadURL);
|
||||
await window.Warpbox.writeClipboard(window.Warpbox.absoluteURL(file.downloadURL));
|
||||
return true;
|
||||
}
|
||||
if (action === "download") {
|
||||
@@ -188,4 +205,40 @@
|
||||
y >= rect.top - contextMenuCloseDistance &&
|
||||
y <= rect.bottom + contextMenuCloseDistance;
|
||||
}
|
||||
|
||||
function applySavedFileBrowserPreferences() {
|
||||
const savedView = readPreference(viewStorageKey);
|
||||
setFileBrowserView(savedView === "list" ? "list" : "thumbs");
|
||||
}
|
||||
|
||||
function setFileBrowserView(view) {
|
||||
const normalized = view === "thumbs" ? "thumbs" : "list";
|
||||
fileBrowser.classList.toggle("is-list", normalized === "list");
|
||||
fileBrowser.classList.toggle("is-thumbs", normalized === "thumbs");
|
||||
if (fileBrowserWindow) {
|
||||
fileBrowserWindow.classList.toggle("is-list-view", normalized === "list");
|
||||
fileBrowserWindow.classList.toggle("is-icon-view", normalized === "thumbs");
|
||||
}
|
||||
viewButtons.forEach((item) => {
|
||||
const active = item.getAttribute("data-view-button") === normalized;
|
||||
item.classList.toggle("is-active", active);
|
||||
item.setAttribute("aria-pressed", active ? "true" : "false");
|
||||
});
|
||||
}
|
||||
|
||||
function readPreference(key) {
|
||||
try {
|
||||
return window.localStorage.getItem(key);
|
||||
} catch (_) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function savePreference(key, value) {
|
||||
try {
|
||||
window.localStorage.setItem(key, value);
|
||||
} catch (_) {
|
||||
// LocalStorage can be unavailable in private or locked-down browsers.
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
304
backend/static/js/12-reactions.js
Normal file
@@ -0,0 +1,304 @@
|
||||
(function () {
|
||||
const picker = document.querySelector("[data-reaction-picker]");
|
||||
const panel = picker ? picker.querySelector(".reaction-picker-panel") : null;
|
||||
const search = picker ? picker.querySelector("[data-reaction-search]") : null;
|
||||
const closeButton = picker ? picker.querySelector("[data-reaction-close]") : null;
|
||||
const existingSection = picker ? picker.querySelector("[data-reaction-existing]") : null;
|
||||
const existingList = picker ? picker.querySelector("[data-reaction-existing-list]") : null;
|
||||
const readonlyNote = picker ? picker.querySelector("[data-reaction-readonly]") : null;
|
||||
const chooserElements = picker ? Array.from(picker.querySelectorAll(".reaction-picker-tabs, .reaction-search, .reaction-grid-wrap")) : [];
|
||||
const tabs = picker ? Array.from(picker.querySelectorAll("[data-reaction-tab]")) : [];
|
||||
const panels = picker ? Array.from(picker.querySelectorAll("[data-reaction-panel]")) : [];
|
||||
|
||||
let activeButton = null;
|
||||
let activeCard = null;
|
||||
|
||||
document.querySelectorAll("[data-reaction-button]").forEach((button) => {
|
||||
button.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
openPicker(button);
|
||||
});
|
||||
});
|
||||
|
||||
document.addEventListener("click", (event) => {
|
||||
const pill = event.target.closest("[data-reaction-pill]");
|
||||
if (pill) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const card = pill.closest("[data-reaction-card]") || activeCard;
|
||||
if (!card) {
|
||||
return;
|
||||
}
|
||||
if (card.dataset.reacted === "true") {
|
||||
openPickerForCard(card, pill);
|
||||
return;
|
||||
}
|
||||
submitReactionForCard(card, pill.dataset.reactionEmojiId);
|
||||
return;
|
||||
}
|
||||
|
||||
const more = event.target.closest("[data-reaction-more]");
|
||||
if (!more) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const card = more.closest("[data-reaction-card]");
|
||||
if (card) {
|
||||
openPickerForCard(card, more);
|
||||
}
|
||||
});
|
||||
|
||||
if (!picker || !panel) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Aurora's glass card uses backdrop-filter, and the main content animates
|
||||
// with transform. Both can create a containing block for fixed descendants,
|
||||
// so keep the floating picker at body level where viewport coordinates mean
|
||||
// what they say.
|
||||
document.body.appendChild(picker);
|
||||
|
||||
picker.addEventListener("click", (event) => {
|
||||
if (event.target === picker) {
|
||||
closePicker();
|
||||
}
|
||||
});
|
||||
|
||||
panel.addEventListener("click", async (event) => {
|
||||
const emoji = event.target.closest("[data-emoji-id]");
|
||||
if (!emoji || !activeCard || activeCard.dataset.reacted === "true") {
|
||||
return;
|
||||
}
|
||||
await submitReactionForCard(activeCard, emoji.dataset.emojiId);
|
||||
});
|
||||
|
||||
tabs.forEach((tab) => {
|
||||
tab.addEventListener("click", () => {
|
||||
setActiveTab(tab.dataset.reactionTab);
|
||||
});
|
||||
});
|
||||
|
||||
if (search) {
|
||||
search.addEventListener("input", () => filterEmoji(search.value));
|
||||
}
|
||||
|
||||
if (closeButton) {
|
||||
closeButton.addEventListener("click", closePicker);
|
||||
}
|
||||
|
||||
document.addEventListener("click", (event) => {
|
||||
if (picker.hidden) {
|
||||
return;
|
||||
}
|
||||
if (panel.contains(event.target) || event.target.closest("[data-reaction-button]")) {
|
||||
return;
|
||||
}
|
||||
if (event.target.closest("[data-reaction-more]") || event.target.closest("[data-reaction-pill]")) {
|
||||
return;
|
||||
}
|
||||
closePicker();
|
||||
});
|
||||
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") {
|
||||
closePicker();
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener("resize", () => {
|
||||
if (activeButton && !picker.hidden) {
|
||||
positionPicker(activeButton);
|
||||
}
|
||||
});
|
||||
|
||||
function openPicker(button) {
|
||||
openPickerForCard(button.closest("[data-reaction-card]"), button);
|
||||
}
|
||||
|
||||
function openPickerForCard(card, trigger) {
|
||||
if (!card) {
|
||||
return;
|
||||
}
|
||||
activeButton = trigger || card.querySelector("[data-reaction-button]");
|
||||
activeCard = card;
|
||||
populateExistingReactions(card);
|
||||
setPickerReadonly(card.dataset.reacted === "true");
|
||||
picker.hidden = false;
|
||||
picker.classList.add("is-open");
|
||||
if (search) {
|
||||
search.value = "";
|
||||
filterEmoji("");
|
||||
}
|
||||
positionPicker(activeButton || card);
|
||||
}
|
||||
|
||||
function closePicker() {
|
||||
picker.hidden = true;
|
||||
picker.classList.remove("is-open", "is-mobile");
|
||||
document.documentElement.classList.remove("reaction-picker-open");
|
||||
picker.style.left = "";
|
||||
picker.style.top = "";
|
||||
setPickerReadonly(false);
|
||||
activeButton = null;
|
||||
activeCard = null;
|
||||
}
|
||||
|
||||
function positionPicker(button) {
|
||||
if (isMobilePicker()) {
|
||||
picker.classList.add("is-mobile");
|
||||
document.documentElement.classList.add("reaction-picker-open");
|
||||
picker.style.left = "0px";
|
||||
picker.style.top = "0px";
|
||||
return;
|
||||
}
|
||||
|
||||
picker.classList.remove("is-mobile");
|
||||
document.documentElement.classList.remove("reaction-picker-open");
|
||||
picker.style.left = "0px";
|
||||
picker.style.top = "0px";
|
||||
const buttonRect = button.getBoundingClientRect();
|
||||
const pickerRect = panel.getBoundingClientRect();
|
||||
const margin = 10;
|
||||
const preferredLeft = buttonRect.left + (buttonRect.width / 2) - (pickerRect.width / 2);
|
||||
const preferredTop = buttonRect.bottom + 8;
|
||||
const left = Math.min(Math.max(margin, preferredLeft), window.innerWidth - pickerRect.width - margin);
|
||||
const top = Math.min(Math.max(margin, preferredTop), window.innerHeight - pickerRect.height - margin);
|
||||
picker.style.left = `${left}px`;
|
||||
picker.style.top = `${top}px`;
|
||||
}
|
||||
|
||||
function isMobilePicker() {
|
||||
return window.matchMedia("(max-width: 820px), (pointer: coarse)").matches;
|
||||
}
|
||||
|
||||
function setActiveTab(tabID) {
|
||||
tabs.forEach((tab) => {
|
||||
const active = tab.dataset.reactionTab === tabID;
|
||||
tab.classList.toggle("is-active", active);
|
||||
tab.setAttribute("aria-selected", active ? "true" : "false");
|
||||
});
|
||||
panels.forEach((item) => {
|
||||
item.classList.toggle("is-active", item.dataset.reactionPanel === tabID);
|
||||
});
|
||||
}
|
||||
|
||||
function filterEmoji(value) {
|
||||
const query = value.trim().toLowerCase();
|
||||
picker.querySelectorAll("[data-emoji-id]").forEach((button) => {
|
||||
const haystack = `${button.dataset.emojiId} ${button.dataset.emojiLabel}`.toLowerCase();
|
||||
button.hidden = query !== "" && !haystack.includes(query);
|
||||
});
|
||||
}
|
||||
|
||||
async function submitReactionForCard(card, emojiID) {
|
||||
if (!card || !emojiID || card.dataset.reacted === "true") {
|
||||
return;
|
||||
}
|
||||
const body = new URLSearchParams();
|
||||
body.set("emoji_id", emojiID);
|
||||
|
||||
const reactButton = card.querySelector("[data-reaction-button]");
|
||||
if (reactButton) {
|
||||
reactButton.disabled = true;
|
||||
}
|
||||
const response = await fetch(card.dataset.reactUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (reactButton) {
|
||||
reactButton.disabled = false;
|
||||
}
|
||||
closePicker();
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = await response.json();
|
||||
renderReactions(card, payload.reactions || []);
|
||||
card.dataset.reacted = "true";
|
||||
if (reactButton) {
|
||||
reactButton.remove();
|
||||
}
|
||||
closePicker();
|
||||
}
|
||||
|
||||
function renderReactions(card, reactions) {
|
||||
const list = card.querySelector("[data-reaction-list]");
|
||||
if (!list) {
|
||||
return;
|
||||
}
|
||||
list.replaceChildren();
|
||||
reactions.forEach((reaction) => {
|
||||
const pill = buildReactionPill(reaction);
|
||||
if (!reaction.visible) {
|
||||
pill.classList.add("is-hidden-summary");
|
||||
}
|
||||
list.append(pill);
|
||||
});
|
||||
const hiddenCount = reactions.length > 2 ? reactions.length - 2 : 0;
|
||||
if (hiddenCount > 0) {
|
||||
const more = document.createElement("button");
|
||||
more.className = "reaction-more";
|
||||
more.type = "button";
|
||||
more.dataset.reactionMore = "";
|
||||
more.textContent = `+${hiddenCount}`;
|
||||
more.setAttribute("aria-label", `Show ${hiddenCount} more reactions`);
|
||||
list.append(more);
|
||||
}
|
||||
}
|
||||
|
||||
function buildReactionPill(reaction) {
|
||||
const pill = document.createElement("button");
|
||||
pill.className = "reaction-pill";
|
||||
pill.type = "button";
|
||||
pill.title = reaction.label || reaction.emojiId;
|
||||
pill.dataset.reactionPill = "";
|
||||
pill.dataset.reactionEmojiId = reaction.emojiId;
|
||||
pill.dataset.reactionLabel = reaction.label || reaction.emojiId;
|
||||
pill.dataset.reactionUrl = reaction.url;
|
||||
pill.dataset.reactionCount = reaction.count;
|
||||
pill.setAttribute("aria-label", `React with ${reaction.label || reaction.emojiId}`);
|
||||
|
||||
const image = document.createElement("img");
|
||||
image.src = reaction.url;
|
||||
image.alt = reaction.label || reaction.emojiId;
|
||||
image.loading = "lazy";
|
||||
|
||||
const count = document.createElement("span");
|
||||
count.textContent = reaction.count;
|
||||
|
||||
pill.append(image, count);
|
||||
return pill;
|
||||
}
|
||||
|
||||
function populateExistingReactions(card) {
|
||||
if (!existingSection || !existingList) {
|
||||
return;
|
||||
}
|
||||
existingList.replaceChildren();
|
||||
card.querySelectorAll("[data-reaction-pill]").forEach((pill) => {
|
||||
const clone = pill.cloneNode(true);
|
||||
clone.classList.remove("is-hidden-summary");
|
||||
existingList.append(clone);
|
||||
});
|
||||
existingSection.hidden = existingList.children.length === 0;
|
||||
}
|
||||
|
||||
function setPickerReadonly(readonly) {
|
||||
picker.classList.toggle("is-readonly", readonly);
|
||||
chooserElements.forEach((element) => {
|
||||
element.hidden = readonly;
|
||||
});
|
||||
if (readonlyNote) {
|
||||
readonlyNote.hidden = !readonly;
|
||||
}
|
||||
}
|
||||
})();
|
||||
@@ -1,4 +1,16 @@
|
||||
(function () {
|
||||
document.querySelectorAll("[data-storage-delete-warning]").forEach((button) => {
|
||||
button.addEventListener("click", (event) => {
|
||||
const name = button.getAttribute("data-storage-delete-warning") || "this storage backend";
|
||||
const confirmed = window.confirm(
|
||||
`Delete ${name}?\n\nAll boxes stored on this location will also be deleted. Any global defaults or user storage overrides pointing at it will be reset back to inherited local storage.`
|
||||
);
|
||||
if (!confirmed) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-storage-speed-open]").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
const modal = document.querySelector("[data-storage-speed-modal]");
|
||||
|
||||
57
backend/static/js/25-admin-charts.js
Normal file
@@ -0,0 +1,57 @@
|
||||
(function () {
|
||||
const maxBarHeight = 150;
|
||||
|
||||
function numberAttr(element, name) {
|
||||
const value = Number(element.getAttribute(name));
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
function applyChartBars() {
|
||||
document.querySelectorAll(".bar-chart").forEach((chart) => {
|
||||
const bars = Array.from(chart.querySelectorAll(".bar-chart-col"));
|
||||
const maxValue = Math.max(0, ...bars.map((bar) => numberAttr(bar, "data-chart-value")));
|
||||
|
||||
bars.forEach((bar) => {
|
||||
const fill = bar.querySelector(".bar-chart-bar");
|
||||
if (!fill) {
|
||||
return;
|
||||
}
|
||||
const value = numberAttr(bar, "data-chart-value");
|
||||
let height = numberAttr(fill, "data-height-px");
|
||||
if (maxValue > 0) {
|
||||
height = value <= 0 ? 0 : Math.max(8, Math.round((value / maxValue) * maxBarHeight));
|
||||
}
|
||||
fill.style.height = `${Math.min(maxBarHeight, height)}px`;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function applyStatusBars() {
|
||||
const rows = Array.from(document.querySelectorAll(".stat-bar"));
|
||||
const maxValue = Math.max(0, ...rows.map((row) => numberAttr(row, "data-stat-value")));
|
||||
|
||||
rows.forEach((row) => {
|
||||
const fill = row.querySelector(".stat-bar-fill");
|
||||
if (!fill) {
|
||||
return;
|
||||
}
|
||||
const value = numberAttr(row, "data-stat-value");
|
||||
let width = numberAttr(fill, "data-width-percent");
|
||||
if (maxValue > 0) {
|
||||
width = value <= 0 ? 0 : Math.round((value / maxValue) * 100);
|
||||
}
|
||||
fill.style.width = `${Math.max(0, Math.min(100, width))}%`;
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
applyChartBars();
|
||||
applyStatusBars();
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
43
backend/static/js/35-pagination.js
Normal file
@@ -0,0 +1,43 @@
|
||||
// Per-page selector: remembers the chosen page size in localStorage and keeps
|
||||
// the URL's `per` query param in sync. CSP-safe (external file, no inline JS).
|
||||
(function () {
|
||||
const select = document.querySelector("[data-per-page]");
|
||||
if (!select) {
|
||||
return;
|
||||
}
|
||||
|
||||
const key = "warpbox-perpage-" + select.dataset.perPage;
|
||||
const url = new URL(window.location.href);
|
||||
const current = url.searchParams.get("per");
|
||||
let stored = null;
|
||||
try {
|
||||
stored = window.localStorage.getItem(key);
|
||||
} catch (err) {
|
||||
stored = null;
|
||||
}
|
||||
|
||||
// No explicit choice in the URL but a remembered preference exists: apply it.
|
||||
if (!current && stored && stored !== select.value) {
|
||||
const valid = Array.prototype.some.call(select.options, function (opt) {
|
||||
return opt.value === stored;
|
||||
});
|
||||
if (valid) {
|
||||
url.searchParams.set("per", stored);
|
||||
url.searchParams.delete("page");
|
||||
window.location.replace(url.toString());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
select.addEventListener("change", function () {
|
||||
try {
|
||||
window.localStorage.setItem(key, select.value);
|
||||
} catch (err) {
|
||||
/* ignore storage failures (private mode, etc.) */
|
||||
}
|
||||
const next = new URL(window.location.href);
|
||||
next.searchParams.set("per", select.value);
|
||||
next.searchParams.delete("page");
|
||||
window.location.assign(next.toString());
|
||||
});
|
||||
})();
|
||||
@@ -13,6 +13,8 @@
|
||||
const copyURL = document.querySelector("#copy-url");
|
||||
const openBox = document.querySelector("#open-box");
|
||||
const manageLink = document.querySelector("#manage-link");
|
||||
const newUpload = document.querySelector("#new-upload");
|
||||
const RESUMABLE_SESSIONS_KEY = "warpbox-resumable-sessions";
|
||||
|
||||
if (!form || !dropZone || !fileInput) {
|
||||
return;
|
||||
@@ -42,6 +44,9 @@
|
||||
|
||||
let latestBoxURL = "";
|
||||
let selectedFiles = [];
|
||||
let uploadLocked = false;
|
||||
let recoveredDraft = null;
|
||||
let resumeMode = false;
|
||||
|
||||
["dragenter", "dragover"].forEach((eventName) => {
|
||||
dropZone.addEventListener(eventName, (event) => {
|
||||
@@ -57,33 +62,65 @@
|
||||
});
|
||||
});
|
||||
|
||||
dropZone.addEventListener("drop", (event) => {
|
||||
if (event.dataTransfer && event.dataTransfer.files.length > 0) {
|
||||
fileInput.files = event.dataTransfer.files;
|
||||
updateSelectedState(event.dataTransfer.files);
|
||||
document.addEventListener("dragover", (event) => {
|
||||
if (event.dataTransfer && Array.from(event.dataTransfer.types || []).includes("Files")) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
fileInput.addEventListener("change", () => updateSelectedState(fileInput.files));
|
||||
document.addEventListener("drop", (event) => {
|
||||
if (!event.dataTransfer || !event.dataTransfer.files.length) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
if (!dropZone.contains(event.target)) {
|
||||
addSelectedFiles(event.dataTransfer.files);
|
||||
}
|
||||
});
|
||||
|
||||
dropZone.addEventListener("drop", (event) => {
|
||||
if (event.dataTransfer && event.dataTransfer.files.length > 0) {
|
||||
addSelectedFiles(event.dataTransfer.files);
|
||||
}
|
||||
});
|
||||
|
||||
fileInput.addEventListener("change", () => {
|
||||
addSelectedFiles(fileInput.files);
|
||||
fileInput.value = "";
|
||||
});
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
if (!fileInput.files || fileInput.files.length === 0) {
|
||||
if (selectedFiles.length === 0) {
|
||||
updateStatus("Choose at least one file first.");
|
||||
return;
|
||||
}
|
||||
|
||||
const submit = form.querySelector("button[type='submit']");
|
||||
const formData = new FormData(form);
|
||||
selectedFiles = Array.from(fileInput.files);
|
||||
renderQueue(selectedFiles, "queued");
|
||||
const formData = uploadFormData();
|
||||
if (resumeMode && recoveredDraft) {
|
||||
renderResumeQueue(recoveredDraft.session, selectedFiles);
|
||||
} else {
|
||||
renderQueue(selectedFiles, "queued");
|
||||
}
|
||||
setLoading(true, submit);
|
||||
|
||||
try {
|
||||
const payload = await uploadWithProgress(form.action, formData, selectedFiles);
|
||||
const payload = await uploadResumable(form.action, formData, selectedFiles);
|
||||
renderResult(payload);
|
||||
form.reset();
|
||||
updateSelectedState([]);
|
||||
selectedFiles = [];
|
||||
resumeMode = false;
|
||||
recoveredDraft = null;
|
||||
fileInput.value = "";
|
||||
if (uploadQueue) {
|
||||
uploadQueue.hidden = true;
|
||||
uploadQueue.replaceChildren();
|
||||
}
|
||||
updateNewUploadVisibility();
|
||||
if (fileSummary) {
|
||||
fileSummary.textContent = "Upload complete.";
|
||||
}
|
||||
} catch (error) {
|
||||
updateStatus(error.message || "Upload failed");
|
||||
} finally {
|
||||
@@ -97,25 +134,73 @@
|
||||
});
|
||||
}
|
||||
|
||||
function updateSelectedState(files) {
|
||||
selectedFiles = Array.from(files || []);
|
||||
if (newUpload) {
|
||||
newUpload.addEventListener("click", () => {
|
||||
cancelRecoveredDraft().catch((error) => {
|
||||
updateStatus(error.message || "Upload draft could not be deleted");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
recoverResumableSessions();
|
||||
|
||||
function addSelectedFiles(files) {
|
||||
if (uploadLocked) {
|
||||
return;
|
||||
}
|
||||
Array.from(files || []).forEach((file) => {
|
||||
if (!selectedFiles.some((existing) => fileIdentity(existing) === fileIdentity(file))) {
|
||||
selectedFiles.push(file);
|
||||
}
|
||||
});
|
||||
updateSelectedState();
|
||||
}
|
||||
|
||||
function removeSelectedFile(index) {
|
||||
if (uploadLocked) {
|
||||
return;
|
||||
}
|
||||
selectedFiles.splice(index, 1);
|
||||
updateSelectedState();
|
||||
}
|
||||
|
||||
function updateSelectedState() {
|
||||
const count = selectedFiles.length || 0;
|
||||
const title = dropZone.querySelector(".drop-title");
|
||||
if (title) {
|
||||
title.textContent = count === 0 ? "Drop files to upload" : count === 1 ? "1 file selected" : `${count} files selected`;
|
||||
}
|
||||
if (fileSummary) {
|
||||
fileSummary.textContent = count === 0 ? "Choose one or more files to begin." : `${count} file${count === 1 ? "" : "s"} ready.`;
|
||||
if (resumeMode && recoveredDraft) {
|
||||
fileSummary.textContent = count === 0
|
||||
? "Reselect missing files to resume, or add extra files to this upload."
|
||||
: `${count} local file${count === 1 ? "" : "s"} ready for the recovered upload.`;
|
||||
} else {
|
||||
fileSummary.textContent = count === 0 ? "Choose one or more files to begin." : `${count} file${count === 1 ? "" : "s"} ready.`;
|
||||
}
|
||||
}
|
||||
if (count > 0) {
|
||||
if (resumeMode && recoveredDraft) {
|
||||
renderResumeQueue(recoveredDraft.session, selectedFiles);
|
||||
} else if (count > 0) {
|
||||
renderQueue(selectedFiles, "queued");
|
||||
} else if (uploadQueue) {
|
||||
uploadQueue.hidden = true;
|
||||
uploadQueue.replaceChildren();
|
||||
}
|
||||
updateNewUploadVisibility();
|
||||
}
|
||||
|
||||
function updateNewUploadVisibility() {
|
||||
if (!newUpload) {
|
||||
return;
|
||||
}
|
||||
const visible = Boolean(resumeMode && recoveredDraft);
|
||||
newUpload.hidden = !visible;
|
||||
newUpload.style.display = visible ? "" : "none";
|
||||
}
|
||||
|
||||
function setLoading(isLoading, submit) {
|
||||
uploadLocked = isLoading;
|
||||
if (progress) {
|
||||
progress.hidden = !isLoading;
|
||||
}
|
||||
@@ -123,6 +208,9 @@
|
||||
submit.disabled = isLoading;
|
||||
submit.textContent = isLoading ? "Uploading..." : "Upload files";
|
||||
}
|
||||
if (newUpload) {
|
||||
newUpload.disabled = isLoading;
|
||||
}
|
||||
updateStatus(isLoading ? "Transferring files..." : "");
|
||||
setTotalProgress(isLoading ? 0 : 100);
|
||||
}
|
||||
@@ -133,20 +221,55 @@
|
||||
}
|
||||
}
|
||||
|
||||
function updateUploadProgress(percent, bytesPerSecond) {
|
||||
const clamped = Math.max(0, Math.min(100, Math.round(percent || 0)));
|
||||
const rate = formatTransferRate(bytesPerSecond);
|
||||
updateStatus(rate ? `${clamped}% · ${rate}` : `${clamped}%`);
|
||||
}
|
||||
|
||||
function createTransferRateTracker(initialBytes) {
|
||||
const startedAt = performance.now();
|
||||
const baseline = Math.max(0, initialBytes || 0);
|
||||
let lastRate = 0;
|
||||
return function track(currentBytes) {
|
||||
const elapsedSeconds = (performance.now() - startedAt) / 1000;
|
||||
const transferred = Math.max(0, (currentBytes || 0) - baseline);
|
||||
if (elapsedSeconds < 0.25 || transferred <= 0) {
|
||||
return lastRate;
|
||||
}
|
||||
lastRate = transferred / elapsedSeconds;
|
||||
return lastRate;
|
||||
};
|
||||
}
|
||||
|
||||
function formatTransferRate(bytesPerSecond) {
|
||||
if (!Number.isFinite(bytesPerSecond) || bytesPerSecond <= 0) {
|
||||
return "";
|
||||
}
|
||||
const units = ["b/s", "Kb/s", "Mb/s", "Gb/s"];
|
||||
let value = bytesPerSecond * 8;
|
||||
let unit = 0;
|
||||
while (value >= 1000 && unit < units.length - 1) {
|
||||
value /= 1000;
|
||||
unit += 1;
|
||||
}
|
||||
return `${value >= 10 || unit === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[unit]}`;
|
||||
}
|
||||
|
||||
function renderResult(payload) {
|
||||
if (!result || !resultList || !resultMeta || !openBox) {
|
||||
return;
|
||||
}
|
||||
|
||||
latestBoxURL = payload.boxUrl;
|
||||
latestBoxURL = window.Warpbox.absoluteURL(payload.boxUrl);
|
||||
result.hidden = false;
|
||||
openBox.href = payload.boxUrl;
|
||||
openBox.href = latestBoxURL;
|
||||
resultMeta.textContent = `${payload.files.length} file${payload.files.length === 1 ? "" : "s"} · expires ${window.Warpbox.formatDate(payload.expiresAt)}`;
|
||||
if (manageLink) {
|
||||
const anchor = manageLink.querySelector("a");
|
||||
manageLink.hidden = !payload.manageUrl;
|
||||
if (anchor && payload.manageUrl) {
|
||||
anchor.href = payload.manageUrl;
|
||||
anchor.href = window.Warpbox.absoluteURL(payload.manageUrl);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,26 +277,29 @@
|
||||
payload.files.forEach((file) => {
|
||||
resultList.append(createFileRow({
|
||||
name: file.name,
|
||||
meta: `${file.size} · ${file.url}`,
|
||||
meta: `${file.size} · ${window.Warpbox.absoluteURL(file.url)}`,
|
||||
progress: 100,
|
||||
status: "complete",
|
||||
}));
|
||||
});
|
||||
result.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
}
|
||||
|
||||
function uploadWithProgress(url, formData, files) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = new XMLHttpRequest();
|
||||
const rateTracker = createTransferRateTracker(0);
|
||||
request.open("POST", url);
|
||||
request.setRequestHeader("Accept", "application/json");
|
||||
|
||||
request.upload.addEventListener("progress", (event) => {
|
||||
const rate = rateTracker(event.loaded || 0);
|
||||
if (!event.lengthComputable) {
|
||||
updateStatus("Uploading...");
|
||||
updateStatus(rate > 0 ? `Uploading · ${formatTransferRate(rate)}` : "Uploading...");
|
||||
return;
|
||||
}
|
||||
const percent = Math.round((event.loaded / event.total) * 100);
|
||||
updateStatus(`${percent}%`);
|
||||
updateUploadProgress(percent, rate);
|
||||
setTotalProgress(percent);
|
||||
setFileProgress(files, percent);
|
||||
});
|
||||
@@ -201,26 +327,617 @@
|
||||
});
|
||||
}
|
||||
|
||||
async function uploadResumable(fallbackUrl, formData, files) {
|
||||
if (!window.fetch || typeof Blob === "undefined") {
|
||||
return uploadWithProgress(fallbackUrl, formData, files);
|
||||
}
|
||||
|
||||
updateStatus("Fingerprinting files...");
|
||||
const fingerprints = await Promise.all(files.map((file) => fileFingerprint(file)));
|
||||
const createPayload = {
|
||||
files: files.map((file, index) => ({
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
contentType: file.type || "application/octet-stream",
|
||||
fingerprint: fingerprints[index],
|
||||
})),
|
||||
expiresMinutes: parseInt(formData.get("expires_minutes") || "0", 10) || 0,
|
||||
maxDownloads: parseInt(formData.get("max_downloads") || "0", 10) || 0,
|
||||
password: formData.get("password") || "",
|
||||
obfuscateMetadata: formData.get("obfuscate_metadata") === "on",
|
||||
collectionId: formData.get("collection_id") || "",
|
||||
};
|
||||
const persistable = !createPayload.password;
|
||||
let session = null;
|
||||
if (persistable && resumeMode && recoveredDraft) {
|
||||
session = await fetchResumableStatus(recoveredDraft.session.sessionId, recoveredDraft.session.resumeToken);
|
||||
session.resumeToken = recoveredDraft.session.resumeToken;
|
||||
} else if (persistable) {
|
||||
session = await findResumableSession(createPayload);
|
||||
}
|
||||
if (session) {
|
||||
validateResumeSelection(session, createPayload);
|
||||
session = await addMissingResumableFiles(session, createPayload);
|
||||
if (resumeMode && recoveredDraft && recoveredDraft.session.sessionId === session.sessionId) {
|
||||
recoveredDraft.session = session;
|
||||
}
|
||||
if (persistable) {
|
||||
saveResumableSession(session, createPayload);
|
||||
}
|
||||
}
|
||||
if (!session || session.status !== "uploading") {
|
||||
try {
|
||||
session = await createResumableSession(createPayload);
|
||||
} catch (error) {
|
||||
if ((error.message || "").toLowerCase().includes("resumable uploads are disabled")) {
|
||||
return uploadWithProgress(fallbackUrl, formData, files);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (persistable) {
|
||||
saveResumableSession(session, createPayload);
|
||||
}
|
||||
}
|
||||
const sessionFiles = files.map((file, index) => matchSessionFile(session, createPayload.files[index]));
|
||||
if (sessionFiles.some((file) => !file)) {
|
||||
throw new Error("Upload session could not match the selected files");
|
||||
}
|
||||
|
||||
updateStatus("Uploading...");
|
||||
const totalBytes = files.reduce((sum, file) => sum + file.size, 0);
|
||||
const completedByFile = new Array(files.length).fill(0);
|
||||
sessionFiles.forEach((sessionFile, index) => {
|
||||
completedByFile[index] = uploadedBytesForSessionFile(sessionFile, session.chunkSize);
|
||||
setSingleFileProgress(index, files[index], percentForBytes(completedByFile[index], files[index].size));
|
||||
});
|
||||
const initiallyUploadedBytes = completedByFile.reduce((sum, bytes) => sum + bytes, 0);
|
||||
const rateTracker = createTransferRateTracker(initiallyUploadedBytes);
|
||||
setTotalProgress(percentForBytes(initiallyUploadedBytes, totalBytes));
|
||||
|
||||
for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
|
||||
const file = files[fileIndex];
|
||||
const sessionFile = sessionFiles[fileIndex];
|
||||
const uploaded = new Set(sessionFile.uploadedChunks || []);
|
||||
for (let chunkIndex = 0; chunkIndex < sessionFile.chunkCount; chunkIndex++) {
|
||||
if (uploaded.has(chunkIndex)) {
|
||||
continue;
|
||||
}
|
||||
const start = chunkIndex * session.chunkSize;
|
||||
const end = Math.min(file.size, start + session.chunkSize);
|
||||
await uploadChunkWithRetry(session, sessionFile, chunkIndex, file.slice(start, end), (loaded) => {
|
||||
const currentTotal = completedByFile.reduce((sum, bytes) => sum + bytes, 0) + loaded;
|
||||
const percent = percentForBytes(currentTotal, totalBytes);
|
||||
const rate = rateTracker(currentTotal);
|
||||
setTotalProgress(percent);
|
||||
setSingleFileProgress(fileIndex, file, percentForBytes(completedByFile[fileIndex] + loaded, file.size));
|
||||
updateUploadProgress(percent, rate);
|
||||
});
|
||||
completedByFile[fileIndex] += end - start;
|
||||
uploaded.add(chunkIndex);
|
||||
sessionFile.uploadedChunks = Array.from(uploaded).sort((a, b) => a - b);
|
||||
if (persistable) {
|
||||
saveResumableSession(session, createPayload);
|
||||
}
|
||||
}
|
||||
setSingleFileProgress(fileIndex, file, 100);
|
||||
}
|
||||
|
||||
updateStatus("Finalizing upload...");
|
||||
const resultPayload = await completeResumableSession(session.sessionId, session.resumeToken);
|
||||
const wasResumeMode = resumeMode;
|
||||
if (persistable) {
|
||||
removeResumableSession(session.sessionId);
|
||||
}
|
||||
if (resumeMode && recoveredDraft && recoveredDraft.session.sessionId === session.sessionId) {
|
||||
resumeMode = false;
|
||||
recoveredDraft = null;
|
||||
}
|
||||
setTotalProgress(100);
|
||||
if (!wasResumeMode) {
|
||||
setFileProgress(files, 100);
|
||||
}
|
||||
return resultPayload;
|
||||
}
|
||||
|
||||
async function createResumableSession(payload) {
|
||||
const response = await fetch("/api/v1/uploads/resumable", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return readUploadJSON(response, "Upload session could not be created");
|
||||
}
|
||||
|
||||
async function fetchResumableStatus(sessionID, resumeToken) {
|
||||
const response = await fetch(`/api/v1/uploads/resumable/${encodeURIComponent(sessionID)}`, {
|
||||
headers: resumableHeaders(resumeToken),
|
||||
});
|
||||
return readUploadJSON(response, "Upload session could not be resumed");
|
||||
}
|
||||
|
||||
async function addResumableFiles(sessionID, resumeToken, files) {
|
||||
const response = await fetch(`/api/v1/uploads/resumable/${encodeURIComponent(sessionID)}/files`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
...resumableHeaders(resumeToken),
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ files }),
|
||||
});
|
||||
return readUploadJSON(response, "Upload session files could not be added");
|
||||
}
|
||||
|
||||
function uploadChunk(sessionID, resumeToken, fileID, chunkIndex, chunk, onProgress) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = new XMLHttpRequest();
|
||||
request.open("PUT", `/api/v1/uploads/resumable/${encodeURIComponent(sessionID)}/files/${encodeURIComponent(fileID)}/chunks/${chunkIndex}`);
|
||||
request.setRequestHeader("Accept", "application/json");
|
||||
request.setRequestHeader("X-Warpbox-Resume-Token", resumeToken || "");
|
||||
request.upload.addEventListener("progress", (event) => {
|
||||
if (event.lengthComputable && onProgress) {
|
||||
onProgress(event.loaded);
|
||||
}
|
||||
});
|
||||
request.addEventListener("load", () => {
|
||||
if (request.status < 200 || request.status >= 300) {
|
||||
let payload = {};
|
||||
try {
|
||||
payload = JSON.parse(request.responseText || "{}");
|
||||
} catch (error) {
|
||||
payload = {};
|
||||
}
|
||||
reject(new Error(payload.error || "Chunk upload failed"));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
request.addEventListener("error", () => reject(new Error("Network error during chunk upload")));
|
||||
request.addEventListener("abort", () => reject(new Error("Chunk upload aborted")));
|
||||
request.send(chunk);
|
||||
});
|
||||
}
|
||||
|
||||
async function uploadChunkWithRetry(session, sessionFile, chunkIndex, chunk, onProgress) {
|
||||
const delays = [1000, 2000, 5000, 10000, 20000];
|
||||
let lastError = null;
|
||||
for (let attempt = 0; attempt <= delays.length; attempt++) {
|
||||
try {
|
||||
return await uploadChunk(session.sessionId, session.resumeToken, sessionFile.id, chunkIndex, chunk, onProgress);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt >= delays.length) {
|
||||
break;
|
||||
}
|
||||
const seconds = Math.round(delays[attempt] / 1000);
|
||||
updateStatus(`Connection interrupted, retrying chunk ${chunkIndex + 1} in ${seconds}s`);
|
||||
await wait(delays[attempt]);
|
||||
}
|
||||
}
|
||||
throw lastError || new Error("Chunk upload failed");
|
||||
}
|
||||
|
||||
async function completeResumableSession(sessionID, resumeToken) {
|
||||
const response = await fetch(`/api/v1/uploads/resumable/${encodeURIComponent(sessionID)}/complete`, {
|
||||
method: "POST",
|
||||
headers: resumableHeaders(resumeToken),
|
||||
});
|
||||
return readUploadJSON(response, "Upload could not be completed");
|
||||
}
|
||||
|
||||
async function cancelResumableSession(sessionID, resumeToken) {
|
||||
const response = await fetch(`/api/v1/uploads/resumable/${encodeURIComponent(sessionID)}`, {
|
||||
method: "DELETE",
|
||||
headers: resumableHeaders(resumeToken),
|
||||
});
|
||||
if (!response.ok && response.status !== 404) {
|
||||
await readUploadJSON(response, "Upload draft could not be deleted");
|
||||
}
|
||||
}
|
||||
|
||||
function resumableHeaders(resumeToken) {
|
||||
return {
|
||||
"Accept": "application/json",
|
||||
"X-Warpbox-Resume-Token": resumeToken || "",
|
||||
};
|
||||
}
|
||||
|
||||
function wait(ms) {
|
||||
return new Promise((resolve) => window.setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function readUploadJSON(response, fallback) {
|
||||
let payload = {};
|
||||
try {
|
||||
payload = await response.json();
|
||||
} catch (error) {
|
||||
payload = {};
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.error || fallback);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function findResumableSession(payload) {
|
||||
const records = loadResumableSessions();
|
||||
const optionKey = resumableOptionKey(payload);
|
||||
const selectedKeys = new Set(payload.files.map((file) => resumableFileKey(file)));
|
||||
for (const record of records) {
|
||||
if (record.optionKey !== optionKey) {
|
||||
continue;
|
||||
}
|
||||
if (!record.files || !record.files.some((file) => selectedKeys.has(resumableFileKey(file)))) {
|
||||
continue;
|
||||
}
|
||||
const session = await fetchResumableStatus(record.sessionId, record.resumeToken).catch(() => null);
|
||||
if (!session || session.status !== "uploading") {
|
||||
removeResumableSession(record.sessionId);
|
||||
continue;
|
||||
}
|
||||
session.resumeToken = record.resumeToken;
|
||||
const sessionKeys = new Set(session.files.map((file) => resumableFileKey(file)));
|
||||
const selectedContainsSessionFile = Array.from(sessionKeys).some((key) => selectedKeys.has(key));
|
||||
if (selectedContainsSessionFile) {
|
||||
return session;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function addMissingResumableFiles(session, payload) {
|
||||
const existing = new Set(session.files.map((file) => resumableFileKey(file)));
|
||||
const missing = payload.files.filter((file) => !existing.has(resumableFileKey(file)));
|
||||
if (missing.length === 0) {
|
||||
return session;
|
||||
}
|
||||
const updated = await addResumableFiles(session.sessionId, session.resumeToken, missing);
|
||||
updated.resumeToken = session.resumeToken;
|
||||
return updated;
|
||||
}
|
||||
|
||||
function validateResumeSelection(session, payload) {
|
||||
if (!resumeMode || !recoveredDraft || session.sessionId !== recoveredDraft.session.sessionId) {
|
||||
return;
|
||||
}
|
||||
const existingByNameSize = new Map();
|
||||
(session.files || []).forEach((file) => {
|
||||
existingByNameSize.set(`${file.name}:${file.size}`, resumableFileKey(file));
|
||||
});
|
||||
for (const file of payload.files || []) {
|
||||
const expectedKey = existingByNameSize.get(`${file.name}:${file.size}`);
|
||||
if (expectedKey && expectedKey !== resumableFileKey(file)) {
|
||||
throw new Error(`"${file.name}" does not match the pending upload. Select the exact original file.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function matchSessionFile(session, file) {
|
||||
const key = resumableFileKey(file);
|
||||
return session.files.find((sessionFile) => resumableFileKey(sessionFile) === key) || null;
|
||||
}
|
||||
|
||||
function resumableOptionKey(payload) {
|
||||
return [
|
||||
payload.expiresMinutes,
|
||||
payload.maxDownloads,
|
||||
payload.obfuscateMetadata ? "1" : "0",
|
||||
payload.collectionId || "",
|
||||
].join(":");
|
||||
}
|
||||
|
||||
function resumableFileKey(file) {
|
||||
return [file.name, file.size, file.fingerprint || ""].join(":");
|
||||
}
|
||||
|
||||
function loadResumableSessions() {
|
||||
try {
|
||||
const value = localStorage.getItem(RESUMABLE_SESSIONS_KEY);
|
||||
const records = value ? JSON.parse(value) : [];
|
||||
return Array.isArray(records) ? records : [];
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function saveResumableSession(session, payload) {
|
||||
try {
|
||||
const records = loadResumableSessions().filter((record) => record.sessionId !== session.sessionId);
|
||||
records.push({
|
||||
sessionId: session.sessionId,
|
||||
resumeToken: session.resumeToken || "",
|
||||
optionKey: resumableOptionKey(payload),
|
||||
options: {
|
||||
expiresMinutes: payload.expiresMinutes,
|
||||
maxDownloads: payload.maxDownloads,
|
||||
obfuscateMetadata: !!payload.obfuscateMetadata,
|
||||
collectionId: payload.collectionId || "",
|
||||
},
|
||||
files: session.files.map((file) => ({
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
contentType: file.contentType || "application/octet-stream",
|
||||
fingerprint: file.fingerprint || "",
|
||||
uploadedChunks: file.uploadedChunks || [],
|
||||
chunkCount: file.chunkCount || 0,
|
||||
})),
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
localStorage.setItem(RESUMABLE_SESSIONS_KEY, JSON.stringify(records.slice(-25)));
|
||||
} catch (error) {
|
||||
/* ignore persistence failures */
|
||||
}
|
||||
}
|
||||
|
||||
async function recoverResumableSessions() {
|
||||
const records = loadResumableSessions()
|
||||
.filter((record) => record.sessionId && record.resumeToken)
|
||||
.sort((a, b) => new Date(b.updatedAt || 0).getTime() - new Date(a.updatedAt || 0).getTime());
|
||||
if (records.length === 0) {
|
||||
return;
|
||||
}
|
||||
for (const record of records) {
|
||||
const session = await fetchResumableStatus(record.sessionId, record.resumeToken).catch(() => null);
|
||||
if (!session || session.status !== "uploading") {
|
||||
removeResumableSession(record.sessionId);
|
||||
continue;
|
||||
}
|
||||
session.resumeToken = record.resumeToken;
|
||||
recoveredDraft = { session, record };
|
||||
selectedFiles = [];
|
||||
renderRecoveredQueue([{ session, record }]);
|
||||
updateRecoveredSummary(session);
|
||||
showRecoveryModal(recoveredDraft);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function updateRecoveredSummary(session) {
|
||||
updateStatus("Unfinished upload found. Choose how to continue.");
|
||||
if (fileSummary) {
|
||||
const totalFiles = (session.files || []).length;
|
||||
const completedFiles = completedSessionFiles(session).length;
|
||||
fileSummary.textContent = `Recovered ${totalFiles} pending file${totalFiles === 1 ? "" : "s"}; ${completedFiles} fully uploaded.`;
|
||||
}
|
||||
}
|
||||
|
||||
function removeResumableSession(sessionID) {
|
||||
try {
|
||||
const records = loadResumableSessions().filter((record) => record.sessionId !== sessionID);
|
||||
localStorage.setItem(RESUMABLE_SESSIONS_KEY, JSON.stringify(records));
|
||||
} catch (error) {
|
||||
/* ignore persistence failures */
|
||||
}
|
||||
}
|
||||
|
||||
function completedSessionFiles(session) {
|
||||
return (session.files || []).filter((file) => (file.uploadedChunks || []).length >= file.chunkCount);
|
||||
}
|
||||
|
||||
function showRecoveryModal(draft) {
|
||||
const old = document.querySelector(".upload-recovery-overlay");
|
||||
if (old) {
|
||||
old.remove();
|
||||
}
|
||||
const completeCount = completedSessionFiles(draft.session).length;
|
||||
const totalCount = (draft.session.files || []).length;
|
||||
const overlay = document.createElement("div");
|
||||
overlay.className = "upload-recovery-overlay";
|
||||
overlay.setAttribute("role", "dialog");
|
||||
overlay.setAttribute("aria-modal", "true");
|
||||
overlay.setAttribute("aria-labelledby", "upload-recovery-title");
|
||||
|
||||
const modal = document.createElement("div");
|
||||
modal.className = "upload-recovery-modal card";
|
||||
const content = document.createElement("div");
|
||||
content.className = "card-content";
|
||||
|
||||
const title = document.createElement("h2");
|
||||
title.id = "upload-recovery-title";
|
||||
title.textContent = "Unfinished upload found";
|
||||
const copy = document.createElement("p");
|
||||
copy.textContent = `Warpbox found a private draft with ${totalCount} file${totalCount === 1 ? "" : "s"}. ${completeCount} file${completeCount === 1 ? " is" : "s are"} already fully uploaded.`;
|
||||
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "upload-recovery-actions";
|
||||
|
||||
const startOver = document.createElement("button");
|
||||
startOver.type = "button";
|
||||
startOver.className = "button button-danger";
|
||||
startOver.textContent = "New Upload";
|
||||
startOver.addEventListener("click", async () => {
|
||||
startOver.disabled = true;
|
||||
try {
|
||||
await cancelRecoveredDraft();
|
||||
overlay.remove();
|
||||
} catch (error) {
|
||||
startOver.disabled = false;
|
||||
updateStatus(error.message || "Upload draft could not be deleted");
|
||||
}
|
||||
});
|
||||
|
||||
const resume = document.createElement("button");
|
||||
resume.type = "button";
|
||||
resume.className = "button button-primary";
|
||||
resume.textContent = "Resume";
|
||||
resume.addEventListener("click", () => {
|
||||
resumeRecoveredDraft();
|
||||
overlay.remove();
|
||||
});
|
||||
|
||||
actions.append(startOver, resume);
|
||||
content.append(title, copy, actions);
|
||||
modal.append(content);
|
||||
overlay.append(modal);
|
||||
document.body.append(overlay);
|
||||
}
|
||||
|
||||
async function cancelRecoveredDraft() {
|
||||
if (!recoveredDraft) {
|
||||
resetFreshUploadState();
|
||||
return;
|
||||
}
|
||||
const draft = recoveredDraft;
|
||||
updateStatus("Deleting unfinished upload...");
|
||||
await cancelResumableSession(draft.session.sessionId, draft.session.resumeToken);
|
||||
removeResumableSession(draft.session.sessionId);
|
||||
resetFreshUploadState();
|
||||
}
|
||||
|
||||
function resumeRecoveredDraft() {
|
||||
if (!recoveredDraft) {
|
||||
return;
|
||||
}
|
||||
resumeMode = true;
|
||||
selectedFiles = [];
|
||||
renderResumeQueue(recoveredDraft.session, selectedFiles);
|
||||
updateSelectedState();
|
||||
updateNewUploadVisibility();
|
||||
updateStatus("Drop or reselect missing files to continue. Extra files will be added to this upload.");
|
||||
}
|
||||
|
||||
function resetFreshUploadState() {
|
||||
selectedFiles = [];
|
||||
resumeMode = false;
|
||||
recoveredDraft = null;
|
||||
fileInput.value = "";
|
||||
result.hidden = true;
|
||||
if (resultList) {
|
||||
resultList.replaceChildren();
|
||||
}
|
||||
setTotalProgress(0);
|
||||
updateStatus("");
|
||||
updateSelectedState();
|
||||
}
|
||||
|
||||
function uploadedBytesForSessionFile(file, chunkSize) {
|
||||
return (file.uploadedChunks || []).reduce((sum, index) => {
|
||||
const start = index * chunkSize;
|
||||
const end = Math.min(file.size, start + chunkSize);
|
||||
return sum + Math.max(0, end - start);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function renderRecoveredQueue(items) {
|
||||
if (!uploadQueue) {
|
||||
return;
|
||||
}
|
||||
const rows = [];
|
||||
items.forEach(({ session }) => {
|
||||
(session.files || []).forEach((file) => {
|
||||
const uploadedBytes = uploadedBytesForSessionFile(file, session.chunkSize);
|
||||
const complete = (file.uploadedChunks || []).length >= file.chunkCount;
|
||||
rows.push({
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
uploadedBytes,
|
||||
meta: complete
|
||||
? `${window.Warpbox.formatBytes(file.size)} · uploaded`
|
||||
: `${window.Warpbox.formatBytes(uploadedBytes)} of ${window.Warpbox.formatBytes(file.size)} · Drop/reselect this file to continue`,
|
||||
progress: percentForBytes(uploadedBytes, file.size),
|
||||
status: complete ? "complete" : "waiting",
|
||||
readonly: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
uploadQueue.hidden = rows.length === 0;
|
||||
uploadQueue.replaceChildren();
|
||||
rows.forEach((row) => uploadQueue.append(createFileRow(row)));
|
||||
const totalBytes = rows.reduce((sum, row) => sum + (row.size || 0), 0);
|
||||
if (totalBytes > 0) {
|
||||
setTotalProgress(percentForBytes(rows.reduce((sum, row) => sum + (row.uploadedBytes || 0), 0), totalBytes));
|
||||
} else if (rows.length > 0) {
|
||||
const completed = rows.filter((row) => row.status === "complete").length;
|
||||
setTotalProgress(percentForBytes(completed, rows.length));
|
||||
}
|
||||
}
|
||||
|
||||
function renderResumeQueue(session, localFiles) {
|
||||
if (!uploadQueue) {
|
||||
return;
|
||||
}
|
||||
const rows = [];
|
||||
const localByNameSize = new Map();
|
||||
(localFiles || []).forEach((file, index) => {
|
||||
localByNameSize.set(`${file.name}:${file.size}`, { file, index });
|
||||
});
|
||||
const usedLocalIndexes = new Set();
|
||||
(session.files || []).forEach((file) => {
|
||||
const uploadedBytes = uploadedBytesForSessionFile(file, session.chunkSize);
|
||||
const complete = (file.uploadedChunks || []).length >= file.chunkCount;
|
||||
const localMatch = localByNameSize.get(`${file.name}:${file.size}`) || null;
|
||||
if (localMatch) {
|
||||
usedLocalIndexes.add(localMatch.index);
|
||||
}
|
||||
rows.push({
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
uploadedBytes,
|
||||
meta: complete
|
||||
? `${window.Warpbox.formatBytes(file.size)} · uploaded`
|
||||
: localMatch
|
||||
? `${window.Warpbox.formatBytes(uploadedBytes)} of ${window.Warpbox.formatBytes(file.size)} · ready to resume`
|
||||
: `${window.Warpbox.formatBytes(uploadedBytes)} of ${window.Warpbox.formatBytes(file.size)} · waiting for local file`,
|
||||
progress: percentForBytes(uploadedBytes, file.size),
|
||||
status: complete ? "complete" : localMatch ? "queued" : "waiting",
|
||||
readonly: !localMatch,
|
||||
index: localMatch ? localMatch.index : undefined,
|
||||
removable: Boolean(localMatch && !complete),
|
||||
});
|
||||
});
|
||||
(localFiles || []).forEach((file, index) => {
|
||||
if (usedLocalIndexes.has(index)) {
|
||||
return;
|
||||
}
|
||||
rows.push({
|
||||
name: file.name,
|
||||
meta: `${window.Warpbox.formatBytes(file.size)} · new file`,
|
||||
progress: 0,
|
||||
status: "queued",
|
||||
index,
|
||||
removable: true,
|
||||
});
|
||||
});
|
||||
uploadQueue.hidden = rows.length === 0;
|
||||
uploadQueue.replaceChildren();
|
||||
rows.forEach((row) => uploadQueue.append(createFileRow(row)));
|
||||
}
|
||||
|
||||
function percentForBytes(bytes, total) {
|
||||
if (!total) {
|
||||
return 100;
|
||||
}
|
||||
return Math.max(0, Math.min(100, Math.round((bytes / total) * 100)));
|
||||
}
|
||||
|
||||
function renderQueue(files, status) {
|
||||
if (!uploadQueue) {
|
||||
return;
|
||||
}
|
||||
uploadQueue.hidden = files.length === 0;
|
||||
uploadQueue.replaceChildren();
|
||||
files.forEach((file) => {
|
||||
files.forEach((file, index) => {
|
||||
uploadQueue.append(createFileRow({
|
||||
name: file.name,
|
||||
meta: window.Warpbox.formatBytes(file.size),
|
||||
progress: status === "queued" ? 0 : 100,
|
||||
status,
|
||||
index,
|
||||
removable: status === "queued",
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
function createFileRow(file) {
|
||||
const row = document.createElement("div");
|
||||
row.className = "result-item upload-file-row";
|
||||
row.className = `result-item upload-file-row upload-file-${file.status || "queued"}`;
|
||||
row.dataset.fileName = file.name;
|
||||
if (typeof file.index === "number") {
|
||||
row.dataset.fileIndex = file.index;
|
||||
}
|
||||
|
||||
const body = document.createElement("span");
|
||||
const name = document.createElement("strong");
|
||||
@@ -242,11 +959,53 @@
|
||||
fill.style.transform = `scaleX(${file.progress / 100})`;
|
||||
bar.append(fill);
|
||||
side.append(percent, bar);
|
||||
if (file.status === "waiting") {
|
||||
const badge = document.createElement("small");
|
||||
badge.className = "upload-file-state";
|
||||
badge.textContent = "Needs local file";
|
||||
side.append(badge);
|
||||
}
|
||||
if (file.removable) {
|
||||
const remove = document.createElement("button");
|
||||
remove.className = "upload-file-remove";
|
||||
remove.type = "button";
|
||||
remove.setAttribute("aria-label", `Remove ${file.name}`);
|
||||
remove.textContent = "×";
|
||||
remove.addEventListener("click", () => removeSelectedFile(file.index || 0));
|
||||
side.append(remove);
|
||||
}
|
||||
|
||||
row.append(body, side);
|
||||
return row;
|
||||
}
|
||||
|
||||
function uploadFormData() {
|
||||
const formData = new FormData(form);
|
||||
formData.delete("file");
|
||||
selectedFiles.forEach((file) => {
|
||||
formData.append("file", file, file.name);
|
||||
});
|
||||
return formData;
|
||||
}
|
||||
|
||||
function fileIdentity(file) {
|
||||
return [file.name, file.size, file.lastModified || 0].join(":");
|
||||
}
|
||||
|
||||
async function fileFingerprint(file) {
|
||||
if (!window.crypto || !window.crypto.subtle || !file.slice || typeof TextEncoder === "undefined") {
|
||||
return fileIdentity(file);
|
||||
}
|
||||
const sampleSize = Math.min(file.size, 1024 * 1024);
|
||||
const sample = await file.slice(0, sampleSize).arrayBuffer();
|
||||
const metadata = new TextEncoder().encode([file.name, file.size, file.lastModified || 0, sampleSize].join(":"));
|
||||
const combined = new Uint8Array(metadata.byteLength + sample.byteLength);
|
||||
combined.set(metadata, 0);
|
||||
combined.set(new Uint8Array(sample), metadata.byteLength);
|
||||
const digest = await window.crypto.subtle.digest("SHA-256", combined);
|
||||
return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
function setTotalProgress(percent) {
|
||||
if (totalProgressBar) {
|
||||
totalProgressBar.style.transform = `scaleX(${Math.max(0, Math.min(100, percent)) / 100})`;
|
||||
@@ -271,4 +1030,23 @@
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setSingleFileProgress(index, file, progress) {
|
||||
if (!uploadQueue) {
|
||||
return;
|
||||
}
|
||||
const row = uploadQueue.querySelector(`.upload-file-row[data-file-index="${index}"]`);
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
const percent = row.querySelector(".file-progress-percent");
|
||||
const fill = row.querySelector(".file-progress span");
|
||||
const normalized = Math.max(0, Math.min(100, progress));
|
||||
if (percent) {
|
||||
percent.textContent = `${normalized}%`;
|
||||
}
|
||||
if (fill) {
|
||||
fill.style.transform = `scaleX(${normalized / 100})`;
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -15,23 +15,28 @@
|
||||
{{if .ImageURL}}<meta property="og:image" content="{{.ImageURL}}">{{end}}
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
{{if .ImageURL}}<meta name="twitter:image" content="{{.ImageURL}}">{{end}}
|
||||
<script src="/static/js/05-theme.js"></script>
|
||||
<link rel="stylesheet" href="/static/css/00-base.css">
|
||||
<link rel="stylesheet" href="/static/css/10-layout.css">
|
||||
<link rel="stylesheet" href="/static/css/15-revamp.css">
|
||||
<link rel="stylesheet" href="/static/css/16-retro.css">
|
||||
<link rel="stylesheet" href="/static/css/20-upload.css">
|
||||
<link rel="stylesheet" href="/static/css/30-download.css">
|
||||
<link rel="stylesheet" href="/static/css/40-docs.css">
|
||||
<link rel="stylesheet" href="/static/css/50-admin.css">
|
||||
<link rel="stylesheet" href="/static/css/60-storage.css">
|
||||
<link rel="stylesheet" href="/static/css/70-tokens.css">
|
||||
<link rel="stylesheet" href="/static/css/90-responsive.css">
|
||||
<script defer src="/static/js/00-utils.js"></script>
|
||||
<script defer src="/static/js/10-file-browser.js"></script>
|
||||
<script defer src="/static/js/20-storage-admin.js"></script>
|
||||
<script defer src="/static/js/30-token-copy.js"></script>
|
||||
<script defer src="/static/js/40-upload.js"></script>
|
||||
<script src="/static/js/05-theme.js?version={{.AppVersion}}"></script>
|
||||
<link rel="stylesheet" href="/static/css/00-base.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/10-layout.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/15-revamp.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/16-retro.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/17-gruvbox.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/18-cyberpunk.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/20-upload.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/30-download.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/40-docs.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/50-admin.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/60-storage.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/70-tokens.css?version={{.AppVersion}}">
|
||||
<link rel="stylesheet" href="/static/css/90-responsive.css?version={{.AppVersion}}">
|
||||
<script defer src="/static/js/00-utils.js?version={{.AppVersion}}"></script>
|
||||
<script defer src="/static/js/10-file-browser.js?version={{.AppVersion}}"></script>
|
||||
<script defer src="/static/js/12-reactions.js?version={{.AppVersion}}"></script>
|
||||
<script defer src="/static/js/20-storage-admin.js?version={{.AppVersion}}"></script>
|
||||
<script defer src="/static/js/25-admin-charts.js?version={{.AppVersion}}"></script>
|
||||
<script defer src="/static/js/30-token-copy.js?version={{.AppVersion}}"></script>
|
||||
<script defer src="/static/js/35-pagination.js?version={{.AppVersion}}"></script>
|
||||
<script defer src="/static/js/40-upload.js?version={{.AppVersion}}"></script>
|
||||
</head>
|
||||
<body class="dark">
|
||||
<a class="skip-link" href="#main">Skip to content</a>
|
||||
@@ -60,13 +65,15 @@
|
||||
</main>
|
||||
|
||||
<footer class="site-footer">
|
||||
<span>{{.AppName}} · {{.AppVersion}} · {{.CurrentYear}} · self-hosted</span>
|
||||
<span>{{.AppName}} · {{.AppVersion}} · {{.CurrentYear}}</span>
|
||||
<label class="theme-picker">
|
||||
<span>Theme</span>
|
||||
<select data-theme-select aria-label="Site theme">
|
||||
<option value="revamp">Aurora (default)</option>
|
||||
<option value="classic">Classic</option>
|
||||
<option value="retro">Web 1.0 (retro)</option>
|
||||
<option value="gruvbox">Gruvbox</option>
|
||||
<option value="cyberpunk">CyberPunk</option>
|
||||
</select>
|
||||
</label>
|
||||
<span class="footer-links">{{if .CurrentUser}}<a href="/app">Dashboard</a><a href="/api">API</a><a href="/account/settings">Account</a>{{else}}<a href="/login">Sign in</a><a href="/api">API</a>{{end}}</span>
|
||||
|
||||
@@ -58,6 +58,55 @@
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div class="admin-charts">
|
||||
<div class="card chart-card">
|
||||
<div class="card-content">
|
||||
<h2>Uploads per day</h2>
|
||||
<p class="muted-copy">New boxes created over the last 14 days.</p>
|
||||
<div class="bar-chart" role="img" aria-label="Uploads per day for the last 14 days">
|
||||
{{range .Data.Overview.UploadDays}}
|
||||
<div class="bar-chart-col" title="{{.Label}}: {{.Value}}" data-chart-value="{{.RawValue}}">
|
||||
<span class="bar-chart-value">{{.Value}}</span>
|
||||
<span class="bar-chart-track"><span class="bar-chart-bar" data-height-px="{{.HeightPx}}" style="height: {{.HeightPx}}px"></span></span>
|
||||
<span class="bar-chart-label">{{.Label}}</span>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card chart-card">
|
||||
<div class="card-content">
|
||||
<h2>Box status</h2>
|
||||
<p class="muted-copy">Share of all {{.Data.Stats.TotalBoxes}} boxes.</p>
|
||||
<div class="stat-bars">
|
||||
{{range .Data.Overview.StatusBars}}
|
||||
<div class="stat-bar" data-stat-value="{{.RawValue}}">
|
||||
<span>{{.Label}} <strong>{{.Value}}</strong></span>
|
||||
<span class="stat-bar-track"><span class="stat-bar-fill" data-width-percent="{{.WidthPercent}}" style="width: {{.WidthPercent}}%"></span></span>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card chart-card">
|
||||
<div class="card-content">
|
||||
<h2>Storage added per day</h2>
|
||||
<p class="muted-copy">Bytes uploaded over the last 14 days.</p>
|
||||
<div class="bar-chart" role="img" aria-label="Storage added per day for the last 14 days">
|
||||
{{range .Data.Overview.StorageDays}}
|
||||
<div class="bar-chart-col" title="{{.Label}}: {{.Value}}" data-chart-value="{{.RawValue}}">
|
||||
<span class="bar-chart-value">{{.Value}}</span>
|
||||
<span class="bar-chart-track"><span class="bar-chart-bar" data-height-px="{{.HeightPx}}" style="height: {{.HeightPx}}px"></span></span>
|
||||
<span class="bar-chart-label">{{.Label}}</span>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card admin-table-card">
|
||||
<div class="card-content">
|
||||
<div class="table-header">
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
{{if .Data.Bans.Notice}}<div class="notice">{{.Data.Bans.Notice}}</div>{{end}}
|
||||
{{if .Data.Bans.Error}}<div class="notice notice-error">{{.Data.Bans.Error}}</div>{{end}}
|
||||
|
||||
<div class="metric-grid">
|
||||
<div class="metric-grid metric-grid-4">
|
||||
<article class="metric-card"><span>Active bans</span><strong>{{.Data.Bans.ActiveCount}}</strong></article>
|
||||
<article class="metric-card"><span>Expired</span><strong>{{.Data.Bans.ExpiredCount}}</strong></article>
|
||||
<article class="metric-card"><span>Unbanned</span><strong>{{.Data.Bans.UnbannedCount}}</strong></article>
|
||||
|
||||
131
backend/templates/pages/admin_box_edit.html
Normal file
@@ -0,0 +1,131 @@
|
||||
{{define "admin_box_edit.html"}}{{template "base" .}}{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
<section class="app-shell admin-shell" aria-labelledby="admin-box-edit-title">
|
||||
<aside class="app-sidebar">
|
||||
<nav class="sidebar-nav">
|
||||
<a class="sidebar-link" href="/admin">{{template "icon-dashboard" .}}<span>Overview</span></a>
|
||||
<a class="sidebar-link is-active" href="/admin/files">{{template "icon-folder" .}}<span>Files</span></a>
|
||||
<a class="sidebar-link" href="/admin/users">{{template "icon-user-circle" .}}<span>Users</span></a>
|
||||
<a class="sidebar-link" href="/admin/settings">{{template "icon-settings" .}}<span>Settings</span></a>
|
||||
<a class="sidebar-link" href="/admin/storage">{{template "icon-database" .}}<span>Storage</span></a>
|
||||
<a class="sidebar-link" href="/admin/logs">{{template "icon-database" .}}<span>Logs</span></a>
|
||||
<a class="sidebar-link" href="/admin/bans">{{template "icon-settings" .}}<span>Bans</span></a>
|
||||
</nav>
|
||||
<hr class="sidebar-sep">
|
||||
<nav class="sidebar-nav">
|
||||
<a class="sidebar-link" href="/app">{{template "icon-home-simple" .}}<span>My Files</span></a>
|
||||
</nav>
|
||||
<hr class="sidebar-sep">
|
||||
<form class="sidebar-logout" action="/admin/logout" method="post">
|
||||
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
|
||||
<button class="button button-outline" type="submit">{{template "icon-log-out" .}}<span>Sign out</span></button>
|
||||
</form>
|
||||
</aside>
|
||||
|
||||
<div class="app-main">
|
||||
<div class="admin-header">
|
||||
<div>
|
||||
<p class="kicker">Operator console · <a href="/admin/files">Files</a></p>
|
||||
<h1 id="admin-box-edit-title">{{.Data.PageTitle}}</h1>
|
||||
<p class="muted-copy">Box <code>{{.Data.Box.ID}}</code> · {{.Data.Box.Owner}}</p>
|
||||
</div>
|
||||
<a class="button button-outline" href="/admin/boxes/{{.Data.Box.ID}}/view">Open box</a>
|
||||
</div>
|
||||
|
||||
{{if .Data.Notice}}<p class="form-success">{{.Data.Notice}}</p>{{end}}
|
||||
{{if .Data.Error}}<p class="form-error">{{.Data.Error}}</p>{{end}}
|
||||
|
||||
<div class="card admin-table-card">
|
||||
<div class="card-content">
|
||||
<div class="table-header">
|
||||
<div>
|
||||
<h2>Box settings</h2>
|
||||
<p>Change expiration, download limit, and protection.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<dl class="manage-details">
|
||||
<div><dt>Created</dt><dd>{{.Data.Box.CreatedAt}}</dd></div>
|
||||
<div><dt>Files</dt><dd>{{.Data.Box.FileCount}}</dd></div>
|
||||
<div><dt>Total size</dt><dd>{{.Data.Box.TotalSize}}</dd></div>
|
||||
<div><dt>Downloads</dt><dd>{{.Data.Box.DownloadCount}}{{if .Data.Box.MaxDownloads}} / {{.Data.Box.MaxDownloads}}{{end}}</dd></div>
|
||||
<div><dt>Expires</dt><dd>{{.Data.Box.ExpiresLabel}}</dd></div>
|
||||
<div><dt>Storage backend</dt><dd>{{.Data.Box.BackendID}}</dd></div>
|
||||
<div><dt>Protected</dt><dd>{{if .Data.Box.Protected}}Yes{{else}}No{{end}}</dd></div>
|
||||
</dl>
|
||||
|
||||
<form class="settings-form settings-form-narrow" action="/admin/boxes/{{.Data.Box.ID}}/edit" method="post">
|
||||
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
|
||||
<label>
|
||||
<span>Expires at (UTC)</span>
|
||||
<input type="datetime-local" name="expires_at" value="{{.Data.Box.ExpiresInput}}">
|
||||
</label>
|
||||
<label class="checkbox-field">
|
||||
<input type="checkbox" name="never_expires" {{if .Data.Box.NeverExpires}}checked{{end}}>
|
||||
<span>Never expires (overrides the date above)</span>
|
||||
</label>
|
||||
<label>
|
||||
<span>Max downloads (0 = unlimited)</span>
|
||||
<input type="number" min="0" name="max_downloads" value="{{.Data.Box.MaxDownloads}}">
|
||||
</label>
|
||||
{{if .Data.Box.Protected}}
|
||||
<label class="checkbox-field">
|
||||
<input type="checkbox" name="remove_password">
|
||||
<span>Remove password protection</span>
|
||||
</label>
|
||||
{{end}}
|
||||
<button class="button button-primary" type="submit">Save changes</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card admin-table-card">
|
||||
<div class="card-content">
|
||||
<div class="table-header">
|
||||
<div>
|
||||
<h2>Files</h2>
|
||||
<p>Remove individual files from this box. Removing the last file deletes the box.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="result-list">
|
||||
{{range .Data.Files}}
|
||||
<article class="download-item">
|
||||
{{if .HasPreview}}<a class="thumb-link" href="{{.DownloadURL}}?inline=1" target="_blank" rel="noopener noreferrer"><img src="{{.ThumbnailURL}}" alt="" loading="lazy"></a>{{end}}
|
||||
<a class="file-main" href="{{.DownloadURL}}?inline=1" target="_blank" rel="noopener noreferrer">
|
||||
<strong class="file-name" title="{{.Name}}">{{.Name}}</strong>
|
||||
<small>{{.Size}} · {{.ContentType}}</small>
|
||||
</a>
|
||||
<div class="file-actions">
|
||||
<a class="button button-outline button-sm" href="{{.DownloadURL}}" download="{{.Name}}">Download</a>
|
||||
<form action="/admin/boxes/{{$.Data.Box.ID}}/files/{{.ID}}/delete" method="post">
|
||||
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
|
||||
<button class="button button-danger button-sm" type="submit">Remove</button>
|
||||
</form>
|
||||
</div>
|
||||
</article>
|
||||
{{else}}
|
||||
<p class="muted-copy">This box has no files.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card admin-table-card">
|
||||
<div class="card-content">
|
||||
<div class="table-header">
|
||||
<div>
|
||||
<h2>Danger zone</h2>
|
||||
<p>Permanently delete this box and all of its files.</p>
|
||||
</div>
|
||||
<form action="/admin/boxes/{{.Data.Box.ID}}/delete" method="post">
|
||||
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
|
||||
<button class="button button-danger" type="submit">Delete box</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{{end}}
|
||||
114
backend/templates/pages/admin_files.html
Normal file
@@ -0,0 +1,114 @@
|
||||
{{define "admin_files.html"}}{{template "base" .}}{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
<section class="app-shell admin-shell" aria-labelledby="admin-files-title">
|
||||
<aside class="app-sidebar">
|
||||
<nav class="sidebar-nav">
|
||||
<a class="sidebar-link" href="/admin">{{template "icon-dashboard" .}}<span>Overview</span></a>
|
||||
<a class="sidebar-link is-active" href="/admin/files">{{template "icon-folder" .}}<span>Files</span></a>
|
||||
<a class="sidebar-link" href="/admin/users">{{template "icon-user-circle" .}}<span>Users</span></a>
|
||||
<a class="sidebar-link" href="/admin/settings">{{template "icon-settings" .}}<span>Settings</span></a>
|
||||
<a class="sidebar-link" href="/admin/storage">{{template "icon-database" .}}<span>Storage</span></a>
|
||||
<a class="sidebar-link" href="/admin/logs">{{template "icon-database" .}}<span>Logs</span></a>
|
||||
<a class="sidebar-link" href="/admin/bans">{{template "icon-settings" .}}<span>Bans</span></a>
|
||||
</nav>
|
||||
<hr class="sidebar-sep">
|
||||
<nav class="sidebar-nav">
|
||||
<a class="sidebar-link" href="/app">{{template "icon-home-simple" .}}<span>My Files</span></a>
|
||||
</nav>
|
||||
<hr class="sidebar-sep">
|
||||
<form class="sidebar-logout" action="/admin/logout" method="post">
|
||||
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
|
||||
<button class="button button-outline" type="submit">{{template "icon-log-out" .}}<span>Sign out</span></button>
|
||||
</form>
|
||||
</aside>
|
||||
|
||||
<div class="app-main">
|
||||
<div class="admin-header">
|
||||
<div>
|
||||
<p class="kicker">Operator console</p>
|
||||
<h1 id="admin-files-title">{{.Data.PageTitle}}</h1>
|
||||
<p class="muted-copy">{{.Data.Total}} box{{if ne .Data.Total 1}}es{{end}} total.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card admin-table-card">
|
||||
<div class="card-content">
|
||||
<div class="table-header">
|
||||
<div>
|
||||
<h2>All uploads</h2>
|
||||
<p>Search, sort, and manage every box.</p>
|
||||
</div>
|
||||
<form class="inline-controls" method="get" action="/admin/files">
|
||||
<input type="hidden" name="sort" value="{{.Data.Sort}}">
|
||||
<input type="hidden" name="dir" value="{{.Data.Dir}}">
|
||||
<input type="hidden" name="per" value="{{.Data.PerPage}}">
|
||||
<label>
|
||||
<span class="sr-only">Search</span>
|
||||
<input type="search" name="q" value="{{.Data.Query}}" placeholder="Search box id or owner">
|
||||
</label>
|
||||
<button class="button button-primary button-sm" type="submit">Search</button>
|
||||
{{if .Data.Query}}<a class="button button-outline button-sm" href="/admin/files">Clear</a>{{end}}
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{{range .Data.Columns}}
|
||||
<th><a class="sort-link {{if .Sorted}}is-sorted{{end}}" href="{{.Href}}">{{.Label}}{{if .Sorted}}<span class="sort-arrow" aria-hidden="true">{{if .Ascending}}▲{{else}}▼{{end}}</span>{{end}}</a></th>
|
||||
{{end}}
|
||||
<th>Status</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{range .Data.Boxes}}
|
||||
<tr>
|
||||
<td><a href="/admin/boxes/{{.ID}}/edit"><code>{{.ID}}</code></a></td>
|
||||
<td>{{.Owner}}</td>
|
||||
<td>{{.FileCount}}</td>
|
||||
<td>{{.TotalSizeLabel}}</td>
|
||||
<td>{{.DownloadCount}}{{if .MaxDownloads}} / {{.MaxDownloads}}{{end}}</td>
|
||||
<td>{{.CreatedAt}}</td>
|
||||
<td>{{.ExpiresAt}}</td>
|
||||
<td>
|
||||
{{if .Expired}}<span class="badge">expired</span>{{else}}<span class="badge">active</span>{{end}}
|
||||
{{if .Protected}}<span class="badge">protected</span>{{end}}
|
||||
</td>
|
||||
<td class="table-actions">
|
||||
<a class="button button-primary button-sm" href="/admin/boxes/{{.ID}}/edit">Edit</a>
|
||||
<a class="button button-outline button-sm" href="/admin/boxes/{{.ID}}/view">View</a>
|
||||
<form action="/admin/boxes/{{.ID}}/delete" method="post">
|
||||
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
|
||||
<button class="button button-danger button-sm" type="submit">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{{else}}
|
||||
<tr><td colspan="9">No boxes match.</td></tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pagination-bar">
|
||||
<nav class="pagination" aria-label="Pagination">
|
||||
{{if .Data.HasPrev}}<a class="button button-outline button-sm" href="{{.Data.PrevHref}}">← Prev</a>{{else}}<span class="button button-outline button-sm is-disabled" aria-disabled="true">← Prev</span>{{end}}
|
||||
{{range .Data.PageLinks}}<a class="button button-sm {{if .Active}}is-active{{else}}button-outline{{end}}" href="{{.Href}}">{{.Page}}</a>{{end}}
|
||||
{{if .Data.HasNext}}<a class="button button-outline button-sm" href="{{.Data.NextHref}}">Next →</a>{{else}}<span class="button button-outline button-sm is-disabled" aria-disabled="true">Next →</span>{{end}}
|
||||
</nav>
|
||||
<label class="per-page-control">
|
||||
<span>Per page</span>
|
||||
<select data-per-page="files" aria-label="Items per page">
|
||||
{{range .Data.PerPageOptions}}<option value="{{.}}" {{if eq . $.Data.PerPage}}selected{{end}}>{{.}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<p class="pagination-summary">Showing {{.Data.RangeFrom}}–{{.Data.RangeTo}} of {{.Data.Total}} · Page {{.Data.Page}} of {{.Data.TotalPages}}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{{end}}
|
||||
@@ -54,6 +54,7 @@
|
||||
<option value="asc" {{if eq .Data.Logs.Sort "asc"}}selected{{end}}>Oldest first</option>
|
||||
</select>
|
||||
</label>
|
||||
<input type="hidden" name="per" value="{{.Data.Logs.PerPage}}">
|
||||
<button class="button button-primary" type="submit">Filter</button>
|
||||
</form>
|
||||
|
||||
@@ -62,7 +63,7 @@
|
||||
<div class="table-header">
|
||||
<div>
|
||||
<h2>Log entries</h2>
|
||||
<p>Showing up to 500 entries. {{.Data.Logs.TotalShown}} currently visible.</p>
|
||||
<p>{{.Data.Logs.Total}} entries match these filters.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-table-wrap">
|
||||
@@ -98,6 +99,21 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pagination-bar">
|
||||
<nav class="pagination" aria-label="Pagination">
|
||||
{{if .Data.Logs.HasPrev}}<a class="button button-outline button-sm" href="{{.Data.Logs.PrevHref}}">← Prev</a>{{else}}<span class="button button-outline button-sm is-disabled" aria-disabled="true">← Prev</span>{{end}}
|
||||
{{range .Data.Logs.PageLinks}}<a class="button button-sm {{if .Active}}is-active{{else}}button-outline{{end}}" href="{{.Href}}">{{.Page}}</a>{{end}}
|
||||
{{if .Data.Logs.HasNext}}<a class="button button-outline button-sm" href="{{.Data.Logs.NextHref}}">Next →</a>{{else}}<span class="button button-outline button-sm is-disabled" aria-disabled="true">Next →</span>{{end}}
|
||||
</nav>
|
||||
<label class="per-page-control">
|
||||
<span>Per page</span>
|
||||
<select data-per-page="logs" aria-label="Items per page">
|
||||
{{range .Data.Logs.PerPageOptions}}<option value="{{.}}" {{if eq . $.Data.Logs.PerPage}}selected{{end}}>{{.}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<p class="pagination-summary">Showing {{.Data.Logs.RangeFrom}}–{{.Data.Logs.RangeTo}} of {{.Data.Logs.Total}} · Page {{.Data.Logs.Page}} of {{.Data.Logs.TotalPages}}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -126,6 +126,33 @@
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="settings-section">
|
||||
<h3 class="settings-section-title">Resumable uploads</h3>
|
||||
<label class="checkbox-field">
|
||||
<input type="checkbox" name="resumable_uploads_enabled" {{if .Data.Settings.ResumableUploadsEnabled}}checked{{end}}>
|
||||
<span>Enable browser/API resumable uploads</span>
|
||||
</label>
|
||||
<label>
|
||||
<span>Chunk size (MB)</span>
|
||||
<input name="resumable_chunk_size_mb" value="{{.Data.Settings.ResumableChunkSizeMB}}" required>
|
||||
</label>
|
||||
<label>
|
||||
<span>Draft retention (hours)</span>
|
||||
<input type="number" name="resumable_retention_hours" min="1" value="{{.Data.Settings.ResumableRetentionHours}}" required>
|
||||
</label>
|
||||
<label>
|
||||
<span>Chunk storage</span>
|
||||
<select name="resumable_chunk_mode" required>
|
||||
<option value="same" {{if eq .Data.Settings.ResumableChunkMode "same"}}selected{{end}}>Default local data path</option>
|
||||
<option value="custom" {{if eq .Data.Settings.ResumableChunkMode "custom"}}selected{{end}}>Custom local path, e.g. fast SSD</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>Custom chunk path</span>
|
||||
<input name="resumable_chunk_path" value="{{.Data.Settings.ResumableChunkPath}}" placeholder="/mnt/fast-ssd/warpbox-chunks">
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button class="button button-primary" type="submit">Save settings</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||