feat: polish workspace transfers and verify Craft server file workflows
This commit is contained in:
1 parent
7fd7ae6733
commit
c209f1effc
49 files changed
+1459
-670
No files matched your search
@@ -1,160 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Guidance for Claude when working in this repository (File Browser, `filebrowser/filebrowser`).
|
||||
|
||||
## Repo orientation
|
||||
|
||||
- Go backend (`github.com/filebrowser/filebrowser/v2`, ecosystem `go`) + Vue frontend under `frontend/`.
|
||||
- The project is in **maintenance-only mode** (see `SECURITY.md`). Prefer small, surgical, well-tested changes.
|
||||
- Version scheme: `v2.63.x`. Conventional-commit messages (`fix(scope): …`, `feat: …`, `chore: …`).
|
||||
- Verify with `go build ./...`, `go vet ./...`, `go test ./...`. Reuse existing test harnesses (e.g. `signToken`, `scopedUserStorage`, `handle`, `customFSUser`, `mockUserStore`).
|
||||
|
||||
---
|
||||
|
||||
# Handling security advisories
|
||||
|
||||
Use this playbook when asked to triage, verify, fix, or manage GitHub security advisories.
|
||||
All advisory state lives on GitHub and is driven with the `gh` CLI. States are
|
||||
`triage → draft → published`, plus `closed`.
|
||||
|
||||
## 1. Fetch
|
||||
|
||||
```bash
|
||||
# List by state (also: published, draft, closed)
|
||||
gh api '/repos/filebrowser/filebrowser/security-advisories?state=triage&per_page=100' \
|
||||
--jq '.[] | {ghsa_id, severity, summary, state}'
|
||||
|
||||
# Full report for one advisory (read .summary and .description)
|
||||
gh api /repos/filebrowser/filebrowser/security-advisories/GHSA-xxxx-xxxx-xxxx \
|
||||
--jq '.summary, "---", .description'
|
||||
```
|
||||
|
||||
Always pull the **published** set too — you need it to dedup against.
|
||||
|
||||
## 2. Verify each report — do NOT trust the report text
|
||||
|
||||
Read the actual source **at HEAD** and reach one verdict per advisory:
|
||||
|
||||
- **CONFIRMED** — defect exists at HEAD. Quote the exact `file:line`.
|
||||
- **FIXED** — already patched (find the fix commit).
|
||||
- **FALSE / NOT APPLICABLE** — claim is wrong, or targets a different project.
|
||||
- **NOT EXPLOITABLE** — pattern exists but no code path can reach the precondition.
|
||||
- **DUPLICATE** — of a published advisory, or of another triage advisory.
|
||||
|
||||
Common traps — check each before accepting a report:
|
||||
|
||||
- **"Incomplete fix of a prior advisory."** Read the original fix commit and confirm the *specific*
|
||||
sibling code path is actually still unguarded — a prior fix may already cover a related path.
|
||||
- **Wrong project.** Confirm the referenced files, symbols, and endpoints exist in this repo; reports
|
||||
sometimes describe a fork. If the cited code isn't here, close as not applicable.
|
||||
- **"Legacy / upgraded / imported records are affected."** Trace the field's git history and confirm that
|
||||
some released version could actually produce such a record before believing it
|
||||
(`git log -S'Field' -- path`, `git show <commit>`, `git tag --contains <commit>`).
|
||||
- **Overlapping reports.** Two triage advisories may share one root cause — consolidate and fix once.
|
||||
- **Known, intentionally-unaddressed classes.** Some areas are known and tracked but not fixed (see
|
||||
`SECURITY.md`'s Known Issues); matching reports are duplicates.
|
||||
|
||||
Record, per advisory: verdict, the `file:line` evidence, exploitability preconditions
|
||||
(default config? platform-specific? auth required?), and the disposition.
|
||||
|
||||
## 3. Fix (one commit per advisory)
|
||||
|
||||
- Branch off `master` first; never commit fixes directly to `master`.
|
||||
- **One commit per fix**, each referencing the GHSA in the body (`Refs GHSA-xxxx-xxxx-xxxx`).
|
||||
- When several advisories share a root cause because parallel code paths diverged, **centralize** the logic
|
||||
(e.g. `settings.CreateUserHome` used by signup, proxy, and hook provisioning) so they cannot drift again.
|
||||
- Keep it surgical; match surrounding style.
|
||||
|
||||
## 4. Add a regression test per fix
|
||||
|
||||
- Reuse the existing harnesses; add a focused test asserting the fixed behavior (and that the legitimate
|
||||
path still works). Commit tests alongside the fixes (`test(scope): …`, `Refs GHSA-…`).
|
||||
- Run `go test ./... && go vet ./...` before finishing.
|
||||
|
||||
## 5. Severity — set a CVSS vector, don't hand-assert
|
||||
|
||||
Set a CVSS v3.1 vector; GitHub derives the score **and** severity from it (overriding the plain `severity`
|
||||
field). Encode the real preconditions in the vector so the band is defensible:
|
||||
|
||||
- Requires a specific target configuration/platform (e.g. case-insensitive FS) → **AC:H**.
|
||||
- Unauthenticated vs needs an account → **PR:N / PR:L**.
|
||||
- Keep it consistent with the **predecessor CVE's** rating (an incomplete-fix follow-up should not outrank
|
||||
its parent). Bands: `0.1–3.9` low, `4.0–6.9` medium, `7.0–8.9` high, `9.0–10.0` critical.
|
||||
|
||||
```bash
|
||||
gh api -X PATCH /repos/filebrowser/filebrowser/security-advisories/GHSA-xxxx-xxxx-xxxx \
|
||||
-f cvss_vector_string='CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H' \
|
||||
--jq '{ghsa_id, severity, score: .cvss.score, vector: .cvss.vector_string}'
|
||||
```
|
||||
|
||||
## 6. Clean up the title
|
||||
|
||||
Rewrite reporter titles to the concise, sentence-case, backtick-free style of the published advisories
|
||||
(state the vuln; drop "Incomplete fix of…" prefixes and jargon). The title is the `summary` field:
|
||||
|
||||
```bash
|
||||
gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx \
|
||||
-f summary='Proxy-auth auto-provisioning ignores createUserDir and grants the server root scope'
|
||||
```
|
||||
|
||||
## 7. Rewrite the body into the standard structure
|
||||
|
||||
Reporter reports arrive in whatever shape the reporter used. Before drafting, rewrite the
|
||||
`description` into the sections below — **reusing the reporter's own wording wherever it is
|
||||
accurate**, rather than paraphrasing it. Drop the greeting, the offer to help, and any claim the
|
||||
verification in step 2 disproved. Keep sections in this order and omit the ones that don't apply:
|
||||
|
||||
| Section | Contents |
|
||||
| --- | --- |
|
||||
| `## Summary` | What the defect is, in two or three sentences. Note the version it was reported against and the range it was verified over. |
|
||||
| `## Details` | Root cause, naming `file.go`, the function, and a short quote of the **pre-fix** code. |
|
||||
| `## PoC` | The reporter's reproduction steps and observed result, trimmed to the essentials. |
|
||||
| `## Impact` | Who can exploit it (privilege level, preconditions) and what they get. |
|
||||
| `## Patches` | Fixed version plus a link to the fix commit, and one sentence on what the fix does. Mention it if the reporter re-tested and confirmed. |
|
||||
| `## Workarounds` | Real mitigations, or `None. Upgrade to vX.Y.Z.` |
|
||||
| `## Out of scope` | Anything in the original report deliberately **not** treated as a vulnerability, with the reasoning. Needed whenever the advisory is narrower than the report. |
|
||||
| `## References` | Fix and regression-test commit links. |
|
||||
|
||||
Use `##` headings (matching the published advisories) and keep the body in the maintainer's voice —
|
||||
first person ("I reproduced…") belongs only inside quoted PoC steps.
|
||||
|
||||
Send it as a file so the Markdown survives shell quoting:
|
||||
|
||||
```bash
|
||||
jq -Rs '{description: .}' desc.md \
|
||||
| gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx --input -
|
||||
```
|
||||
|
||||
## 8. Set affected & patched versions
|
||||
|
||||
The package is always `{ecosystem: "go", name: "github.com/filebrowser/filebrowser/v2"}`.
|
||||
|
||||
- `vulnerable_version_range` — `<= <latest released version>` (the newest tag; find it with
|
||||
`git tag --list 'v2.*' --sort=-version:refname | head -1`).
|
||||
- `patched_versions` — the **next** release that will actually ship the fix. It doesn't exist just
|
||||
because the branch does; it still has to be cut. **When unsure which version that will be, ask.**
|
||||
|
||||
Replace the placeholder versions below before sending:
|
||||
|
||||
```bash
|
||||
printf '%s' '{"vulnerabilities":[{"package":{"ecosystem":"go","name":"github.com/filebrowser/filebrowser/v2"},"vulnerable_version_range":"<= <latest>","patched_versions":"<next>","vulnerable_functions":[]}]}' \
|
||||
| gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx --input -
|
||||
```
|
||||
|
||||
## 9. Move state / close, by disposition
|
||||
|
||||
```bash
|
||||
gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx -f state=draft # fixed, awaiting release
|
||||
gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx -f state=closed # duplicate / N-A / not-exploitable
|
||||
```
|
||||
|
||||
- **CONFIRMED & fixed** → metadata done → **draft**. Publish after the patched release ships.
|
||||
- **DUPLICATE / NOT APPLICABLE / NOT EXPLOITABLE** → **closed**.
|
||||
- **DEFERRED** (confirmed but not yet fixed) → leave in **triage** with a note.
|
||||
- The REST API **cannot post advisory comments** — replies to reporters (dup notice, evidence, links to
|
||||
the relevant tracking issue) must be posted manually in the advisory UI. Draft the text for the maintainer.
|
||||
|
||||
## 10. Release & publish
|
||||
|
||||
Push the branch, open a PR, merge, tag/release the `patched_versions` you set, then publish the drafts.
|
||||
Confirm outward-facing/irreversible advisory actions (close, publish) with the maintainer before doing them.
|
||||
@@ -1 +0,0 @@
|
||||
* @filebrowser/maintainers
|
||||
@@ -1,18 +1,21 @@
|
||||
# File Browser SSO
|
||||
# File Browser
|
||||
|
||||
Файловое пространство для AniDev: вход через SSO, удобная работа с файлами и короткие публичные ссылки.
|
||||
**Ваши файлы, ссылки и браузерные инструменты — на своём сервере.**
|
||||
|
||||
- **Один вход.** OpenID Connect с PKCE S256; роли `Master Admin` и `FS Admin` дают права администратора.
|
||||
- **Лёгкий интерфейс.** Светлая и тёмная темы, системные шрифты, адаптивная вёрстка. Редактор, переводы и диалоги загружаются по требованию.
|
||||
- **Понятные ссылки.** Собственное имя при публикации: `https://files.example.com/s/quarterly-report`, пароль и срок действия.
|
||||
- **Один бинарник.** Сервер и интерфейс в `filebrowser`; на Debian не нужны Node.js, Go или отдельная СУБД.
|
||||
- **Настройка через `filebrowser init`.** Мастер создаёт конфигурацию и базу; локальных паролей и регистрации нет.
|
||||
[Скачать](https://git.anidev.ru/SantaSpeen/filebrowser/releases) · [Установка](docs/deployment.md) · [Разработка](#сборка)
|
||||
|
||||

|
||||

|
||||
|
||||
## Начало работы
|
||||
[Мобильный интерфейс](docs/images/workspace-mobile.png)
|
||||
|
||||
Подробная установка, подключение SSO и пример systemd/nginx: [инструкция для Debian](docs/deployment.md).
|
||||
- **SSO вместо паролей.** OIDC, роли `Master Admin` и `FS Admin`, профиль и аватар.
|
||||
- **Удобное пространство.** Дерево папок, закладки, поиск, меню действий, светлая и тёмная темы, мобильная вёрстка.
|
||||
- **Мои ссылки.** Короткие адреса `/s/имя`, несколько ссылок на файл, необязательные пароль и срок действия.
|
||||
- **Предпросмотр.** Изображения, PDF, DICOM 2D, текст, Markdown, CSV, книги, аудио и видео. ZIP показывает дерево без распаковки.
|
||||
- **Craft-аддоны.** Установка и обновление из панели управления; совместимые редакторы открывают и сохраняют файлы на сервере.
|
||||
- **Один бинарник.** Debian amd64 и Windows amd64; отдельная СУБД и Node.js для запуска не нужны.
|
||||
|
||||
## Запуск
|
||||
|
||||
```sh
|
||||
chmod +x filebrowser
|
||||
@@ -20,11 +23,9 @@ chmod +x filebrowser
|
||||
./filebrowser
|
||||
```
|
||||
|
||||
Мастер напечатает точный callback URL для приложения в SSO. Конфигурация хранится в `.filebrowser.json` с правами `0600`; `.env` не используется.
|
||||
На Windows: `filebrowser.exe init`, затем `filebrowser.exe`. Мастер настраивает хранилище и SSO без `.env`. Подробности, systemd и nginx — в [инструкции](docs/deployment.md).
|
||||
|
||||
Сессия — 8 часов, с выходом после 30 минут бездействия, как в VTNL Panel. Роли обновляются при входе. Смена роли или блокировка в SSO не отзывает уже существующую локальную сессию автоматически. Перезапуск File Browser завершает все его сессии.
|
||||
|
||||
## Разработка и сборка
|
||||
## Сборка
|
||||
|
||||
Go 1.26+, Node.js 24+, pnpm 10.33.4.
|
||||
|
||||
@@ -32,20 +33,14 @@ Go 1.26+, Node.js 24+, pnpm 10.33.4.
|
||||
cd frontend
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm run build
|
||||
pnpm run test
|
||||
pnpm test
|
||||
cd ..
|
||||
go test ./...
|
||||
go build -o filebrowser .
|
||||
```
|
||||
|
||||
Готовый архив Debian amd64: `sh scripts/build-release.sh` на Linux или `./scripts/build-release.ps1` на Windows. Результаты — `build/filebrowser-linux-amd64.tar.gz` и `build/SHA256SUMS`. Бинарник собирается с `CGO_ENABLED=0`, `GOAMD64=v1`.
|
||||
Релиз для Debian: `sh scripts/build-release.sh` или `./scripts/build-release.ps1`. Архивы и контрольные суммы находятся в `build/`.
|
||||
|
||||
Ветки:
|
||||
`dev` — разработка · `master` — страница проекта · `master-copy` — исходная версия upstream.
|
||||
|
||||
- `master-copy` — неизменённая исходная версия upstream;
|
||||
- `dev` — исходники и разработка этого форка;
|
||||
- `master` — краткая презентация и ссылки на сборки.
|
||||
|
||||
Обзор проверок и ограничений: [безопасность](docs/SECURITY-REVIEW.md). Команды и хуки отключены, выходящие за файловую область симлинки запрещены. Старые ссылки `/share/{key}` сохранены как совместимый маршрут.
|
||||
|
||||
Основано на [File Browser](https://github.com/filebrowser/filebrowser), архивированном upstream. Это независимый форк. Лицензия [Apache-2.0](LICENSE), авторство исходных участников сохранено.
|
||||
Независимый форк [File Browser](https://github.com/filebrowser/filebrowser). [Apache-2.0](LICENSE). [Безопасность и ограничения](docs/SECURITY-REVIEW.md).
|
||||
+5
-26
@@ -1,30 +1,9 @@
|
||||
# Security Policy
|
||||
# Безопасность
|
||||
|
||||
## Supported Versions
|
||||
Этот репозиторий — независимый форк File Browser. Политика архивированного upstream к нему не относится.
|
||||
|
||||
No version receives security fixes. The last planned release has already shipped and no further changes will be merged.
|
||||
Ограничения и выполненные проверки: [обзор безопасности](docs/SECURITY-REVIEW.md).
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | --------- |
|
||||
| 2.x | ❌ |
|
||||
| < 2.0 | ❌ |
|
||||
При обнаружении уязвимости сообщите владельцу этого форка приватно. Укажите версию или коммит, шаги воспроизведения и влияние. Не публикуйте токены, пароли и реальные медицинские файлы.
|
||||
|
||||
## Before Reporting
|
||||
|
||||
This project is being wound down. To avoid duplicates, first check the [existing advisories](https://github.com/filebrowser/filebrowser/security/advisories) and open issues, and confirm:
|
||||
|
||||
- **It concerns this project, not a fork.** Reports about code, features, or endpoints that don't exist here belong to the relevant fork.
|
||||
- **It isn't an already-known class** that remains unaddressed. Those are listed under [Security](README.md#security) in the README; reports covering them are likely to be closed as duplicates.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Until 2026-09-01, report privately via the [Security](https://github.com/filebrowser/filebrowser/security) page. After that date this repository is read-only and reports can no longer be submitted.
|
||||
|
||||
Please include, where possible:
|
||||
|
||||
- The commit the issue was found at
|
||||
- A plaintext proof of concept (no binaries)
|
||||
- Steps to reproduce
|
||||
- Recommended remediation, if any
|
||||
|
||||
No fix will ship for any report: the last planned release has already shipped and no further changes will be merged. Reports may still be published as advisories so that people running File Browser can assess their exposure.
|
||||
Для размещения в интернете используйте HTTPS и своевременно обновляйте сервер и аддоны. Наличие проверок не гарантирует отсутствия уязвимостей.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Проверка 3.1.0
|
||||
|
||||
Edge/Chromium, Windows amd64; 1440×1000 и 390×844. Изолированное временное хранилище, настоящие HTTP-обработчики сервера, синтетические файлы. Реальные пользовательские данные и SSO не использовались.
|
||||
|
||||
## Интерфейс и файловые операции
|
||||
|
||||
- Предпросмотр PNG, JPEG, GIF, BMP, TIFF, WebP, SVG, PDF, DICOM 2D, TXT, Markdown, CSV, JSON, XML, HTML, JavaScript, ZIP, EPUB, WAV; WebM проверен отдельно.
|
||||
- Настройки, панель управления, пользователи, публичная ссылка и парольная форма, длинные имена, серверный диалог открытия. Проверены снимки экранов и горизонтальное переполнение.
|
||||
- Создание папки, загрузка, копирование, перемещение, изменение, скачивание и удаление через реальный сервер.
|
||||
- Загрузка 3 МиБ по частям, новая статистика и отмена; сравнение полученного файла с исходными байтами.
|
||||
- Несколько ссылок на один файл, независимые пароль и срок действия.
|
||||
|
||||
## Craft
|
||||
|
||||
| Инструмент | Результат |
|
||||
| --- | --- |
|
||||
| WordCraft | Изменённый текст найден внутри DOCX; сохранение и повторное открытие |
|
||||
| GridCraft | Значение ячейки найдено внутри XLSX; сохранение и повторное открытие |
|
||||
| DeckCraft | Сохранение и повторное открытие собственного `.deckcraft` |
|
||||
| PdfCraft | Пометка сохранена в PDF; повторное открытие |
|
||||
| PhotoCraft | Рисование, сохранение отдельного PSD и повторное открытие; исходный PNG сохранён |
|
||||
| VectorCraft | SVG открыт, проект сохранён в `.vectorcraft` и открыт повторно |
|
||||
| DesignCraft | Валидный проект сохранён и повторно открыт |
|
||||
| CADCraft | DXF сохранён и повторно открыт |
|
||||
| SoundCraft | Отключён: официальная веб-сборка работает только с демосессией |
|
||||
| FigCraft | Отключён: надёжная загрузка/выгрузка серверного проекта не подтверждена |
|
||||
| LightCraft | Отключён: изображение открывается, надёжный экспорт на сервер не подтверждён |
|
||||
|
||||
Открытие второго документа из WordCraft через серверный диалог проверено отдельно: изменения записаны во второй файл, первый остался неизменным.
|
||||
|
||||
Для проверенных сохранений сопоставлены отправленные данные и файл на диске. Это проверка представительных форматов, а не гарантия совместимости каждого импортируемого формата или сложного документа. Мобильная вёрстка сторонних Craft-инструментов определяется самими инструментами.
|
||||
|
||||
DICOM 3D временно выключен; сохранённые предпочтения не удалены. Проверки 2D и декодирования остаются.
|
||||
|
||||
## Повторение
|
||||
|
||||
Обычные проверки: `pnpm --dir frontend test`, `pnpm --dir frontend lint`, `pnpm --dir frontend build`, `go test ./...`, `go vet ./...`.
|
||||
|
||||
Для браузерных сценариев предусмотрен `TestWorkspaceBrowserQA`: задайте `FILEBROWSER_QA=1`, `FILEBROWSER_QA_SCRIPT` (абсолютный путь к `frontend/scripts/check-workspace.cjs` или `check-previews.cjs`), `FILEBROWSER_QA_FIXTURES`, `FILEBROWSER_QA_ADDONS`, `FILEBROWSER_QA_OUTPUT`, `PLAYWRIGHT_MODULE` и `BROWSER_EXECUTABLE`. Затем `go test ./http -run TestWorkspaceBrowserQA -v -count=1`. Сценарии требуют тестовые файлы с именами, перечисленными в их исходниках; авторизация подставляется только внутри тестового бинарника.
|
||||
|
||||
Linux-бинарник собран для amd64/v1 без CGO; запуск на Debian в этой среде не проверялся.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 99 KiB |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "filebrowser-frontend",
|
||||
"version": "3.0.0",
|
||||
"version": "3.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
@@ -38,7 +38,6 @@
|
||||
"pdfjs-dist": "^6.4.299",
|
||||
"pinia": "^3.0.4",
|
||||
"pretty-bytes": "^7.2.0",
|
||||
"qrcode.vue": "^3.11.0",
|
||||
"tus-js-client": "^4.3.1",
|
||||
"utif": "^3.1.0",
|
||||
"video.js": "^8.24.2",
|
||||
|
||||
Generated
-12
@@ -75,9 +75,6 @@ importers:
|
||||
pretty-bytes:
|
||||
specifier: ^7.2.0
|
||||
version: 7.2.0
|
||||
qrcode.vue:
|
||||
specifier: ^3.11.0
|
||||
version: 3.11.0(vue@3.5.44(typescript@5.9.3))
|
||||
tus-js-client:
|
||||
specifier: ^4.3.1
|
||||
version: 4.3.1
|
||||
@@ -2526,11 +2523,6 @@ packages:
|
||||
resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
qrcode.vue@3.11.0:
|
||||
resolution: {integrity: sha512-PnaO9yqcEVsH9euUmo4Nn0JZMkNwk4u6fDUosKjDTXv2Cgv7rHZhr2D8Iq54clBvSycOESwgUE/rw/tBRBjIVg==}
|
||||
peerDependencies:
|
||||
vue: ^3.0.0
|
||||
|
||||
quansync@0.2.11:
|
||||
resolution: {integrity: sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==}
|
||||
|
||||
@@ -5427,10 +5419,6 @@ snapshots:
|
||||
dependencies:
|
||||
hookified: 2.2.0
|
||||
|
||||
qrcode.vue@3.11.0(vue@3.5.44(typescript@5.9.3)):
|
||||
dependencies:
|
||||
vue: 3.5.44(typescript@5.9.3)
|
||||
|
||||
quansync@0.2.11: {}
|
||||
|
||||
querystringify@2.2.0: {}
|
||||
|
||||
@@ -124,29 +124,8 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
await page.goto(base + "/settings/profile");
|
||||
await page.getByLabel("3D preview quality").selectOption("half");
|
||||
await page.getByLabel("Voxel memory limit").selectOption("512");
|
||||
await page.getByLabel("Initial opacity").fill("50");
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(r) => r.url().endsWith("/api/users/1") && r.status() === 200
|
||||
),
|
||||
page.getByRole("button", { name: "Save", exact: true }).click(),
|
||||
]);
|
||||
await page.reload();
|
||||
await page.getByLabel("3D preview quality").waitFor();
|
||||
if (
|
||||
(await page.getByLabel("3D preview quality").inputValue()) !== "half" ||
|
||||
(await page.getByLabel("Voxel memory limit").inputValue()) !== "512"
|
||||
)
|
||||
throw new Error("3D profile settings were not restored");
|
||||
await page.getByLabel("3D preview quality").selectOption("auto");
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(r) => r.url().endsWith("/api/users/1") && r.status() === 200
|
||||
),
|
||||
page.getByRole("button", { name: "Save", exact: true }).click(),
|
||||
]);
|
||||
if (await page.getByLabel("3D preview quality").count())
|
||||
throw new Error("Disabled 3D settings are still visible");
|
||||
await page.goto(base + "/files/series/scan_1.dcm");
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
@@ -155,32 +134,13 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
null,
|
||||
{ timeout: 20000 }
|
||||
);
|
||||
await page
|
||||
.getByRole("button", { name: "Open as 3D (3)", exact: true })
|
||||
.click();
|
||||
await page
|
||||
.locator(".dicom-volume-stage canvas")
|
||||
.waitFor({ timeout: 20000 });
|
||||
if (
|
||||
(await page.locator('.dicom-volume input[type="range"]').inputValue()) !==
|
||||
"0.5"
|
||||
(await page.locator(".dicom-volume-stage").count()) ||
|
||||
(await page.getByRole("button", { name: /Open as 3D/ }).count())
|
||||
)
|
||||
throw new Error("Viewer ignored profile opacity");
|
||||
for (const label of ["Axial", "Sagittal", "Coronal", "3D"]) {
|
||||
await page.getByRole("button", { name: label, exact: true }).click();
|
||||
await page.waitForTimeout(150);
|
||||
}
|
||||
await page.getByRole("button", { name: "Back to 2D", exact: true }).click();
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
!document.querySelector(".dicom-volume-stage") &&
|
||||
document.querySelector(".dicom-viewer .document-stage canvas")
|
||||
?.width === 2
|
||||
);
|
||||
throw new Error("3D must remain disabled");
|
||||
if (errors.length) throw new Error(errors.join("\n"));
|
||||
console.log(
|
||||
"DICOM preview in embedded server: 2D, series offer, 3D, MPR and return to 2D passed"
|
||||
);
|
||||
console.log("DICOM preview: 2D passed; 3D is disabled");
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.close();
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
const fs = require("node:fs"),
|
||||
path = require("node:path"),
|
||||
{ pathToFileURL } = require("node:url");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const base = process.env.FILEBROWSER_QA_URL,
|
||||
root = process.env.FILEBROWSER_QA_ROOT,
|
||||
out = process.env.FILEBROWSER_QA_OUTPUT;
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const { fixture } = await import(
|
||||
pathToFileURL(
|
||||
path.resolve(__dirname, "../src/utils/__tests__/fixtures/dicom.ts")
|
||||
)
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(root, "scan_1.dcm"),
|
||||
Buffer.from(fixture(16, { slice: 0 }))
|
||||
);
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
args: [
|
||||
"--use-angle=swiftshader",
|
||||
"--enable-unsafe-swiftshader",
|
||||
"--autoplay-policy=no-user-gesture-required",
|
||||
],
|
||||
});
|
||||
const results = [];
|
||||
try {
|
||||
for (const mobile of [false, true]) {
|
||||
const context = await browser.newContext({
|
||||
viewport: mobile
|
||||
? { width: 390, height: 844 }
|
||||
: { width: 1440, height: 1000 },
|
||||
isMobile: mobile,
|
||||
hasTouch: mobile,
|
||||
acceptDownloads: true,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
let errors = [];
|
||||
page.on("pageerror", (e) => errors.push(String(e)));
|
||||
page.on("response", (r) => {
|
||||
if (
|
||||
r.status() >= 400 &&
|
||||
new URL(r.url()).pathname.startsWith("/static/")
|
||||
)
|
||||
errors.push(`${r.status()} ${r.url()}`);
|
||||
});
|
||||
await page.goto(base + "/files/");
|
||||
await page.waitForTimeout(1200);
|
||||
await page.screenshot({
|
||||
path: path.join(out, `${mobile ? "mobile" : "desktop"}-listing.png`),
|
||||
fullPage: true,
|
||||
});
|
||||
for (const name of [
|
||||
"image.png",
|
||||
"image.jpg",
|
||||
"image.gif",
|
||||
"image.bmp",
|
||||
"image.tiff",
|
||||
"image.webp",
|
||||
"image.svg",
|
||||
"notes.txt",
|
||||
"report.md",
|
||||
"table.csv",
|
||||
"data.json",
|
||||
"config.xml",
|
||||
"index.html",
|
||||
"script.js",
|
||||
"document.pdf",
|
||||
"archive.zip",
|
||||
"book.epub",
|
||||
"sound.wav",
|
||||
"scan_1.dcm",
|
||||
"unsupported.bin",
|
||||
]) {
|
||||
errors = [];
|
||||
await page.goto(base + "/files/" + encodeURIComponent(name));
|
||||
await page.waitForTimeout(name.endsWith(".epub") ? 1800 : 800);
|
||||
if (/^image\./.test(name)) {
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
[...document.querySelectorAll("#previewer img")].some(
|
||||
(i) => i.naturalWidth > 0
|
||||
),
|
||||
null,
|
||||
{ timeout: 15000 }
|
||||
);
|
||||
}
|
||||
const state = await page.evaluate(() => ({
|
||||
overflow: document.documentElement.scrollWidth > innerWidth + 1,
|
||||
text: document.body.innerText.slice(-500),
|
||||
canvas: [...document.querySelectorAll("canvas")].map((c) => [
|
||||
c.width,
|
||||
c.height,
|
||||
]),
|
||||
images: [...document.querySelectorAll("#previewer img")].map((i) => [
|
||||
i.naturalWidth,
|
||||
i.naturalHeight,
|
||||
]),
|
||||
}));
|
||||
const label =
|
||||
(mobile ? "mobile" : "desktop") + "-" + name.replaceAll(".", "-");
|
||||
await page.screenshot({
|
||||
path: path.join(out, label + ".png"),
|
||||
fullPage: true,
|
||||
});
|
||||
results.push({ mobile, name, ...state, errors: [...errors] });
|
||||
fs.writeFileSync(
|
||||
path.join(out, "results.json"),
|
||||
JSON.stringify(results, null, 2)
|
||||
);
|
||||
}
|
||||
for (const route of [
|
||||
"/settings/profile",
|
||||
"/settings/shares",
|
||||
"/settings/global",
|
||||
]) {
|
||||
errors = [];
|
||||
await page.goto(base + route);
|
||||
await page.waitForTimeout(800);
|
||||
await page.screenshot({
|
||||
path: path.join(
|
||||
out,
|
||||
(mobile ? "mobile" : "desktop") +
|
||||
route.replaceAll("/", "-") +
|
||||
".png"
|
||||
),
|
||||
fullPage: true,
|
||||
});
|
||||
results.push({
|
||||
mobile,
|
||||
route,
|
||||
overflow: await page.evaluate(
|
||||
() => document.documentElement.scrollWidth > innerWidth + 1
|
||||
),
|
||||
errors: [...errors],
|
||||
});
|
||||
}
|
||||
await context.close();
|
||||
}
|
||||
for (const r of results) {
|
||||
if (r.overflow || r.errors?.length) throw Error(JSON.stringify(r));
|
||||
}
|
||||
console.log("QA completed", results.length);
|
||||
fs.writeFileSync(
|
||||
path.join(out, "results.json"),
|
||||
JSON.stringify(results, null, 2)
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
})().catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
const fs = require("node:fs"),
|
||||
path = require("node:path"),
|
||||
assert = require("node:assert/strict");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const base = process.env.FILEBROWSER_QA_URL,
|
||||
root = process.env.FILEBROWSER_QA_ROOT,
|
||||
out = process.env.FILEBROWSER_QA_OUTPUT;
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const b = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"],
|
||||
});
|
||||
const result = [];
|
||||
try {
|
||||
const p = await b.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
p.on("dialog", (d) => d.accept());
|
||||
const request = async (method, url, data) => {
|
||||
let r = await p.request.fetch(base + url, {
|
||||
method,
|
||||
data,
|
||||
headers: { "X-FB-Request": "1" },
|
||||
});
|
||||
assert(
|
||||
r.ok(),
|
||||
method + " " + url + ":" + r.status() + " " + (await r.text())
|
||||
);
|
||||
return r;
|
||||
};
|
||||
await request("POST", "/api/resources/projects/");
|
||||
await request("POST", "/api/resources/projects/test.txt", "Hello server");
|
||||
await request(
|
||||
"PATCH",
|
||||
"/api/resources/projects/test.txt?action=copy&destination=%2Fprojects%2Fcopy.txt"
|
||||
);
|
||||
await request(
|
||||
"PATCH",
|
||||
"/api/resources/projects/copy.txt?action=rename&destination=%2Frenamed.txt"
|
||||
);
|
||||
await request("PUT", "/api/resources/renamed.txt", "Updated file");
|
||||
assert.equal(
|
||||
await (await request("GET", "/api/raw/renamed.txt")).text(),
|
||||
"Updated file"
|
||||
);
|
||||
await request("DELETE", "/api/resources/renamed.txt");
|
||||
assert(!fs.existsSync(path.join(root, "renamed.txt")));
|
||||
result.push("create/upload/copy/move/update/download/delete");
|
||||
await request("POST", "/api/share/notes.txt", { key: "qa-main" });
|
||||
await request("POST", "/api/share/notes.txt", {
|
||||
key: "qa-protected",
|
||||
password: "test-password",
|
||||
expires: "1",
|
||||
unit: "hours",
|
||||
});
|
||||
let links = await (await request("GET", "/api/share/notes.txt")).json();
|
||||
assert.equal(links.length, 2);
|
||||
result.push("multiple shares, optional password and expiration");
|
||||
await p.goto(base + "/files/");
|
||||
let video = await p.evaluate(async () => {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = 320;
|
||||
c.height = 180;
|
||||
let ctx = c.getContext("2d");
|
||||
ctx.fillStyle = "#21334d";
|
||||
ctx.fillRect(0, 0, 320, 180);
|
||||
ctx.fillStyle = "white";
|
||||
ctx.font = "22px sans-serif";
|
||||
ctx.fillText("Video preview", 70, 90);
|
||||
let rec = new MediaRecorder(c.captureStream(10), {
|
||||
mimeType: "video/webm",
|
||||
}),
|
||||
chunks = [];
|
||||
rec.ondataavailable = (e) => chunks.push(e.data);
|
||||
let done = new Promise(
|
||||
(resolve) =>
|
||||
(rec.onstop = async () =>
|
||||
resolve([...new Uint8Array(await new Blob(chunks).arrayBuffer())]))
|
||||
);
|
||||
rec.start();
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
rec.stop();
|
||||
return done;
|
||||
});
|
||||
fs.writeFileSync(path.join(root, "movie.webm"), Buffer.from(video));
|
||||
await p.route("**/api/tus/**", async (route) => {
|
||||
if (route.request().method() === "PATCH")
|
||||
await new Promise((r) => setTimeout(r, 1800));
|
||||
await route.continue().catch(() => {});
|
||||
});
|
||||
let payload = Buffer.alloc(3 * 1024 * 1024, 65);
|
||||
await p
|
||||
.locator("#upload-input")
|
||||
.setInputFiles({
|
||||
name: "upload-check.txt",
|
||||
mimeType: "text/plain",
|
||||
buffer: payload,
|
||||
});
|
||||
await p.locator(".upload-files").waitFor();
|
||||
await p.screenshot({ path: path.join(out, "desktop-upload.png") });
|
||||
await p.locator(".transfer-header button").first().click();
|
||||
await p.screenshot({ path: path.join(out, "desktop-upload-expanded.png") });
|
||||
await p
|
||||
.locator(".upload-files")
|
||||
.waitFor({ state: "hidden", timeout: 30000 });
|
||||
assert(
|
||||
fs.readFileSync(path.join(root, "upload-check.txt")).equals(payload)
|
||||
);
|
||||
result.push("UI chunked upload and transfer panel");
|
||||
await p
|
||||
.locator("#upload-input")
|
||||
.setInputFiles({
|
||||
name: "cancel-check.txt",
|
||||
mimeType: "text/plain",
|
||||
buffer: payload,
|
||||
});
|
||||
await p.locator(".upload-files").waitFor();
|
||||
await p.locator(".transfer-header button").last().click();
|
||||
await p.locator(".upload-files").waitFor({ state: "hidden" });
|
||||
await p.waitForTimeout(2300);
|
||||
assert(!fs.existsSync(path.join(root, "cancel-check.txt")));
|
||||
result.push("upload cancellation");
|
||||
await p.unroute("**/api/tus/**");
|
||||
for (let mobile of [false, true]) {
|
||||
await p.setViewportSize(
|
||||
mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }
|
||||
);
|
||||
for (let route of [
|
||||
"/files/",
|
||||
"/files/movie.webm",
|
||||
"/settings/profile",
|
||||
"/settings/shares",
|
||||
"/settings/global",
|
||||
"/s/qa-main",
|
||||
"/s/qa-protected",
|
||||
]) {
|
||||
await p.goto(base + route);
|
||||
await p.waitForTimeout(650);
|
||||
assert.equal(
|
||||
await p.evaluate(
|
||||
() => document.documentElement.scrollWidth > innerWidth + 1
|
||||
),
|
||||
false,
|
||||
"overflow " + route
|
||||
);
|
||||
await p.screenshot({
|
||||
path: path.join(
|
||||
out,
|
||||
(mobile ? "mobile" : "desktop") +
|
||||
route.replaceAll("/", "-") +
|
||||
".png"
|
||||
),
|
||||
fullPage: true,
|
||||
});
|
||||
}
|
||||
await p.goto(base + "/settings/global");
|
||||
await p.locator(".admin-users-tile").click();
|
||||
await p.locator(".users-management").waitFor();
|
||||
await p.screenshot({
|
||||
path: path.join(out, (mobile ? "mobile" : "desktop") + "-users.png"),
|
||||
fullPage: true,
|
||||
});
|
||||
await p.keyboard.press("Escape");
|
||||
await p.goto(base + "/editor/wordcraft?path=%2Fdocument.docx");
|
||||
await p.waitForTimeout(5000);
|
||||
let f = p.frames().find((x) => x !== p.mainFrame());
|
||||
await f
|
||||
.locator("canvas")
|
||||
.click({ position: { x: Math.min(mobile ? 190 : 550, 550), y: 350 } });
|
||||
await p.keyboard.press("Control+o");
|
||||
await p.locator(".server-picker").waitFor();
|
||||
await p.locator(".server-picker li").first().waitFor();
|
||||
await p.screenshot({
|
||||
path: path.join(
|
||||
out,
|
||||
(mobile ? "mobile" : "desktop") + "-server-picker.png"
|
||||
),
|
||||
});
|
||||
await p.locator(".picker-header button").click();
|
||||
}
|
||||
console.log(JSON.stringify(result));
|
||||
fs.writeFileSync(
|
||||
path.join(out, "functional.json"),
|
||||
JSON.stringify(result, null, 2)
|
||||
);
|
||||
} finally {
|
||||
await b.close();
|
||||
}
|
||||
})().catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -3,6 +3,10 @@ import { baseURL } from "@/utils/constants";
|
||||
import { upload as postTus, useTus } from "./tus";
|
||||
import { createURL, fetchURL, removePrefix, StatusError } from "./utils";
|
||||
import { isEncodableResponse, makeRawResource } from "@/utils/encodings";
|
||||
const resourceUploads = new Set<XMLHttpRequest>();
|
||||
export function abortResourceUploads() {
|
||||
for (const request of resourceUploads) request.abort();
|
||||
}
|
||||
|
||||
export async function fetch(url: string, signal?: AbortSignal) {
|
||||
const encoding = isEncodableResponse(url);
|
||||
@@ -140,6 +144,9 @@ async function postResources(
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = new XMLHttpRequest();
|
||||
resourceUploads.add(request);
|
||||
request.onloadend = () => resourceUploads.delete(request);
|
||||
request.onabort = () => reject(new Error("Upload aborted"));
|
||||
request.open(
|
||||
"POST",
|
||||
`${baseURL}/api/resources${url}?override=${overwrite}`,
|
||||
|
||||
@@ -29,7 +29,10 @@ const tools = computed(() =>
|
||||
auth.user?.perm.modify
|
||||
? store.items.filter(
|
||||
(item) =>
|
||||
item.enabled && item.build && addonAccepts(item, props.file!.name)
|
||||
item.enabled &&
|
||||
!item.compatibilityIssue &&
|
||||
item.build &&
|
||||
addonAccepts(item, props.file!.name)
|
||||
)
|
||||
: []
|
||||
);
|
||||
|
||||
@@ -177,7 +177,7 @@ watch(selectedEncoding, () => {
|
||||
background-color: var(--surfacePrimary);
|
||||
color: var(--textSecondary);
|
||||
padding: 1rem;
|
||||
padding-top: 4em;
|
||||
padding-top: 1rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
|
||||
@@ -80,6 +80,7 @@ import { readDicomFile } from "@/utils/dicom-file";
|
||||
import { findDicomSeries } from "@/utils/dicom-context";
|
||||
import { loadDicomVolume } from "@/utils/dicom-volume";
|
||||
import type { DicomSource, DicomVolume } from "@/utils/dicom-series";
|
||||
import { DICOM_3D_ENABLED } from "@/utils/dicom-series";
|
||||
const DicomVolumeViewer = defineAsyncComponent({
|
||||
loader: () => import("./DicomVolumeViewer.vue"),
|
||||
onError: (_error, _retry, fail) => {
|
||||
@@ -108,6 +109,7 @@ function volumeFailed() {
|
||||
volumeError.value = t("documents.volumeUnavailable");
|
||||
}
|
||||
async function openVolume() {
|
||||
if (!DICOM_3D_ENABLED) return;
|
||||
closeVolume();
|
||||
volumeError.value = "";
|
||||
const probe = document.createElement("canvas");
|
||||
@@ -149,7 +151,7 @@ watch(
|
||||
closeVolume();
|
||||
volumeError.value = "";
|
||||
series.value = [];
|
||||
if (!resource) return;
|
||||
if (!resource || !DICOM_3D_ENABLED) return;
|
||||
const request = (seriesController = new AbortController());
|
||||
try {
|
||||
const found = await findDicomSeries(resource, request.signal);
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
<template>
|
||||
<div
|
||||
class="server-picker-backdrop"
|
||||
@keydown.esc.stop.prevent="$emit('cancel')"
|
||||
@keydown.tab="trapFocus"
|
||||
@click.self="$emit('cancel')"
|
||||
>
|
||||
<section
|
||||
class="server-picker"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('addons.serverOpen')"
|
||||
ref="dialog"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="picker-header">
|
||||
<div>
|
||||
<h2>{{ t("addons.serverOpen") }}</h2>
|
||||
<p>{{ t("addons.serverOpenHint") }}</p>
|
||||
</div>
|
||||
<button
|
||||
class="action"
|
||||
:aria-label="t('buttons.close')"
|
||||
@click="$emit('cancel')"
|
||||
>
|
||||
<AppIcon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="picker-toolbar">
|
||||
<button class="action" :disabled="path === '/' || busy" @click="parent">
|
||||
<AppIcon name="arrow_upward" /></button
|
||||
><span :title="path">{{ path }}</span
|
||||
><input
|
||||
v-model="query"
|
||||
class="input"
|
||||
:placeholder="t('search.search')"
|
||||
:aria-label="t('search.search')"
|
||||
/>
|
||||
</div>
|
||||
<p v-if="error || externalError" role="alert" class="document-error">
|
||||
{{ error || externalError }}
|
||||
</p>
|
||||
<p v-if="busy" class="picker-status">{{ t("files.loading") }}</p>
|
||||
<ul v-else>
|
||||
<li v-for="item in visible" :key="item.path">
|
||||
<button
|
||||
:class="{ selected: selected?.path === item.path }"
|
||||
@click="item.isDir ? load(item.path) : (selected = item)"
|
||||
@dblclick="!item.isDir && open(item)"
|
||||
>
|
||||
<FileIcon :name="item.name" :directory="item.isDir" /><span>{{
|
||||
item.name
|
||||
}}</span
|
||||
><small>{{ item.isDir ? "" : filesize(item.size) }}</small>
|
||||
</button>
|
||||
</li>
|
||||
<li v-if="!visible.length" class="picker-status">
|
||||
{{ t("files.noItems") }}
|
||||
</li>
|
||||
</ul>
|
||||
<footer>
|
||||
<span :title="selected?.name">{{ selected?.name }}</span
|
||||
><button class="button button--flat" @click="$emit('cancel')">
|
||||
{{ t("buttons.cancel") }}</button
|
||||
><button
|
||||
v-if="selected && canOpen(selected)"
|
||||
class="button"
|
||||
:disabled="busy"
|
||||
@click="open(selected)"
|
||||
>
|
||||
{{ t("buttons.open") }}</button
|
||||
><button
|
||||
v-if="selected && intent !== 'open'"
|
||||
class="button button--flat"
|
||||
:disabled="busy"
|
||||
@click="$emit('import', selected)"
|
||||
>
|
||||
{{ t("addons.importServerFile") }}
|
||||
</button>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onBeforeUnmount, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import * as api from "@/api/files";
|
||||
import { encodePath } from "@/utils/url";
|
||||
import { filesize } from "filesize";
|
||||
import FileIcon from "./FileIcon.vue";
|
||||
const props = defineProps<{
|
||||
initialPath: string;
|
||||
extensions: string[];
|
||||
intent: string;
|
||||
externalError?: string;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
open: [item: ResourceItem];
|
||||
import: [item: ResourceItem];
|
||||
cancel: [];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const path = ref("/"),
|
||||
query = ref(""),
|
||||
items = ref<ResourceItem[]>([]),
|
||||
selected = ref<ResourceItem>(),
|
||||
busy = ref(false),
|
||||
error = ref(""),
|
||||
dialog = ref<HTMLElement>();
|
||||
let controller: AbortController | undefined;
|
||||
const canOpen = (item: ResourceItem) =>
|
||||
props.extensions.some((ext) => item.name.toLowerCase().endsWith(ext));
|
||||
const visible = computed(() =>
|
||||
items.value
|
||||
.filter(
|
||||
(i) =>
|
||||
i.isDir ||
|
||||
(i.name.toLowerCase().includes(query.value.toLowerCase()) &&
|
||||
(props.intent !== "open" || canOpen(i)))
|
||||
)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Number(b.isDir) - Number(a.isDir) || a.name.localeCompare(b.name)
|
||||
)
|
||||
);
|
||||
async function load(directory: string) {
|
||||
controller?.abort();
|
||||
const request = (controller = new AbortController());
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
selected.value = undefined;
|
||||
try {
|
||||
const data = await api.fetch(
|
||||
"/files" + encodePath(directory),
|
||||
request.signal
|
||||
);
|
||||
if (request.signal.aborted) return;
|
||||
if (!data.isDir) throw new Error("Not a directory");
|
||||
path.value = directory;
|
||||
items.value = data.items;
|
||||
query.value = "";
|
||||
} catch (e) {
|
||||
if (!request.signal.aborted) error.value = String(e);
|
||||
} finally {
|
||||
if (controller === request) busy.value = false;
|
||||
}
|
||||
}
|
||||
function parent() {
|
||||
load(
|
||||
path.value
|
||||
.replace(/\/$/, "")
|
||||
.slice(0, path.value.replace(/\/$/, "").lastIndexOf("/") + 1) || "/"
|
||||
);
|
||||
}
|
||||
function open(item: ResourceItem) {
|
||||
if (canOpen(item)) emit("open", item);
|
||||
}
|
||||
const previousFocus = document.activeElement as HTMLElement | null;
|
||||
function trapFocus(event: KeyboardEvent) {
|
||||
const elements = [
|
||||
...(dialog.value?.querySelectorAll<HTMLElement>(
|
||||
'button:not(:disabled), input, [tabindex="0"]'
|
||||
) || []),
|
||||
];
|
||||
if (!elements.length) return;
|
||||
const next = event.shiftKey ? elements[0] : elements.at(-1);
|
||||
if (
|
||||
document.activeElement === next ||
|
||||
document.activeElement === dialog.value
|
||||
) {
|
||||
event.preventDefault();
|
||||
(event.shiftKey ? elements.at(-1) : elements[0])?.focus();
|
||||
}
|
||||
}
|
||||
onMounted(() => {
|
||||
dialog.value?.focus();
|
||||
load(props.initialPath);
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
controller?.abort();
|
||||
previousFocus?.focus();
|
||||
});
|
||||
</script>
|
||||
<style scoped>
|
||||
.server-picker-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: #0008;
|
||||
z-index: 10020;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 20px;
|
||||
}
|
||||
.server-picker {
|
||||
width: min(900px, 100%);
|
||||
max-height: min(700px, calc(100dvh - 40px));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--surfacePrimary);
|
||||
color: var(--textSecondary);
|
||||
border: 1px solid var(--borderPrimary);
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 20px 70px #0005;
|
||||
}
|
||||
.server-picker .picker-header,
|
||||
.server-picker footer,
|
||||
.server-picker .picker-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
.server-picker .picker-header {
|
||||
justify-content: space-between;
|
||||
border-bottom: 1px solid var(--borderPrimary);
|
||||
}
|
||||
.server-picker h2 {
|
||||
font-size: 18px;
|
||||
margin: 0 0 6px;
|
||||
}
|
||||
.server-picker p {
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
}
|
||||
.server-picker .picker-toolbar span {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 13px;
|
||||
}
|
||||
.server-picker .picker-toolbar input {
|
||||
width: 200px;
|
||||
margin: 0;
|
||||
}
|
||||
.server-picker ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0 12px;
|
||||
overflow: auto;
|
||||
flex: 1;
|
||||
min-height: 180px;
|
||||
}
|
||||
.server-picker li button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
color: inherit;
|
||||
border-radius: 9px;
|
||||
}
|
||||
.server-picker li button:hover,
|
||||
.server-picker li button.selected {
|
||||
background: var(--surfaceSecondary);
|
||||
}
|
||||
.server-picker li .file-icon {
|
||||
width: 28px;
|
||||
height: 32px;
|
||||
flex: none;
|
||||
}
|
||||
.server-picker li span {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.server-picker small {
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.server-picker footer {
|
||||
border-top: 1px solid var(--borderPrimary);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.server-picker footer > span {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.picker-status {
|
||||
padding: 20px;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.server-picker-backdrop {
|
||||
padding: 10px;
|
||||
}
|
||||
.server-picker {
|
||||
max-height: calc(100dvh - 20px);
|
||||
}
|
||||
.server-picker .picker-header,
|
||||
.server-picker footer,
|
||||
.server-picker .picker-toolbar {
|
||||
padding: 12px;
|
||||
gap: 8px;
|
||||
}
|
||||
.server-picker .picker-toolbar {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.server-picker .picker-toolbar input {
|
||||
width: 100%;
|
||||
}
|
||||
.server-picker footer > span {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.server-picker footer .button {
|
||||
padding: 10px;
|
||||
}
|
||||
.server-picker li span {
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,58 +0,0 @@
|
||||
<template>
|
||||
<div class="card floating">
|
||||
<div class="card-title">
|
||||
<h2>{{ $t("prompts.currentPassword") }}</h2>
|
||||
</div>
|
||||
|
||||
<div class="card-content">
|
||||
<p>
|
||||
{{ $t("prompts.currentPasswordMessage") }}
|
||||
</p>
|
||||
<input
|
||||
id="focus-prompt"
|
||||
class="input input--block"
|
||||
type="password"
|
||||
@keyup.enter="submit"
|
||||
v-model="password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="card-action">
|
||||
<button
|
||||
class="button button--flat button--grey"
|
||||
@click="cancel"
|
||||
:aria-label="$t('buttons.cancel')"
|
||||
:title="$t('buttons.cancel')"
|
||||
>
|
||||
{{ $t("buttons.cancel") }}
|
||||
</button>
|
||||
<button
|
||||
@click="submit"
|
||||
class="button button--flat"
|
||||
type="submit"
|
||||
:aria-label="$t('buttons.ok')"
|
||||
:title="$t('buttons.ok')"
|
||||
>
|
||||
{{ $t("buttons.ok") }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
const layoutStore = useLayoutStore();
|
||||
|
||||
const { currentPrompt } = layoutStore;
|
||||
|
||||
const password = ref("");
|
||||
|
||||
const submit = (event: Event) => {
|
||||
currentPrompt?.confirm(event, password.value);
|
||||
};
|
||||
|
||||
const cancel = () => {
|
||||
layoutStore.closeHovers();
|
||||
};
|
||||
</script>
|
||||
@@ -1,40 +0,0 @@
|
||||
<template>
|
||||
<div class="card floating">
|
||||
<div class="card-content">
|
||||
<p>{{ t("prompts.deleteUser") }}</p>
|
||||
</div>
|
||||
|
||||
<div class="card-action">
|
||||
<button
|
||||
id="focus-prompt"
|
||||
class="button button--flat button--grey"
|
||||
@click="layoutStore.closeHovers"
|
||||
:aria-label="t('buttons.cancel')"
|
||||
:title="t('buttons.cancel')"
|
||||
tabindex="1"
|
||||
>
|
||||
{{ t("buttons.cancel") }}
|
||||
</button>
|
||||
<button
|
||||
class="button button--flat"
|
||||
@click="layoutStore.currentPrompt?.confirm"
|
||||
tabindex="2"
|
||||
>
|
||||
{{ t("buttons.delete") }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
import { useI18n } from "vue-i18n";
|
||||
|
||||
const layoutStore = useLayoutStore();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
// const emit = defineEmits<{
|
||||
// (e: "confirm"): void;
|
||||
// }>();
|
||||
</script>
|
||||
@@ -15,7 +15,6 @@ import BaseModal from "./BaseModal.vue";
|
||||
const Help = defineAsyncComponent(() => import("./Help.vue"));
|
||||
const Info = defineAsyncComponent(() => import("./Info.vue"));
|
||||
const Delete = defineAsyncComponent(() => import("./Delete.vue"));
|
||||
const DeleteUser = defineAsyncComponent(() => import("./DeleteUser.vue"));
|
||||
const Rename = defineAsyncComponent(() => import("./Rename.vue"));
|
||||
const Move = defineAsyncComponent(() => import("./Move.vue"));
|
||||
const Copy = defineAsyncComponent(() => import("./Copy.vue"));
|
||||
@@ -35,9 +34,6 @@ const DiscardEditorChanges = defineAsyncComponent(
|
||||
const ResolveConflict = defineAsyncComponent(
|
||||
() => import("./ResolveConflict.vue")
|
||||
);
|
||||
const CurrentPassword = defineAsyncComponent(
|
||||
() => import("./CurrentPassword.vue")
|
||||
);
|
||||
|
||||
const layoutStore = useLayoutStore();
|
||||
|
||||
@@ -58,10 +54,8 @@ const components = new Map<string, any>([
|
||||
["share", Share],
|
||||
["upload", Upload],
|
||||
["share-delete", ShareDelete],
|
||||
["deleteUser", DeleteUser],
|
||||
["discardEditorChanges", DiscardEditorChanges],
|
||||
["resolve-conflict", ResolveConflict],
|
||||
["current-password", CurrentPassword],
|
||||
]);
|
||||
|
||||
const modal = computed(() => {
|
||||
|
||||
@@ -1,218 +1,126 @@
|
||||
<template>
|
||||
<div
|
||||
v-if="uploadStore.activeUploads.size > 0"
|
||||
<aside
|
||||
v-if="uploadStore.activeUploads.size"
|
||||
class="upload-files"
|
||||
v-bind:class="{ closed: !open }"
|
||||
:class="{ closed: !open }"
|
||||
:aria-label="t('transfer.title')"
|
||||
>
|
||||
<div class="card floating">
|
||||
<div class="card-title">
|
||||
<h2>
|
||||
{{
|
||||
$t("prompts.uploadFiles", {
|
||||
files: uploadStore.pendingUploadCount,
|
||||
})
|
||||
}}
|
||||
</h2>
|
||||
<div class="upload-info">
|
||||
<div class="upload-speed">{{ speedText }}/s</div>
|
||||
<div class="upload-eta">{{ formattedETA }} remaining</div>
|
||||
<div class="upload-percentage">{{ sentPercent }}% Completed</div>
|
||||
<div class="upload-fraction">
|
||||
{{ sentMbytes }} /
|
||||
{{ totalMbytes }}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
class="action"
|
||||
@click="abortAll"
|
||||
aria-label="Abort upload"
|
||||
title="Abort upload"
|
||||
>
|
||||
<AppIcon :name="'cancel'" />
|
||||
</button>
|
||||
<button
|
||||
class="action"
|
||||
@click="toggle"
|
||||
aria-label="Toggle file upload list"
|
||||
title="Toggle file upload list"
|
||||
>
|
||||
<AppIcon :name="open ? 'keyboard_arrow_down' : 'keyboard_arrow_up'" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="card-content file-icons">
|
||||
<div
|
||||
class="file"
|
||||
v-for="upload in uploadStore.activeUploads"
|
||||
:key="upload.path"
|
||||
:data-dir="upload.type === 'dir'"
|
||||
:data-type="upload.type"
|
||||
:aria-label="upload.name"
|
||||
>
|
||||
<div class="file-name"><AppIcon name="file" /> {{ upload.name }}</div>
|
||||
<div class="file-progress">
|
||||
<div
|
||||
v-bind:style="{
|
||||
width: (upload.sentBytes / upload.totalBytes) * 100 + '%',
|
||||
}"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="transfer-header">
|
||||
<span class="transfer-symbol"><AppIcon name="upload" /></span>
|
||||
<div class="transfer-heading">
|
||||
<strong>{{ t("transfer.title") }}</strong
|
||||
><span>{{
|
||||
t("transfer.remainingFiles", {
|
||||
count: uploadStore.pendingUploadCount,
|
||||
})
|
||||
}}</span>
|
||||
</div>
|
||||
<strong class="transfer-percent">{{ percent }}%</strong>
|
||||
<button
|
||||
class="action"
|
||||
:aria-expanded="open"
|
||||
:aria-label="t('transfer.toggle')"
|
||||
@click="open = !open"
|
||||
>
|
||||
<AppIcon :name="open ? 'expand_more' : 'expand_less'" />
|
||||
</button>
|
||||
<button
|
||||
class="action"
|
||||
:aria-label="t('transfer.cancel')"
|
||||
@click="abortAll"
|
||||
>
|
||||
<AppIcon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="transfer-progress"
|
||||
role="progressbar"
|
||||
:aria-label="t('transfer.title')"
|
||||
:aria-valuenow="percent"
|
||||
aria-valuemin="0"
|
||||
aria-valuemax="100"
|
||||
>
|
||||
<span :style="{ width: percent + '%' }" />
|
||||
</div>
|
||||
<div class="transfer-stats">
|
||||
<span
|
||||
>{{ bytes(uploadStore.sentBytes) }} /
|
||||
{{ bytes(uploadStore.totalBytes) }}</span
|
||||
><span>{{ bytes(rate) }}/s</span><span>{{ remaining }}</span>
|
||||
</div>
|
||||
<ul v-if="open" class="transfer-list">
|
||||
<li v-for="file in uploadStore.activeUploads" :key="file.path">
|
||||
<FileIcon :name="file.name" :directory="file.type === 'dir'" />
|
||||
<div class="transfer-file">
|
||||
<span :title="file.name">{{ file.name }}</span>
|
||||
<div class="transfer-progress">
|
||||
<span
|
||||
:style="{
|
||||
width: progress(file.sentBytes, file.totalBytes) + '%',
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<small>{{ progress(file.sentBytes, file.totalBytes) }}%</small>
|
||||
</li>
|
||||
</ul>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useFileStore } from "@/stores/file";
|
||||
import { useUploadStore } from "@/stores/upload";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import buttons from "@/utils/buttons";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { partial } from "filesize";
|
||||
|
||||
const { t } = useI18n({});
|
||||
|
||||
const open = ref<boolean>(false);
|
||||
const speed = ref<number>(0);
|
||||
const eta = ref<number>(Infinity);
|
||||
|
||||
const fileStore = useFileStore();
|
||||
const uploadStore = useUploadStore();
|
||||
|
||||
const { sentBytes, totalBytes } = storeToRefs(uploadStore);
|
||||
|
||||
const byteToMbyte = partial({ exponent: 2 });
|
||||
const byteToKbyte = partial({ exponent: 1 });
|
||||
|
||||
const sentPercent = computed(() =>
|
||||
((uploadStore.sentBytes / uploadStore.totalBytes) * 100).toFixed(2)
|
||||
import { filesize } from "filesize";
|
||||
import FileIcon from "@/components/files/FileIcon.vue";
|
||||
import { transferProgress, transferSample } from "@/utils/transfer";
|
||||
const { t } = useI18n();
|
||||
const uploadStore = useUploadStore(),
|
||||
fileStore = useFileStore();
|
||||
const open = ref(false),
|
||||
rate = ref(0);
|
||||
const bytes = (value: number) =>
|
||||
filesize(Math.max(0, value), { base: 2, round: 1 });
|
||||
const progress = transferProgress;
|
||||
const percent = computed(() =>
|
||||
progress(uploadStore.sentBytes, uploadStore.totalBytes)
|
||||
);
|
||||
|
||||
const sentMbytes = computed(() => byteToMbyte(uploadStore.sentBytes));
|
||||
const totalMbytes = computed(() => byteToMbyte(uploadStore.totalBytes));
|
||||
const speedText = computed(() => {
|
||||
const bytes = speed.value;
|
||||
|
||||
if (bytes < 1024 * 1024) {
|
||||
const kb = parseFloat(byteToKbyte(bytes));
|
||||
return `${kb.toFixed(2)} KB`;
|
||||
} else {
|
||||
const mb = parseFloat(byteToMbyte(bytes));
|
||||
return `${mb.toFixed(2)} MB`;
|
||||
let previous = { bytes: 0, time: performance.now(), rate: 0 };
|
||||
watch(
|
||||
() => uploadStore.sentBytes,
|
||||
(value) => {
|
||||
previous = transferSample(previous, value, performance.now());
|
||||
rate.value = previous.rate;
|
||||
}
|
||||
);
|
||||
watch(
|
||||
() => uploadStore.totalBytes,
|
||||
(value, old) => {
|
||||
if (!old || !value) {
|
||||
previous = {
|
||||
bytes: uploadStore.sentBytes,
|
||||
time: performance.now(),
|
||||
rate: 0,
|
||||
};
|
||||
rate.value = 0;
|
||||
}
|
||||
}
|
||||
);
|
||||
const remaining = computed(() => {
|
||||
if (rate.value <= 0) return t("transfer.estimating");
|
||||
const seconds = Math.ceil(
|
||||
Math.max(0, uploadStore.totalBytes - uploadStore.sentBytes) / rate.value
|
||||
);
|
||||
return t("transfer.remaining", {
|
||||
time:
|
||||
seconds < 60
|
||||
? `${seconds} ${t("transfer.seconds")}`
|
||||
: `${Math.ceil(seconds / 60)} ${t("transfer.minutes")}`,
|
||||
});
|
||||
});
|
||||
|
||||
let lastSpeedUpdate: number = 0;
|
||||
let recentSpeeds: number[] = [];
|
||||
|
||||
let lastThrottleTime = 0;
|
||||
|
||||
const throttledCalculateSpeed = (sentBytes: number, oldSentBytes: number) => {
|
||||
const now = Date.now();
|
||||
if (now - lastThrottleTime < 100) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastThrottleTime = now;
|
||||
calculateSpeed(sentBytes, oldSentBytes);
|
||||
};
|
||||
|
||||
const calculateSpeed = (sentBytes: number, oldSentBytes: number) => {
|
||||
// Reset the state when the uploads batch is complete
|
||||
if (sentBytes === 0) {
|
||||
lastSpeedUpdate = 0;
|
||||
recentSpeeds = [];
|
||||
|
||||
eta.value = Infinity;
|
||||
speed.value = 0;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const elapsedTime = (Date.now() - (lastSpeedUpdate ?? 0)) / 1000;
|
||||
const bytesSinceLastUpdate = sentBytes - oldSentBytes;
|
||||
const currentSpeed = bytesSinceLastUpdate / elapsedTime;
|
||||
|
||||
recentSpeeds.push(currentSpeed);
|
||||
if (recentSpeeds.length > 5) {
|
||||
recentSpeeds.shift();
|
||||
}
|
||||
|
||||
const recentSpeedsAverage =
|
||||
recentSpeeds.reduce((acc, curr) => acc + curr) / recentSpeeds.length;
|
||||
|
||||
// Use the current speed for the first update to avoid smoothing lag
|
||||
if (recentSpeeds.length === 1) {
|
||||
speed.value = currentSpeed;
|
||||
}
|
||||
|
||||
speed.value = recentSpeedsAverage * 0.2 + speed.value * 0.8;
|
||||
|
||||
lastSpeedUpdate = Date.now();
|
||||
|
||||
calculateEta();
|
||||
};
|
||||
|
||||
const calculateEta = () => {
|
||||
if (speed.value === 0) {
|
||||
eta.value = Infinity;
|
||||
|
||||
return Infinity;
|
||||
}
|
||||
|
||||
const remainingSize = uploadStore.totalBytes - uploadStore.sentBytes;
|
||||
const speedBytesPerSecond = speed.value;
|
||||
|
||||
eta.value = remainingSize / speedBytesPerSecond;
|
||||
};
|
||||
|
||||
watch(sentBytes, throttledCalculateSpeed);
|
||||
|
||||
watch(totalBytes, (totalBytes, oldTotalBytes) => {
|
||||
if (oldTotalBytes !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark the start time of a new upload batch
|
||||
lastSpeedUpdate = Date.now();
|
||||
});
|
||||
|
||||
const formattedETA = computed(() => {
|
||||
if (!eta.value || eta.value === Infinity) {
|
||||
return "--:--:--";
|
||||
}
|
||||
|
||||
let totalSeconds = eta.value;
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
totalSeconds %= 3600;
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = Math.round(totalSeconds % 60);
|
||||
|
||||
return `${hours.toString().padStart(2, "0")}:${minutes
|
||||
.toString()
|
||||
.padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
|
||||
});
|
||||
|
||||
const toggle = () => {
|
||||
open.value = !open.value;
|
||||
};
|
||||
|
||||
const abortAll = () => {
|
||||
if (confirm(t("upload.abortUpload"))) {
|
||||
buttons.done("upload");
|
||||
open.value = false;
|
||||
uploadStore.abort();
|
||||
fileStore.reload = true; // Trigger reload in the file store
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.upload-info {
|
||||
min-width: 19ch;
|
||||
width: auto;
|
||||
text-align: left;
|
||||
function abortAll() {
|
||||
if (!confirm(t("upload.abortUpload"))) return;
|
||||
uploadStore.abort();
|
||||
fileStore.reload = true;
|
||||
}
|
||||
</style>
|
||||
</script>
|
||||
@@ -27,6 +27,10 @@
|
||||
}}</small>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="addon.compatibilityIssue" class="addon-incompatible">
|
||||
<strong>{{ t("addons.incompatible") }}</strong> ·
|
||||
{{ t("addons.compatibility." + addon.compatibilityIssue) }}
|
||||
</p>
|
||||
<p v-if="addon.id === 'deckcraft'" class="field-hint">
|
||||
{{ t("addons.deckcraftFormat") }}
|
||||
</p>
|
||||
@@ -39,7 +43,7 @@
|
||||
><input
|
||||
type="checkbox"
|
||||
:checked="addon.enabled"
|
||||
:disabled="changing === addon.id"
|
||||
:disabled="changing === addon.id || !!addon.compatibilityIssue"
|
||||
@change="
|
||||
toggle(addon, ($event.target as HTMLInputElement).checked)
|
||||
"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
.epub-reader .container {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
height: calc(100% - 64px);
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
* button instead of opening the table of contents. Push it just below the
|
||||
* header, tracking the header's height so it stays clear if that changes.
|
||||
*/
|
||||
top: calc(4em + 10px);
|
||||
top: 10px;
|
||||
}
|
||||
|
||||
.epub-reader .tocButton.tocButtonExpanded {
|
||||
@@ -67,7 +67,7 @@
|
||||
right: 25px;
|
||||
outline: none;
|
||||
position: absolute;
|
||||
top: 78px;
|
||||
top: 12px;
|
||||
}
|
||||
|
||||
.epub-reader .size span {
|
||||
|
||||
@@ -184,27 +184,27 @@ main .spinner .bounce2 {
|
||||
}
|
||||
|
||||
#previewer header {
|
||||
background: none;
|
||||
color: #fff;
|
||||
background: var(--surfacePrimary);
|
||||
color: var(--textPrimary);
|
||||
border-bottom: 0px;
|
||||
box-shadow: 0px 0px 0px;
|
||||
z-index: 19999;
|
||||
}
|
||||
|
||||
#previewer header > .action .app-icon {
|
||||
color: #fff;
|
||||
text-shadow: 1px 1px 1px #000000;
|
||||
color: var(--textPrimary);
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
#previewer header > title {
|
||||
white-space: nowrap;
|
||||
text-shadow: 1px 1px 1px #000000;
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
@media (min-width: 738px) {
|
||||
#previewer header #dropdown .action .app-icon {
|
||||
color: #fff;
|
||||
text-shadow: 1px 1px 1px #000000;
|
||||
color: var(--textPrimary);
|
||||
text-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,61 +1,141 @@
|
||||
.upload-files .card.floating {
|
||||
left: auto;
|
||||
top: auto;
|
||||
.upload-files {
|
||||
position: fixed;
|
||||
z-index: 1005;
|
||||
right: 20px;
|
||||
bottom: 20px;
|
||||
width: min(440px, calc(100vw - 32px));
|
||||
border: 1px solid var(--borderPrimary);
|
||||
border-radius: 16px;
|
||||
background: var(--surfacePrimary);
|
||||
color: var(--textSecondary);
|
||||
box-shadow: 0 8px 28px #0003;
|
||||
overflow: hidden;
|
||||
}
|
||||
.transfer-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 16px 14px 12px;
|
||||
}
|
||||
.transfer-symbol {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
flex: none;
|
||||
border-radius: 12px;
|
||||
background: var(--surfaceSecondary);
|
||||
color: var(--blue);
|
||||
}
|
||||
.transfer-heading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
gap: 4px;
|
||||
}
|
||||
.transfer-heading strong {
|
||||
font-size: 14px;
|
||||
color: var(--textPrimary);
|
||||
}
|
||||
.transfer-heading span,
|
||||
.transfer-stats {
|
||||
font-size: 12px;
|
||||
color: var(--textSecondary);
|
||||
}
|
||||
.transfer-percent {
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 14px;
|
||||
}
|
||||
.transfer-header .action {
|
||||
margin: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
transform: none;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
min-width: 32px;
|
||||
padding: 6px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.upload-files .file {
|
||||
margin-bottom: 8px;
|
||||
.transfer-header .app-icon {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.upload-files .file .file-name {
|
||||
font-size: 1.1em;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
.transfer-progress {
|
||||
height: 4px;
|
||||
background: var(--surfaceSecondary);
|
||||
overflow: hidden;
|
||||
border-radius: 9px;
|
||||
}
|
||||
|
||||
.upload-files .file .file-name .app-icon {
|
||||
margin-right: 5px;
|
||||
.upload-files > .transfer-progress {
|
||||
margin: 0 16px;
|
||||
}
|
||||
|
||||
.upload-files .file .file-progress {
|
||||
margin-top: 2px;
|
||||
width: 100%;
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
.upload-files .file .file-progress div {
|
||||
.transfer-progress > span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background-color: #40c4ff;
|
||||
width: 0;
|
||||
transition: 0.2s ease width;
|
||||
border-radius: 10px;
|
||||
background: var(--blue);
|
||||
transition: width 0.2s;
|
||||
}
|
||||
|
||||
.upload-files.closed .card-content {
|
||||
display: none;
|
||||
padding: 0em 1em 1em 1em;
|
||||
.transfer-stats {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 6px 12px;
|
||||
padding: 12px 16px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.upload-files .card .card-title {
|
||||
.transfer-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0 16px 12px;
|
||||
max-height: min(260px, 40vh);
|
||||
overflow: auto;
|
||||
}
|
||||
.transfer-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 0.8em;
|
||||
padding: 1em 1em 0em;
|
||||
gap: 10px;
|
||||
padding: 12px 0;
|
||||
border-top: 1px solid var(--borderPrimary);
|
||||
}
|
||||
|
||||
.upload-files.closed .card-title {
|
||||
font-size: 0.7em;
|
||||
padding: 0.5em 1em;
|
||||
.transfer-list .file-icon {
|
||||
width: 28px;
|
||||
height: 32px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
@media (max-width: 450px) {
|
||||
.upload-files .card.floating {
|
||||
max-width: 100%;
|
||||
width: 100%;
|
||||
.transfer-file {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.transfer-file > span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 13px;
|
||||
}
|
||||
.transfer-list small {
|
||||
font-size: 11px;
|
||||
width: 32px;
|
||||
text-align: right;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.upload-files {
|
||||
right: 10px;
|
||||
bottom: max(10px, env(safe-area-inset-bottom));
|
||||
width: calc(100vw - 20px);
|
||||
border-radius: 14px;
|
||||
}
|
||||
.transfer-header {
|
||||
gap: 7px;
|
||||
padding: 12px 10px;
|
||||
}
|
||||
.transfer-symbol {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
}
|
||||
.transfer-stats {
|
||||
font-size: 11px;
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,8 @@
|
||||
min-height: 0;
|
||||
}
|
||||
#previewer .preview.document-preview {
|
||||
background: var(--background);
|
||||
color: var(--textPrimary);
|
||||
position: absolute;
|
||||
top: 4em;
|
||||
bottom: 0;
|
||||
@@ -963,3 +965,12 @@ select:focus {
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
.addon-incompatible {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--textPrimary);
|
||||
padding: 10px;
|
||||
border-radius: 8px;
|
||||
background: var(--surfaceSecondary);
|
||||
}
|
||||
@@ -54,7 +54,8 @@
|
||||
"overrideAll": "Replace all files in destination folder",
|
||||
"skipAll": "Skip all conflicting files",
|
||||
"renameAll": "Rename all files (create a copy)",
|
||||
"singleDecision": "Decide for each conflicting file"
|
||||
"singleDecision": "Decide for each conflicting file",
|
||||
"open": "Open"
|
||||
},
|
||||
"download": {
|
||||
"downloadFile": "Download File",
|
||||
@@ -470,6 +471,24 @@
|
||||
"verifying": "Verifying SHA-256",
|
||||
"extracting": "Installing"
|
||||
},
|
||||
"sessionExpired": "Session expired. Sign in in another tab, then retry saving."
|
||||
"sessionExpired": "Session expired. Sign in in another tab, then retry saving.",
|
||||
"serverOpen": "Open from server",
|
||||
"serverOpenHint": "Choose a document or an import file from your accessible folders.",
|
||||
"importServerFile": "Insert / import",
|
||||
"incompatible": "Not compatible",
|
||||
"compatibility": {
|
||||
"demoOnly": "This web release only opens its demo project and cannot load or save server files.",
|
||||
"serverSave": "Loading and saving server projects could not be verified in this web build. The tool is temporarily disabled."
|
||||
}
|
||||
},
|
||||
"transfer": {
|
||||
"title": "Uploading files",
|
||||
"remainingFiles": "Files remaining: {count}",
|
||||
"toggle": "Show or hide upload queue",
|
||||
"cancel": "Cancel uploads",
|
||||
"estimating": "Estimating…",
|
||||
"remaining": "{time} remaining",
|
||||
"seconds": "s",
|
||||
"minutes": "min"
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,8 @@
|
||||
"overrideAll": "Replace all files in destination folder",
|
||||
"skipAll": "Skip all conflicting files",
|
||||
"renameAll": "Rename all files (create a copy)",
|
||||
"singleDecision": "Decide for each conflicting file"
|
||||
"singleDecision": "Decide for each conflicting file",
|
||||
"open": "Открыть"
|
||||
},
|
||||
"download": {
|
||||
"downloadFile": "Скачать файл",
|
||||
@@ -250,7 +251,7 @@
|
||||
"permissions": "Права доступа",
|
||||
"permissionsHelp": "Права на работу с файлами. Администраторы определяются ролями SSO.",
|
||||
"profileSettings": "Интерфейс",
|
||||
"redirectAfterCopyMove": "Redirect to destination after copy/move",
|
||||
"redirectAfterCopyMove": "Переходить в папку назначения после копирования или перемещения",
|
||||
"ruleExample1": "предотвратить доступ к любому скрытому файлу (например: .git, .gitignore) в каждой папке.\n",
|
||||
"ruleExample2": "блокирует доступ к файлу с именем Caddyfile в корневой области.",
|
||||
"rules": "Права",
|
||||
@@ -467,6 +468,24 @@
|
||||
"verifying": "Проверка SHA-256",
|
||||
"extracting": "Установка"
|
||||
},
|
||||
"sessionExpired": "Сессия истекла. Войдите в соседней вкладке, затем повторите сохранение."
|
||||
"sessionExpired": "Сессия истекла. Войдите в соседней вкладке, затем повторите сохранение.",
|
||||
"serverOpen": "Открыть с сервера",
|
||||
"serverOpenHint": "Выберите документ или файл для импорта из доступных папок.",
|
||||
"importServerFile": "Вставить / импортировать",
|
||||
"incompatible": "Не совместимо",
|
||||
"compatibility": {
|
||||
"demoOnly": "Эта веб-версия открывает только демопроект и не поддерживает загрузку и сохранение файлов сервера.",
|
||||
"serverSave": "В этой веб-сборке не удалось подтвердить загрузку и сохранение проекта на сервер. Инструмент временно отключён."
|
||||
}
|
||||
},
|
||||
"transfer": {
|
||||
"title": "Загрузка файлов",
|
||||
"remainingFiles": "Осталось файлов: {count}",
|
||||
"toggle": "Показать или скрыть очередь",
|
||||
"cancel": "Отменить загрузку",
|
||||
"estimating": "Расчёт времени…",
|
||||
"remaining": "Осталось {time}",
|
||||
"seconds": "с",
|
||||
"minutes": "мин"
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export interface Addon {
|
||||
enabled: boolean;
|
||||
state: string;
|
||||
error?: string;
|
||||
compatibilityIssue?: string;
|
||||
downloaded: number;
|
||||
total: number;
|
||||
}
|
||||
@@ -34,7 +35,11 @@ export const useAddonsStore = defineStore("addons", {
|
||||
},
|
||||
available(id: string) {
|
||||
return this.items.some(
|
||||
(item) => item.id === id && item.enabled && !!item.build
|
||||
(item) =>
|
||||
item.id === id &&
|
||||
item.enabled &&
|
||||
!item.compatibilityIssue &&
|
||||
!!item.build
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -69,17 +69,20 @@ export const useUploadStore = defineStore("upload", () => {
|
||||
// Resets the state by preventing the processing of the remaning uploads
|
||||
lastUpload.value = Infinity;
|
||||
tus.abortAllUploads();
|
||||
api.abortResourceUploads();
|
||||
};
|
||||
|
||||
//
|
||||
// GETTERS
|
||||
//
|
||||
|
||||
const pendingUploadCount = computed(
|
||||
() =>
|
||||
const pendingUploadCount = computed(() =>
|
||||
Math.max(
|
||||
0,
|
||||
allUploads.value.length -
|
||||
(lastUpload.value + 1) +
|
||||
activeUploads.value.size
|
||||
(lastUpload.value + 1) +
|
||||
activeUploads.value.size
|
||||
)
|
||||
);
|
||||
|
||||
//
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { transferProgress, transferSample } from "../transfer";
|
||||
it("keeps throttled progress bytes until the next speed sample", () => {
|
||||
const start = { bytes: 0, time: 1000, rate: 0 };
|
||||
const deferred = transferSample(start, 100, 1100);
|
||||
expect(deferred).toBe(start);
|
||||
expect(transferSample(deferred, 500, 1500).rate).toBe(1000);
|
||||
});
|
||||
it("resets the rate for a restarted upload and bounds progress", () => {
|
||||
expect(
|
||||
transferSample({ bytes: 1000, time: 1000, rate: 100 }, 0, 2000).rate
|
||||
).toBe(0);
|
||||
expect(transferProgress(11, 10)).toBe(100);
|
||||
expect(transferProgress(0, 0)).toBe(0);
|
||||
expect(transferProgress(-1, 10)).toBe(0);
|
||||
});
|
||||
@@ -54,6 +54,7 @@ export function craftMessage(
|
||||
dirty?: boolean;
|
||||
saveAs?: boolean;
|
||||
error?: string;
|
||||
intent?: string;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -78,6 +79,7 @@ export function defaultCraftTool(items: Addon[], name: string, type = "") {
|
||||
return items.find(
|
||||
(item) =>
|
||||
item.enabled &&
|
||||
!item.compatibilityIssue &&
|
||||
item.build &&
|
||||
addonAccepts(item, name) &&
|
||||
(preview !== "pdf" || item.id === "pdfcraft")
|
||||
|
||||
@@ -6,6 +6,8 @@ export interface DicomSource {
|
||||
}
|
||||
export const MAX_VOLUME_BYTES = 1.5 * 1024 * 1024 * 1024;
|
||||
export const MAX_SERIES_FILES = 2048;
|
||||
// Temporarily disabled while volume rendering is being stabilized.
|
||||
export const DICOM_3D_ENABLED = false;
|
||||
|
||||
// Names only trigger the offer. Patient-space geometry is checked after consent.
|
||||
export function dicomSeries(
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
export function transferProgress(sent: number, total: number) {
|
||||
return total > 0 && Number.isFinite(sent)
|
||||
? Math.max(0, Math.min(100, Math.round((sent / total) * 100)))
|
||||
: 0;
|
||||
}
|
||||
export function transferSample(
|
||||
previous: { bytes: number; time: number; rate: number },
|
||||
bytes: number,
|
||||
time: number
|
||||
) {
|
||||
if (bytes < previous.bytes || bytes === 0) return { bytes, time, rate: 0 };
|
||||
const elapsed = (time - previous.time) / 1000;
|
||||
if (elapsed < 0.25) return previous;
|
||||
const current = (bytes - previous.bytes) / elapsed;
|
||||
return {
|
||||
bytes,
|
||||
time,
|
||||
rate: previous.rate ? current * 0.4 + previous.rate * 0.6 : current,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,17 @@
|
||||
<template>
|
||||
<div class="craft-editor">
|
||||
<ServerFilePicker
|
||||
v-if="pickerRequest"
|
||||
:initial-path="
|
||||
currentPath.slice(0, currentPath.lastIndexOf('/') + 1) || '/'
|
||||
"
|
||||
:extensions="activeTool?.extensions || [activeTool?.extension || '']"
|
||||
:intent="pickerRequest.intent"
|
||||
:external-error="error"
|
||||
@cancel="cancelPicker"
|
||||
@open="openServerDocument"
|
||||
@import="importServerFile"
|
||||
/>
|
||||
<div v-if="pending || error || saving || saveAs" class="craft-feedback">
|
||||
<div class="craft-status" role="status">
|
||||
<strong>{{ title }}</strong
|
||||
@@ -78,7 +90,15 @@
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, onMounted, onBeforeUnmount } from "vue";
|
||||
import { useRoute, onBeforeRouteLeave, onBeforeRouteUpdate } from "vue-router";
|
||||
import {
|
||||
useRoute,
|
||||
useRouter,
|
||||
onBeforeRouteLeave,
|
||||
onBeforeRouteUpdate,
|
||||
} from "vue-router";
|
||||
import ServerFilePicker from "@/components/files/ServerFilePicker.vue";
|
||||
import { getDownloadURL } from "@/api/files";
|
||||
import { previewBuffer } from "@/utils/preview";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useFileStore } from "@/stores/file";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
@@ -92,6 +112,7 @@ import {
|
||||
safeCraftName,
|
||||
} from "@/utils/craft";
|
||||
const route = useRoute(),
|
||||
router = useRouter(),
|
||||
store = useAddonsStore(),
|
||||
files = useFileStore(),
|
||||
auth = useAuthStore(),
|
||||
@@ -126,6 +147,79 @@ interface Save {
|
||||
}
|
||||
const pending = ref<Save>();
|
||||
const authExpired = ref(false);
|
||||
const pickerRequest = ref<{ requestId: string; intent: string }>();
|
||||
function cancelPicker() {
|
||||
if (!pickerRequest.value) return;
|
||||
frame.value?.contentWindow?.postMessage(
|
||||
{
|
||||
type: id + ":pick-result",
|
||||
requestId: pickerRequest.value.requestId,
|
||||
error: "AbortError",
|
||||
},
|
||||
window.location.origin
|
||||
);
|
||||
pickerRequest.value = undefined;
|
||||
}
|
||||
function openServerDocument(item: ResourceItem) {
|
||||
if (
|
||||
!activeTool.value ||
|
||||
!addonAccepts(activeTool.value, item.name) ||
|
||||
!mayLeave()
|
||||
)
|
||||
return;
|
||||
if (item.size > 64 * 1024 * 1024) {
|
||||
error.value = t("addons.tooLarge");
|
||||
return;
|
||||
}
|
||||
cancelPicker();
|
||||
pending.value = undefined;
|
||||
frameDirty.value = false;
|
||||
window.location.assign(
|
||||
router.resolve({
|
||||
name: "CraftEditor",
|
||||
params: { addon: id },
|
||||
query: { path: item.path },
|
||||
}).href
|
||||
);
|
||||
}
|
||||
async function importServerFile(item: ResourceItem) {
|
||||
const request = pickerRequest.value;
|
||||
if (!request) return;
|
||||
try {
|
||||
if (item.size > 64 * 1024 * 1024) throw new Error(t("addons.tooLarge"));
|
||||
const bytes = await previewBuffer(
|
||||
getDownloadURL(item, true),
|
||||
controller.signal,
|
||||
64 * 1024 * 1024
|
||||
);
|
||||
if (pickerRequest.value !== request || disposed) return;
|
||||
const mime =
|
||||
(
|
||||
{
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".svg": "image/svg+xml",
|
||||
".pdf": "application/pdf",
|
||||
".wav": "audio/wav",
|
||||
} as Record<string, string>
|
||||
)[item.extension] || "";
|
||||
frame.value?.contentWindow?.postMessage(
|
||||
{
|
||||
type: id + ":pick-result",
|
||||
requestId: request.requestId,
|
||||
files: [{ name: item.name, bytes, mime }],
|
||||
},
|
||||
window.location.origin,
|
||||
[bytes]
|
||||
);
|
||||
pickerRequest.value = undefined;
|
||||
frameDirty.value = true;
|
||||
revision++;
|
||||
} catch (failure) {
|
||||
if (!disposed) error.value = String(failure);
|
||||
}
|
||||
}
|
||||
let activityDocument: Document | null = null,
|
||||
lastActivity = 0;
|
||||
const activityEvents = [
|
||||
@@ -290,7 +384,20 @@ function receive(event: MessageEvent) {
|
||||
window.location.origin
|
||||
);
|
||||
if (!message) return;
|
||||
if (message.type === id + ":ready") {
|
||||
if (message.type === id + ":pick-request") {
|
||||
if (
|
||||
typeof message.requestId !== "string" ||
|
||||
message.requestId.length > 80 ||
|
||||
!auth.user?.perm.download
|
||||
)
|
||||
return;
|
||||
if (pickerRequest.value) return;
|
||||
error.value = "";
|
||||
pickerRequest.value = {
|
||||
requestId: message.requestId,
|
||||
intent: message.intent === "open" ? "open" : "choose",
|
||||
};
|
||||
} else if (message.type === id + ":ready") {
|
||||
if (opened || !original) return;
|
||||
opened = true;
|
||||
clearTimeout(startup);
|
||||
@@ -354,7 +461,8 @@ onMounted(async () => {
|
||||
document.title = currentName.value;
|
||||
await store.refresh();
|
||||
const addon = store.items.find(
|
||||
(item) => item.id === id && item.enabled && item.build
|
||||
(item) =>
|
||||
item.id === id && item.enabled && !item.compatibilityIssue && item.build
|
||||
);
|
||||
if (
|
||||
!addon ||
|
||||
|
||||
@@ -72,7 +72,10 @@
|
||||
<template v-else>
|
||||
<div
|
||||
class="preview"
|
||||
:class="{ 'document-preview': isDicom || isPdf || isGenericPreview }"
|
||||
:class="{
|
||||
'document-preview':
|
||||
isDicom || isPdf || isEpub || isCsv || isGenericPreview,
|
||||
}"
|
||||
>
|
||||
<PdfViewer v-if="isPdf" :source="previewUrl" />
|
||||
<DicomViewer
|
||||
@@ -159,6 +162,7 @@
|
||||
</template>
|
||||
|
||||
<button
|
||||
v-if="['image', 'audio', 'video'].includes(fileStore.req?.type || '')"
|
||||
@click="prev"
|
||||
@mouseover="hoverNav = true"
|
||||
@mouseleave="hoverNav = false"
|
||||
@@ -169,6 +173,7 @@
|
||||
<AppIcon name="chevron_left" />
|
||||
</button>
|
||||
<button
|
||||
v-if="['image', 'audio', 'video'].includes(fileStore.req?.type || '')"
|
||||
@click="next"
|
||||
@mouseover="hoverNav = true"
|
||||
@mouseleave="hoverNav = false"
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
><input type="checkbox" v-model="redirectAfterCopyMove"
|
||||
/></label>
|
||||
</section>
|
||||
<section class="card settings-section">
|
||||
<section v-if="DICOM_3D_ENABLED" class="card settings-section">
|
||||
<h2><AppIcon name="tune" />{{ t("preferences.dicom3D") }}</h2>
|
||||
<label class="settings-field"
|
||||
>{{ t("preferences.dicomQuality") }}
|
||||
@@ -110,8 +110,10 @@ import { users as api } from "@/api";
|
||||
import Languages from "@/components/settings/Languages.vue";
|
||||
import AccountAvatar from "@/components/AccountAvatar.vue";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { getTheme, setTheme } from "@/utils/theme";
|
||||
import { getTheme, getMediaPreference, setTheme } from "@/utils/theme";
|
||||
import { dicomPreferences } from "@/utils/dicom-quality";
|
||||
import { detectLocale } from "@/i18n";
|
||||
import { DICOM_3D_ENABLED } from "@/utils/dicom-series";
|
||||
import { inject, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
|
||||
@@ -128,7 +130,7 @@ const singleClick = ref<boolean>(false);
|
||||
const redirectAfterCopyMove = ref<boolean>(false);
|
||||
const dateFormat = ref<boolean>(false);
|
||||
const locale = ref<string>("");
|
||||
const selectedTheme = ref<UserTheme>(getTheme());
|
||||
const selectedTheme = ref<UserTheme>(getTheme() || getMediaPreference());
|
||||
const saving = ref(false);
|
||||
const dicom3D = ref(dicomPreferences());
|
||||
|
||||
@@ -138,7 +140,7 @@ onMounted(async () => {
|
||||
layoutStore.loading = false;
|
||||
return false;
|
||||
}
|
||||
locale.value = authStore.user.locale;
|
||||
locale.value = authStore.user.locale || detectLocale();
|
||||
hideDotfiles.value = authStore.user.hideDotfiles;
|
||||
showPreviews.value = !authStore.user.hidePreviews;
|
||||
singleClick.value = authStore.user.singleClick;
|
||||
|
||||
+21
-7
@@ -23,11 +23,14 @@ func addonListHandler(manager *addons.Manager) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
type entry struct {
|
||||
addons.Status
|
||||
Enabled bool `json:"enabled"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CompatibilityIssue string `json:"compatibilityIssue,omitempty"`
|
||||
}
|
||||
items := []entry{}
|
||||
for _, tool := range addons.Catalog {
|
||||
items = append(items, entry{manager.Status(tool.ID), addonEnabled(d, tool.ID)})
|
||||
status := manager.Status(tool.ID)
|
||||
issue := addons.CompatibilityIssue(tool.ID, status.Build)
|
||||
items = append(items, entry{status, addonEnabled(d, tool.ID) && issue == "", issue})
|
||||
}
|
||||
return renderJSON(w, r, items)
|
||||
})
|
||||
@@ -51,7 +54,8 @@ var addonToggleHandler = withAdmin(func(w http.ResponseWriter, r *http.Request,
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
var payload struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CompatibilityIssue string `json:"compatibilityIssue,omitempty"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024)).Decode(&payload); err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
@@ -90,8 +94,9 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
bridge := needsOfficeBridge(id) && name == "filebrowser-bridge.js"
|
||||
pickerBridge := name == "filebrowser-picker.js"
|
||||
lookup := name
|
||||
if bridge {
|
||||
if bridge || pickerBridge {
|
||||
lookup = "index.html"
|
||||
}
|
||||
file, err := manager.Open(id, vars["build"], lookup)
|
||||
@@ -99,8 +104,8 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
defer file.Close()
|
||||
adaptIndex := needsOfficeBridge(id) && name == "index.html" && r.URL.Query().Get("host") == "parent"
|
||||
if !bridge && !adaptIndex && acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
|
||||
adaptIndex := name == "index.html" && r.URL.Query().Get("host") == "parent"
|
||||
if !bridge && !pickerBridge && !adaptIndex && acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
|
||||
if compressed, e := manager.Open(id, vars["build"], name+".gz"); e == nil {
|
||||
file.Close()
|
||||
file = compressed
|
||||
@@ -118,6 +123,11 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400")
|
||||
// Only installed, checksum-verified vendor pages get WASM and framing permissions.
|
||||
w.Header().Set("Content-Security-Policy", `default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:; media-src 'self' blob:; frame-src 'none'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'`)
|
||||
if pickerBridge {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(craftPicker))
|
||||
return 0, nil
|
||||
}
|
||||
if bridge {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
tool, _ := addons.Find(id)
|
||||
@@ -138,7 +148,11 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
if !bytes.Contains(content, marker) {
|
||||
return http.StatusUnprocessableEntity, nil
|
||||
}
|
||||
content = bytes.Replace(content, marker, []byte(`<script src="./filebrowser-bridge.js"></script></head>`), 1)
|
||||
scripts := `<script src="./filebrowser-picker.js"></script>`
|
||||
if needsOfficeBridge(id) {
|
||||
scripts += `<script src="./filebrowser-bridge.js"></script>`
|
||||
}
|
||||
content = bytes.Replace(content, marker, []byte(scripts+`</head>`), 1)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(content))
|
||||
return 0, nil
|
||||
|
||||
+3
-2
@@ -258,10 +258,11 @@ func blankCraftDocument(id string) ([]byte, error) {
|
||||
return nil, errors.New("unsupported editor")
|
||||
}
|
||||
entries := map[string]string{
|
||||
"[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>`,
|
||||
"[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>`,
|
||||
"_rels/.rels": `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
|
||||
"xl/workbook.xml": `<?xml version="1.0"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>`,
|
||||
"xl/_rels/workbook.xml.rels": `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>`,
|
||||
"xl/_rels/workbook.xml.rels": `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>`,
|
||||
"xl/styles.xml": `<?xml version="1.0"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`,
|
||||
"xl/worksheets/sheet1.xml": `<?xml version="1.0"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>`}
|
||||
var b bytes.Buffer
|
||||
writer := zip.NewWriter(&b)
|
||||
|
||||
@@ -6,6 +6,9 @@ import "github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
//go:embed craft_bridge.js
|
||||
var officeBridge []byte
|
||||
|
||||
//go:embed craft_picker.js
|
||||
var craftPicker []byte
|
||||
|
||||
//go:embed deckcraft_compat.js
|
||||
var deckcraftCompat []byte
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// File selection stays inside the authenticated server scope. No vendor bundle
|
||||
// is modified: both the File System Access API and hidden file inputs are bridged.
|
||||
(() => {
|
||||
"use strict";
|
||||
const parts = location.pathname.split("/"), id = parts[parts.lastIndexOf("addons") + 1];
|
||||
if (parent === window || new URLSearchParams(location.search).get("host") !== "parent") return;
|
||||
const jobs = new Map(); let sequence = 0;
|
||||
const request = (accept, intent = "choose") => new Promise((resolve, reject) => {
|
||||
if (jobs.size) { reject(new DOMException("Selection already pending", "AbortError")); return; }
|
||||
const requestId = `picker-${++sequence}`;
|
||||
jobs.set(requestId, { resolve, reject });
|
||||
parent.postMessage({ type: id + ":pick-request", requestId, accept: String(accept || "").slice(0, 2048), intent }, location.origin);
|
||||
});
|
||||
addEventListener("message", event => {
|
||||
if (event.source !== parent || event.origin !== location.origin || event.data?.type !== id + ":pick-result") return;
|
||||
const message = event.data, job = jobs.get(message.requestId); if (!job) return;
|
||||
jobs.delete(message.requestId);
|
||||
if (!Array.isArray(message.files)) { job.reject(new DOMException("Selection cancelled", "AbortError")); return; }
|
||||
const files = message.files.filter(f => typeof f.name === "string" && f.bytes instanceof ArrayBuffer && f.bytes.byteLength <= 64 * 1024 * 1024)
|
||||
.map(f => new File([f.bytes], f.name, { type: typeof f.mime === "string" ? f.mime : "" }));
|
||||
if (!files.length) job.reject(new DOMException("No file selected", "AbortError")); else job.resolve(files);
|
||||
});
|
||||
const chooseInput = input => {
|
||||
request(input.accept).then(files => {
|
||||
const transfer = new DataTransfer(); for (const file of files) transfer.items.add(file);
|
||||
input.files = transfer.files;
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
input.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
}).catch(() => input.dispatchEvent(new Event("cancel", { bubbles: true })));
|
||||
};
|
||||
const click = HTMLInputElement.prototype.click;
|
||||
HTMLInputElement.prototype.click = function () { if (this.type === "file") return chooseInput(this); return click.call(this); };
|
||||
if (HTMLInputElement.prototype.showPicker) {
|
||||
const show = HTMLInputElement.prototype.showPicker;
|
||||
HTMLInputElement.prototype.showPicker = function () { if (this.type === "file") return chooseInput(this); return show.call(this); };
|
||||
}
|
||||
addEventListener("click", event => { if (event.target instanceof HTMLInputElement && event.target.type === "file") { event.preventDefault(); event.stopImmediatePropagation(); chooseInput(event.target); } }, true);
|
||||
window.showOpenFilePicker = async options => {
|
||||
const accept = (options?.types || []).flatMap(t => Object.values(t.accept || {}).flat()).join(",");
|
||||
const files = await request(accept);
|
||||
return files.map(file => ({ kind: "file", name: file.name, getFile: async () => file, queryPermission: async () => "granted", requestPermission: async () => "granted" }));
|
||||
};
|
||||
addEventListener("keydown", event => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "o") {
|
||||
event.preventDefault(); event.stopImmediatePropagation(); request("", "open").catch(() => {});
|
||||
}
|
||||
}, true);
|
||||
})();
|
||||
@@ -365,3 +365,30 @@ func TestAddonRoutesAuthMIMECompressionAndDisable(t *testing.T) {
|
||||
t.Fatalf("disabled addon accessible %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlankSpreadsheetHasStylesRelationship(t *testing.T) {
|
||||
data, err := blankCraftDocument("gridcraft")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts := map[string]string{}
|
||||
for _, f := range reader.File {
|
||||
r, err := f.Open()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := io.ReadAll(r)
|
||||
r.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts[f.Name] = string(b)
|
||||
}
|
||||
if !strings.Contains(parts["xl/styles.xml"], "<cellXfs") || !strings.Contains(parts["xl/_rels/workbook.xml.rels"], `Target="styles.xml"`) || !strings.Contains(parts["[Content_Types].xml"], `/xl/styles.xml`) {
|
||||
t.Fatal("missing spreadsheet styles or relationship")
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -47,7 +47,7 @@ func NewHandler(
|
||||
r := mux.NewRouter()
|
||||
r.Use(func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Security-Policy", `default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'`)
|
||||
w.Header().Set("Content-Security-Policy", `default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'`)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
})
|
||||
|
||||
+1
-1
@@ -73,7 +73,7 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
|
||||
cached, _ = indexTemplates.LoadOrStore(contents, parsed)
|
||||
}
|
||||
index := cached.(*template.Template)
|
||||
w.Header().Set("Content-Security-Policy", fmt.Sprintf("default-src 'self'; script-src 'self' 'nonce-%s' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"]))
|
||||
w.Header().Set("Content-Security-Policy", fmt.Sprintf("default-src 'self'; script-src 'self' 'nonce-%s' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"]))
|
||||
err = index.Execute(w, data)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"github.com/filebrowser/filebrowser/v2/diskcache"
|
||||
"github.com/filebrowser/filebrowser/v2/frontend"
|
||||
"github.com/filebrowser/filebrowser/v2/img"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The browser operates on an isolated test filesystem through the production
|
||||
// HTTP handlers. Authentication is injected only in this test binary.
|
||||
func TestWorkspaceBrowserQA(t *testing.T) {
|
||||
if os.Getenv("FILEBROWSER_QA") != "1" {
|
||||
t.Skip("optional full browser QA")
|
||||
}
|
||||
root := t.TempDir()
|
||||
fixtures := os.Getenv("FILEBROWSER_QA_FIXTURES")
|
||||
if fixtures == "" {
|
||||
t.Fatal("missing fixture directory")
|
||||
}
|
||||
if err := os.CopyFS(root, os.DirFS(fixtures)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, id := range []string{"wordcraft", "gridcraft", "deckcraft", "pdfcraft"} {
|
||||
data, err := blankCraftDocument(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ext := map[string]string{"wordcraft": "docx", "gridcraft": "xlsx", "deckcraft": "pptx", "pdfcraft": "pdf"}[id]
|
||||
if err := os.WriteFile(filepath.Join(root, "document."+ext), data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if data, err := os.ReadFile("testdata/deckcraft-blank.deckcraft"); err == nil {
|
||||
os.WriteFile(filepath.Join(root, "native.deckcraft"), data, 0600)
|
||||
}
|
||||
st := scopedUserStorage(t, root, users.Permissions{Admin: true, Create: true, Modify: true, Rename: true, Delete: true, Share: true, Download: true}, []byte("qa-key"))
|
||||
config, _ := st.Settings.Get()
|
||||
config.Branding.Name = "File Browser"
|
||||
config.Tus.ChunkSize = 1 << 20
|
||||
config.Tus.RetryCount = 1
|
||||
config.DownloadArchiveFormat = "zip"
|
||||
st.Settings.Save(config)
|
||||
serverConfig := &settings.Server{Root: root, AddonsPath: os.Getenv("FILEBROWSER_QA_ADDONS"), EnableThumbnails: true, ResizePreview: true, TypeDetectionByHeader: true}
|
||||
assets, err := fs.Sub(frontend.Assets(), "dist")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cache := diskcache.NewNoOp()
|
||||
uploads, err := NewUploadCache("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer uploads.Close()
|
||||
handler, err := NewHandler(img.New(2), cache, uploads, st, serverConfig, assets)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r = authorizeTestRequest(r, testSession(1, "QA", true))
|
||||
if r.URL.Path == "/api/session" {
|
||||
u, err := st.Users.Get(root, false, uint(1))
|
||||
if err != nil {
|
||||
http.Error(w, "user", 500)
|
||||
return
|
||||
}
|
||||
u.DisplayName = "QA Account"
|
||||
renderJSON(w, r, ssoUserInfo(u))
|
||||
return
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
command := exec.Command("node", os.Getenv("FILEBROWSER_QA_SCRIPT"))
|
||||
command.Env = append(os.Environ(), "FILEBROWSER_QA_URL="+server.URL, "FILEBROWSER_QA_ROOT="+root)
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("%v\n%s", err, output)
|
||||
}
|
||||
t.Log(string(output))
|
||||
}
|
||||
@@ -41,3 +41,15 @@ func containsExtension(list []string, extension string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Known web builds that could not complete server file round trips.
|
||||
// Keep installation available so users can update them when upstream fixes land.
|
||||
func CompatibilityIssue(id, build string) string {
|
||||
if id == "soundcraft" && build == "v0.11.0-ca335c74d511" {
|
||||
return "demoOnly"
|
||||
}
|
||||
if (id == "figcraft" && build == "v0.9.0-ab8d50277339") || (id == "lightcraft" && build == "v0.11.0-7cc682e1d543") {
|
||||
return "serverSave"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package addons
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestKnownDemoBuildIsIncompatible(t *testing.T) {
|
||||
if CompatibilityIssue("soundcraft", "v0.11.0-ca335c74d511") != "demoOnly" {
|
||||
t.Fatal("demo must not be offered as a server editor")
|
||||
}
|
||||
if CompatibilityIssue("wordcraft", "v0.11.0-ca335c74d511") != "" {
|
||||
t.Fatal("unrelated editor blocked")
|
||||
}
|
||||
if CompatibilityIssue("soundcraft", "test-123") != "" {
|
||||
t.Fatal("unrelated build blocked")
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
param([string]$Version = '3.0.0-sso.29')
|
||||
param([string]$Version = '3.1.0')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
Push-Location $repo
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
VERSION="${VERSION:-3.0.0-sso.29}"
|
||||
VERSION="${VERSION:-3.1.0}"
|
||||
COMMIT=$(git rev-parse --short HEAD)
|
||||
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
|
||||
mkdir -p build/release/linux-amd64
|
||||
|
||||
Reference in new issue
Block a user