Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a29a8b18ad | ||
|
|
e33abc948c | ||
|
|
ab49e22357 | ||
|
|
75ae2092ad | ||
|
|
0dc0384c78 | ||
|
|
17b6dd2041 | ||
|
|
0a59059738 | ||
|
|
bfcf6e48b2 | ||
|
|
02307802bc | ||
|
|
fff91c446b | ||
|
|
e158558da3 | ||
|
|
c84f90e2cc | ||
|
|
72567acd28 | ||
|
|
39aaaed969 | ||
|
|
8eb6b36888 | ||
|
|
83b604437c | ||
|
|
73ad61e7a5 | ||
|
|
fb20258489 | ||
|
|
78c006184b | ||
|
|
d3116aba96 | ||
|
|
b7518aa450 | ||
|
|
eb8031b126 | ||
|
|
e4b841a8d8 |
No files matched your search
@@ -0,0 +1,27 @@
|
||||
name: ci / module boundaries
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/core/src/**'
|
||||
- 'apps/web/src/features/uploads/**'
|
||||
- 'services/api/internal/uploads/**'
|
||||
- 'scripts/check-boundaries.mjs'
|
||||
- '.gitea/workflows/ci-boundaries.yml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'packages/core/src/**'
|
||||
- 'apps/web/src/features/uploads/**'
|
||||
- 'services/api/internal/uploads/**'
|
||||
- 'scripts/check-boundaries.mjs'
|
||||
- '.gitea/workflows/ci-boundaries.yml'
|
||||
|
||||
jobs:
|
||||
boundaries:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: '22' }
|
||||
- run: node scripts/check-boundaries.mjs
|
||||
@@ -1,5 +1,5 @@
|
||||
# Rust-часть десктопа: прокси и проверки URL. Полная сборка инсталлятора — локально
|
||||
# (`pnpm --filter @pipu/desktop bundle`): на раннере нет Windows и WebKitGTK.
|
||||
# Rust-часть десктопа: прокси и проверки URL. Установщики — в release.yml
|
||||
# (Linux .deb и Windows NSIS через cargo-xwin на ubuntu-latest).
|
||||
name: ci / desktop
|
||||
|
||||
on:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# Релиз по тегу vMAJOR.MINOR.PATCH[-rc.N]: Gitea Release с заметками → APK.
|
||||
# Релиз создаётся сразу (статус Android — «собирается»); сборка APK докладывает в него файлы
|
||||
# и переписывает статус: собран / не удалась (scripts/release.mjs).
|
||||
# Релиз по тегу vMAJOR.MINOR.PATCH[-rc.N]: Gitea Release с заметками → APK, Linux и Windows.
|
||||
# Релиз создаётся сразу (статусы Android/десктоп — «собирается»); сборки докладывают файлы
|
||||
# и переписывают статус: собран / не удалась (scripts/release.mjs).
|
||||
# Один Ubuntu-раннер: сначала APK, потом десктоп (Linux native + Windows через cargo-xwin).
|
||||
# После сборок job prune оставляет файлы у последних 8 релизов и последние 8 прогонов Actions.
|
||||
# Docker-образы не публикуются: сервер собирает их сам из клонированного репозитория (deploy/update.sh).
|
||||
#
|
||||
# Секреты (Settings → Actions → Secrets):
|
||||
@@ -197,3 +199,142 @@ jobs:
|
||||
- name: Статус в релизе — сборка отменена
|
||||
if: cancelled()
|
||||
run: node scripts/release.mjs android cancelled
|
||||
|
||||
# После Android: на одном хосте параллельный Tauri + Gradle валит раннер.
|
||||
# Windows NSIS — cargo-xwin + makensis на этом же Ubuntu (виндового раннера нет).
|
||||
desktop:
|
||||
name: desktop (Linux и Windows в релиз)
|
||||
needs: [release, android]
|
||||
if: always() && needs.release.result == 'success'
|
||||
timeout-minutes: 90
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
PIPU_VERSION: ${{ needs.release.outputs.version }}
|
||||
GITEA_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
PUBLIC_URL: ${{ vars.PUBLIC_URL || 'https://gitea.hsrv.site' }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
VERSION: ${{ needs.release.outputs.version }}
|
||||
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
XWIN_CACHE_DIR: /opt/ci-cache/xwin
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Статус в релизе — собирается
|
||||
run: |
|
||||
node scripts/release.mjs desktop linux building
|
||||
node scripts/release.mjs desktop windows building
|
||||
- name: Rust
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
- run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential curl wget file \
|
||||
libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev \
|
||||
libdbus-1-dev libsecret-1-dev patchelf \
|
||||
nsis lld llvm clang
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: "${{ env.NODE_VERSION }}", cache: pnpm }
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
~/.cargo/bin/cargo-xwin
|
||||
key: cargo-desktop-${{ hashFiles('apps/desktop/src-tauri/Cargo.toml') }}
|
||||
restore-keys: cargo-desktop-
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Сборка deb
|
||||
id: linux
|
||||
working-directory: apps/desktop
|
||||
run: |
|
||||
set -euo pipefail
|
||||
pnpm bundle:linux
|
||||
bundle=src-tauri/target/release/bundle
|
||||
shopt -s nullglob
|
||||
for f in "$bundle"/deb/*.deb; do
|
||||
cp "$f" "$GITHUB_WORKSPACE/pipu-music-${PIPU_VERSION}-linux.deb"
|
||||
done
|
||||
ls -lh "$GITHUB_WORKSPACE/pipu-music-${PIPU_VERSION}-linux.deb"
|
||||
rm -rf src-tauri/target/release
|
||||
- name: Linux в релиз
|
||||
id: linux-upload
|
||||
run: |
|
||||
set -euo pipefail
|
||||
f="pipu-music-${PIPU_VERSION}-linux.deb"
|
||||
if [ ! -f "$f" ]; then
|
||||
echo "::error::нет $f после сборки"
|
||||
exit 1
|
||||
fi
|
||||
node scripts/release.mjs desktop linux success "$f"
|
||||
- name: Windows toolchain
|
||||
if: ${{ !cancelled() }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rustup target add x86_64-pc-windows-msvc
|
||||
if ! command -v cargo-xwin >/dev/null; then
|
||||
cargo install --locked cargo-xwin
|
||||
fi
|
||||
if [ ! -d /opt/ci-cache ]; then
|
||||
echo "XWIN_CACHE_DIR=$HOME/.cache/xwin" >> "$GITHUB_ENV"
|
||||
mkdir -p "$HOME/.cache/xwin"
|
||||
else
|
||||
mkdir -p /opt/ci-cache/xwin
|
||||
fi
|
||||
- name: Сборка NSIS
|
||||
id: win
|
||||
if: ${{ !cancelled() }}
|
||||
working-directory: apps/desktop
|
||||
run: |
|
||||
set -euo pipefail
|
||||
pnpm bundle:windows:cross
|
||||
bundle=src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis
|
||||
shopt -s nullglob
|
||||
copied=
|
||||
for f in "$bundle"/*-setup.exe; do
|
||||
cp "$f" "$GITHUB_WORKSPACE/pipu-music-${PIPU_VERSION}-windows-setup.exe"
|
||||
copied=1
|
||||
done
|
||||
if [ -z "$copied" ]; then
|
||||
echo "::error::нет NSIS setup.exe после сборки в $bundle"
|
||||
ls -la "$bundle" || true
|
||||
exit 1
|
||||
fi
|
||||
ls -lh "$GITHUB_WORKSPACE/pipu-music-${PIPU_VERSION}-windows-setup.exe"
|
||||
- name: Windows в релиз
|
||||
id: win-upload
|
||||
if: ${{ !cancelled() && steps.win.outcome == 'success' }}
|
||||
run: node scripts/release.mjs desktop windows success "pipu-music-${PIPU_VERSION}-windows-setup.exe"
|
||||
- name: Статус Linux — сборка не удалась
|
||||
if: failure() && steps.linux-upload.outcome != 'success'
|
||||
run: node scripts/release.mjs desktop linux failure
|
||||
- name: Статус Windows — сборка не удалась
|
||||
if: failure() && steps.win-upload.outcome != 'success'
|
||||
run: node scripts/release.mjs desktop windows failure
|
||||
- name: Статус в релизе — сборка отменена
|
||||
if: cancelled()
|
||||
run: |
|
||||
node scripts/release.mjs desktop linux cancelled
|
||||
node scripts/release.mjs desktop windows cancelled
|
||||
|
||||
prune:
|
||||
name: prune (старые файлы и прогоны)
|
||||
needs: [release, android, desktop]
|
||||
if: always() && needs.release.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: "${{ env.NODE_VERSION }}" }
|
||||
- name: Оставить 8 релизов и 8 прогонов
|
||||
env:
|
||||
GITEA_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
run: node scripts/release.mjs prune
|
||||
@@ -20,6 +20,8 @@ __pycache__/
|
||||
.ruff_cache/
|
||||
|
||||
# env / secrets
|
||||
deploy/config.local
|
||||
deploy/.management.lock
|
||||
.env
|
||||
*.pem
|
||||
*.keystore
|
||||
@@ -41,3 +43,6 @@ apps/desktop/src-tauri/target/
|
||||
apps/desktop/src-tauri/gen/
|
||||
apps/desktop/src-tauri/tauri.release.json
|
||||
apps/desktop/release/
|
||||
|
||||
# Intermediate platform icon renders (final assets live under apps/).
|
||||
/artifacts/icon-build/
|
||||
@@ -0,0 +1,10 @@
|
||||
# Работа с проектом
|
||||
|
||||
- Начинай с ближайшего локального `AGENTS.md` и файлов конкретной возможности. Карта документов: `docs/README.md`; реализация архитектуры: `docs/architecture.md`.
|
||||
- Web/desktop UI: `apps/web/src`; Android: `apps/mobile/src`; общие правила клиентов: `packages/core/src`; Go API: `services/api/internal`; рекомендации: `services/recommender/pipu_rec`.
|
||||
- Контракт HTTP — `api/openapi.yaml`. Читай нужную операцию и связанные схемы. Generated-код (`**/gen/**`, `**/generated/**`) и lock-файлы исследуй точечно; не редактируй вручную.
|
||||
- После изменения OpenAPI: `pnpm --filter @pipu/api-client generate`, затем из `services/api`: `go generate ./...`. Проверяй и коммить результат генерации.
|
||||
- Новые правила размещай у владельца сценария, IO — в адаптере. Сохраняй явные границы транзакций и платформенные особенности. Узкий интерфейс вводи для конкретного потребителя.
|
||||
- Локально достаточно запускать проверки затронутой области и непосредственно связанных сценариев. Полный набор тестов и проверок повторно выполняется в CI/CD; не запускай все проверки проекта перед каждой сдачей без необходимости. Расширяй локальную проверку при изменении общих контрактов, межмодульных зависимостей или при обнаружении ошибок. Команды запускаются из корня, если не сказано иначе.
|
||||
- Справочник полных проверок (выбирай локально только относящиеся к изменению): `pnpm typecheck`, `pnpm test`, `pnpm i18n:check`, `pnpm test:scripts`. Go: из `services/api` — `go vet ./...`, `go test ./...`. Python: из `services/recommender` — `uv run ruff check .`, `uv run mypy pipu_rec`, `uv run pytest`.
|
||||
- Не меняй пользовательские артефакты, локальные бинарники и посторонние незакоммиченные файлы.
|
||||
@@ -5,6 +5,7 @@ Self-hosted музыкальный сервис: веб, десктоп и Andro
|
||||
|
||||
- Идея продукта: [docs/IDEA.md](docs/IDEA.md)
|
||||
- Документация: [docs/README.md](docs/README.md)
|
||||
- Карта работы с кодом и проверок: [AGENTS.md](AGENTS.md)
|
||||
- Установка сервера на свой домен: [docs/install-guide.md](docs/install-guide.md)
|
||||
|
||||
## Структура
|
||||
@@ -47,6 +48,7 @@ pnpm --filter @pipu/web dev
|
||||
|
||||
```bash
|
||||
pnpm typecheck && pnpm test && pnpm i18n:check && pnpm test:scripts
|
||||
pnpm check:boundaries
|
||||
```
|
||||
|
||||
```bash
|
||||
|
||||
@@ -22,6 +22,149 @@ tags:
|
||||
security:
|
||||
- bearerAuth: []
|
||||
paths:
|
||||
/api/v1/admin/server/updates:
|
||||
get:
|
||||
operationId: getServerUpdates
|
||||
tags: [admin]
|
||||
parameters:
|
||||
- in: query
|
||||
name: source_id
|
||||
schema: {type: string}
|
||||
responses:
|
||||
"200":
|
||||
description: Server management result
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ServerUpdates"
|
||||
default:
|
||||
$ref: "#/components/responses/Problem"
|
||||
post:
|
||||
operationId: startServerUpdate
|
||||
tags: [admin]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ServerUpdateRequest"
|
||||
responses:
|
||||
"202":
|
||||
description: Server management result
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ServerJob"
|
||||
default:
|
||||
$ref: "#/components/responses/Problem"
|
||||
/api/v1/admin/server/update-sources:
|
||||
put:
|
||||
operationId: saveServerUpdateSources
|
||||
tags: [admin]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ServerSources"
|
||||
responses:
|
||||
"200":
|
||||
description: Server management result
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ServerSources"
|
||||
default:
|
||||
$ref: "#/components/responses/Problem"
|
||||
/api/v1/admin/server/config:
|
||||
get:
|
||||
operationId: getServerConfig
|
||||
tags: [admin]
|
||||
responses:
|
||||
"200":
|
||||
description: Server management result
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ServerConfig"
|
||||
default:
|
||||
$ref: "#/components/responses/Problem"
|
||||
patch:
|
||||
operationId: saveServerConfig
|
||||
tags: [admin]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ServerConfigPatch"
|
||||
responses:
|
||||
"200":
|
||||
description: Server management result
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ServerConfig"
|
||||
default:
|
||||
$ref: "#/components/responses/Problem"
|
||||
/api/v1/admin/server/config/apply:
|
||||
post:
|
||||
operationId: applyServerConfig
|
||||
tags: [admin]
|
||||
responses:
|
||||
"202":
|
||||
description: Server management result
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ServerJob"
|
||||
default:
|
||||
$ref: "#/components/responses/Problem"
|
||||
/api/v1/admin/genius:
|
||||
get:
|
||||
operationId: getGeniusStats
|
||||
tags: [admin]
|
||||
responses:
|
||||
"200":
|
||||
description: Persistent enrichment statistics (admin only)
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/GeniusStats"
|
||||
post:
|
||||
operationId: controlGenius
|
||||
tags: [admin]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [action]
|
||||
properties:
|
||||
action:
|
||||
type: string
|
||||
enum: [start, pause, retry]
|
||||
responses:
|
||||
"200":
|
||||
description: Updated statistics
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/GeniusStats"
|
||||
/api/v1/tracks/{id}/genius:
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityId"
|
||||
get:
|
||||
operationId: getTrackGenius
|
||||
tags: [catalog]
|
||||
responses:
|
||||
"200":
|
||||
description: Cached lyrics and annotations; never makes an upstream request
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/GeniusContent"
|
||||
/healthz:
|
||||
get:
|
||||
operationId: getHealthz
|
||||
@@ -946,6 +1089,23 @@ paths:
|
||||
$ref: "#/components/schemas/LibraryErrorPage"
|
||||
default:
|
||||
$ref: "#/components/responses/Problem"
|
||||
/api/v1/admin/library/analysis/errors:
|
||||
get:
|
||||
operationId: listAnalysisErrors
|
||||
tags: [library]
|
||||
summary: Неудавшиеся задачи аудиоанализа с путями файлов (admin)
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/Limit"
|
||||
- $ref: "#/components/parameters/Cursor"
|
||||
responses:
|
||||
"200":
|
||||
description: Страница ошибок аудиоанализа, упорядоченная по ID трека
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/AnalysisErrorPage"
|
||||
default:
|
||||
$ref: "#/components/responses/Problem"
|
||||
/api/v1/admin/library/host-dirs:
|
||||
get:
|
||||
operationId: listHostDirs
|
||||
@@ -1382,9 +1542,10 @@ paths:
|
||||
get:
|
||||
operationId: getOnboarding
|
||||
tags: [wave]
|
||||
summary: Онбординг вкуса — исполнители и жанры библиотеки для выбора
|
||||
summary: Анкета рекомендаций — варианты, сохранённые ответы и необходимость заполнения
|
||||
description: |
|
||||
`required` — показать онбординг: пользователь его не проходил и не пропускал, а своей истории почти нет.
|
||||
`required` — пользователь не проходил и не пропускал анкету либо администратор сбросил рекомендации.
|
||||
`choice` содержит ответы с текущей приблизительной возрастной группой; исходная группа и год хранятся на сервере.
|
||||
responses:
|
||||
"200":
|
||||
description: Варианты и состояние
|
||||
@@ -1502,9 +1663,10 @@ paths:
|
||||
operationId: getAppClients
|
||||
tags: [app]
|
||||
security: [] # публично: страница /download без входа
|
||||
summary: Клиенты последнего релиза (Android и десктоп)
|
||||
summary: Клиенты последних релизов (Android и десктоп)
|
||||
description: |
|
||||
Тот же релиз Gitea, что и для Android: APK, установщик Windows, AppImage/deb, DMG.
|
||||
Тот же релиз Gitea, что и для Android: APK, установщик Windows, .deb, DMG.
|
||||
У каждой платформы `older` — предыдущие сборки (до 8 релизов, сколько есть с файлами).
|
||||
Нет настроек Gitea или файлов клиентов — `404 app.update_unavailable`.
|
||||
responses:
|
||||
"200":
|
||||
@@ -1660,6 +1822,54 @@ paths:
|
||||
'204':
|
||||
description: Deleted
|
||||
|
||||
/api/v1/me/playlists/{id}/share:
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema: { type: string, format: uuid }
|
||||
post:
|
||||
tags: [collection]
|
||||
operationId: sharePlaylist
|
||||
summary: Создать или вернуть ссылку только для чтения (только владелец)
|
||||
responses:
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
'200':
|
||||
description: Идентификатор ссылки для /shared/playlist/{shareId}; для открытия требуется вход
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/PlaylistShare'
|
||||
delete:
|
||||
tags: [collection]
|
||||
operationId: revokePlaylistShare
|
||||
summary: Отозвать ссылку (только владелец); повторная публикация создаёт новую ссылку
|
||||
responses:
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
'204':
|
||||
description: Доступ по прежней ссылке отключён
|
||||
/api/v1/shared/playlists/{shareId}:
|
||||
parameters:
|
||||
- in: path
|
||||
name: shareId
|
||||
required: true
|
||||
schema: { type: string, format: uuid }
|
||||
get:
|
||||
tags: [collection]
|
||||
operationId: getSharedPlaylist
|
||||
summary: Прочитать плейлист по действующей ссылке (требуется вход)
|
||||
responses:
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
'200':
|
||||
description: Плейлист с реакциями и ссылками на стрим для текущего слушателя
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Playlist'
|
||||
|
||||
components:
|
||||
parameters:
|
||||
SourceId:
|
||||
@@ -1720,6 +1930,90 @@ components:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Problem"
|
||||
schemas:
|
||||
ServerSource:
|
||||
type: object
|
||||
required: [id, name, url]
|
||||
properties:
|
||||
id: {type: string, maxLength: 64}
|
||||
name: {type: string, maxLength: 100}
|
||||
url: {type: string, maxLength: 2048}
|
||||
ServerSources:
|
||||
type: object
|
||||
required: [sources]
|
||||
properties:
|
||||
sources:
|
||||
type: array
|
||||
maxItems: 20
|
||||
items: {$ref: "#/components/schemas/ServerSource"}
|
||||
ServerJob:
|
||||
type: object
|
||||
required: [id, kind, state, started_at, finished_at, target, log]
|
||||
properties:
|
||||
id: {type: string}
|
||||
kind: {type: string, enum: [update, config]}
|
||||
state: {type: string, enum: [running, succeeded, failed]}
|
||||
started_at: {type: string}
|
||||
finished_at: {type: string}
|
||||
target: {type: string}
|
||||
log: {type: string}
|
||||
ServerUpdates:
|
||||
type: object
|
||||
required: [sources, versions, current_version, job, source_error]
|
||||
properties:
|
||||
sources:
|
||||
type: array
|
||||
items: {$ref: "#/components/schemas/ServerSource"}
|
||||
versions:
|
||||
type: array
|
||||
items: {type: string}
|
||||
current_version: {type: string}
|
||||
source_error: {type: string}
|
||||
job:
|
||||
allOf: [{$ref: "#/components/schemas/ServerJob"}]
|
||||
nullable: true
|
||||
ServerUpdateRequest:
|
||||
type: object
|
||||
required: [source_id, channel]
|
||||
properties:
|
||||
source_id: {type: string}
|
||||
channel: {type: string, enum: [latest, version, main]}
|
||||
version: {type: string}
|
||||
ServerConfigEntry:
|
||||
type: object
|
||||
required: [key, group, type, secret, readonly, effective, env, local, default_value, source]
|
||||
properties:
|
||||
key: {type: string}
|
||||
group: {type: string}
|
||||
type: {type: string}
|
||||
secret: {type: boolean}
|
||||
readonly: {type: boolean}
|
||||
effective: {type: string}
|
||||
env: {type: string, nullable: true}
|
||||
local: {type: string, nullable: true}
|
||||
default_value: {type: string}
|
||||
source: {type: string, enum: [env, local, default]}
|
||||
ServerConfig:
|
||||
type: object
|
||||
required: [entries, revision, restart_required]
|
||||
properties:
|
||||
revision: {type: string}
|
||||
restart_required: {type: boolean}
|
||||
entries:
|
||||
type: array
|
||||
items: {$ref: "#/components/schemas/ServerConfigEntry"}
|
||||
ServerConfigPatch:
|
||||
type: object
|
||||
required: [revision, values]
|
||||
properties:
|
||||
revision: {type: string}
|
||||
values:
|
||||
type: object
|
||||
additionalProperties: {type: string, nullable: true}
|
||||
PlaylistShare:
|
||||
type: object
|
||||
required: [share_id]
|
||||
properties:
|
||||
share_id: { type: string, format: uuid }
|
||||
PlaylistInput:
|
||||
type: object
|
||||
required: [name, description, track_ids]
|
||||
@@ -1756,6 +2050,12 @@ components:
|
||||
- type: object
|
||||
required: [tracks]
|
||||
properties:
|
||||
share_id:
|
||||
type: string
|
||||
format: uuid
|
||||
nullable: true
|
||||
readOnly: true
|
||||
description: Действующая ссылка; возвращается только владельцу через /me/playlists
|
||||
tracks:
|
||||
type: array
|
||||
items: { $ref: '#/components/schemas/Track' }
|
||||
@@ -1773,6 +2073,8 @@ components:
|
||||
properties:
|
||||
required:
|
||||
type: boolean
|
||||
choice:
|
||||
$ref: "#/components/schemas/OnboardingChoice"
|
||||
artists:
|
||||
type: array
|
||||
items:
|
||||
@@ -1808,6 +2110,19 @@ components:
|
||||
type: object
|
||||
required: [artist_ids, genres]
|
||||
properties:
|
||||
gender:
|
||||
type: string
|
||||
nullable: true
|
||||
enum: [male, female, other]
|
||||
age_group:
|
||||
type: string
|
||||
nullable: true
|
||||
enum: [under_13, "13_19", "20_29", "30_39", "40_49", "50_59", 60_plus]
|
||||
description: Текущая приблизительная возрастная группа. Сервер хранит год выбора и учитывает прошедшие годы.
|
||||
age_group_year:
|
||||
type: integer
|
||||
readOnly: true
|
||||
description: Год последнего выбора возрастной группы.
|
||||
artist_ids:
|
||||
type: array
|
||||
maxItems: 50
|
||||
@@ -2357,6 +2672,9 @@ components:
|
||||
nullable: true
|
||||
role:
|
||||
$ref: "#/components/schemas/Role"
|
||||
manages_updates:
|
||||
type: boolean
|
||||
description: Управление обновлениями сервера. У admin всегда; другим выдаёт только admin
|
||||
reviews_uploads:
|
||||
type: boolean
|
||||
description: Может рассматривать очередь на добавление. Не следует из роли и может быть у нескольких людей сразу
|
||||
@@ -2412,6 +2730,9 @@ components:
|
||||
nullable: true
|
||||
role:
|
||||
$ref: "#/components/schemas/Role"
|
||||
manages_updates:
|
||||
type: boolean
|
||||
description: Управление обновлениями сервера. У admin всегда; другим выдаёт только admin
|
||||
reviews_uploads:
|
||||
type: boolean
|
||||
description: Может рассматривать очередь на добавление. Не следует из роли и может быть у нескольких людей сразу
|
||||
@@ -2452,6 +2773,9 @@ components:
|
||||
maxLength: 64
|
||||
role:
|
||||
$ref: "#/components/schemas/Role"
|
||||
manages_updates:
|
||||
type: boolean
|
||||
description: Управление обновлениями сервера. У admin всегда; другим выдаёт только admin
|
||||
reviews_uploads:
|
||||
type: boolean
|
||||
description: Сразу выдать аудит загрузок. Может задать только админ
|
||||
@@ -2478,6 +2802,9 @@ components:
|
||||
$ref: "#/components/schemas/Role"
|
||||
is_blocked:
|
||||
type: boolean
|
||||
manages_updates:
|
||||
type: boolean
|
||||
description: Управление обновлениями сервера. У admin всегда; другим выдаёт только admin
|
||||
reviews_uploads:
|
||||
type: boolean
|
||||
description: Выдать или забрать аудит загрузок. Может менять только админ, в том числе у себя
|
||||
@@ -2549,6 +2876,8 @@ components:
|
||||
type: object
|
||||
required: [id, name, type, nfs_server, nfs_export, nfs_options, local_path, tag_priority, scan_interval_minutes, accepts_uploads, write_template, status, status_message, last_scan_at, created_at, scan]
|
||||
properties:
|
||||
excluded_dirs:
|
||||
$ref: "#/components/schemas/ExcludedDirs"
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
@@ -2609,6 +2938,8 @@ components:
|
||||
type: object
|
||||
required: [name, type]
|
||||
properties:
|
||||
excluded_dirs:
|
||||
$ref: "#/components/schemas/ExcludedDirs"
|
||||
name:
|
||||
type: string
|
||||
maxLength: 100
|
||||
@@ -2636,6 +2967,8 @@ components:
|
||||
SourcePatch:
|
||||
type: object
|
||||
properties:
|
||||
excluded_dirs:
|
||||
$ref: "#/components/schemas/ExcludedDirs"
|
||||
name:
|
||||
type: string
|
||||
maxLength: 100
|
||||
@@ -2664,6 +2997,14 @@ components:
|
||||
description: |
|
||||
Шаблон пути новых файлов; пусто — убрать. Неверный синтаксис — `422 validation.template_invalid`
|
||||
с `params.reason`. Проверка обратимости не обязательна для сохранения — её показывает `write-template/check`.
|
||||
ExcludedDirs:
|
||||
type: array
|
||||
maxItems: 100
|
||||
description: Literal folder paths relative to the storage root, including all descendants. Case sensitive; no glob matching. Empty list clears exclusions. Existing library records are retained, but their scan and analysis are skipped. Changes require no running scan.
|
||||
items:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 1000
|
||||
SourceTestResult:
|
||||
type: object
|
||||
required: [ok, message, audio_files]
|
||||
@@ -2834,6 +3175,16 @@ components:
|
||||
type: object
|
||||
required: [running, full, started_at, finished_at, found, to_process, processed, added, updated, moved, missing, errors, error]
|
||||
properties:
|
||||
phase:
|
||||
type: string
|
||||
enum: [walking, preparing, processing, finalizing]
|
||||
description: Current scan stage; progress percentage is available only during processing.
|
||||
walked_dirs:
|
||||
type: integer
|
||||
description: Directories visited so far, including the source root.
|
||||
current_dir:
|
||||
type: string
|
||||
description: Current directory relative to the source root, using forward slashes.
|
||||
running:
|
||||
type: boolean
|
||||
full:
|
||||
@@ -2935,6 +3286,39 @@ components:
|
||||
next_cursor:
|
||||
type: string
|
||||
nullable: true
|
||||
AnalysisError:
|
||||
type: object
|
||||
required: [track_id, title, source_id, source_name, rel_path, error]
|
||||
properties:
|
||||
track_id:
|
||||
type: string
|
||||
format: uuid
|
||||
title:
|
||||
type: string
|
||||
source_id:
|
||||
type: string
|
||||
format: uuid
|
||||
nullable: true
|
||||
source_name:
|
||||
type: string
|
||||
nullable: true
|
||||
rel_path:
|
||||
type: string
|
||||
nullable: true
|
||||
description: Path relative to the source root; primary file if available, otherwise a known file of this track.
|
||||
error:
|
||||
type: string
|
||||
AnalysisErrorPage:
|
||||
type: object
|
||||
required: [items, next_cursor]
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/AnalysisError"
|
||||
next_cursor:
|
||||
type: string
|
||||
nullable: true
|
||||
HostDirList:
|
||||
type: object
|
||||
required: [path, dirs]
|
||||
@@ -3016,10 +3400,51 @@ components:
|
||||
description: Аудиопризнаки (после анализа) — для анимации волны и выравнивания громкости
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/TrackFeatures"
|
||||
GeniusStats:
|
||||
type: object
|
||||
required: [configured, paused, running, total, pending, matched, lyrics, annotations, images, unmatched, errors, last_error, cooldown_until]
|
||||
properties:
|
||||
configured: { type: boolean }
|
||||
paused: { type: boolean }
|
||||
running: { type: boolean }
|
||||
total: { type: integer }
|
||||
pending: { type: integer }
|
||||
matched: { type: integer }
|
||||
lyrics: { type: integer }
|
||||
annotations: { type: integer }
|
||||
images: { type: integer }
|
||||
unmatched: { type: integer }
|
||||
errors: { type: integer }
|
||||
last_error: { type: string }
|
||||
cooldown_until: { type: string, format: date-time }
|
||||
GeniusContent:
|
||||
type: object
|
||||
required: [status, lyrics, source_url, song_image_url, artist_image_url, description, annotations]
|
||||
properties:
|
||||
status: { type: string }
|
||||
lyrics: { type: string }
|
||||
source_url: { type: string }
|
||||
song_image_url: { type: string }
|
||||
artist_image_url: { type: string }
|
||||
description: { type: string }
|
||||
annotations:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/GeniusAnnotation"
|
||||
GeniusAnnotation:
|
||||
type: object
|
||||
required: [fragment, text, url, verified, authors]
|
||||
properties:
|
||||
fragment: { type: string }
|
||||
text: { type: string }
|
||||
url: { type: string }
|
||||
verified: { type: boolean }
|
||||
authors: { type: string }
|
||||
Artist:
|
||||
type: object
|
||||
required: [id, name, album_count, track_count]
|
||||
properties:
|
||||
image_url: { type: string }
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
@@ -3495,12 +3920,12 @@ components:
|
||||
AppClient:
|
||||
type: string
|
||||
enum: [android, windows, linux, macos]
|
||||
AppClientFile:
|
||||
AppClientBuild:
|
||||
type: object
|
||||
required: [client, filename, size, download_url]
|
||||
required: [version, filename, size, download_url]
|
||||
properties:
|
||||
client:
|
||||
$ref: "#/components/schemas/AppClient"
|
||||
version:
|
||||
type: string
|
||||
filename:
|
||||
type: string
|
||||
size:
|
||||
@@ -3510,6 +3935,27 @@ components:
|
||||
type: string
|
||||
download_url:
|
||||
type: string
|
||||
AppClientFile:
|
||||
type: object
|
||||
required: [client, filename, size, download_url]
|
||||
properties:
|
||||
client:
|
||||
$ref: "#/components/schemas/AppClient"
|
||||
version:
|
||||
type: string
|
||||
filename:
|
||||
type: string
|
||||
size:
|
||||
type: integer
|
||||
format: int64
|
||||
sha256:
|
||||
type: string
|
||||
download_url:
|
||||
type: string
|
||||
older:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/AppClientBuild"
|
||||
AppClients:
|
||||
type: object
|
||||
required: [version, version_code, notes_md, clients]
|
||||
|
||||
@@ -5,12 +5,14 @@ import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = dirname(fileURLToPath(import.meta.url));
|
||||
const conf = JSON.parse(readFileSync(resolve(root, 'src-tauri/tauri.conf.json'), 'utf8'));
|
||||
let version = '0.0.0';
|
||||
try {
|
||||
let version = process.env.PIPU_VERSION ?? '0.0.0';
|
||||
if (!process.env.PIPU_VERSION) {
|
||||
try {
|
||||
const tag = execFileSync('git', ['describe', '--tags', '--abbrev=0'], { encoding: 'utf8' }).trim();
|
||||
version = tag.replace(/^v/, '').replace(/-rc\.\d+$/, '');
|
||||
} catch {
|
||||
version = tag.replace(/^v/, '');
|
||||
} catch {
|
||||
// local untagged build
|
||||
}
|
||||
}
|
||||
conf.version = version;
|
||||
writeFileSync(resolve(root, 'src-tauri/tauri.release.json'), JSON.stringify(conf, null, 2));
|
||||
|
||||
@@ -6,8 +6,11 @@
|
||||
"scripts": {
|
||||
"dev": "tauri dev",
|
||||
"bundle": "node inject-version.mjs && tauri build --config src-tauri/tauri.release.json",
|
||||
"bundle:linux": "node inject-version.mjs && tauri build --config src-tauri/tauri.release.json --bundles deb",
|
||||
"bundle:windows": "node inject-version.mjs && tauri build --config src-tauri/tauri.release.json --bundles nsis",
|
||||
"bundle:windows:cross": "node inject-version.mjs && tauri build --config src-tauri/tauri.release.json --runner cargo-xwin --target x86_64-pc-windows-msvc --bundles nsis",
|
||||
"tauri": "tauri",
|
||||
"icons": "tauri icon ../web/public/favicon.svg"
|
||||
"icons": "node ../../scripts/generate-icons.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.9.0"
|
||||
|
||||
@@ -20,6 +20,7 @@ tauri-plugin-window-state = "2"
|
||||
tauri-plugin-single-instance = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
tokio = { version = "1", features = ["net", "sync", "time"] }
|
||||
axum = "0.8"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream", "json"] }
|
||||
@@ -38,5 +39,7 @@ keyring = { version = "3.6.3", features = ["apple-native"] }
|
||||
|
||||
[profile.release]
|
||||
strip = true
|
||||
lto = "thin"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
opt-level = "s"
|
||||
panic = "abort"
|
||||
|
Before Width: | Height: | Size: 6.5 KiB After Width: | Height: | Size: 8.0 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 31 KiB |
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 46 KiB |
@@ -1,6 +1,7 @@
|
||||
mod media;
|
||||
mod proxy;
|
||||
mod store;
|
||||
mod update;
|
||||
|
||||
use media::Media;
|
||||
use proxy::Proxy;
|
||||
@@ -110,6 +111,7 @@ pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _, _| show_main(app)))
|
||||
.plugin(tauri_plugin_window_state::Builder::default().build())
|
||||
.manage(update::Updater::default())
|
||||
.setup(|app| {
|
||||
let saved = store::load_server(app.handle())?;
|
||||
let proxy = tauri::async_runtime::block_on(Proxy::start(saved.clone())).map_err(|e| e.to_string())?;
|
||||
@@ -150,7 +152,8 @@ pub fn run() {
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
bootstrap, set_server, clear_server, token_get, token_set, token_clear, user_get, user_set, user_clear, media_set
|
||||
bootstrap, set_server, clear_server, token_get, token_set, token_clear, user_get, user_set, user_clear, media_set,
|
||||
update::update_check, update::update_install
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("desktop app failed to start");
|
||||
|
||||
@@ -86,7 +86,7 @@ fn cors(headers: &mut HeaderMap, origin: Option<&str>) {
|
||||
}
|
||||
headers.insert("access-control-allow-methods", HeaderValue::from_static("GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS"));
|
||||
headers.insert("access-control-allow-headers", HeaderValue::from_static("authorization, content-type, range, tus-resumable, upload-length, upload-offset, upload-metadata, upload-defer-length, x-requested-with"));
|
||||
headers.insert("access-control-expose-headers", HeaderValue::from_static("content-range, accept-ranges, location, upload-offset, upload-length, tus-resumable, retry-after"));
|
||||
headers.insert("access-control-expose-headers", HeaderValue::from_static("content-range, accept-ranges, location, upload-offset, upload-length, tus-resumable, retry-after, x-pipu-transport-error"));
|
||||
}
|
||||
|
||||
async fn forward(State(proxy): State<Proxy>, request: Request) -> Response {
|
||||
@@ -110,7 +110,11 @@ async fn forward(State(proxy): State<Proxy>, request: Request) -> Response {
|
||||
} else {
|
||||
match transfer(&proxy, request, tail).await {
|
||||
Ok(response) => response,
|
||||
Err(_) => (StatusCode::BAD_GATEWAY, "Server unavailable").into_response(),
|
||||
Err(_) => {
|
||||
let mut response = (StatusCode::BAD_GATEWAY, "Server unavailable").into_response();
|
||||
response.headers_mut().insert("x-pipu-transport-error", HeaderValue::from_static("1"));
|
||||
response
|
||||
},
|
||||
}
|
||||
};
|
||||
cors(response.headers_mut(), origin.as_deref());
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Server-proxied releases: never accept installer paths or commands from the UI.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{io::Write, path::Path, time::Duration};
|
||||
use tauri::{AppHandle, Emitter, Manager, State};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize)]
|
||||
pub struct Build {
|
||||
client: String,
|
||||
version: String,
|
||||
filename: String,
|
||||
size: u64,
|
||||
sha256: Option<String>,
|
||||
download_url: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Catalog { version: String, notes_md: String, clients: Vec<Build> }
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct Release { build: Build, notes: String }
|
||||
#[derive(Default)]
|
||||
pub struct Updater { release: Mutex<Option<(String, Release)>> }
|
||||
|
||||
fn client() -> &'static str {
|
||||
if cfg!(target_os = "windows") { "windows" }
|
||||
else if cfg!(target_os = "macos") { "macos" } else { "linux" }
|
||||
}
|
||||
|
||||
fn version_code(raw: &str) -> Option<u64> {
|
||||
let (base, rc) = raw.trim_start_matches('v').split_once("-rc.").map_or((raw.trim_start_matches('v'), "99"), |v| v);
|
||||
let parts: Vec<u64> = base.split('.').map(str::parse).collect::<Result<_, _>>().ok()?;
|
||||
let rc: u64 = rc.parse().ok()?;
|
||||
if parts.len() != 3 || parts[0] > 1_000_000 || parts[1] > 99 || parts[2] > 99 || rc > 99 { return None; }
|
||||
Some(parts[0] * 1_000_000 + parts[1] * 10_000 + parts[2] * 100 + rc)
|
||||
}
|
||||
|
||||
fn http() -> Result<reqwest::Client, String> {
|
||||
reqwest::Client::builder().redirect(reqwest::redirect::Policy::none())
|
||||
.connect_timeout(Duration::from_secs(10)).read_timeout(Duration::from_secs(60))
|
||||
.build().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn update_check(app: AppHandle, updater: State<'_, Updater>) -> Result<Option<Release>, String> {
|
||||
let mut saved = updater.release.lock().await;
|
||||
*saved = None;
|
||||
let server = crate::store::load_server(&app)?.ok_or("No server selected")?;
|
||||
let catalog: Catalog = http()?.get(format!("{server}/api/v1/app/clients")).send().await
|
||||
.map_err(|e| e.to_string())?.error_for_status().map_err(|e| e.to_string())?
|
||||
.json().await.map_err(|e| e.to_string())?;
|
||||
let Some(build) = catalog.clients.into_iter().find(|b| b.client == client()) else { return Ok(None); };
|
||||
let current = version_code(&app.package_info().version.to_string()).ok_or("Invalid installed version")?;
|
||||
if version_code(&build.version).ok_or("Invalid release version")? <= current { return Ok(None); }
|
||||
let notes = if build.version == catalog.version { catalog.notes_md } else { String::new() };
|
||||
let release = Release { build, notes };
|
||||
validate_build(&release.build)?;
|
||||
*saved = Some((server, release.clone()));
|
||||
Ok(Some(release))
|
||||
}
|
||||
|
||||
fn validate_build(build: &Build) -> Result<(), String> {
|
||||
let safe_name = !build.filename.is_empty() && build.filename.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b));
|
||||
let extension = Path::new(&build.filename).extension().and_then(|s| s.to_str()).unwrap_or("");
|
||||
let supported = match client() { "windows" => extension == "exe" || extension == "msi", "linux" => extension == "deb" || extension == "rpm", _ => extension == "dmg" };
|
||||
let checksum = build.sha256.as_deref().is_some_and(|s| s.len() == 64 && s.bytes().all(|c| c.is_ascii_hexdigit()));
|
||||
if !safe_name || !supported || !checksum || build.size == 0 || build.size > 1024 * 1024 * 1024 { return Err("Unsupported installer or missing checksum".into()); }
|
||||
// Restrict to the existing, public Pipu client-file route; no arbitrary URL from a release.
|
||||
if build.download_url != format!("/api/v1/app/download/{}/{}", client(), build.version) {
|
||||
return Err("Invalid installer URL".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn update_install(app: AppHandle, updater: State<'_, Updater>) -> Result<(), String> {
|
||||
let saved = updater.release.lock().await;
|
||||
let (server, release) = saved.as_ref().ok_or("Check for an update first")?;
|
||||
if crate::store::load_server(&app)?.as_ref() != Some(server) { return Err("Server changed".into()); }
|
||||
let build = &release.build;
|
||||
validate_build(build)?;
|
||||
let dir = app.path().app_cache_dir().map_err(|e| e.to_string())?.join("updates");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
let path = dir.join(&build.filename);
|
||||
let part = dir.join(format!("{}.part", uuid::Uuid::new_v4()));
|
||||
let result = async {
|
||||
let mut response = http()?.get(format!("{server}{}", build.download_url)).send().await
|
||||
.map_err(|e| e.to_string())?.error_for_status().map_err(|e| e.to_string())?;
|
||||
let mut file = std::fs::File::create(&part).map_err(|e| e.to_string())?;
|
||||
let mut hash = Sha256::new();
|
||||
let mut bytes = 0u64;
|
||||
while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
|
||||
bytes += chunk.len() as u64;
|
||||
if bytes > build.size { return Err("Installer exceeds expected size".to_string()); }
|
||||
hash.update(&chunk);
|
||||
file.write_all(&chunk).map_err(|e| e.to_string())?;
|
||||
let _ = app.emit("update-progress", (bytes as f64 / build.size as f64).to_string());
|
||||
}
|
||||
if bytes != build.size || format!("{:x}", hash.finalize()) != build.sha256.as_ref().unwrap().to_lowercase() { return Err("Installer checksum mismatch".into()); }
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
drop(file);
|
||||
if path.exists() { std::fs::remove_file(&path).map_err(|e| e.to_string())?; }
|
||||
std::fs::rename(&part, &path).map_err(|e| e.to_string())?;
|
||||
launch(&path)?;
|
||||
Ok(())
|
||||
}.await;
|
||||
let _ = std::fs::remove_file(&part);
|
||||
result
|
||||
}
|
||||
|
||||
fn launch(path: &Path) -> Result<(), String> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
let mut command = if path.extension().and_then(|s| s.to_str()) == Some("msi") {
|
||||
let mut cmd = std::process::Command::new("msiexec.exe"); cmd.arg("/i").arg(path); cmd
|
||||
} else { std::process::Command::new(path) };
|
||||
command.creation_flags(0x08000000).spawn().map_err(|e| e.to_string())?;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{ std::process::Command::new("xdg-open").arg(path).spawn().map_err(|e| e.to_string())?; }
|
||||
#[cfg(target_os = "macos")]
|
||||
{ std::process::Command::new("open").arg(path).spawn().map_err(|e| e.to_string())?; }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn release_order() {
|
||||
assert!(version_code("1.7.2") > version_code("1.7.2-rc.3"));
|
||||
assert!(version_code("1.8.0-rc.1") > version_code("1.7.99"));
|
||||
assert_eq!(version_code("1.7.1"), Some(1070199));
|
||||
assert_eq!(version_code("1.7.100"), None);
|
||||
assert_eq!(version_code("1.7.1;cmd"), None);
|
||||
}
|
||||
#[test]
|
||||
fn installer_is_restricted_to_verified_server_asset() {
|
||||
let extension = match client() { "windows" => "exe", "linux" => "deb", _ => "dmg" };
|
||||
let mut build = Build { client: client().into(), version: "1.8.0".into(), filename: format!("pipu-1.8.0.{extension}"), size: 42,
|
||||
sha256: Some("a".repeat(64)), download_url: format!("/api/v1/app/download/{}/1.8.0", client()) };
|
||||
assert!(validate_build(&build).is_ok());
|
||||
build.download_url = "https://other.example/installer.exe".into();
|
||||
assert!(validate_build(&build).is_err());
|
||||
build.download_url = format!("/api/v1/app/download/{}/1.8.0", client());
|
||||
build.filename = "../installer.exe".into();
|
||||
assert!(validate_build(&build).is_err());
|
||||
build.filename = format!("pipu.{extension}");
|
||||
build.sha256 = None;
|
||||
assert!(validate_build(&build).is_err());
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
"icon": ["icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.ico", "icons/icon.icns"],
|
||||
"linux": {
|
||||
"deb": { "depends": ["libwebkit2gtk-4.1-0", "libayatana-appindicator3-1", "libsecret-1-0", "gstreamer1.0-plugins-good", "gstreamer1.0-plugins-bad", "gstreamer1.0-libav"] },
|
||||
"appimage": { "bundleMediaFramework": true }
|
||||
"appimage": { "bundleMediaFramework": false }
|
||||
},
|
||||
"windows": { "nsis": { "installMode": "currentUser", "languages": ["English", "Russian"], "displayLanguageSelector": true } }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Android
|
||||
|
||||
- `src/player/controller.ts` — фасад и зеркало native-очереди; `service.ts` — фоновые события. Владельцем воспроизводимой очереди остаётся TrackPlayer.
|
||||
- Общая политика волны — `packages/core/src`; офлайн-адаптация — `src/player/offlineWave.ts`, `src/offline`.
|
||||
- Сессия/настройки — `src/lib`; маршруты — `src/app`. Сохраняй работу при выгруженном UI и изоляцию офлайн-данных по пользователю/серверу.
|
||||
- `pnpm --filter @pipu/mobile typecheck`, `pnpm --filter @pipu/mobile test`.
|
||||
- Изменения native playback требуют проверки на устройстве: background, смена трека, offline→online. Unit-тесты не заменяют эту проверку.
|
||||
@@ -9,6 +9,7 @@ export default ({ config }: ConfigContext): ExpoConfig => ({
|
||||
name: 'Pipu Music',
|
||||
slug: 'pipu-music',
|
||||
scheme: 'pipu',
|
||||
icon: './assets/icon.png',
|
||||
version,
|
||||
orientation: 'portrait',
|
||||
userInterfaceStyle: 'automatic',
|
||||
@@ -17,6 +18,11 @@ export default ({ config }: ConfigContext): ExpoConfig => ({
|
||||
newArchEnabled: false,
|
||||
backgroundColor: '#05070D',
|
||||
android: {
|
||||
adaptiveIcon: {
|
||||
foregroundImage: './assets/adaptive-icon.png',
|
||||
monochromeImage: './assets/monochrome-icon.png',
|
||||
backgroundColor: '#05070D',
|
||||
},
|
||||
package: 'app.pipu.music',
|
||||
versionCode,
|
||||
edgeToEdgeEnabled: true,
|
||||
|
||||
|
After Width: | Height: | Size: 71 KiB |
|
After Width: | Height: | Size: 111 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
@@ -9,6 +9,7 @@ import { player } from '../../player/controller';
|
||||
import { usePlayerState } from '../../player/hooks';
|
||||
import { useColors } from '../../theme';
|
||||
import { ErrorBox, Icon, Screen, useErrorText, type IconName } from '../../ui/kit';
|
||||
import { OnboardingGate } from '../../ui/Onboarding';
|
||||
import { WaveOrb } from '../../ui/wave/WaveOrb';
|
||||
|
||||
/** Имена из /wave/options (Material Symbols) → MaterialIcons. */
|
||||
@@ -22,6 +23,10 @@ function iconFor(name: string): IconName {
|
||||
* На Android спектр недоступен, поэтому пульс берётся из BPM и energy трека (docs/mobile.md).
|
||||
*/
|
||||
export default function HomeScreen() {
|
||||
return <OnboardingGate><WaveHome /></OnboardingGate>;
|
||||
}
|
||||
|
||||
function WaveHome() {
|
||||
const colors = useColors();
|
||||
const { t } = useTranslation();
|
||||
const tr = t as unknown as (k: string) => string;
|
||||
|
||||
@@ -15,6 +15,7 @@ import { player } from '../../player/controller';
|
||||
import { radius, useColors } from '../../theme';
|
||||
import { Button, H1, Icon, Muted, Screen, Segmented } from '../../ui/kit';
|
||||
import { useDownloads } from '../../ui/downloads';
|
||||
import { RecommendationSettings } from '../../ui/Onboarding';
|
||||
import { PasswordSheet, QualitySheet, useQualityPrefs } from '../../ui/settings';
|
||||
import { useUpdateState } from '../../ui/UpdateDialog';
|
||||
|
||||
@@ -74,6 +75,8 @@ export default function ProfileScreen() {
|
||||
@{user.username} · {t(`roles.${user.role}`)}
|
||||
</Muted>
|
||||
|
||||
<RecommendationSettings />
|
||||
|
||||
<Section>
|
||||
<Row label={t('language.label')}>
|
||||
<Segmented<Locale>
|
||||
|
||||
@@ -91,6 +91,12 @@ export default function PlayerScreen() {
|
||||
<Text numberOfLines={1} style={{ color: colors.text2, fontSize: 15 }}>
|
||||
{track.artists.map((a) => a.name).join(', ')}
|
||||
</Text>
|
||||
<Pressable onPress={() => router.push({ pathname: '/playlists', params: { track: track.id } })}
|
||||
accessibilityRole="button" accessibilityLabel={t('playlists.add')}
|
||||
style={{ flexDirection: 'row', alignItems: 'center', gap: 8, minHeight: 44, alignSelf: 'flex-start' }}>
|
||||
<Icon name="playlist-add" size={24} color={colors.text2} />
|
||||
<Text style={{ color: colors.text2 }}>{t('playlists.add')}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View style={{ gap: 6 }}>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { playlistShareUrl, unwrap } from '@pipu/core';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useLocalSearchParams, useRouter } from 'expo-router';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Alert, FlatList, Modal, ScrollView, View } from 'react-native';
|
||||
import { useSession, useUser } from '../lib/session';
|
||||
import { Alert, FlatList, Modal, ScrollView, Share, View } from 'react-native';
|
||||
import { useSession, useSessionCtx, useUser } from '../lib/session';
|
||||
import { player } from '../player/controller';
|
||||
import { Button, ErrorBox, Field, H1, Muted, Screen, TrackRow, formatDuration, useErrorText } from '../ui/kit';
|
||||
|
||||
@@ -78,6 +78,7 @@ function Editor({ playlist, track, onClose, onSaved }: { playlist?: Playlist; tr
|
||||
|
||||
function Detail({ id }: { id: string }) {
|
||||
const session = useSession();
|
||||
const { server } = useSessionCtx();
|
||||
const user = useUser();
|
||||
const router = useRouter();
|
||||
const { t } = useTranslation();
|
||||
@@ -89,6 +90,15 @@ function Detail({ id }: { id: string }) {
|
||||
const key = ['m-playlists', user.id, id];
|
||||
const query = useQuery({ queryKey: key, queryFn: async () => unwrap(await session.client.GET('/api/v1/me/playlists/{id}', { params: { path: { id } } })) });
|
||||
const p = query.data;
|
||||
const sharing = useMutation({ mutationFn: async () => {
|
||||
if (!server || !p) throw new Error('Server unavailable');
|
||||
const token = unwrap(await session.client.POST('/api/v1/me/playlists/{id}/share', { params: { path: { id } } })).share_id;
|
||||
cache.setQueryData<Playlist>(key, current => current ? { ...current, share_id: token } : current);
|
||||
await Share.share({ title: p.name, message: playlistShareUrl(server, token) }, { dialogTitle: t('playlists.share') });
|
||||
} });
|
||||
const revoke = useMutation({ mutationFn: async () => unwrap(await session.client.DELETE('/api/v1/me/playlists/{id}/share', { params: { path: { id } } })),
|
||||
onSuccess: () => { cache.setQueryData<Playlist>(key, current => current ? { ...current, share_id: null } : current); } });
|
||||
|
||||
const save = useMutation({ mutationFn: async (ids: string[]) => unwrap(await session.client.PUT('/api/v1/me/playlists/{id}', { params: { path: { id } }, body: { ...input(p!), track_ids: ids } })),
|
||||
onSuccess: data => { cache.setQueryData(key, data); void cache.invalidateQueries({ queryKey: ['m-playlists'] }); },
|
||||
onError: () => { void cache.invalidateQueries({ queryKey: ['m-playlists'] }); } });
|
||||
@@ -105,11 +115,14 @@ function Detail({ id }: { id: string }) {
|
||||
return <Screen><FlatList data={p?.tracks ?? []} keyExtractor={t => t.id} onRefresh={() => void query.refetch()} refreshing={query.isRefetching}
|
||||
ListHeaderComponent={<View style={{ padding:16,gap:12 }}>
|
||||
<Button title={t('playlists.title')} variant="ghost" onPress={() => router.back()} />
|
||||
<ErrorBox>{query.error || save.error || deletion.error || playError ? errorText(query.error ?? save.error ?? deletion.error ?? playError) : null}</ErrorBox>
|
||||
<ErrorBox>{query.error || save.error || deletion.error || playError || sharing.error || revoke.error ? errorText(query.error ?? save.error ?? deletion.error ?? playError ?? sharing.error ?? revoke.error) : null}</ErrorBox>
|
||||
{query.isPending && <Muted>{t('playlists.loading')}</Muted>}
|
||||
{p && <><H1>{p.name}</H1><Muted>{p.description}</Muted><Muted>{t('catalog.track_count',{count:p.track_count})} · {formatDuration(p.duration_ms)}</Muted>
|
||||
<Button title={t('collection.play_all')} disabled={!p.tracks.some(t => t.available)} onPress={() => play(false)} />
|
||||
<Button title={t('collection.shuffle')} variant="secondary" disabled={!p.tracks.some(t => t.available)} onPress={() => play(true)} />
|
||||
<Button title={t('playlists.share')} variant="secondary" busy={sharing.isPending} disabled={revoke.isPending} onPress={() => sharing.mutate()} />
|
||||
<Muted>{t('playlists.share_hint')}</Muted>
|
||||
{p.share_id && <Button title={t('playlists.revoke_share')} variant="ghost" busy={revoke.isPending} disabled={sharing.isPending} onPress={() => revoke.mutate()} />}
|
||||
<Button title={t('playlists.edit')} variant="secondary" disabled={save.isPending || deletion.isPending} onPress={() => setEdit(true)} />
|
||||
<Button title={t('playlists.manage')} variant="secondary" onPress={() => setManage(!manage)} />
|
||||
<Button title={t('playlists.delete')} variant="danger" disabled={save.isPending} busy={deletion.isPending} onPress={() => Alert.alert(t('playlists.delete'),t('playlists.delete_confirm',{name:p.name}),[
|
||||
|
||||
@@ -272,7 +272,7 @@ class Downloads {
|
||||
if (track.album.cover_url) {
|
||||
const cover = this.cover(track.album.id);
|
||||
const info = await FileSystem.getInfoAsync(cover);
|
||||
if (!info.exists) await FileSystem.downloadAsync(`${this.abs(track.album.cover_url)}&size=300`, cover).catch(() => undefined);
|
||||
if (!info.exists) await FileSystem.downloadAsync(sizedCover(this.abs(track.album.cover_url), 300), cover).catch(() => undefined);
|
||||
}
|
||||
const info = await FileSystem.getInfoAsync(this.file(id));
|
||||
await status('done', { progress: 1, bytes: info.exists ? info.size : 0 }, track);
|
||||
@@ -286,4 +286,9 @@ class Downloads {
|
||||
}
|
||||
}
|
||||
|
||||
/** Размер нужен только обложкам Pipu. Прямые ссылки Genius параметр size не принимают. */
|
||||
export function sizedCover(url: string, size: number): string {
|
||||
return url.includes('/api/v1/covers/') ? `${url}&size=${size}` : url;
|
||||
}
|
||||
|
||||
export const downloads = new Downloads();
|
||||
@@ -1,6 +1,11 @@
|
||||
import NetInfo from '@react-native-community/netinfo';
|
||||
import {
|
||||
EventBuffer,
|
||||
WaveCoordinator,
|
||||
EARLY_SKIP_MS,
|
||||
type WaveInfo,
|
||||
type WaveOutcome,
|
||||
type WaveFeedback,
|
||||
PlayAttempt,
|
||||
normalizeGain,
|
||||
unwrap,
|
||||
@@ -17,19 +22,14 @@ import TrackPlayer, {
|
||||
} from 'react-native-track-player';
|
||||
|
||||
import { playerCache, qualityPrefs, type Quality } from '../lib/prefs';
|
||||
import { downloads } from '../offline/downloads';
|
||||
import { downloads, sizedCover } from '../offline/downloads';
|
||||
import { PersistentEvents } from '../offline/events';
|
||||
import { offlineWave } from './offlineWave';
|
||||
import { eventId } from './eventId';
|
||||
|
||||
export { offlineWave };
|
||||
|
||||
export interface WaveInfo {
|
||||
sessionId: string;
|
||||
activity: string | null;
|
||||
mood: string | null;
|
||||
fallback: boolean;
|
||||
}
|
||||
export type { WaveInfo } from '@pipu/core';
|
||||
|
||||
export interface PlayerState {
|
||||
ready: boolean;
|
||||
@@ -44,10 +44,6 @@ export interface PlayerState {
|
||||
wave: WaveInfo | null;
|
||||
}
|
||||
|
||||
type WaveOutcome = 'complete' | 'skip' | 'skip_early' | 'like' | 'dislike';
|
||||
|
||||
const WAVE_REFILL_AT = 2;
|
||||
const EARLY_SKIP_MS = 30_000;
|
||||
const SAVE_EVERY_MS = 10_000;
|
||||
|
||||
const playable = (t: Track) => t.available && (!!t.stream_url || downloads.isDownloaded(t.id));
|
||||
@@ -84,8 +80,13 @@ class Controller {
|
||||
private attempt: PlayAttempt | null = null;
|
||||
private lastPositionMs = 0;
|
||||
private lastSave = 0;
|
||||
private waveFeedback: { track_id: string; outcome: WaveOutcome }[] = [];
|
||||
private waveLoading = false;
|
||||
private readonly wavePolicy = new WaveCoordinator({
|
||||
next: async (id: string, feedback: WaveFeedback[]) => unwrap(
|
||||
await this.session!.client.POST('/api/v1/wave/sessions/{id}/next', {
|
||||
params: { path: { id } }, body: { feedback },
|
||||
}),
|
||||
),
|
||||
});
|
||||
private neutralSwitch = false; // следующая смена трека — из-за нового контекста волны
|
||||
private setupDone: Promise<void> | null = null;
|
||||
private listeners = new Set<() => void>();
|
||||
@@ -224,15 +225,18 @@ class Controller {
|
||||
private async toRntp(tracks: Track[]): Promise<RntpTrack[]> {
|
||||
const q = await quality();
|
||||
// Скачанный трек играется из файла (и без сети), остальные — стримом по качеству сети.
|
||||
return tracks.map((t) => ({
|
||||
return tracks.map((t) => {
|
||||
const cover = absolute(this.server, t.album.cover_url);
|
||||
return {
|
||||
id: t.id,
|
||||
url: downloads.localTrack(t.id) ?? `${absolute(this.server, t.stream_url)}&q=${q}`,
|
||||
title: t.title,
|
||||
artist: t.artists.map((a) => a.name).join(', '),
|
||||
album: t.album.title,
|
||||
artwork: downloads.localCover(t) ?? (t.album.cover_url ? `${absolute(this.server, t.album.cover_url)}&size=300` : undefined),
|
||||
artwork: downloads.localCover(t) ?? (cover ? sizedCover(cover, 300) : undefined),
|
||||
duration: t.duration_ms / 1000,
|
||||
}));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async playList(tracks: Track[], index: number, context: PlayContext) {
|
||||
@@ -305,18 +309,22 @@ class Controller {
|
||||
if (!this.session) return;
|
||||
await this.setup();
|
||||
this.leaveWave();
|
||||
const version = this.wavePolicy.version;
|
||||
let res;
|
||||
try {
|
||||
res = unwrap(await this.session.client.POST('/api/v1/wave/sessions', { body: { activity, mood } }));
|
||||
} catch (e) {
|
||||
if (!this.wavePolicy.isCurrent(version)) return;
|
||||
// Нет связи с сервером — офлайн-волна из скачанного.
|
||||
const local = offlineWave(downloads.downloaded());
|
||||
if (!local.length) throw e;
|
||||
return this.playList(local, 0, { type: 'collection', id: 'downloads' });
|
||||
}
|
||||
if (!this.wavePolicy.isCurrent(version)) return;
|
||||
const tracks = res.tracks.filter(playable);
|
||||
if (!tracks.length) return;
|
||||
this.finishAttempt(this.lastPositionMs / 1000);
|
||||
this.wavePolicy.activate(res.session_id);
|
||||
this.update({
|
||||
queue: tracks, index: 0, track: tracks[0] ?? null, context: { type: 'wave', id: res.session_id },
|
||||
wave: { sessionId: res.session_id, activity: res.activity, mood: res.mood, fallback: res.fallback },
|
||||
@@ -329,13 +337,16 @@ class Controller {
|
||||
async setWaveContext(activity: string | null, mood: string | null) {
|
||||
const wave = this.state.wave;
|
||||
if (!wave || !this.session) return this.startWave(activity, mood);
|
||||
const version = this.wavePolicy.changeContext(wave.sessionId);
|
||||
const res = unwrap(
|
||||
await this.session.client.PATCH('/api/v1/wave/sessions/{id}', {
|
||||
params: { path: { id: wave.sessionId } },
|
||||
body: { activity, mood },
|
||||
}),
|
||||
);
|
||||
await this.replaceUpcoming(res.tracks);
|
||||
if (!this.wavePolicy.isCurrent(version)) return;
|
||||
await this.replaceUpcoming(res.tracks, () => this.wavePolicy.isCurrent(version));
|
||||
if (!this.wavePolicy.isCurrent(version)) return;
|
||||
this.update({ wave: { ...wave, activity: res.activity, mood: res.mood, fallback: res.fallback } });
|
||||
// Новый контекст звучит сразу; прерванный трек — не скип для волны (как в вебе).
|
||||
if (res.tracks.some(playable)) {
|
||||
@@ -348,8 +359,8 @@ class Controller {
|
||||
|
||||
private leaveWave() {
|
||||
const wave = this.state.wave;
|
||||
this.wavePolicy.activate(null);
|
||||
if (!wave) return;
|
||||
this.waveFeedback = [];
|
||||
this.update({ wave: null });
|
||||
void this.session?.client
|
||||
.DELETE('/api/v1/wave/sessions/{id}', { params: { path: { id: wave.sessionId } } })
|
||||
@@ -357,46 +368,36 @@ class Controller {
|
||||
}
|
||||
|
||||
private noteWave(trackId: string, outcome: WaveOutcome) {
|
||||
if (this.state.wave) this.waveFeedback.push({ track_id: trackId, outcome });
|
||||
this.wavePolicy.note(trackId, outcome);
|
||||
}
|
||||
|
||||
/** Убрать не начатые треки и поставить новые (после реакции или смены контекста). */
|
||||
private async replaceUpcoming(tracks: Track[]) {
|
||||
private async replaceUpcoming(tracks: Track[], current: () => boolean = () => true) {
|
||||
const keep = this.state.queue.slice(0, this.state.index + 1);
|
||||
await TrackPlayer.removeUpcomingTracks();
|
||||
const add = tracks.filter(playable);
|
||||
await TrackPlayer.add(await this.toRntp(add));
|
||||
this.update({ queue: [...keep, ...add] });
|
||||
const native = await this.toRntp(add);
|
||||
if (!current()) return;
|
||||
await TrackPlayer.removeUpcomingTracks();
|
||||
if (!current()) return;
|
||||
await TrackPlayer.add(native);
|
||||
if (current()) this.update({ queue: [...keep, ...add] });
|
||||
}
|
||||
|
||||
private async refillWave(refresh = false) {
|
||||
const wave = this.state.wave;
|
||||
if (!wave || !this.session || this.waveLoading) return;
|
||||
if (!this.session) return;
|
||||
const remaining = this.state.queue.length - this.state.index - 1;
|
||||
if (!refresh && remaining > WAVE_REFILL_AT) return;
|
||||
this.waveLoading = true;
|
||||
const feedback = this.waveFeedback;
|
||||
this.waveFeedback = [];
|
||||
try {
|
||||
const res = unwrap(
|
||||
await this.session.client.POST('/api/v1/wave/sessions/{id}/next', {
|
||||
params: { path: { id: wave.sessionId } },
|
||||
body: { feedback },
|
||||
}),
|
||||
);
|
||||
if (this.state.wave?.sessionId !== wave.sessionId) return;
|
||||
if (refresh) await this.replaceUpcoming(res.tracks);
|
||||
await this.wavePolicy.refill(remaining, refresh, async (res, current) => {
|
||||
if (refresh) await this.replaceUpcoming(res.tracks, current);
|
||||
else {
|
||||
const add = res.tracks.filter(playable);
|
||||
await TrackPlayer.add(await this.toRntp(add));
|
||||
const native = await this.toRntp(add);
|
||||
if (!current()) return;
|
||||
await TrackPlayer.add(native);
|
||||
if (!current()) return;
|
||||
this.update({ queue: [...this.state.queue, ...add] });
|
||||
}
|
||||
this.update({ wave: { ...wave, fallback: res.fallback } });
|
||||
} catch {
|
||||
this.waveFeedback = [...feedback, ...this.waveFeedback];
|
||||
} finally {
|
||||
this.waveLoading = false;
|
||||
}
|
||||
if (current()) this.update({ wave: { ...this.state.wave!, fallback: res.fallback } });
|
||||
});
|
||||
}
|
||||
|
||||
// --- состояние ---
|
||||
@@ -440,6 +441,7 @@ class Controller {
|
||||
}
|
||||
|
||||
async reset() {
|
||||
this.wavePolicy.activate(null);
|
||||
this.attempt = null;
|
||||
this.update({ queue: [], track: null, index: 0, playing: false, positionMs: 0, wave: null, context: null });
|
||||
if (this.setupDone) await TrackPlayer.reset().catch(() => undefined);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { AGE_GROUPS, GENDERS, unwrap } from '@pipu/core';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ActivityIndicator, Pressable, ScrollView, Text, View } from 'react-native';
|
||||
|
||||
import { useSession, useSessionCtx, useUser } from '../lib/session';
|
||||
import { useColors } from '../theme';
|
||||
import { Button, ErrorBox, H1, Muted, Screen, useErrorText } from './kit';
|
||||
|
||||
type Options = components['schemas']['Onboarding'];
|
||||
type Choice = components['schemas']['OnboardingChoice'];
|
||||
|
||||
function useOnboarding() {
|
||||
const session = useSession();
|
||||
const user = useUser();
|
||||
const { server } = useSessionCtx();
|
||||
return useQuery({ queryKey: ['onboarding', server, user.id],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/onboarding')),
|
||||
staleTime: 0, refetchInterval: 30_000 });
|
||||
}
|
||||
|
||||
export function OnboardingGate({ children }: { children: ReactNode }) {
|
||||
const query = useOnboarding();
|
||||
const client = useQueryClient();
|
||||
if (query.isPending) return <Screen><ActivityIndicator /></Screen>;
|
||||
if (!query.data?.required) return <>{children}</>;
|
||||
return <Screen><ScrollView contentContainerStyle={{ padding: 16 }}>
|
||||
<Onboarding options={query.data} onDone={() => void client.invalidateQueries({ queryKey: ['onboarding'] })} />
|
||||
</ScrollView></Screen>;
|
||||
}
|
||||
|
||||
export function RecommendationSettings() {
|
||||
const { t } = useTranslation();
|
||||
const query = useOnboarding();
|
||||
const client = useQueryClient();
|
||||
const [editing, setEditing] = useState(false);
|
||||
const errorText = useErrorText();
|
||||
return <View>
|
||||
{editing && query.data ? <Onboarding key={JSON.stringify(query.data.choice)} options={query.data} editing onDone={() => {
|
||||
setEditing(false); void client.invalidateQueries({ queryKey: ['onboarding'] });
|
||||
}} /> : <Button title={t('onboarding.edit')} variant="secondary" busy={query.isFetching} onPress={() => { void query.refetch().then((result) => { if (result.data && !result.error) setEditing(true); }); }} />}
|
||||
<ErrorBox>{query.error ? errorText(query.error) : null}</ErrorBox>
|
||||
</View>;
|
||||
}
|
||||
|
||||
function Onboarding({ options, onDone, editing = false }: { options: Options; onDone: () => void; editing?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const session = useSession();
|
||||
const errorText = useErrorText();
|
||||
const [choice, setChoice] = useState<Choice>(options.choice ?? { artist_ids: [], genres: [], gender: null, age_group: null });
|
||||
const save = useMutation({ mutationFn: async (skip: boolean) => unwrap(await session.client.PUT('/api/v1/me/onboarding', {
|
||||
body: skip ? { artist_ids: [], genres: [], gender: null, age_group: null } : choice,
|
||||
})), onSuccess: onDone });
|
||||
const toggle = (key: 'artist_ids' | 'genres', value: string) => setChoice((old) => ({ ...old,
|
||||
[key]: old[key].includes(value) ? old[key].filter((x) => x !== value) : [...old[key], value],
|
||||
}));
|
||||
return <View style={{ gap: 20 }}>
|
||||
<H1>{t('onboarding.title')}</H1><Muted>{t('onboarding.subtitle')}</Muted>
|
||||
<Choices title={t('onboarding.gender')} items={[{ value: '', label: t('onboarding.unspecified') }, ...GENDERS.map((g) => ({ value: g, label: t(`onboarding.genders.${g}`) }))]}
|
||||
selected={[choice.gender ?? '']} onPick={(v) => setChoice((old) => ({ ...old, gender: (v || null) as Choice['gender'] }))} />
|
||||
<Choices title={t('onboarding.age_group')} items={[{ value: '', label: t('onboarding.unspecified') }, ...AGE_GROUPS.map((g) => ({ value: g, label: t(`onboarding.ages.${g}`) }))]}
|
||||
selected={[choice.age_group ?? '']} onPick={(v) => setChoice((old) => ({ ...old, age_group: (v || null) as Choice['age_group'] }))} />
|
||||
<Muted>{t('onboarding.age_hint')}</Muted>
|
||||
<Choices title={t('onboarding.artists')} items={options.artists.map((a) => ({ value: a.id, label: a.name }))} selected={choice.artist_ids} onPick={(v) => toggle('artist_ids', v)} />
|
||||
<Choices title={t('onboarding.genres')} items={options.genres.map((g) => ({ value: g.name, label: g.name }))} selected={choice.genres} onPick={(v) => toggle('genres', v)} />
|
||||
<ErrorBox>{save.error ? errorText(save.error) : null}</ErrorBox>
|
||||
<Button title={t(editing ? 'settings.save' : 'onboarding.done')} busy={save.isPending} onPress={() => save.mutate(false)} />
|
||||
<Button title={t(editing ? 'form.cancel' : 'onboarding.skip')} variant="ghost" disabled={save.isPending} onPress={() => editing ? onDone() : save.mutate(true)} />
|
||||
</View>;
|
||||
}
|
||||
|
||||
function Choices({ title, items, selected, onPick }: { title: string; items: { value: string; label: string }[]; selected: string[]; onPick: (value: string) => void }) {
|
||||
const colors = useColors();
|
||||
return <View style={{ gap: 10 }}><Text style={{ color: colors.text, fontWeight: '600' }}>{title}</Text>
|
||||
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 8 }}>{items.map((item) => {
|
||||
const on = selected.includes(item.value);
|
||||
return <Pressable key={item.value} accessibilityRole="button" accessibilityState={{ selected: on }} onPress={() => onPick(item.value)}
|
||||
style={{ padding: 12, borderRadius: 20, backgroundColor: on ? colors['accent-fill'] : colors.surface2 }}>
|
||||
<Text style={{ color: on ? '#fff' : colors.text }}>{item.label}</Text>
|
||||
</Pressable>;
|
||||
})}</View>
|
||||
</View>;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useSyncExternalStore } from 'react';
|
||||
import { releaseNotesText } from '@pipu/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AppState, Modal, Pressable, ScrollView, Text, View } from 'react-native';
|
||||
|
||||
@@ -10,7 +11,6 @@ import { Button } from './kit';
|
||||
export function useUpdateState() {
|
||||
return useSyncExternalStore(updater.subscribe, () => updater.state);
|
||||
}
|
||||
|
||||
/** Проверяет обновления при запуске и возврате в приложение; показывает диалог с «Что нового». */
|
||||
export function UpdateDialog() {
|
||||
const colors = useColors();
|
||||
@@ -32,6 +32,7 @@ export function UpdateDialog() {
|
||||
|
||||
const { release, required } = st;
|
||||
const busy = st.status === 'downloading' || st.status === 'verifying';
|
||||
const notes = releaseNotesText(release.notes_md);
|
||||
const action = () => void updater.downloadAndInstall(session, server ?? '');
|
||||
|
||||
return (
|
||||
@@ -57,9 +58,9 @@ export function UpdateDialog() {
|
||||
{t('mobile.update_title', { version: release.version })}
|
||||
</Text>
|
||||
{required && <Text style={{ color: colors.danger }}>{t('mobile.update_required')}</Text>}
|
||||
{release.notes_md.trim() !== '' && (
|
||||
<ScrollView style={{ maxHeight: 240 }}>
|
||||
<Text style={{ color: colors.text2, lineHeight: 20 }}>{plainNotes(release.notes_md)}</Text>
|
||||
{notes !== '' && (
|
||||
<ScrollView style={{ maxHeight: 240, flexShrink: 1 }}>
|
||||
<Text style={{ color: colors.text2, lineHeight: 20 }}>{notes}</Text>
|
||||
</ScrollView>
|
||||
)}
|
||||
<Text style={{ color: colors.text3, fontSize: 12 }}>
|
||||
@@ -115,13 +116,3 @@ export function UpdateDialog() {
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/** Заметки релиза — Markdown; в диалоге показываем текстом без разметки заголовков и выделения. */
|
||||
function plainNotes(md: string): string {
|
||||
return md
|
||||
.replace(/^#{1,6}\s*/gm, '')
|
||||
.replace(/\*\*(.+?)\*\*/g, '$1')
|
||||
.replace(/^\s*[-*]\s+/gm, '• ')
|
||||
.replace(/\[(.+?)\]\(.+?\)/g, '$1')
|
||||
.trim();
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
|
||||
import { useSessionCtx } from '../lib/session';
|
||||
import { downloads } from '../offline/downloads';
|
||||
import { downloads, sizedCover } from '../offline/downloads';
|
||||
import { absolute } from '../player/controller';
|
||||
import { radius, useColors, type Colors } from '../theme';
|
||||
|
||||
@@ -161,7 +161,7 @@ export function Cover({
|
||||
const px = size * 2 <= 64 ? 64 : size * 2 <= 300 ? 300 : 1200;
|
||||
// У скачанных альбомов обложка 300 px лежит на устройстве — работает и без сети.
|
||||
const local = useSyncExternalStore(downloads.subscribe, () => (px <= 300 ? downloads.localAlbumCover(album.id) : undefined));
|
||||
const uri = local ?? (remote ? `${remote}&size=${px}` : undefined);
|
||||
const uri = local ?? (remote ? sizedCover(remote, px) : undefined);
|
||||
const bg = album.cover_colors?.[0] ?? colors.surface3;
|
||||
return (
|
||||
<View style={{ width: size, height: size, borderRadius: round ? size / 2 : 8, backgroundColor: bg, overflow: 'hidden', alignItems: 'center', justifyContent: 'center' }}>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { initialWaveState, step, WAVE_COLORS, waveScale, type WaveState } from '@pipu/core';
|
||||
import { initialWaveState, step, wavePalette, waveScale, type WaveState } from '@pipu/core';
|
||||
import { Canvas, createPicture, Picture } from '@shopify/react-native-skia';
|
||||
import { useFocusEffect } from 'expo-router';
|
||||
import { useCallback, useEffect, useState, type ReactNode } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import { AppState, Pressable, View } from 'react-native';
|
||||
import Animated, { useAnimatedStyle, useDerivedValue, useFrameCallback, useReducedMotion, useSharedValue } from 'react-native-reanimated';
|
||||
|
||||
@@ -36,7 +36,7 @@ export function WaveOrb({ variant, playing, bpm = 100, energy = 0.6, colors, siz
|
||||
}, []),
|
||||
);
|
||||
const [foreground, setForeground] = useState(AppState.currentState === 'active');
|
||||
const palette = (colors?.length === 3 ? colors : WAVE_COLORS) as [string, string, string];
|
||||
const palette = useMemo(() => wavePalette(colors), [colors]);
|
||||
|
||||
const props = useSharedValue({ variant, playing, bpm, energy, colors: palette, dark, reduced });
|
||||
const state = useSharedValue<WaveState>(initialWaveState(size));
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { AuthSession, Track } from '@pipu/core';
|
||||
import { beforeEach, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@react-native-community/netinfo', () => ({ default: {
|
||||
fetch: async () => ({ type: 'wifi' }), addEventListener: () => () => {},
|
||||
} }));
|
||||
vi.mock('../src/lib/prefs', () => ({
|
||||
qualityPrefs: { load: async () => ({ wifi: 'high', cellular: 'medium' }) },
|
||||
playerCache: { clearIfRequested: async () => {} },
|
||||
}));
|
||||
vi.mock('../src/offline/events', () => ({ PersistentEvents: class {} }));
|
||||
vi.mock('../src/offline/downloads', () => ({
|
||||
downloads: { isDownloaded: () => false, localTrack: () => undefined, localCover: () => undefined, downloaded: () => [] },
|
||||
sizedCover: (s: string) => s,
|
||||
}));
|
||||
vi.mock('react-native-track-player', () => ({
|
||||
default: {
|
||||
isServiceRunning: async () => true, setupPlayer: async () => {}, updateOptions: async () => {},
|
||||
addEventListener: vi.fn(), reset: vi.fn().mockResolvedValue(undefined),
|
||||
add: vi.fn().mockResolvedValue(undefined), play: vi.fn().mockResolvedValue(undefined),
|
||||
skip: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
AppKilledPlaybackBehavior: {}, Capability: {}, Event: {}, State: {},
|
||||
}));
|
||||
|
||||
function track(id: string): Track {
|
||||
return { id, title: id, duration_ms: 1000, artists: [],
|
||||
album: { id: 'album', title: 'Album', year: null, cover_url: null, cover_colors: [] },
|
||||
genres: [], disc_no: 1, track_no: 1, available: true, stream_url: `/s/${id}?sig=x`, reaction: null, features: null };
|
||||
}
|
||||
function deferred<T>() {
|
||||
let resolve!: (v: T) => void;
|
||||
const promise = new Promise<T>((yes) => { resolve = yes; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
const reply = (id: string) => ({ data: { session_id: id, activity: null, mood: null, fallback: false, tracks: [track(id)] }, response: new Response() });
|
||||
|
||||
beforeEach(() => { vi.resetModules(); vi.clearAllMocks(); });
|
||||
|
||||
it('ignores a wave creation response after the player is reset', async () => {
|
||||
const { player } = await import('../src/player/controller');
|
||||
const native = (await import('react-native-track-player')).default;
|
||||
const pending = deferred<ReturnType<typeof reply>>();
|
||||
const post = vi.fn().mockReturnValue(pending.promise);
|
||||
player.attach({ client: { POST: post } } as unknown as AuthSession, 'http://localhost', null);
|
||||
const start = player.startWave(null, null);
|
||||
await vi.waitFor(() => expect(post).toHaveBeenCalled());
|
||||
await player.reset();
|
||||
pending.resolve(reply('old'));
|
||||
await start;
|
||||
expect(player.getState().wave).toBeNull();
|
||||
expect(player.getState().queue).toEqual([]);
|
||||
expect(native.add).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not let a late context response replace a manually selected playlist', async () => {
|
||||
const { player } = await import('../src/player/controller');
|
||||
const pending = deferred<ReturnType<typeof reply>>();
|
||||
const session = { client: {
|
||||
POST: vi.fn().mockResolvedValue(reply('wave')),
|
||||
PATCH: vi.fn().mockReturnValue(pending.promise), DELETE: vi.fn().mockResolvedValue({}),
|
||||
} };
|
||||
player.attach(session as unknown as AuthSession, 'http://localhost', null);
|
||||
await player.startWave(null, null);
|
||||
const change = player.setWaveContext('focus', null);
|
||||
await player.playList([track('manual')], 0, { type: 'album', id: 'album' });
|
||||
pending.resolve(reply('stale'));
|
||||
await change;
|
||||
expect(player.getState().wave).toBeNull();
|
||||
expect(player.getState().queue.map((t) => t.id)).toEqual(['manual']);
|
||||
expect(player.getState().context?.type).toBe('album');
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
# Web и desktop UI
|
||||
|
||||
- Маршруты: `src/app/router.tsx`; сессия: `src/app/session.tsx`; страницы собирают возможности, `src/features` владеет сценариями.
|
||||
- Воспроизведение: `src/player/player.ts` — фасад; адаптеры рядом. Общие правила очереди, событий и волны — `packages/core/src`.
|
||||
- Загрузки: `src/features/uploads`; страница очереди — `src/pages/admin/UploadQueuePage.tsx`. Сохраняй query keys/invalidation, права и поведение диалогов.
|
||||
- `pnpm --filter @pipu/web typecheck`; `pnpm --filter @pipu/web test`. Для локальной проверки можно передать путь теста после `test`.
|
||||
- UI/навигация/диалоги: `pnpm --filter @pipu/web test:e2e`. Проверки используют fake API; реальная серверная авторизация покрывается Go отдельно.
|
||||
- Restore не запускает музыку и не создаёт событие прослушивания. Ошибка preload не пропускает трек. Dispose должен освобождать обработчики.
|
||||
@@ -0,0 +1,63 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test('desktop files survive restart, isolate owners and clear only recent cache', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
const saved = await page.evaluate(async () => {
|
||||
const source = '/src/features/desktop/offline.ts';
|
||||
const { DesktopOffline } = await import(source);
|
||||
const track = { id: 'cached-track', title: 'Offline song', available: true, stream_url: 'data:audio/wav;base64,UklGRg==', duration_ms: 1000, artists: [], album: { id: 'album', title: 'Album', cover_url: null }, genres: [], reaction: null };
|
||||
const session = { client: { POST: async () => ({ data: { items: [track] }, response: new Response('{}') }) } };
|
||||
const offline = new DesktopOffline('test-server/alice', session);
|
||||
await offline.ready;
|
||||
await offline.save(track, true);
|
||||
await offline.save({ ...track, id: 'recent-track' });
|
||||
const tracks = offline.tracks();
|
||||
const result = { count: tracks.length, blob: tracks[0].stream_url.startsWith('blob:'), pinned: offline.pinned(track.id) };
|
||||
offline.dispose();
|
||||
return result;
|
||||
});
|
||||
expect(saved).toEqual({ count: 2, blob: true, pinned: true });
|
||||
await page.reload();
|
||||
const restored = await page.evaluate(async () => {
|
||||
const source = '/src/features/desktop/offline.ts';
|
||||
const { DesktopOffline } = await import(source);
|
||||
const session = { client: { POST: async () => { throw new TypeError('offline'); } } };
|
||||
const alice = new DesktopOffline('test-server/alice', session);
|
||||
const bob = new DesktopOffline('test-server/bob', session);
|
||||
await Promise.all([alice.ready, bob.ready]);
|
||||
const before = alice.tracks().length;
|
||||
const body = await (await fetch(alice.tracks()[0].stream_url)).blob();
|
||||
await alice.clearRecent();
|
||||
const result = { before, bytes: body.size, after: alice.tracks().map((t: { id: string }) => t.id), other: bob.tracks().length };
|
||||
alice.dispose(); bob.dispose();
|
||||
return result;
|
||||
});
|
||||
expect(restored).toEqual({ before: 2, bytes: 4, after: ['cached-track'], other: 0 });
|
||||
});
|
||||
|
||||
test('desktop update dialog hides build reports and launches installer', async ({ page }) => {
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem('pipu.locale', 'ru');
|
||||
(window as Window & { __TAURI__?: unknown }).__TAURI__ = {
|
||||
core: { invoke: async (command: string) => {
|
||||
if (command === 'bootstrap') return { proxyBase: location.origin, server: 'https://music.example' };
|
||||
if (command === 'update_check') return { build: { version: '1.8.0', size: 1048576 }, notes: '<!-- android-status -->\n> APK SHA-256 abc\n<!-- /android-status -->\n## Изменения\n- **Офлайн-музыка**' };
|
||||
if (command === 'update_install') document.documentElement.dataset.installer = 'opened';
|
||||
return null;
|
||||
} },
|
||||
event: { listen: async () => () => undefined },
|
||||
};
|
||||
});
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Логин').fill('alice');
|
||||
await page.getByRole('textbox', { name: 'Пароль' }).fill('alice-password');
|
||||
await page.getByRole('button', { name: 'Войти' }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toContainText('Доступна версия 1.8.0');
|
||||
await expect(dialog).toContainText('• Офлайн-музыка');
|
||||
await expect(dialog).not.toContainText('android-status');
|
||||
await expect(dialog).not.toContainText('SHA-256');
|
||||
await dialog.getByRole('button', { name: 'Скачать и установить' }).click();
|
||||
await expect(dialog).toContainText('Установщик открыт');
|
||||
await expect(page.locator('html')).toHaveAttribute('data-installer', 'opened');
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { expect, test } from '@playwright/test';
|
||||
for (const width of [320, 1280]) {
|
||||
test(`playlists at ${width}px`, async ({ page }, info) => {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.context().grantPermissions(['clipboard-read', 'clipboard-write']);
|
||||
await page.addInitScript(() => localStorage.setItem('pipu.locale', 'ru'));
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Логин', { exact: true }).fill('alice');
|
||||
@@ -10,14 +11,19 @@ for (const width of [320, 1280]) {
|
||||
await page.getByRole('button', { name: 'Войти', exact: true }).click();
|
||||
if (width < 768) await page.getByRole('button', { name: 'Ещё', exact: true }).click();
|
||||
await page.getByRole('link', { name: 'Плейлисты', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Создать плейлист', exact: true }).click();
|
||||
const playlistsHeader = page.locator('header').filter({
|
||||
has: page.getByRole('heading', { name: 'Плейлисты', exact: true }),
|
||||
});
|
||||
await playlistsHeader.getByRole('button', { name: 'Создать плейлист', exact: true }).click();
|
||||
await page.getByLabel('Название', { exact: true }).fill('Музыка для долгой дороги');
|
||||
await page.getByLabel('Описание', { exact: true }).fill('Любимые песни всегда рядом');
|
||||
await page.getByRole('button', { name: 'Сохранить', exact: true }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Музыка для долгой дороги' })).toBeVisible();
|
||||
await page.getByRole('combobox', { name: 'Поиск', exact: true }).fill('кино');
|
||||
await page.getByRole('combobox', { name: 'Поиск', exact: true }).press('Enter');
|
||||
await page.getByRole('button', { name: 'Добавить в плейлист', exact: true }).first().click();
|
||||
await page.getByRole('listitem').first().click();
|
||||
const player = page.getByRole('contentinfo', { name: 'Плеер' });
|
||||
await player.getByRole('button', { name: 'Добавить в плейлист', exact: true }).click();
|
||||
await page.getByRole('button', { name: /Музыка для долгой дороги · 0/ }).click();
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
||||
if (width < 768) await page.getByRole('button', { name: 'Ещё', exact: true }).click();
|
||||
@@ -25,10 +31,22 @@ for (const width of [320, 1280]) {
|
||||
await page.getByRole('link', { name: /Музыка для долгой дороги/ }).click();
|
||||
await page.getByRole('button', { name: 'Управлять треками' }).click();
|
||||
await expect(page.getByRole('button', { name: /Убрать .* из плейлиста/ })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Поделиться плейлистом', exact: true }).click();
|
||||
await expect(page.getByRole('status')).toHaveText('Ссылка на плейлист скопирована');
|
||||
const sharedUrl = await page.evaluate(() => navigator.clipboard.readText());
|
||||
expect(sharedUrl).toMatch(/^http:\/\/127\.0\.0\.1:4173\/shared\/playlist\/[a-f0-9-]+$/);
|
||||
await expect(page.getByRole('button', { name: 'Отключить доступ по ссылке', exact: true })).toBeVisible();
|
||||
|
||||
await expect.poll(() => page.evaluate(() => {
|
||||
const main = document.querySelector('main')!;
|
||||
return Math.max(document.documentElement.scrollWidth - innerWidth, main.scrollWidth - main.clientWidth);
|
||||
})).toBeLessThanOrEqual(1);
|
||||
await page.screenshot({ path: info.outputPath('playlist.png') });
|
||||
await page.getByRole('button', { name: 'Отключить доступ по ссылке', exact: true }).click();
|
||||
await expect(page.getByRole('button', { name: 'Отключить доступ по ссылке', exact: true })).toHaveCount(0);
|
||||
await page.getByRole('button', { name: 'Поделиться плейлистом', exact: true }).click();
|
||||
await expect(page.getByRole('status')).toHaveText('Ссылка на плейлист скопирована');
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).not.toBe(sharedUrl);
|
||||
|
||||
});
|
||||
}
|
||||
@@ -48,6 +48,15 @@ test('settings expose crossfade and loudness normalization', async ({ page }) =>
|
||||
const slider = page.getByRole('slider', { name: /Кроссфейд/ });
|
||||
await slider.fill('4');
|
||||
await expect(page.getByText('Кроссфейд, 4 с')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Настроить рекомендации' }).click();
|
||||
await page.getByRole('button', { name: 'Мужской', exact: true }).click();
|
||||
await page.getByRole('button', { name: '13–19', exact: true }).click();
|
||||
const form = page.getByRole('heading', { name: 'Что вы любите слушать?' }).locator('../..');
|
||||
await form.getByRole('button', { name: 'Сохранить', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Настроить рекомендации' }).click();
|
||||
await expect(page.getByRole('button', { name: 'Мужской', exact: true })).toHaveAttribute('aria-pressed', 'true');
|
||||
await expect(page.getByRole('button', { name: '13–19', exact: true })).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
});
|
||||
test('9. login page switches between Russian and English', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
|
||||
async function login(page: Page, username = 'mobile-admin', target = '/') {
|
||||
await page.addInitScript(() => localStorage.setItem('pipu.locale', 'ru'));
|
||||
await page.goto(`/login?redirect=${encodeURIComponent(target)}`);
|
||||
await page.getByLabel('Логин').fill(username);
|
||||
await page.getByRole('textbox', { name: 'Пароль' }).fill(`${username}-password`);
|
||||
await page.getByRole('button', { name: 'Войти' }).click();
|
||||
await expect(page.getByRole('button', { name: 'Меню профиля' })).toBeVisible();
|
||||
}
|
||||
|
||||
test('admin selects repository and version, confirms and sees persistent job log', async ({ page }) => {
|
||||
await login(page, 'mobile-admin', '/admin/updates');
|
||||
await expect(page.getByRole('heading', { name: 'Обновления', exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Последний релиз', exact: true })).toHaveAttribute('aria-pressed', 'true');
|
||||
await page.getByRole('button', { name: 'Источники обновлений', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Добавить источник' }).click();
|
||||
await page.getByLabel('Название', { exact: true }).last().fill('Тестовая репа');
|
||||
await page.getByLabel('URL Git-репозитория').last().fill('https://git.example.org/pipu/testing.git');
|
||||
await page.getByRole('button', { name: 'Сохранить', exact: true }).click();
|
||||
await expect(page.getByRole('dialog')).not.toBeVisible();
|
||||
await page.getByLabel('Источник', { exact: true }).selectOption({ label: 'Тестовая репа' });
|
||||
await page.getByRole('button', { name: 'Выбрать версию', exact: true }).click();
|
||||
await page.getByLabel('Версия', { exact: true }).selectOption('v1.10.0');
|
||||
await page.getByRole('button', { name: 'Установить обновление', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toContainText('Тестовая репа');
|
||||
await expect(dialog).toContainText('v1.10.0');
|
||||
await dialog.getByRole('button', { name: 'Установить обновление' }).click();
|
||||
await expect(page.getByRole('status').filter({ hasText: 'Выполняется' })).toBeVisible();
|
||||
await expect(page.getByLabel('Журнал выполнения')).toContainText('build and restart');
|
||||
await expect(page.getByRole('button', { name: 'Установить обновление', exact: true })).toBeDisabled();
|
||||
await page.screenshot({ path: 'test-results/server-updates.png', fullPage: true });
|
||||
});
|
||||
|
||||
test('config keeps secret unchanged, saves local override and applies separately', async ({ page }) => {
|
||||
await login(page, 'mobile-admin', '/admin/config');
|
||||
await expect(page.getByRole('heading', { name: 'Конфигурация', exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel('GITEA_TOKEN · config.local', { exact: true })).toHaveValue('');
|
||||
await page.getByLabel('LOG_LEVEL · config.local', { exact: true }).fill('debug');
|
||||
await expect(page.getByText('В .env есть значение:', { exact: false })).toBeVisible();
|
||||
await page.getByLabel('TRAIN_HOUR · config.local', { exact: true }).fill('6');
|
||||
await expect(page.getByRole('button', { name: 'Применить и перезапустить', exact: true })).toBeDisabled();
|
||||
await page.getByRole('button', { name: 'Сохранить', exact: true }).click();
|
||||
await expect(page.getByText('Изменения сохранены в config.local', { exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel('GITEA_TOKEN · config.local', { exact: true })).toHaveAttribute('placeholder', 'Секрет сохранён');
|
||||
await expect(page.getByText('Выполняется', { exact: true })).not.toBeVisible();
|
||||
await page.getByRole('main').evaluate((element) => { element.scrollTop = 0; });
|
||||
await page.screenshot({ path: 'test-results/server-config.png', fullPage: true });
|
||||
await page.getByRole('button', { name: 'Применить и перезапустить', exact: true }).click();
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'Применить и перезапустить' }).click();
|
||||
await expect(page.getByLabel('Журнал выполнения')).toContainText('build and restart');
|
||||
});
|
||||
|
||||
test('update delegate can update but cannot open configuration', async ({ page }) => {
|
||||
await login(page, 'update-manager', '/admin/updates');
|
||||
await expect(page.getByRole('heading', { name: 'Обновления', exact: true })).toBeVisible();
|
||||
await page.evaluate(() => { history.pushState({}, '', '/admin/config'); window.dispatchEvent(new PopStateEvent('popstate')); });
|
||||
await expect(page).toHaveURL('/');
|
||||
await expect(page.getByRole('heading', { name: 'Конфигурация', exact: true })).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('ordinary user is redirected away from server management', async ({ page }) => {
|
||||
await login(page, 'alice', '/admin/updates');
|
||||
await expect(page).toHaveURL('/');
|
||||
});
|
||||
@@ -5,6 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="icon" href="/favicon-32.png" type="image/png" sizes="32x32" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" sizes="180x180" />
|
||||
<title>pipu</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
@@ -1 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><defs><radialGradient id="g" cx="35%" cy="30%" r="75%"><stop offset="0" stop-color="#9CC6FF"/><stop offset=".55" stop-color="#2F80FF"/><stop offset="1" stop-color="#3A1FA8"/></radialGradient></defs><circle cx="16" cy="16" r="14" fill="url(#g)"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
|
||||
<defs>
|
||||
<radialGradient id="orb" cx="28%" cy="18%" r="95%">
|
||||
<stop stop-color="#9CC6FF"/>
|
||||
<stop offset=".42" stop-color="#2F80FF"/>
|
||||
<stop offset=".78" stop-color="#6354E8"/>
|
||||
<stop offset="1" stop-color="#3A1FA8"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="note" x1="0" y1="0" x2=".3" y2="1">
|
||||
<stop stop-color="#FFFFFF"/>
|
||||
<stop offset="1" stop-color="#DFEBFF"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<circle cx="256" cy="256" r="240" fill="url(#orb)"/>
|
||||
<path d="M208 348V164H270C356 164 356 280 270 280H208" fill="none" stroke="url(#note)" stroke-width="44" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<ellipse cx="181" cy="348" rx="49" ry="36" fill="url(#note)" transform="rotate(-18 181 348)"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 312 B After Width: | Height: | Size: 840 B |
@@ -10,7 +10,7 @@ import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { App } from './App';
|
||||
import { createAppRouter, safeRedirect } from './app/router';
|
||||
import { fakeApi, makeUser, type FakeUser } from './test/fakeApi';
|
||||
import { albumTracks, fakeApi, makeUser, type FakeUser } from './test/fakeApi';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
@@ -291,7 +291,7 @@ describe('player', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Войти' }));
|
||||
await screen.findByRole('heading', { name: 'Закрой за мной дверь' });
|
||||
expect(router.state.location.pathname).toBe(path);
|
||||
await user.click(screen.getByRole('listitem'));
|
||||
await user.click(screen.getByRole('button', { name: 'Слушать' }));
|
||||
const bar = screen.getByRole('contentinfo', { name: 'Плеер' });
|
||||
await user.click(within(bar).getByRole('button', { name: 'Поделиться треком' }));
|
||||
expect(await within(bar).findByRole('status')).toHaveTextContent('Ссылка на трек скопирована');
|
||||
@@ -409,6 +409,26 @@ describe('safeRedirect', () => {
|
||||
});
|
||||
|
||||
describe('playlists', () => {
|
||||
it('adds the playing track from the player, keeping the selected track when playback advances', async () => {
|
||||
const alice = makeUser('alice', 'user');
|
||||
const { user, api } = await renderApp([alice], '/album/00000000-0000-4000-8000-0000000000bb', { signedInAs: alice });
|
||||
await screen.findByRole('heading', { name: 'Группа крови' });
|
||||
await user.click(screen.getAllByRole('listitem')[0]!);
|
||||
const bar = screen.getByRole('contentinfo', { name: 'Плеер' });
|
||||
await user.click(within(bar).getByRole('button', { name: 'Добавить в плейлист' }));
|
||||
await user.click(await screen.findByRole('button', { name: 'Создать плейлист' }));
|
||||
await user.type(screen.getByLabelText('Название'), 'Из плеера');
|
||||
await user.click(screen.getByRole('button', { name: 'Сохранить' }));
|
||||
await waitFor(() => expect(api.playlists.size).toBe(1));
|
||||
expect([...api.playlists.values()][0]?.tracks[0]?.title).toBe('Группа крови');
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
await user.click(within(bar).getByRole('button', { name: 'Добавить в плейлист' }));
|
||||
// Simulate automatic advancement while the picker is open.
|
||||
await user.click(within(bar).getByRole('button', { name: 'Следующий' }));
|
||||
await user.click(await screen.findByRole('button', { name: 'Из плеера · 1' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect([...api.playlists.values()][0]?.tracks.map(t => t.title)).toEqual(['Группа крови']);
|
||||
});
|
||||
it('creates, edits, adds an album, reorders, removes and deletes a playlist', async () => {
|
||||
const alice = makeUser('alice', 'user');
|
||||
const { user, router, api } = await renderApp([alice], '/collection/playlists', { signedInAs: alice });
|
||||
@@ -459,3 +479,82 @@ describe('playlists', () => {
|
||||
expect(api.playlists.get(item.id)?.name).toBe('Другое устройство');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('recommendation preferences', () => {
|
||||
it('saves demographics, edits the age group and asks again after an admin reset', async () => {
|
||||
const admin = makeUser('owner', 'admin');
|
||||
const { user, api, router, session } = await renderApp([admin], '/settings', { signedInAs: admin });
|
||||
await user.click(await screen.findByRole('button', { name: 'Настроить рекомендации' }));
|
||||
await user.click(await screen.findByRole('button', { name: 'Мужской' }));
|
||||
await user.click(screen.getByRole('button', { name: '13–19' }));
|
||||
await user.click(screen.getAllByRole('button', { name: 'Сохранить' }).find((b) => !b.hasAttribute('disabled'))!);
|
||||
await screen.findByRole('button', { name: 'Настроить рекомендации' });
|
||||
expect(api.calls.filter((c) => c.path === '/api/v1/me/onboarding').at(-1)?.body).toMatchObject({ gender: 'male', age_group: '13_19' });
|
||||
await user.click(screen.getByRole('button', { name: 'Настроить рекомендации' }));
|
||||
expect(await screen.findByRole('button', { name: '13–19' })).toHaveAttribute('aria-pressed', 'true');
|
||||
await user.click(screen.getByRole('button', { name: '20–29' }));
|
||||
await user.click(screen.getAllByRole('button', { name: 'Сохранить' }).find((b) => !b.hasAttribute('disabled'))!);
|
||||
await screen.findByRole('button', { name: 'Настроить рекомендации' });
|
||||
await session.client.POST('/api/v1/admin/users/{id}/reset-recommendations', { params: { path: { id: admin.id } } });
|
||||
await router.navigate({ to: '/' });
|
||||
await screen.findByRole('heading', { name: 'Что вы любите слушать?' });
|
||||
expect(screen.getByRole('button', { name: 'Мужской' })).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(screen.getByRole('button', { name: '20–29' })).toHaveAttribute('aria-pressed', 'false');
|
||||
await user.click(screen.getByRole('button', { name: 'Пропустить' }));
|
||||
await screen.findByRole('button', { name: 'Запустить «Мою волну»' });
|
||||
expect(api.calls.filter((c) => c.path === '/api/v1/me/onboarding').at(-1)?.body).toEqual({ artist_ids: [], genres: [], gender: null, age_group: null });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('playlist sharing', () => {
|
||||
it('copies a stable read-only link and revokes it without exposing editing controls', async () => {
|
||||
const alice = makeUser('alice', 'user');
|
||||
const { user, router, session, api } = await renderApp([alice], '/', { signedInAs: alice });
|
||||
const created = await session.client.POST('/api/v1/me/playlists', { body: { name: 'Общий микс', description: 'Для друзей', track_ids: [albumTracks[0]!.id] } });
|
||||
const playlist = created.data!;
|
||||
await router.navigate({ to: '/playlist/$id', params: { id: playlist.id } });
|
||||
await screen.findByRole('heading', { name: 'Общий микс' });
|
||||
await user.click(screen.getByRole('button', { name: 'Поделиться плейлистом' }));
|
||||
expect(await screen.findByRole('status')).toHaveTextContent('Ссылка на плейлист скопирована');
|
||||
const shareId = api.playlists.get(playlist.id)!.share_id!;
|
||||
expect(await navigator.clipboard.readText()).toBe(`${window.location.origin}/shared/playlist/${shareId}`);
|
||||
await user.click(screen.getByRole('button', { name: 'Поделиться плейлистом' }));
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Поделиться плейлистом' })).toBeEnabled());
|
||||
expect(api.calls.filter(c => c.method === 'POST' && c.path.endsWith('/share'))).toHaveLength(2);
|
||||
expect(api.playlists.get(playlist.id)?.share_id).toBe(shareId);
|
||||
await router.navigate({ to: '/shared/playlist/$shareId', params: { shareId } });
|
||||
await screen.findByRole('heading', { name: 'Общий микс' });
|
||||
expect(screen.queryByRole('button', { name: 'Изменить плейлист' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Управлять треками' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Удалить плейлист' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Пауза' })).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Слушать всё' }));
|
||||
await screen.findByRole('contentinfo', { name: 'Плеер' });
|
||||
await router.navigate({ to: '/playlist/$id', params: { id: playlist.id } });
|
||||
await user.click(await screen.findByRole('button', { name: 'Отключить доступ по ссылке' }));
|
||||
await waitFor(() => expect(api.playlists.get(playlist.id)?.share_id).toBeNull());
|
||||
await user.click(screen.getByRole('button', { name: 'Поделиться плейлистом' }));
|
||||
await waitFor(() => expect(api.playlists.get(playlist.id)?.share_id).toBeTruthy());
|
||||
expect(api.playlists.get(playlist.id)?.share_id).not.toBe(shareId);
|
||||
await router.navigate({ to: '/shared/playlist/$shareId', params: { shareId } });
|
||||
await screen.findByRole('alert');
|
||||
expect(screen.queryByRole('heading', { name: 'Общий микс' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('returns to the shared playlist after login without starting playback', async () => {
|
||||
const bob = makeUser('bob', 'user');
|
||||
const shareId = '00000000-0000-4000-9001-000000000001';
|
||||
const { api, user, router } = await renderApp([bob], `/shared/playlist/${shareId}`);
|
||||
api.playlists.set('00000000-0000-4000-9000-000000000001', { id: '00000000-0000-4000-9000-000000000001', name: 'От друга', description: '', revision: 1, tracks: [albumTracks[0]!], track_count: 1, duration_ms: 200000, created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z', share_id: shareId });
|
||||
await screen.findByRole('heading', { name: 'Вход' });
|
||||
await user.type(screen.getByLabelText('Логин'), bob.username);
|
||||
await user.type(screen.getByLabelText('Пароль'), bob.password);
|
||||
await user.click(screen.getByRole('button', { name: 'Войти' }));
|
||||
await screen.findByRole('heading', { name: 'От друга' });
|
||||
expect(router.state.location.pathname).toBe(`/shared/playlist/${shareId}`);
|
||||
expect(screen.queryByRole('button', { name: 'Пауза' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Изменить плейлист' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
} from '@tanstack/react-router';
|
||||
import { lazy } from 'react';
|
||||
|
||||
const ServerUpdatesPage = lazy(() => import('../features/server-management/UpdatesPage').then((m) => ({ default: m.UpdatesPage })));
|
||||
const ServerConfigPage = lazy(() => import('../features/server-management/ConfigPage').then((m) => ({ default: m.ConfigPage })));
|
||||
const AuditPage = lazy(() => import('../pages/admin/AuditPage').then((m) => ({ default: m.AuditPage })));
|
||||
const LibraryPage = lazy(() => import('../pages/admin/LibraryPage').then((m) => ({ default: m.LibraryPage })));
|
||||
const PatternsPage = lazy(() => import('../pages/admin/PatternsPage').then((m) => ({ default: m.PatternsPage })));
|
||||
@@ -33,6 +35,7 @@ import { SettingsPage } from '../pages/SettingsPage';
|
||||
import { SetupPage } from '../pages/SetupPage';
|
||||
import { AppShell } from '../widgets/AppShell';
|
||||
import { RouteError } from '../widgets/RouteError';
|
||||
import { DesktopDownloadsPage } from '../features/desktop/DesktopFeatures';
|
||||
|
||||
export interface RouterContext {
|
||||
session: AuthSession;
|
||||
@@ -145,7 +148,11 @@ const adminOnly = ({ context }: { context: { user: AuthUser } }) => {
|
||||
|
||||
const homeRoute = createRoute({ getParentRoute: () => appRoute, path: '/', component: HomePage });
|
||||
const trackRoute = createRoute({ getParentRoute: () => appRoute, path: '/track/$id', component: () => <TrackPage key={trackRoute.useParams().id} id={trackRoute.useParams().id} /> });
|
||||
const sharedPlaylistRoute = createRoute({ getParentRoute: () => appRoute, path: '/shared/playlist/$shareId', component: () => <PlaylistPage key={sharedPlaylistRoute.useParams().shareId} id={sharedPlaylistRoute.useParams().shareId} shared /> });
|
||||
const playlistsRoute = createRoute({ getParentRoute: () => appRoute, path: '/collection/playlists', component: PlaylistsPage });
|
||||
const downloadsRoute = createRoute({ getParentRoute: () => appRoute, path: '/collection/downloads', component: DesktopDownloadsPage,
|
||||
beforeLoad: ({ context }) => { if (!context.desktop) throw redirect({ to: '/settings' }); },
|
||||
});
|
||||
const playlistRoute = createRoute({ getParentRoute: () => appRoute, path: '/playlist/$id', component: () => <PlaylistPage id={playlistRoute.useParams().id} /> });
|
||||
|
||||
const settingsRoute = createRoute({ getParentRoute: () => appRoute, path: '/settings', component: SettingsPage });
|
||||
@@ -269,6 +276,14 @@ const adminSettingsRoute = createRoute({
|
||||
component: AdminSettingsPage,
|
||||
});
|
||||
|
||||
const serverUpdatesRoute = createRoute({
|
||||
getParentRoute: () => appRoute, path: '/admin/updates', component: ServerUpdatesPage,
|
||||
beforeLoad: ({ context }) => {
|
||||
if (context.user.role !== 'admin' && !context.user.manages_updates) throw redirect({ to: '/' });
|
||||
},
|
||||
});
|
||||
const serverConfigRoute = createRoute({ getParentRoute: () => appRoute, path: '/admin/config', beforeLoad: adminOnly, component: ServerConfigPage });
|
||||
|
||||
const routeTree = rootRoute.addChildren([
|
||||
downloadAppRoute,
|
||||
androidAppRoute,
|
||||
@@ -280,6 +295,8 @@ const routeTree = rootRoute.addChildren([
|
||||
homeRoute,
|
||||
trackRoute,
|
||||
playlistsRoute,
|
||||
downloadsRoute,
|
||||
sharedPlaylistRoute,
|
||||
playlistRoute,
|
||||
settingsRoute,
|
||||
searchRoute,
|
||||
@@ -297,6 +314,8 @@ const routeTree = rootRoute.addChildren([
|
||||
myUploadsRoute,
|
||||
uploadQueueRoute,
|
||||
adminSettingsRoute,
|
||||
serverUpdatesRoute,
|
||||
serverConfigRoute,
|
||||
]),
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { AuthSession, type AuthUser } from '@pipu/core';
|
||||
|
||||
import { createDesktop, isDesktop } from './desktop';
|
||||
import { createDesktop, desktopFetch, isDesktop } from './desktop';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('desktop bridge', () => {
|
||||
it('restores the last desktop user when the proxy cannot reach the server', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('offline', { status: 502, headers: { 'x-pipu-transport-error': '1' } })));
|
||||
const user = { id: 'alice', username: 'alice' } as AuthUser;
|
||||
const clear = vi.fn();
|
||||
const session = new AuthSession({ clientType: 'desktop', fetch: desktopFetch, baseUrl: 'http://local', refreshStore: {
|
||||
get: async () => 'refresh', set: vi.fn(), clear, getUser: async () => user,
|
||||
} });
|
||||
expect(await session.restore()).toEqual({ status: 'signed_in', offline: true, user });
|
||||
expect(clear).not.toHaveBeenCalled();
|
||||
});
|
||||
it('reports a failed proxy hop as a network failure, preserving real HTTP errors', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('offline', { status: 502, headers: { 'x-pipu-transport-error': '1' } })));
|
||||
await expect(desktopFetch('http://local/api')).rejects.toThrow('Server unavailable');
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('denied', { status: 401 })));
|
||||
expect((await desktopFetch('http://local/api')).status).toBe(401);
|
||||
});
|
||||
it('is inactive in the browser', () => {
|
||||
expect(isDesktop()).toBe(false);
|
||||
});
|
||||
|
||||
@@ -14,11 +14,19 @@ export function isDesktop(): boolean {
|
||||
return api() !== undefined;
|
||||
}
|
||||
|
||||
function invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
|
||||
/** A failed loopback hop must behave like a network failure to offline auth restore. */
|
||||
export const desktopFetch: typeof fetch = async (input, init) => {
|
||||
const response = await fetch(input, init);
|
||||
if (response.headers.get('x-pipu-transport-error') === '1') throw new TypeError('Server unavailable');
|
||||
return response;
|
||||
};
|
||||
|
||||
export function desktopInvoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
|
||||
const tauri = api();
|
||||
if (!tauri) throw new Error('Tauri API unavailable');
|
||||
return tauri.core.invoke(cmd, args) as Promise<T>;
|
||||
}
|
||||
const invoke = desktopInvoke;
|
||||
|
||||
export type DesktopHandle = {
|
||||
proxyBase: string;
|
||||
|
||||
@@ -8,12 +8,18 @@
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
|
||||
.cover img {
|
||||
.coverImg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
opacity: 0;
|
||||
transition: opacity 0.35s ease;
|
||||
}
|
||||
|
||||
.coverImgOn {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.round {
|
||||
@@ -59,10 +65,52 @@
|
||||
width: 128px;
|
||||
}
|
||||
|
||||
.cardCoverWrap {
|
||||
position: relative;
|
||||
margin-bottom: 4px;
|
||||
overflow: hidden;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.cardCover {
|
||||
aspect-ratio: 1;
|
||||
border-radius: 12px;
|
||||
margin-bottom: 4px;
|
||||
transition: transform 0.28s cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||
}
|
||||
|
||||
.card:hover .cardCover,
|
||||
.card:focus-within .cardCover {
|
||||
transform: scale(1.04);
|
||||
}
|
||||
|
||||
.cardPlay {
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
bottom: 10px;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
color: #05070d;
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
transition:
|
||||
opacity 0.18s,
|
||||
transform 0.18s;
|
||||
}
|
||||
|
||||
.card:hover .cardPlay,
|
||||
.card:focus-within .cardPlay,
|
||||
.cardPlay:focus-visible {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.cardPlay:active {
|
||||
transform: scale(0.94);
|
||||
}
|
||||
|
||||
.cardTitle {
|
||||
@@ -104,6 +152,12 @@
|
||||
min-height: 56px;
|
||||
padding: 6px 12px;
|
||||
border-radius: 10px;
|
||||
animation: pipuIn 0.2s ease-out both;
|
||||
animation-delay: var(--stagger, 0ms);
|
||||
}
|
||||
|
||||
.trackStatic {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.track:has(.trackAlbum) {
|
||||
@@ -272,6 +326,7 @@
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.cardPlay { opacity: 1; transform: none; }
|
||||
.grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
|
||||
.track, .track:has(.trackAlbum) { gap: 8px; padding: 6px 4px; }
|
||||
.track:has(.lead), .track:has(.lead):has(.trackAlbum) { grid-template-columns: 24px 40px minmax(0, 1fr) auto; }
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { Fragment, useRef, type ReactNode } from 'react';
|
||||
import { Fragment, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react';
|
||||
import { AddToPlaylist } from './playlists';
|
||||
import { SaveOfflineButton } from '../features/desktop/DesktopFeatures';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSession } from '../app/session';
|
||||
import { formatDuration } from '../shared/lib/format';
|
||||
import { usePlayer, usePlayerState } from '../player/context';
|
||||
import type { PlayContext } from '../player/player';
|
||||
@@ -28,6 +31,7 @@ function fallbackColors(id: string): string[] {
|
||||
|
||||
/** Размер WebP с сервера (64 / 300 / 1200) под отображаемый размер и плотность экрана. */
|
||||
export function coverSrc(url: string, cssPx: number): string {
|
||||
if (!url.includes('/api/v1/covers/')) return url;
|
||||
const px = cssPx * (typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1);
|
||||
const size = px <= 64 ? 64 : px <= 300 ? 300 : 1200;
|
||||
return `${url}&size=${size}`;
|
||||
@@ -58,7 +62,7 @@ export function Cover({
|
||||
aria-hidden
|
||||
>
|
||||
{album.cover_url ? (
|
||||
<img src={coverSrc(album.cover_url, typeof size === 'number' ? size : 300)} alt="" loading="lazy" />
|
||||
<CoverImg src={coverSrc(album.cover_url, typeof size === 'number' ? size : 300)} />
|
||||
) : (
|
||||
<Icon src={round ? personIcon : albumIcon} size={typeof size === 'number' ? Math.max(16, size * 0.4) : 40} />
|
||||
)}
|
||||
@@ -82,10 +86,39 @@ export function ArtistLinks({ artists }: { artists: ArtistRef[] }) {
|
||||
);
|
||||
}
|
||||
|
||||
function CoverImg({ src }: { src: string }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
className={cx(s.coverImg, ready && s.coverImgOn)}
|
||||
onLoad={() => setReady(true)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function AlbumCard({ album }: { album: AlbumSummary }) {
|
||||
const { t } = useTranslation();
|
||||
const session = useSession();
|
||||
const player = usePlayer();
|
||||
const play = (e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void (async () => {
|
||||
const full = unwrap(await session.client.GET('/api/v1/albums/{id}', { params: { path: { id: album.id } } }));
|
||||
if (full.tracks.some((tr) => tr.available)) player.playList(full.tracks, 0, { type: 'album', id: album.id, label: album.title });
|
||||
})();
|
||||
};
|
||||
return (
|
||||
<Link to="/album/$id" params={{ id: album.id }} className={s.card}>
|
||||
<span className={s.cardCoverWrap}>
|
||||
<Cover album={album} size="100%" className={s.cardCover} />
|
||||
<button type="button" className={s.cardPlay} aria-label={t('catalog.play')} onClick={play}>
|
||||
<Icon src={playIcon} size={22} />
|
||||
</button>
|
||||
</span>
|
||||
<span className={s.cardTitle}>{album.title}</span>
|
||||
<span className={s.cardMeta}>
|
||||
{[album.artist.name, album.year].filter(Boolean).join(' · ')}
|
||||
@@ -154,7 +187,8 @@ export function TrackList({
|
||||
role="listitem"
|
||||
tabIndex={tr.available ? 0 : -1}
|
||||
aria-current={isCurrent || undefined}
|
||||
className={cx(s.track, !tr.available && s.unavailable, isCurrent && s.current)}
|
||||
className={cx(s.track, !tr.available && s.unavailable, isCurrent && s.current, virtual && s.trackStatic)}
|
||||
style={{ '--stagger': `${Math.min(i, 12) * 40}ms` } as CSSProperties}
|
||||
title={tr.available ? undefined : t('catalog.unavailable')}
|
||||
onClick={(e) => {
|
||||
if (e.currentTarget.contains(e.target as Node) && !(e.target as HTMLElement).closest('a, button')) play();
|
||||
@@ -185,6 +219,7 @@ export function TrackList({
|
||||
</Link>
|
||||
)}
|
||||
<span className={s.end} data-playlist-actions={actions ? true : undefined}>
|
||||
{!actions && <SaveOfflineButton track={tr} compact />}
|
||||
{actions ? actions(tr, i) : <AddToPlaylist trackIds={[tr.id]} compact />}
|
||||
{disliked ? (
|
||||
<button
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { memo, useCallback, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSession } from '../app/session';
|
||||
import { useSession, useUser } from '../app/session';
|
||||
import { useErrorText } from '../shared/lib/errors';
|
||||
import { Button, Dialog, Field, FormError, Icon } from '../shared/ui/ui';
|
||||
import { queueIcon } from '../shared/ui/icons';
|
||||
import { playlistAddIcon } from '../shared/ui/icons';
|
||||
import s from './catalog.module.css';
|
||||
|
||||
export type Playlist = components['schemas']['Playlist'];
|
||||
@@ -18,10 +18,13 @@ export function usePlaylists(enabled = true) {
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/me/playlists')) });
|
||||
}
|
||||
|
||||
export function usePlaylist(id: string) {
|
||||
export function usePlaylist(id: string, shared = false) {
|
||||
const session = useSession();
|
||||
return useQuery({ queryKey: ['playlists', id],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/me/playlists/{id}', { params: { path: { id } } })) });
|
||||
const user = useUser();
|
||||
return useQuery({ queryKey: shared ? ['shared-playlists', id, user.id] : ['playlists', id], staleTime: 0,
|
||||
queryFn: async () => shared
|
||||
? unwrap(await session.client.GET('/api/v1/shared/playlists/{shareId}', { params: { path: { shareId: id } } }))
|
||||
: unwrap(await session.client.GET('/api/v1/me/playlists/{id}', { params: { path: { id } } })) });
|
||||
}
|
||||
|
||||
export function playlistInput(p: Playlist): PlaylistInput & { revision: number } {
|
||||
@@ -61,7 +64,7 @@ export function PlaylistEditor({ playlist, trackIds = [], onClose, onSaved }: {
|
||||
}
|
||||
|
||||
/** Mounted only while open, so catalog rows do not each subscribe to the playlist list. */
|
||||
function PlaylistPicker({ trackIds, onClose }: { trackIds: string[]; onClose: () => void }) {
|
||||
const PlaylistPicker = memo(function PlaylistPicker({ trackIds, onClose }: { trackIds: string[]; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const session = useSession();
|
||||
const cache = useQueryClient();
|
||||
@@ -84,14 +87,15 @@ function PlaylistPicker({ trackIds, onClose }: { trackIds: string[]; onClose: ()
|
||||
<Button variant="primary" disabled={add.isPending} onClick={() => setCreate(true)}>{t('playlists.create')}</Button>
|
||||
</div>
|
||||
</Dialog>;
|
||||
}
|
||||
});
|
||||
|
||||
export function AddToPlaylist({ trackIds, compact = false }: { trackIds: string[]; compact?: boolean }) {
|
||||
export function AddToPlaylist({ trackIds, compact = false, className }: { trackIds: string[]; compact?: boolean; className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedIds, setSelectedIds] = useState<string[] | null>(null);
|
||||
const close = useCallback(() => setSelectedIds(null), []);
|
||||
return <>
|
||||
{compact ? <button type="button" className={s.like} aria-label={t('playlists.add')} title={t('playlists.add')} onClick={() => setOpen(true)}><Icon src={queueIcon} size={18} /></button>
|
||||
: <Button icon={queueIcon} disabled={trackIds.length === 0} onClick={() => setOpen(true)}>{t('playlists.add')}</Button>}
|
||||
{open && <PlaylistPicker trackIds={trackIds} onClose={() => setOpen(false)} />}
|
||||
{compact ? <button type="button" className={className ?? s.like} aria-label={t('playlists.add')} title={t('playlists.add')} onClick={() => setSelectedIds([...trackIds])}><Icon src={playlistAddIcon} size={20} /></button>
|
||||
: <Button icon={playlistAddIcon} disabled={trackIds.length === 0} onClick={() => setSelectedIds([...trackIds])}>{t('playlists.add')}</Button>}
|
||||
{selectedIds && <PlaylistPicker trackIds={selectedIds} onClose={close} />}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { releaseNotesText, type Track } from '@pipu/core';
|
||||
import { useEffect, useState, useSyncExternalStore } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAuthState, useSession } from '../../app/session';
|
||||
import { desktopInvoke, useDesktop } from '../../desktop';
|
||||
import { TrackList } from '../../entities/catalog';
|
||||
import { usePlayer, usePlayerState } from '../../player/context';
|
||||
import { Button, Dialog, FormError } from '../../shared/ui/ui';
|
||||
import { formatBytes } from '../../shared/lib/format';
|
||||
import { checkIcon, downloadIcon } from '../../shared/ui/icons';
|
||||
import s from '../../pages/page.module.css';
|
||||
|
||||
export function useOffline() {
|
||||
const offline = usePlayer().offline;
|
||||
useSyncExternalStore(offline?.subscribe ?? (() => () => undefined), offline?.snapshot ?? (() => 0));
|
||||
return offline;
|
||||
}
|
||||
|
||||
export function SaveOfflineButton({ track, compact = false }: { track: Track; compact?: boolean }) {
|
||||
const offline = useOffline();
|
||||
const { t } = useTranslation();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
if (!offline) return null;
|
||||
return <span>
|
||||
<Button busy={busy} disabled={!track.available} icon={offline.pinned(track.id) ? checkIcon : downloadIcon}
|
||||
aria-label={t(offline.pinned(track.id) ? 'desktop.remove_download' : 'desktop.save_track')}
|
||||
title={t(offline.pinned(track.id) ? 'desktop.remove_download' : 'desktop.save_track')} onClick={() => {
|
||||
setBusy(true); setError(false);
|
||||
void (offline.pinned(track.id) ? offline.remove(track.id) : offline.save(track, true))
|
||||
.catch(() => setError(true)).finally(() => setBusy(false));
|
||||
}}>{compact ? null : t(offline.pinned(track.id) ? 'desktop.remove_download' : 'desktop.save_track')}</Button>
|
||||
{error && <span role="alert">{t('desktop.download_failed')}</span>}
|
||||
</span>;
|
||||
}
|
||||
|
||||
export function DesktopOfflineSection() {
|
||||
const offline = useOffline();
|
||||
const { track } = usePlayerState();
|
||||
const { t, i18n } = useTranslation();
|
||||
const [error, setError] = useState(false);
|
||||
useEffect(() => { void offline?.ready.catch(() => setError(true)); }, [offline]);
|
||||
if (!offline) return null;
|
||||
const tracks = offline.tracks();
|
||||
return <section className={s.section}>
|
||||
<h2>{t('desktop.offline')}</h2>
|
||||
<p className={s.note}>{t('desktop.cache_hint')}</p>
|
||||
<div className={s.toolbar}>
|
||||
<span>{formatBytes(offline.bytes, i18n.language)}</span>
|
||||
<Button onClick={() => void offline.clearRecent().catch(() => setError(true))}>{t('desktop.clear_recent')}</Button>
|
||||
{track && <SaveOfflineButton track={track} />}
|
||||
</div>
|
||||
<FormError>{error ? t('desktop.storage_failed') : null}</FormError>
|
||||
{tracks.length > 0 ? <TrackList tracks={tracks} context={{ type: 'collection', id: 'offline' }} actions={(track) => <SaveOfflineButton track={track} compact />} /> : <p>{t('desktop.offline_empty')}</p>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function DesktopDownloadsPage() {
|
||||
const { t } = useTranslation();
|
||||
return <div className={s.page}><h1>{t('desktop.offline')}</h1><DesktopOfflineSection /></div>;
|
||||
}
|
||||
|
||||
export function DesktopOfflineBanner() {
|
||||
const state = useAuthState();
|
||||
const desktop = useDesktop();
|
||||
const { t } = useTranslation();
|
||||
return desktop && state.status === 'signed_in' && state.offline ? <p role="status">{t('mobile.offline')}</p> : null;
|
||||
}
|
||||
|
||||
type Release = { build: { version: string; size: number }; notes: string };
|
||||
type Update = { status: 'idle' | 'checking' | 'latest' | 'error' | 'available' | 'installing' | 'ready'; release?: Release; dismissed?: boolean; progress?: number };
|
||||
let update: Update = { status: 'idle' };
|
||||
let generation = 0;
|
||||
const listeners = new Set<() => void>();
|
||||
function setUpdate(value: Update) { update = value; for (const fn of listeners) fn(); }
|
||||
const subscribe = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };
|
||||
function useUpdate() { return useSyncExternalStore(subscribe, () => update); }
|
||||
async function checkUpdate(server: string, manual = false) {
|
||||
if (update.status === 'checking' || update.status === 'installing') return;
|
||||
const key = `pipu.update.checked.${server}`;
|
||||
if (!manual && Date.now() - Number(localStorage.getItem(key) ?? 0) < 6 * 60 * 60 * 1000) return;
|
||||
setUpdate({ status: 'checking' });
|
||||
const requestGeneration = generation;
|
||||
try {
|
||||
const release = await desktopInvoke<Release | null>('update_check');
|
||||
if (requestGeneration !== generation) return;
|
||||
localStorage.setItem(key, String(Date.now()));
|
||||
setUpdate(release ? { status: 'available', release } : { status: manual ? 'latest' : 'idle' });
|
||||
} catch { if (requestGeneration === generation) setUpdate({ status: manual ? 'error' : 'idle' }); }
|
||||
}
|
||||
|
||||
export function DesktopUpdateButton() {
|
||||
const desktop = useDesktop();
|
||||
const state = useUpdate();
|
||||
const { t } = useTranslation();
|
||||
if (!desktop?.server) return null;
|
||||
return <section className={s.section}>
|
||||
<h2>{t('desktop.updates')}</h2>
|
||||
<Button busy={state.status === 'checking'} disabled={state.status === 'installing'} onClick={() => void checkUpdate(desktop.server!, true)}>{t('mobile.update_check')}</Button>
|
||||
{state.status === 'latest' && <p role="status">{t('mobile.update_latest')}</p>}
|
||||
{state.status === 'error' && !state.release && <FormError>{t('desktop.check_failed')}</FormError>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function DesktopUpdateDialog() {
|
||||
const desktop = useDesktop();
|
||||
const session = useSession();
|
||||
const state = useUpdate();
|
||||
const { t } = useTranslation();
|
||||
useEffect(() => {
|
||||
if (!desktop?.server) return;
|
||||
const check = () => void checkUpdate(desktop.server!);
|
||||
check();
|
||||
window.addEventListener('focus', check);
|
||||
return () => { window.removeEventListener('focus', check); generation++; setUpdate({ status: 'idle' }); };
|
||||
}, [desktop, session]);
|
||||
useEffect(() => {
|
||||
if (!desktop) return;
|
||||
let stop: (() => void) | undefined;
|
||||
let disposed = false;
|
||||
// The native updater emits progress through the same Tauri event surface as media controls.
|
||||
const api = (window as Window & { __TAURI__?: { event: { listen: (name: string, fn: (e: { payload: string }) => void) => Promise<() => void> } } }).__TAURI__;
|
||||
void api?.event.listen('update-progress', (e) => {
|
||||
const progress = Number(e.payload);
|
||||
if (update.status === 'installing' && Number.isFinite(progress)) setUpdate({ ...update, progress: Math.min(1, Math.max(0, progress)) });
|
||||
}).then((fn) => { if (disposed) fn(); else stop = fn; });
|
||||
return () => { disposed = true; stop?.(); };
|
||||
}, [desktop]);
|
||||
if (!desktop || !state.release || state.dismissed) return null;
|
||||
const release = state.release;
|
||||
const busy = state.status === 'installing';
|
||||
const close = () => { if (!busy) setUpdate({ ...state, dismissed: true }); };
|
||||
const notes = releaseNotesText(release.notes);
|
||||
return <Dialog title={t('mobile.update_title', { version: release.build.version })} onClose={close} footer={<>
|
||||
<Button disabled={busy} onClick={close}>{t('mobile.update_later')}</Button>
|
||||
<Button busy={busy} onClick={() => {
|
||||
setUpdate({ status: 'installing', release, progress: 0 });
|
||||
void desktopInvoke('update_install').then(() => setUpdate({ status: 'ready', release })).catch(() => setUpdate({ status: 'error', release }));
|
||||
}}>{t('mobile.update_install')}</Button>
|
||||
</>}>
|
||||
{notes && <p style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', maxHeight: '35vh', overflowY: 'auto' }}>{notes}</p>}
|
||||
<p>{t('mobile.update_size', { size: (release.build.size / 1048576).toFixed(1) })}</p>
|
||||
{busy && <p role="status">{t('mobile.update_downloading', { percent: Math.round((state.progress ?? 0) * 100) })}</p>}
|
||||
{state.status === 'ready' && <p role="status">{t('desktop.installer_open')}</p>}
|
||||
{state.status === 'error' && <FormError>{t('mobile.update_failed')}</FormError>}
|
||||
</Dialog>;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { AuthSession, PlayEvent } from '@pipu/core';
|
||||
import { desktopEventSink, evictRecent, offlineOwner } from './offline';
|
||||
import { createDesktop } from '../../desktop';
|
||||
import { albumTracks } from '../../test/fakeApi';
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
delete (window as Window & { __TAURI__?: unknown }).__TAURI__;
|
||||
});
|
||||
|
||||
describe('desktop cache policy', () => {
|
||||
it('evicts oldest recent files while keeping manual downloads outside the limit', () => {
|
||||
const entry = (id: string, used: number, pinned = false) => ({ id, used, pinned, track: albumTracks[0]!, audio: { size: 60 } as Blob });
|
||||
expect(evictRecent([entry('new', 3), entry('manual', 0, true), entry('old', 1), entry('middle', 2)], 100)).toEqual(['old', 'middle']);
|
||||
});
|
||||
});
|
||||
|
||||
it('persists offline events across sink restarts and deduplicates retries', async () => {
|
||||
(window as Window & { __TAURI__?: unknown }).__TAURI__ = { core: { invoke: async () => ({ proxyBase: 'http://local', server: 'https://music.example' }) } };
|
||||
await createDesktop();
|
||||
const post = vi.fn().mockRejectedValueOnce(new TypeError('offline')).mockResolvedValue({ data: {}, response: new Response('{}') });
|
||||
const session = { state: { status: 'signed_in', user: { id: 'alice' } }, client: { POST: post } } as unknown as AuthSession;
|
||||
const owner = offlineOwner(session)!;
|
||||
const event: PlayEvent = { id: 'one', type: 'play_start', occurred_at: new Date().toISOString(), track_id: 'track' };
|
||||
await expect(desktopEventSink(session, owner)([event])).rejects.toThrow('offline');
|
||||
await desktopEventSink(session, owner)([event]);
|
||||
expect(post.mock.calls[1]?.[1].body.events).toEqual([event]);
|
||||
expect(JSON.parse(localStorage.getItem(`pipu.events.${owner}`)!)).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import { unwrap, type AuthSession, type PlayEvent, type Track } from '@pipu/core';
|
||||
import { desktopHandle } from '../../desktop';
|
||||
|
||||
export const RECENT_LIMIT = 500 * 1024 * 1024;
|
||||
type Entry = { id: string; track: Track; audio: Blob; cover?: Blob; pinned: boolean; used: number };
|
||||
const size = (e: Entry) => e.audio.size + (e.cover?.size ?? 0);
|
||||
|
||||
export function evictRecent(entries: Entry[], limit = RECENT_LIMIT): string[] {
|
||||
let total = entries.filter((e) => !e.pinned).reduce((n, e) => n + size(e), 0);
|
||||
const removed: string[] = [];
|
||||
for (const e of entries.filter((e) => !e.pinned).sort((a, b) => a.used - b.used)) {
|
||||
if (total <= limit) break;
|
||||
removed.push(e.id);
|
||||
total -= size(e);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
export function offlineOwner(session: AuthSession): string | null {
|
||||
const desktop = desktopHandle();
|
||||
return desktop?.server && session.state.status === 'signed_in'
|
||||
? JSON.stringify([desktop.server, session.state.user.id]) : null;
|
||||
}
|
||||
|
||||
/** WebView IndexedDB is persistent across desktop restarts; signed URLs are never stored. */
|
||||
export class DesktopOffline {
|
||||
private db: Promise<IDBDatabase> | null = null;
|
||||
private loaded: Promise<void> | null = null;
|
||||
private entries: Entry[] = [];
|
||||
private urls = new Map<string, Track>();
|
||||
private objects = new Map<string, string[]>();
|
||||
private inUse = new Set<string>();
|
||||
private listeners = new Set<() => void>();
|
||||
private revision = 0;
|
||||
private writes: Promise<unknown> = Promise.resolve();
|
||||
private disposed = false;
|
||||
get ready(): Promise<void> {
|
||||
this.loaded ??= this.reload();
|
||||
return this.loaded;
|
||||
}
|
||||
activate() { this.disposed = false; }
|
||||
constructor(readonly owner: string, private session: AuthSession) {}
|
||||
private database(): Promise<IDBDatabase> {
|
||||
return this.db ??= new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(`pipu.offline.${this.owner}`, 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore('tracks', { keyPath: 'id' });
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
subscribe = (fn: () => void) => { this.listeners.add(fn); return () => { this.listeners.delete(fn); }; };
|
||||
snapshot = () => this.revision;
|
||||
private async reload() {
|
||||
const db = await this.database();
|
||||
const entries = await new Promise<Entry[]>((resolve, reject) => {
|
||||
const req = db.transaction('tracks').objectStore('tracks').getAll();
|
||||
req.onsuccess = () => resolve(req.result as Entry[]);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
if (this.disposed) return;
|
||||
this.entries = entries;
|
||||
for (const e of entries) {
|
||||
if (this.urls.has(e.id)) continue;
|
||||
const audio = URL.createObjectURL(e.audio);
|
||||
const cover = e.cover ? URL.createObjectURL(e.cover) : null;
|
||||
this.objects.set(e.id, [...(this.objects.get(e.id) ?? []), audio, ...(cover ? [cover] : [])]);
|
||||
this.urls.set(e.id, { ...e.track, stream_url: audio, available: true, album: { ...e.track.album, cover_url: cover } });
|
||||
}
|
||||
for (const id of this.urls.keys()) if (!entries.some((e) => e.id === id)) {
|
||||
this.urls.delete(id);
|
||||
if (!this.inUse.has(id)) this.release(id);
|
||||
}
|
||||
this.revision++;
|
||||
for (const fn of this.listeners) fn();
|
||||
}
|
||||
tracks() { return this.entries.map((e) => this.local(e.track)); }
|
||||
private release(id: string) {
|
||||
for (const url of this.objects.get(id) ?? []) URL.revokeObjectURL(url);
|
||||
this.objects.delete(id);
|
||||
}
|
||||
/** Keep only files currently playing/crossfading alive after cache deletion. */
|
||||
keep(ids: string[]) {
|
||||
this.inUse = new Set(ids);
|
||||
for (const id of this.objects.keys()) if (!this.inUse.has(id) && !this.urls.has(id)) this.release(id);
|
||||
}
|
||||
local(track: Track): Track { return this.urls.get(track.id) ?? track; }
|
||||
has(id: string) { return this.entries.some((e) => e.id === id); }
|
||||
pinned(id: string) { return this.entries.some((e) => e.id === id && e.pinned); }
|
||||
get bytes() { return this.entries.reduce((n, e) => n + size(e), 0); }
|
||||
private mutate(fn: (store: IDBObjectStore) => void): Promise<void> {
|
||||
const work = this.writes.catch(() => undefined).then(async () => {
|
||||
const db = await this.database();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('tracks', 'readwrite');
|
||||
fn(tx.objectStore('tracks'));
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
tx.onabort = () => reject(tx.error);
|
||||
});
|
||||
await this.reload();
|
||||
});
|
||||
this.writes = work;
|
||||
return work;
|
||||
}
|
||||
private downloads = new Map<string, Promise<void>>();
|
||||
private downloadTail: Promise<unknown> = Promise.resolve();
|
||||
async save(track: Track, pinned = false): Promise<void> {
|
||||
await this.ready;
|
||||
const pending = this.downloads.get(track.id);
|
||||
if (pending) { await pending; return this.save(track, pinned); }
|
||||
const existing = this.entries.find((e) => e.id === track.id);
|
||||
if (existing) {
|
||||
await this.mutate((store) => {
|
||||
const latest = this.entries.find((e) => e.id === track.id);
|
||||
if (latest) store.put({ ...latest, pinned: latest.pinned || pinned, used: Date.now() });
|
||||
});
|
||||
return;
|
||||
}
|
||||
const job = this.downloadTail.catch(() => undefined).then(() => this.download(track, pinned));
|
||||
this.downloadTail = job;
|
||||
this.downloads.set(track.id, job);
|
||||
try { await job; } finally { this.downloads.delete(track.id); }
|
||||
}
|
||||
private async download(track: Track, pinned: boolean) {
|
||||
if (this.disposed) return;
|
||||
const fresh = unwrap(await this.session.client.POST('/api/v1/tracks/batch', { body: { ids: [track.id] } })).items[0];
|
||||
if (!fresh?.available || !fresh.stream_url) throw new Error('Track unavailable');
|
||||
const response = await fetch(fresh.stream_url);
|
||||
if (!response.ok) throw new Error('Download failed');
|
||||
const audio = await response.blob();
|
||||
if (!audio.size) throw new Error('Empty download');
|
||||
let cover: Blob | undefined;
|
||||
if (fresh.album.cover_url) {
|
||||
try {
|
||||
const response = await fetch(`${fresh.album.cover_url}&size=300`);
|
||||
if (response.ok) cover = await response.blob();
|
||||
} catch { /* Artwork is optional. */ }
|
||||
}
|
||||
if (this.disposed) return;
|
||||
const entry: Entry = { id: track.id, track: { ...fresh, stream_url: null, album: { ...fresh.album, cover_url: null } }, audio, cover, pinned, used: Date.now() };
|
||||
await this.mutate((store) => {
|
||||
const removed = evictRecent([...this.entries.filter((e) => e.id !== entry.id), entry]);
|
||||
for (const id of removed) store.delete(id);
|
||||
if (!removed.includes(entry.id)) store.put(entry);
|
||||
});
|
||||
}
|
||||
async remove(id: string) { await this.mutate((store) => store.delete(id)); }
|
||||
async clearRecent() { await this.mutate((store) => { for (const e of this.entries) if (!e.pinned) store.delete(e.id); }); }
|
||||
dispose() {
|
||||
this.disposed = true;
|
||||
queueMicrotask(() => {
|
||||
if (!this.disposed) return;
|
||||
for (const id of this.objects.keys()) this.release(id);
|
||||
void this.downloadTail.catch(() => undefined).then(() => this.writes)
|
||||
.finally(() => this.db?.then((db) => db.close())).catch(() => undefined);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Persist before sending; retries keep event IDs for server-side deduplication. */
|
||||
export function desktopEventSink(session: AuthSession, owner: string) {
|
||||
const key = `pipu.events.${owner}`;
|
||||
let sending = Promise.resolve();
|
||||
return async (events: PlayEvent[]) => {
|
||||
const work = sending.catch(() => undefined).then(async () => {
|
||||
const old = JSON.parse(localStorage.getItem(key) ?? '[]') as PlayEvent[];
|
||||
const merged = [...new Map([...old, ...events].map((e) => [e.id, e])).values()];
|
||||
localStorage.setItem(key, JSON.stringify(merged));
|
||||
if (offlineOwner(session) !== owner) return;
|
||||
while (merged.length) {
|
||||
if (offlineOwner(session) !== owner) return;
|
||||
const batch = merged.slice(0, 100);
|
||||
unwrap(await session.client.POST('/api/v1/events', { body: { events: batch } }));
|
||||
merged.splice(0, batch.length);
|
||||
localStorage.setItem(key, JSON.stringify(merged));
|
||||
}
|
||||
});
|
||||
sending = work;
|
||||
await work;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSession } from '../../app/session';
|
||||
import { useErrorText } from '../../shared/lib/errors';
|
||||
import { Button, Dialog, Field, FormError, PageSkeleton } from '../../shared/ui/ui';
|
||||
import { JobPanel } from './JobPanel';
|
||||
import s from './management.module.css';
|
||||
|
||||
export function ConfigPage() {
|
||||
const { t } = useTranslation('admin');
|
||||
const session = useSession();
|
||||
const errorText = useErrorText();
|
||||
const qc = useQueryClient();
|
||||
const [draft, setDraft] = useState<Record<string, string | null>>({});
|
||||
const [baseRevision, setBaseRevision] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState('');
|
||||
const [group, setGroup] = useState('all');
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const dirty = Object.keys(draft).length > 0;
|
||||
const query = useQuery({ queryKey: ['server-config'], queryFn: async () => unwrap(await session.client.GET('/api/v1/admin/server/config')), retry: false });
|
||||
const status = useQuery({ queryKey: ['server-updates', 'config'], queryFn: async () => unwrap(await session.client.GET('/api/v1/admin/server/updates')), refetchInterval: 3000, retry: false });
|
||||
const running = status.data?.job?.state === 'running';
|
||||
useEffect(() => {
|
||||
if (!dirty) return;
|
||||
const prevent = (e: BeforeUnloadEvent) => { e.preventDefault(); };
|
||||
window.addEventListener('beforeunload', prevent);
|
||||
return () => window.removeEventListener('beforeunload', prevent);
|
||||
}, [dirty]);
|
||||
useEffect(() => {
|
||||
if (status.data?.job?.state === 'succeeded') void qc.invalidateQueries({ queryKey: ['server-config'] });
|
||||
}, [status.data?.job?.id, status.data?.job?.state, qc]);
|
||||
const save = useMutation({
|
||||
mutationFn: async () => unwrap(await session.client.PATCH('/api/v1/admin/server/config', { body: { revision: baseRevision ?? query.data!.revision, values: draft } })),
|
||||
onSuccess: (data) => { qc.setQueryData(['server-config'], data); setDraft({}); setBaseRevision(null); setSaved(true); },
|
||||
});
|
||||
const apply = useMutation({
|
||||
mutationFn: async () => unwrap(await session.client.POST('/api/v1/admin/server/config/apply')),
|
||||
onSuccess: (job) => {
|
||||
setConfirm(false);
|
||||
qc.setQueryData<components['schemas']['ServerUpdates']>(['server-updates', 'config'], (old) => old ? { ...old, job } : old);
|
||||
void qc.invalidateQueries({ queryKey: ['server-updates'] });
|
||||
},
|
||||
});
|
||||
const change = (key: string, value: string | null) => {
|
||||
setBaseRevision((v) => v ?? query.data!.revision);
|
||||
setDraft((v) => ({ ...v, [key]: value })); setSaved(false); save.reset();
|
||||
};
|
||||
if (query.isPending) return <PageSkeleton />;
|
||||
const entries = query.data?.entries.filter((e) => (group === 'all' || e.group === group) && `${e.key} ${e.group}`.toLowerCase().includes(search.toLowerCase())) ?? [];
|
||||
return <div className={s.page}>
|
||||
<header className={s.header}><div><span className={s.eyebrow}>{t('management.server')}</span><h1>{t('management.config')}</h1><p>{t('management.config_intro')}</p></div></header>
|
||||
{query.error && <FormError>{errorText(query.error)}</FormError>}
|
||||
{query.data && <>
|
||||
<section className={s.hero}><div><span className={s.eyebrow}>{t('management.priority')}</span><strong className={s.priority}>ENV → config.local → {t('management.defaults')}</strong></div><p>{t('management.priority_hint')}</p></section>
|
||||
<div className={s.toolbar}><Field type="search" label={t('management.search')} value={search} onChange={setSearch} /><label className={s.selectLabel}>{t('management.group')}<select value={group} onChange={(e) => setGroup(e.target.value)}><option value="all">{t('management.all')}</option>{[...new Set(query.data.entries.map((v) => v.group))].map((v) => <option key={v} value={v}>{t(`management.groups.${v}`, { defaultValue: v })}</option>)}</select></label></div>
|
||||
<p className={s.note}>{t('management.config_files_hint')}</p>
|
||||
<div className={s.configList}>{entries.map((entry) => {
|
||||
const changed = Object.hasOwn(draft, entry.key);
|
||||
const value = changed ? draft[entry.key] ?? '' : entry.secret ? '' : entry.local ?? '';
|
||||
return <section className={s.configRow} key={entry.key} data-changed={changed || undefined}>
|
||||
<div className={s.configMeta}><code>{entry.key}</code><span className={s.tag}>{t(`management.groups.${entry.group}`, { defaultValue: entry.group })}</span><span className={s.note}>{t(`management.value_source.${entry.source}`)}</span></div>
|
||||
<div className={s.values}><span>{t('management.effective')}: <code>{entry.effective || '—'}</code></span><span>ENV: <code>{entry.env ?? '—'}</code></span></div>
|
||||
{entry.readonly ? <p className={s.note}>{t('management.readonly')}</p> : <div className={s.editor}>
|
||||
<Field label={`${entry.key} · config.local`} type={entry.secret ? 'password' : 'text'} value={value} disabled={running || save.isPending} placeholder={entry.secret && entry.local ? t('management.secret_saved') : entry.default_value} hint={changed && draft[entry.key] === null ? t('management.will_reset') : entry.env !== null ? t('management.overridden') : entry.secret ? t('management.secret_hint') : `${t('management.default')}: ${entry.default_value || '—'}`} onChange={(v) => change(entry.key, v)} mono />
|
||||
<Button disabled={running || save.isPending || (!changed && entry.local === null)} onClick={() => change(entry.key, null)}>{t('management.reset')}</Button>
|
||||
</div>}
|
||||
</section>;
|
||||
})}</div>
|
||||
{!entries.length && <p className={s.note}>{t('management.no_results')}</p>}
|
||||
<section className={s.saveBar}>
|
||||
<div role="status">{saved ? t('management.saved') : dirty ? t('management.unsaved', { count: Object.keys(draft).length }) : query.data.restart_required ? t('management.pending_restart') : t('management.no_changes')}</div>
|
||||
<div className={s.actions}><Button disabled={!dirty || save.isPending} onClick={() => { setDraft({}); setBaseRevision(null); save.reset(); }}>{t('management.discard')}</Button><Button variant="primary" disabled={!dirty || running} busy={save.isPending} onClick={() => save.mutate()}>{t('management.save')}</Button><Button disabled={dirty || running || !query.data.restart_required} busy={apply.isPending} onClick={() => { apply.reset(); setConfirm(true); }}>{t('management.apply')}</Button></div>
|
||||
</section>
|
||||
{save.error && <FormError>{errorText(save.error)}</FormError>}
|
||||
{apply.error && <FormError>{errorText(apply.error)}</FormError>}
|
||||
<JobPanel job={status.data?.job} reconnecting={status.isError} />
|
||||
</>}
|
||||
{confirm && <Dialog title={t('management.apply')} onClose={() => !apply.isPending && setConfirm(false)}><p>{t('management.apply_warning')}</p>{apply.error && <FormError>{errorText(apply.error)}</FormError>}<div className={s.actions}><Button disabled={apply.isPending} onClick={() => setConfirm(false)}>{t('management.cancel')}</Button><Button variant="primary" busy={apply.isPending} onClick={() => apply.mutate()}>{t('management.apply')}</Button></div></Dialog>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import s from './management.module.css';
|
||||
|
||||
export type Job = components['schemas']['ServerJob'];
|
||||
|
||||
export function JobPanel({ job, reconnecting }: { job: Job | null | undefined; reconnecting?: boolean }) {
|
||||
const { t } = useTranslation('admin');
|
||||
if (!job) return null;
|
||||
return <section className={s.card} aria-label={t('management.job')}>
|
||||
<div className={s.cardHead}>
|
||||
<div><span className={s.eyebrow}>{t('management.job')}</span><h2>{job.target}</h2></div>
|
||||
<span className={s.status} data-state={job.state} role="status">{t(`management.state.${job.state}`)}</span>
|
||||
</div>
|
||||
<p className={s.note}>{t('management.started')}: {new Date(job.started_at).toLocaleString()}
|
||||
{job.finished_at && <> · {t('management.finished')}: {new Date(job.finished_at).toLocaleString()}</>}</p>
|
||||
{job.state === 'running' && <p className={s.note}>{t(reconnecting ? 'management.reconnecting' : 'management.running_hint')}</p>}
|
||||
<pre className={s.log} tabIndex={0} aria-label={t('management.log')}>{job.log || t('management.waiting')}</pre>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSession } from '../../app/session';
|
||||
import { useErrorText } from '../../shared/lib/errors';
|
||||
import { Button, Dialog, Field, FormError, PageSkeleton, Segmented } from '../../shared/ui/ui';
|
||||
import { JobPanel } from './JobPanel';
|
||||
import s from './management.module.css';
|
||||
|
||||
type Source = components['schemas']['ServerSource'];
|
||||
type Channel = components['schemas']['ServerUpdateRequest']['channel'];
|
||||
|
||||
export function UpdatesPage() {
|
||||
const { t } = useTranslation('admin');
|
||||
const session = useSession();
|
||||
const qc = useQueryClient();
|
||||
const errorText = useErrorText();
|
||||
const [sourceId, setSourceId] = useState('');
|
||||
const [channel, setChannel] = useState<Channel>('latest');
|
||||
const [version, setVersion] = useState('');
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [editing, setEditing] = useState<Source[] | null>(null);
|
||||
const query = useQuery({
|
||||
queryKey: ['server-updates', sourceId],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/admin/server/updates', {
|
||||
params: { query: { source_id: sourceId || undefined } },
|
||||
})),
|
||||
refetchInterval: 3000,
|
||||
retry: false,
|
||||
});
|
||||
const source = query.data?.sources.find((v) => v.id === sourceId) ?? query.data?.sources[0];
|
||||
const running = query.data?.job?.state === 'running';
|
||||
const refresh = () => qc.invalidateQueries({ queryKey: ['server-updates'] });
|
||||
const save = useMutation({
|
||||
mutationFn: async (sources: Source[]) => unwrap(await session.client.PUT('/api/v1/admin/server/update-sources', { body: { sources } })),
|
||||
onSuccess: () => { setEditing(null); setSourceId(''); void refresh(); },
|
||||
});
|
||||
const start = useMutation({
|
||||
mutationFn: async () => unwrap(await session.client.POST('/api/v1/admin/server/updates', {
|
||||
body: { source_id: source!.id, channel, version: channel === 'version' ? version : undefined },
|
||||
})),
|
||||
onSuccess: (job) => {
|
||||
setConfirm(false);
|
||||
qc.setQueryData<components['schemas']['ServerUpdates']>(['server-updates', sourceId], (old) => old ? { ...old, job } : old);
|
||||
void refresh();
|
||||
},
|
||||
});
|
||||
if (query.isPending) return <PageSkeleton />;
|
||||
return <div className={s.page}>
|
||||
<header className={s.header}><div><span className={s.eyebrow}>{t('management.server')}</span><h1>{t('management.updates')}</h1><p>{t('management.updates_intro')}</p></div>
|
||||
<Button onClick={() => void query.refetch()} busy={query.isFetching}>{t('management.refresh')}</Button>
|
||||
</header>
|
||||
{query.error && <FormError>{errorText(query.error)}</FormError>}
|
||||
{query.data && <>
|
||||
<section className={s.hero}><div><span className={s.eyebrow}>{t('management.current')}</span><strong>{query.data.current_version || '—'}</strong></div><p>{t('management.manual')}</p></section>
|
||||
<section className={s.card}>
|
||||
<div className={s.cardHead}><h2>{t('management.update_target')}</h2><Button disabled={running} onClick={() => { save.reset(); setEditing(query.data.sources.map((v) => ({ ...v }))); }}>{t('management.sources')}</Button></div>
|
||||
<label className={s.selectLabel}>{t('management.source')}
|
||||
<select aria-label={t('management.source')} value={source?.id ?? ''} disabled={running || start.isPending} onChange={(e) => { setSourceId(e.target.value); setVersion(''); start.reset(); }}>
|
||||
{query.data.sources.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<p className={s.url}>{source?.url}</p>
|
||||
<Segmented label={t('management.channel')} value={channel} options={(['latest', 'version', 'main'] as const).map((value) => ({ value, label: t(`management.channel_${value}`) }))} onChange={(v) => { setChannel(v); start.reset(); }} />
|
||||
<p className={s.note}>{t(`management.hint_${channel}`)}</p>
|
||||
{channel === 'version' && <label className={s.selectLabel}>{t('management.version')}<select aria-label={t('management.version')} value={version} onChange={(e) => setVersion(e.target.value)}><option value="">{t('management.choose_version')}</option>{query.data.versions.map((v) => <option key={v} value={v}>{v}</option>)}</select></label>}
|
||||
{query.data.source_error && <FormError>{t('management.source_unavailable')}</FormError>}
|
||||
{start.error && <FormError>{errorText(start.error)}</FormError>}
|
||||
<div className={s.actions}><Button variant="primary" disabled={!source || running || !!query.data.source_error || (channel === 'version' && !version)} busy={start.isPending} onClick={() => { start.reset(); setConfirm(true); }}>{t('management.install')}</Button></div>
|
||||
</section>
|
||||
<JobPanel job={query.data.job} reconnecting={query.isError} />
|
||||
</>}
|
||||
{confirm && <Dialog title={t('management.confirm_update')} onClose={() => !start.isPending && setConfirm(false)}>
|
||||
<p>{t('management.confirm_update_text', { source: source?.name, target: channel === 'version' ? version : t(`management.channel_${channel}`) })}</p>
|
||||
<p className={s.note}>{t('management.update_warning')}</p>
|
||||
{start.error && <FormError>{errorText(start.error)}</FormError>}
|
||||
<div className={s.actions}><Button disabled={start.isPending} onClick={() => setConfirm(false)}>{t('management.cancel')}</Button><Button variant="primary" busy={start.isPending} onClick={() => start.mutate()}>{t('management.install')}</Button></div>
|
||||
</Dialog>}
|
||||
{editing && <Dialog title={t('management.sources')} onClose={() => !save.isPending && setEditing(null)}>
|
||||
<p className={s.note}>{t('management.sources_hint')}</p>
|
||||
<div className={s.sourceList}>{editing.map((item, index) => <div className={s.sourceEditor} key={item.id}>
|
||||
<Field label={t('management.source_name')} value={item.name} maxLength={100} onChange={(name) => setEditing(editing.map((v, i) => i === index ? { ...v, name } : v))} />
|
||||
<Field label={t('management.repository')} value={item.url} maxLength={2048} mono onChange={(url) => setEditing(editing.map((v, i) => i === index ? { ...v, url } : v))} />
|
||||
<Button disabled={editing.length === 1 || save.isPending} onClick={() => setEditing(editing.filter((v) => v.id !== item.id))}>{t('management.remove_source')}</Button>
|
||||
</div>)}</div>
|
||||
{save.error && <FormError>{errorText(save.error)}</FormError>}
|
||||
<div className={s.actions}><Button disabled={editing.length >= 20 || save.isPending} onClick={() => setEditing([...editing, { id: crypto.randomUUID(), name: '', url: '' }])}>{t('management.add_source')}</Button><Button variant="primary" disabled={editing.some((v) => !v.name.trim() || !v.url.trim())} busy={save.isPending} onClick={() => save.mutate(editing)}>{t('management.save')}</Button></div>
|
||||
</Dialog>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
.page { max-width: 1050px; margin: 0 auto; display: flex; flex-direction: column; gap: 24px; }
|
||||
.header, .cardHead { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 16px; }
|
||||
.header h1 { margin: 6px 0; font-family: var(--font-display); font-size: 30px; }
|
||||
.header p, .note { color: var(--text2); font-size: 13px; line-height: 1.6; margin: 0; }
|
||||
.eyebrow { font-size: 11px; text-transform: uppercase; letter-spacing: .12em; color: var(--text2); font-weight: 600; }
|
||||
.hero { display: flex; gap: 24px; align-items: center; justify-content: space-between; padding: 28px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: linear-gradient(120deg, var(--accent-soft), var(--surface-a)); }
|
||||
.hero strong { display: block; font-family: var(--font-display); font-size: 30px; margin-top: 8px; overflow-wrap: anywhere; }
|
||||
.hero strong.priority { font-size: 19px; }
|
||||
.hero p { color: var(--text2); max-width: 340px; line-height: 1.6; font-size: 13px; }
|
||||
.card { padding: 24px; background: var(--surface-a); border: 1px solid var(--line); border-radius: var(--radius-lg); display: flex; flex-direction: column; gap: 18px; }
|
||||
.card h2 { margin: 0; font-size: 18px; }
|
||||
.selectLabel { display: flex; flex-direction: column; gap: 8px; font-size: 13px; font-weight: 500; }
|
||||
.selectLabel select { height: 42px; padding: 0 12px; font: inherit; color: var(--text); border: 1px solid var(--line); border-radius: 10px; background: var(--surface2); max-width: 100%; }
|
||||
.selectLabel select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.url { color: var(--text2); font: 12px monospace; overflow-wrap: anywhere; margin: -8px 0 0; }
|
||||
.actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 10px; }
|
||||
.status, .tag { padding: 5px 10px; border: 1px solid var(--line); border-radius: 99px; color: var(--text2); font-size: 12px; }
|
||||
.status[data-state='running'] { background: var(--accent-soft); color: var(--accent); }
|
||||
.status[data-state='succeeded'] { color: var(--ok); }
|
||||
.status[data-state='failed'] { color: var(--danger); }
|
||||
.log { margin: 0; padding: 18px; border-radius: 12px; background: var(--surface2); border: 1px solid var(--line); max-height: 380px; min-height: 100px; overflow: auto; font-size: 12px; line-height: 1.7; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.sourceList { display: flex; flex-direction: column; gap: 16px; max-height: 50vh; overflow: auto; margin-bottom: 18px; }
|
||||
.sourceEditor { display: flex; flex-direction: column; gap: 12px; padding: 14px; border: 1px solid var(--line); border-radius: 12px; }
|
||||
.toolbar { display: grid; grid-template-columns: 1fr 220px; gap: 16px; align-items: end; }
|
||||
.configList { display: flex; flex-direction: column; gap: 12px; }
|
||||
.configRow { padding: 20px; border: 1px solid var(--line); border-radius: 14px; background: var(--surface-a); display: flex; flex-direction: column; gap: 14px; }
|
||||
.configRow[data-changed] { border-color: var(--accent); }
|
||||
.configMeta { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
|
||||
.configMeta > code { font-size: 13px; font-weight: 600; overflow-wrap: anywhere; }
|
||||
.values { display: flex; flex-wrap: wrap; gap: 12px 24px; color: var(--text2); font-size: 12px; }
|
||||
.values code { overflow-wrap: anywhere; }
|
||||
.editor { display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 12px; }
|
||||
.saveBar { position: sticky; bottom: 12px; z-index: 2; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; padding: 16px 20px; border: 1px solid var(--line); border-radius: 14px; background: var(--surface2); box-shadow: 0 8px 32px #0003; font-size: 13px; }
|
||||
@media (max-width: 650px) { .hero { flex-direction: column; align-items: flex-start; gap: 10px; padding: 20px; } .hero p { max-width: none; } .toolbar { grid-template-columns: 1fr; } .editor { grid-template-columns: 1fr; } .card, .configRow { padding: 16px; } .actions { justify-content: flex-start; } }
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useErrorText } from '../../shared/lib/errors';
|
||||
import { useUploadsApi } from './queries';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Dialog, Field, FormError } from '../../shared/ui/ui';
|
||||
import s from '../../pages/page.module.css';
|
||||
export function BatchEditDialog({ batchId, onClose, onSaved }: { batchId: string; onClose: () => void; onSaved: () => void }) {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const api = useUploadsApi();
|
||||
const errorText = useErrorText();
|
||||
const [artist, setArtist] = useState('');
|
||||
const [album, setAlbum] = useState('');
|
||||
const [year, setYear] = useState('');
|
||||
const [cover, setCover] = useState<string | null | undefined>(undefined);
|
||||
const save = useMutation({
|
||||
mutationFn: () => api.updateBatch(batchId, {
|
||||
...(artist.trim() ? { artist: artist.trim() } : {}),
|
||||
...(album.trim() ? { album: album.trim() } : {}),
|
||||
...(year.trim() ? { year: Number.parseInt(year, 10) } : {}),
|
||||
...(cover !== undefined ? { cover_base64: cover } : {}),
|
||||
}),
|
||||
onSuccess: onSaved,
|
||||
});
|
||||
const pickCover = (file: File | undefined) => {
|
||||
if (!file) {
|
||||
setCover(undefined);
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const data = String(reader.result ?? '');
|
||||
const comma = data.indexOf(',');
|
||||
setCover(comma >= 0 ? data.slice(comma + 1) : data);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
title={t('uploads.batch_edit_title')}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t('common:form.cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" busy={save.isPending} onClick={() => save.mutate()}>
|
||||
{t('uploads.save')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={s.sessions}>
|
||||
<p className={s.note}>{t('uploads.batch_edit_hint')}</p>
|
||||
<Field label={t('uploads.meta_artist')} value={artist} onChange={setArtist} maxLength={500} />
|
||||
<Field label={t('uploads.meta_album')} value={album} onChange={setAlbum} maxLength={500} />
|
||||
<Field label={t('uploads.meta_year')} value={year} inputMode="numeric" onChange={setYear} />
|
||||
<label className={s.sessions}>
|
||||
<span>{t('uploads.batch_cover')}</span>
|
||||
<input type="file" accept="image/jpeg,image/png,image/webp" onChange={(e) => pickCover(e.target.files?.[0])} />
|
||||
</label>
|
||||
<Button variant="ghost" onClick={() => setCover(null)}>
|
||||
{t('uploads.batch_cover_clear')}
|
||||
</Button>
|
||||
<FormError>{save.error ? errorText(save.error) : null}</FormError>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { AuthSession } from '@pipu/core';
|
||||
import { createI18n } from '@pipu/i18n';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { SessionProvider } from '../../app/session';
|
||||
import { mobileFixtures } from '../../test/mobileFixtures';
|
||||
import { EditDialog } from './EditDialog';
|
||||
import type { UploadFile } from './common';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
async function fixture(fail = false) {
|
||||
const file = (mobileFixtures['/api/v1/admin/uploads'] as { items: UploadFile[] }).items[0]!;
|
||||
const requests: unknown[] = [];
|
||||
const fetchImpl: typeof fetch = async (input) => {
|
||||
const req = input as Request;
|
||||
if (req.method === 'PATCH') {
|
||||
requests.push(await req.json());
|
||||
return new Response(JSON.stringify(fail ? { status: 409, code: 'uploads.wrong_status' } : file), { status: fail ? 409 : 200 });
|
||||
}
|
||||
return new Response(JSON.stringify(mobileFixtures['/api/v1/admin/sources']));
|
||||
};
|
||||
const session = new AuthSession({ baseUrl: 'http://localhost', fetch: fetchImpl, clientType: 'web' });
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
const onSaved = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
const i18n = await createI18n('ru');
|
||||
render(<I18nextProvider i18n={i18n}><SessionProvider session={session}><QueryClientProvider client={queryClient}>
|
||||
<EditDialog file={file} onSaved={onSaved} onClose={onClose} />
|
||||
</QueryClientProvider></SessionProvider></I18nextProvider>);
|
||||
const user = userEvent.setup();
|
||||
await user.type(screen.getByLabelText('Исполнитель', { exact: true }), 'Кино');
|
||||
await user.type(screen.getByLabelText('Название', { exact: true }), 'Перемен');
|
||||
return { requests, onSaved, onClose, user };
|
||||
}
|
||||
|
||||
it('saves edited metadata with the target source and closes only after success', async () => {
|
||||
const f = await fixture();
|
||||
await f.user.click(screen.getByRole('button', { name: 'Сохранить' }));
|
||||
await waitFor(() => expect(f.onSaved).toHaveBeenCalledOnce());
|
||||
expect(f.onClose).toHaveBeenCalledOnce();
|
||||
expect(f.requests).toEqual([expect.objectContaining({ metadata: expect.objectContaining({ artist: 'Кино', title: 'Перемен' }), target_source_id: expect.any(String) })]);
|
||||
});
|
||||
|
||||
it('keeps the editor and input when a concurrent review rejects the save', async () => {
|
||||
const f = await fixture(true);
|
||||
await f.user.click(screen.getByRole('button', { name: 'Сохранить' }));
|
||||
await waitFor(() => expect(screen.getByRole('alert')).toBeVisible());
|
||||
expect(screen.getByRole('dialog')).toBeVisible();
|
||||
expect(screen.getByLabelText('Название', { exact: true })).toHaveValue('Перемен');
|
||||
expect(f.onSaved).not.toHaveBeenCalled();
|
||||
expect(f.onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useErrorText, useFieldError } from '../../shared/lib/errors';
|
||||
import { Button, Dialog, Field, FormError } from '../../shared/ui/ui';
|
||||
import { useUploadsApi, useUploadSources } from './queries';
|
||||
import type { UploadFile } from './common';
|
||||
import s from '../../pages/page.module.css';
|
||||
import u from '../../pages/uploads/uploads.module.css';
|
||||
|
||||
type Meta = components['schemas']['UploadMeta'];
|
||||
const EMPTY_META: Meta = { artist: '', albumartist: '', album: '', title: '', genre: '', year: null, track: null, disc: null };
|
||||
|
||||
export function EditDialog({ file, onClose, onSaved }: { file: UploadFile; onClose: () => void; onSaved: () => void }) {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const api = useUploadsApi();
|
||||
const errorText = useErrorText();
|
||||
const fieldError = useFieldError();
|
||||
const [m, setM] = useState<Meta>(file.metadata ?? EMPTY_META);
|
||||
const [source, setSource] = useState(file.target_source_id ?? '');
|
||||
const sources = useUploadSources();
|
||||
const save = useMutation({
|
||||
mutationFn: () => api.updateFile(file.id, { metadata: m, ...(source ? { target_source_id: source } : {}) }),
|
||||
onSuccess: () => {
|
||||
onSaved();
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
const text = (k: 'artist' | 'albumartist' | 'album' | 'title' | 'genre') => (
|
||||
<Field label={t(`uploads.meta_${k}`)} value={m[k]} onChange={(v) => setM({ ...m, [k]: v })} maxLength={500} />
|
||||
);
|
||||
const num = (k: 'year' | 'track' | 'disc') => (
|
||||
<Field
|
||||
label={t(`uploads.meta_${k}`)}
|
||||
value={m[k] === null ? '' : String(m[k])}
|
||||
inputMode="numeric"
|
||||
onChange={(v) => setM({ ...m, [k]: v.trim() === '' ? null : Number.parseInt(v, 10) || null })}
|
||||
/>
|
||||
);
|
||||
const accepting = sources.data?.filter((x) => x.accepts_uploads) ?? [];
|
||||
return (
|
||||
<Dialog
|
||||
title={t('uploads.edit_title')}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t('common:form.cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" busy={save.isPending} disabled={!m.artist.trim() || !m.title.trim()} onClick={() => save.mutate()}>
|
||||
{t('uploads.save')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={s.sessions}>
|
||||
<p className={s.note}>{file.client_rel_path ?? file.original_name}</p>
|
||||
<div className={u.grid}>
|
||||
{text('artist')}
|
||||
{text('albumartist')}
|
||||
{text('album')}
|
||||
{text('title')}
|
||||
{text('genre')}
|
||||
{num('year')}
|
||||
{num('track')}
|
||||
{num('disc')}
|
||||
</div>
|
||||
<label className={s.sessions}>
|
||||
<span>{t('uploads.target_source')}</span>
|
||||
<select className={s.select} value={source} onChange={(e) => setSource(e.target.value)}>
|
||||
<option value="">{t('uploads.target_default')}</option>
|
||||
{accepting.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className={s.note}>{t('uploads.tags_note')}</p>
|
||||
<FormError>{save.error ? (fieldError(save.error, 'metadata') ?? errorText(save.error)) : null}</FormError>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { formatBytes, formatDateTime, formatDuration } from '../../shared/lib/format';
|
||||
import { editIcon, refreshIcon } from '../../shared/ui/icons';
|
||||
import { needsFormatAttention } from './files';
|
||||
import { UploadStatusBadge, useReasonText, type UploadFile } from './common';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, cx, Icon } from '../../shared/ui/ui';
|
||||
import s from '../../pages/page.module.css';
|
||||
import u from '../../pages/uploads/uploads.module.css';
|
||||
export function BatchCard({
|
||||
files,
|
||||
selectable,
|
||||
selected,
|
||||
onToggle,
|
||||
onEdit,
|
||||
onEditBatch,
|
||||
onRetry,
|
||||
}: {
|
||||
files: UploadFile[];
|
||||
selectable: boolean;
|
||||
selected: Set<string>;
|
||||
onToggle: (ids: string[], on: boolean) => void;
|
||||
onEdit: (f: UploadFile) => void;
|
||||
onEditBatch: (batchId: string) => void;
|
||||
onRetry: (id: string) => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation('admin');
|
||||
const first = files[0]!;
|
||||
const ids = files.map((f) => f.id);
|
||||
const all = ids.every((id) => selected.has(id));
|
||||
const size = files.reduce((n, f) => n + f.size_bytes, 0);
|
||||
return (
|
||||
<section className={u.batch} aria-label={t('uploads.batch_of', { author: first.author.username })}>
|
||||
<div className={u.batchHead}>
|
||||
{selectable && (
|
||||
<input type="checkbox" aria-label={t('uploads.select_batch')} checked={all} onChange={(e) => onToggle(ids, e.target.checked)} />
|
||||
)}
|
||||
<b>{first.author.username}</b>
|
||||
<span>{formatDateTime(first.created_at, i18n.language)}</span>
|
||||
<span>{t('uploads.batch_size', { count: files.length, size: formatBytes(size, i18n.language) })}</span>
|
||||
{first.batch_comment && <span className={u.comment}>«{first.batch_comment}»</span>}
|
||||
<span style={{ flex: 1 }} />
|
||||
{selectable && (
|
||||
<Button variant="ghost" onClick={() => onEditBatch(first.batch_id)}>
|
||||
{t('uploads.edit_batch')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{files.map((f) => (
|
||||
<QueueRow
|
||||
key={f.id}
|
||||
file={f}
|
||||
selectable={selectable}
|
||||
checked={selected.has(f.id)}
|
||||
onCheck={(on) => onToggle([f.id], on)}
|
||||
onEdit={() => onEdit(f)}
|
||||
onRetry={() => onRetry(f.id)}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function QueueRow({
|
||||
file: f,
|
||||
selectable,
|
||||
checked,
|
||||
onCheck,
|
||||
onEdit,
|
||||
onRetry,
|
||||
}: {
|
||||
file: UploadFile;
|
||||
selectable: boolean;
|
||||
checked: boolean;
|
||||
onCheck: (on: boolean) => void;
|
||||
onEdit: () => void;
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation('admin');
|
||||
const reason = useReasonText()(f.status_reason);
|
||||
const m = f.metadata;
|
||||
const quality = [
|
||||
f.format?.toUpperCase(),
|
||||
f.bitrate ? `${Math.round(f.bitrate / 1000)} kbps` : null,
|
||||
f.sample_rate ? `${(f.sample_rate / 1000).toFixed(1)} kHz` : null,
|
||||
f.bit_depth ? `${f.bit_depth} bit` : null,
|
||||
f.duration_ms ? formatDuration(f.duration_ms) : null,
|
||||
formatBytes(f.size_bytes, i18n.language),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
const editable = f.status === 'pending_review' || f.status === 'import_failed';
|
||||
return (
|
||||
<div className={u.queueRow}>
|
||||
{selectable ? (
|
||||
<input type="checkbox" aria-label={t('uploads.select_file', { name: f.original_name })} checked={checked} onChange={(e) => onCheck(e.target.checked)} />
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<div className={u.meta}>
|
||||
<span className={u.metaTitle}>{m ? `${m.artist} — ${m.title}` : f.original_name}</span>
|
||||
{m && (
|
||||
<span className={u.sub}>
|
||||
{[m.album, m.year, m.disc && m.disc > 1 ? t('uploads.disc', { n: m.disc }) : null, m.track ? `#${m.track}` : null, m.genre]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
{f.metadata_edited && ` · ${t('uploads.edited')}`}
|
||||
</span>
|
||||
)}
|
||||
<span className={u.sub}>{quality}</span>
|
||||
<span className={u.sub} title={f.client_rel_path ?? undefined}>
|
||||
{f.client_rel_path ?? f.original_name}
|
||||
</span>
|
||||
</div>
|
||||
<div className={u.meta}>
|
||||
<div className={u.flags}>
|
||||
<UploadStatusBadge status={f.status} />
|
||||
{needsFormatAttention(f.format, f.original_name) && (
|
||||
<span className={cx(s.badge, u.tone_warn)} title={t('uploads.format_attention')}>
|
||||
{t('uploads.flag_attention')}
|
||||
</span>
|
||||
)}
|
||||
{f.possible_duplicate && <span className={cx(s.badge, u.tone_warn)}>{t('uploads.flag_possible')}</span>}
|
||||
{f.quality_upgrade && <span className={cx(s.badge, u.tone_info)}>{t('uploads.flag_quality')}</span>}
|
||||
{f.matched_album_id ? (
|
||||
<span className={cx(s.badge, u.tone_info)}>{t('uploads.flag_existing_album')}</span>
|
||||
) : (
|
||||
m && <span className={cx(s.badge, u.tone_muted)}>{t('uploads.flag_new_album')}</span>
|
||||
)}
|
||||
</div>
|
||||
{f.target_rel_path && <span className={u.target}>{f.target_rel_path}</span>}
|
||||
{reason && <span className={f.status === 'pending_review' ? u.warn : u.bad}>{reason}</span>}
|
||||
{f.duplicate_level && f.status === 'duplicate' && (
|
||||
<span className={u.sub}>{t(`uploads.dup_level_${f.duplicate_level}`)}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className={u.rowActions}>
|
||||
{f.stream_url && (
|
||||
<audio controls preload="none" src={f.stream_url} aria-label={t('uploads.listen', { name: f.original_name })} />
|
||||
)}
|
||||
{editable && (
|
||||
<Button variant="ghost" aria-label={t('uploads.edit', { name: f.original_name })} onClick={onEdit}>
|
||||
<Icon src={editIcon} size={18} />
|
||||
</Button>
|
||||
)}
|
||||
{f.status === 'import_failed' && (
|
||||
<Button variant="ghost" icon={refreshIcon} onClick={onRetry}>
|
||||
{t('uploads.retry')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Dialog } from '../../shared/ui/ui';
|
||||
import s from '../../pages/page.module.css';
|
||||
import u from '../../pages/uploads/uploads.module.css';
|
||||
export function RejectDialog({
|
||||
count,
|
||||
busy,
|
||||
onClose,
|
||||
onReject,
|
||||
}: {
|
||||
count: number;
|
||||
busy: boolean;
|
||||
onClose: () => void;
|
||||
onReject: (reason: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const [reason, setReason] = useState('');
|
||||
return (
|
||||
<Dialog
|
||||
title={t('uploads.reject_title', { count })}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t('common:form.cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" busy={busy} onClick={() => onReject(reason)}>
|
||||
{t('uploads.reject')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<label className={s.sessions}>
|
||||
<span>{t('uploads.reject_reason')}</span>
|
||||
<textarea className={u.textarea} value={reason} maxLength={1000} onChange={(e) => setReason(e.target.value)} />
|
||||
</label>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { ApiError } from '@pipu/core';
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { checkIcon, closeIcon, inboxIcon } from '../../shared/ui/icons';
|
||||
import { useErrorText } from '../../shared/lib/errors';
|
||||
import { QuotaMeter, type UploadFile, type UploadStatus } from './common';
|
||||
import { BatchCard } from './QueueRows';
|
||||
import { BatchEditDialog } from './BatchEditDialog';
|
||||
import { EditDialog } from './EditDialog';
|
||||
import { RejectDialog } from './RejectDialog';
|
||||
import { useUploadQueue, useUploadsApi } from './queries';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, EmptyState, FormError } from '../../shared/ui/ui';
|
||||
import s from '../../pages/page.module.css';
|
||||
import u from '../../pages/uploads/uploads.module.css';
|
||||
const TABS = {
|
||||
review: ['pending_review'],
|
||||
failed: ['import_failed'],
|
||||
progress: ['uploading', 'processing', 'approved', 'importing'],
|
||||
imported: ['imported'],
|
||||
declined: ['rejected', 'duplicate', 'invalid', 'withdrawn', 'expired'],
|
||||
} satisfies Record<string, UploadStatus[]>;
|
||||
type Tab = keyof typeof TABS;
|
||||
|
||||
/** «Очередь на добавление» (docs/uploads.md#8): рассмотрение по пачкам, правка метаданных, массовые решения. */
|
||||
export function UploadQueue() {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const api = useUploadsApi();
|
||||
const queryClient = useQueryClient();
|
||||
const errorText = useErrorText();
|
||||
const [tab, setTab] = useState<Tab>('review');
|
||||
const [onlyPossible, setOnlyPossible] = useState(false);
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const [editing, setEditing] = useState<UploadFile | null>(null);
|
||||
const [batchEdit, setBatchEdit] = useState<string | null>(null);
|
||||
const [rejecting, setRejecting] = useState(false);
|
||||
|
||||
const list = useUploadQueue(TABS[tab], tab, onlyPossible);
|
||||
const items = useMemo(() => list.data?.pages.flatMap((p) => p.items) ?? [], [list.data]);
|
||||
useEffect(() => setSelected(new Set()), [tab, onlyPossible]);
|
||||
|
||||
const refresh = async () => {
|
||||
setSelected(new Set());
|
||||
await queryClient.invalidateQueries({ queryKey: ['admin-uploads'] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['upload-quota'] });
|
||||
};
|
||||
const review = useMutation({
|
||||
mutationFn: (v: { decision: 'approve' | 'reject'; ids: string[]; reason?: string }) => api.review(v),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
const retry = useMutation({
|
||||
mutationFn: api.retry,
|
||||
onSuccess: refresh,
|
||||
});
|
||||
const failed = review.data?.items.filter((r) => !r.ok) ?? [];
|
||||
|
||||
// Группировка по пачке: файлы одной загрузки (обычно альбом) рассматриваются вместе.
|
||||
const batches = useMemo(() => {
|
||||
const m = new Map<string, UploadFile[]>();
|
||||
for (const f of items) m.set(f.batch_id, [...(m.get(f.batch_id) ?? []), f]);
|
||||
return [...m.values()];
|
||||
}, [items]);
|
||||
const toggle = (ids: string[], on: boolean) =>
|
||||
setSelected((cur) => {
|
||||
const next = new Set(cur);
|
||||
for (const id of ids) {
|
||||
if (on) next.add(id);
|
||||
else next.delete(id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
const selectable = tab === 'review' || tab === 'failed';
|
||||
const ids = [...selected];
|
||||
|
||||
return (
|
||||
<div className={s.page}>
|
||||
<div className={s.head}>
|
||||
<div>
|
||||
<h1>{t('uploads.queue_title')}</h1>
|
||||
<p className={s.subtitle}>{t('uploads.queue_subtitle')}</p>
|
||||
</div>
|
||||
<QuotaMeter />
|
||||
</div>
|
||||
<div className={s.toolbar}>
|
||||
<div className={s.chips} role="group" aria-label={t('uploads.filter')}>
|
||||
{(Object.keys(TABS) as Tab[]).map((k) => (
|
||||
<button key={k} type="button" className={s.chip} aria-pressed={tab === k} onClick={() => setTab(k)}>
|
||||
{t(`uploads.tab_${k}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span style={{ flex: 1 }} />
|
||||
<label className={u.sub} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<input type="checkbox" checked={onlyPossible} onChange={(e) => setOnlyPossible(e.target.checked)} />
|
||||
{t('uploads.only_possible')}
|
||||
</label>
|
||||
</div>
|
||||
<FormError>{(list.error ?? review.error ?? retry.error) ? errorText(list.error ?? review.error ?? retry.error) : null}</FormError>
|
||||
{failed.length > 0 && (
|
||||
<FormError>{t('uploads.review_failed', { count: failed.length, reason: failed[0]?.error ? errorText(problemError(failed[0].error)) : '' })}</FormError>
|
||||
)}
|
||||
{list.isSuccess && items.length === 0 && <EmptyState icon={inboxIcon}>{t('uploads.queue_empty')}</EmptyState>}
|
||||
|
||||
{batches.map((files) => (
|
||||
<BatchCard
|
||||
key={files[0]!.batch_id}
|
||||
files={files}
|
||||
selectable={selectable}
|
||||
selected={selected}
|
||||
onToggle={toggle}
|
||||
onEdit={setEditing}
|
||||
onEditBatch={setBatchEdit}
|
||||
onRetry={(id) => retry.mutate(id)}
|
||||
/>
|
||||
))}
|
||||
{list.hasNextPage && (
|
||||
<Button busy={list.isFetchingNextPage} onClick={() => void list.fetchNextPage()}>
|
||||
{t('uploads.load_more')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{ids.length > 0 && (
|
||||
<div className={u.bulk} role="region" aria-label={t('uploads.bulk')}>
|
||||
<span>{t('uploads.selected', { count: ids.length })}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<Button variant="ghost" onClick={() => setSelected(new Set())}>
|
||||
{t('common:form.cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" icon={closeIcon} onClick={() => setRejecting(true)}>
|
||||
{t('uploads.reject')}
|
||||
</Button>
|
||||
{tab === 'review' && (
|
||||
<Button variant="primary" icon={checkIcon} busy={review.isPending} onClick={() => review.mutate({ decision: 'approve', ids })}>
|
||||
{t('uploads.approve')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{batchEdit && (
|
||||
<BatchEditDialog
|
||||
batchId={batchEdit}
|
||||
onClose={() => setBatchEdit(null)}
|
||||
onSaved={() => {
|
||||
setBatchEdit(null);
|
||||
void refresh();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{editing && (
|
||||
<EditDialog
|
||||
file={editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={() => {
|
||||
review.reset();
|
||||
void refresh();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{rejecting && (
|
||||
<RejectDialog
|
||||
count={ids.length}
|
||||
busy={review.isPending}
|
||||
onClose={() => setRejecting(false)}
|
||||
onReject={(reason) => {
|
||||
setRejecting(false);
|
||||
review.mutate({ decision: 'reject', ids, reason });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Problem из ответа массового решения → объект, понятный useErrorText. */
|
||||
function problemError(p: components['schemas']['Problem']) {
|
||||
return new ApiError(p.status, p.code, p.params ?? {});
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useErrorText } from '../../shared/lib/errors';
|
||||
import { Button, Field, FormError } from '../../shared/ui/ui';
|
||||
import { useUploadsApi, useUploadSources, useUploadSettings } from './queries';
|
||||
import s from '../../pages/page.module.css';
|
||||
import u from '../../pages/uploads/uploads.module.css';
|
||||
|
||||
type Settings = components['schemas']['UploadSettings'];
|
||||
const GB = 1024 ** 3;
|
||||
|
||||
/** Настройки очереди: общий лимит, лимит на модератора, размер файла, хранилище по умолчанию. */
|
||||
export function UploadSettingsSection() {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const api = useUploadsApi();
|
||||
const queryClient = useQueryClient();
|
||||
const errorText = useErrorText();
|
||||
const settings = useUploadSettings();
|
||||
const sources = useUploadSources();
|
||||
const [form, setForm] = useState<{ queue: string; perUser: string; maxFile: string; source: string; upgrade: boolean } | null>(null);
|
||||
useEffect(() => {
|
||||
if (settings.data) setForm(toForm(settings.data));
|
||||
}, [settings.data]);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: async () => {
|
||||
const f = form!;
|
||||
const gb = (v: string) => Math.round(Number.parseFloat(v.replace(',', '.')) * GB);
|
||||
return api.updateSettings({
|
||||
queue_limit_bytes: gb(f.queue), max_file_bytes: gb(f.maxFile),
|
||||
per_user_limit_bytes: f.perUser.trim() ? gb(f.perUser) : null,
|
||||
default_source_id: f.source || null, allow_quality_upgrade: f.upgrade,
|
||||
});
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
queryClient.setQueryData(['upload-settings'], data);
|
||||
await queryClient.invalidateQueries({ queryKey: ['upload-quota'] });
|
||||
},
|
||||
});
|
||||
if (!form) return null;
|
||||
const valid = [form.queue, form.maxFile].every((v) => Number.parseFloat(v.replace(',', '.')) > 0) &&
|
||||
(!form.perUser.trim() || Number.parseFloat(form.perUser.replace(',', '.')) > 0);
|
||||
const dirty = settings.data ? JSON.stringify(toForm(settings.data)) !== JSON.stringify(form) : false;
|
||||
return (
|
||||
<section className={s.section}>
|
||||
<h2>{t('uploads.settings_title')}</h2>
|
||||
<div className={u.settingsGrid}>
|
||||
<Field label={t('uploads.set_queue')} value={form.queue} onChange={(v) => setForm({ ...form, queue: v })} inputMode="decimal" />
|
||||
<Field
|
||||
label={t('uploads.set_per_user')}
|
||||
value={form.perUser}
|
||||
hint={t('uploads.set_per_user_hint')}
|
||||
onChange={(v) => setForm({ ...form, perUser: v })}
|
||||
inputMode="decimal"
|
||||
/>
|
||||
<Field label={t('uploads.set_max_file')} value={form.maxFile} onChange={(v) => setForm({ ...form, maxFile: v })} inputMode="decimal" />
|
||||
<label>
|
||||
<span className={u.settingsLabel}>{t('uploads.set_source')}</span>
|
||||
<select className={s.select} value={form.source} onChange={(e) => setForm({ ...form, source: e.target.value })}>
|
||||
<option value="">{t('uploads.set_source_auto')}</option>
|
||||
{sources.data
|
||||
?.filter((x) => x.accepts_uploads)
|
||||
.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<label className={u.settingsCheck}>
|
||||
<input type="checkbox" checked={form.upgrade} onChange={(e) => setForm({ ...form, upgrade: e.target.checked })} />
|
||||
<span>{t('uploads.set_upgrade')}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<p className={s.note}>{t('uploads.set_note')}</p>
|
||||
<div className={s.toolbar}>
|
||||
<span style={{ flex: 1 }} />
|
||||
<Button variant="primary" busy={save.isPending} disabled={!dirty || !valid} onClick={() => save.mutate()}>
|
||||
{t('uploads.save')}
|
||||
</Button>
|
||||
</div>
|
||||
{save.isSuccess && !dirty && <span className={s.ok}>{t('uploads.saved')}</span>}
|
||||
<FormError>{save.error ? errorText(save.error) : null}</FormError>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function toForm(st: Settings) {
|
||||
const gb = (n: number) => String(Math.round((n / GB) * 100) / 100);
|
||||
return {
|
||||
queue: gb(st.queue_limit_bytes),
|
||||
perUser: st.per_user_limit_bytes === null ? '' : gb(st.per_user_limit_bytes),
|
||||
maxFile: gb(st.max_file_bytes),
|
||||
source: st.default_source_id ?? '',
|
||||
upgrade: st.allow_quality_upgrade,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { ApiClient, components, paths } from '@pipu/api-client';
|
||||
import { unwrap } from '@pipu/core';
|
||||
|
||||
type FilePatch = paths['/api/v1/admin/uploads/files/{id}']['patch']['requestBody']['content']['application/json'];
|
||||
type BatchPatch = paths['/api/v1/admin/uploads/batches/{id}']['patch']['requestBody']['content']['application/json'];
|
||||
type SettingsPatch = paths['/api/v1/admin/settings/uploads']['patch']['requestBody']['content']['application/json'];
|
||||
|
||||
/** The feature owns transport mapping; views only provide form values. */
|
||||
export function uploadsApi(client: ApiClient) {
|
||||
return {
|
||||
list: async (status: components['schemas']['UploadStatus'][], possible: boolean, cursor?: string) => unwrap(
|
||||
await client.GET('/api/v1/admin/uploads', {
|
||||
params: { query: { status, possible_duplicate: possible || undefined, cursor, limit: 100 } },
|
||||
}),
|
||||
),
|
||||
review: async (v: { ids: string[]; decision: 'approve' | 'reject'; reason?: string }) => unwrap(
|
||||
await client.POST('/api/v1/admin/uploads/review', { body: { file_ids: v.ids, decision: v.decision, reason: v.reason } }),
|
||||
),
|
||||
retry: async (id: string) => unwrap(await client.POST('/api/v1/admin/uploads/files/{id}/retry', { params: { path: { id } } })),
|
||||
updateFile: async (id: string, body: FilePatch) => unwrap(await client.PATCH('/api/v1/admin/uploads/files/{id}', { params: { path: { id } }, body })),
|
||||
updateBatch: async (id: string, body: BatchPatch) => unwrap(await client.PATCH('/api/v1/admin/uploads/batches/{id}', { params: { path: { id } }, body })),
|
||||
sources: async () => unwrap(await client.GET('/api/v1/admin/sources')).items,
|
||||
settings: async () => unwrap(await client.GET('/api/v1/admin/settings/uploads')),
|
||||
updateSettings: async (body: SettingsPatch) => unwrap(await client.PATCH('/api/v1/admin/settings/uploads', { body })),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSession } from '../../app/session';
|
||||
import { formatBytes } from '../../shared/lib/format';
|
||||
import { cx } from '../../shared/ui/ui';
|
||||
import s from '../../pages/page.module.css';
|
||||
import u from '../../pages/uploads/uploads.module.css';
|
||||
|
||||
export type UploadStatus = components['schemas']['UploadStatus'];
|
||||
export type UploadFile = components['schemas']['UploadFile'];
|
||||
|
||||
const TONE: Record<UploadStatus, 'ok' | 'warn' | 'bad' | 'info' | 'muted'> = {
|
||||
uploading: 'info',
|
||||
processing: 'info',
|
||||
pending_review: 'warn',
|
||||
approved: 'info',
|
||||
importing: 'info',
|
||||
imported: 'ok',
|
||||
import_failed: 'bad',
|
||||
duplicate: 'muted',
|
||||
invalid: 'bad',
|
||||
rejected: 'bad',
|
||||
withdrawn: 'muted',
|
||||
expired: 'muted',
|
||||
};
|
||||
|
||||
/** Статусы, которые ещё меняются сами (обработка, импорт) — список опрашивается. */
|
||||
export const MOVING: UploadStatus[] = ['uploading', 'processing', 'approved', 'importing'];
|
||||
|
||||
export function UploadStatusBadge({ status }: { status: UploadStatus }) {
|
||||
const { t } = useTranslation('admin');
|
||||
return <span className={cx(s.badge, u[`tone_${TONE[status]}`])}>{t(`uploads.status.${status}`)}</span>;
|
||||
}
|
||||
|
||||
export function useUploadQuota() {
|
||||
const session = useSession();
|
||||
return useQuery({
|
||||
queryKey: ['upload-quota'],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/uploads/quota')),
|
||||
});
|
||||
}
|
||||
|
||||
/** «Очередь: 6,2 ГБ из 10 ГБ» — видят модераторы и админ (docs/uploads.md#3). */
|
||||
export function QuotaMeter() {
|
||||
const { t, i18n } = useTranslation('admin');
|
||||
const quota = useUploadQuota();
|
||||
const id = useId();
|
||||
if (!quota.data) return null;
|
||||
const q = quota.data;
|
||||
const ratio = q.limit_bytes > 0 ? Math.min(q.used_bytes / q.limit_bytes, 1) : 1;
|
||||
const fmt = (n: number) => formatBytes(n, i18n.language);
|
||||
return (
|
||||
<div className={u.quota}>
|
||||
<span className={u.quotaText} id={id}>
|
||||
{t('uploads.quota', { used: fmt(q.used_bytes), limit: fmt(q.limit_bytes) })}
|
||||
{q.per_user_limit_bytes !== null &&
|
||||
` · ${t('uploads.quota_mine', { used: fmt(q.user_used_bytes), limit: fmt(q.per_user_limit_bytes) })}`}
|
||||
</span>
|
||||
<div className={u.progress} role="progressbar" aria-labelledby={id} aria-valuenow={Math.round(ratio * 100)} aria-valuemin={0} aria-valuemax={100}>
|
||||
<span style={{ width: `${ratio * 100}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Понятный текст причины: код из errors:<code> или текст отклонения админа. */
|
||||
export function useReasonText(): (reason: string | null) => string | null {
|
||||
const { t, i18n } = useTranslation(['admin', 'errors']);
|
||||
const tr = t as unknown as (k: string) => string;
|
||||
return (reason) => {
|
||||
if (!reason) return null;
|
||||
const code = reason.split(':')[0]!.trim();
|
||||
const key = `errors:${code}`;
|
||||
if (i18n.exists(key)) {
|
||||
const rest = reason.slice(code.length + 1).trim();
|
||||
return rest ? `${tr(key)}: ${rest}` : tr(key);
|
||||
}
|
||||
return reason;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
|
||||
import { useSession } from '../../app/session';
|
||||
import { uploadsApi } from './api';
|
||||
import { MOVING, type UploadStatus } from './common';
|
||||
|
||||
export function useUploadsApi() { return uploadsApi(useSession().client); }
|
||||
|
||||
export function useUploadQueue(status: UploadStatus[], tab: string, onlyPossible: boolean) {
|
||||
const api = useUploadsApi();
|
||||
return useInfiniteQuery({
|
||||
queryKey: ['admin-uploads', tab, onlyPossible],
|
||||
initialPageParam: undefined as string | undefined,
|
||||
queryFn: ({ pageParam }) => api.list(status, onlyPossible, pageParam),
|
||||
getNextPageParam: (p) => p.next_cursor ?? undefined,
|
||||
refetchInterval: (q) => q.state.data?.pages.some((p) => p.items.some((it) => MOVING.includes(it.status))) ? 5000 : false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadSources() {
|
||||
const api = useUploadsApi();
|
||||
return useQuery({ queryKey: ['sources'], queryFn: api.sources });
|
||||
}
|
||||
|
||||
export function useUploadSettings() {
|
||||
const api = useUploadsApi();
|
||||
return useQuery({ queryKey: ['upload-settings'], queryFn: api.settings });
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { I18nextProvider } from 'react-i18next';
|
||||
import { App } from './App';
|
||||
import { createAppRouter } from './app/router';
|
||||
import { applyTheme } from './app/session';
|
||||
import { createDesktop, DesktopProvider } from './desktop';
|
||||
import { createDesktop, DesktopProvider, desktopFetch } from './desktop';
|
||||
|
||||
const LOCALE_KEY = 'pipu.locale';
|
||||
|
||||
@@ -70,6 +70,7 @@ const session = new AuthSession({
|
||||
deviceName: desktop ? 'Pipu / Desktop' : deviceName(),
|
||||
baseUrl: desktop?.proxyBase,
|
||||
refreshStore: desktop?.refreshStore,
|
||||
fetch: desktop ? desktopFetch : undefined,
|
||||
});
|
||||
// До первого рендера узнаём, есть ли сессия (refresh-cookie), — guards роутера решают сразу.
|
||||
await session.restore();
|
||||
|
||||
@@ -4,12 +4,12 @@ import { Link } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSession } from '../app/session';
|
||||
import { Cover, TrackList } from '../entities/catalog';
|
||||
import { Cover, TrackList, coverSrc } from '../entities/catalog';
|
||||
import { AddToPlaylist } from '../entities/playlists';
|
||||
import { usePlayer } from '../player/context';
|
||||
import { formatDuration } from '../shared/lib/format';
|
||||
import { playIcon, shuffleIcon } from '../shared/ui/icons';
|
||||
import { Button } from '../shared/ui/ui';
|
||||
import { Button, PageSkeleton } from '../shared/ui/ui';
|
||||
import { NotFound } from './NotFound';
|
||||
import s from './page.module.css';
|
||||
import c from './catalog.module.css';
|
||||
@@ -23,30 +23,41 @@ export function AlbumPage({ id }: { id: string }) {
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/albums/{id}', { params: { path: { id } } })),
|
||||
});
|
||||
|
||||
if (album.isPending) {
|
||||
return (
|
||||
<div className={s.page}>
|
||||
<PageSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (album.isError) return <NotFound error={album.error} />;
|
||||
const a = album.data;
|
||||
const colors = a?.cover_colors.length === 3 ? a.cover_colors : null;
|
||||
const ctx = { type: 'album' as const, id, label: a?.title };
|
||||
if (!a) return null;
|
||||
const colors = a.cover_colors.length === 3 ? a.cover_colors : null;
|
||||
const ctx = { type: 'album' as const, id, label: a.title };
|
||||
|
||||
return (
|
||||
<div className={s.page}>
|
||||
<header className={c.hero}>
|
||||
{a.cover_url && (
|
||||
<span className={c.heroBg} aria-hidden>
|
||||
<img src={coverSrc(a.cover_url, 300)} alt="" />
|
||||
</span>
|
||||
)}
|
||||
{colors && <span className={c.tint} style={{ background: `linear-gradient(180deg, ${colors[0]}66, transparent)` }} aria-hidden />}
|
||||
<Cover album={a ?? { id }} size={200} />
|
||||
<Cover album={a} size={200} className={c.heroCover} />
|
||||
<div className={c.heroBody}>
|
||||
<span className={c.kind}>{t('catalog.album')}</span>
|
||||
<h1 className={c.heroTitle}>{a?.title ?? '…'}</h1>
|
||||
{a && (
|
||||
<h1 className={c.heroTitle}>{a.title}</h1>
|
||||
<span className={c.heroMeta}>
|
||||
<Link to="/artist/$id" params={{ id: a.artist.id }}>
|
||||
{a.artist.name}
|
||||
</Link>
|
||||
{a.year ? ` · ${a.year}` : ''} · {t('catalog.track_count', { count: a.tracks.length })} · {formatDuration(a.duration_ms)}
|
||||
</span>
|
||||
)}
|
||||
{a && a.tracks.some((tr) => tr.available) && (
|
||||
{a.tracks.some((tr) => tr.available) && (
|
||||
<div className={c.heroActions}>
|
||||
<AddToPlaylist trackIds={a.tracks.map(tr => tr.id)} />
|
||||
<AddToPlaylist trackIds={a.tracks.map((tr) => tr.id)} />
|
||||
<Button variant="primary" className={c.pill} icon={playIcon} onClick={() => player.playList(a.tracks, 0, ctx)}>
|
||||
{t('catalog.play')}
|
||||
</Button>
|
||||
@@ -67,7 +78,7 @@ export function AlbumPage({ id }: { id: string }) {
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
{a && <TrackList tracks={a.tracks} numbered context={ctx} />}
|
||||
<TrackList tracks={a.tracks} numbered context={ctx} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import s from './auth.module.css';
|
||||
|
||||
/**
|
||||
* Публичная страница приложений (/download, /android): ссылку можно отправить человеку.
|
||||
* Сборки — последний релиз Gitea через сервер; первым предлагается клиент текущей ОС.
|
||||
* Сборки — до 8 последних релизов Gitea через сервер; первым предлагается клиент текущей ОС.
|
||||
*/
|
||||
export function AppDownloadPage() {
|
||||
const { t, i18n } = useTranslation(['auth', 'common']);
|
||||
@@ -40,10 +40,17 @@ export function AppDownloadPage() {
|
||||
<span className={s.badge}>{detected ? t(`app.platform.${detected}`) : t('app.badge')}</span>
|
||||
<h1>{t('app.title')}</h1>
|
||||
<p className={s.lead}>{t('app.subtitle')}</p>
|
||||
{latest.isPending ? null : data ? (
|
||||
{latest.isPending ? (
|
||||
<p role="status">{t('common:loading')}</p>
|
||||
) : latest.isError ? (
|
||||
<div className={s.hint}>{t('app.unavailable')}</div>
|
||||
) : data ? (
|
||||
<>
|
||||
{primary ? (
|
||||
<DownloadButton client={detected!} href={primary.download_url} meta={`${t('app.version', { version: data.version })} · ${formatBytes(primary.size, i18n.language)}`} />
|
||||
<>
|
||||
<DownloadButton client={detected!} href={primary.download_url} meta={`${t('app.version', { version: primary.version ?? data.version })} · ${formatBytes(primary.size, i18n.language)}`} />
|
||||
<OlderVersions items={primary.older ?? []} />
|
||||
</>
|
||||
) : detected ? (
|
||||
<div className={s.hint}>{t('app.unavailable_platform', { platform: t(`app.platform.${detected}`) })}</div>
|
||||
) : null}
|
||||
@@ -72,12 +79,15 @@ export function AppDownloadPage() {
|
||||
{others.map((id) => {
|
||||
const file = files[id]!;
|
||||
return (
|
||||
<a key={id} className={s.downloadAlt} href={file.download_url} download={file.filename}>
|
||||
<div key={id} className={s.otherBlock}>
|
||||
<a className={s.downloadAlt} href={file.download_url} download={file.filename}>
|
||||
{t(`app.download.${id}`)}
|
||||
<span>
|
||||
{t('app.version', { version: data.version })} · {formatBytes(file.size, i18n.language)}
|
||||
{t('app.version', { version: file.version ?? data.version })} · {formatBytes(file.size, i18n.language)}
|
||||
</span>
|
||||
</a>
|
||||
<OlderVersions items={file.older ?? []} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
@@ -91,6 +101,22 @@ export function AppDownloadPage() {
|
||||
);
|
||||
}
|
||||
|
||||
function OlderVersions({ items }: { items: { version: string; filename?: string; size: number; download_url: string }[] }) {
|
||||
const { t, i18n } = useTranslation(['auth', 'common']);
|
||||
if (items.length === 0) return null;
|
||||
return (
|
||||
<details className={s.older}>
|
||||
<summary>{t('app.older')}</summary>
|
||||
{items.map((b) => (
|
||||
<a key={b.version} className={s.downloadAlt} href={b.download_url} download={b.filename}>
|
||||
{t('app.version', { version: b.version })}
|
||||
<span>{formatBytes(b.size, i18n.language)}</span>
|
||||
</a>
|
||||
))}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function DownloadButton({ client, href, meta }: { client: AppClient; href: string; meta: string }) {
|
||||
const { t } = useTranslation('auth');
|
||||
return (
|
||||
|
||||
@@ -3,10 +3,10 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSession } from '../app/session';
|
||||
import { AlbumGrid, Cover, TrackList } from '../entities/catalog';
|
||||
import { AlbumGrid, Cover, TrackList, coverSrc } from '../entities/catalog';
|
||||
import { usePlayer } from '../player/context';
|
||||
import { playIcon, waveIcon } from '../shared/ui/icons';
|
||||
import { Button } from '../shared/ui/ui';
|
||||
import { Button, PageSkeleton } from '../shared/ui/ui';
|
||||
import { NotFound } from './NotFound';
|
||||
import s from './page.module.css';
|
||||
import c from './catalog.module.css';
|
||||
@@ -29,26 +29,36 @@ export function ArtistPage({ id }: { id: string }) {
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/artists/{id}/albums', { params: { path: { id } } })).items,
|
||||
});
|
||||
|
||||
if (artist.isPending) {
|
||||
return (
|
||||
<div className={s.page}>
|
||||
<PageSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (artist.isError) return <NotFound error={artist.error} />;
|
||||
const a = artist.data;
|
||||
if (!a) return null;
|
||||
const tracks = top.data ?? [];
|
||||
const ctx = { type: 'artist' as const, id, label: a?.name };
|
||||
const ctx = { type: 'artist' as const, id, label: a.name };
|
||||
const own = albums.data?.filter((al) => al.artist.id === id) ?? [];
|
||||
const appears = albums.data?.filter((al) => al.artist.id !== id) ?? [];
|
||||
|
||||
return (
|
||||
<div className={s.page}>
|
||||
<header className={c.hero}>
|
||||
<Cover album={{ id }} size={168} round />
|
||||
{a.image_url && (
|
||||
<span className={c.heroBg} aria-hidden>
|
||||
<img src={coverSrc(a.image_url, 300)} alt="" />
|
||||
</span>
|
||||
)}
|
||||
<Cover album={{ id, cover_url: a.image_url }} size={168} round className={c.heroCover} />
|
||||
<div className={c.heroBody}>
|
||||
<span className={c.kind}>{t('catalog.artist')}</span>
|
||||
<h1 className={c.heroTitle}>{a?.name ?? '…'}</h1>
|
||||
{a && (
|
||||
<h1 className={c.heroTitle}>{a.name}</h1>
|
||||
<span className={c.heroMeta}>
|
||||
{t('catalog.album_count', { count: a.album_count })} · {t('catalog.track_count', { count: a.track_count })}
|
||||
</span>
|
||||
)}
|
||||
{a && (
|
||||
<div className={c.heroActions}>
|
||||
<Button
|
||||
variant="primary"
|
||||
@@ -64,7 +74,6 @@ export function ArtistPage({ id }: { id: string }) {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
{tracks.length > 0 && (
|
||||
|
||||
@@ -2,16 +2,21 @@ import type { ReactNode } from 'react';
|
||||
|
||||
import { Logo } from '../shared/ui/ui';
|
||||
import { LanguageSwitch } from '../widgets/LanguageSwitch';
|
||||
import { WaveButton } from '../widgets/wave/WaveButton';
|
||||
import s from './auth.module.css';
|
||||
|
||||
/** Экран без каркаса: декоративный фон волны и стеклянная карточка по центру. */
|
||||
/** Экран без каркаса: декоративная волна и стеклянная карточка по центру. */
|
||||
export function AuthLayout({ children, footer }: { children: ReactNode; footer?: ReactNode }) {
|
||||
const theme = typeof document !== 'undefined' && document.documentElement.dataset.theme === 'light' ? 'light' : 'dark';
|
||||
return (
|
||||
<div className={s.screen}>
|
||||
<div className={s.backdrop} aria-hidden>
|
||||
<span className={s.blob1} />
|
||||
<span className={s.blob2} />
|
||||
<span className={s.blob3} />
|
||||
<div className={s.waveDecor}>
|
||||
<WaveButton interactive={false} size={620} label="" theme={theme} />
|
||||
</div>
|
||||
</div>
|
||||
<header className={s.top}>
|
||||
<Logo />
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useCollectionCounts } from '../entities/collection';
|
||||
import { usePlayer } from '../player/context';
|
||||
import { useErrorText } from '../shared/lib/errors';
|
||||
import { dislikeFillIcon, historyFillIcon, likeFillIcon, playIcon, shuffleIcon } from '../shared/ui/icons';
|
||||
import { Button, Dialog, FormError, Icon } from '../shared/ui/ui';
|
||||
import { Button, Dialog, EmptyState, FormError, Icon, PageSkeleton } from '../shared/ui/ui';
|
||||
import c from './catalog.module.css';
|
||||
import s from './page.module.css';
|
||||
|
||||
@@ -109,7 +109,12 @@ function History() {
|
||||
</div>
|
||||
)}
|
||||
<FormError>{history.error || clear.error ? errorText(history.error ?? clear.error) : null}</FormError>
|
||||
{history.isSuccess && items.length === 0 && <div className={s.empty}>{t('collection.empty_history')}</div>}
|
||||
{history.isPending && <PageSkeleton />}
|
||||
{history.isSuccess && items.length === 0 && (
|
||||
<EmptyState icon={historyFillIcon} action={<Link to="/">{t('catalog.back_home')}</Link>}>
|
||||
{t('collection.empty_history')}
|
||||
</EmptyState>
|
||||
)}
|
||||
{groups.map((g) => (
|
||||
<section key={g.key} className={c.section}>
|
||||
<h2 className={c.day}>{g.title}</h2>
|
||||
@@ -189,8 +194,18 @@ function Reacted({ reaction }: { reaction: 'like' | 'dislike' }) {
|
||||
</div>
|
||||
)}
|
||||
<FormError>{list.error ? errorText(list.error) : null}</FormError>
|
||||
{list.isPending && <PageSkeleton />}
|
||||
{list.isSuccess && tracks.length === 0 && (
|
||||
<div className={s.empty}>{t(reaction === 'like' ? 'collection.empty_likes' : 'collection.empty_dislikes')}</div>
|
||||
<EmptyState
|
||||
icon={reaction === 'like' ? likeFillIcon : dislikeFillIcon}
|
||||
action={
|
||||
<Link to="/search" search={{ q: '' }}>
|
||||
{t('playlists.find_tracks')}
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
{t(reaction === 'like' ? 'collection.empty_likes' : 'collection.empty_dislikes')}
|
||||
</EmptyState>
|
||||
)}
|
||||
{tracks.length > 0 && (
|
||||
<TrackList
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
waveSunIcon,
|
||||
waveWeekendIcon,
|
||||
} from '../shared/ui/icons';
|
||||
import { cx, FormError, Icon } from '../shared/ui/ui';
|
||||
import { cx, FormError, Icon, Skeleton } from '../shared/ui/ui';
|
||||
import { WaveButton } from '../widgets/wave/WaveButton';
|
||||
import s from './home.module.css';
|
||||
import { Onboarding } from './Onboarding';
|
||||
@@ -41,8 +41,6 @@ const ICONS: Record<string, string> = {
|
||||
rainy: waveRainyIcon,
|
||||
};
|
||||
|
||||
const WAVE_COLORS: [string, string, string] = ['#2F80FF', '#7C5CFF', '#35D3FF'];
|
||||
|
||||
type Tr = (key: string) => string;
|
||||
|
||||
/** Главная: для нового пользователя без истории — сначала онбординг вкуса, затем волна. */
|
||||
@@ -52,8 +50,16 @@ export function HomePage() {
|
||||
const onboarding = useQuery({
|
||||
queryKey: ['onboarding'],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/onboarding')),
|
||||
staleTime: Infinity,
|
||||
staleTime: 0,
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
if (onboarding.isPending) {
|
||||
return (
|
||||
<div className={s.home}>
|
||||
<Skeleton round style={{ width: 320, height: 320, maxWidth: '70vw', maxHeight: '70vw' }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (onboarding.data?.required) {
|
||||
return (
|
||||
<Onboarding
|
||||
@@ -89,8 +95,6 @@ function WaveHome() {
|
||||
const waveOn = st.wave !== null;
|
||||
const playing = waveOn && st.playing;
|
||||
const track = waveOn ? st.track : null;
|
||||
const colors: [string, string, string] =
|
||||
track?.album.cover_colors.length === 3 ? (track.album.cover_colors as [string, string, string]) : WAVE_COLORS;
|
||||
|
||||
const run = (fn: () => Promise<void> | void) => {
|
||||
setError(null);
|
||||
@@ -121,7 +125,7 @@ function WaveHome() {
|
||||
readAudio={player.readAudio}
|
||||
bpm={track?.features?.bpm ?? undefined}
|
||||
energy={track?.features?.energy ?? undefined}
|
||||
colors={colors}
|
||||
colors={track?.album.cover_colors}
|
||||
theme={document.documentElement.dataset.theme === 'light' ? 'light' : 'dark'}
|
||||
size={320}
|
||||
label={t(playing ? 'wave.pause' : 'wave.start')}
|
||||
@@ -136,6 +140,12 @@ function WaveHome() {
|
||||
{st.error === 'wave.empty' && <p className={s.note}>{t('wave.empty')}</p>}
|
||||
<FormError>{error ? errorText(error) : null}</FormError>
|
||||
|
||||
{options.isPending && (showActivities || showMoods) && (
|
||||
<div className={s.picker}>
|
||||
<Skeleton style={{ width: 280, height: 38, borderRadius: 999 }} />
|
||||
<Skeleton style={{ width: 240, height: 38, borderRadius: 999 }} />
|
||||
</div>
|
||||
)}
|
||||
{options.data && (showActivities || showMoods) && (
|
||||
<div className={s.picker}>
|
||||
{showActivities && (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { AGE_GROUPS, GENDERS, unwrap } from '@pipu/core';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
@@ -20,17 +20,19 @@ const MIN_ARTISTS = 3;
|
||||
* Онбординг вкуса (docs/recommendations.md#7): исполнители и жанры библиотеки — начальный вкус «Моей волны»,
|
||||
* пока своей истории почти нет. Пропуск тоже запоминается: второй раз не спросим.
|
||||
*/
|
||||
export function Onboarding({ options, onDone }: { options: Options; onDone: () => void }) {
|
||||
export function Onboarding({ options, onDone, editing = false }: { options: Options; onDone: () => void; editing?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const session = useSession();
|
||||
const errorText = useErrorText();
|
||||
const [artists, setArtists] = useState<Set<string>>(new Set());
|
||||
const [genres, setGenres] = useState<Set<string>>(new Set());
|
||||
const [artists, setArtists] = useState<Set<string>>(new Set(options.choice?.artist_ids));
|
||||
const [genres, setGenres] = useState<Set<string>>(new Set(options.choice?.genres));
|
||||
const [gender, setGender] = useState(options.choice?.gender ?? null);
|
||||
const [ageGroup, setAgeGroup] = useState(options.choice?.age_group ?? null);
|
||||
const save = useMutation({
|
||||
mutationFn: async (skip: boolean) =>
|
||||
unwrap(
|
||||
await session.client.PUT('/api/v1/me/onboarding', {
|
||||
body: skip ? { artist_ids: [], genres: [] } : { artist_ids: [...artists], genres: [...genres] },
|
||||
body: skip ? { artist_ids: [], genres: [], gender: null, age_group: null } : { artist_ids: [...artists], genres: [...genres], gender, age_group: ageGroup },
|
||||
}),
|
||||
),
|
||||
onSuccess: onDone,
|
||||
@@ -43,7 +45,7 @@ export function Onboarding({ options, onDone }: { options: Options; onDone: () =
|
||||
else next.add(key);
|
||||
return next;
|
||||
});
|
||||
const enough = artists.size >= MIN_ARTISTS || (artists.size > 0 && genres.size > 0);
|
||||
const enough = editing || artists.size >= MIN_ARTISTS || (artists.size > 0 && genres.size > 0) || !!gender || !!ageGroup || options.artists.length === 0;
|
||||
|
||||
return (
|
||||
<div className={s.page}>
|
||||
@@ -52,6 +54,21 @@ export function Onboarding({ options, onDone }: { options: Options; onDone: () =
|
||||
<p>{t('onboarding.subtitle')}</p>
|
||||
</header>
|
||||
|
||||
<section aria-label={t('onboarding.gender')}>
|
||||
<h2 className={s.label}>{t('onboarding.gender')}</h2>
|
||||
<div className={s.genres}>
|
||||
<button type="button" className={s.genre} aria-pressed={!gender} onClick={() => setGender(null)}>{t('onboarding.unspecified')}</button>
|
||||
{GENDERS.map((g) => <button type="button" key={g} className={s.genre} aria-pressed={gender === g} onClick={() => setGender(g)}>{t(`onboarding.genders.${g}`)}</button>)}
|
||||
</div>
|
||||
</section>
|
||||
<section aria-label={t('onboarding.age_group')}>
|
||||
<h2 className={s.label}>{t('onboarding.age_group')}</h2>
|
||||
<p>{t('onboarding.age_hint')}</p>
|
||||
<div className={s.genres}>
|
||||
<button type="button" className={s.genre} aria-pressed={!ageGroup} onClick={() => setAgeGroup(null)}>{t('onboarding.unspecified')}</button>
|
||||
{AGE_GROUPS.map((g) => <button type="button" key={g} className={s.genre} aria-pressed={ageGroup === g} onClick={() => setAgeGroup(g)}>{t(`onboarding.ages.${g}`)}</button>)}
|
||||
</div>
|
||||
</section>
|
||||
<section aria-label={t('onboarding.artists')}>
|
||||
<h2 className={s.label}>{t('onboarding.artists')}</h2>
|
||||
<div className={s.artists}>
|
||||
@@ -101,11 +118,11 @@ export function Onboarding({ options, onDone }: { options: Options; onDone: () =
|
||||
|
||||
<FormError>{save.error ? errorText(save.error) : null}</FormError>
|
||||
<div className={s.actions}>
|
||||
<Button variant="ghost" busy={save.isPending && save.variables} onClick={() => save.mutate(true)}>
|
||||
{t('onboarding.skip')}
|
||||
<Button variant="ghost" disabled={save.isPending} busy={save.isPending && save.variables} onClick={() => editing ? onDone() : save.mutate(true)}>
|
||||
{t(editing ? 'form.cancel' : 'onboarding.skip')}
|
||||
</Button>
|
||||
<Button variant="primary" busy={save.isPending && !save.variables} disabled={!enough} onClick={() => save.mutate(false)}>
|
||||
{enough ? t('onboarding.done') : t('onboarding.pick_more', { count: MIN_ARTISTS - artists.size })}
|
||||
<Button variant="primary" busy={save.isPending && !save.variables} disabled={!enough || save.isPending} onClick={() => save.mutate(false)}>
|
||||
{enough ? t(editing ? 'settings.save' : 'onboarding.done') : t('onboarding.pick_more', { count: MIN_ARTISTS - artists.size })}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Link, useNavigate } from '@tanstack/react-router';
|
||||
import { useState } from 'react';
|
||||
import { useState, type MouseEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSession } from '../app/session';
|
||||
import { Cover, TrackList } from '../entities/catalog';
|
||||
import { PlaylistEditor, playlistInput, usePlaylist, usePlaylists, type Playlist } from '../entities/playlists';
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { usePlayer } from '../player/context';
|
||||
import { useErrorText } from '../shared/lib/errors';
|
||||
import { sharePlaylist } from '../shared/lib/share';
|
||||
import { formatDuration } from '../shared/lib/format';
|
||||
import { Button, Dialog, Field, FormError } from '../shared/ui/ui';
|
||||
import { playIcon, shuffleIcon } from '../shared/ui/icons';
|
||||
import { Button, Dialog, EmptyState, Field, FormError, Icon, PageSkeleton } from '../shared/ui/ui';
|
||||
import { playIcon, playlistAddIcon, searchIcon, shuffleIcon, shareIcon } from '../shared/ui/icons';
|
||||
import c from './catalog.module.css';
|
||||
import s from './page.module.css';
|
||||
import p from './playlists.module.css';
|
||||
@@ -27,30 +29,33 @@ export function PlaylistsPage() {
|
||||
<header className={s.toolbar}><h1>{t('playlists.title')}</h1><Button variant="primary" onClick={() => setCreate(true)}>{t('playlists.create')}</Button></header>
|
||||
<Field label={t('playlists.search')} value={search} onChange={setSearch} type="search" />
|
||||
<FormError>{list.error ? errorText(list.error) : null}</FormError>
|
||||
{list.isPending && <p role="status">{t('playlists.loading')}</p>}
|
||||
{list.isSuccess && !items.length && <p className={s.empty}>{t(search ? 'playlists.no_results' : 'playlists.empty')}</p>}
|
||||
<div className={p.grid}>{items.map(item => <Link key={item.id} to="/playlist/$id" params={{ id: item.id }} className={p.card}>
|
||||
<Cover album={item} size="100%" />
|
||||
<strong>{item.name}</strong><span>{t('catalog.track_count', { count: item.track_count })} · {formatDuration(item.duration_ms)}</span>
|
||||
{item.description && <span className={p.description}>{item.description}</span>}
|
||||
</Link>)}</div>
|
||||
{list.isPending && <PageSkeleton />}
|
||||
{list.isSuccess && !items.length && (
|
||||
<EmptyState
|
||||
icon={search ? searchIcon : playlistAddIcon}
|
||||
action={!search ? <Button variant="primary" onClick={() => setCreate(true)}>{t('playlists.create')}</Button> : undefined}
|
||||
>
|
||||
{t(search ? 'playlists.no_results' : 'playlists.empty')}
|
||||
</EmptyState>
|
||||
)}
|
||||
<div className={p.grid}>{items.map(item => <PlaylistCard key={item.id} item={item} />)}</div>
|
||||
{create && <PlaylistEditor onClose={() => setCreate(false)} onSaved={item => { setCreate(false); void navigate({ to: '/playlist/$id', params: { id: item.id } }); }} />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function PlaylistPage({ id }: { id: string }) {
|
||||
export function PlaylistPage({ id, shared = false }: { id: string; shared?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const query = usePlaylist(id);
|
||||
const query = usePlaylist(id, shared);
|
||||
const errorText = useErrorText();
|
||||
return <div className={s.page}>
|
||||
<Link to="/collection/playlists">← {t('playlists.title')}</Link>
|
||||
<FormError>{query.error ? errorText(query.error) : null}</FormError>
|
||||
{query.isPending && <p role="status">{t('playlists.loading')}</p>}
|
||||
{query.data && <PlaylistDetail key={id} playlist={query.data} />}
|
||||
{query.isPending && <PageSkeleton />}
|
||||
{query.data && !query.isError && <PlaylistDetail key={id} playlist={query.data} readOnly={shared} shareId={shared ? id : undefined} />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function PlaylistDetail({ playlist }: { playlist: Playlist }) {
|
||||
function PlaylistDetail({ playlist, readOnly = false, shareId }: { playlist: Playlist; readOnly?: boolean; shareId?: string }) {
|
||||
const { t } = useTranslation();
|
||||
const session = useSession();
|
||||
const cache = useQueryClient();
|
||||
@@ -60,6 +65,21 @@ function PlaylistDetail({ playlist }: { playlist: Playlist }) {
|
||||
const [edit, setEdit] = useState(false);
|
||||
const [remove, setRemove] = useState(false);
|
||||
const [manage, setManage] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const sharing = useMutation({ mutationFn: async () => {
|
||||
setCopied(false);
|
||||
let token = shareId ?? playlist.share_id;
|
||||
if (!readOnly) {
|
||||
token = unwrap(await session.client.POST('/api/v1/me/playlists/{id}/share', { params: { path: { id: playlist.id } } })).share_id;
|
||||
cache.setQueryData<Playlist>(['playlists', playlist.id], current => current ? { ...current, share_id: token } : current);
|
||||
}
|
||||
if (!token) throw new Error('Share link unavailable');
|
||||
const result = await sharePlaylist(token, playlist.name);
|
||||
if (result === 'copied') setCopied(true);
|
||||
} });
|
||||
const revoke = useMutation({ mutationFn: async () => unwrap(await session.client.DELETE('/api/v1/me/playlists/{id}/share', { params: { path: { id: playlist.id } } })),
|
||||
onSuccess: () => { setCopied(false); cache.setQueryData<Playlist>(['playlists', playlist.id], current => current ? { ...current, share_id: null } : current); cache.removeQueries({ queryKey: ['shared-playlists', playlist.share_id] }); } });
|
||||
|
||||
const context = { type: 'collection' as const, id: playlist.id, label: playlist.name };
|
||||
const save = useMutation({ mutationFn: async (ids: string[]) => unwrap(await session.client.PUT('/api/v1/me/playlists/{id}', {
|
||||
params: { path: { id: playlist.id } }, body: { ...playlistInput(playlist), track_ids: ids },
|
||||
@@ -80,7 +100,7 @@ function PlaylistDetail({ playlist }: { playlist: Playlist }) {
|
||||
return <>
|
||||
<header className={c.colHero}>
|
||||
<Cover album={playlist.tracks[0]?.album ?? playlist} size={144} />
|
||||
<div className={c.heroText}><span className={c.kicker}>{t('playlists.private')}</span><h1 className={c.colTitle}>{playlist.name}</h1>
|
||||
<div className={c.heroText}><span className={c.kicker}>{t(readOnly || playlist.share_id ? 'playlists.shared' : 'playlists.private')}</span><h1 className={c.colTitle}>{playlist.name}</h1>
|
||||
<p className={p.description}>{playlist.description}</p>
|
||||
<span>{t('catalog.track_count', { count: playlist.track_count })} · {formatDuration(playlist.duration_ms)}</span>
|
||||
</div>
|
||||
@@ -88,22 +108,76 @@ function PlaylistDetail({ playlist }: { playlist: Playlist }) {
|
||||
<div className={s.toolbar}>
|
||||
<Button variant="primary" icon={playIcon} disabled={!playlist.tracks.some(x => x.available)} onClick={() => play(false)}>{t('collection.play_all')}</Button>
|
||||
<Button icon={shuffleIcon} disabled={!playlist.tracks.some(x => x.available)} onClick={() => play(true)}>{t('collection.shuffle')}</Button>
|
||||
<Button icon={shareIcon} busy={sharing.isPending} disabled={revoke.isPending} onClick={() => sharing.mutate()}>{t('playlists.share')}</Button>
|
||||
{!readOnly && <>
|
||||
<Button disabled={save.isPending} onClick={() => setEdit(true)}>{t('playlists.edit')}</Button>
|
||||
<Button aria-pressed={manage} onClick={() => setManage(!manage)}>{t('playlists.manage')}</Button>
|
||||
<Button variant="ghost" disabled={save.isPending} onClick={() => setRemove(true)}>{t('playlists.delete')}</Button>
|
||||
{playlist.share_id && <Button variant="ghost" busy={revoke.isPending} disabled={sharing.isPending} onClick={() => revoke.mutate()}>{t('playlists.revoke_share')}</Button>}
|
||||
</>}
|
||||
</div>
|
||||
{!readOnly && <p>{t('playlists.share_hint')}</p>}
|
||||
{copied && <p role="status">{t('playlists.link_copied')}</p>}
|
||||
<FormError>{sharing.error ? t('player.share_error') : revoke.error ? errorText(revoke.error) : null}</FormError>
|
||||
<FormError>{save.error ? errorText(save.error) : null}</FormError>
|
||||
{!playlist.tracks.length && <div className={s.empty}><p>{t('playlists.empty_tracks')}</p><Link to="/search" search={{ q: '' }}>{t('playlists.find_tracks')}</Link></div>}
|
||||
{!playlist.tracks.length && (
|
||||
<EmptyState icon={playlistAddIcon} action={<Link to="/search" search={{ q: '' }}>{t('playlists.find_tracks')}</Link>}>
|
||||
{t('playlists.empty_tracks')}
|
||||
</EmptyState>
|
||||
)}
|
||||
<TrackList tracks={playlist.tracks} showAlbum context={context} lead={(_, i) => String(i + 1)}
|
||||
actions={manage ? (track, i) => <span className={p.actions}>
|
||||
actions={!readOnly && manage ? (track, i) => <span className={p.actions}>
|
||||
<button type="button" disabled={i === 0 || save.isPending} aria-label={t('playlists.move_up', { name: track.title })} onClick={() => move(i, -1)}>↑</button>
|
||||
<button type="button" disabled={i === playlist.tracks.length - 1 || save.isPending} aria-label={t('playlists.move_down', { name: track.title })} onClick={() => move(i, 1)}>↓</button>
|
||||
<button type="button" disabled={save.isPending} aria-label={t('playlists.remove_track', { name: track.title })} onClick={() => save.mutate(playlist.tracks.filter(x => x.id !== track.id).map(x => x.id))}>×</button>
|
||||
</span> : undefined} />
|
||||
{edit && <PlaylistEditor playlist={playlist} onClose={() => setEdit(false)} onSaved={() => setEdit(false)} />}
|
||||
{remove && <Dialog title={t('playlists.delete')} onClose={() => { if (!deletion.isPending) setRemove(false); }} footer={<>
|
||||
{!readOnly && edit && <PlaylistEditor playlist={playlist} onClose={() => setEdit(false)} onSaved={() => setEdit(false)} />}
|
||||
{!readOnly && remove && (
|
||||
<Dialog
|
||||
title={t('playlists.delete')}
|
||||
onClose={() => {
|
||||
if (!deletion.isPending) setRemove(false);
|
||||
}}
|
||||
footer={
|
||||
<>
|
||||
<Button disabled={deletion.isPending} onClick={() => setRemove(false)}>{t('form.cancel')}</Button>
|
||||
<Button variant="danger" busy={deletion.isPending} onClick={() => deletion.mutate()}>{t('playlists.delete')}</Button>
|
||||
</>}><p>{t('playlists.delete_confirm', { name: playlist.name })}</p><FormError>{deletion.error ? errorText(deletion.error) : null}</FormError></Dialog>}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p>{t('playlists.delete_confirm', { name: playlist.name })}</p>
|
||||
<FormError>{deletion.error ? errorText(deletion.error) : null}</FormError>
|
||||
</Dialog>
|
||||
)}
|
||||
</>;
|
||||
}
|
||||
|
||||
function PlaylistCard({ item }: { item: components['schemas']['PlaylistSummary'] }) {
|
||||
const { t } = useTranslation();
|
||||
const session = useSession();
|
||||
const player = usePlayer();
|
||||
const play = (e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void (async () => {
|
||||
const full = unwrap(await session.client.GET('/api/v1/me/playlists/{id}', { params: { path: { id: item.id } } }));
|
||||
const tracks = full.tracks.filter((x) => x.available);
|
||||
if (tracks.length) player.playList(tracks, 0, { type: 'collection', id: item.id, label: item.name });
|
||||
})();
|
||||
};
|
||||
return (
|
||||
<Link to="/playlist/$id" params={{ id: item.id }} className={p.card}>
|
||||
<span className={p.coverWrap}>
|
||||
<Cover album={item} size="100%" />
|
||||
{item.track_count > 0 && (
|
||||
<button type="button" className={p.play} aria-label={t('catalog.play')} onClick={play}>
|
||||
<Icon src={playIcon} size={22} />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
<strong>{item.name}</strong>
|
||||
<span>{t('catalog.track_count', { count: item.track_count })} · {formatDuration(item.duration_ms)}</span>
|
||||
{item.description && <span className={p.description}>{item.description}</span>}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,8 @@ import { useTranslation } from 'react-i18next';
|
||||
import { useSession } from '../app/session';
|
||||
import { AlbumGrid, ArtistChip, TrackList } from '../entities/catalog';
|
||||
import { useErrorText } from '../shared/lib/errors';
|
||||
import { Button, FormError } from '../shared/ui/ui';
|
||||
import { searchIcon } from '../shared/ui/icons';
|
||||
import { Button, EmptyState, FormError, PageSkeleton } from '../shared/ui/ui';
|
||||
import s from './page.module.css';
|
||||
import c from './catalog.module.css';
|
||||
|
||||
@@ -68,7 +69,11 @@ export function SearchPage({ q, type }: { q: string; type: SearchType }) {
|
||||
</div>
|
||||
|
||||
<FormError>{results.error ? errorText(results.error) : null}</FormError>
|
||||
{empty && <div className={s.empty}>{t('search.nothing')}</div>}
|
||||
{query === '' && <EmptyState icon={searchIcon}>{t('search.type_query')}</EmptyState>}
|
||||
{query !== '' && results.isPending && <PageSkeleton />}
|
||||
{empty && (
|
||||
<EmptyState icon={searchIcon}>{t('search.nothing')}</EmptyState>
|
||||
)}
|
||||
|
||||
{artists.length > 0 && (
|
||||
<section className={c.section}>
|
||||
|
||||
@@ -12,6 +12,8 @@ import { formatDateTime } from '../shared/lib/format';
|
||||
import { Button, Field, FormError, Segmented } from '../shared/ui/ui';
|
||||
import { LanguageSwitch } from '../widgets/LanguageSwitch';
|
||||
import s from './page.module.css';
|
||||
import { Onboarding } from './Onboarding';
|
||||
import { DesktopOfflineSection, DesktopUpdateButton } from '../features/desktop/DesktopFeatures';
|
||||
|
||||
type Theme = NonNullable<components['schemas']['UiPrefs']['theme']>;
|
||||
type WaveVariant = NonNullable<components['schemas']['UiPrefs']['wave_variant']>;
|
||||
@@ -24,7 +26,10 @@ export function SettingsPage() {
|
||||
<h1>{t('settings.title')}</h1>
|
||||
</div>
|
||||
<ProfileSection />
|
||||
<RecommendationSettings />
|
||||
<AppearanceSection />
|
||||
<DesktopOfflineSection />
|
||||
<DesktopUpdateButton />
|
||||
<PasswordSection />
|
||||
<SessionsSection />
|
||||
</div>
|
||||
@@ -357,3 +362,17 @@ function SessionsSection() {
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RecommendationSettings() {
|
||||
const { t } = useTranslation();
|
||||
const session = useSession();
|
||||
const queryClient = useQueryClient();
|
||||
const [editing, setEditing] = useState(false);
|
||||
const errorText = useErrorText();
|
||||
const options = useQuery({ queryKey: ['onboarding'], queryFn: async () => unwrap(await session.client.GET('/api/v1/onboarding')), staleTime: 0 });
|
||||
return <section className={s.section}>
|
||||
{editing && options.data ? <Onboarding key={JSON.stringify(options.data.choice)} options={options.data} editing onDone={() => { setEditing(false); void queryClient.invalidateQueries({ queryKey: ['onboarding'] }); }} />
|
||||
: <Button busy={options.isFetching} onClick={() => { void options.refetch().then((result) => { if (result.data && !result.error) setEditing(true); }); }}>{t('onboarding.edit')}</Button>}
|
||||
<FormError>{options.error ? errorText(options.error) : null}</FormError>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSession } from '../app/session';
|
||||
import { useErrorText } from '../shared/lib/errors';
|
||||
import { FormError } from '../shared/ui/ui';
|
||||
import s from './page.module.css';
|
||||
import g from './genius.module.css';
|
||||
|
||||
export function TrackGenius({ id }: { id: string }) {
|
||||
const session = useSession();
|
||||
const { t } = useTranslation();
|
||||
const errorText = useErrorText();
|
||||
const query = useQuery({
|
||||
queryKey: ['track-genius', id],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/tracks/{id}/genius', { params: { path: { id } } })),
|
||||
refetchInterval: (q) => ['pending', 'processing'].includes(q.state.data?.status ?? '') ? 10000 : false,
|
||||
});
|
||||
const data = query.data;
|
||||
if (data?.status === 'disabled') return null;
|
||||
return <section className={s.section}>
|
||||
<FormError>{query.error ? errorText(query.error) : null}</FormError>
|
||||
{query.isPending && <p>{t('genius.loading')}</p>}
|
||||
{data?.description && <><h2>{t('genius.about')}</h2><p className={g.lyrics}>{data.description}</p></>}
|
||||
<div className={s.head}><h2>{t('genius.lyrics')}</h2>{data?.source_url && <a href={data.source_url} target="_blank" rel="noopener noreferrer">Genius ↗</a>}</div>
|
||||
{data && (data.lyrics ? <div className={g.lyrics}>{data.lyrics}</div> : <p className={s.subtitle}>{['pending', 'processing'].includes(data.status) ? t('genius.pending_text') : t('genius.no_lyrics')}</p>)}
|
||||
{!!data?.annotations.length && <>
|
||||
<h2>{t('genius.explanations')}</h2>
|
||||
{data.annotations.map((a, i) => <details className={g.annotation} key={`${a.url}-${i}`}>
|
||||
<summary>{a.fragment}{a.verified && <span className={g.badge}>{t('genius.verified')}</span>}</summary>
|
||||
<p className={g.lyrics}>{a.text}</p>
|
||||
<p className={s.subtitle}>{a.authors}{a.url && <> · <a href={a.url} target="_blank" rel="noopener noreferrer">Genius ↗</a></>}</p>
|
||||
</details>)}
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
@@ -4,35 +4,77 @@ import { Link } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSession } from '../app/session';
|
||||
import { ArtistLinks, Cover, TrackList } from '../entities/catalog';
|
||||
import { ArtistLinks, Cover, coverSrc } from '../entities/catalog';
|
||||
import { AddToPlaylist } from '../entities/playlists';
|
||||
import { usePlayer, usePlayerState } from '../player/context';
|
||||
import { formatDuration } from '../shared/lib/format';
|
||||
import { pauseIcon, playIcon } from '../shared/ui/icons';
|
||||
import { Button, PageSkeleton } from '../shared/ui/ui';
|
||||
import { NotFound } from './NotFound';
|
||||
import s from './page.module.css';
|
||||
import c from './catalog.module.css';
|
||||
import { TrackGenius } from './TrackGenius';
|
||||
|
||||
export function TrackPage({ id }: { id: string }) {
|
||||
const { t } = useTranslation();
|
||||
const session = useSession();
|
||||
const player = usePlayer();
|
||||
const st = usePlayerState();
|
||||
const track = useQuery({
|
||||
queryKey: ['track', id],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/tracks/{id}', { params: { path: { id } } })),
|
||||
});
|
||||
if (track.isError) return <NotFound error={track.error} />;
|
||||
const tr = track.data;
|
||||
if (track.isPending) {
|
||||
return (
|
||||
<div className={s.page}>
|
||||
<PageSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (track.isError) return <NotFound error={track.error} />;
|
||||
const tr = track.data;
|
||||
if (!tr) return null;
|
||||
const ctx = { type: 'queue' as const };
|
||||
const current = st.track?.id === tr.id;
|
||||
const playing = current && st.playing;
|
||||
return (
|
||||
<div className={s.page}>
|
||||
<div className={c.listen}>
|
||||
<header className={c.hero}>
|
||||
{tr && <Cover album={tr.album} size={200} />}
|
||||
{tr.album.cover_url && (
|
||||
<span className={c.heroBg} aria-hidden>
|
||||
<img src={coverSrc(tr.album.cover_url, 300)} alt="" />
|
||||
</span>
|
||||
)}
|
||||
<Cover album={tr.album} size={280} className={c.heroCover} />
|
||||
<div className={c.heroBody}>
|
||||
<span className={c.kind}>{t('player.track_page')}</span>
|
||||
<h1 className={c.heroTitle}>{tr?.title ?? '…'}</h1>
|
||||
{tr && <>
|
||||
<span className={c.heroMeta}><ArtistLinks artists={tr.artists} /> · {formatDuration(tr.duration_ms)}</span>
|
||||
<Link to="/album/$id" params={{ id: tr.album.id }}>{tr.album.title}</Link>
|
||||
</>}
|
||||
<h1 className={c.heroTitle}>{tr.title}</h1>
|
||||
<span className={c.heroMeta}>
|
||||
<ArtistLinks artists={tr.artists} /> · {formatDuration(tr.duration_ms)}
|
||||
</span>
|
||||
<Link to="/album/$id" params={{ id: tr.album.id }}>
|
||||
{tr.album.title}
|
||||
</Link>
|
||||
<div className={c.heroActions}>
|
||||
{tr.available && (
|
||||
<Button
|
||||
variant="primary"
|
||||
className={c.pill}
|
||||
icon={playing ? pauseIcon : playIcon}
|
||||
onClick={() => (current ? player.toggle() : player.playList([tr], 0, ctx))}
|
||||
>
|
||||
{t(playing ? 'player.pause' : 'catalog.play')}
|
||||
</Button>
|
||||
)}
|
||||
<AddToPlaylist trackIds={[tr.id]} />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
{tr && <TrackList tracks={[tr]} context={{ type: 'queue' }} />}
|
||||
<div className={c.listenLyrics}>
|
||||
<TrackGenius id={id} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import s from '../page.module.css';
|
||||
import { UploadSettingsSection } from './UploadQueuePage';
|
||||
import { UploadSettingsSection } from '../../features/uploads/UploadSettingsSection';
|
||||
|
||||
/** «Настройки» админки: параметры сервера, которые меняет администратор (пока — очередь на добавление). */
|
||||
export function AdminSettingsPage() {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { AuthSession } from '@pipu/core';
|
||||
import { createI18n } from '@pipu/i18n';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { cleanup, render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { SessionProvider } from '../../app/session';
|
||||
import { AnalysisErrorsDialog } from './AnalysisErrorsDialog';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
async function fixture(mode: 'pages' | 'empty' | 'error' = 'pages') {
|
||||
const cursors: (string | null)[] = [];
|
||||
const session = new AuthSession({ baseUrl: 'http://localhost', clientType: 'web', fetch: async (input, init) => {
|
||||
const req = new Request(input, init);
|
||||
const cursor = new URL(req.url).searchParams.get('cursor');
|
||||
cursors.push(cursor);
|
||||
if (mode === 'error') return new Response(JSON.stringify({ code: 'server.error' }), { status: 500 });
|
||||
return new Response(JSON.stringify({
|
||||
items: mode === 'empty' ? [] : cursor ? [{ track_id: 'second', title: 'Без файла', source_id: null, source_name: null, rel_path: null, error: '' }]
|
||||
: [{ track_id: 'first', title: 'Короткий трек', source_id: 'source', source_name: 'Base', rel_path: 'Исполнитель/Альбом/track.mp3', error: 'audio is shorter than 1 s' }],
|
||||
next_cursor: mode === 'pages' && !cursor ? 'next-page' : null,
|
||||
}), { headers: { 'Content-Type': 'application/json' } });
|
||||
} });
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const i18n = await createI18n('ru');
|
||||
const close = vi.fn();
|
||||
render(<I18nextProvider i18n={i18n}><SessionProvider session={session}><QueryClientProvider client={client}>
|
||||
<AnalysisErrorsDialog onClose={close} />
|
||||
</QueryClientProvider></SessionProvider></I18nextProvider>);
|
||||
return { close, cursors, user: userEvent.setup() };
|
||||
}
|
||||
|
||||
it('shows storage, path and error, loads the next page and closes with Escape', async () => {
|
||||
const { user, cursors, close } = await fixture();
|
||||
expect(screen.getByRole('dialog', { name: 'Ошибки аудиоанализа' })).toBeVisible();
|
||||
expect(await screen.findByText('Исполнитель/Альбом/track.mp3')).toBeVisible();
|
||||
expect(screen.getByText('Хранилище: Base')).toBeVisible();
|
||||
expect(screen.getByText('audio is shorter than 1 s')).toBeVisible();
|
||||
await user.click(screen.getByRole('button', { name: 'Показать ещё' }));
|
||||
expect(await screen.findByText('В библиотеке больше нет файла этого трека.')).toBeVisible();
|
||||
expect(screen.getByText('Короткий трек')).toBeVisible();
|
||||
expect(cursors).toEqual([null, 'next-page']);
|
||||
expect(screen.queryByRole('button', { name: 'Показать ещё' })).not.toBeInTheDocument();
|
||||
await user.keyboard('{Escape}');
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('shows an empty state after failed jobs have been retried', async () => {
|
||||
await fixture('empty');
|
||||
expect(await screen.findByText('Неудавшихся задач анализа нет.')).toBeVisible();
|
||||
});
|
||||
|
||||
it('shows a request failure without claiming the list is empty', async () => {
|
||||
await fixture('error');
|
||||
expect(await screen.findByRole('alert')).toBeVisible();
|
||||
expect(screen.queryByText('Неудавшихся задач анализа нет.')).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSession } from '../../app/session';
|
||||
import { useErrorText } from '../../shared/lib/errors';
|
||||
import { Button, Dialog, FormError } from '../../shared/ui/ui';
|
||||
import s from './library.module.css';
|
||||
|
||||
export function AnalysisErrorsDialog({ onClose }: { onClose: () => void }) {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const session = useSession();
|
||||
const errorText = useErrorText();
|
||||
const errors = useInfiniteQuery({
|
||||
queryKey: ['analysis-errors'],
|
||||
initialPageParam: undefined as string | undefined,
|
||||
queryFn: async ({ pageParam }) => unwrap(await session.client.GET('/api/v1/admin/library/analysis/errors', {
|
||||
params: { query: { limit: 50, cursor: pageParam } },
|
||||
})),
|
||||
getNextPageParam: (page) => page.next_cursor ?? undefined,
|
||||
});
|
||||
const items = errors.data?.pages.flatMap((page) => page.items) ?? [];
|
||||
|
||||
return <Dialog title={t('library.analysis_errors_title')} onClose={onClose}
|
||||
footer={<Button onClick={onClose}>{t('common:form.close')}</Button>}>
|
||||
<p>{t('library.analysis_errors_hint')}</p>
|
||||
{errors.isPending && <p role="status">{t('common:loading')}</p>}
|
||||
<FormError>{errors.error ? errorText(errors.error) : null}</FormError>
|
||||
{errors.isSuccess && items.length === 0 && <p>{t('library.analysis_errors_empty')}</p>}
|
||||
{items.length > 0 && <ul className={s.analysisErrors}>
|
||||
{items.map((item) => <li key={item.track_id}>
|
||||
<strong>{item.title}</strong>
|
||||
{item.source_name && <span className={s.scanSummary}>{t('library.analysis_error_source', { name: item.source_name })}</span>}
|
||||
<code className={s.analysisPath}>{item.rel_path ?? t('library.analysis_error_no_file')}</code>
|
||||
<span className={s.scanError}>{item.error || t('library.analysis_error_unknown')}</span>
|
||||
</li>)}
|
||||
</ul>}
|
||||
{errors.hasNextPage && <Button busy={errors.isFetchingNextPage} onClick={() => void errors.fetchNextPage()}>{t('library.analysis_errors_more')}</Button>}
|
||||
</Dialog>;
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { useSession } from '../../app/session';
|
||||
import { useErrorText } from '../../shared/lib/errors';
|
||||
import { formatDateTime } from '../../shared/lib/format';
|
||||
import { Button, FormError } from '../../shared/ui/ui';
|
||||
import { Button, EmptyState, FormError, PageSkeleton } from '../../shared/ui/ui';
|
||||
import s from '../page.module.css';
|
||||
|
||||
type Entry = components['schemas']['AuditEntry'];
|
||||
@@ -67,8 +67,8 @@ export function AuditPage() {
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{list.isSuccess && entries.length === 0 && <div className={s.empty}>{t('audit.empty')}</div>}
|
||||
{list.isPending && <div className={s.empty}>{t('common:loading')}</div>}
|
||||
{list.isSuccess && entries.length === 0 && <EmptyState>{t('audit.empty')}</EmptyState>}
|
||||
{list.isPending && <PageSkeleton />}
|
||||
</div>
|
||||
{list.hasNextPage && (
|
||||
<Button className={s.more} busy={list.isFetchingNextPage} onClick={() => void list.fetchNextPage()}>
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { AuthSession } from '@pipu/core';
|
||||
import { createI18n } from '@pipu/i18n';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { cleanup, render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import { afterEach, expect, it } from 'vitest';
|
||||
import { SessionProvider } from '../../app/session';
|
||||
import { GeniusPanel } from './GeniusPanel';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const initial = {
|
||||
configured: true, paused: false, running: true,
|
||||
total: 100, pending: 80, matched: 17, lyrics: 15, annotations: 5, images: 17,
|
||||
unmatched: 2, errors: 1, last_error: '', cooldown_until: '2000-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
async function fixture(overrides: Partial<typeof initial> = {}) {
|
||||
let data = { ...initial, ...overrides };
|
||||
const actions: string[] = [];
|
||||
const session = new AuthSession({ baseUrl: 'http://localhost', clientType: 'web', fetch: async (url, init) => {
|
||||
const request = new Request(url, init);
|
||||
if (request.method === 'POST') {
|
||||
const { action } = await request.json() as { action: string };
|
||||
actions.push(action);
|
||||
data = { ...data, paused: action === 'pause' };
|
||||
}
|
||||
return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } });
|
||||
} });
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
|
||||
client.setQueryData(['genius-stats'], data);
|
||||
const i18n = await createI18n('ru');
|
||||
render(<I18nextProvider i18n={i18n}><SessionProvider session={session}><QueryClientProvider client={client}>
|
||||
<GeniusPanel />
|
||||
</QueryClientProvider></SessionProvider></I18nextProvider>);
|
||||
return { actions, user: userEvent.setup() };
|
||||
}
|
||||
|
||||
it.each<[Partial<typeof initial>, string]>([
|
||||
[{}, 'Получение данных из Genius…'],
|
||||
[{ running: false }, 'Очередь ожидает обработки'],
|
||||
[{ paused: true }, 'Обработка приостановлена'],
|
||||
[{ cooldown_until: '2099-01-01T00:00:00Z' }, 'Ожидание после ограничения Genius'],
|
||||
[{ running: false, pending: 0 }, 'Ожидание новых треков'],
|
||||
])('shows queue state and progress for %j', async (overrides, status) => {
|
||||
await fixture(overrides);
|
||||
expect(screen.getByRole('status')).toHaveTextContent(status);
|
||||
const progress = screen.getByRole('progressbar', { name: 'Прогресс обработки Genius' });
|
||||
expect(progress).toHaveAttribute('max', '100');
|
||||
expect(progress).toHaveAttribute('value', String(100 - (overrides.pending ?? 80)));
|
||||
});
|
||||
|
||||
it('pauses and resumes the existing queue without requesting a retry', async () => {
|
||||
const { user, actions } = await fixture();
|
||||
await user.click(screen.getByRole('button', { name: 'Приостановить обработку' }));
|
||||
await user.click(await screen.findByRole('button', { name: 'Продолжить обработку' }));
|
||||
expect(actions).toEqual(['pause', 'start']);
|
||||
expect(screen.getByRole('progressbar')).toHaveAttribute('value', '20');
|
||||
});
|
||||
|
||||
it('explains the retry scope and sends the retry action', async () => {
|
||||
const { user, actions } = await fixture();
|
||||
expect(screen.getByText(/Повтор добавит в очередь только/)).toBeVisible();
|
||||
await user.click(screen.getByRole('button', { name: 'Добавить проблемные треки в очередь' }));
|
||||
expect(actions).toEqual(['retry']);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSession } from '../../app/session';
|
||||
import { useErrorText } from '../../shared/lib/errors';
|
||||
import { Button, FormError } from '../../shared/ui/ui';
|
||||
import s from '../page.module.css';
|
||||
import g from '../genius.module.css';
|
||||
|
||||
export function GeniusPanel() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const session = useSession();
|
||||
const queries = useQueryClient();
|
||||
const errorText = useErrorText();
|
||||
const stats = useQuery({
|
||||
queryKey: ['genius-stats'],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/admin/genius')),
|
||||
refetchInterval: 5000,
|
||||
});
|
||||
const control = useMutation({
|
||||
mutationFn: async (action: 'start' | 'pause' | 'retry') =>
|
||||
unwrap(await session.client.POST('/api/v1/admin/genius', { body: { action } })),
|
||||
onSuccess: (data) => { queries.setQueryData(['genius-stats'], data); },
|
||||
});
|
||||
const data = stats.data;
|
||||
const cooling = data && Date.parse(data.cooldown_until) > Date.now();
|
||||
const state = !data ? t('genius.loading') : !data.configured ? t('genius.disabled') : data.paused ? t('genius.paused') : cooling ? t('genius.cooldown') : data.running ? t('genius.running') : data.pending > 0 ? t('genius.queued') : t('genius.waiting');
|
||||
const processed = data ? Math.max(0, data.total - data.pending) : 0;
|
||||
const formatNumber = (value: number) => value.toLocaleString(i18n.language);
|
||||
return <section className={s.section} aria-label="Genius">
|
||||
<div className={s.head}><h2>Genius</h2><span role="status">{state}</span></div>
|
||||
<p className={s.subtitle}>{t('genius.description')}</p>
|
||||
<FormError>{stats.error ? errorText(stats.error) : control.error ? errorText(control.error) : null}</FormError>
|
||||
{data && <>
|
||||
{!data.configured && <p>{t('genius.configure')}</p>}
|
||||
{data.total > 0 && <div className={g.progress}>
|
||||
<span>{t('genius.progress', { processed: formatNumber(processed), total: formatNumber(data.total) })}</span>
|
||||
<progress aria-label={t('genius.progress_label')} value={processed} max={data.total} />
|
||||
<p className={s.subtitle}>{t('genius.progress_hint')}</p>
|
||||
</div>}
|
||||
<dl className={g.stats}>
|
||||
{(['total', 'pending', 'matched', 'lyrics', 'annotations', 'images', 'unmatched', 'errors'] as const).map((key) =>
|
||||
<div key={key}><dt>{t(`genius.${key}`)}</dt><dd>{formatNumber(data[key])}</dd></div>)}
|
||||
</dl>
|
||||
{data.last_error && <p role="alert">{t('genius.last_error')}: {data.last_error === 'http_401' ? t('genius.token_error') : data.last_error === 'http_403' ? t('genius.access_error') : data.last_error === 'http_429' ? t('genius.cooldown') : data.last_error === 'lyrics_unavailable' ? t('genius.no_lyrics') : t('genius.request_error')}</p>}
|
||||
{cooling && <p>{t('genius.resume_at')}: {new Date(data.cooldown_until).toLocaleString()}</p>}
|
||||
<div className={g.actions}>
|
||||
<Button disabled={!data.configured || control.isPending} onClick={() => control.mutate(data.paused ? 'start' : 'pause')}>{t(data.paused ? 'genius.start' : 'genius.pause')}</Button>
|
||||
<Button disabled={!data.configured || control.isPending || data.errors + data.unmatched === 0} onClick={() => control.mutate('retry')}>{t('genius.retry')}</Button>
|
||||
</div>
|
||||
<p className={s.subtitle}>{t('genius.controls_hint')}</p>
|
||||
<p className={s.subtitle}>{t('genius.retry_hint')}</p>
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useId } from 'react';
|
||||
import { useId, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSession, useUser } from '../../app/session';
|
||||
@@ -10,6 +10,7 @@ import { Button, FormError } from '../../shared/ui/ui';
|
||||
import s from '../page.module.css';
|
||||
import l from './library.module.css';
|
||||
import { ScanLine, StatusBadge } from './ScanStatus';
|
||||
import { AnalysisErrorsDialog } from './AnalysisErrorsDialog';
|
||||
|
||||
/** Состояние библиотеки: счётчики, хранилища и сканы (admin, moderator), ошибки чтения (admin). */
|
||||
export function LibraryPage() {
|
||||
@@ -18,6 +19,7 @@ export function LibraryPage() {
|
||||
const user = useUser();
|
||||
const errorText = useErrorText();
|
||||
const admin = user.role === 'admin';
|
||||
const [showAnalysisErrors, setShowAnalysisErrors] = useState(false);
|
||||
|
||||
const status = useQuery({
|
||||
queryKey: ['library-status'],
|
||||
@@ -27,6 +29,7 @@ export function LibraryPage() {
|
||||
const errors = useQuery({
|
||||
queryKey: ['library-errors'],
|
||||
enabled: admin,
|
||||
refetchInterval: status.data?.sources.some((source) => source.scan?.running) ? 2000 : 15000,
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/admin/library/errors', { params: { query: { limit: 50 } } })),
|
||||
});
|
||||
const reindex = useMutation({
|
||||
@@ -35,7 +38,10 @@ export function LibraryPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const retry = useMutation({
|
||||
mutationFn: async () => unwrap(await session.client.POST('/api/v1/admin/library/analysis/retry')),
|
||||
onSuccess: () => void queryClient.invalidateQueries({ queryKey: ['library-status'] }),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['library-status'] });
|
||||
void queryClient.invalidateQueries({ queryKey: ['analysis-errors'] });
|
||||
},
|
||||
});
|
||||
const d = status.data;
|
||||
const tiles = d
|
||||
@@ -89,13 +95,17 @@ export function LibraryPage() {
|
||||
{d.analysis.top_error && <span className={l.errorDetail}>{d.analysis.top_error}</span>}
|
||||
</span>
|
||||
{admin && (
|
||||
<div className={l.analysisActions}>
|
||||
<Button onClick={() => setShowAnalysisErrors(true)}>{t('library.analysis_show_errors')}</Button>
|
||||
<Button variant="secondary" icon={refreshIcon} busy={retry.isPending} onClick={() => retry.mutate()}>
|
||||
{t('library.analysis_retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{d.analysis.analyzer_ver && <span className={l.scanSummary}>{t('library.analyzer', { ver: d.analysis.analyzer_ver })}</span>}
|
||||
{showAnalysisErrors && <AnalysisErrorsDialog onClose={() => setShowAnalysisErrors(false)} />}
|
||||
</section>
|
||||
)}
|
||||
{d && (
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { createI18n } from '@pipu/i18n';
|
||||
import { cleanup, render, screen } from '@testing-library/react';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import { afterEach, expect, it } from 'vitest';
|
||||
import { ScanLine } from './ScanStatus';
|
||||
|
||||
afterEach(cleanup);
|
||||
const scan: components['schemas']['ScanProgress'] = {
|
||||
running: true, full: false, started_at: '2026-10-22T12:00:00Z', finished_at: null,
|
||||
found: 12, to_process: 0, processed: 0, added: 0, updated: 0, moved: 0, missing: 0, errors: 0, error: null,
|
||||
phase: 'walking', walked_dirs: 4, current_dir: 'Artist/Album',
|
||||
};
|
||||
|
||||
async function fixture(overrides: Partial<typeof scan> = {}) {
|
||||
const i18n = await createI18n('ru');
|
||||
render(<I18nextProvider i18n={i18n}><ScanLine scan={{ ...scan, ...overrides }} lastScanAt={null} /></I18nextProvider>);
|
||||
}
|
||||
|
||||
it('shows changing folder and file counts during the walk without a misleading percentage', async () => {
|
||||
await fixture();
|
||||
expect(screen.getByText(/Проверено папок: 4 · найдено аудиофайлов: 12/)).toBeVisible();
|
||||
expect(screen.getByText('Текущая папка: Artist/Album')).toBeVisible();
|
||||
expect(screen.getByRole('progressbar')).not.toHaveAttribute('aria-valuenow');
|
||||
});
|
||||
|
||||
it('shows a percentage only once file processing has a known total', async () => {
|
||||
await fixture({ phase: 'processing', to_process: 12, processed: 3 });
|
||||
expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '25');
|
||||
expect(screen.queryByText(/Текущая папка/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([['preparing', 'Сопоставление файлов с библиотекой…'], ['finalizing', 'Завершение сканирования…']] as const)('labels the %s stage', async (phase, label) => {
|
||||
await fixture({ phase });
|
||||
expect(screen.getByText(label)).toBeVisible();
|
||||
expect(screen.getByRole('progressbar')).not.toHaveAttribute('aria-valuenow');
|
||||
});
|
||||
|
||||
it('supports servers without the new progress fields', async () => {
|
||||
await fixture({ phase: undefined, walked_dirs: undefined, current_dir: undefined, found: 0 });
|
||||
expect(screen.getByText('Обход папок…')).toBeVisible();
|
||||
});
|
||||
@@ -19,14 +19,22 @@ export function ScanLine({ scan, lastScanAt }: { scan: ScanProgress | null; last
|
||||
const { t, i18n } = useTranslation('admin');
|
||||
const id = useId();
|
||||
if (scan?.running) {
|
||||
const phase = scan.phase ?? (scan.found === 0 ? 'walking' : scan.to_process > 0 ? 'processing' : 'preparing');
|
||||
const determinate = phase === 'processing' && scan.to_process > 0;
|
||||
const pct = scan.to_process > 0 ? Math.round((scan.processed / scan.to_process) * 100) : 0;
|
||||
const state = phase === 'walking'
|
||||
? scan.walked_dirs === undefined ? t('sources.scan_walking') : t('sources.scan_walk_progress', { dirs: scan.walked_dirs.toLocaleString(i18n.language), found: scan.found.toLocaleString(i18n.language) })
|
||||
: phase === 'preparing' ? t('sources.scan_preparing')
|
||||
: phase === 'finalizing' ? t('sources.scan_finalizing')
|
||||
: t('sources.scanning', { processed: scan.processed, total: scan.to_process });
|
||||
return (
|
||||
<div className={s.scan}>
|
||||
<div className={s.scanText} id={id}>
|
||||
{scan.found === 0 ? t('sources.scan_walking') : t('sources.scanning', { processed: scan.processed, total: scan.to_process })}
|
||||
{state}
|
||||
</div>
|
||||
<div className={s.bar} role="progressbar" aria-labelledby={id} aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
|
||||
<span style={{ width: `${pct}%` }} />
|
||||
{phase === 'walking' && scan.current_dir && <div className={s.scanPath} title={scan.current_dir}>{t('sources.scan_current_dir', { path: scan.current_dir })}</div>}
|
||||
<div className={cx(s.bar, !determinate && s.indeterminate)} role="progressbar" aria-labelledby={id} aria-valuenow={determinate ? pct : undefined} aria-valuemin={0} aria-valuemax={100}>
|
||||
<span style={determinate ? { width: `${pct}%` } : undefined} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { AuthSession } from '@pipu/core';
|
||||
import { createI18n } from '@pipu/i18n';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { SessionProvider } from '../../app/session';
|
||||
import { mobileFixtures } from '../../test/mobileFixtures';
|
||||
import { SourceDialog } from './SourcesPage';
|
||||
|
||||
afterEach(cleanup);
|
||||
type Source = components['schemas']['Source'];
|
||||
const base = (mobileFixtures['/api/v1/admin/sources'] as { items: Source[] }).items[0]!;
|
||||
|
||||
async function fixture(source: Source | null = { ...base, excluded_dirs: ['Downloads_PumpEars'] }, reject = false) {
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
const session = new AuthSession({ baseUrl: 'http://localhost', clientType: 'web', fetch: async (input, init) => {
|
||||
const req = new Request(input, init);
|
||||
if (req.method === 'PATCH' || req.method === 'POST') {
|
||||
const body = await req.json() as Record<string, unknown>;
|
||||
bodies.push(body);
|
||||
return new Response(JSON.stringify(reject
|
||||
? { code: 'validation.excluded_dirs_invalid', errors: [{ field: 'excluded_dirs', code: 'validation.excluded_dirs_invalid' }] }
|
||||
: { ...base, ...body }), { status: reject ? 422 : 200, headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
return new Response(JSON.stringify({ path: '', dirs: [] }), { headers: { 'Content-Type': 'application/json' } });
|
||||
} });
|
||||
const i18n = await createI18n('ru');
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const close = vi.fn();
|
||||
render(<I18nextProvider i18n={i18n}><SessionProvider session={session}><QueryClientProvider client={client}>
|
||||
<SourceDialog source={source} onClose={close} />
|
||||
</QueryClientProvider></SessionProvider></I18nextProvider>);
|
||||
return { bodies, close, user: userEvent.setup() };
|
||||
}
|
||||
|
||||
it('loads and saves one excluded path per line', async () => {
|
||||
const { bodies, close, user } = await fixture();
|
||||
const input = screen.getByLabelText('Не сканировать папки');
|
||||
expect(input).toHaveValue('Downloads_PumpEars');
|
||||
await user.type(input, '\nArtist/Samples\n');
|
||||
await user.click(screen.getByRole('button', { name: 'Сохранить' }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalledOnce());
|
||||
expect(bodies[0]?.excluded_dirs).toEqual(['Downloads_PumpEars', 'Artist/Samples']);
|
||||
});
|
||||
|
||||
it('clears the list explicitly so excluded folders can be scanned again', async () => {
|
||||
const { bodies, close, user } = await fixture();
|
||||
await user.clear(screen.getByLabelText('Не сканировать папки'));
|
||||
await user.click(screen.getByRole('button', { name: 'Сохранить' }));
|
||||
await waitFor(() => expect(close).toHaveBeenCalledOnce());
|
||||
expect(bodies[0]?.excluded_dirs).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps invalid paths in the editor and displays the server validation', async () => {
|
||||
const { user, close } = await fixture({ ...base, excluded_dirs: ['../outside'] }, true);
|
||||
await user.click(screen.getByRole('button', { name: 'Сохранить' }));
|
||||
await waitFor(() => expect(screen.getByLabelText('Не сканировать папки')).toHaveAttribute('aria-invalid', 'true'));
|
||||
expect(screen.getByLabelText('Не сканировать папки')).toHaveValue('../outside');
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -2,13 +2,14 @@ import type { components } from '@pipu/api-client';
|
||||
import { unwrap } from '@pipu/core';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useId, useState, type FormEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSession } from '../../app/session';
|
||||
import { useSession, useUser } from '../../app/session';
|
||||
import { GeniusPanel } from './GeniusPanel';
|
||||
import { useErrorText, useFieldError } from '../../shared/lib/errors';
|
||||
import { addIcon, chevronRightIcon, folderIcon, moreIcon, refreshIcon } from '../../shared/ui/icons';
|
||||
import { Button, Dialog, Field, FormError, Icon, Menu, Segmented, type MenuItem } from '../../shared/ui/ui';
|
||||
import { Button, Dialog, EmptyState, Field, FormError, Icon, Menu, Segmented, type MenuItem } from '../../shared/ui/ui';
|
||||
import s from '../page.module.css';
|
||||
import l from './library.module.css';
|
||||
import { ScanLine, StatusBadge } from './ScanStatus';
|
||||
@@ -19,6 +20,7 @@ type TestResult = components['schemas']['SourceTestResult'];
|
||||
const SCAN_POLL_MS = 2000;
|
||||
|
||||
export function SourcesPage() {
|
||||
const user = useUser();
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const session = useSession();
|
||||
const errorText = useErrorText();
|
||||
@@ -43,7 +45,12 @@ export function SourcesPage() {
|
||||
</Button>
|
||||
</div>
|
||||
<FormError>{sources.error ? errorText(sources.error) : null}</FormError>
|
||||
{sources.isSuccess && sources.data.length === 0 && <div className={s.empty}>{t('sources.empty')}</div>}
|
||||
{user.role === 'admin' && <GeniusPanel />}
|
||||
{sources.isSuccess && sources.data.length === 0 && (
|
||||
<EmptyState icon={folderIcon} action={<Button variant="primary" onClick={() => setEditing('new')}>{t('sources.add')}</Button>}>
|
||||
{t('sources.empty')}
|
||||
</EmptyState>
|
||||
)}
|
||||
<div className={l.list}>
|
||||
{sources.data?.map((src) => (
|
||||
<SourceCard key={src.id} source={src} onEdit={() => setEditing(src)} />
|
||||
@@ -113,6 +120,7 @@ function SourceCard({ source, onEdit }: { source: Source; onEdit: () => void })
|
||||
{source.accepts_uploads && <span className={l.typeBadge}>{t('write_template.badge')}</span>}
|
||||
</div>
|
||||
<span className={l.location}>{location(source)}</span>
|
||||
{!!source.excluded_dirs?.length && <span className={s.note}>{t('sources.excluded_count', { count: source.excluded_dirs.length })}</span>}
|
||||
{source.status === 'error' && source.status_message && (
|
||||
<span className={l.message}>{source.status_message}</span>
|
||||
)}
|
||||
@@ -178,7 +186,7 @@ function SourceCard({ source, onEdit }: { source: Source; onEdit: () => void })
|
||||
|
||||
const INTERVALS = [0, 60, 360, 1440];
|
||||
|
||||
function SourceDialog({ source, onClose }: { source: Source | null; onClose: () => void }) {
|
||||
export function SourceDialog({ source, onClose }: { source: Source | null; onClose: () => void }) {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const session = useSession();
|
||||
const queryClient = useQueryClient();
|
||||
@@ -192,12 +200,15 @@ function SourceDialog({ source, onClose }: { source: Source | null; onClose: ()
|
||||
const [options, setOptions] = useState(source?.nfs_options ?? 'nfsvers=4.1,soft,timeo=150,retrans=3');
|
||||
const [priority, setPriority] = useState<'tags_first' | 'path_first'>(source?.tag_priority ?? 'tags_first');
|
||||
const [interval, setIntervalMin] = useState(source?.scan_interval_minutes ?? 0);
|
||||
const [excludedDirs, setExcludedDirs] = useState((source?.excluded_dirs ?? []).join('\n'));
|
||||
const excludedDirsId = useId();
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: async () => {
|
||||
const common = {
|
||||
name: name.trim(),
|
||||
tag_priority: priority,
|
||||
excluded_dirs: excludedDirs.split(/\r?\n/).map((dir) => dir.trim()).filter(Boolean),
|
||||
...(type === 'local'
|
||||
? { local_path: localPath }
|
||||
: { nfs_server: server.trim(), nfs_export: exportPath.trim(), nfs_options: options.trim() }),
|
||||
@@ -217,11 +228,14 @@ function SourceDialog({ source, onClose }: { source: Source | null; onClose: ()
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['sources'] });
|
||||
for (const key of ['library-status', 'library-errors', 'analysis-errors']) {
|
||||
void queryClient.invalidateQueries({ queryKey: [key] });
|
||||
}
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
const err = save.error;
|
||||
const fields = ['name', 'local_path', 'nfs_server', 'nfs_export', 'nfs_options'];
|
||||
const fields = ['name', 'local_path', 'nfs_server', 'nfs_export', 'nfs_options', 'excluded_dirs'];
|
||||
const general = err && !fields.some((f) => fieldError(err, f)) ? errorText(err) : null;
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
@@ -290,6 +304,18 @@ function SourceDialog({ source, onClose }: { source: Source | null; onClose: ()
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<div className={l.field}>
|
||||
<label htmlFor={excludedDirsId} className={l.label}>{t('sources.excluded_dirs')}</label>
|
||||
<textarea id={excludedDirsId} className={l.excludedDirs} rows={5}
|
||||
value={excludedDirs} onChange={(event) => setExcludedDirs(event.target.value)}
|
||||
disabled={source?.scan?.running ?? false}
|
||||
placeholder="Downloads_PumpEars"
|
||||
aria-invalid={!!fieldError(err, 'excluded_dirs')}
|
||||
aria-describedby={`${excludedDirsId}-hint`} />
|
||||
<span id={`${excludedDirsId}-hint`} className={s.note}>
|
||||
{fieldError(err, 'excluded_dirs') ?? t(source?.scan?.running ? 'sources.excluded_running' : 'sources.excluded_hint')}
|
||||
</span>
|
||||
</div>
|
||||
<div className={l.field}>
|
||||
<span className={l.label}>{t('sources.tag_priority')}</span>
|
||||
<Segmented
|
||||
|
||||
@@ -1,640 +1,3 @@
|
||||
import type { components } from '@pipu/api-client';
|
||||
import { ApiError, unwrap } from '@pipu/core';
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { UploadQueue } from '../../features/uploads/UploadQueue';
|
||||
|
||||
import { useSession } from '../../app/session';
|
||||
import { needsFormatAttention } from '../../features/uploads/files';
|
||||
import { useErrorText, useFieldError } from '../../shared/lib/errors';
|
||||
import { formatBytes, formatDateTime, formatDuration } from '../../shared/lib/format';
|
||||
import { checkIcon, closeIcon, editIcon, refreshIcon } from '../../shared/ui/icons';
|
||||
import { Button, cx, Dialog, Field, FormError, Icon } from '../../shared/ui/ui';
|
||||
import s from '../page.module.css';
|
||||
import { MOVING, QuotaMeter, UploadStatusBadge, useReasonText, type UploadFile, type UploadStatus } from '../uploads/common';
|
||||
import u from '../uploads/uploads.module.css';
|
||||
|
||||
type Meta = components['schemas']['UploadMeta'];
|
||||
type Settings = components['schemas']['UploadSettings'];
|
||||
|
||||
const TABS = {
|
||||
review: ['pending_review'],
|
||||
failed: ['import_failed'],
|
||||
progress: ['uploading', 'processing', 'approved', 'importing'],
|
||||
imported: ['imported'],
|
||||
declined: ['rejected', 'duplicate', 'invalid', 'withdrawn', 'expired'],
|
||||
} satisfies Record<string, UploadStatus[]>;
|
||||
type Tab = keyof typeof TABS;
|
||||
|
||||
/** «Очередь на добавление» (docs/uploads.md#8): рассмотрение по пачкам, правка метаданных, массовые решения. */
|
||||
export function UploadQueuePage() {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const session = useSession();
|
||||
const queryClient = useQueryClient();
|
||||
const errorText = useErrorText();
|
||||
const [tab, setTab] = useState<Tab>('review');
|
||||
const [onlyPossible, setOnlyPossible] = useState(false);
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const [editing, setEditing] = useState<UploadFile | null>(null);
|
||||
const [batchEdit, setBatchEdit] = useState<string | null>(null);
|
||||
const [rejecting, setRejecting] = useState(false);
|
||||
|
||||
const list = useInfiniteQuery({
|
||||
queryKey: ['admin-uploads', tab, onlyPossible],
|
||||
initialPageParam: undefined as string | undefined,
|
||||
queryFn: async ({ pageParam }) =>
|
||||
unwrap(
|
||||
await session.client.GET('/api/v1/admin/uploads', {
|
||||
params: {
|
||||
query: { status: [...TABS[tab]], possible_duplicate: onlyPossible || undefined, cursor: pageParam, limit: 100 },
|
||||
},
|
||||
}),
|
||||
),
|
||||
getNextPageParam: (p) => p.next_cursor ?? undefined,
|
||||
refetchInterval: (q) =>
|
||||
q.state.data?.pages.some((p) => p.items.some((it) => MOVING.includes(it.status))) ? 5000 : false,
|
||||
});
|
||||
const items = useMemo(() => list.data?.pages.flatMap((p) => p.items) ?? [], [list.data]);
|
||||
useEffect(() => setSelected(new Set()), [tab, onlyPossible]);
|
||||
|
||||
const refresh = async () => {
|
||||
setSelected(new Set());
|
||||
await queryClient.invalidateQueries({ queryKey: ['admin-uploads'] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['upload-quota'] });
|
||||
};
|
||||
const review = useMutation({
|
||||
mutationFn: async (v: { decision: 'approve' | 'reject'; ids: string[]; reason?: string }) =>
|
||||
unwrap(
|
||||
await session.client.POST('/api/v1/admin/uploads/review', {
|
||||
body: { file_ids: v.ids, decision: v.decision, reason: v.reason },
|
||||
}),
|
||||
),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
const retry = useMutation({
|
||||
mutationFn: async (id: string) =>
|
||||
unwrap(await session.client.POST('/api/v1/admin/uploads/files/{id}/retry', { params: { path: { id } } })),
|
||||
onSuccess: refresh,
|
||||
});
|
||||
const failed = review.data?.items.filter((r) => !r.ok) ?? [];
|
||||
|
||||
// Группировка по пачке: файлы одной загрузки (обычно альбом) рассматриваются вместе.
|
||||
const batches = useMemo(() => {
|
||||
const m = new Map<string, UploadFile[]>();
|
||||
for (const f of items) m.set(f.batch_id, [...(m.get(f.batch_id) ?? []), f]);
|
||||
return [...m.values()];
|
||||
}, [items]);
|
||||
const toggle = (ids: string[], on: boolean) =>
|
||||
setSelected((cur) => {
|
||||
const next = new Set(cur);
|
||||
for (const id of ids) {
|
||||
if (on) next.add(id);
|
||||
else next.delete(id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
const selectable = tab === 'review' || tab === 'failed';
|
||||
const ids = [...selected];
|
||||
|
||||
return (
|
||||
<div className={s.page}>
|
||||
<div className={s.head}>
|
||||
<div>
|
||||
<h1>{t('uploads.queue_title')}</h1>
|
||||
<p className={s.subtitle}>{t('uploads.queue_subtitle')}</p>
|
||||
</div>
|
||||
<QuotaMeter />
|
||||
</div>
|
||||
<div className={s.toolbar}>
|
||||
<div className={s.chips} role="group" aria-label={t('uploads.filter')}>
|
||||
{(Object.keys(TABS) as Tab[]).map((k) => (
|
||||
<button key={k} type="button" className={s.chip} aria-pressed={tab === k} onClick={() => setTab(k)}>
|
||||
{t(`uploads.tab_${k}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span style={{ flex: 1 }} />
|
||||
<label className={u.sub} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<input type="checkbox" checked={onlyPossible} onChange={(e) => setOnlyPossible(e.target.checked)} />
|
||||
{t('uploads.only_possible')}
|
||||
</label>
|
||||
</div>
|
||||
<FormError>{(list.error ?? review.error ?? retry.error) ? errorText(list.error ?? review.error ?? retry.error) : null}</FormError>
|
||||
{failed.length > 0 && (
|
||||
<FormError>{t('uploads.review_failed', { count: failed.length, reason: failed[0]?.error ? errorText(problemError(failed[0].error)) : '' })}</FormError>
|
||||
)}
|
||||
{list.isSuccess && items.length === 0 && <div className={s.empty}>{t('uploads.queue_empty')}</div>}
|
||||
|
||||
{batches.map((files) => (
|
||||
<BatchCard
|
||||
key={files[0]!.batch_id}
|
||||
files={files}
|
||||
selectable={selectable}
|
||||
selected={selected}
|
||||
onToggle={toggle}
|
||||
onEdit={setEditing}
|
||||
onEditBatch={setBatchEdit}
|
||||
onRetry={(id) => retry.mutate(id)}
|
||||
/>
|
||||
))}
|
||||
{list.hasNextPage && (
|
||||
<Button busy={list.isFetchingNextPage} onClick={() => void list.fetchNextPage()}>
|
||||
{t('uploads.load_more')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{ids.length > 0 && (
|
||||
<div className={u.bulk} role="region" aria-label={t('uploads.bulk')}>
|
||||
<span>{t('uploads.selected', { count: ids.length })}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<Button variant="ghost" onClick={() => setSelected(new Set())}>
|
||||
{t('common:form.cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" icon={closeIcon} onClick={() => setRejecting(true)}>
|
||||
{t('uploads.reject')}
|
||||
</Button>
|
||||
{tab === 'review' && (
|
||||
<Button variant="primary" icon={checkIcon} busy={review.isPending} onClick={() => review.mutate({ decision: 'approve', ids })}>
|
||||
{t('uploads.approve')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{batchEdit && (
|
||||
<BatchEditDialog
|
||||
batchId={batchEdit}
|
||||
onClose={() => setBatchEdit(null)}
|
||||
onSaved={() => {
|
||||
setBatchEdit(null);
|
||||
void refresh();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{editing && (
|
||||
<EditDialog
|
||||
file={editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={() => {
|
||||
review.reset();
|
||||
void refresh();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{rejecting && (
|
||||
<RejectDialog
|
||||
count={ids.length}
|
||||
busy={review.isPending}
|
||||
onClose={() => setRejecting(false)}
|
||||
onReject={(reason) => {
|
||||
setRejecting(false);
|
||||
review.mutate({ decision: 'reject', ids, reason });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Problem из ответа массового решения → объект, понятный useErrorText. */
|
||||
function problemError(p: components['schemas']['Problem']) {
|
||||
return new ApiError(p.status, p.code, p.params ?? {});
|
||||
}
|
||||
|
||||
function BatchCard({
|
||||
files,
|
||||
selectable,
|
||||
selected,
|
||||
onToggle,
|
||||
onEdit,
|
||||
onEditBatch,
|
||||
onRetry,
|
||||
}: {
|
||||
files: UploadFile[];
|
||||
selectable: boolean;
|
||||
selected: Set<string>;
|
||||
onToggle: (ids: string[], on: boolean) => void;
|
||||
onEdit: (f: UploadFile) => void;
|
||||
onEditBatch: (batchId: string) => void;
|
||||
onRetry: (id: string) => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation('admin');
|
||||
const first = files[0]!;
|
||||
const ids = files.map((f) => f.id);
|
||||
const all = ids.every((id) => selected.has(id));
|
||||
const size = files.reduce((n, f) => n + f.size_bytes, 0);
|
||||
return (
|
||||
<section className={u.batch} aria-label={t('uploads.batch_of', { author: first.author.username })}>
|
||||
<div className={u.batchHead}>
|
||||
{selectable && (
|
||||
<input type="checkbox" aria-label={t('uploads.select_batch')} checked={all} onChange={(e) => onToggle(ids, e.target.checked)} />
|
||||
)}
|
||||
<b>{first.author.username}</b>
|
||||
<span>{formatDateTime(first.created_at, i18n.language)}</span>
|
||||
<span>{t('uploads.batch_size', { count: files.length, size: formatBytes(size, i18n.language) })}</span>
|
||||
{first.batch_comment && <span className={u.comment}>«{first.batch_comment}»</span>}
|
||||
<span style={{ flex: 1 }} />
|
||||
{selectable && (
|
||||
<Button variant="ghost" onClick={() => onEditBatch(first.batch_id)}>
|
||||
{t('uploads.edit_batch')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{files.map((f) => (
|
||||
<QueueRow
|
||||
key={f.id}
|
||||
file={f}
|
||||
selectable={selectable}
|
||||
checked={selected.has(f.id)}
|
||||
onCheck={(on) => onToggle([f.id], on)}
|
||||
onEdit={() => onEdit(f)}
|
||||
onRetry={() => onRetry(f.id)}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function QueueRow({
|
||||
file: f,
|
||||
selectable,
|
||||
checked,
|
||||
onCheck,
|
||||
onEdit,
|
||||
onRetry,
|
||||
}: {
|
||||
file: UploadFile;
|
||||
selectable: boolean;
|
||||
checked: boolean;
|
||||
onCheck: (on: boolean) => void;
|
||||
onEdit: () => void;
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation('admin');
|
||||
const reason = useReasonText()(f.status_reason);
|
||||
const m = f.metadata;
|
||||
const quality = [
|
||||
f.format?.toUpperCase(),
|
||||
f.bitrate ? `${Math.round(f.bitrate / 1000)} kbps` : null,
|
||||
f.sample_rate ? `${(f.sample_rate / 1000).toFixed(1)} kHz` : null,
|
||||
f.bit_depth ? `${f.bit_depth} bit` : null,
|
||||
f.duration_ms ? formatDuration(f.duration_ms) : null,
|
||||
formatBytes(f.size_bytes, i18n.language),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
const editable = f.status === 'pending_review' || f.status === 'import_failed';
|
||||
return (
|
||||
<div className={u.queueRow}>
|
||||
{selectable ? (
|
||||
<input type="checkbox" aria-label={t('uploads.select_file', { name: f.original_name })} checked={checked} onChange={(e) => onCheck(e.target.checked)} />
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<div className={u.meta}>
|
||||
<span className={u.metaTitle}>{m ? `${m.artist} — ${m.title}` : f.original_name}</span>
|
||||
{m && (
|
||||
<span className={u.sub}>
|
||||
{[m.album, m.year, m.disc && m.disc > 1 ? t('uploads.disc', { n: m.disc }) : null, m.track ? `#${m.track}` : null, m.genre]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
{f.metadata_edited && ` · ${t('uploads.edited')}`}
|
||||
</span>
|
||||
)}
|
||||
<span className={u.sub}>{quality}</span>
|
||||
<span className={u.sub} title={f.client_rel_path ?? undefined}>
|
||||
{f.client_rel_path ?? f.original_name}
|
||||
</span>
|
||||
</div>
|
||||
<div className={u.meta}>
|
||||
<div className={u.flags}>
|
||||
<UploadStatusBadge status={f.status} />
|
||||
{needsFormatAttention(f.format, f.original_name) && (
|
||||
<span className={cx(s.badge, u.tone_warn)} title={t('uploads.format_attention')}>
|
||||
{t('uploads.flag_attention')}
|
||||
</span>
|
||||
)}
|
||||
{f.possible_duplicate && <span className={cx(s.badge, u.tone_warn)}>{t('uploads.flag_possible')}</span>}
|
||||
{f.quality_upgrade && <span className={cx(s.badge, u.tone_info)}>{t('uploads.flag_quality')}</span>}
|
||||
{f.matched_album_id ? (
|
||||
<span className={cx(s.badge, u.tone_info)}>{t('uploads.flag_existing_album')}</span>
|
||||
) : (
|
||||
m && <span className={cx(s.badge, u.tone_muted)}>{t('uploads.flag_new_album')}</span>
|
||||
)}
|
||||
</div>
|
||||
{f.target_rel_path && <span className={u.target}>{f.target_rel_path}</span>}
|
||||
{reason && <span className={f.status === 'pending_review' ? u.warn : u.bad}>{reason}</span>}
|
||||
{f.duplicate_level && f.status === 'duplicate' && (
|
||||
<span className={u.sub}>{t(`uploads.dup_level_${f.duplicate_level}`)}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className={u.rowActions}>
|
||||
{f.stream_url && (
|
||||
<audio controls preload="none" src={f.stream_url} aria-label={t('uploads.listen', { name: f.original_name })} />
|
||||
)}
|
||||
{editable && (
|
||||
<Button variant="ghost" aria-label={t('uploads.edit', { name: f.original_name })} onClick={onEdit}>
|
||||
<Icon src={editIcon} size={18} />
|
||||
</Button>
|
||||
)}
|
||||
{f.status === 'import_failed' && (
|
||||
<Button variant="ghost" icon={refreshIcon} onClick={onRetry}>
|
||||
{t('uploads.retry')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const EMPTY_META: Meta = { artist: '', albumartist: '', album: '', title: '', genre: '', year: null, track: null, disc: null };
|
||||
|
||||
function BatchEditDialog({ batchId, onClose, onSaved }: { batchId: string; onClose: () => void; onSaved: () => void }) {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const session = useSession();
|
||||
const errorText = useErrorText();
|
||||
const [artist, setArtist] = useState('');
|
||||
const [album, setAlbum] = useState('');
|
||||
const [year, setYear] = useState('');
|
||||
const [cover, setCover] = useState<string | null | undefined>(undefined);
|
||||
const save = useMutation({
|
||||
mutationFn: async () =>
|
||||
unwrap(
|
||||
await session.client.PATCH('/api/v1/admin/uploads/batches/{id}', {
|
||||
params: { path: { id: batchId } },
|
||||
body: {
|
||||
...(artist.trim() ? { artist: artist.trim() } : {}),
|
||||
...(album.trim() ? { album: album.trim() } : {}),
|
||||
...(year.trim() ? { year: Number.parseInt(year, 10) } : {}),
|
||||
...(cover !== undefined ? { cover_base64: cover } : {}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
onSuccess: onSaved,
|
||||
});
|
||||
const pickCover = (file: File | undefined) => {
|
||||
if (!file) {
|
||||
setCover(undefined);
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const data = String(reader.result ?? '');
|
||||
const comma = data.indexOf(',');
|
||||
setCover(comma >= 0 ? data.slice(comma + 1) : data);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
title={t('uploads.batch_edit_title')}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t('common:form.cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" busy={save.isPending} onClick={() => save.mutate()}>
|
||||
{t('uploads.save')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={s.sessions}>
|
||||
<p className={s.note}>{t('uploads.batch_edit_hint')}</p>
|
||||
<Field label={t('uploads.meta_artist')} value={artist} onChange={setArtist} maxLength={500} />
|
||||
<Field label={t('uploads.meta_album')} value={album} onChange={setAlbum} maxLength={500} />
|
||||
<Field label={t('uploads.meta_year')} value={year} inputMode="numeric" onChange={setYear} />
|
||||
<label className={s.sessions}>
|
||||
<span>{t('uploads.batch_cover')}</span>
|
||||
<input type="file" accept="image/jpeg,image/png,image/webp" onChange={(e) => pickCover(e.target.files?.[0])} />
|
||||
</label>
|
||||
<Button variant="ghost" onClick={() => setCover(null)}>
|
||||
{t('uploads.batch_cover_clear')}
|
||||
</Button>
|
||||
<FormError>{save.error ? errorText(save.error) : null}</FormError>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function EditDialog({ file, onClose, onSaved }: { file: UploadFile; onClose: () => void; onSaved: () => void }) {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const session = useSession();
|
||||
const errorText = useErrorText();
|
||||
const fieldError = useFieldError();
|
||||
const [m, setM] = useState<Meta>(file.metadata ?? EMPTY_META);
|
||||
const [source, setSource] = useState(file.target_source_id ?? '');
|
||||
const sources = useQuery({
|
||||
queryKey: ['sources'],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/admin/sources')).items,
|
||||
});
|
||||
const save = useMutation({
|
||||
mutationFn: async () =>
|
||||
unwrap(
|
||||
await session.client.PATCH('/api/v1/admin/uploads/files/{id}', {
|
||||
params: { path: { id: file.id } },
|
||||
body: { metadata: m, ...(source ? { target_source_id: source } : {}) },
|
||||
}),
|
||||
),
|
||||
onSuccess: () => {
|
||||
onSaved();
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
const text = (k: 'artist' | 'albumartist' | 'album' | 'title' | 'genre') => (
|
||||
<Field label={t(`uploads.meta_${k}`)} value={m[k]} onChange={(v) => setM({ ...m, [k]: v })} maxLength={500} />
|
||||
);
|
||||
const num = (k: 'year' | 'track' | 'disc') => (
|
||||
<Field
|
||||
label={t(`uploads.meta_${k}`)}
|
||||
value={m[k] === null ? '' : String(m[k])}
|
||||
inputMode="numeric"
|
||||
onChange={(v) => setM({ ...m, [k]: v.trim() === '' ? null : Number.parseInt(v, 10) || null })}
|
||||
/>
|
||||
);
|
||||
const accepting = sources.data?.filter((x) => x.accepts_uploads) ?? [];
|
||||
return (
|
||||
<Dialog
|
||||
title={t('uploads.edit_title')}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t('common:form.cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" busy={save.isPending} disabled={!m.artist.trim() || !m.title.trim()} onClick={() => save.mutate()}>
|
||||
{t('uploads.save')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={s.sessions}>
|
||||
<p className={s.note}>{file.client_rel_path ?? file.original_name}</p>
|
||||
<div className={u.grid}>
|
||||
{text('artist')}
|
||||
{text('albumartist')}
|
||||
{text('album')}
|
||||
{text('title')}
|
||||
{text('genre')}
|
||||
{num('year')}
|
||||
{num('track')}
|
||||
{num('disc')}
|
||||
</div>
|
||||
<label className={s.sessions}>
|
||||
<span>{t('uploads.target_source')}</span>
|
||||
<select className={s.select} value={source} onChange={(e) => setSource(e.target.value)}>
|
||||
<option value="">{t('uploads.target_default')}</option>
|
||||
{accepting.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className={s.note}>{t('uploads.tags_note')}</p>
|
||||
<FormError>{save.error ? (fieldError(save.error, 'metadata') ?? errorText(save.error)) : null}</FormError>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function RejectDialog({
|
||||
count,
|
||||
busy,
|
||||
onClose,
|
||||
onReject,
|
||||
}: {
|
||||
count: number;
|
||||
busy: boolean;
|
||||
onClose: () => void;
|
||||
onReject: (reason: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const [reason, setReason] = useState('');
|
||||
return (
|
||||
<Dialog
|
||||
title={t('uploads.reject_title', { count })}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t('common:form.cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" busy={busy} onClick={() => onReject(reason)}>
|
||||
{t('uploads.reject')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<label className={s.sessions}>
|
||||
<span>{t('uploads.reject_reason')}</span>
|
||||
<textarea className={u.textarea} value={reason} maxLength={1000} onChange={(e) => setReason(e.target.value)} />
|
||||
</label>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
const GB = 1024 ** 3;
|
||||
|
||||
/** Настройки очереди: общий лимит, лимит на модератора, размер файла, хранилище по умолчанию. */
|
||||
export function UploadSettingsSection() {
|
||||
const { t } = useTranslation(['admin', 'common']);
|
||||
const session = useSession();
|
||||
const queryClient = useQueryClient();
|
||||
const errorText = useErrorText();
|
||||
const settings = useQuery({
|
||||
queryKey: ['upload-settings'],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/admin/settings/uploads')),
|
||||
});
|
||||
const sources = useQuery({
|
||||
queryKey: ['sources'],
|
||||
queryFn: async () => unwrap(await session.client.GET('/api/v1/admin/sources')).items,
|
||||
});
|
||||
const [form, setForm] = useState<{ queue: string; perUser: string; maxFile: string; source: string; upgrade: boolean } | null>(null);
|
||||
useEffect(() => {
|
||||
if (settings.data) setForm(toForm(settings.data));
|
||||
}, [settings.data]);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: async () => {
|
||||
const f = form!;
|
||||
const gb = (v: string) => Math.round(Number.parseFloat(v.replace(',', '.')) * GB);
|
||||
return unwrap(
|
||||
await session.client.PATCH('/api/v1/admin/settings/uploads', {
|
||||
body: {
|
||||
queue_limit_bytes: gb(f.queue),
|
||||
max_file_bytes: gb(f.maxFile),
|
||||
per_user_limit_bytes: f.perUser.trim() ? gb(f.perUser) : null,
|
||||
default_source_id: f.source || null,
|
||||
allow_quality_upgrade: f.upgrade,
|
||||
},
|
||||
}),
|
||||
);
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
queryClient.setQueryData(['upload-settings'], data);
|
||||
await queryClient.invalidateQueries({ queryKey: ['upload-quota'] });
|
||||
},
|
||||
});
|
||||
if (!form) return null;
|
||||
const valid = [form.queue, form.maxFile].every((v) => Number.parseFloat(v.replace(',', '.')) > 0) &&
|
||||
(!form.perUser.trim() || Number.parseFloat(form.perUser.replace(',', '.')) > 0);
|
||||
const dirty = settings.data ? JSON.stringify(toForm(settings.data)) !== JSON.stringify(form) : false;
|
||||
return (
|
||||
<section className={s.section}>
|
||||
<h2>{t('uploads.settings_title')}</h2>
|
||||
<div className={u.settingsGrid}>
|
||||
<Field label={t('uploads.set_queue')} value={form.queue} onChange={(v) => setForm({ ...form, queue: v })} inputMode="decimal" />
|
||||
<Field
|
||||
label={t('uploads.set_per_user')}
|
||||
value={form.perUser}
|
||||
hint={t('uploads.set_per_user_hint')}
|
||||
onChange={(v) => setForm({ ...form, perUser: v })}
|
||||
inputMode="decimal"
|
||||
/>
|
||||
<Field label={t('uploads.set_max_file')} value={form.maxFile} onChange={(v) => setForm({ ...form, maxFile: v })} inputMode="decimal" />
|
||||
<label>
|
||||
<span className={u.settingsLabel}>{t('uploads.set_source')}</span>
|
||||
<select className={s.select} value={form.source} onChange={(e) => setForm({ ...form, source: e.target.value })}>
|
||||
<option value="">{t('uploads.set_source_auto')}</option>
|
||||
{sources.data
|
||||
?.filter((x) => x.accepts_uploads)
|
||||
.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<label className={u.settingsCheck}>
|
||||
<input type="checkbox" checked={form.upgrade} onChange={(e) => setForm({ ...form, upgrade: e.target.checked })} />
|
||||
<span>{t('uploads.set_upgrade')}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<p className={s.note}>{t('uploads.set_note')}</p>
|
||||
<div className={s.toolbar}>
|
||||
<span style={{ flex: 1 }} />
|
||||
<Button variant="primary" busy={save.isPending} disabled={!dirty || !valid} onClick={() => save.mutate()}>
|
||||
{t('uploads.save')}
|
||||
</Button>
|
||||
</div>
|
||||
{save.isSuccess && !dirty && <span className={s.ok}>{t('uploads.saved')}</span>}
|
||||
<FormError>{save.error ? errorText(save.error) : null}</FormError>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function toForm(st: Settings) {
|
||||
const gb = (n: number) => String(Math.round((n / GB) * 100) / 100);
|
||||
return {
|
||||
queue: gb(st.queue_limit_bytes),
|
||||
perUser: st.per_user_limit_bytes === null ? '' : gb(st.per_user_limit_bytes),
|
||||
maxFile: gb(st.max_file_bytes),
|
||||
source: st.default_source_id ?? '',
|
||||
upgrade: st.allow_quality_upgrade,
|
||||
};
|
||||
}
|
||||
export function UploadQueuePage() { return <UploadQueue />; }
|
||||
@@ -9,7 +9,7 @@ import { useErrorText, useFieldError } from '../../shared/lib/errors';
|
||||
import { formatRelative } from '../../shared/lib/format';
|
||||
import { assignableRoles, canManageUser, type Role } from '../../shared/lib/policy';
|
||||
import { addIcon, checkIcon, copyIcon, lockResetIcon, moreIcon, refreshIcon, searchIcon } from '../../shared/ui/icons';
|
||||
import { Avatar, Button, cx, Dialog, Field, FormError, Icon, Menu, type MenuItem } from '../../shared/ui/ui';
|
||||
import { Avatar, Button, cx, Dialog, EmptyState, Field, FormError, Icon, Menu, PageSkeleton, type MenuItem } from '../../shared/ui/ui';
|
||||
import s from '../page.module.css';
|
||||
|
||||
type AdminUser = components['schemas']['AdminUser'];
|
||||
@@ -140,6 +140,11 @@ export function UsersPage() {
|
||||
label: t(u.reviews_uploads ? 'users.revoke_review' : 'users.grant_review'),
|
||||
onSelect: () => patch.mutate({ id: u.id, body: { reviews_uploads: !u.reviews_uploads } }),
|
||||
});
|
||||
if (me.role === 'admin' && u.role !== 'admin')
|
||||
items.push({
|
||||
label: t(u.manages_updates ? 'users.revoke_updates' : 'users.grant_updates'),
|
||||
onSelect: () => patch.mutate({ id: u.id, body: { manages_updates: !u.manages_updates } }),
|
||||
});
|
||||
if (can('delete'))
|
||||
items.push({ label: t('users.delete'), danger: true, onSelect: () => setConfirm({ kind: 'delete', user: u }) });
|
||||
return items;
|
||||
@@ -214,6 +219,7 @@ export function UsersPage() {
|
||||
</td>
|
||||
<td data-label={t('users.col_role')}>
|
||||
<span className={cx(s.badge, s[`role_${u.role}`])}>{t(`common:roles.${u.role}`)}</span>
|
||||
{u.manages_updates && <span className={cx(s.badge, s.role_moderator)}>{t('users.manage_updates')}</span>}
|
||||
{u.reviews_uploads && <span className={cx(s.badge, s.role_moderator)}>{t('users.review_uploads')}</span>}
|
||||
</td>
|
||||
<td data-label={t('users.col_status')}>
|
||||
@@ -232,8 +238,8 @@ export function UsersPage() {
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
{list.isSuccess && users.length === 0 && <div className={s.empty}>{t('users.empty')}</div>}
|
||||
{list.isPending && <div className={s.empty}>{t('common:loading')}</div>}
|
||||
{list.isSuccess && users.length === 0 && <EmptyState icon={searchIcon}>{t('users.empty')}</EmptyState>}
|
||||
{list.isPending && <PageSkeleton />}
|
||||
</div>
|
||||
{list.hasNextPage && (
|
||||
<Button className={s.more} busy={list.isFetchingNextPage} onClick={() => void list.fetchNextPage()}>
|
||||
|
||||
@@ -123,8 +123,14 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.analysisActions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.analysisErrors { display: grid; gap: 16px; list-style: none; margin: 16px 0; padding: 0; }
|
||||
.analysisErrors li { display: grid; gap: 6px; padding-bottom: 16px; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
|
||||
.analysisPath { font-size: 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
|
||||
.errorDetail {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
@@ -146,6 +152,26 @@
|
||||
transition: width 0.4s;
|
||||
}
|
||||
|
||||
.scanPath {
|
||||
font-size: 12px;
|
||||
color: var(--text3);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.indeterminate span {
|
||||
width: 35%;
|
||||
animation: scanActivity 1.5s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
@keyframes scanActivity {
|
||||
from { transform: translateX(0); }
|
||||
to { transform: translateX(185%); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.indeterminate span { animation: none; }
|
||||
}
|
||||
|
||||
.test {
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -212,6 +238,20 @@
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.excludedDirs {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
resize: vertical;
|
||||
border: 1px solid var(--line2);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 10px 12px;
|
||||
background: var(--surface2);
|
||||
color: var(--text);
|
||||
font: 13px var(--font-mono);
|
||||
}
|
||||
.excludedDirs:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.excludedDirs:disabled { opacity: 0.6; }
|
||||
|
||||
.tiles {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
||||
|
||||
@@ -20,6 +20,15 @@
|
||||
filter: blur(30px);
|
||||
}
|
||||
|
||||
.waveDecor {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 46%;
|
||||
transform: translate(-50%, -50%);
|
||||
opacity: 0.55;
|
||||
filter: blur(0);
|
||||
}
|
||||
|
||||
.blob1 {
|
||||
width: 62vmax;
|
||||
height: 62vmax;
|
||||
@@ -244,6 +253,12 @@
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.otherBlock {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.otherTitle {
|
||||
margin: 8px 0 0;
|
||||
color: var(--text3);
|
||||
@@ -272,6 +287,20 @@
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.older {
|
||||
font-size: 13px;
|
||||
color: var(--text3);
|
||||
}
|
||||
|
||||
.older summary {
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.older .downloadAlt {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.link {
|
||||
align-self: center;
|
||||
}
|
||||
@@ -60,12 +60,23 @@
|
||||
|
||||
.heroBg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0.35;
|
||||
inset: -20%;
|
||||
opacity: 0.4;
|
||||
filter: blur(60px);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.heroBg img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.heroCover {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.tint {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
@@ -81,12 +92,40 @@
|
||||
|
||||
.heroBody {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.listen {
|
||||
display: grid;
|
||||
gap: 28px;
|
||||
}
|
||||
|
||||
.listenLyrics {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@media (min-width: 900px) {
|
||||
.listen {
|
||||
grid-template-columns: minmax(240px, 300px) minmax(0, 1fr);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.listen .hero {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.listen .heroTitle {
|
||||
font-size: clamp(28px, 3vw, 40px);
|
||||
}
|
||||
}
|
||||
|
||||
.kind {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 16px; margin: 0; }
|
||||
.stats dt { color: var(--text2); font-size: 13px; }
|
||||
.stats dd { margin: 6px 0 0; font-size: 25px; font-variant-numeric: tabular-nums; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: 12px; }
|
||||
.progress { display: grid; gap: 8px; font-variant-numeric: tabular-nums; }
|
||||
.progress progress { display: block; width: 100%; height: 8px; accent-color: var(--accent); }
|
||||
.lyrics { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.8; }
|
||||
.annotation { border-top: 1px solid var(--line); padding-top: 16px; overflow-wrap: anywhere; }
|
||||
.annotation summary { cursor: pointer; line-height: 1.6; }
|
||||
.badge { display: inline-block; margin-left: 12px; font-size: 12px; color: var(--text2); }
|
||||