diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md deleted file mode 100644 index 8d08beae..00000000 --- a/.claude/CLAUDE.md +++ /dev/null @@ -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 `, `git tag --contains `). -- **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` — `<= ` (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":"<= ","patched_versions":"","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. diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index 4c1605e6..00000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1 +0,0 @@ -* @filebrowser/maintainers diff --git a/README.md b/README.md index db2e47ac..623cf42a 100644 --- a/README.md +++ b/README.md @@ -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.png) +![Файловое пространство](docs/images/workspace.png) -## Начало работы +[Мобильный интерфейс](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). diff --git a/SECURITY.md b/SECURITY.md index f9a2989d..065f403b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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 и своевременно обновляйте сервер и аддоны. Наличие проверок не гарантирует отсутствия уязвимостей. diff --git a/docs/QA-3.1.0.md b/docs/QA-3.1.0.md new file mode 100644 index 00000000..ea685866 --- /dev/null +++ b/docs/QA-3.1.0.md @@ -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 в этой среде не проверялся. diff --git a/docs/images/workspace-mobile.png b/docs/images/workspace-mobile.png new file mode 100644 index 00000000..9f0604f7 Binary files /dev/null and b/docs/images/workspace-mobile.png differ diff --git a/docs/images/workspace.png b/docs/images/workspace.png index b8bf15be..7a373b40 100644 Binary files a/docs/images/workspace.png and b/docs/images/workspace.png differ diff --git a/frontend/package.json b/frontend/package.json index 98422d93..7b253209 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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", diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index 8519537d..a22309b9 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -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: {} diff --git a/frontend/scripts/check-dicom-preview.cjs b/frontend/scripts/check-dicom-preview.cjs index c7bf3038..9c3aa2aa 100644 --- a/frontend/scripts/check-dicom-preview.cjs +++ b/frontend/scripts/check-dicom-preview.cjs @@ -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(); diff --git a/frontend/scripts/check-previews.cjs b/frontend/scripts/check-previews.cjs new file mode 100644 index 00000000..dab76550 --- /dev/null +++ b/frontend/scripts/check-previews.cjs @@ -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; +}); diff --git a/frontend/scripts/check-workspace.cjs b/frontend/scripts/check-workspace.cjs new file mode 100644 index 00000000..6307ce68 --- /dev/null +++ b/frontend/scripts/check-workspace.cjs @@ -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; +}); diff --git a/frontend/src/api/files.ts b/frontend/src/api/files.ts index 0513ea15..e3aff258 100644 --- a/frontend/src/api/files.ts +++ b/frontend/src/api/files.ts @@ -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(); +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}`, diff --git a/frontend/src/components/files/CraftAction.vue b/frontend/src/components/files/CraftAction.vue index bde64c63..fba3cdc6 100644 --- a/frontend/src/components/files/CraftAction.vue +++ b/frontend/src/components/files/CraftAction.vue @@ -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) ) : [] ); diff --git a/frontend/src/components/files/CsvViewer.vue b/frontend/src/components/files/CsvViewer.vue index d15e9281..e9790d8a 100644 --- a/frontend/src/components/files/CsvViewer.vue +++ b/frontend/src/components/files/CsvViewer.vue @@ -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; } diff --git a/frontend/src/components/files/DicomViewer.vue b/frontend/src/components/files/DicomViewer.vue index ae367258..1e68ba71 100644 --- a/frontend/src/components/files/DicomViewer.vue +++ b/frontend/src/components/files/DicomViewer.vue @@ -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); diff --git a/frontend/src/components/files/ServerFilePicker.vue b/frontend/src/components/files/ServerFilePicker.vue new file mode 100644 index 00000000..9161549d --- /dev/null +++ b/frontend/src/components/files/ServerFilePicker.vue @@ -0,0 +1,319 @@ + + + diff --git a/frontend/src/components/prompts/CurrentPassword.vue b/frontend/src/components/prompts/CurrentPassword.vue deleted file mode 100644 index dfccf3fd..00000000 --- a/frontend/src/components/prompts/CurrentPassword.vue +++ /dev/null @@ -1,58 +0,0 @@ - - - diff --git a/frontend/src/components/prompts/DeleteUser.vue b/frontend/src/components/prompts/DeleteUser.vue deleted file mode 100644 index 821db17d..00000000 --- a/frontend/src/components/prompts/DeleteUser.vue +++ /dev/null @@ -1,40 +0,0 @@ - - - diff --git a/frontend/src/components/prompts/Prompts.vue b/frontend/src/components/prompts/Prompts.vue index 38acef10..49f5c33b 100644 --- a/frontend/src/components/prompts/Prompts.vue +++ b/frontend/src/components/prompts/Prompts.vue @@ -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([ ["share", Share], ["upload", Upload], ["share-delete", ShareDelete], - ["deleteUser", DeleteUser], ["discardEditorChanges", DiscardEditorChanges], ["resolve-conflict", ResolveConflict], - ["current-password", CurrentPassword], ]); const modal = computed(() => { diff --git a/frontend/src/components/prompts/UploadFiles.vue b/frontend/src/components/prompts/UploadFiles.vue index 8b3a0add..c6f9a4f6 100644 --- a/frontend/src/components/prompts/UploadFiles.vue +++ b/frontend/src/components/prompts/UploadFiles.vue @@ -1,218 +1,126 @@ - - - + diff --git a/frontend/src/components/settings/Addons.vue b/frontend/src/components/settings/Addons.vue index c5231637..0165483f 100644 --- a/frontend/src/components/settings/Addons.vue +++ b/frontend/src/components/settings/Addons.vue @@ -27,6 +27,10 @@ }} +

