Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 17c31be8b4 | |||
| 313c89483c | |||
| 5cd476e7f3 | |||
| d3b6a86753 | |||
| cf5d8bb50d | |||
| 8e3f783780 | |||
| 6c87187c6d |
@@ -9,6 +9,11 @@ WARPBOX_CLEANUP_ENABLED=true
|
|||||||
WARPBOX_CLEANUP_EVERY=1h
|
WARPBOX_CLEANUP_EVERY=1h
|
||||||
WARPBOX_THUMBNAIL_ENABLED=true
|
WARPBOX_THUMBNAIL_ENABLED=true
|
||||||
WARPBOX_THUMBNAIL_EVERY=1m
|
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_MAX_UPLOAD_SIZE_MB=16384
|
||||||
WARPBOX_ANONYMOUS_UPLOADS_ENABLED=true
|
WARPBOX_ANONYMOUS_UPLOADS_ENABLED=true
|
||||||
WARPBOX_ANONYMOUS_MAX_UPLOAD_MB=512
|
WARPBOX_ANONYMOUS_MAX_UPLOAD_MB=512
|
||||||
|
|||||||
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.
|
||||||
342
README.md
@@ -1,6 +1,20 @@
|
|||||||
# Warpbox.dev
|
# 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
|
## 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`.
|
The default server listens on `:8080`.
|
||||||
|
|
||||||
Upload size limits are configured in megabytes through `WARPBOX_MAX_UPLOAD_SIZE_MB`.
|
For one off Go commands, run them from the backend module:
|
||||||
Fractions are supported, so `0.5Mb` is 512 KiB and `1.5Mb` is 1536 KiB.
|
|
||||||
|
|
||||||
Upload policy defaults are also configured in megabytes and can later be changed from
|
```bash
|
||||||
`/admin/settings`:
|
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_UPLOADS_ENABLED=true`
|
||||||
- `WARPBOX_ANONYMOUS_MAX_UPLOAD_MB=512`
|
- `WARPBOX_ANONYMOUS_MAX_UPLOAD_MB=512`
|
||||||
@@ -33,32 +61,150 @@ Upload policy defaults are also configured in megabytes and can later be changed
|
|||||||
- `WARPBOX_SHORT_WINDOW_SECONDS=60`
|
- `WARPBOX_SHORT_WINDOW_SECONDS=60`
|
||||||
- `WARPBOX_ANONYMOUS_STORAGE_BACKEND=local`
|
- `WARPBOX_ANONYMOUS_STORAGE_BACKEND=local`
|
||||||
- `WARPBOX_USER_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.
|
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.
|
The dev script resolves that path from the repository root.
|
||||||
|
|
||||||
Large uploads are expected to take minutes on normal home/server connections. Keep
|
### Background jobs
|
||||||
`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.
|
|
||||||
|
|
||||||
Background jobs are enabled with `WARPBOX_JOBS_ENABLED=true`. Individual jobs can be toggled with
|
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_ENABLED` and `WARPBOX_THUMBNAIL_ENABLED`, and their schedules are configured with
|
||||||
`WARPBOX_CLEANUP_EVERY` and `WARPBOX_THUMBNAIL_EVERY`.
|
`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
|
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
|
the instance admin and normal registration closes after bootstrap. Admins can create copyable invite
|
||||||
links from `/admin/users`.
|
links from `/admin/users`.
|
||||||
|
|
||||||
The env admin token still exists as emergency fallback access. Set `WARPBOX_ADMIN_TOKEN` and use it
|
The env admin token exists as emergency fallback access. Set `WARPBOX_ADMIN_TOKEN` and use it at
|
||||||
at `/admin/login` if you need to recover access without a user session.
|
`/admin/login` if you need to recover access without a user session.
|
||||||
|
|
||||||
|
## 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
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
## 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
|
## Emoji reaction packs
|
||||||
|
|
||||||
File reactions use emoji packs from the runtime data directory, not from the application code. By
|
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
|
default that means `./data/emoji`; if you change `WARPBOX_DATA_DIR`, use `$WARPBOX_DATA_DIR/emoji`
|
||||||
`$WARPBOX_DATA_DIR/emoji` instead.
|
instead.
|
||||||
|
|
||||||
Each folder under `./data/emoji` becomes one emoji tab in the reaction picker. Put image files
|
Each folder under `./data/emoji` becomes one emoji tab in the reaction picker. Put image files
|
||||||
directly inside the pack folder:
|
directly inside the pack folder:
|
||||||
@@ -69,35 +215,30 @@ data/
|
|||||||
├── files/
|
├── files/
|
||||||
├── logs/
|
├── logs/
|
||||||
└── emoji/
|
└── emoji/
|
||||||
├── openmoji/
|
├── openmoji/
|
||||||
│ ├── 1F600.svg
|
│ ├── 1F600.svg
|
||||||
│ ├── 1F44D.svg
|
│ ├── 1F44D.svg
|
||||||
│ └── 2764.svg
|
│ └── 2764.svg
|
||||||
├── pixel-pack/
|
├── pixel-pack/
|
||||||
│ ├── happy.webp
|
│ ├── happy.webp
|
||||||
│ ├── fire.webp
|
│ ├── fire.webp
|
||||||
│ └── star.webp
|
│ └── star.webp
|
||||||
└── custom-work/
|
└── custom-work/
|
||||||
├── approved.png
|
├── approved.png
|
||||||
└── shipped.png
|
└── shipped.png
|
||||||
```
|
```
|
||||||
|
|
||||||
In this example, the picker shows tabs named `Openmoji`, `Pixel pack`, and `Custom work`.
|
In this example, the picker shows tabs named `Openmoji`, `Pixel pack`, and `Custom work`. Supported
|
||||||
Supported emoji image extensions are `.svg`, `.webp`, `.png`, `.jpg`, `.jpeg`, and `.gif`.
|
emoji image extensions are `.svg`, `.webp`, `.png`, `.jpg`, `.jpeg`, and `.gif`.
|
||||||
|
|
||||||
For one-off Go commands, run them from the backend module:
|
## Deployment
|
||||||
|
|
||||||
```bash
|
### Docker / Podman
|
||||||
cd backend
|
|
||||||
go run ./cmd/warpbox
|
|
||||||
```
|
|
||||||
|
|
||||||
## Docker / Podman
|
|
||||||
|
|
||||||
Copy the example environment file and adjust values such as `WARPBOX_BASE_URL` and
|
Copy the example environment file and adjust values such as `WARPBOX_BASE_URL` and
|
||||||
`WARPBOX_ADMIN_TOKEN` before running the container:
|
`WARPBOX_ADMIN_TOKEN` before running the container. Copy the example
|
||||||
|
[docker-compose.example.yml](./docker-compose.example.yml) to
|
||||||
Copy the example [docker-compose.example.yml](./docker-compose.example.yml) to [docker-compose.yml](./docker-compose.yml), modify as need-be
|
[docker-compose.yml](./docker-compose.yml), modify as need-be:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
@@ -105,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
|
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:/data:Z` for SELinux relabeling, and the container overrides runtime paths to use `/data`,
|
||||||
`/data`, `/app/static`, and `/app/templates`.
|
`/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
|
### Reverse proxy security
|
||||||
use `/health`.
|
|
||||||
|
|
||||||
## Reverse Proxy Security
|
|
||||||
|
|
||||||
Warpbox uses the resolved client IP for anonymous limits, manual bans, and automatic bans. The
|
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
|
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
|
without extra setup. For hardened deployments where the app port might be reachable from more than one
|
||||||
one network, set `WARPBOX_TRUSTED_PROXIES` to trusted proxy IPs/CIDRs. See
|
network, set `WARPBOX_TRUSTED_PROXIES` to trusted proxy IPs/CIDRs. See
|
||||||
[SECURITY_PROXY.md](./SECURITY_PROXY.md) for Caddy examples and Docker/systemd notes.
|
[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:
|
Build the binary on the server, create a dedicated user, and keep runtime data outside the repo:
|
||||||
|
|
||||||
@@ -181,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.
|
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/cmd/warpbox` - main application entry point.
|
||||||
- `backend/libs/config` - environment-backed configuration.
|
- `backend/libs/config` - environment-backed configuration.
|
||||||
@@ -189,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/handlers` - HTTP handlers for pages, API, health, static files.
|
||||||
- `backend/libs/jobs` - background job registration and job loop definitions.
|
- `backend/libs/jobs` - background job registration and job loop definitions.
|
||||||
- `backend/libs/middleware` - request logging, recovery, security headers, gzip, request IDs.
|
- `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/helpers` - small reusable helpers.
|
||||||
- `backend/libs/web` - Go template renderer.
|
- `backend/libs/web` - Go template renderer.
|
||||||
- `backend/templates` - server-rendered Go templates.
|
- `backend/templates` - server-rendered Go templates.
|
||||||
@@ -198,92 +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.example` - tracked development environment template.
|
||||||
- `scripts/env/dev.env` - local development environment, ignored by git.
|
- `scripts/env/dev.env` - local development environment, ignored by git.
|
||||||
|
|
||||||
## Stage 2 Operator Tools
|
## Static asset policy
|
||||||
|
|
||||||
- `/admin/login` - token-based admin login.
|
The static handler sets long-lived immutable caching for images, video, audio, and fonts, shorter
|
||||||
- `/admin` - overview metrics: boxes, files, storage, recent uploads, protected/expired boxes.
|
caching for CSS/JS, and gzip compression for compressible responses.
|
||||||
- `/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, 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.
|
|
||||||
|
|
||||||
## 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.
|
|
||||||
|
|||||||
@@ -11,27 +11,30 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
AppName string
|
AppName string
|
||||||
AppVersion string
|
AppVersion string
|
||||||
Environment string
|
Environment string
|
||||||
Addr string
|
Addr string
|
||||||
BaseURL string
|
BaseURL string
|
||||||
DataDir string
|
DataDir string
|
||||||
AdminToken string
|
AdminToken string
|
||||||
StaticDir string
|
StaticDir string
|
||||||
TemplateDir string
|
TemplateDir string
|
||||||
ReadHeaderTimeout time.Duration
|
ReadHeaderTimeout time.Duration
|
||||||
ReadTimeout time.Duration
|
ReadTimeout time.Duration
|
||||||
WriteTimeout time.Duration
|
WriteTimeout time.Duration
|
||||||
IdleTimeout time.Duration
|
IdleTimeout time.Duration
|
||||||
TrustedProxies []string
|
TrustedProxies []string
|
||||||
JobsEnabled bool
|
JobsEnabled bool
|
||||||
CleanupEnabled bool
|
CleanupEnabled bool
|
||||||
CleanupEvery time.Duration
|
CleanupEvery time.Duration
|
||||||
ThumbnailEnabled bool
|
ThumbnailEnabled bool
|
||||||
ThumbnailEvery time.Duration
|
ThumbnailEvery time.Duration
|
||||||
MaxUploadSize int64
|
ResumableUploadsEnabled bool
|
||||||
DefaultSettings SettingsDefaults
|
ResumableChunkSize int64
|
||||||
|
ResumableRetention time.Duration
|
||||||
|
MaxUploadSize int64
|
||||||
|
DefaultSettings SettingsDefaults
|
||||||
}
|
}
|
||||||
|
|
||||||
type SettingsDefaults struct {
|
type SettingsDefaults struct {
|
||||||
@@ -52,30 +55,38 @@ type SettingsDefaults struct {
|
|||||||
ShortWindowSeconds int
|
ShortWindowSeconds int
|
||||||
AnonymousStorageBackend string
|
AnonymousStorageBackend string
|
||||||
UserStorageBackend string
|
UserStorageBackend string
|
||||||
|
ResumableUploadsEnabled bool
|
||||||
|
ResumableChunkSizeMB float64
|
||||||
|
ResumableRetentionHours int
|
||||||
|
ResumableChunkMode string
|
||||||
|
ResumableChunkPath string
|
||||||
}
|
}
|
||||||
|
|
||||||
func Load() (Config, error) {
|
func Load() (Config, error) {
|
||||||
cfg := Config{
|
cfg := Config{
|
||||||
AppName: envString("WARPBOX_APP_NAME", "warpbox.dev"),
|
AppName: envString("WARPBOX_APP_NAME", "warpbox.dev"),
|
||||||
AppVersion: envString("APP_VERSION", "dev"),
|
AppVersion: envString("APP_VERSION", "dev"),
|
||||||
Environment: envString("WARPBOX_ENV", "development"),
|
Environment: envString("WARPBOX_ENV", "development"),
|
||||||
Addr: envString("WARPBOX_ADDR", ":8080"),
|
Addr: envString("WARPBOX_ADDR", ":8080"),
|
||||||
BaseURL: strings.TrimRight(envString("WARPBOX_BASE_URL", "http://localhost:8080"), "/"),
|
BaseURL: strings.TrimRight(envString("WARPBOX_BASE_URL", "http://localhost:8080"), "/"),
|
||||||
DataDir: envString("WARPBOX_DATA_DIR", defaultPath("data")),
|
DataDir: envString("WARPBOX_DATA_DIR", defaultPath("data")),
|
||||||
AdminToken: envString("WARPBOX_ADMIN_TOKEN", ""),
|
AdminToken: envString("WARPBOX_ADMIN_TOKEN", ""),
|
||||||
StaticDir: envString("WARPBOX_STATIC_DIR", defaultPath("static")),
|
StaticDir: envString("WARPBOX_STATIC_DIR", defaultPath("static")),
|
||||||
TemplateDir: envString("WARPBOX_TEMPLATE_DIR", defaultPath("templates")),
|
TemplateDir: envString("WARPBOX_TEMPLATE_DIR", defaultPath("templates")),
|
||||||
ReadHeaderTimeout: envDuration("WARPBOX_READ_HEADER_TIMEOUT", 15*time.Second),
|
ReadHeaderTimeout: envDuration("WARPBOX_READ_HEADER_TIMEOUT", 15*time.Second),
|
||||||
ReadTimeout: envDuration("WARPBOX_READ_TIMEOUT", 0),
|
ReadTimeout: envDuration("WARPBOX_READ_TIMEOUT", 0),
|
||||||
WriteTimeout: envDuration("WARPBOX_WRITE_TIMEOUT", 0),
|
WriteTimeout: envDuration("WARPBOX_WRITE_TIMEOUT", 0),
|
||||||
IdleTimeout: envDuration("WARPBOX_IDLE_TIMEOUT", 120*time.Second),
|
IdleTimeout: envDuration("WARPBOX_IDLE_TIMEOUT", 120*time.Second),
|
||||||
TrustedProxies: envCSV("WARPBOX_TRUSTED_PROXIES"),
|
TrustedProxies: envCSV("WARPBOX_TRUSTED_PROXIES"),
|
||||||
JobsEnabled: envBool("WARPBOX_JOBS_ENABLED", true),
|
JobsEnabled: envBool("WARPBOX_JOBS_ENABLED", true),
|
||||||
CleanupEnabled: envBool("WARPBOX_CLEANUP_ENABLED", true),
|
CleanupEnabled: envBool("WARPBOX_CLEANUP_ENABLED", true),
|
||||||
CleanupEvery: envDuration("WARPBOX_CLEANUP_EVERY", time.Hour),
|
CleanupEvery: envDuration("WARPBOX_CLEANUP_EVERY", time.Hour),
|
||||||
ThumbnailEnabled: envBool("WARPBOX_THUMBNAIL_ENABLED", true),
|
ThumbnailEnabled: envBool("WARPBOX_THUMBNAIL_ENABLED", true),
|
||||||
ThumbnailEvery: envDuration("WARPBOX_THUMBNAIL_EVERY", time.Minute),
|
ThumbnailEvery: envDuration("WARPBOX_THUMBNAIL_EVERY", time.Minute),
|
||||||
MaxUploadSize: envMegabytes("WARPBOX_MAX_UPLOAD_SIZE_MB", 2048), // 2 GiB default.
|
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{
|
DefaultSettings: SettingsDefaults{
|
||||||
AnonymousUploadsEnabled: envBool("WARPBOX_ANONYMOUS_UPLOADS_ENABLED", true),
|
AnonymousUploadsEnabled: envBool("WARPBOX_ANONYMOUS_UPLOADS_ENABLED", true),
|
||||||
AnonymousMaxUploadMB: envMegabytesLimitFloat("WARPBOX_ANONYMOUS_MAX_UPLOAD_MB", 512),
|
AnonymousMaxUploadMB: envMegabytesLimitFloat("WARPBOX_ANONYMOUS_MAX_UPLOAD_MB", 512),
|
||||||
@@ -94,8 +105,13 @@ func Load() (Config, error) {
|
|||||||
ShortWindowSeconds: envInt("WARPBOX_SHORT_WINDOW_SECONDS", 60),
|
ShortWindowSeconds: envInt("WARPBOX_SHORT_WINDOW_SECONDS", 60),
|
||||||
AnonymousStorageBackend: envString("WARPBOX_ANONYMOUS_STORAGE_BACKEND", "local"),
|
AnonymousStorageBackend: envString("WARPBOX_ANONYMOUS_STORAGE_BACKEND", "local"),
|
||||||
UserStorageBackend: envString("WARPBOX_USER_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 == "" {
|
if cfg.BaseURL == "" {
|
||||||
return Config{}, fmt.Errorf("WARPBOX_BASE_URL cannot be empty")
|
return Config{}, fmt.Errorf("WARPBOX_BASE_URL cannot be empty")
|
||||||
@@ -103,6 +119,12 @@ func Load() (Config, error) {
|
|||||||
if cfg.MaxUploadSize <= 0 {
|
if cfg.MaxUploadSize <= 0 {
|
||||||
return Config{}, fmt.Errorf("WARPBOX_MAX_UPLOAD_SIZE_MB must be positive")
|
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) ||
|
if !validUnlimitedMegabyteLimit(cfg.DefaultSettings.AnonymousMaxUploadMB) ||
|
||||||
!validUnlimitedMegabyteLimit(cfg.DefaultSettings.AnonymousDailyUploadMB) ||
|
!validUnlimitedMegabyteLimit(cfg.DefaultSettings.AnonymousDailyUploadMB) ||
|
||||||
!validUnlimitedMegabyteLimit(cfg.DefaultSettings.UserDailyUploadMB) ||
|
!validUnlimitedMegabyteLimit(cfg.DefaultSettings.UserDailyUploadMB) ||
|
||||||
|
|||||||
@@ -68,4 +68,13 @@ func TestLoadDefaultsUseLargeUploadFriendlyTimeouts(t *testing.T) {
|
|||||||
if cfg.WriteTimeout != 0 {
|
if cfg.WriteTimeout != 0 {
|
||||||
t.Fatalf("WriteTimeout = %s, want 0 for long uploads", cfg.WriteTimeout)
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -574,6 +574,7 @@ func (a *App) AdminSettingsPost(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
settings.AnonymousUploadsEnabled = r.FormValue("anonymous_uploads_enabled") == "on"
|
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 {
|
if value := parsePositiveInt(r.FormValue("usage_retention_days")); value > 0 {
|
||||||
settings.UsageRetentionDays = value
|
settings.UsageRetentionDays = value
|
||||||
}
|
}
|
||||||
@@ -604,6 +605,16 @@ func (a *App) AdminSettingsPost(w http.ResponseWriter, r *http.Request) {
|
|||||||
if value := parsePositiveInt(r.FormValue("short_window_seconds")); value > 0 {
|
if value := parsePositiveInt(r.FormValue("short_window_seconds")); value > 0 {
|
||||||
settings.ShortWindowSeconds = value
|
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 != "" {
|
if value := r.FormValue("anonymous_storage_backend"); value != "" {
|
||||||
settings.AnonymousStorageBackend = value
|
settings.AnonymousStorageBackend = value
|
||||||
}
|
}
|
||||||
@@ -1770,7 +1781,7 @@ func isHealthCheckLogEntry(raw map[string]any) bool {
|
|||||||
if idx := strings.IndexByte(path, '?'); idx >= 0 {
|
if idx := strings.IndexByte(path, '?'); idx >= 0 {
|
||||||
path = path[:idx]
|
path = path[:idx]
|
||||||
}
|
}
|
||||||
return path == "/health" || path == "/healthz" || path == "/api/v1/health"
|
return path == "/health"
|
||||||
}
|
}
|
||||||
|
|
||||||
func logEntryFromMap(raw map[string]any) adminLogEntry {
|
func logEntryFromMap(raw map[string]any) adminLogEntry {
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import (
|
|||||||
type apiDocsData struct {
|
type apiDocsData struct {
|
||||||
BaseURL string
|
BaseURL string
|
||||||
UploadURL string
|
UploadURL string
|
||||||
HealthURL string
|
|
||||||
RequestSchemaURL string
|
RequestSchemaURL string
|
||||||
ResponseSchemaURL string
|
ResponseSchemaURL string
|
||||||
ShareXExamplePath string
|
ShareXExamplePath string
|
||||||
@@ -39,7 +38,6 @@ func (a *App) APIDocs(w http.ResponseWriter, r *http.Request) {
|
|||||||
Data: apiDocsData{
|
Data: apiDocsData{
|
||||||
BaseURL: a.cfg.BaseURL,
|
BaseURL: a.cfg.BaseURL,
|
||||||
UploadURL: a.cfg.BaseURL + "/api/v1/upload",
|
UploadURL: a.cfg.BaseURL + "/api/v1/upload",
|
||||||
HealthURL: a.cfg.BaseURL + "/api/v1/health",
|
|
||||||
RequestSchemaURL: a.cfg.BaseURL + "/api/v1/schemas/upload-request.json",
|
RequestSchemaURL: a.cfg.BaseURL + "/api/v1/schemas/upload-request.json",
|
||||||
ResponseSchemaURL: a.cfg.BaseURL + "/api/v1/schemas/upload-response.json",
|
ResponseSchemaURL: a.cfg.BaseURL + "/api/v1/schemas/upload-response.json",
|
||||||
ShareXExamplePath: "examples/sharex/warpbox-anonymous.sxcu",
|
ShareXExamplePath: "examples/sharex/warpbox-anonymous.sxcu",
|
||||||
|
|||||||
@@ -20,9 +20,14 @@ type App struct {
|
|||||||
banService *services.BanService
|
banService *services.BanService
|
||||||
rateLimiter *rateLimiter
|
rateLimiter *rateLimiter
|
||||||
uploadGroups *uploadGrouper
|
uploadGroups *uploadGrouper
|
||||||
|
fileIcons *fileIconSet
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
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{
|
return &App{
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
@@ -34,6 +39,7 @@ func NewApp(cfg config.Config, logger *slog.Logger, renderer *web.Renderer, uplo
|
|||||||
banService: banService,
|
banService: banService,
|
||||||
rateLimiter: newRateLimiter(),
|
rateLimiter: newRateLimiter(),
|
||||||
uploadGroups: newUploadGrouper(),
|
uploadGroups: newUploadGrouper(),
|
||||||
|
fileIcons: fileIcons,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,12 +135,23 @@ func (a *App) RegisterRoutes(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("GET /d/{boxID}/thumb/{fileID}", a.Thumbnail)
|
mux.HandleFunc("GET /d/{boxID}/thumb/{fileID}", a.Thumbnail)
|
||||||
mux.HandleFunc("GET /d/{boxID}/og-image.jpg", a.BoxOGImage)
|
mux.HandleFunc("GET /d/{boxID}/og-image.jpg", a.BoxOGImage)
|
||||||
mux.HandleFunc("GET /health", a.Health)
|
mux.HandleFunc("GET /health", a.Health)
|
||||||
mux.HandleFunc("GET /healthz", a.Health)
|
mux.HandleFunc("GET /healthz", notFound)
|
||||||
mux.HandleFunc("GET /api/v1/health", a.Health)
|
mux.HandleFunc("GET /api/v1/health", notFound)
|
||||||
mux.HandleFunc("GET /api/v1/sharex/warpbox-anonymous.sxcu", a.ShareXAnonymousConfig)
|
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-request.json", a.UploadRequestSchema)
|
||||||
mux.HandleFunc("GET /api/v1/schemas/upload-response.json", a.UploadResponseSchema)
|
mux.HandleFunc("GET /api/v1/schemas/upload-response.json", a.UploadResponseSchema)
|
||||||
mux.HandleFunc("POST /api/v1/upload", a.Upload)
|
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.HandleFunc("GET /emoji/{pack}/{file}", a.EmojiAsset)
|
||||||
mux.Handle("GET /static/", a.Static())
|
mux.Handle("GET /static/", a.Static())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func notFound(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
|||||||
@@ -45,9 +45,14 @@ type fileView struct {
|
|||||||
URL string
|
URL string
|
||||||
DownloadURL string
|
DownloadURL string
|
||||||
ThumbnailURL string
|
ThumbnailURL string
|
||||||
|
HasThumbnail bool
|
||||||
|
IconURL string
|
||||||
|
IconRetroURL string
|
||||||
ReactURL string
|
ReactURL string
|
||||||
Reactions []reactionView
|
Reactions []reactionView
|
||||||
|
ReactionMore int
|
||||||
Reacted bool
|
Reacted bool
|
||||||
|
Processing bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type reactionView struct {
|
type reactionView struct {
|
||||||
@@ -55,6 +60,7 @@ type reactionView struct {
|
|||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
Label string `json:"label"`
|
Label string `json:"label"`
|
||||||
Count int `json:"count"`
|
Count int `json:"count"`
|
||||||
|
Visible bool `json:"visible"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type emojiTabView struct {
|
type emojiTabView struct {
|
||||||
@@ -96,6 +102,15 @@ func (a *App) DownloadPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
locked := a.uploadService.IsProtected(box) && !a.isBoxUnlocked(r, box)
|
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)
|
visitorID := a.reactionVisitorID(w, r)
|
||||||
reactionsByFile, reactedByFile, err := a.reactionService.SummaryForBox(box.ID, visitorID)
|
reactionsByFile, reactedByFile, err := a.reactionService.SummaryForBox(box.ID, visitorID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -154,6 +169,15 @@ func (a *App) DownloadFile(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
locked := a.uploadService.IsProtected(box) && !a.isBoxUnlocked(r, box)
|
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)
|
view := a.fileView(box, file)
|
||||||
title := file.Name
|
title := file.Name
|
||||||
description := fmt.Sprintf("%s shared via Warpbox", helpers.FormatBytes(file.Size))
|
description := fmt.Sprintf("%s shared via Warpbox", helpers.FormatBytes(file.Size))
|
||||||
@@ -188,6 +212,10 @@ func (a *App) DownloadFileContent(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, "password required", http.StatusUnauthorized)
|
http.Error(w, "password required", http.StatusUnauthorized)
|
||||||
return
|
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.serveFileContent(w, r, box, file, 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")...)
|
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")...)
|
||||||
@@ -350,6 +378,8 @@ func (a *App) fileView(box services.Box, file services.File) fileView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) fileViewWithReactions(box services.Box, file services.File, reactions []services.ReactionSummary, reacted bool) fileView {
|
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{
|
return fileView{
|
||||||
ID: file.ID,
|
ID: file.ID,
|
||||||
Name: file.Name,
|
Name: file.Name,
|
||||||
@@ -359,9 +389,14 @@ func (a *App) fileViewWithReactions(box services.Box, file services.File, reacti
|
|||||||
URL: fmt.Sprintf("/d/%s/f/%s", box.ID, file.ID),
|
URL: fmt.Sprintf("/d/%s/f/%s", box.ID, file.ID),
|
||||||
DownloadURL: fmt.Sprintf("/d/%s/f/%s/download", 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),
|
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),
|
ReactURL: fmt.Sprintf("/d/%s/f/%s/react", box.ID, file.ID),
|
||||||
Reactions: a.reactionViews(reactions),
|
Reactions: reactionViews,
|
||||||
|
ReactionMore: reactionOverflowCount(reactionViews),
|
||||||
Reacted: reacted,
|
Reacted: reacted,
|
||||||
|
Processing: file.Processing,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,17 +441,25 @@ func (a *App) ReactToFile(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (a *App) reactionViews(reactions []services.ReactionSummary) []reactionView {
|
func (a *App) reactionViews(reactions []services.ReactionSummary) []reactionView {
|
||||||
views := make([]reactionView, 0, len(reactions))
|
views := make([]reactionView, 0, len(reactions))
|
||||||
for _, reaction := range reactions {
|
for index, reaction := range reactions {
|
||||||
views = append(views, reactionView{
|
views = append(views, reactionView{
|
||||||
EmojiID: reaction.EmojiID,
|
EmojiID: reaction.EmojiID,
|
||||||
URL: emojiURL(reaction.EmojiID),
|
URL: emojiURL(reaction.EmojiID),
|
||||||
Label: emojiLabel(reaction.EmojiID),
|
Label: emojiLabel(reaction.EmojiID),
|
||||||
Count: reaction.Count,
|
Count: reaction.Count,
|
||||||
|
Visible: index < 2,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return views
|
return views
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func reactionOverflowCount(reactions []reactionView) int {
|
||||||
|
if len(reactions) <= 2 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return len(reactions) - 2
|
||||||
|
}
|
||||||
|
|
||||||
func (a *App) emojiTabs() ([]emojiTabView, error) {
|
func (a *App) emojiTabs() ([]emojiTabView, error) {
|
||||||
root := a.emojiRoot()
|
root := a.emojiRoot()
|
||||||
entries, err := os.ReadDir(root)
|
entries, err := os.ReadDir(root)
|
||||||
@@ -564,3 +607,31 @@ func absoluteURL(r *http.Request, path string) string {
|
|||||||
}
|
}
|
||||||
return fmt.Sprintf("%s://%s%s", scheme, r.Host, path)
|
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) {
|
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{
|
helpers.WriteJSON(w, http.StatusOK, healthResponse{
|
||||||
Status: "ok",
|
Status: "ok",
|
||||||
Time: time.Now().UTC().Format(time.RFC3339),
|
Time: time.Now().UTC().Format(time.RFC3339),
|
||||||
|
|||||||
@@ -13,16 +13,20 @@ func TestHealthRoutes(t *testing.T) {
|
|||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
app.RegisterRoutes(mux)
|
app.RegisterRoutes(mux)
|
||||||
|
|
||||||
for _, path := range []string{"/health", "/healthz", "/api/v1/health"} {
|
request := httptest.NewRequest(http.MethodGet, "/health", nil)
|
||||||
t.Run(path, func(t *testing.T) {
|
response := httptest.NewRecorder()
|
||||||
request := httptest.NewRequest(http.MethodGet, path, nil)
|
|
||||||
response := httptest.NewRecorder()
|
|
||||||
|
|
||||||
mux.ServeHTTP(response, request)
|
mux.ServeHTTP(response, request)
|
||||||
|
|
||||||
if response.Code != http.StatusOK {
|
if response.Code != http.StatusOK {
|
||||||
t.Fatalf("status = %d, body = %s", response.Code, response.Body.String())
|
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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -228,11 +228,22 @@ func (a *App) checkUploadPolicy(r *http.Request, user services.User, loggedIn bo
|
|||||||
if len(files) == 0 {
|
if len(files) == 0 {
|
||||||
return 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()
|
now := time.Now().UTC()
|
||||||
if policy.MaxUploadMB > 0 {
|
if policy.MaxUploadMB > 0 {
|
||||||
maxBytes := services.MegabytesToBytes(policy.MaxUploadMB)
|
maxBytes := services.MegabytesToBytes(policy.MaxUploadMB)
|
||||||
for _, file := range files {
|
for _, fileSize := range fileSizes {
|
||||||
if file.Size > maxBytes {
|
if fileSize > maxBytes {
|
||||||
return http.StatusRequestEntityTooLarge, "file exceeds upload size limit"
|
return http.StatusRequestEntityTooLarge, "file exceeds upload size limit"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package handlers
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
@@ -10,8 +11,10 @@ import (
|
|||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"warpbox.dev/backend/libs/config"
|
"warpbox.dev/backend/libs/config"
|
||||||
"warpbox.dev/backend/libs/services"
|
"warpbox.dev/backend/libs/services"
|
||||||
@@ -103,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) {
|
func TestManageBoxAndDeleteFlow(t *testing.T) {
|
||||||
app, cleanup := newTestApp(t)
|
app, cleanup := newTestApp(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
@@ -214,13 +596,16 @@ func newTestApp(t *testing.T) (*App, func()) {
|
|||||||
|
|
||||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||||
cfg := config.Config{
|
cfg := config.Config{
|
||||||
AppName: "warpbox.dev",
|
AppName: "warpbox.dev",
|
||||||
AppVersion: "test",
|
AppVersion: "test",
|
||||||
BaseURL: "http://example.test",
|
BaseURL: "http://example.test",
|
||||||
DataDir: filepath.Join(root, "data"),
|
DataDir: filepath.Join(root, "data"),
|
||||||
StaticDir: staticDir,
|
StaticDir: staticDir,
|
||||||
TemplateDir: templateDir,
|
TemplateDir: templateDir,
|
||||||
MaxUploadSize: 1024 * 1024,
|
MaxUploadSize: 1024 * 1024,
|
||||||
|
ResumableUploadsEnabled: true,
|
||||||
|
ResumableChunkSize: 4,
|
||||||
|
ResumableRetention: time.Hour,
|
||||||
DefaultSettings: config.SettingsDefaults{
|
DefaultSettings: config.SettingsDefaults{
|
||||||
AnonymousUploadsEnabled: true,
|
AnonymousUploadsEnabled: true,
|
||||||
AnonymousMaxUploadMB: 1,
|
AnonymousMaxUploadMB: 1,
|
||||||
@@ -228,6 +613,10 @@ func newTestApp(t *testing.T) (*App, func()) {
|
|||||||
UserDailyUploadMB: 8,
|
UserDailyUploadMB: 8,
|
||||||
DefaultUserStorageMB: 16,
|
DefaultUserStorageMB: 16,
|
||||||
UsageRetentionDays: 30,
|
UsageRetentionDays: 30,
|
||||||
|
ResumableUploadsEnabled: true,
|
||||||
|
ResumableChunkSizeMB: 0.000003814697265625,
|
||||||
|
ResumableRetentionHours: 1,
|
||||||
|
ResumableChunkMode: "same",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
service, err := services.NewUploadService(cfg.MaxUploadSize, cfg.DataDir, cfg.BaseURL, logger)
|
service, err := services.NewUploadService(cfg.MaxUploadSize, cfg.DataDir, cfg.BaseURL, logger)
|
||||||
@@ -342,6 +731,31 @@ func tokenFromURL(t *testing.T, value string) string {
|
|||||||
return parts[len(parts)-1]
|
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 {
|
func copyDir(src, dst string) error {
|
||||||
return filepath.WalkDir(src, func(path string, d os.DirEntry, err error) error {
|
return filepath.WalkDir(src, func(path string, d os.DirEntry, err error) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -22,6 +22,14 @@ func newCleanupJob(cfg config.Config, logger *slog.Logger, uploadService *servic
|
|||||||
if cleaned > 0 {
|
if cleaned > 0 {
|
||||||
logger.Info("cleanup job complete", "source", "housekeeping", "severity", "user_activity", "code", 2202, "cleaned", cleaned)
|
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 {
|
if banService != nil {
|
||||||
cleanedEvents, err := banService.CleanupAbuseEvents(time.Now().UTC())
|
cleanedEvents, err := banService.CleanupAbuseEvents(time.Now().UTC())
|
||||||
if err != nil {
|
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) {
|
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) {
|
func cleanupUnavailableBoxes(uploadService *services.UploadService, logger *slog.Logger) (int, error) {
|
||||||
|
|||||||
@@ -472,7 +472,7 @@ func (s *BanService) MaliciousPattern(path string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func shouldSkipMaliciousPath(path string) bool {
|
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) {
|
func (s *BanService) RecordAbuse(ip, kind, detail string, threshold int, now time.Time) (AbuseResult, error) {
|
||||||
|
|||||||
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"`
|
ShortWindowSeconds int `json:"shortWindowSeconds"`
|
||||||
AnonymousStorageBackend string `json:"anonymousStorageBackend"`
|
AnonymousStorageBackend string `json:"anonymousStorageBackend"`
|
||||||
UserStorageBackend string `json:"userStorageBackend"`
|
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 {
|
type UsageRecord struct {
|
||||||
@@ -89,6 +94,11 @@ func NewSettingsService(db *bbolt.DB, defaults config.SettingsDefaults) (*Settin
|
|||||||
ShortWindowSeconds: defaults.ShortWindowSeconds,
|
ShortWindowSeconds: defaults.ShortWindowSeconds,
|
||||||
AnonymousStorageBackend: defaults.AnonymousStorageBackend,
|
AnonymousStorageBackend: defaults.AnonymousStorageBackend,
|
||||||
UserStorageBackend: defaults.UserStorageBackend,
|
UserStorageBackend: defaults.UserStorageBackend,
|
||||||
|
ResumableUploadsEnabled: defaults.ResumableUploadsEnabled,
|
||||||
|
ResumableChunkSizeMB: defaults.ResumableChunkSizeMB,
|
||||||
|
ResumableRetentionHours: defaults.ResumableRetentionHours,
|
||||||
|
ResumableChunkMode: defaults.ResumableChunkMode,
|
||||||
|
ResumableChunkPath: defaults.ResumableChunkPath,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
service.defaults = service.withBuiltinDefaultGaps(service.defaults)
|
service.defaults = service.withBuiltinDefaultGaps(service.defaults)
|
||||||
@@ -143,6 +153,15 @@ func (s *SettingsService) withBuiltinDefaultGaps(settings UploadPolicySettings)
|
|||||||
if strings.TrimSpace(settings.UserStorageBackend) == "" {
|
if strings.TrimSpace(settings.UserStorageBackend) == "" {
|
||||||
settings.UserStorageBackend = StorageBackendLocal
|
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
|
return settings
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,6 +175,13 @@ func (s *SettingsService) UploadPolicy() (UploadPolicySettings, error) {
|
|||||||
if err := json.Unmarshal(data, &settings); err != nil {
|
if err := json.Unmarshal(data, &settings); err != nil {
|
||||||
return err
|
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)
|
settings = s.withDefaultGaps(settings)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -217,6 +243,15 @@ func (s *SettingsService) withDefaultGaps(settings UploadPolicySettings) UploadP
|
|||||||
if strings.TrimSpace(settings.UserStorageBackend) == "" {
|
if strings.TrimSpace(settings.UserStorageBackend) == "" {
|
||||||
settings.UserStorageBackend = s.defaults.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
|
return settings
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -422,6 +457,18 @@ func (s *SettingsService) validate(settings UploadPolicySettings) error {
|
|||||||
if settings.ShortWindowRequests <= 0 || settings.ShortWindowSeconds <= 0 {
|
if settings.ShortWindowRequests <= 0 || settings.ShortWindowSeconds <= 0 {
|
||||||
return fmt.Errorf("short-window rate limits must be positive")
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ type UploadOptions struct {
|
|||||||
ExpiresInMinutes int
|
ExpiresInMinutes int
|
||||||
MaxDownloads int
|
MaxDownloads int
|
||||||
Password string
|
Password string
|
||||||
|
PasswordSalt string
|
||||||
|
PasswordHash string
|
||||||
ObfuscateMetadata bool
|
ObfuscateMetadata bool
|
||||||
OwnerID string
|
OwnerID string
|
||||||
CollectionID string
|
CollectionID string
|
||||||
@@ -50,6 +52,56 @@ type UploadOptions struct {
|
|||||||
StorageBackendID string
|
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 {
|
type Box struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
OwnerID string `json:"ownerId,omitempty"`
|
OwnerID string `json:"ownerId,omitempty"`
|
||||||
@@ -78,6 +130,8 @@ type File struct {
|
|||||||
Thumbnail string `json:"thumbnail,omitempty"`
|
Thumbnail string `json:"thumbnail,omitempty"`
|
||||||
ObjectKey string `json:"objectKey,omitempty"`
|
ObjectKey string `json:"objectKey,omitempty"`
|
||||||
ThumbnailObjectKey string `json:"thumbnailObjectKey,omitempty"`
|
ThumbnailObjectKey string `json:"thumbnailObjectKey,omitempty"`
|
||||||
|
Processing bool `json:"processing,omitempty"`
|
||||||
|
ProcessingError string `json:"processingError,omitempty"`
|
||||||
UploadedAt time.Time `json:"uploadedAt"`
|
UploadedAt time.Time `json:"uploadedAt"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,6 +152,7 @@ type ResultFile struct {
|
|||||||
Size string `json:"size"`
|
Size string `json:"size"`
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
ThumbnailURL string `json:"thumbnailUrl"`
|
ThumbnailURL string `json:"thumbnailUrl"`
|
||||||
|
Processing bool `json:"processing,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AdminStats struct {
|
type AdminStats struct {
|
||||||
@@ -198,6 +253,14 @@ func (s *UploadService) ValidateSize(size int64) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *UploadService) CreateBox(files []*multipart.FileHeader, opts UploadOptions) (UploadResult, 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 {
|
if len(files) == 0 {
|
||||||
return UploadResult{}, fmt.Errorf("no files were uploaded")
|
return UploadResult{}, fmt.Errorf("no files were uploaded")
|
||||||
}
|
}
|
||||||
@@ -232,13 +295,16 @@ func (s *UploadService) CreateBox(files []*multipart.FileHeader, opts UploadOpti
|
|||||||
}
|
}
|
||||||
deleteToken := randomID(32)
|
deleteToken := randomID(32)
|
||||||
box.DeleteTokenHash = deleteTokenHash(box.ID, deleteToken)
|
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)
|
salt, hash := hashPassword(opts.Password)
|
||||||
box.PasswordSalt = salt
|
box.PasswordSalt = salt
|
||||||
box.PasswordHash = hash
|
box.PasswordHash = hash
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.writeFilesToBox(&box, files, opts); err != nil {
|
if err := s.writeIncomingFilesToBox(ctx, &box, files, opts); err != nil {
|
||||||
return UploadResult{}, err
|
return UploadResult{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,6 +327,10 @@ func (s *UploadService) CreateBox(files []*multipart.FileHeader, opts UploadOpti
|
|||||||
// selection into a single box). The box keeps its original expiry, password and
|
// selection into a single box). The box keeps its original expiry, password and
|
||||||
// other settings; only the new files are written.
|
// other settings; only the new files are written.
|
||||||
func (s *UploadService) AppendFiles(boxID string, files []*multipart.FileHeader, opts UploadOptions) (UploadResult, error) {
|
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 {
|
if len(files) == 0 {
|
||||||
return UploadResult{}, fmt.Errorf("no files were uploaded")
|
return UploadResult{}, fmt.Errorf("no files were uploaded")
|
||||||
}
|
}
|
||||||
@@ -268,7 +338,7 @@ func (s *UploadService) AppendFiles(boxID string, files []*multipart.FileHeader,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return UploadResult{}, err
|
return UploadResult{}, err
|
||||||
}
|
}
|
||||||
if err := s.writeFilesToBox(&box, files, opts); err != nil {
|
if err := s.writeIncomingFilesToBox(context.Background(), &box, files, opts); err != nil {
|
||||||
return UploadResult{}, err
|
return UploadResult{}, err
|
||||||
}
|
}
|
||||||
if err := s.SaveBox(box); err != nil {
|
if err := s.SaveBox(box); err != nil {
|
||||||
@@ -289,14 +359,26 @@ func (s *UploadService) AppendFiles(boxID string, files []*multipart.FileHeader,
|
|||||||
// appends the file metadata to box.Files. The box's StorageBackendID determines
|
// appends the file metadata to box.Files. The box's StorageBackendID determines
|
||||||
// where files land, so it works for both new and existing boxes.
|
// where files land, so it works for both new and existing boxes.
|
||||||
func (s *UploadService) writeFilesToBox(box *Box, files []*multipart.FileHeader, opts UploadOptions) error {
|
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)
|
backend, err := s.storage.Backend(box.StorageBackendID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, header := range files {
|
for _, incoming := range files {
|
||||||
if !opts.SkipSizeLimit {
|
if !opts.SkipSizeLimit {
|
||||||
if err := s.ValidateSize(header.Size); err != nil {
|
if err := s.ValidateSize(incoming.Size()); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -306,15 +388,15 @@ func (s *UploadService) writeFilesToBox(box *Box, files []*multipart.FileHeader,
|
|||||||
maxSize = 0
|
maxSize = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
file, err := header.Open()
|
file, err := incoming.Open()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
fileID := randomID(8)
|
fileID := randomID(8)
|
||||||
storedName := "@each@" + fileID + strings.ToLower(filepath.Ext(header.Filename))
|
storedName := "@each@" + fileID + strings.ToLower(filepath.Ext(incoming.Name()))
|
||||||
objectKey := boxObjectKey(box.ID, storedName)
|
objectKey := boxObjectKey(box.ID, storedName)
|
||||||
contentType := header.Header.Get("Content-Type")
|
contentType := incoming.ContentType()
|
||||||
if contentType == "" {
|
if contentType == "" {
|
||||||
buffer := make([]byte, 512)
|
buffer := make([]byte, 512)
|
||||||
n, _ := file.Read(buffer)
|
n, _ := file.Read(buffer)
|
||||||
@@ -324,17 +406,18 @@ func (s *UploadService) writeFilesToBox(box *Box, files []*multipart.FileHeader,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.writeUploadedObject(context.Background(), backend, objectKey, file, header.Size, maxSize, contentType); err != nil {
|
if err := s.writeUploadedObject(ctx, backend, objectKey, file, incoming.Size(), maxSize, contentType); err != nil {
|
||||||
file.Close()
|
file.Close()
|
||||||
|
_ = backend.Delete(context.Background(), objectKey)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
file.Close()
|
file.Close()
|
||||||
|
|
||||||
box.Files = append(box.Files, File{
|
box.Files = append(box.Files, File{
|
||||||
ID: fileID,
|
ID: fileID,
|
||||||
Name: filepath.Base(header.Filename),
|
Name: filepath.Base(incoming.Name()),
|
||||||
StoredName: storedName,
|
StoredName: storedName,
|
||||||
Size: header.Size,
|
Size: incoming.Size(),
|
||||||
ContentType: contentType,
|
ContentType: contentType,
|
||||||
PreviewKind: previewKind(contentType),
|
PreviewKind: previewKind(contentType),
|
||||||
ObjectKey: objectKey,
|
ObjectKey: objectKey,
|
||||||
@@ -736,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) {
|
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))
|
backend, err := s.storage.Backend(s.BoxStorageBackendID(box))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return StorageObject{}, err
|
return StorageObject{}, err
|
||||||
@@ -857,6 +943,13 @@ func (s *UploadService) WriteZip(w io.Writer, box Box) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *UploadService) SaveBox(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 == "" {
|
if box.StorageBackendID == "" {
|
||||||
box.StorageBackendID = StorageBackendLocal
|
box.StorageBackendID = StorageBackendLocal
|
||||||
}
|
}
|
||||||
@@ -866,10 +959,7 @@ func (s *UploadService) SaveBox(box Box) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return s.db.Update(func(tx *bbolt.Tx) error {
|
return s.db.Update(func(tx *bbolt.Tx) error {
|
||||||
if err := tx.Bucket(boxesBucket).Put([]byte(box.ID), data); err != nil {
|
return tx.Bucket(boxesBucket).Put([]byte(box.ID), data)
|
||||||
return err
|
|
||||||
}
|
|
||||||
return s.writeBoxMetadata(box)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -882,6 +972,7 @@ func (s *UploadService) resultForBox(box Box, deleteToken string) UploadResult {
|
|||||||
Size: helpers.FormatBytes(file.Size),
|
Size: helpers.FormatBytes(file.Size),
|
||||||
URL: fmt.Sprintf("%s/d/%s/f/%s", s.baseURL, box.ID, file.ID),
|
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),
|
ThumbnailURL: fmt.Sprintf("%s/d/%s/thumb/%s", s.baseURL, box.ID, file.ID),
|
||||||
|
Processing: file.Processing,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -931,21 +1022,34 @@ func writeUploadedFile(path string, source multipart.File, maxSize int64) error
|
|||||||
return nil
|
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
|
var reader io.Reader = source
|
||||||
|
putSize := size
|
||||||
if maxSize > 0 {
|
if maxSize > 0 {
|
||||||
reader = io.LimitReader(source, maxSize+1)
|
if size > maxSize {
|
||||||
var buffer bytes.Buffer
|
|
||||||
written, err := io.Copy(&buffer, reader)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if written > maxSize {
|
|
||||||
return fmt.Errorf("file exceeds max upload size")
|
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 {
|
func boxObjectKey(boxID, name string) string {
|
||||||
|
|||||||
@@ -126,6 +126,262 @@ func TestLocalStorageBackendAndLegacyFallback(t *testing.T) {
|
|||||||
object.Body.Close()
|
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) {
|
func TestContaboStorageConfigAllowsDisplayNamesWithSpaces(t *testing.T) {
|
||||||
service := newTestUploadService(t)
|
service := newTestUploadService(t)
|
||||||
cfg, err := service.Storage().CreateS3Backend(StorageBackendConfig{
|
cfg, err := service.Storage().CreateS3Backend(StorageBackendConfig{
|
||||||
|
|||||||
@@ -592,31 +592,152 @@
|
|||||||
content: "\23F1 ";
|
content: "\23F1 ";
|
||||||
}
|
}
|
||||||
|
|
||||||
/* List / Thumbnails / Preview images = a Win98 toolbar (menubar) of flat
|
/* The file browser becomes a Win98 Explorer window: blue titlebar, grey
|
||||||
buttons that raise on hover and depress when active. */
|
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 {
|
:root[data-theme="retro"] .view-toolbar {
|
||||||
justify-content: flex-start;
|
justify-content: flex-start;
|
||||||
gap: 2px;
|
gap: 2px;
|
||||||
margin-top: 1rem;
|
margin-top: 0;
|
||||||
padding: 3px;
|
padding: 0;
|
||||||
background: #c0c0c0;
|
background: #c0c0c0;
|
||||||
border: 1px solid #000000;
|
border: 0;
|
||||||
box-shadow: inset 1px 1px 0 #ffffff, inset -1px -1px 0 #808080;
|
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;
|
background: transparent;
|
||||||
border: 1px solid transparent;
|
border: 1px solid transparent;
|
||||||
box-shadow: none;
|
box-shadow: none;
|
||||||
font-weight: 400;
|
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;
|
background: #c0c0c0;
|
||||||
box-shadow: inset -1px -1px 0 #808080, inset 1px 1px 0 #ffffff;
|
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;
|
background: #d4d0c8;
|
||||||
box-shadow: inset 1px 1px 0 #808080, inset -1px -1px 0 #ffffff;
|
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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -48,6 +48,10 @@
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.upload-options .form-footer .upload-new-button {
|
||||||
|
margin-top: -0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
.hero-copy {
|
.hero-copy {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
@@ -335,10 +339,13 @@ button {
|
|||||||
.file-progress-side {
|
.file-progress-side {
|
||||||
width: min(10rem, 32vw);
|
width: min(10rem, 32vw);
|
||||||
display: grid;
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
gap: 0.35rem;
|
gap: 0.35rem;
|
||||||
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.file-progress-percent {
|
.file-progress-percent {
|
||||||
|
grid-column: 1 / -1;
|
||||||
color: var(--muted-foreground);
|
color: var(--muted-foreground);
|
||||||
font-size: 0.75rem;
|
font-size: 0.75rem;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
@@ -349,6 +356,81 @@ button {
|
|||||||
margin-top: 0;
|
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,
|
.result-item small,
|
||||||
.download-item small,
|
.download-item small,
|
||||||
.result-item code,
|
.result-item code,
|
||||||
|
|||||||
@@ -46,12 +46,31 @@
|
|||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.view-toolbar {
|
.upload-processing-alert {
|
||||||
display: flex;
|
margin: 1rem 0;
|
||||||
justify-content: center;
|
padding: .85rem 1rem;
|
||||||
flex-wrap: wrap;
|
border: 1px solid color-mix(in srgb, var(--primary) 45%, transparent);
|
||||||
gap: 0.5rem;
|
border-radius: var(--radius);
|
||||||
margin-top: 1rem;
|
background: color-mix(in srgb, var(--primary) 12%, transparent);
|
||||||
|
color: var(--foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thumb-link {
|
||||||
|
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.2rem);
|
||||||
|
background: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thumb-link img {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
display: block;
|
||||||
|
object-fit: cover;
|
||||||
}
|
}
|
||||||
|
|
||||||
.button.is-active {
|
.button.is-active {
|
||||||
@@ -59,26 +78,157 @@
|
|||||||
color: var(--primary-foreground);
|
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 {
|
.file-browser {
|
||||||
|
display: grid;
|
||||||
|
gap: 0;
|
||||||
|
padding: 0.35rem;
|
||||||
transition: opacity 160ms ease;
|
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 {
|
.file-card {
|
||||||
position: relative;
|
position: relative;
|
||||||
padding-bottom: 2.6rem;
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-card.is-processing {
|
||||||
|
opacity: .62;
|
||||||
|
filter: grayscale(.25);
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-card.is-processing .file-open {
|
||||||
|
cursor: wait;
|
||||||
}
|
}
|
||||||
|
|
||||||
.file-reaction-dock {
|
.file-reaction-dock {
|
||||||
position: absolute;
|
position: static;
|
||||||
right: 0.65rem;
|
|
||||||
bottom: 0.55rem;
|
|
||||||
z-index: 2;
|
z-index: 2;
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
max-width: calc(100% - 1.3rem);
|
min-width: 0;
|
||||||
|
max-width: 100%;
|
||||||
gap: 0.35rem;
|
gap: 0.35rem;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
|
padding-right: 0.65rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.file-reactions {
|
.file-reactions {
|
||||||
@@ -87,10 +237,13 @@
|
|||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
gap: 0.25rem;
|
gap: 0.25rem;
|
||||||
flex-wrap: wrap;
|
flex-wrap: nowrap;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.reaction-pill {
|
.reaction-pill {
|
||||||
|
appearance: none;
|
||||||
|
flex: 0 0 auto;
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.2rem;
|
gap: 0.2rem;
|
||||||
@@ -104,6 +257,11 @@
|
|||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.24);
|
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.24);
|
||||||
pointer-events: auto;
|
pointer-events: auto;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reaction-pill.is-hidden-summary {
|
||||||
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.reaction-pill img {
|
.reaction-pill img {
|
||||||
@@ -112,6 +270,31 @@
|
|||||||
display: block;
|
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 {
|
.reaction-button {
|
||||||
width: 2.1rem;
|
width: 2.1rem;
|
||||||
height: 2.1rem;
|
height: 2.1rem;
|
||||||
@@ -212,6 +395,30 @@ html.reaction-picker-open body {
|
|||||||
font-size: 0.75rem;
|
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 {
|
.reaction-picker-tabs {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 0.35rem;
|
gap: 0.35rem;
|
||||||
@@ -303,76 +510,182 @@ html.reaction-picker-open body {
|
|||||||
object-fit: contain;
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
|
|
||||||
.thumb-link {
|
/* A file row behaves like an entry in a desktop file explorer: a small
|
||||||
display: block;
|
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;
|
overflow: hidden;
|
||||||
flex: 0 0 4.75rem;
|
|
||||||
width: 4.75rem;
|
|
||||||
aspect-ratio: 16 / 10;
|
|
||||||
border: 1px solid var(--border);
|
border: 1px solid var(--border);
|
||||||
border-radius: calc(var(--radius) - 0.125rem);
|
border-radius: calc(var(--radius) - 0.125rem);
|
||||||
background: var(--muted);
|
background: var(--muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
.thumb-link img {
|
.file-thumb {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
display: block;
|
display: block;
|
||||||
object-fit: cover;
|
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 {
|
.file-main {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
flex: 1;
|
|
||||||
color: var(--foreground);
|
color: var(--foreground);
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.file-actions {
|
.file-name {
|
||||||
display: inline-flex;
|
min-width: 0;
|
||||||
align-items: center;
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.preview-action [hidden] {
|
.file-main small {
|
||||||
display: none;
|
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 {
|
.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 {
|
.file-browser.is-thumbs .file-card {
|
||||||
display: grid;
|
display: grid;
|
||||||
|
min-height: 13.75rem;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
align-content: start;
|
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 {
|
.file-browser.is-thumbs .file-main {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
gap: 0.25rem;
|
||||||
|
align-self: start;
|
||||||
|
padding-top: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.file-browser.is-thumbs .thumb-link {
|
.file-browser.is-thumbs .file-type,
|
||||||
width: 100%;
|
.file-browser.is-thumbs .file-size {
|
||||||
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"]) {
|
|
||||||
display: none;
|
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 {
|
.context-menu {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
z-index: 30;
|
z-index: 30;
|
||||||
|
|||||||
@@ -95,6 +95,41 @@
|
|||||||
flex: 1;
|
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 {
|
h1 {
|
||||||
font-size: 1.65rem;
|
font-size: 1.65rem;
|
||||||
}
|
}
|
||||||
@@ -213,6 +248,54 @@
|
|||||||
flex-wrap: wrap;
|
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-actions,
|
||||||
.file-browser.is-thumbs .file-actions {
|
.file-browser.is-thumbs .file-actions {
|
||||||
width: 100%;
|
width: 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.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) {
|
window.Warpbox.writeClipboard = async function writeClipboard(text) {
|
||||||
if (navigator.clipboard && window.isSecureContext) {
|
if (navigator.clipboard && window.isSecureContext) {
|
||||||
await navigator.clipboard.writeText(text);
|
await navigator.clipboard.writeText(text);
|
||||||
@@ -26,6 +37,9 @@
|
|||||||
if (!text || !button) {
|
if (!text || !button) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (typeof text === "string" && (text.startsWith("/") || /^https?:\/\//i.test(text))) {
|
||||||
|
text = window.Warpbox.absoluteURL(text);
|
||||||
|
}
|
||||||
await window.Warpbox.writeClipboard(text);
|
await window.Warpbox.writeClipboard(text);
|
||||||
const previous = button.textContent;
|
const previous = button.textContent;
|
||||||
button.textContent = copiedLabel;
|
button.textContent = copiedLabel;
|
||||||
|
|||||||
@@ -1,33 +1,50 @@
|
|||||||
(function () {
|
(function () {
|
||||||
const fileBrowser = document.querySelector("[data-file-browser]");
|
const fileBrowser = document.querySelector("[data-file-browser]");
|
||||||
const viewButtons = document.querySelectorAll("[data-view-button]");
|
const viewButtons = document.querySelectorAll("[data-view-button]");
|
||||||
const previewImages = document.querySelector("[data-preview-images]");
|
|
||||||
const previewActions = document.querySelectorAll("[data-preview-action]");
|
const previewActions = document.querySelectorAll("[data-preview-action]");
|
||||||
const fileContextMenu = document.querySelector("[data-file-context-menu]");
|
const fileContextMenu = document.querySelector("[data-file-context-menu]");
|
||||||
|
const fileBrowserWindow = document.querySelector("[data-file-browser-window]");
|
||||||
|
|
||||||
let ctrlCopyMode = false;
|
let ctrlCopyMode = false;
|
||||||
let contextFile = null;
|
let contextFile = null;
|
||||||
const contextMenuCloseDistance = 80;
|
const contextMenuCloseDistance = 80;
|
||||||
|
const viewStorageKey = "warpbox.fileBrowser.view";
|
||||||
|
|
||||||
if (fileBrowser) {
|
if (fileBrowser) {
|
||||||
|
applySavedFileBrowserPreferences();
|
||||||
|
|
||||||
viewButtons.forEach((button) => {
|
viewButtons.forEach((button) => {
|
||||||
button.addEventListener("click", () => {
|
button.addEventListener("click", () => {
|
||||||
const view = button.getAttribute("data-view-button");
|
const view = button.getAttribute("data-view-button");
|
||||||
fileBrowser.classList.toggle("is-list", view === "list");
|
setFileBrowserView(view);
|
||||||
fileBrowser.classList.toggle("is-thumbs", view === "thumbs");
|
savePreference(viewStorageKey, view);
|
||||||
viewButtons.forEach((item) => item.classList.toggle("is-active", item === button));
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
if (previewImages) {
|
|
||||||
previewImages.addEventListener("click", () => {
|
|
||||||
fileBrowser.classList.toggle("images-only");
|
|
||||||
previewImages.classList.toggle("is-active");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (fileBrowser && fileContextMenu) {
|
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) => {
|
fileBrowser.addEventListener("contextmenu", (event) => {
|
||||||
const card = event.target.closest("[data-file-context]");
|
const card = event.target.closest("[data-file-context]");
|
||||||
if (!card) {
|
if (!card) {
|
||||||
@@ -107,7 +124,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function copyPreviewLink(button) {
|
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]");
|
const label = button.querySelector("[data-preview-label]");
|
||||||
if (!label) {
|
if (!label) {
|
||||||
return;
|
return;
|
||||||
@@ -147,11 +164,11 @@
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (action === "copy-preview") {
|
if (action === "copy-preview") {
|
||||||
await window.Warpbox.writeClipboard(file.previewURL);
|
await window.Warpbox.writeClipboard(window.Warpbox.absoluteURL(file.previewURL));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (action === "copy-download") {
|
if (action === "copy-download") {
|
||||||
await window.Warpbox.writeClipboard(file.downloadURL);
|
await window.Warpbox.writeClipboard(window.Warpbox.absoluteURL(file.downloadURL));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (action === "download") {
|
if (action === "download") {
|
||||||
@@ -188,4 +205,40 @@
|
|||||||
y >= rect.top - contextMenuCloseDistance &&
|
y >= rect.top - contextMenuCloseDistance &&
|
||||||
y <= rect.bottom + 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.
|
||||||
|
}
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -3,6 +3,10 @@
|
|||||||
const panel = picker ? picker.querySelector(".reaction-picker-panel") : null;
|
const panel = picker ? picker.querySelector(".reaction-picker-panel") : null;
|
||||||
const search = picker ? picker.querySelector("[data-reaction-search]") : null;
|
const search = picker ? picker.querySelector("[data-reaction-search]") : null;
|
||||||
const closeButton = picker ? picker.querySelector("[data-reaction-close]") : 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 tabs = picker ? Array.from(picker.querySelectorAll("[data-reaction-tab]")) : [];
|
||||||
const panels = picker ? Array.from(picker.querySelectorAll("[data-reaction-panel]")) : [];
|
const panels = picker ? Array.from(picker.querySelectorAll("[data-reaction-panel]")) : [];
|
||||||
|
|
||||||
@@ -17,6 +21,36 @@
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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) {
|
if (!picker || !panel) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -35,10 +69,10 @@
|
|||||||
|
|
||||||
panel.addEventListener("click", async (event) => {
|
panel.addEventListener("click", async (event) => {
|
||||||
const emoji = event.target.closest("[data-emoji-id]");
|
const emoji = event.target.closest("[data-emoji-id]");
|
||||||
if (!emoji || !activeButton || !activeCard) {
|
if (!emoji || !activeCard || activeCard.dataset.reacted === "true") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await submitReaction(emoji);
|
await submitReactionForCard(activeCard, emoji.dataset.emojiId);
|
||||||
});
|
});
|
||||||
|
|
||||||
tabs.forEach((tab) => {
|
tabs.forEach((tab) => {
|
||||||
@@ -62,6 +96,9 @@
|
|||||||
if (panel.contains(event.target) || event.target.closest("[data-reaction-button]")) {
|
if (panel.contains(event.target) || event.target.closest("[data-reaction-button]")) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (event.target.closest("[data-reaction-more]") || event.target.closest("[data-reaction-pill]")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
closePicker();
|
closePicker();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -78,15 +115,24 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
function openPicker(button) {
|
function openPicker(button) {
|
||||||
activeButton = button;
|
openPickerForCard(button.closest("[data-reaction-card]"), button);
|
||||||
activeCard = button.closest("[data-reaction-card]");
|
}
|
||||||
|
|
||||||
|
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.hidden = false;
|
||||||
picker.classList.add("is-open");
|
picker.classList.add("is-open");
|
||||||
if (search) {
|
if (search) {
|
||||||
search.value = "";
|
search.value = "";
|
||||||
filterEmoji("");
|
filterEmoji("");
|
||||||
}
|
}
|
||||||
positionPicker(button);
|
positionPicker(activeButton || card);
|
||||||
}
|
}
|
||||||
|
|
||||||
function closePicker() {
|
function closePicker() {
|
||||||
@@ -95,6 +141,7 @@
|
|||||||
document.documentElement.classList.remove("reaction-picker-open");
|
document.documentElement.classList.remove("reaction-picker-open");
|
||||||
picker.style.left = "";
|
picker.style.left = "";
|
||||||
picker.style.top = "";
|
picker.style.top = "";
|
||||||
|
setPickerReadonly(false);
|
||||||
activeButton = null;
|
activeButton = null;
|
||||||
activeCard = null;
|
activeCard = null;
|
||||||
}
|
}
|
||||||
@@ -146,12 +193,18 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitReaction(emoji) {
|
async function submitReactionForCard(card, emojiID) {
|
||||||
|
if (!card || !emojiID || card.dataset.reacted === "true") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const body = new URLSearchParams();
|
const body = new URLSearchParams();
|
||||||
body.set("emoji_id", emoji.dataset.emojiId);
|
body.set("emoji_id", emojiID);
|
||||||
|
|
||||||
activeButton.disabled = true;
|
const reactButton = card.querySelector("[data-reaction-button]");
|
||||||
const response = await fetch(activeButton.dataset.reactUrl, {
|
if (reactButton) {
|
||||||
|
reactButton.disabled = true;
|
||||||
|
}
|
||||||
|
const response = await fetch(card.dataset.reactUrl, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Accept": "application/json",
|
"Accept": "application/json",
|
||||||
@@ -161,14 +214,19 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
activeButton.disabled = false;
|
if (reactButton) {
|
||||||
|
reactButton.disabled = false;
|
||||||
|
}
|
||||||
closePicker();
|
closePicker();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload = await response.json();
|
const payload = await response.json();
|
||||||
renderReactions(activeCard, payload.reactions || []);
|
renderReactions(card, payload.reactions || []);
|
||||||
activeButton.remove();
|
card.dataset.reacted = "true";
|
||||||
|
if (reactButton) {
|
||||||
|
reactButton.remove();
|
||||||
|
}
|
||||||
closePicker();
|
closePicker();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,20 +237,68 @@
|
|||||||
}
|
}
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
reactions.forEach((reaction) => {
|
reactions.forEach((reaction) => {
|
||||||
const pill = document.createElement("span");
|
const pill = buildReactionPill(reaction);
|
||||||
pill.className = "reaction-pill";
|
if (!reaction.visible) {
|
||||||
pill.title = reaction.label || reaction.emojiId;
|
pill.classList.add("is-hidden-summary");
|
||||||
|
}
|
||||||
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);
|
|
||||||
list.append(pill);
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -13,6 +13,8 @@
|
|||||||
const copyURL = document.querySelector("#copy-url");
|
const copyURL = document.querySelector("#copy-url");
|
||||||
const openBox = document.querySelector("#open-box");
|
const openBox = document.querySelector("#open-box");
|
||||||
const manageLink = document.querySelector("#manage-link");
|
const manageLink = document.querySelector("#manage-link");
|
||||||
|
const newUpload = document.querySelector("#new-upload");
|
||||||
|
const RESUMABLE_SESSIONS_KEY = "warpbox-resumable-sessions";
|
||||||
|
|
||||||
if (!form || !dropZone || !fileInput) {
|
if (!form || !dropZone || !fileInput) {
|
||||||
return;
|
return;
|
||||||
@@ -42,6 +44,9 @@
|
|||||||
|
|
||||||
let latestBoxURL = "";
|
let latestBoxURL = "";
|
||||||
let selectedFiles = [];
|
let selectedFiles = [];
|
||||||
|
let uploadLocked = false;
|
||||||
|
let recoveredDraft = null;
|
||||||
|
let resumeMode = false;
|
||||||
|
|
||||||
["dragenter", "dragover"].forEach((eventName) => {
|
["dragenter", "dragover"].forEach((eventName) => {
|
||||||
dropZone.addEventListener(eventName, (event) => {
|
dropZone.addEventListener(eventName, (event) => {
|
||||||
@@ -57,33 +62,67 @@
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
dropZone.addEventListener("drop", (event) => {
|
document.addEventListener("dragover", (event) => {
|
||||||
if (event.dataTransfer && event.dataTransfer.files.length > 0) {
|
if (event.dataTransfer && Array.from(event.dataTransfer.types || []).includes("Files")) {
|
||||||
fileInput.files = event.dataTransfer.files;
|
event.preventDefault();
|
||||||
updateSelectedState(event.dataTransfer.files);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
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) => {
|
form.addEventListener("submit", async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (!fileInput.files || fileInput.files.length === 0) {
|
if (selectedFiles.length === 0) {
|
||||||
updateStatus("Choose at least one file first.");
|
updateStatus("Choose at least one file first.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const submit = form.querySelector("button[type='submit']");
|
const submit = form.querySelector("button[type='submit']");
|
||||||
const formData = new FormData(form);
|
const formData = uploadFormData();
|
||||||
selectedFiles = Array.from(fileInput.files);
|
if (resumeMode && recoveredDraft) {
|
||||||
renderQueue(selectedFiles, "queued");
|
renderResumeQueue(recoveredDraft.session, selectedFiles);
|
||||||
|
} else {
|
||||||
|
renderQueue(selectedFiles, "queued");
|
||||||
|
}
|
||||||
setLoading(true, submit);
|
setLoading(true, submit);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const payload = await uploadWithProgress(form.action, formData, selectedFiles);
|
const payload = await uploadResumable(form.action, formData, selectedFiles);
|
||||||
renderResult(payload);
|
renderResult(payload);
|
||||||
form.reset();
|
form.reset();
|
||||||
updateSelectedState([]);
|
selectedFiles = [];
|
||||||
|
resumeMode = false;
|
||||||
|
recoveredDraft = null;
|
||||||
|
fileInput.value = "";
|
||||||
|
if (uploadQueue) {
|
||||||
|
uploadQueue.hidden = true;
|
||||||
|
uploadQueue.replaceChildren();
|
||||||
|
}
|
||||||
|
if (newUpload) {
|
||||||
|
newUpload.hidden = true;
|
||||||
|
}
|
||||||
|
if (fileSummary) {
|
||||||
|
fileSummary.textContent = "Upload complete.";
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
updateStatus(error.message || "Upload failed");
|
updateStatus(error.message || "Upload failed");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -97,25 +136,66 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateSelectedState(files) {
|
if (newUpload) {
|
||||||
selectedFiles = Array.from(files || []);
|
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 count = selectedFiles.length || 0;
|
||||||
const title = dropZone.querySelector(".drop-title");
|
const title = dropZone.querySelector(".drop-title");
|
||||||
if (title) {
|
if (title) {
|
||||||
title.textContent = count === 0 ? "Drop files to upload" : count === 1 ? "1 file selected" : `${count} files selected`;
|
title.textContent = count === 0 ? "Drop files to upload" : count === 1 ? "1 file selected" : `${count} files selected`;
|
||||||
}
|
}
|
||||||
if (fileSummary) {
|
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");
|
renderQueue(selectedFiles, "queued");
|
||||||
} else if (uploadQueue) {
|
} else if (uploadQueue) {
|
||||||
uploadQueue.hidden = true;
|
uploadQueue.hidden = true;
|
||||||
uploadQueue.replaceChildren();
|
uploadQueue.replaceChildren();
|
||||||
}
|
}
|
||||||
|
if (newUpload) {
|
||||||
|
newUpload.hidden = !(resumeMode && recoveredDraft);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setLoading(isLoading, submit) {
|
function setLoading(isLoading, submit) {
|
||||||
|
uploadLocked = isLoading;
|
||||||
if (progress) {
|
if (progress) {
|
||||||
progress.hidden = !isLoading;
|
progress.hidden = !isLoading;
|
||||||
}
|
}
|
||||||
@@ -123,6 +203,9 @@
|
|||||||
submit.disabled = isLoading;
|
submit.disabled = isLoading;
|
||||||
submit.textContent = isLoading ? "Uploading..." : "Upload files";
|
submit.textContent = isLoading ? "Uploading..." : "Upload files";
|
||||||
}
|
}
|
||||||
|
if (newUpload) {
|
||||||
|
newUpload.disabled = isLoading;
|
||||||
|
}
|
||||||
updateStatus(isLoading ? "Transferring files..." : "");
|
updateStatus(isLoading ? "Transferring files..." : "");
|
||||||
setTotalProgress(isLoading ? 0 : 100);
|
setTotalProgress(isLoading ? 0 : 100);
|
||||||
}
|
}
|
||||||
@@ -138,15 +221,15 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
latestBoxURL = payload.boxUrl;
|
latestBoxURL = window.Warpbox.absoluteURL(payload.boxUrl);
|
||||||
result.hidden = false;
|
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)}`;
|
resultMeta.textContent = `${payload.files.length} file${payload.files.length === 1 ? "" : "s"} · expires ${window.Warpbox.formatDate(payload.expiresAt)}`;
|
||||||
if (manageLink) {
|
if (manageLink) {
|
||||||
const anchor = manageLink.querySelector("a");
|
const anchor = manageLink.querySelector("a");
|
||||||
manageLink.hidden = !payload.manageUrl;
|
manageLink.hidden = !payload.manageUrl;
|
||||||
if (anchor && payload.manageUrl) {
|
if (anchor && payload.manageUrl) {
|
||||||
anchor.href = payload.manageUrl;
|
anchor.href = window.Warpbox.absoluteURL(payload.manageUrl);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,11 +237,12 @@
|
|||||||
payload.files.forEach((file) => {
|
payload.files.forEach((file) => {
|
||||||
resultList.append(createFileRow({
|
resultList.append(createFileRow({
|
||||||
name: file.name,
|
name: file.name,
|
||||||
meta: `${file.size} · ${file.url}`,
|
meta: `${file.size} · ${window.Warpbox.absoluteURL(file.url)}`,
|
||||||
progress: 100,
|
progress: 100,
|
||||||
status: "complete",
|
status: "complete",
|
||||||
}));
|
}));
|
||||||
});
|
});
|
||||||
|
result.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||||
}
|
}
|
||||||
|
|
||||||
function uploadWithProgress(url, formData, files) {
|
function uploadWithProgress(url, formData, files) {
|
||||||
@@ -201,26 +285,612 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
});
|
||||||
|
setTotalProgress(percentForBytes(completedByFile.reduce((sum, bytes) => sum + bytes, 0), 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;
|
||||||
|
setTotalProgress(percentForBytes(currentTotal, totalBytes));
|
||||||
|
setSingleFileProgress(fileIndex, file, percentForBytes(completedByFile[fileIndex] + loaded, file.size));
|
||||||
|
updateStatus(`${percentForBytes(currentTotal, totalBytes)}%`);
|
||||||
|
});
|
||||||
|
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();
|
||||||
|
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) {
|
function renderQueue(files, status) {
|
||||||
if (!uploadQueue) {
|
if (!uploadQueue) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
uploadQueue.hidden = files.length === 0;
|
uploadQueue.hidden = files.length === 0;
|
||||||
uploadQueue.replaceChildren();
|
uploadQueue.replaceChildren();
|
||||||
files.forEach((file) => {
|
files.forEach((file, index) => {
|
||||||
uploadQueue.append(createFileRow({
|
uploadQueue.append(createFileRow({
|
||||||
name: file.name,
|
name: file.name,
|
||||||
meta: window.Warpbox.formatBytes(file.size),
|
meta: window.Warpbox.formatBytes(file.size),
|
||||||
progress: status === "queued" ? 0 : 100,
|
progress: status === "queued" ? 0 : 100,
|
||||||
status,
|
status,
|
||||||
|
index,
|
||||||
|
removable: status === "queued",
|
||||||
}));
|
}));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function createFileRow(file) {
|
function createFileRow(file) {
|
||||||
const row = document.createElement("div");
|
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;
|
row.dataset.fileName = file.name;
|
||||||
|
if (typeof file.index === "number") {
|
||||||
|
row.dataset.fileIndex = file.index;
|
||||||
|
}
|
||||||
|
|
||||||
const body = document.createElement("span");
|
const body = document.createElement("span");
|
||||||
const name = document.createElement("strong");
|
const name = document.createElement("strong");
|
||||||
@@ -242,11 +912,53 @@
|
|||||||
fill.style.transform = `scaleX(${file.progress / 100})`;
|
fill.style.transform = `scaleX(${file.progress / 100})`;
|
||||||
bar.append(fill);
|
bar.append(fill);
|
||||||
side.append(percent, bar);
|
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);
|
row.append(body, side);
|
||||||
return row;
|
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) {
|
function setTotalProgress(percent) {
|
||||||
if (totalProgressBar) {
|
if (totalProgressBar) {
|
||||||
totalProgressBar.style.transform = `scaleX(${Math.max(0, Math.min(100, percent)) / 100})`;
|
totalProgressBar.style.transform = `scaleX(${Math.max(0, Math.min(100, percent)) / 100})`;
|
||||||
@@ -271,4 +983,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})`;
|
||||||
|
}
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -126,6 +126,33 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</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>
|
<button class="button button-primary" type="submit">Save settings</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,13 +14,39 @@
|
|||||||
<h2>Endpoints</h2>
|
<h2>Endpoints</h2>
|
||||||
<dl class="endpoint-list">
|
<dl class="endpoint-list">
|
||||||
<div><dt>Upload</dt><dd><code>POST /api/v1/upload</code></dd></div>
|
<div><dt>Upload</dt><dd><code>POST /api/v1/upload</code></dd></div>
|
||||||
<div><dt>Health</dt><dd><code>GET /api/v1/health</code></dd></div>
|
<div><dt>Resumable create</dt><dd><code>POST /api/v1/uploads/resumable</code></dd></div>
|
||||||
|
<div><dt>Resumable status</dt><dd><code>GET /api/v1/uploads/resumable/{sessionID}</code></dd></div>
|
||||||
|
<div><dt>Resumable chunk</dt><dd><code>PUT /api/v1/uploads/resumable/{sessionID}/files/{fileID}/chunks/{index}</code></dd></div>
|
||||||
|
<div><dt>Resumable complete</dt><dd><code>POST /api/v1/uploads/resumable/{sessionID}/complete</code></dd></div>
|
||||||
|
<div><dt>Health</dt><dd><code>GET /health</code></dd></div>
|
||||||
<div><dt>Request schema</dt><dd><a href="/api/v1/schemas/upload-request.json"><code>/api/v1/schemas/upload-request.json</code></a></dd></div>
|
<div><dt>Request schema</dt><dd><a href="/api/v1/schemas/upload-request.json"><code>/api/v1/schemas/upload-request.json</code></a></dd></div>
|
||||||
<div><dt>Response schema</dt><dd><a href="/api/v1/schemas/upload-response.json"><code>/api/v1/schemas/upload-response.json</code></a></dd></div>
|
<div><dt>Response schema</dt><dd><a href="/api/v1/schemas/upload-response.json"><code>/api/v1/schemas/upload-response.json</code></a></dd></div>
|
||||||
</dl>
|
</dl>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
|
<article class="card docs-card docs-card-wide">
|
||||||
|
<div class="card-content">
|
||||||
|
<h2>Resumable uploads</h2>
|
||||||
|
<p>Browser uploads use the resumable API by default. Custom clients can use the same flow: create a session with file metadata, upload exact-sized chunks, then complete the session. Chunks are temporary and are cleaned if the session expires.</p>
|
||||||
|
<pre><code># 1. Create a session.
|
||||||
|
curl -s {{.Data.BaseURL}}/api/v1/uploads/resumable \
|
||||||
|
-H 'Accept: application/json' \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"files":[{"name":"report.pdf","size":1048576,"contentType":"application/pdf"}],"expiresMinutes":1440}'
|
||||||
|
|
||||||
|
# 2. Upload each chunk using the returned sessionId, file id, and chunkSize.
|
||||||
|
dd if=./report.pdf bs=8388608 count=1 skip=0 2>/dev/null | \
|
||||||
|
curl -X PUT --data-binary @- \
|
||||||
|
{{.Data.BaseURL}}/api/v1/uploads/resumable/SESSION_ID/files/FILE_ID/chunks/0
|
||||||
|
|
||||||
|
# 3. Complete after all chunks are present. The response is the normal upload JSON.
|
||||||
|
curl -X POST -H 'Accept: application/json' \
|
||||||
|
{{.Data.BaseURL}}/api/v1/uploads/resumable/SESSION_ID/complete</code></pre>
|
||||||
|
<p class="muted-copy">For authenticated uploads, send the same <code>Authorization: Bearer <token></code> header on every resumable request. Incomplete chunks are stored under <code>data/tmp/uploads</code> before finalizing into the selected storage backend.</p>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
|
||||||
<article class="card docs-card">
|
<article class="card docs-card">
|
||||||
<div class="card-content">
|
<div class="card-content">
|
||||||
<h2>Curl upload</h2>
|
<h2>Curl upload</h2>
|
||||||
|
|||||||
@@ -24,64 +24,102 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
|
|
||||||
{{if .Data.Files}}
|
{{if .Data.Files}}
|
||||||
|
{{$processing := false}}{{range .Data.Files}}{{if .Processing}}{{$processing = true}}{{end}}{{end}}
|
||||||
|
{{if $processing}}
|
||||||
|
<div class="upload-processing-alert" role="status">
|
||||||
|
Some files are still processing. You can share this link now, but processing files will become available shortly.
|
||||||
|
</div>
|
||||||
|
{{end}}
|
||||||
|
{{$single := eq (len .Data.Files) 1}}
|
||||||
<div class="badge-row">
|
<div class="badge-row">
|
||||||
<span class="badge badge-expiry">Expires {{.Data.ExpiresLabel}}</span>
|
<span class="badge badge-expiry">Expires {{.Data.ExpiresLabel}}</span>
|
||||||
{{if .Data.MaxDownloads}}<span class="badge">{{.Data.DownloadCount}} / {{.Data.MaxDownloads}} downloads</span>{{end}}
|
{{if .Data.MaxDownloads}}<span class="badge">{{.Data.DownloadCount}} / {{.Data.MaxDownloads}} downloads</span>{{end}}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{{if not .Data.Locked}}
|
{{if not .Data.Locked}}
|
||||||
<a class="button button-primary button-wide" href="{{.Data.ZipURL}}">
|
{{if $single}}
|
||||||
<svg viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14" /></svg>
|
{{$first := index .Data.Files 0}}
|
||||||
Download zip
|
<a class="button button-primary button-wide" href="{{$first.DownloadURL}}" download="{{$first.Name}}">
|
||||||
</a>
|
<svg viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14" /></svg>
|
||||||
|
Download
|
||||||
|
</a>
|
||||||
|
{{else}}
|
||||||
|
<a class="button button-primary button-wide" href="{{.Data.ZipURL}}">
|
||||||
|
<svg viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14" /></svg>
|
||||||
|
Download zip
|
||||||
|
</a>
|
||||||
|
{{end}}
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|
||||||
<div class="view-toolbar" aria-label="File view options">
|
<div class="file-browser-window" data-file-browser-window>
|
||||||
<button class="button button-outline is-active" type="button" data-view-button="list">List</button>
|
<div class="file-browser-titlebar">
|
||||||
<button class="button button-outline" type="button" data-view-button="thumbs">Thumbnails</button>
|
<div>
|
||||||
<button class="button button-outline" type="button" data-preview-images>Preview images only</button>
|
<strong>File Browser</strong>
|
||||||
</div>
|
<span>{{len .Data.Files}} item{{if ne (len .Data.Files) 1}}s{{end}}</span>
|
||||||
|
</div>
|
||||||
<div class="download-list file-browser is-list" data-file-browser>
|
<div class="file-browser-window-actions" aria-hidden="true">
|
||||||
{{range .Data.Files}}
|
<span></span><span></span><span></span>
|
||||||
<article class="download-item file-card" data-kind="{{.PreviewKind}}" data-file-context data-preview-url="{{.URL}}" data-view-url="{{.DownloadURL}}?inline=1" data-download-url="{{.DownloadURL}}" data-file-name="{{.Name}}" data-reaction-card>
|
</div>
|
||||||
<a class="thumb-link" href="{{.DownloadURL}}?inline=1" aria-label="View {{.Name}}">
|
</div>
|
||||||
<img src="{{.ThumbnailURL}}" alt="" loading="lazy">
|
<div class="file-browser-toolbar" aria-label="File view options">
|
||||||
</a>
|
<div class="view-toolbar">
|
||||||
<a class="file-main" href="{{.DownloadURL}}?inline=1">
|
<button class="button button-outline icon-button" type="button" data-view-button="list" aria-pressed="false" aria-label="List view" title="List view">
|
||||||
<strong class="file-name" title="{{.Name}}">{{.Name}}</strong>
|
<svg viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01" /></svg>
|
||||||
<small>{{.Size}} · {{.ContentType}}</small>
|
<span class="sr-only">List view</span>
|
||||||
</a>
|
</button>
|
||||||
{{if not $.Data.Locked}}
|
<button class="button button-outline icon-button is-active" type="button" data-view-button="thumbs" aria-pressed="true" aria-label="Icon view" title="Icon view">
|
||||||
<div class="file-actions">
|
<svg viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true"><rect x="3" y="3" width="7" height="7" rx="1" /><rect x="14" y="3" width="7" height="7" rx="1" /><rect x="3" y="14" width="7" height="7" rx="1" /><rect x="14" y="14" width="7" height="7" rx="1" /></svg>
|
||||||
<a class="button button-outline preview-action" href="{{.DownloadURL}}?inline=1" target="_blank" rel="noopener noreferrer" data-preview-action data-view-label="View" data-copy-label="Copy link">
|
<span class="sr-only">Icon view</span>
|
||||||
<svg data-preview-view-icon viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true"><path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6Z" /><circle cx="12" cy="12" r="3" /></svg>
|
</button>
|
||||||
<svg data-preview-copy-icon viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true" hidden><rect width="14" height="14" x="8" y="8" rx="2" /><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" /></svg>
|
</div>
|
||||||
<span data-preview-label>View</span>
|
</div>
|
||||||
</a>
|
<div class="file-browser-head" aria-hidden="true">
|
||||||
<a class="button button-outline" href="{{.DownloadURL}}" download="{{.Name}}">
|
<span>Name</span>
|
||||||
<svg viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14" /></svg>
|
<span>Type</span>
|
||||||
Download
|
<span>Size</span>
|
||||||
</a>
|
</div>
|
||||||
</div>
|
<div class="download-list file-browser is-thumbs" data-file-browser>
|
||||||
<div class="file-reaction-dock" data-reaction-dock>
|
{{range .Data.Files}}
|
||||||
<div class="file-reactions" data-reaction-list>
|
<article class="download-item file-card {{if .Processing}}is-processing{{end}}" data-kind="{{.PreviewKind}}" {{if not .Processing}}data-file-context data-preview-url="{{.URL}}" data-view-url="{{.DownloadURL}}?inline=1" data-download-url="{{.DownloadURL}}"{{end}} data-file-name="{{.Name}}" data-reaction-card data-react-url="{{.ReactURL}}" data-reacted="{{if .Reacted}}true{{else}}false{{end}}">
|
||||||
{{range .Reactions}}
|
{{if .Processing}}<div class="file-open" aria-label="{{.Name}} is processing">{{else}}<a class="file-open" href="{{.DownloadURL}}?inline=1"{{if not $single}} target="_blank" rel="noopener noreferrer"{{end}} aria-label="Open {{.Name}}">{{end}}
|
||||||
<span class="reaction-pill" title="{{.Label}}">
|
<span class="file-media">
|
||||||
<img src="{{.URL}}" alt="{{.Label}}" loading="lazy">
|
{{if .HasThumbnail}}
|
||||||
<span>{{.Count}}</span>
|
<img class="file-thumb" src="{{.ThumbnailURL}}" alt="" loading="lazy">
|
||||||
</span>
|
{{else}}
|
||||||
|
{{if .IconURL}}<img class="file-icon file-icon-standard" src="{{.IconURL}}" alt="" loading="lazy">{{end}}
|
||||||
|
{{if .IconRetroURL}}<img class="file-icon file-icon-retro" src="{{.IconRetroURL}}" alt="" loading="lazy">{{end}}
|
||||||
|
{{end}}
|
||||||
|
</span>
|
||||||
|
<span class="file-main">
|
||||||
|
<strong class="file-name" title="{{.Name}}">{{.Name}}</strong>
|
||||||
|
<small>{{.Size}} · {{if .Processing}}Processing{{else}}{{.ContentType}}{{end}}</small>
|
||||||
|
</span>
|
||||||
|
<span class="file-type">{{if .Processing}}Processing{{else}}{{.ContentType}}{{end}}</span>
|
||||||
|
<span class="file-size">{{.Size}}</span>
|
||||||
|
{{if .Processing}}</div>{{else}}</a>{{end}}
|
||||||
|
{{if not $.Data.Locked}}
|
||||||
|
<div class="file-reaction-dock" data-reaction-dock>
|
||||||
|
<div class="file-reactions" data-reaction-list>
|
||||||
|
{{range .Reactions}}
|
||||||
|
<button class="reaction-pill {{if not .Visible}}is-hidden-summary{{end}}" type="button" title="{{.Label}}" data-reaction-pill data-reaction-emoji-id="{{.EmojiID}}" data-reaction-label="{{.Label}}" data-reaction-url="{{.URL}}" data-reaction-count="{{.Count}}" aria-label="{{if $.Data.Locked}}Reaction{{else}}React with {{.Label}}{{end}}">
|
||||||
|
<img src="{{.URL}}" alt="{{.Label}}" loading="lazy">
|
||||||
|
<span>{{.Count}}</span>
|
||||||
|
</button>
|
||||||
|
{{end}}
|
||||||
|
{{if .ReactionMore}}
|
||||||
|
<button class="reaction-more" type="button" data-reaction-more aria-label="Show all reactions">+{{.ReactionMore}}</button>
|
||||||
|
{{end}}
|
||||||
|
</div>
|
||||||
|
{{if not .Reacted}}
|
||||||
|
<button class="reaction-button" type="button" data-reaction-button data-react-url="{{.ReactURL}}" aria-label="React to {{.Name}}" title="React">
|
||||||
|
<svg viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true"><path d="M12 21a9 9 0 1 0-9-9 9 9 0 0 0 9 9Z" /><path d="M8 14s1.4 2 4 2 4-2 4-2" /><path d="M9 9h.01M15 9h.01" /></svg>
|
||||||
|
</button>
|
||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
{{if not .Reacted}}
|
{{end}}
|
||||||
<button class="reaction-button" type="button" data-reaction-button data-react-url="{{.ReactURL}}" aria-label="React to {{.Name}}" title="React">
|
</article>
|
||||||
<svg viewBox="0 0 24 24" role="img" focusable="false" aria-hidden="true"><path d="M12 21a9 9 0 1 0-9-9 9 9 0 0 0 9 9Z" /><path d="M8 14s1.4 2 4 2 4-2 4-2" /><path d="M9 9h.01M15 9h.01" /></svg>
|
{{end}}
|
||||||
</button>
|
</div>
|
||||||
{{end}}
|
|
||||||
</div>
|
|
||||||
{{end}}
|
|
||||||
</article>
|
|
||||||
{{end}}
|
|
||||||
</div>
|
</div>
|
||||||
{{if not .Data.Locked}}
|
{{if not .Data.Locked}}
|
||||||
<div class="reaction-picker" data-reaction-picker hidden>
|
<div class="reaction-picker" data-reaction-picker hidden>
|
||||||
@@ -90,6 +128,11 @@
|
|||||||
<strong>React</strong>
|
<strong>React</strong>
|
||||||
<button class="button button-ghost reaction-picker-close" type="button" data-reaction-close aria-label="Close reaction picker">Close</button>
|
<button class="button button-ghost reaction-picker-close" type="button" data-reaction-close aria-label="Close reaction picker">Close</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="reaction-existing" data-reaction-existing hidden>
|
||||||
|
<small>Existing reactions</small>
|
||||||
|
<div class="reaction-existing-list" data-reaction-existing-list></div>
|
||||||
|
</div>
|
||||||
|
<p class="reaction-readonly-note" data-reaction-readonly hidden>You already reacted to this file.</p>
|
||||||
<div class="reaction-picker-tabs" role="tablist" aria-label="Emoji themes">
|
<div class="reaction-picker-tabs" role="tablist" aria-label="Emoji themes">
|
||||||
{{range $index, $tab := .Data.EmojiTabs}}
|
{{range $index, $tab := .Data.EmojiTabs}}
|
||||||
<button type="button" class="reaction-tab {{if eq $index 0}}is-active{{end}}" data-reaction-tab="{{$tab.ID}}" role="tab" aria-selected="{{if eq $index 0}}true{{else}}false{{end}}">{{$tab.Label}}</button>
|
<button type="button" class="reaction-tab {{if eq $index 0}}is-active{{end}}" data-reaction-tab="{{$tab.ID}}" role="tab" aria-selected="{{if eq $index 0}}true{{else}}false{{end}}">{{$tab.Label}}</button>
|
||||||
|
|||||||
@@ -77,6 +77,7 @@
|
|||||||
<div class="form-footer">
|
<div class="form-footer">
|
||||||
<p id="file-summary">Choose one or more files to begin.</p>
|
<p id="file-summary">Choose one or more files to begin.</p>
|
||||||
<button class="button button-primary" type="submit">Upload files</button>
|
<button class="button button-primary" type="submit">Upload files</button>
|
||||||
|
<button class="button button-danger upload-new-button" type="button" id="new-upload" hidden>New upload</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
5
scripts/env/dev.env.example
vendored
@@ -9,6 +9,11 @@ WARPBOX_CLEANUP_ENABLED=true
|
|||||||
WARPBOX_CLEANUP_EVERY=1h
|
WARPBOX_CLEANUP_EVERY=1h
|
||||||
WARPBOX_THUMBNAIL_ENABLED=true
|
WARPBOX_THUMBNAIL_ENABLED=true
|
||||||
WARPBOX_THUMBNAIL_EVERY=1m
|
WARPBOX_THUMBNAIL_EVERY=1m
|
||||||
|
WARPBOX_RESUMABLE_UPLOADS_ENABLED=true
|
||||||
|
WARPBOX_RESUMABLE_CHUNK_MB=16
|
||||||
|
WARPBOX_RESUMABLE_RETENTION_HOURS=1
|
||||||
|
WARPBOX_RESUMABLE_CHUNK_MODE=same
|
||||||
|
WARPBOX_RESUMABLE_CHUNK_PATH=
|
||||||
WARPBOX_MAX_UPLOAD_SIZE_MB=16384
|
WARPBOX_MAX_UPLOAD_SIZE_MB=16384
|
||||||
WARPBOX_ANONYMOUS_UPLOADS_ENABLED=true
|
WARPBOX_ANONYMOUS_UPLOADS_ENABLED=true
|
||||||
WARPBOX_ANONYMOUS_MAX_UPLOAD_MB=512
|
WARPBOX_ANONYMOUS_MAX_UPLOAD_MB=512
|
||||||
|
|||||||