+ {{ t("addons.incompatible") }} · + {{ t("addons.compatibility." + addon.compatibilityIssue) }} +

{{ t("addons.deckcraftFormat") }}

@@ -39,7 +43,7 @@ > .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; } } diff --git a/frontend/src/css/upload-files.css b/frontend/src/css/upload-files.css index ca1a1c48..214866b0 100644 --- a/frontend/src/css/upload-files.css +++ b/frontend/src/css/upload-files.css @@ -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; } } diff --git a/frontend/src/css/workspace.css b/frontend/src/css/workspace.css index e5895c1d..f2b3efb9 100644 --- a/frontend/src/css/workspace.css +++ b/frontend/src/css/workspace.css @@ -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); +} diff --git a/frontend/src/i18n/en.json b/frontend/src/i18n/en.json index 1b9b9ba2..93c1e2b9 100644 --- a/frontend/src/i18n/en.json +++ b/frontend/src/i18n/en.json @@ -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" } } diff --git a/frontend/src/i18n/ru.json b/frontend/src/i18n/ru.json index 8d00659b..e83c02f1 100644 --- a/frontend/src/i18n/ru.json +++ b/frontend/src/i18n/ru.json @@ -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": "мин" } } diff --git a/frontend/src/stores/addons.ts b/frontend/src/stores/addons.ts index e89722a8..6c43066f 100644 --- a/frontend/src/stores/addons.ts +++ b/frontend/src/stores/addons.ts @@ -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 ); }, }, diff --git a/frontend/src/stores/upload.ts b/frontend/src/stores/upload.ts index 065679fd..5569db77 100644 --- a/frontend/src/stores/upload.ts +++ b/frontend/src/stores/upload.ts @@ -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 + ) ); // diff --git a/frontend/src/utils/__tests__/transfer.test.ts b/frontend/src/utils/__tests__/transfer.test.ts new file mode 100644 index 00000000..fb7be9ac --- /dev/null +++ b/frontend/src/utils/__tests__/transfer.test.ts @@ -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); +}); diff --git a/frontend/src/utils/craft.ts b/frontend/src/utils/craft.ts index 1836fde3..cb0b2cb6 100644 --- a/frontend/src/utils/craft.ts +++ b/frontend/src/utils/craft.ts @@ -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") diff --git a/frontend/src/utils/dicom-series.ts b/frontend/src/utils/dicom-series.ts index 2df80976..1ea138ee 100644 --- a/frontend/src/utils/dicom-series.ts +++ b/frontend/src/utils/dicom-series.ts @@ -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( diff --git a/frontend/src/utils/transfer.ts b/frontend/src/utils/transfer.ts new file mode 100644 index 00000000..209584e0 --- /dev/null +++ b/frontend/src/utils/transfer.ts @@ -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, + }; +} diff --git a/frontend/src/views/files/CraftEditor.vue b/frontend/src/views/files/CraftEditor.vue index 937ddce8..8dbb9857 100644 --- a/frontend/src/views/files/CraftEditor.vue +++ b/frontend/src/views/files/CraftEditor.vue @@ -1,5 +1,17 @@