Compare commits

...
4 Commits
Author SHA1 Message Date
Aleksandr Bogomiakov 9b923851ae Fixed build. Reworked mobile admin UI
Build and Publish / Build and Publish Docker Image (push) Successful in 7m46s
2026-11-18 15:17:50 +00:00
Aleksandr Bogomiakov 939fc00e4c Reworked new users login, improved share feature, enabled track downloads
Build and Publish / Build and Publish Docker Image (push) Failing after 4m21s
2026-11-18 14:40:16 +00:00
Aleksandr Bogomiakov 2b7117a4f6 Fixed metadata AI assistant
Build and Publish / Build and Publish Docker Image (push) Successful in 4m28s
2026-11-16 01:10:59 +00:00
Aleksandr Bogomiakov 3d886d1acd Improved metadata AI Assistant.
Build and Publish / Build and Publish Docker Image (push) Successful in 5m54s
2026-11-16 00:32:33 +00:00
41 changed files with 5264 additions and 3633 deletions

No files matched your search

+1
View File
@@ -48,4 +48,5 @@ jobs:
push: ${{ github.event_name != 'pull_request' }} push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.docker_tags }} tags: ${{ steps.meta.outputs.docker_tags }}
cache-from: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache cache-from: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache
# Export intermediate stages, including cargo-chef's compiled dependencies.
cache-to: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache,mode=max cache-to: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache,mode=max
Generated
+1 -1
View File
@@ -1988,7 +1988,7 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]] [[package]]
name = "furumusic" name = "furumusic"
version = "0.12.2" version = "0.12.4"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-stream", "async-stream",
+7 -1
View File
@@ -1,9 +1,15 @@
[package] [package]
name = "furumusic" name = "furumusic"
version = "0.12.2" version = "0.12.4"
edition = "2024" edition = "2024"
description = "Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL" description = "Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL"
# Unoptimized dependencies overflow macOS compact unwind's 24-bit DWARF offset
# (16 MiB of __eh_frame). Keep dependency code small while leaving application
# code unoptimized and retaining debug symbols, assertions and panic unwinding.
[profile.dev.package."*"]
opt-level = 1
# macOS 27 rejects some stripped proc-macro dylibs with a misaligned LINKEDIT # macOS 27 rejects some stripped proc-macro dylibs with a misaligned LINKEDIT
# string pool. Build scripts and proc macros are compile-time artifacts only. # string pool. Build scripts and proc macros are compile-time artifacts only.
[profile.release.build-override] [profile.release.build-override]
+16 -3
View File
@@ -1,18 +1,31 @@
FROM rust:1-bookworm AS builder FROM rust:1.97.0-bookworm AS chef
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y --no-install-recommends pkg-config libssl-dev ca-certificates \ && apt-get install -y --no-install-recommends pkg-config libssl-dev ca-certificates \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
RUN cargo install cargo-chef --version 0.1.74 --locked
WORKDIR /app WORKDIR /app
COPY Cargo.toml Cargo.lock* ./ FROM chef AS planner
COPY Cargo.toml Cargo.lock ./
COPY build.rs ./build.rs
COPY src ./src
RUN cargo chef prepare --recipe-path recipe.json
FROM chef AS builder
COPY --from=planner /app/recipe.json ./recipe.json
# Keep compiled dependencies in an ordinary layer exported by CI's registry cache.
RUN cargo chef cook --release --locked --recipe-path recipe.json
COPY Cargo.toml Cargo.lock ./
COPY build.rs ./build.rs COPY build.rs ./build.rs
COPY prompts ./prompts COPY prompts ./prompts
COPY src ./src COPY src ./src
COPY templates ./templates COPY templates ./templates
RUN cargo build --release RUN cargo build --release --locked --bin furumusic
FROM denoland/deno:bin-2.8.3 AS deno FROM denoland/deno:bin-2.8.3 AS deno
+35 -212
View File
@@ -2,229 +2,52 @@
**Your library. Your users. Your network.** **Your library. Your users. Your network.**
Furumusic is a self-hosted, multi-user music server with a full web player and Furumusic is a self-hosted music server with a full web player. Bring your music,
support for the Furumi federated network. It turns a collection of music files share a library with friends, and keep your own playlists, likes, and listening
into a shared library that is available from any modern browser, while every history. Listen from a desktop or phone, or connect independent servers through
user keeps their own playlists, likes, listening history, and playback state. the Furumi federated network.
Music can be uploaded directly, imported from a `.torrent` file, or downloaded ## What you can do
from a magnet link. An optional AI-assisted import pipeline reads the available
tags and path information, reconstructs inconsistent metadata, finds artwork,
and organizes the result into artists, releases, and tracks. Uncertain matches
are kept for review instead of silently entering the library with bad data.
## Why Furumusic? - **Listen anywhere.** Browse artists and releases, search your collection, build
queues, and manage playlists in a responsive web player.
- **Bring your collection.** Upload files and folders, or import music from
YouTube, torrents, and magnet links directly into your library or a playlist.
- **Organize your music.** Optional AI assistance recognizes metadata, finds
artwork, and helps repair messy releases. Review proposed changes before
applying them.
- **Share a song.** Send a track or queue link that anyone can play and download
without creating an account.
- **Welcome your people.** Use password login or SSO. Instance admins can approve
new users without needing access to the identity provider.
- **Discover more.** Find similar tracks and connect Last.fm for scrobbling.
- **Connect your players.** Pair trusted Furumi devices to synchronize playlists,
likes, playback state, and playback controls.
- **Join a network.** Discover and stream music from other participating peers
while keeping your own library independent.
- **Manage from any screen.** Review imports, manage users and background tasks,
and explore listening statistics in a desktop and mobile admin console.
Furumusic is for a household, a small community, or anyone who wants one music AI assistance, federation, similarity search, Last.fm, and SSO are optional.
library without handing it to a subscription service. The server owns the You choose which features to enable.
catalog and media files; the browser is only the player.
- one shared library with separate user accounts; ## Quick start
- a responsive web player with artists, releases, search, queue, and playlists;
- direct file uploads and imports from YouTube, torrent files, or magnet links;
- optional AI-assisted recognition and normalization of metadata;
- password login or OIDC/SSO with group-based access control;
- optional federation without a central catalog or search service;
- trusted-device pairing, playback handoff, and synchronization between Furumi
players;
- Last.fm scrobbling and similarity-based discovery when configured.
Furumusic does not include music. Import only media you are allowed to store and With Rust and PostgreSQL installed, create an empty database and start the server:
share.
## Importing music
Users can add audio files from the web interface or ask the server to download
selected files from a torrent. Both routes feed the same import pipeline, so a
library remains consistent regardless of where its files came from.
The importer combines embedded tags, filenames, folder structure, and existing
catalog context. With an OpenAI-compatible language model configured, it can
normalize artist and release names, separate featured artists, recover track
numbers and release types, and flag ambiguous results for a user to approve.
Cover art is taken from nearby image files or embedded artwork when available.
The inbox and permanent library are separate directories. New files are first
processed in the inbox and are moved into the organized library only after
their metadata has been accepted.
## Federation
Federation is optional. Independent Furumusic and Furumi players that use the
same Network ID discover one another as a logical network. Each peer keeps its
own library and can continue working alone.
When federation is enabled, local and remote artists, releases, and tracks can
appear in the same search and library views. Missing audio is streamed from an
available peer and can optionally be retained locally. Similarity search also
stays decentralized: embeddings and exact ranking remain on the instance that
owns the music.
Trusted-device pairing is separate from public catalog discovery. It connects
a user's own Furumi players so likes, playlists, playback state, and control can
move between approved devices.
## Build and run
Furumusic requires PostgreSQL and a Rust toolchain with Rust 2024 edition
support. Create an empty database, provide its connection URL, and start the
server:
```bash ```bash
export FURU_DATABASE_URL='postgresql://furumusic:password@127.0.0.1/furumusic' export FURU_DATABASE_URL='postgresql://furumusic:password@127.0.0.1/furumusic'
cargo run --release --locked cargo run --release --locked
``` ```
Open <http://127.0.0.1:8000/admin/setup> to create the first administrator. Open <http://127.0.0.1:8000/admin/setup> to create your administrator account,
After setup, configure the inbox and library directories under **Admin → then configure the inbox and music library directories in **Admin → Settings**.
Settings** before importing music.
To listen on another address or port: ## Documentation
```bash - [Installation and configuration](docs/setup.md)
cargo run --release --locked -- -l 0.0.0.0:8000 - [Using and administering Furumusic](docs/administration.md)
``` - [Development, architecture, and tests](docs/development.md)
- [Admin UI conventions](docs/admin-ui.md)
A Nix development shell is included for Linux and macOS: Bug reports, ideas, and contributions are welcome.
```bash
nix develop
cargo run --locked
```
The repository also contains a multi-stage `Dockerfile` for building a small
runtime image. A deployment must provide PostgreSQL plus persistent, writable
volumes for the inbox and music library.
## Admin statistics
The only admin interface is `/admin/v2`, also reachable from `/admin/`.
**Statistics** shows listening totals, a timeline, artist/track/release rankings,
and paginated history. Select an artist or track to see its listeners, then a
listener to see their history within the same filters. The **Users** list links
to each user's full statistics.
Periods use UTC. Counts come from the synchronized `listen_event` history: a
natural finish, half of a track, or four minutes qualifies as a play. Interrupted
sessions under five seconds are not retained. Short retained sessions contribute
to listened time but not play counts. The source filter separates this instance
from synchronized devices. Artist rankings use recorded artist names, including
featured credits; the same artist is counted once per event. Existing history
remains available when its local audio file is deleted. Library and service
cards show current instance totals, independently of the listening filters.
Migration `m_0051_add_listen_statistics_indexes` adds time and content indexes.
The old admin pages and `/admin/debug` are removed; first-run setup remains at
`/admin/setup`.
Regression checks:
```bash
node --test tests/*.test.cjs
cargo test admin:: -- --skip postgres_statistics_drilldown_and_pagination
# Use a disposable PostgreSQL; this test creates connection-local temporary tables.
FURU_STATISTICS_TEST_DATABASE_URL=postgresql://... cargo test postgres_statistics_drilldown_and_pagination -- --ignored
```
`tests/browser-statistics.cjs` additionally exercises a fresh disposable instance
at `FURU_TEST_URL` (default `http://127.0.0.1:3018`) and seeds the disposable Docker
container `furumi-statistics-test-pg`. It requires Playwright (or
`PLAYWRIGHT_MODULE`) and Chrome (or `CHROME_PATH`). Never point this test at a
live service.
## Importing into playlists
The player's download manager offers **Add downloads to a playlist** for file
and folder uploads and torrents, as well as YouTube. Choose an existing owned
playlist or create one before starting; leaving the choice empty imports only
into the library. Selected audio tracks are appended after processing or manual
approval, including files resolved to tracks already in the library.
Migration `m_0052_add_import_playlist_destinations` persists the destination and
completion receipts. Retries and restarts retain the choice, avoid duplicates,
and do not re-add tracks subsequently removed by the user. A started batch keeps
its destination for its remaining files.
```bash
node --test tests/import_playlists.test.cjs
# Disposable PostgreSQL; both tests use temporary tables.
FURU_IMPORT_TEST_DATABASE_URL=postgresql://... cargo test import_destinations -- --ignored
FURU_IMPORT_TEST_DATABASE_URL=postgresql://... cargo test torrent_playlist -- --ignored
```
`tests/browser-import-playlists.cjs` checks the file upload flow, database
reconciliation and the torrent picker on desktop and mobile. It requires a fresh
migrated instance with the import agent disabled at `FURU_TEST_URL` (default
`http://127.0.0.1:3019`), the disposable PostgreSQL container
`furumi-import-playlist-test-pg` with database `furumi_import_test`, and Playwright
and Chrome configured as above. It uses a local torrent preview fixture and
simulated imported tracks, without downloading external torrents.
## Configuration
Most settings can be changed from the administration interface. Every setting
also has a `FURU_`-prefixed environment variable; environment values take
priority over values stored in PostgreSQL.
The settings needed for a useful first installation are:
| Setting | Purpose |
| --- | --- |
| `FURU_DATABASE_URL` | PostgreSQL connection URL; required to run the service |
| `FURU_AGENT_INBOX_DIR` | Temporary inbox for uploads and downloaded files |
| `FURU_AGENT_STORAGE_DIR` | Permanent, organized music library |
| `FURU_AGENT_ENABLED` | Enables the background metadata import pipeline |
| `FURU_AGENT_LLM_URL` | Base URL of an OpenAI-compatible model server |
| `FURU_AGENT_LLM_MODEL` | Model used to recognize and normalize metadata |
| `FURU_FEDERATION_ENABLED` | Publishes the library and enables peer discovery |
| `FURU_FEDERATION_NETWORK_ID` | Joins peers with the same value into one logical network |
AI recognition, federation, similarity search, Last.fm, and OIDC are optional.
A local password-authenticated server can be used without any of them.
## Architecture
Furumusic is written in Rust on the
[Cot](https://cot.rs) web framework. PostgreSQL stores the catalog, accounts,
playlists, configuration, and background-job state. Audio inspection uses
Symphonia, torrent downloads use librqbit, and the shared `music-dht`/Frid
protocol stack provides decentralized catalog search, media transfer, and
connected-device synchronization.
The browser interface and JSON API are served by the same application. Import,
artwork, metadata enrichment, similarity indexing, and maintenance run as
durable background jobs rather than blocking playback requests.
The `lastfm_popularity` job defaults to **light** mode: it requests popularity
only for tracks without a completed lookup or with a changed title or primary
artist. Both matches (including zero counts) and explicit Last.fm “Track not
found” results are skipped on subsequent light runs. HTTP errors, timeouts,
invalid responses, and other API errors remain eligible for retry. A failed
full refresh also makes that track eligible for the next light run.
Choose **Full: refresh all visible tracks** in the task's admin parameters to
refresh existing statistics and retry previous misses. The options endpoint
`POST /admin/v2/api/jobs/lastfm_popularity/run-options` accepts
`{"refresh_existing": true}`; an empty object, scheduled runs, and the ordinary
run endpoint use light mode. Neither mode limits the number of tracks processed.
An authoritative miss clears current statistics while preserving their history.
The migration preserves existing popularity; legacy misses need one more lookup
because older versions did not persist them.
## Contributing
Bug reports, design discussions, and patches are welcome. Before submitting a
change, run:
```bash
cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
cargo test --all-targets
```
Last.fm database tests use temporary tables on a disposable PostgreSQL database:
```bash
FURUMUSIC_LASTFM_TEST_DATABASE_URL=postgres://user:pass@localhost/test_db \
cargo test lastfm_popularity -- --include-ignored
```
+100
View File
@@ -0,0 +1,100 @@
# Admin interface conventions
[Project overview](../README.md) · [Development](development.md)
The admin UI uses one Alpine application and shared layout primitives for every
section. Add features to this model rather than introducing a separate mobile
page or section-specific navigation.
## Ownership
- `templates/admin/navigation.html`: the single navigation tree, grouped into
Operations (reviews/tasks), Music (library/tools/statistics), and Instance
(users/settings). Existing hash routes remain the source of navigation state.
- `templates/admin/styles.html`: colors, typography and component appearance.
- `templates/admin/responsive.html`: shared layout, breakpoints, touch targets,
scroll regions, table cards and dialog sizing. Put responsive rules here.
- `templates/admin/ui.html`: viewport state, task tabs, settings navigation and
the shared overlay lifecycle. Business data and API actions remain in
`adminV2()` in `v2.html`.
## Layout
| Width | Navigation | Workspaces | Lists and dialogs |
| --- | --- | --- | --- |
| 1280 px and above | Persistent sidebar | Task list/detail/log side by side | Tables, centered bounded dialogs |
| 1024–1279 px | Persistent sidebar | Task tabs; settings in one column | Tables, bounded dialogs |
| 768–1023 px | Drawer | Task tabs; settings section picker | Tables in contained scroll areas |
| Below 768 px | Drawer | Single column | Table cards, full viewport dialogs |
Keep CSS and `matchMedia` breakpoints in `ui.html` synchronized. The main panel
owns page scrolling. Use `minmax(0, 1fr)` and `min-width:0` for grid/flex children;
never restore a global minimum page width. The top bar stays available while
content scrolls. Navigation closes after route changes and when switching to
the desktop layout. It retains the active section and the existing URL routes.
Use `.panel`, `.panel-head`, `.panel-title`, `.toolbar`, `.action-strip`, `.field`
and `.editor-grid` for new content. Toolbars wrap, inputs fill available space,
and mobile controls use 44 px touch targets and 16 px input text. Long identifiers,
paths and names must wrap. Avoid fixed column widths and inline grid definitions.
For tabular lists, add `.responsive-table`, a `data-label` to every cell, and
`data-primary` to its identifying cell. Mobile CSS presents the same DOM as cards;
do not duplicate rows or hide actions. Give clickable row titles real buttons
using `.row-link`, so the operation also works with a keyboard. Dense comparisons,
charts and logs may scroll inside a named, keyboard-focusable region; horizontal
scrolling must never propagate to the page. Keep these exceptions intentional.
Task tabs change presentation only: configuration and selected run stay in memory
when switching tabs or rotating the device. In settings, add a section ID and a
matching entry to the section picker. Put related controls in `.settings-grid`.
## Dialogs
Every dialog uses the same hierarchy and lifecycle:
```html
<div class="modal-backdrop" x-show="exampleOpen"
x-effect="adminOverlay.sync($el, !!exampleOpen)"
@keydown="adminOverlay.keydown($event, $el)"
@click.self="closeExample()">
<section class="modal" role="dialog" aria-modal="true"
aria-labelledby="example-title" tabindex="-1">
<div class="modal-head">
<strong id="example-title">Edit item</strong>
<button class="icon-btn" data-dialog-close
aria-label="Close dialog" @click="closeExample()">…</button>
</div>
<form class="modal-body" @submit.prevent="saveExample()">
<!-- .field and .editor-grid -->
<div class="dialog-actions"><button type="submit" class="btn primary">Save</button></div>
</form>
</section>
</div>
```
The helper locks the background with `inert`, moves focus into the dialog, traps
Tab/Shift+Tab, handles Escape through the existing close button, and restores
focus on close. Keep business rules in the close handler and disable that button
when closing is not allowed (for example, while merging). Nested pickers consume
Escape with `.stop` before the dialog handles it. Headers remain fixed while the
body scrolls; `.dialog-actions` keeps actions available at the bottom. On mobile,
dialogs use `100dvh` and safe-area padding. Reuse the helper for new overlays.
For content gated by an asynchronous load inside an animated dialog, use
`:hidden="loading"` instead of nesting competing `x-show` transitions. Loading
and content should not both stay hidden when a response arrives during opening.
## Verification
Run `node --test tests/*.test.cjs` and build the Rust application (templates are
compiled into the binary). `tests/browser-admin-responsive.cjs` checks all seven
sections at 320, 390, 768, 1024 and 1440 px, navigation focus, task state retention,
settings jumps, all five dialogs, long content and landscape geometry. It uses a
disposable running instance with an admin and at least one release containing a
track; browser fixtures do not modify server data. Supply `FURU_TEST_URL`,
`FURU_TEST_USERNAME`, `FURU_TEST_PASSWORD`, `PLAYWRIGHT_MODULE`, and `CHROME_PATH`
as appropriate. Set `FURU_TEST_SCREENSHOTS` to inspect screenshots visually.
Check both populated and empty views, long names/paths, loading states, keyboard
navigation, reachable Save/Close controls, and resize while an overlay is open.
+131
View File
@@ -0,0 +1,131 @@
# Using and administering Furumusic
[Project overview](../README.md) · [Installation](setup.md) · [Development and tests](development.md)
## Access and public sharing
OIDC identifies accounts by issuer and subject. Matching admin groups take
precedence over matching user groups, and either SSO grant takes precedence over
a local role. Without matching groups (including an empty group configuration),
a new account waits for approval in **Admin → Users**. Any instance administrator
can approve it as a user or administrator. The waiting page updates automatically.
On subsequent SSO logins the group grant is refreshed: if it disappears, only an
independently assigned local role preserves access. Existing password accounts
keep their local roles; existing OIDC-only accounts retain their last SSO grant
until the next login, without receiving an implicit local approval.
Sharing creates an unguessable `/share/{token}` link to a snapshot of track IDs,
including their order and repetitions. Guests and accounts awaiting approval can
play and download only the tracks in that snapshot, using the regular player.
They cannot browse the library, search, use recommendations, or write personal
history. Signing in from a share returns to that share; signing in from the root
shows only the approval page until access is granted. Track info offers a browser
download of the original audio file. The old radio implementation is removed.
Migration `m_0053_local_approval_and_public_shares` deletes the old share records.
Old track/release/playlist URL routes are removed, with no compatibility layer.
Link expiry, cleanup, and revocation are not part of this implementation.
## Importing music
Users can add audio files from the web interface or ask the server to download
selected files from a torrent. Both routes feed the same import pipeline, so a
library remains consistent regardless of where its files came from.
The importer combines embedded tags, filenames, folder structure, and existing
catalog context. With an OpenAI-compatible language model configured, it can
normalize artist and release names, separate featured artists, recover track
numbers and release types, and flag ambiguous results for a user to approve.
Cover art is taken from nearby image files or embedded artwork when available.
The inbox and permanent library are separate directories. New files are first
processed in the inbox and are moved into the organized library only after
their metadata has been accepted.
## Importing into playlists
The player's download manager offers **Add downloads to a playlist** for file
and folder uploads and torrents, as well as YouTube. Choose an existing owned
playlist or create one before starting; leaving the choice empty imports only
into the library. Selected audio tracks are appended after processing or manual
approval, including files resolved to tracks already in the library.
Migration `m_0052_add_import_playlist_destinations` persists the destination and
completion receipts. Retries and restarts retain the choice, avoid duplicates,
and do not re-add tracks subsequently removed by the user. A started batch keeps
its destination for its remaining files.
## Federation
Federation is optional. Independent Furumusic and Furumi players that use the
same Network ID discover one another as a logical network. Each peer keeps its
own library and can continue working alone.
When federation is enabled, local and remote artists, releases, and tracks can
appear in the same search and library views. Missing audio is streamed from an
available peer and can optionally be retained locally. Similarity search also
stays decentralized: embeddings and exact ranking remain on the instance that
owns the music.
Trusted-device pairing is separate from public catalog discovery. It connects
a user's own Furumi players so likes, playlists, playback state, and control can
move between approved devices.
## Admin statistics
The only admin interface is `/admin/v2`, also reachable from `/admin/`.
**Statistics** shows listening totals, a timeline, artist/track/release rankings,
and paginated history. Select an artist or track to see its listeners, then a
listener to see their history within the same filters. The **Users** list links
to each user's full statistics.
Periods use UTC. Counts come from the synchronized `listen_event` history: a
natural finish, half of a track, or four minutes qualifies as a play. Interrupted
sessions under five seconds are not retained. Short retained sessions contribute
to listened time but not play counts. The source filter separates this instance
from synchronized devices. Artist rankings use recorded artist names, including
featured credits; the same artist is counted once per event. Existing history
remains available when its local audio file is deleted. Library and service
cards show current instance totals, independently of the listening filters.
Migration `m_0051_add_listen_statistics_indexes` adds time and content indexes.
The old admin pages and `/admin/debug` are removed; first-run setup remains at
`/admin/setup`.
## Metadata Repair
Admin → Library Tools provides a chat for editing the selected library resources.
Use **Show related**, then **Deselect all** to choose only the resources needed
for the task. Selecting a release includes its tracks; individual tracks can
then be unchecked to exclude them. Unselected artists remain read-only context
and their IDs can still be used in credits. Releases show their years; tracks
show their source release.
The assistant sees the complete selected scope and replaces the proposed plan
after every clarification. Expand **Proposed changes** in the chat to review or
edit it before applying. Plans support moving tracks, creating releases, merging
releases, and deleting artists, releases, or tracks. Release deletion requires
explicit moves or deletion of all its tracks. Artist deletion detaches credits
and requires all credited releases and tracks to be included.
Applied plans are transactional and can be undone from History. Metadata Repair
retains audio and artwork files for Undo. Undo refuses to overwrite subsequent
metadata, playback, or federation changes.
## Last.fm popularity updates
The `lastfm_popularity` job defaults to **light** mode: it requests popularity
only for tracks without a completed lookup or with a changed title or primary
artist. Both matches (including zero counts) and explicit Last.fm “Track not
found” results are skipped on subsequent light runs. HTTP errors, timeouts,
invalid responses, and other API errors remain eligible for retry. A failed
full refresh also makes that track eligible for the next light run.
Choose **Full: refresh all visible tracks** in the task's admin parameters to
refresh existing statistics and retry previous misses. The options endpoint
`POST /admin/v2/api/jobs/lastfm_popularity/run-options` accepts
`{"refresh_existing": true}`; an empty object, scheduled runs, and the ordinary
run endpoint use light mode. Neither mode limits the number of tracks processed.
An authoritative miss clears current statistics while preserving their history.
The migration preserves existing popularity; legacy misses need one more lookup
because older versions did not persist them.
+122
View File
@@ -0,0 +1,122 @@
# Development
[Project overview](../README.md) · [Installation](setup.md) · [Admin UI conventions](admin-ui.md)
## Architecture
Furumusic is written in Rust on the
[Cot](https://cot.rs) web framework. PostgreSQL stores the catalog, accounts,
playlists, configuration, and background-job state. Audio inspection uses
Symphonia, torrent downloads use librqbit, and the shared `music-dht`/Frid
protocol stack provides decentralized catalog search, media transfer, and
connected-device synchronization.
The browser interface and JSON API are served by the same application. Import,
artwork, metadata enrichment, similarity indexing, and maintenance run as
durable background jobs rather than blocking playback requests.
## Build profiles
Development and test builds use basic optimization (`opt-level = 1`) for
dependencies to keep macOS unwind tables below the compact-unwind size limit.
Application code stays unoptimized; debug symbols, assertions and panic
unwinding remain enabled. The first build compiles dependencies with these
settings, then reuses them from Cargo's cache. Dependency stepping in a debugger
can be less exact because of optimization. Release settings are independent.
See the [Cargo profile override documentation](https://doc.rust-lang.org/cargo/reference/profiles.html#overrides) for dependency-specific settings.
## Container builds and CI
CI uses Rust 1.97.0 and cargo-chef 0.1.74 to cache compiled dependencies separately
from application sources. Buildx imports and exports intermediate layers through
`ultradesu/furumusic:buildcache` (`mode=max`). After the first build, changes to
source code, templates or prompts reuse the dependency layer when its recipe and
toolchain are unchanged. Both dependency and application builds use `--locked`.
Update the pinned build tools in `Dockerfile`; changing them rebuilds the cache.
## Contributing
Bug reports, design discussions, and patches are welcome. Before submitting a
change, run:
```bash
cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
cargo test --all-targets
```
Last.fm database tests use temporary tables on a disposable PostgreSQL database:
```bash
FURUMUSIC_LASTFM_TEST_DATABASE_URL=postgres://user:pass@localhost/test_db \
cargo test lastfm_popularity -- --include-ignored
```
## Access and sharing tests
The access regression suite uses a disposable migrated database and a local OIDC
provider with signed tokens and PKCE:
```bash
node --test tests/*.test.cjs
FURU_ACCESS_TEST_DATABASE_URL=postgresql://... cargo test postgres_approval_survives_sso_changes_without_implicit_grants -- --ignored
# Fresh disposable instance on :18048, media root /tmp/furumi-access-media,
# PostgreSQL container furumi-access-test-pg, database furumi_access_test:
node tests/browser-access-sharing.cjs
```
The browser test requires Playwright (`PLAYWRIGHT_MODULE`) and Chrome
(`CHROME_PATH`), and uses local port 18049 for its OIDC provider. It checks
approval, SSO precedence and group removal, guest playback and downloads,
unauthorized track substitution, and desktop/mobile player behavior.
## Statistics tests
```bash
node --test tests/*.test.cjs
cargo test admin:: -- --skip postgres_statistics_drilldown_and_pagination
# Use a disposable PostgreSQL; this test creates connection-local temporary tables.
FURU_STATISTICS_TEST_DATABASE_URL=postgresql://... cargo test postgres_statistics_drilldown_and_pagination -- --ignored
```
`tests/browser-statistics.cjs` additionally exercises a fresh disposable instance
at `FURU_TEST_URL` (default `http://127.0.0.1:3018`) and seeds the disposable Docker
container `furumi-statistics-test-pg`. It requires Playwright (or
`PLAYWRIGHT_MODULE`) and Chrome (or `CHROME_PATH`). Never point this test at a
live service.
## Metadata Repair tests
```bash
node --test tests/admin_metadata_repair.test.cjs
cargo test admin::metadata_fix::tests
```
`tests/browser-metadata-repair.cjs` checks the chat and plan updates, a four-release
merge, deletion and restoration of tracks and artist credits, playlists, playback
queues, and undo conflicts. Run it only against a disposable instance and a
PostgreSQL container named `furumi-repair-test-pg`, with database
`furumi_repair_test`. Set `FURU_TEST_URL`, `FURU_REPAIR_TEST_PG`, `CHROME_PATH`, and
`PLAYWRIGHT_MODULE` as needed. It seeds `tests/metadata_repair_fixture.sql` after
creating the test administrator. Set `FURU_REPAIR_SKIP_SEED=1` for a seeded database.
With `FURU_REPAIR_TEST_MODEL=1`, it additionally checks the reported release-only
selection and full ordered tracklist against the configured model, applies and
undoes that plan, and verifies individual track exclusions.
## Import destination tests
```bash
node --test tests/import_playlists.test.cjs
# Disposable PostgreSQL; both tests use temporary tables.
FURU_IMPORT_TEST_DATABASE_URL=postgresql://... cargo test import_destinations -- --ignored
FURU_IMPORT_TEST_DATABASE_URL=postgresql://... cargo test torrent_playlist -- --ignored
```
`tests/browser-import-playlists.cjs` checks the file upload flow, database
reconciliation and the torrent picker on desktop and mobile. It requires a fresh
migrated instance with the import agent disabled at `FURU_TEST_URL` (default
`http://127.0.0.1:3019`), the disposable PostgreSQL container
`furumi-import-playlist-test-pg` with database `furumi_import_test`, and Playwright
and Chrome configured as above. It uses a local torrent preview fixture and
simulated imported tracks, without downloading external torrents.
+57
View File
@@ -0,0 +1,57 @@
# Installation and configuration
[Project overview](../README.md) · [Administration guide](administration.md)
## Build and run
Furumusic requires PostgreSQL and a Rust toolchain with Rust 2024 edition
support. Create an empty database, provide its connection URL, and start the
server:
```bash
export FURU_DATABASE_URL='postgresql://furumusic:password@127.0.0.1/furumusic'
cargo run --release --locked
```
Open <http://127.0.0.1:8000/admin/setup> to create the first administrator.
After setup, configure the inbox and library directories under **Admin →
Settings** before importing music.
To listen on another address or port:
```bash
cargo run --release --locked -- -l 0.0.0.0:8000
```
A Nix development shell is included for Linux and macOS:
```bash
nix develop
cargo run --locked
```
The repository also contains a multi-stage `Dockerfile` for building a small
runtime image. A deployment must provide PostgreSQL plus persistent, writable
volumes for the inbox and music library.
## Configuration
Most settings can be changed from the administration interface. Every setting
also has a `FURU_`-prefixed environment variable; environment values take
priority over values stored in PostgreSQL.
The settings needed for a useful first installation are:
| Setting | Purpose |
| --- | --- |
| `FURU_DATABASE_URL` | PostgreSQL connection URL; required to run the service |
| `FURU_AGENT_INBOX_DIR` | Temporary inbox for uploads and downloaded files |
| `FURU_AGENT_STORAGE_DIR` | Permanent, organized music library |
| `FURU_AGENT_ENABLED` | Enables the background metadata import pipeline |
| `FURU_AGENT_LLM_URL` | Base URL of an OpenAI-compatible model server |
| `FURU_AGENT_LLM_MODEL` | Model used to recognize and normalize metadata |
| `FURU_FEDERATION_ENABLED` | Publishes the library and enables peer discovery |
| `FURU_FEDERATION_NETWORK_ID` | Joins peers with the same value into one logical network |
AI recognition, federation, similarity search, Last.fm, and OIDC are optional.
A local password-authenticated server can be used without any of them.
+18 -6
View File
@@ -28,7 +28,18 @@ pub(super) async fn manage_user(
Ok(u) => u, Ok(u) => u,
Err(r) => return Ok(r), Err(r) => return Ok(r),
}; };
if body.action == "delete" { if body.action == "approve" {
let Some(id) = body.id.filter(|id| *id > 0) else {
return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user"));
};
if Role::from_code(&body.role).is_none() || (id == admin.id && body.role != "admin") {
return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid role"));
}
let Some(mut user) = User::get_by_id(&db, id).await? else {
return Ok(json_error(StatusCode::NOT_FOUND, "User not found"));
};
user.approve(&db, &body.role, admin.id).await?;
} else if body.action == "delete" {
let Some(id) = body.id.filter(|id| *id > 0) else { let Some(id) = body.id.filter(|id| *id > 0) else {
return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user")); return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user"));
}; };
@@ -43,7 +54,8 @@ pub(super) async fn manage_user(
if !["create", "update"].contains(&body.action.as_str()) if !["create", "update"].contains(&body.action.as_str())
|| body.username.trim().is_empty() || body.username.trim().is_empty()
|| body.username.chars().count() > 255 || body.username.chars().count() > 255
|| Role::from_code(&body.role).is_none() || (Role::from_code(&body.role).is_none()
&& !(body.action == "update" && body.role.is_empty()))
|| (body.action == "create" && body.password.is_empty()) || (body.action == "create" && body.password.is_empty())
{ {
return Ok(json_error( return Ok(json_error(
@@ -74,15 +86,15 @@ pub(super) async fn manage_user(
let Some(id) = body.id.filter(|id| *id > 0) else { let Some(id) = body.id.filter(|id| *id > 0) else {
return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user")); return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user"));
}; };
if id == admin.id && body.role != "admin" { let Some(mut user) = User::get_by_id(&db, id).await? else {
return Ok(json_error(StatusCode::NOT_FOUND, "User not found"));
};
if id == admin.id && body.role != "admin" && !user.has_sso_admin_role() {
return Ok(json_error( return Ok(json_error(
StatusCode::BAD_REQUEST, StatusCode::BAD_REQUEST,
"You cannot remove your own administrator role", "You cannot remove your own administrator role",
)); ));
} }
let Some(mut user) = User::get_by_id(&db, id).await? else {
return Ok(json_error(StatusCode::NOT_FOUND, "User not found"));
};
if User::get_by_username(&db, body.username.trim()) if User::get_by_username(&db, body.username.trim())
.await? .await?
.is_some_and(|u| u.id_val() != id) .is_some_and(|u| u.id_val() != id)
+713 -182
View File
File diff suppressed because it is too large. Load diff
+9 -3
View File
@@ -230,6 +230,8 @@ struct AdminUserRowDto {
email: Option<String>, email: Option<String>,
role: String, role: String,
is_active: bool, is_active: bool,
local_role: Option<String>,
sso_role: Option<String>,
is_online: bool, is_online: bool,
last_seen_ms: Option<i64>, last_seen_ms: Option<i64>,
plays: i64, plays: i64,
@@ -2667,6 +2669,8 @@ struct AdminUserSqlRow {
email: Option<String>, email: Option<String>,
role: String, role: String,
is_active: bool, is_active: bool,
local_role: Option<String>,
sso_role: Option<String>,
plays: i64, plays: i64,
listened_seconds: i64, listened_seconds: i64,
last_play_ms: Option<i64>, last_play_ms: Option<i64>,
@@ -2700,7 +2704,7 @@ async fn load_admin_users_page(
let total: i64 = count_qb.build_query_scalar().fetch_one(pool).await?; let total: i64 = count_qb.build_query_scalar().fetch_one(pool).await?;
let mut qb = QueryBuilder::<Postgres>::new( let mut qb = QueryBuilder::<Postgres>::new(
"SELECT id, username::text, display_name, email, role::text, is_active, \ "SELECT id, username::text, display_name, email, role::text, is_active, local_role, sso_role, \
(SELECT COUNT(*) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS plays, \ (SELECT COUNT(*) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS plays, \
(SELECT (COALESCE(SUM(listened_ms), 0) / 1000)::bigint FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id) AS listened_seconds, \ (SELECT (COALESCE(SUM(listened_ms), 0) / 1000)::bigint FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id) AS listened_seconds, \
(SELECT MAX(started_at_ms) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS last_play_ms \ (SELECT MAX(started_at_ms) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS last_play_ms \
@@ -2715,7 +2719,7 @@ async fn load_admin_users_page(
qb.push_bind(pattern); qb.push_bind(pattern);
qb.push(")"); qb.push(")");
} }
qb.push(" ORDER BY username ASC LIMIT "); qb.push(" ORDER BY is_active ASC, username ASC LIMIT ");
qb.push_bind(limit); qb.push_bind(limit);
qb.push(" OFFSET "); qb.push(" OFFSET ");
qb.push_bind(offset); qb.push_bind(offset);
@@ -2747,7 +2751,7 @@ async fn load_admin_user_detail(
user_id: i64, user_id: i64,
) -> anyhow::Result<Option<AdminUserDetailDto>> { ) -> anyhow::Result<Option<AdminUserDetailDto>> {
let row = sqlx::query_as::<_, AdminUserSqlRow>( let row = sqlx::query_as::<_, AdminUserSqlRow>(
"SELECT id, username::text, display_name, email, role::text, is_active, \ "SELECT id, username::text, display_name, email, role::text, is_active, local_role, sso_role, \
(SELECT COUNT(*) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS plays, \ (SELECT COUNT(*) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS plays, \
(SELECT (COALESCE(SUM(listened_ms), 0) / 1000)::bigint FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id) AS listened_seconds, \ (SELECT (COALESCE(SUM(listened_ms), 0) / 1000)::bigint FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id) AS listened_seconds, \
(SELECT MAX(started_at_ms) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS last_play_ms \ (SELECT MAX(started_at_ms) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS last_play_ms \
@@ -2939,6 +2943,8 @@ fn admin_user_row(
email: row.email, email: row.email,
role: row.role, role: row.role,
is_active: row.is_active, is_active: row.is_active,
local_role: row.local_role,
sso_role: row.sso_role,
plays: row.plays, plays: row.plays,
listened_seconds: row.listened_seconds, listened_seconds: row.listened_seconds,
last_play_ms: row.last_play_ms, last_play_ms: row.last_play_ms,
+7 -2
View File
@@ -72,8 +72,13 @@ fn authenticated_user_from_user(user: User) -> Option<AuthenticatedUser> {
}) })
} }
/// Read `user_id` from the session, fetch the `User` from DB, return /// Return the signed-in identity, including an account awaiting approval.
/// `AuthenticatedUser` if the user exists and is active. pub async fn get_session_identity(session: &Session, db: &Database) -> Option<User> {
let user_id: i64 = session.get(SESSION_USER_ID).await.ok()??;
User::get_by_id(db, user_id).await.ok()?
}
/// Return a session user only when access to the instance has been granted.
pub async fn get_session_user(session: &Session, db: &Database) -> Option<AuthenticatedUser> { pub async fn get_session_user(session: &Session, db: &Database) -> Option<AuthenticatedUser> {
let user_id: i64 = session.get(SESSION_USER_ID).await.ok()??; let user_id: i64 = session.get(SESSION_USER_ID).await.ok()??;
let user = User::get_by_id(db, user_id).await.ok()??; let user = User::get_by_id(db, user_id).await.ok()??;
+7 -3
View File
@@ -1,6 +1,12 @@
use super::translations; use super::translations;
translations! { translations! {
approval_heading: "Awaiting approval", "Ожидается одобрение";
approval_message: "You are signed in. An instance administrator must approve your account before you can access the library.", "Вы вошли в аккаунт. Для доступа к библиотеке нужно одобрение администратора инстанса.";
guest_login: "Sign in / register", "Войти / зарегистрироваться";
guest_label: "Shared music", "Музыка по ссылке";
share_unavailable: "This link is unavailable or contains no playable tracks.", "Ссылка недоступна или не содержит доступных треков.";
track_download: "Download", "Скачать";
// Global // Global
site_name: "furumusic" , "furumusic"; site_name: "furumusic" , "furumusic";
@@ -71,7 +77,7 @@ translations! {
settings_oidc_admin_groups: "Admin groups" , "Группы администраторов"; settings_oidc_admin_groups: "Admin groups" , "Группы администраторов";
settings_oidc_admin_groups_help: "Comma-separated OIDC group names that grant admin role (e.g. /admin,/furumusic-admins)" , "OIDC группы через запятую, дающие роль администратора (напр. /admin,/furumusic-admins)"; settings_oidc_admin_groups_help: "Comma-separated OIDC group names that grant admin role (e.g. /admin,/furumusic-admins)" , "OIDC группы через запятую, дающие роль администратора (напр. /admin,/furumusic-admins)";
settings_oidc_user_groups: "User groups" , "Группы пользователей"; settings_oidc_user_groups: "User groups" , "Группы пользователей";
settings_oidc_user_groups_help: "Comma-separated OIDC group names allowed to access the service. If empty, any authenticated SSO user is allowed." , "OIDC группы через запятую, которым разрешён доступ к сервису. Если пусто, разрешён любой SSO пользователь."; settings_oidc_user_groups_help: "Comma-separated OIDC groups granting automatic user access. Everyone else needs local administrator approval." , "OIDC группы через запятую, дающие автоматический доступ. Остальным нужно локальное одобрение администратора.";
// User management // User management
nav_users: "Users" , "Пользователи"; nav_users: "Users" , "Пользователи";
@@ -360,8 +366,6 @@ translations! {
player_play: "Play" , "Играть"; player_play: "Play" , "Играть";
player_listen: "Listen" , "Слушать"; player_listen: "Listen" , "Слушать";
player_listen_artist: "Listen to artist" , "Слушать артиста"; player_listen_artist: "Listen to artist" , "Слушать артиста";
player_start_radio: "Start radio" , "Запустить радио";
player_radio_failed: "Could not start radio" , "Не удалось запустить радио";
player_played_at: "Played" , "Прослушано"; player_played_at: "Played" , "Прослушано";
player_like: "Like" , "Лайк"; player_like: "Like" , "Лайк";
player_add_to_queue: "Add to queue" , "Добавить в очередь"; player_add_to_queue: "Add to queue" , "Добавить в очередь";
+82 -108
View File
@@ -70,59 +70,64 @@ fn build_registry() -> Arc<JobRegistry> {
// Handlers // Handlers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
#[derive(Deserialize)] async fn index(session: Session, db: Database, i18n: I18n) -> cot::Result<cot::response::Response> {
struct IndexQuery { render_player(session, db, i18n, String::new()).await
track: Option<i64>,
release: Option<i64>,
playlist_share: Option<String>,
} }
async fn index( async fn render_player(
session: Session, session: Session,
db: Database, db: Database,
i18n: I18n, i18n: I18n,
UrlQuery(query): UrlQuery<IndexQuery>, share_token: String,
) -> cot::Result<cot::response::Response> { ) -> cot::Result<cot::response::Response> {
let _user = match auth::get_session_user(&session, &db).await { let guest = auth::get_session_user(&session, &db).await.is_none();
Some(u) => u, if guest && share_token.is_empty() {
None => { if auth::get_session_identity(&session, &db).await.is_some() {
if let Some(location) = share_query_redirect(&query) { return Html::new(PendingTemplate { t: i18n.t }.render()?).into_response();
auth::remember_post_login_redirect(&session, &location).await?;
}
return Ok(auth::redirect("/login"));
} }
}; return Ok(auth::redirect("/login"));
}
let (config, _) = AppConfig::load_with_db(&db).await; let (config, _) = AppConfig::load_with_db(&db).await;
let template = player::PlayerPageTemplate { Html::new(
t: i18n.t, player::PlayerPageTemplate {
downloads_enabled: config.downloads_enabled, t: i18n.t,
torrent_downloads_enabled: config.downloads_enabled && config.torrent_downloads_enabled, guest,
youtube_downloads_enabled: config.downloads_enabled && config.youtube_downloads_enabled, share_token,
}; downloads_enabled: !guest && config.downloads_enabled,
Html::new(template.render()?).into_response() torrent_downloads_enabled: !guest
&& config.downloads_enabled
&& config.torrent_downloads_enabled,
youtube_downloads_enabled: !guest
&& config.downloads_enabled
&& config.youtube_downloads_enabled,
}
.render()?,
)
.into_response()
} }
fn share_query_redirect(query: &IndexQuery) -> Option<String> { #[derive(Debug, Template)]
if let Some(track_id) = query.track.filter(|id| *id > 0) { #[template(path = "pending.html")]
return Some(format!("/?track={track_id}")); struct PendingTemplate {
} t: &'static Translations,
if let Some(release_id) = query.release.filter(|id| *id > 0) { }
return Some(format!("/?release={release_id}"));
} async fn access_status(session: Session, db: Database) -> cot::Result<cot::response::Response> {
let token = query.playlist_share.as_deref()?.trim(); let identity = auth::get_session_identity(&session, &db).await;
if is_share_token(token) { let status = match identity {
Some(format!("/?playlist_share={token}")) Some(user) if user.is_active() => "active",
} else { Some(_) => "pending",
None None => "anonymous",
} };
let mut response = cot::json::Json(serde_json::json!({"status": status})).into_response()?;
response
.headers_mut()
.insert("Cache-Control", "private, no-store".parse().unwrap());
Ok(response)
} }
fn is_share_token(token: &str) -> bool { fn is_share_token(token: &str) -> bool {
!token.is_empty() token.len() == 32 && token.bytes().all(|b| b.is_ascii_hexdigit())
&& token.len() <= 64
&& token
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -187,11 +192,7 @@ struct LoginForm {
#[derive(Deserialize)] #[derive(Deserialize)]
struct LoginQuery { struct LoginQuery {
error: Option<String>, error: Option<String>,
} next: Option<String>,
#[derive(Deserialize)]
struct SharePathId {
id: i64,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -236,56 +237,26 @@ async fn metrics_handler(
.expect("valid response")) .expect("valid response"))
} }
async fn share_track_handler( async fn share_handler(
session: Session,
db: Database,
Path(path): Path<SharePathId>,
) -> cot::Result<cot::response::Response> {
let location = if path.id > 0 {
format!("/?track={}", path.id)
} else {
"/".to_string()
};
if auth::get_session_user(&session, &db).await.is_none() {
auth::remember_post_login_redirect(&session, &location).await?;
return Ok(auth::redirect("/login"));
}
Ok(auth::redirect(&location))
}
async fn share_release_handler(
session: Session,
db: Database,
Path(path): Path<SharePathId>,
) -> cot::Result<cot::response::Response> {
let location = if path.id > 0 {
format!("/?release={}", path.id)
} else {
"/".to_string()
};
if auth::get_session_user(&session, &db).await.is_none() {
auth::remember_post_login_redirect(&session, &location).await?;
return Ok(auth::redirect("/login"));
}
Ok(auth::redirect(&location))
}
async fn share_playlist_handler(
session: Session, session: Session,
db: Database, db: Database,
i18n: I18n,
Path(path): Path<SharePathToken>, Path(path): Path<SharePathToken>,
) -> cot::Result<cot::response::Response> { ) -> cot::Result<cot::response::Response> {
let token = path.token.trim(); if !is_share_token(&path.token) {
let location = if is_share_token(token) { return Ok(cot::http::Response::builder()
format!("/?playlist_share={token}") .status(cot::http::StatusCode::NOT_FOUND)
} else { .body(Body::fixed("Shared music not found"))
"/".to_string() .expect("valid response"));
};
if auth::get_session_user(&session, &db).await.is_none() {
auth::remember_post_login_redirect(&session, &location).await?;
return Ok(auth::redirect("/login"));
} }
Ok(auth::redirect(&location)) let mut response = render_player(session, db, i18n, path.token).await?;
response
.headers_mut()
.insert("Referrer-Policy", "no-referrer".parse().unwrap());
response
.headers_mut()
.insert("Cache-Control", "private, no-store".parse().unwrap());
Ok(response)
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -316,26 +287,13 @@ impl App for FuruApp {
), ),
Route::with_handler_and_name( Route::with_handler_and_name(
"/", "/",
|session: Session, db: Database, i18n: I18n, query: UrlQuery<IndexQuery>| async move { |session: Session, db: Database, i18n: I18n| async move {
index(session, db, i18n, query).await index(session, db, i18n).await
}, },
"index", "index",
), ),
Route::with_handler_and_name( Route::with_handler_and_name("/share/{token}", get(share_handler), "share"),
"/share/track/{id}", Route::with_handler_and_name("/auth/status", get(access_status), "access_status"),
get(share_track_handler),
"share_track",
),
Route::with_handler_and_name(
"/share/release/{id}",
get(share_release_handler),
"share_release",
),
Route::with_handler_and_name(
"/share/playlist/{token}",
get(share_playlist_handler),
"share_playlist",
),
Route::with_handler_and_name( Route::with_handler_and_name(
"/metrics", "/metrics",
get({ get({
@@ -353,13 +311,29 @@ impl App for FuruApp {
"/login", "/login",
get({ get({
let config = Arc::clone(&self.config); let config = Arc::clone(&self.config);
move |i18n: I18n, db: Database, query: UrlQuery<LoginQuery>| { move |i18n: I18n,
db: Database,
session: Session,
query: UrlQuery<LoginQuery>| {
let config = Arc::clone(&config); let config = Arc::clone(&config);
async move { async move {
// No users at all → redirect to first-run setup // No users at all → redirect to first-run setup
if User::count_all(&db).await.unwrap_or(0) == 0 { if User::count_all(&db).await.unwrap_or(0) == 0 {
return Ok(auth::redirect("/admin/setup")); return Ok(auth::redirect("/admin/setup"));
} }
if let Some(next) = query.0.next.as_deref() {
if next.strip_prefix("/share/").is_some_and(is_share_token) {
auth::remember_post_login_redirect(&session, next).await?;
}
} else {
auth::clear_post_login_redirect(&session).await?;
}
if auth::get_session_identity(&session, &db).await.is_some() {
let destination = auth::get_post_login_redirect(&session)
.await?
.unwrap_or_else(|| "/".into());
return Ok(auth::redirect(&destination));
}
let message = query.0.error.unwrap_or_default(); let message = query.0.error.unwrap_or_default();
login_page_handler(i18n, &config, db, message) login_page_handler(i18n, &config, db, message)
.await? .await?
+9 -12
View File
@@ -808,9 +808,8 @@ const KNOWN_HTTP_ROUTES: &[&str] = &[
"/admin", "/admin",
"/swagger", "/swagger",
"/swagger/openapi.json", "/swagger/openapi.json",
"/share/track/{id}", "/share/{token}",
"/share/release/{id}", "/auth/status",
"/share/playlist/{token}",
"/metrics", "/metrics",
"/login", "/login",
"/logout", "/logout",
@@ -880,10 +879,11 @@ const KNOWN_HTTP_ROUTES: &[&str] = &[
"/api/player/artists", "/api/player/artists",
"/api/player/artists/{id}", "/api/player/artists/{id}",
"/api/player/releases/{id}", "/api/player/releases/{id}",
"/api/player/radio/{kind}/{id}",
"/api/player/playlists", "/api/player/playlists",
"/api/player/share-playlist", "/api/player/shares",
"/api/player/share-playlist/{id}", "/api/player/shares/{id}",
"/api/player/shares/{token}/{action}/{track_id}",
"/api/player/download/{track_id}",
"/api/player/playlists/{id}", "/api/player/playlists/{id}",
"/api/player/playlists/{id}/tracks", "/api/player/playlists/{id}/tracks",
"/api/player/likes", "/api/player/likes",
@@ -928,13 +928,10 @@ mod tests {
known_http_route("/admin/v2/api/jobs/metadata_backfill/runs/123"), known_http_route("/admin/v2/api/jobs/metadata_backfill/runs/123"),
Some("/admin/v2/api/jobs/{name}/runs/{run_id}") Some("/admin/v2/api/jobs/{name}/runs/{run_id}")
); );
assert_eq!(known_http_route("/share/abcDEF123"), Some("/share/{token}"));
assert_eq!( assert_eq!(
known_http_route("/share/playlist/abcDEF123"), known_http_route("/api/player/shares/abcDEF123/stream/42"),
Some("/share/playlist/{token}") Some("/api/player/shares/{token}/{action}/{track_id}")
);
assert_eq!(
known_http_route("/share/release/42"),
Some("/share/release/{id}")
); );
assert_eq!( assert_eq!(
known_http_route("/api/player/youtube/start"), known_http_route("/api/player/youtube/start"),
+135 -84
View File
@@ -418,16 +418,6 @@ pub async fn oidc_callback_handler(
config.oidc_user_groups, config.oidc_user_groups,
); );
if !is_allowed_by_groups(&groups, &config.oidc_user_groups, &config.oidc_admin_groups) {
tracing::warn!(
"OIDC login denied by group allowlist: sub={sub}, groups={groups:?}, user_groups={:?}, admin_groups={:?}",
config.oidc_user_groups,
config.oidc_admin_groups,
);
crate::metrics::record_auth_attempt("oidc", "failure", "not_in_group");
return redirect_login_with_error(i18n.t.login_access_denied);
}
// User provisioning logic. // User provisioning logic.
let user = match provision_user( let user = match provision_user(
&db, &db,
@@ -437,6 +427,7 @@ pub async fn oidc_callback_handler(
name.as_deref(), name.as_deref(),
&groups, &groups,
&config.oidc_admin_groups, &config.oidc_admin_groups,
&config.oidc_user_groups,
) )
.await .await
{ {
@@ -728,17 +719,6 @@ pub async fn oidc_mobile_callback_handler(
.map(|n| n.to_string()); .map(|n| n.to_string());
let groups = extract_groups_from_jwt(&id_token.to_string()); let groups = extract_groups_from_jwt(&id_token.to_string());
if !is_allowed_by_groups(&groups, &config.oidc_user_groups, &config.oidc_admin_groups) {
tracing::warn!(
"Mobile OIDC login denied by group allowlist: sub={sub}, groups={groups:?}, user_groups={:?}, admin_groups={:?}",
config.oidc_user_groups,
config.oidc_admin_groups,
);
crate::metrics::record_auth_attempt("mobile_oidc", "failure", "not_in_group");
clear_mobile_oidc_session(&session).await?;
return Ok(mobile_redirect_error(&app_redirect_uri, "access_denied"));
}
let user = match provision_user( let user = match provision_user(
&db, &db,
&issuer, &issuer,
@@ -747,6 +727,7 @@ pub async fn oidc_mobile_callback_handler(
name.as_deref(), name.as_deref(),
&groups, &groups,
&config.oidc_admin_groups, &config.oidc_admin_groups,
&config.oidc_user_groups,
) )
.await .await
{ {
@@ -759,6 +740,11 @@ pub async fn oidc_mobile_callback_handler(
} }
}; };
if !user.is_active() {
clear_mobile_oidc_session(&session).await?;
return Ok(mobile_redirect_error(&app_redirect_uri, "approval_pending"));
}
let exchange_code = auth::create_mobile_exchange_code(&db, user.id_val()) let exchange_code = auth::create_mobile_exchange_code(&db, user.id_val())
.await .await
.map_err(|e| cot::Error::internal(e.to_string()))?; .map_err(|e| cot::Error::internal(e.to_string()))?;
@@ -773,48 +759,26 @@ pub async fn oidc_mobile_callback_handler(
// User provisioning // User provisioning
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/// Resolve the role based on OIDC group membership. /// Group-derived access always takes precedence over local approval.
/// If `admin_groups` is non-empty and any user group matches, return "admin"; fn resolve_sso_role(
/// otherwise return "user". groups: &[String],
fn resolve_role(groups: &[String], admin_groups: &str) -> &'static str { admin_groups: &str,
if admin_groups.is_empty() { user_groups: &str,
return auth::Role::User.code(); ) -> Option<&'static str> {
let matches = |configured: &str| {
configured
.split(',')
.map(str::trim)
.filter(|group| !group.is_empty())
.any(|group| groups.iter().any(|g| g == group))
};
if matches(admin_groups) {
Some("admin")
} else if matches(user_groups) {
Some("user")
} else {
None
} }
let admin_set: std::collections::HashSet<&str> = admin_groups
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.collect();
if admin_set.is_empty() {
return auth::Role::User.code();
}
for g in groups {
if admin_set.contains(g.as_str()) {
return auth::Role::Admin.code();
}
}
auth::Role::User.code()
}
fn parse_group_set(groups: &str) -> std::collections::HashSet<&str> {
groups
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.collect()
}
fn has_any_group(groups: &[String], allowed: &std::collections::HashSet<&str>) -> bool {
groups.iter().any(|g| allowed.contains(g.as_str()))
}
fn is_allowed_by_groups(groups: &[String], user_groups: &str, admin_groups: &str) -> bool {
let user_set = parse_group_set(user_groups);
if user_set.is_empty() {
return true;
}
let admin_set = parse_group_set(admin_groups);
has_any_group(groups, &user_set) || has_any_group(groups, &admin_set)
} }
async fn provision_user( async fn provision_user(
@@ -825,8 +789,9 @@ async fn provision_user(
name: Option<&str>, name: Option<&str>,
groups: &[String], groups: &[String],
admin_groups: &str, admin_groups: &str,
user_groups: &str,
) -> Result<User, String> { ) -> Result<User, String> {
let role = resolve_role(groups, admin_groups); let role = resolve_sso_role(groups, admin_groups, user_groups);
// 1. Check for existing OIDC link. // 1. Check for existing OIDC link.
if let Some(mut link) = OidcLink::find_by_issuer_sub(db, issuer, sub) if let Some(mut link) = OidcLink::find_by_issuer_sub(db, issuer, sub)
@@ -841,8 +806,8 @@ async fn provision_user(
.await .await
.map_err(|e| format!("DB error updating OIDC link: {e}"))?; .map_err(|e| format!("DB error updating OIDC link: {e}"))?;
// Always update role on login. // Refresh only the SSO grant; preserve independent local approval.
user.update_role(db, role) user.sync_sso_role(db, role)
.await .await
.map_err(|e| format!("DB error updating user role: {e}"))?; .map_err(|e| format!("DB error updating user role: {e}"))?;
@@ -863,25 +828,6 @@ async fn provision_user(
} }
} }
// 2. No existing link — try to find a user by email.
if let Some(email_str) = email {
if let Some(mut user) = User::get_by_email(db, email_str)
.await
.map_err(|e| format!("DB error finding user by email: {e}"))?
{
// Create OIDC link for existing user.
OidcLink::create_link(db, user.id_val(), issuer, sub, email, name)
.await
.map_err(|e| format!("DB error creating OIDC link: {e}"))?;
user.update_role(db, role)
.await
.map_err(|e| format!("DB error updating user role: {e}"))?;
return Ok(user);
}
}
// 3. Create a brand-new user + OIDC link. // 3. Create a brand-new user + OIDC link.
// Generate a unique username from the sub or email. // Generate a unique username from the sub or email.
let username = if let Some(email_str) = email { let username = if let Some(email_str) = email {
@@ -1300,3 +1246,108 @@ mod tests {
assert!(safe_mobile_redirect_uri(Some("http://127.0.0.1:notaport/x")).is_none()); assert!(safe_mobile_redirect_uri(Some("http://127.0.0.1:notaport/x")).is_none());
} }
} }
#[cfg(test)]
mod approval_tests {
use super::*;
#[test]
fn matching_groups_are_required_and_admin_wins() {
let groups = vec!["listeners".into(), "admins".into()];
assert_eq!(
resolve_sso_role(&groups, " admins ", "listeners"),
Some("admin")
);
assert_eq!(
resolve_sso_role(&groups, "other", "listeners"),
Some("user")
);
assert_eq!(resolve_sso_role(&groups, "other", ""), None);
assert_eq!(resolve_sso_role(&[], "", ""), None);
}
#[tokio::test]
#[ignore = "requires a migrated disposable database in FURU_ACCESS_TEST_DATABASE_URL"]
async fn postgres_approval_survives_sso_changes_without_implicit_grants() {
let db = Database::new(std::env::var("FURU_ACCESS_TEST_DATABASE_URL").unwrap())
.await
.unwrap();
let subject = format!("approval-test-{}", uuid::Uuid::new_v4());
let provision = |groups: Vec<String>| {
let db = &db;
let subject = &subject;
async move {
provision_user(
db,
"https://test.example",
subject,
None,
Some("Test pending user"),
&groups,
"admins",
"listeners",
)
.await
.unwrap()
}
};
let first = provision(vec![]).await;
assert!(!first.is_active());
let mut again = provision(vec![]).await;
assert_eq!(again.id_val(), first.id_val());
again.approve(&db, "admin", 1).await.unwrap();
assert_eq!(provision(vec![]).await.role(), auth::Role::Admin);
assert_eq!(
provision(vec!["listeners".into()]).await.role(),
auth::Role::User
);
assert_eq!(
provision(vec!["admins".into()]).await.role(),
auth::Role::Admin
);
assert_eq!(provision(vec![]).await.role(), auth::Role::Admin);
let auto_sub = format!("auto-{subject}");
let automatic = provision_user(
&db,
"https://test.example",
&auto_sub,
None,
None,
&["listeners".into()],
"admins",
"listeners",
)
.await
.unwrap();
assert!(automatic.is_active());
let removed = provision_user(
&db,
"https://test.example",
&auto_sub,
None,
None,
&[],
"admins",
"listeners",
)
.await
.unwrap();
assert!(!removed.is_active());
assert_eq!(automatic.id_val(), removed.id_val());
// A stale User held by an OIDC callback must retain a newer local grant.
let mut stale = removed.clone();
let mut approving = removed.clone();
approving.approve(&db, "admin", 1).await.unwrap();
stale.sync_sso_role(&db, Some("user")).await.unwrap();
stale.sync_sso_role(&db, None).await.unwrap();
assert!(stale.is_active());
assert_eq!(stale.role(), auth::Role::Admin);
let username = stale.username_str().to_owned();
stale
.update_fields(&db, &username, None, Some("Renamed"), None, "")
.await
.unwrap();
assert!(!stale.is_active());
}
}
+1 -1
View File
@@ -324,7 +324,7 @@ pub(super) struct ShareLinkResponse {
} }
#[derive(Debug, Serialize, JsonSchema)] #[derive(Debug, Serialize, JsonSchema)]
pub(super) struct PlaylistShareDetail { pub(super) struct ShareDetail {
pub(super) token: String, pub(super) token: String,
pub(super) title: String, pub(super) title: String,
pub(super) tracks: Vec<TrackItem>, pub(super) tracks: Vec<TrackItem>,
+133 -565
View File
@@ -30,6 +30,7 @@ mod dto;
mod helpers; mod helpers;
mod queries; mod queries;
mod rows; mod rows;
mod sharing;
use dto::*; use dto::*;
use helpers::{cover_variant_url, load_release_uploaders, track_cover_variant_url}; use helpers::{cover_variant_url, load_release_uploaders, track_cover_variant_url};
@@ -114,9 +115,6 @@ const PLAYER_DEVICE_COMMAND_TTL_MS: i64 = 20_000;
const PLAYER_DEVICE_MAX_COMMANDS: usize = 32; const PLAYER_DEVICE_MAX_COMMANDS: usize = 32;
const PLAYER_JAM_IDLE_TTL_MS: i64 = 4 * 60 * 60 * 1000; const PLAYER_JAM_IDLE_TTL_MS: i64 = 4 * 60 * 60 * 1000;
const PLAYER_JAM_MAX_INVITEES: usize = 25; const PLAYER_JAM_MAX_INVITEES: usize = 25;
const PLAYER_RADIO_TRACK_LIMIT: usize = 40;
const PLAYER_RADIO_CANDIDATE_LIMIT: i64 = 220;
const PLAYER_RADIO_RELEASE_SEED_TRACKS: i64 = 4;
const FED_DEVICE_PREFIX: &str = "fed:"; const FED_DEVICE_PREFIX: &str = "fed:";
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -1641,6 +1639,8 @@ struct LastfmCallbackQuery {
#[template(path = "player.html")] #[template(path = "player.html")]
pub struct PlayerPageTemplate { pub struct PlayerPageTemplate {
pub t: &'static Translations, pub t: &'static Translations,
pub guest: bool,
pub share_token: String,
pub downloads_enabled: bool, pub downloads_enabled: bool,
pub torrent_downloads_enabled: bool, pub torrent_downloads_enabled: bool,
pub youtube_downloads_enabled: bool, pub youtube_downloads_enabled: bool,
@@ -1655,6 +1655,8 @@ mod page_template_tests {
fn download_manager_button_follows_the_global_switch() { fn download_manager_button_follows_the_global_switch() {
let disabled = PlayerPageTemplate { let disabled = PlayerPageTemplate {
t: Translations::for_lang(Lang::En), t: Translations::for_lang(Lang::En),
guest: false,
share_token: String::new(),
downloads_enabled: false, downloads_enabled: false,
torrent_downloads_enabled: false, torrent_downloads_enabled: false,
youtube_downloads_enabled: false, youtube_downloads_enabled: false,
@@ -1666,6 +1668,8 @@ mod page_template_tests {
let enabled = PlayerPageTemplate { let enabled = PlayerPageTemplate {
t: Translations::for_lang(Lang::En), t: Translations::for_lang(Lang::En),
guest: false,
share_token: String::new(),
downloads_enabled: true, downloads_enabled: true,
torrent_downloads_enabled: true, torrent_downloads_enabled: true,
youtube_downloads_enabled: true, youtube_downloads_enabled: true,
@@ -4770,15 +4774,15 @@ async fn similarity_search_handler(
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /api/player/share-playlist // POST /api/player/shares
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
async fn create_playlist_share_handler( async fn create_share_handler(
auth_ctx: auth::AuthContext, auth_ctx: auth::AuthContext,
session: Session, session: Session,
db: Database, db: Database,
pool: &sqlx::PgPool, pool: &sqlx::PgPool,
Json(body): Json<CreatePlaylistShareRequest>, Json(body): Json<CreateShareRequest>,
) -> cot::Result<cot::response::Response> { ) -> cot::Result<cot::response::Response> {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else { let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
@@ -4818,7 +4822,7 @@ async fn create_playlist_share_handler(
let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
sqlx::query( sqlx::query(
r#"INSERT INTO furumusic__playlist_share_link r#"INSERT INTO furumusic__share_link
(token, creator_user_id, title, track_ids_json, created_at) (token, creator_user_id, title, track_ids_json, created_at)
VALUES ($1, $2, $3, $4, $5)"#, VALUES ($1, $2, $3, $4, $5)"#,
) )
@@ -4833,51 +4837,7 @@ async fn create_playlist_share_handler(
Json(ShareLinkResponse { Json(ShareLinkResponse {
token: token.clone(), token: token.clone(),
url: format!("/share/playlist/{token}"), url: format!("/share/{token}"),
})
.into_response()
}
// ---------------------------------------------------------------------------
// GET /api/player/share-playlist/{id}
// ---------------------------------------------------------------------------
async fn playlist_share_detail_handler(
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
pool: &sqlx::PgPool,
path: Path<PathStringId>,
) -> cot::Result<cot::response::Response> {
let Some(_user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let token = path.0.id.trim().to_string();
let share: Option<(String, String)> = sqlx::query_as(
r#"SELECT title::text, track_ids_json::text
FROM furumusic__playlist_share_link
WHERE token = $1"#,
)
.bind(&token)
.fetch_optional(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let Some((title, track_ids_json)) = share else {
return Ok(json_error(
StatusCode::NOT_FOUND,
"shared playlist not found",
));
};
let ids: Vec<i64> = serde_json::from_str(&track_ids_json).unwrap_or_default();
let tracks = load_track_items_by_ids(pool, &ids).await?;
Json(PlaylistShareDetail {
token,
title,
tracks,
}) })
.into_response() .into_response()
} }
@@ -4993,11 +4953,20 @@ async fn stream_handler(
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
}; };
let track_id = path.0.track_id; audio_response(pool, config, request, path.0.track_id, false).await
}
async fn audio_response(
pool: &sqlx::PgPool,
config: &AppConfig,
request: &cot::http::Request<Body>,
track_id: i64,
download: bool,
) -> cot::Result<cot::http::Response<Body>> {
// Look up track → audio_file_id → MediaFile // Look up track → audio_file_id → MediaFile
let media = sqlx::query_as::<_, MediaFileRow>( let media = sqlx::query_as::<_, MediaFileRow>(
r#"SELECT mf.file_path, r#"SELECT mf.file_path,
mf.original_filename::text AS original_filename,
mf.mime_type::text as mime_type, mf.mime_type::text as mime_type,
mf.file_size_bytes, mf.file_size_bytes,
mf.sha256_hash::text AS sha256_hash, mf.sha256_hash::text AS sha256_hash,
@@ -5025,7 +4994,29 @@ async fn stream_handler(
)); ));
} }
let file_size = media.file_size_bytes as u64; let file_size = tokio::fs::metadata(&full_path)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?
.len();
let filename = media
.original_filename
.rsplit(['/', '\\'])
.next()
.filter(|name| !name.is_empty())
.unwrap_or("track");
let disposition = if download {
format!(
"attachment; filename=\"track-{}\"; filename*=UTF-8''{}",
track_id,
filename
.as_bytes()
.iter()
.map(|b| format!("%{b:02X}"))
.collect::<String>()
)
} else {
"inline".to_owned()
};
let etag = media_etag("audio", track_id, &media.sha256_hash, None); let etag = media_etag("audio", track_id, &media.sha256_hash, None);
// Parse Range header // Parse Range header
@@ -5037,40 +5028,61 @@ async fn stream_handler(
let (start, end) = range; let (start, end) = range;
let chunk_size = end - start + 1; let chunk_size = end - start + 1;
let data = read_file_range(&full_path, start, chunk_size).await?; use futures_util::TryStreamExt;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
let mut file = tokio::fs::File::open(&full_path)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
file.seek(std::io::SeekFrom::Start(start))
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let data = tokio_util::io::ReaderStream::new(file.take(chunk_size))
.map_err(|e| cot::Error::internal(e.to_string()));
crate::metrics::record_stream_request(true, chunk_size); crate::metrics::record_stream_request(true, chunk_size);
let response = cot::http::Response::builder() let response = cot::http::Response::builder()
.status(StatusCode::PARTIAL_CONTENT) .status(StatusCode::PARTIAL_CONTENT)
.header(CONTENT_TYPE, media.mime_type.as_str()) .header(CONTENT_TYPE, media.mime_type.as_str())
.header(ACCEPT_RANGES, "bytes") .header(ACCEPT_RANGES, "bytes")
.header("Content-Disposition", disposition.as_str())
.header("Cache-Control", "private, no-store")
.header(CONTENT_RANGE, format!("bytes {start}-{end}/{file_size}")) .header(CONTENT_RANGE, format!("bytes {start}-{end}/{file_size}"))
.header(CONTENT_LENGTH, chunk_size.to_string()) .header(CONTENT_LENGTH, chunk_size.to_string())
.header("ETag", etag.as_str()) .header("ETag", etag.as_str())
.header("X-Furumi-Content-Sha256", media.sha256_hash.as_str()) .header("X-Furumi-Content-Sha256", media.sha256_hash.as_str())
.header("X-Furumi-Content-Updated-At", media.created_at.as_str()) .header("X-Furumi-Content-Updated-At", media.created_at.as_str())
.body(Body::fixed(data)) .body(Body::streaming(data))
.expect("valid response"); .expect("valid response");
return Ok(response); return Ok(response);
} }
return Ok(cot::http::Response::builder()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(CONTENT_RANGE, format!("bytes */{file_size}"))
.body(Body::fixed(""))
.expect("valid response"));
} }
// No Range or invalid range: return full file // No Range: stream the full file.
let data = tokio::fs::read(&full_path) let file = tokio::fs::File::open(&full_path)
.await .await
.map_err(|e| cot::Error::internal(e.to_string()))?; .map_err(|e| cot::Error::internal(e.to_string()))?;
use futures_util::TryStreamExt;
let data =
tokio_util::io::ReaderStream::new(file).map_err(|e| cot::Error::internal(e.to_string()));
crate::metrics::record_stream_request(false, file_size); crate::metrics::record_stream_request(false, file_size);
let response = cot::http::Response::builder() let response = cot::http::Response::builder()
.status(StatusCode::OK) .status(StatusCode::OK)
.header(CONTENT_TYPE, media.mime_type.as_str()) .header(CONTENT_TYPE, media.mime_type.as_str())
.header(ACCEPT_RANGES, "bytes") .header(ACCEPT_RANGES, "bytes")
.header("Content-Disposition", disposition.as_str())
.header("Cache-Control", "private, no-store")
.header(CONTENT_LENGTH, file_size.to_string()) .header(CONTENT_LENGTH, file_size.to_string())
.header("ETag", etag.as_str()) .header("ETag", etag.as_str())
.header("X-Furumi-Content-Sha256", media.sha256_hash.as_str()) .header("X-Furumi-Content-Sha256", media.sha256_hash.as_str())
.header("X-Furumi-Content-Updated-At", media.created_at.as_str()) .header("X-Furumi-Content-Updated-At", media.created_at.as_str())
.body(Body::fixed(data)) .body(Body::streaming(data))
.expect("valid response"); .expect("valid response");
Ok(response) Ok(response)
@@ -5167,7 +5179,10 @@ async fn local_upload_handler(
{ {
Some(id) => Some(id), Some(id) => Some(id),
None => { None => {
return Ok(json_error(StatusCode::BAD_REQUEST, "invalid target playlist ID")); return Ok(json_error(
StatusCode::BAD_REQUEST,
"invalid target playlist ID",
));
} }
}, },
}; };
@@ -5319,7 +5334,8 @@ async fn local_upload_handler(
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
let sha256 = format!("{:x}", Sha256::digest(&bytes)); let sha256 = format!("{:x}", Sha256::digest(&bytes));
if let Err(error) = if let Err(error) =
crate::import_playlists::register(pool, user.id, playlist_id, &inbox_path, &sha256).await crate::import_playlists::register(pool, user.id, playlist_id, &inbox_path, &sha256)
.await
{ {
return Ok(json_error(StatusCode::BAD_REQUEST, &error.to_string())); return Ok(json_error(StatusCode::BAD_REQUEST, &error.to_string()));
} }
@@ -5452,6 +5468,9 @@ fn hex_value(byte: u8) -> Option<u8> {
} }
fn parse_range(header: &str, file_size: u64) -> Option<(u64, u64)> { fn parse_range(header: &str, file_size: u64) -> Option<(u64, u64)> {
if file_size == 0 {
return None;
}
let bytes_prefix = "bytes="; let bytes_prefix = "bytes=";
if !header.starts_with(bytes_prefix) { if !header.starts_with(bytes_prefix) {
return None; return None;
@@ -5559,8 +5578,18 @@ async fn cover_response(
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
}; };
cover_file_response(pool, config, media_file_id, variant_name).await
}
async fn cover_file_response(
pool: &sqlx::PgPool,
config: &AppConfig,
media_file_id: i64,
variant_name: Option<&str>,
) -> cot::Result<cot::http::Response<Body>> {
let media = sqlx::query_as::<_, MediaFileRow>( let media = sqlx::query_as::<_, MediaFileRow>(
r#"SELECT file_path, r#"SELECT file_path,
original_filename::text AS original_filename,
mime_type::text as mime_type, mime_type::text as mime_type,
file_size_bytes, file_size_bytes,
sha256_hash::text AS sha256_hash, sha256_hash::text AS sha256_hash,
@@ -8085,474 +8114,6 @@ async fn toggle_follow_artist_handler(
} }
} }
// ---------------------------------------------------------------------------
// GET /api/player/radio/{kind}/{id}
// ---------------------------------------------------------------------------
fn append_unique_track_ids(track_ids: &mut Vec<i64>, candidates: Vec<i64>, limit: usize) {
let mut seen: HashSet<i64> = track_ids.iter().copied().collect();
for candidate in candidates {
if track_ids.len() >= limit {
break;
}
if seen.insert(candidate) {
track_ids.push(candidate);
}
}
}
async fn track_primary_artist_ids(pool: &sqlx::PgPool, track_id: i64) -> cot::Result<Vec<i64>> {
sqlx::query_scalar::<_, i64>(
r#"SELECT artist_id
FROM furumusic__track_artist
WHERE track_id = $1 AND role <> 'featuring'
ORDER BY position, artist_id"#,
)
.bind(track_id)
.fetch_all(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))
}
async fn release_primary_artist_ids(pool: &sqlx::PgPool, release_id: i64) -> cot::Result<Vec<i64>> {
sqlx::query_scalar::<_, i64>(
r#"SELECT artist_id
FROM furumusic__release_artist
WHERE release_id = $1
ORDER BY position, artist_id"#,
)
.bind(release_id)
.fetch_all(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))
}
async fn fallback_radio_track_ids(
pool: &sqlx::PgPool,
user_id: i64,
artist_ids: &[i64],
excluded_ids: &[i64],
limit: i64,
) -> cot::Result<Vec<i64>> {
if limit <= 0 {
return Ok(Vec::new());
}
sqlx::query_scalar::<_, i64>(
r#"SELECT t.id
FROM furumusic__track t
JOIN furumusic__release r ON r.id = t.release_id
WHERE t.is_hidden = false
AND r.is_hidden = false
AND NOT (t.id = ANY($3::bigint[]))
ORDER BY (
CASE WHEN EXISTS (
SELECT 1 FROM furumusic__user_liked_track ult
WHERE ult.user_id = $1 AND ult.track_id = t.id
) THEN 9.0 ELSE 0.0 END
+ CASE WHEN EXISTS (
SELECT 1 FROM furumusic__track_artist ta
WHERE ta.track_id = t.id
AND ta.role <> 'featuring'
AND ta.artist_id = ANY($2::bigint[])
) THEN 5.0 ELSE 0.0 END
+ COALESCE(t.lastfm_rating, 0.0) * 0.7
+ ln(COALESCE(t.lastfm_playcount, 0)::double precision + 1.0) * 0.04
+ ln(COALESCE(t.lastfm_listeners, 0)::double precision + 1.0) * 0.03
+ random() * 2.0
) DESC, t.id
LIMIT $4"#,
)
.bind(user_id)
.bind(artist_ids)
.bind(excluded_ids)
.bind(limit)
.fetch_all(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))
}
async fn track_radio_candidate_ids(
pool: &sqlx::PgPool,
user_id: i64,
track_id: i64,
limit: i64,
) -> cot::Result<Vec<i64>> {
sqlx::query_scalar::<_, i64>(
r#"WITH seed_track AS (
SELECT t.id, t.release_id
FROM furumusic__track t
JOIN furumusic__release r ON r.id = t.release_id
WHERE t.id = $1 AND t.is_hidden = false AND r.is_hidden = false
),
seed_artists AS (
SELECT ta.artist_id
FROM furumusic__track_artist ta
JOIN seed_track st ON st.id = ta.track_id
WHERE ta.role <> 'featuring'
),
seed_tag_sources AS (
SELECT egt.genre_id,
ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight
FROM furumusic__entity_genre_tag egt
JOIN seed_track st ON egt.entity_kind = 'track' AND egt.entity_id = st.id
UNION ALL
SELECT tg.genre_id, 1.0 AS weight
FROM furumusic__track_genre tg
JOIN seed_track st ON st.id = tg.track_id
UNION ALL
SELECT egt.genre_id,
ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight
FROM furumusic__entity_genre_tag egt
JOIN seed_track st ON egt.entity_kind = 'release' AND egt.entity_id = st.release_id
),
seed_tags AS (
SELECT genre_id, max(weight) AS seed_weight
FROM seed_tag_sources
GROUP BY genre_id
),
candidate_tag_sources AS (
SELECT egt.entity_id AS track_id,
egt.genre_id,
ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight
FROM furumusic__entity_genre_tag egt
WHERE egt.entity_kind = 'track'
UNION ALL
SELECT tg.track_id, tg.genre_id, 1.0 AS weight
FROM furumusic__track_genre tg
UNION ALL
SELECT t.id AS track_id,
egt.genre_id,
ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight
FROM furumusic__track t
JOIN furumusic__entity_genre_tag egt
ON egt.entity_kind = 'release' AND egt.entity_id = t.release_id
),
candidate_tags AS (
SELECT track_id, genre_id, max(weight) AS weight
FROM candidate_tag_sources
GROUP BY track_id, genre_id
),
tag_scores AS (
SELECT ct.track_id, sum(st.seed_weight * ct.weight) AS tag_score
FROM candidate_tags ct
JOIN seed_tags st ON st.genre_id = ct.genre_id
GROUP BY ct.track_id
)
SELECT t.id
FROM furumusic__track t
JOIN furumusic__release r ON r.id = t.release_id
LEFT JOIN tag_scores score ON score.track_id = t.id
WHERE t.is_hidden = false
AND r.is_hidden = false
AND t.id <> $1
AND (
COALESCE(score.tag_score, 0.0) > 0.0
OR EXISTS (
SELECT 1
FROM furumusic__track_artist ta
JOIN seed_artists sa ON sa.artist_id = ta.artist_id
WHERE ta.track_id = t.id AND ta.role <> 'featuring'
)
OR EXISTS (
SELECT 1 FROM furumusic__user_liked_track ult
WHERE ult.user_id = $2 AND ult.track_id = t.id
)
)
ORDER BY (
COALESCE(score.tag_score, 0.0) * 12.0
+ CASE
WHEN EXISTS (
SELECT 1 FROM furumusic__user_liked_track ult
WHERE ult.user_id = $2 AND ult.track_id = t.id
) AND COALESCE(score.tag_score, 0.0) > 0.0 THEN 12.0
WHEN EXISTS (
SELECT 1 FROM furumusic__user_liked_track ult
WHERE ult.user_id = $2 AND ult.track_id = t.id
) THEN 3.0
ELSE 0.0
END
+ CASE WHEN EXISTS (
SELECT 1
FROM furumusic__track_artist ta
JOIN seed_artists sa ON sa.artist_id = ta.artist_id
WHERE ta.track_id = t.id AND ta.role <> 'featuring'
) THEN 4.0 ELSE 0.0 END
+ COALESCE(t.lastfm_rating, 0.0) * 0.65
+ ln(COALESCE(t.lastfm_playcount, 0)::double precision + 1.0) * 0.04
+ ln(COALESCE(t.lastfm_listeners, 0)::double precision + 1.0) * 0.03
+ random() * 1.6
) DESC, t.id
LIMIT $3"#,
)
.bind(track_id)
.bind(user_id)
.bind(limit)
.fetch_all(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))
}
async fn release_radio_candidate_ids(
pool: &sqlx::PgPool,
user_id: i64,
release_id: i64,
excluded_ids: &[i64],
limit: i64,
) -> cot::Result<Vec<i64>> {
sqlx::query_scalar::<_, i64>(
r#"WITH seed_release AS (
SELECT id
FROM furumusic__release
WHERE id = $1 AND is_hidden = false
),
seed_artists AS (
SELECT ra.artist_id
FROM furumusic__release_artist ra
JOIN seed_release sr ON sr.id = ra.release_id
),
seed_tag_sources AS (
SELECT egt.genre_id,
ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight
FROM furumusic__entity_genre_tag egt
JOIN seed_release sr ON egt.entity_kind = 'release' AND egt.entity_id = sr.id
UNION ALL
SELECT egt.genre_id,
ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight
FROM furumusic__track t
JOIN seed_release sr ON sr.id = t.release_id
JOIN furumusic__entity_genre_tag egt
ON egt.entity_kind = 'track' AND egt.entity_id = t.id
UNION ALL
SELECT tg.genre_id, 1.0 AS weight
FROM furumusic__track t
JOIN seed_release sr ON sr.id = t.release_id
JOIN furumusic__track_genre tg ON tg.track_id = t.id
),
seed_tags AS (
SELECT genre_id, max(weight) AS seed_weight
FROM seed_tag_sources
GROUP BY genre_id
),
candidate_release_tag_sources AS (
SELECT egt.entity_id AS release_id,
egt.genre_id,
ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight
FROM furumusic__entity_genre_tag egt
WHERE egt.entity_kind = 'release'
UNION ALL
SELECT t.release_id,
egt.genre_id,
ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight
FROM furumusic__track t
JOIN furumusic__entity_genre_tag egt
ON egt.entity_kind = 'track' AND egt.entity_id = t.id
UNION ALL
SELECT t.release_id, tg.genre_id, 1.0 AS weight
FROM furumusic__track t
JOIN furumusic__track_genre tg ON tg.track_id = t.id
),
candidate_release_tags AS (
SELECT release_id, genre_id, max(weight) AS weight
FROM candidate_release_tag_sources
GROUP BY release_id, genre_id
),
release_scores AS (
SELECT crt.release_id, sum(st.seed_weight * crt.weight) AS tag_score
FROM candidate_release_tags crt
JOIN seed_tags st ON st.genre_id = crt.genre_id
GROUP BY crt.release_id
),
candidate_tracks AS (
SELECT t.id,
t.release_id,
COALESCE(score.tag_score, 0.0) AS tag_score,
EXISTS (
SELECT 1 FROM furumusic__user_liked_track ult
WHERE ult.user_id = $2 AND ult.track_id = t.id
) AS liked,
EXISTS (
SELECT 1
FROM furumusic__release_artist ra
JOIN seed_artists sa ON sa.artist_id = ra.artist_id
WHERE ra.release_id = t.release_id
) AS same_artist,
COALESCE(t.lastfm_rating, 0.0) AS rating,
COALESCE(t.lastfm_playcount, 0)::double precision AS playcount,
COALESCE(t.lastfm_listeners, 0)::double precision AS listeners
FROM furumusic__track t
JOIN furumusic__release r ON r.id = t.release_id
LEFT JOIN release_scores score ON score.release_id = t.release_id
WHERE t.is_hidden = false
AND r.is_hidden = false
AND t.release_id <> $1
AND NOT (t.id = ANY($3::bigint[]))
AND (
COALESCE(score.tag_score, 0.0) > 0.0
OR EXISTS (
SELECT 1
FROM furumusic__release_artist ra
JOIN seed_artists sa ON sa.artist_id = ra.artist_id
WHERE ra.release_id = t.release_id
)
OR EXISTS (
SELECT 1 FROM furumusic__user_liked_track ult
WHERE ult.user_id = $2 AND ult.track_id = t.id
)
)
),
ranked_tracks AS (
SELECT *,
row_number() OVER (
PARTITION BY release_id
ORDER BY rating DESC, playcount DESC, listeners DESC, random() DESC, id
) AS release_rank
FROM candidate_tracks
)
SELECT id
FROM ranked_tracks
WHERE release_rank <= 4
ORDER BY (
tag_score * 12.0
+ CASE
WHEN liked AND tag_score > 0.0 THEN 11.0
WHEN liked THEN 3.0
ELSE 0.0
END
+ CASE WHEN same_artist THEN 3.5 ELSE 0.0 END
+ rating * 0.65
+ ln(playcount + 1.0) * 0.04
+ ln(listeners + 1.0) * 0.03
+ random() * 1.6
) DESC, id
LIMIT $4"#,
)
.bind(release_id)
.bind(user_id)
.bind(excluded_ids)
.bind(limit)
.fetch_all(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))
}
async fn build_track_radio_ids(
pool: &sqlx::PgPool,
user_id: i64,
track_id: i64,
) -> cot::Result<Option<Vec<i64>>> {
let seed_track = sqlx::query_scalar::<_, i64>(
r#"SELECT t.id
FROM furumusic__track t
JOIN furumusic__release r ON r.id = t.release_id
WHERE t.id = $1 AND t.is_hidden = false AND r.is_hidden = false"#,
)
.bind(track_id)
.fetch_optional(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
if seed_track.is_none() {
return Ok(None);
}
let mut ids = vec![track_id];
let candidate_ids =
track_radio_candidate_ids(pool, user_id, track_id, PLAYER_RADIO_CANDIDATE_LIMIT).await?;
append_unique_track_ids(&mut ids, candidate_ids, PLAYER_RADIO_TRACK_LIMIT);
let artist_ids = track_primary_artist_ids(pool, track_id).await?;
let remaining = PLAYER_RADIO_TRACK_LIMIT.saturating_sub(ids.len()) as i64;
let fallback_ids =
fallback_radio_track_ids(pool, user_id, &artist_ids, &ids, remaining).await?;
append_unique_track_ids(&mut ids, fallback_ids, PLAYER_RADIO_TRACK_LIMIT);
Ok(Some(ids))
}
async fn build_release_radio_ids(
pool: &sqlx::PgPool,
user_id: i64,
release_id: i64,
) -> cot::Result<Option<Vec<i64>>> {
let seed_release = sqlx::query_scalar::<_, i64>(
r#"SELECT id FROM furumusic__release WHERE id = $1 AND is_hidden = false"#,
)
.bind(release_id)
.fetch_optional(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
if seed_release.is_none() {
return Ok(None);
}
let mut ids = sqlx::query_scalar::<_, i64>(
r#"SELECT t.id
FROM furumusic__track t
JOIN furumusic__release r ON r.id = t.release_id
WHERE t.release_id = $1
AND t.is_hidden = false
AND r.is_hidden = false
ORDER BY COALESCE(t.lastfm_rating, 0.0) DESC,
COALESCE(t.lastfm_playcount, 0) DESC,
COALESCE(t.lastfm_listeners, 0) DESC,
t.disc_number NULLS FIRST,
t.track_number NULLS LAST,
t.id
LIMIT $2"#,
)
.bind(release_id)
.bind(PLAYER_RADIO_RELEASE_SEED_TRACKS)
.fetch_all(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let candidate_ids = release_radio_candidate_ids(
pool,
user_id,
release_id,
&ids,
PLAYER_RADIO_CANDIDATE_LIMIT,
)
.await?;
append_unique_track_ids(&mut ids, candidate_ids, PLAYER_RADIO_TRACK_LIMIT);
let artist_ids = release_primary_artist_ids(pool, release_id).await?;
let remaining = PLAYER_RADIO_TRACK_LIMIT.saturating_sub(ids.len()) as i64;
let fallback_ids =
fallback_radio_track_ids(pool, user_id, &artist_ids, &ids, remaining).await?;
append_unique_track_ids(&mut ids, fallback_ids, PLAYER_RADIO_TRACK_LIMIT);
Ok(Some(ids))
}
async fn radio_handler(
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
pool: &sqlx::PgPool,
path: Path<PathRadioSeed>,
) -> cot::Result<cot::response::Response> {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let seed = path.0;
let ids = match seed.kind.as_str() {
"track" => build_track_radio_ids(pool, user.id, seed.id).await?,
"release" => build_release_radio_ids(pool, user.id, seed.id).await?,
_ => return Ok(json_error(StatusCode::BAD_REQUEST, "unknown radio seed")),
};
let Some(ids) = ids else {
return Ok(json_error(StatusCode::NOT_FOUND, "radio seed not found"));
};
let tracks = load_track_items_by_ids(pool, &ids).await?;
Json(tracks).into_response()
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST /api/player/tracks-by-ids // POST /api/player/tracks-by-ids
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -10017,35 +9578,6 @@ impl App for PlayerApp {
}, },
"player_release_detail", "player_release_detail",
), ),
Route::with_handler_and_name(
"/radio/{kind}/{id}",
{
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
get(
move |auth_ctx: auth::AuthContext,
session: Session,
db: Database,
path: Path<PathRadioSeed>| {
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
async move {
let pg_pool = pool
.get_or_init(|| async {
sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(&pool_config.database_url)
.await
.expect("player pool")
})
.await;
radio_handler(auth_ctx, session, db, pg_pool, path).await
}
},
)
},
"player_radio",
),
// -- Playlists (list + create) -- // -- Playlists (list + create) --
Route::with_handler_and_name( Route::with_handler_and_name(
"/playlists", "/playlists",
@@ -10096,14 +9628,14 @@ impl App for PlayerApp {
), ),
// -- Shared playlist snapshots -- // -- Shared playlist snapshots --
Route::with_handler_and_name( Route::with_handler_and_name(
"/share-playlist", "/shares",
post({ post({
let pool = Arc::clone(&pool); let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config); let pool_config = Arc::clone(&pool_config);
move |auth_ctx: auth::AuthContext, move |auth_ctx: auth::AuthContext,
session: Session, session: Session,
db: Database, db: Database,
json: Json<CreatePlaylistShareRequest>| { json: Json<CreateShareRequest>| {
let pool = Arc::clone(&pool); let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config); let pool_config = Arc::clone(&pool_config);
async move { async move {
@@ -10116,15 +9648,15 @@ impl App for PlayerApp {
.expect("player pool") .expect("player pool")
}) })
.await; .await;
create_playlist_share_handler(auth_ctx, session, db, pg_pool, json) create_share_handler(auth_ctx, session, db, pg_pool, json)
.await .await
} }
} }
}), }),
"player_share_playlist", "player_create_share",
), ),
Route::with_handler_and_name( Route::with_handler_and_name(
"/share-playlist/{id}", "/shares/{id}",
get({ get({
let pool = Arc::clone(&pool); let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config); let pool_config = Arc::clone(&pool_config);
@@ -10144,12 +9676,12 @@ impl App for PlayerApp {
.expect("player pool") .expect("player pool")
}) })
.await; .await;
playlist_share_detail_handler(auth_ctx, session, db, pg_pool, path) sharing::detail_handler(auth_ctx, session, db, pg_pool, path)
.await .await
} }
} }
}), }),
"player_share_playlist_detail", "player_share_detail",
), ),
// -- Playlist detail (get, update, delete) -- // -- Playlist detail (get, update, delete) --
Route::with_handler_and_name( Route::with_handler_and_name(
@@ -10447,6 +9979,42 @@ impl App for PlayerApp {
}), }),
"player_follow_toggle", "player_follow_toggle",
), ),
Route::with_handler_and_name(
"/shares/{token}/{action}/{track_id}", get({
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
move |db: Database, path: Path<sharing::MediaPath>, request: cot::request::Request| {
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
async move {
let pg_pool = pool.get_or_init(|| async {
sqlx::postgres::PgPoolOptions::new().max_connections(5)
.connect(&pool_config.database_url).await.expect("player pool")
}).await;
let (live_config, _) = AppConfig::load_with_db(&db).await;
sharing::media_handler(pg_pool, &live_config, &request, path).await
}
}
}), "player_shared_media",
),
Route::with_handler_and_name(
"/download/{track_id}", get({
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
move |db: Database, auth_ctx: auth::AuthContext, session: Session, path: Path<PathTrackId>, request: cot::request::Request| {
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
async move {
let pg_pool = pool.get_or_init(|| async {
sqlx::postgres::PgPoolOptions::new().max_connections(5)
.connect(&pool_config.database_url).await.expect("player pool")
}).await;
let (live_config, _) = AppConfig::load_with_db(&db).await;
sharing::download_handler(auth_ctx, session, db, pg_pool, &live_config, &request, path).await
}
}
}), "player_download",
),
// -- Audio stream -- // -- Audio stream --
Route::with_handler_and_name( Route::with_handler_and_name(
"/stream/{track_id}", "/stream/{track_id}",
+1 -7
View File
@@ -54,7 +54,7 @@ pub(super) struct ReorderPlaylistRequest {
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub(super) struct CreatePlaylistShareRequest { pub(super) struct CreateShareRequest {
pub(super) track_ids: Vec<i64>, pub(super) track_ids: Vec<i64>,
pub(super) title: Option<String>, pub(super) title: Option<String>,
} }
@@ -76,12 +76,6 @@ pub(super) struct PathStringId {
pub(super) id: String, pub(super) id: String,
} }
#[derive(Debug, Deserialize)]
pub(super) struct PathRadioSeed {
pub(super) kind: String,
pub(super) id: i64,
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub(super) struct SearchQuery { pub(super) struct SearchQuery {
pub(super) q: String, pub(super) q: String,
+1 -1
View File
@@ -54,8 +54,8 @@ pub(super) struct ReleaseArtistRefRow {
#[derive(sqlx::FromRow)] #[derive(sqlx::FromRow)]
pub(super) struct MediaFileRow { pub(super) struct MediaFileRow {
pub(super) file_path: String, pub(super) file_path: String,
pub(super) original_filename: String,
pub(super) mime_type: String, pub(super) mime_type: String,
pub(super) file_size_bytes: i64,
pub(super) sha256_hash: String, pub(super) sha256_hash: String,
pub(super) created_at: String, pub(super) created_at: String,
} }
+125
View File
@@ -0,0 +1,125 @@
//! Public capabilities grant access only to a stored snapshot's visible tracks.
use super::*;
#[derive(Deserialize)]
pub(super) struct MediaPath {
token: String,
action: String,
track_id: i64,
}
async fn load_share(pool: &sqlx::PgPool, token: &str) -> cot::Result<Option<ShareDetail>> {
if !crate::is_share_token(token) {
return Ok(None);
}
let row: Option<(String, String)> =
sqlx::query_as("SELECT title, track_ids_json FROM furumusic__share_link WHERE token = $1")
.bind(token)
.fetch_optional(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
let Some((title, json)) = row else {
return Ok(None);
};
let ids: Vec<i64> =
serde_json::from_str(&json).map_err(|e| cot::Error::internal(e.to_string()))?;
let tracks = load_track_items_by_ids(pool, &ids).await?;
Ok(Some(ShareDetail {
token: token.to_owned(),
title,
tracks,
}))
}
pub(super) async fn detail_handler(
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
pool: &sqlx::PgPool,
path: Path<PathStringId>,
) -> cot::Result<cot::response::Response> {
let Some(mut share) = load_share(pool, &path.0.id).await? else {
return Ok(json_error(StatusCode::NOT_FOUND, "shared music not found"));
};
if auth::get_request_user(&auth_ctx, &session, &db)
.await
.is_none()
{
for track in &mut share.tracks {
track.stream_url = format!("/api/player/shares/{}/stream/{}", share.token, track.id);
if track.cover_url.is_some() {
track.cover_url = Some(format!(
"/api/player/shares/{}/cover/{}",
share.token, track.id
));
}
}
}
let mut response = Json(share).into_response()?;
response
.headers_mut()
.insert("Cache-Control", "private, no-store".parse().unwrap());
Ok(response)
}
pub(super) async fn media_handler(
pool: &sqlx::PgPool,
config: &AppConfig,
request: &cot::http::Request<Body>,
path: Path<MediaPath>,
) -> cot::Result<cot::response::Response> {
let p = path.0;
if !crate::is_share_token(&p.token) {
return Ok(json_error(StatusCode::NOT_FOUND, "shared music not found"));
}
// Media range requests need only a membership check, not the metadata and
// artist lists of every track in a potentially large shared queue.
let allowed: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM furumusic__share_link s
JOIN furumusic__track t ON t.id = $2
JOIN furumusic__release r ON r.id = t.release_id
WHERE s.token = $1 AND s.track_ids_json::jsonb @> jsonb_build_array($2::bigint)
AND t.is_hidden = false AND r.is_hidden = false)",
)
.bind(&p.token)
.bind(p.track_id)
.fetch_one(pool)
.await
.map_err(|e| cot::Error::internal(e.to_string()))?;
if !allowed {
return Ok(json_error(StatusCode::NOT_FOUND, "shared track not found"));
}
match p.action.as_str() {
"stream" | "download" => {
audio_response(pool, config, request, p.track_id, p.action == "download").await
}
"cover" => {
let cover: Option<i64> = sqlx::query_scalar(
"SELECT COALESCE(t.cover_file_id, r.cover_file_id) FROM furumusic__track t JOIN furumusic__release r ON r.id = t.release_id WHERE t.id = $1")
.bind(p.track_id).fetch_one(pool).await.map_err(|e| cot::Error::internal(e.to_string()))?;
match cover {
Some(id) => cover_file_response(pool, config, id, Some("card")).await,
None => Ok(json_error(StatusCode::NOT_FOUND, "cover not found")),
}
}
_ => Ok(json_error(StatusCode::NOT_FOUND, "not found")),
}
}
pub(super) async fn download_handler(
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
pool: &sqlx::PgPool,
config: &AppConfig,
request: &cot::http::Request<Body>,
path: Path<PathTrackId>,
) -> cot::Result<cot::response::Response> {
if auth::get_request_user(&auth_ctx, &session, &db)
.await
.is_none()
{
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
}
audio_response(pool, config, request, path.0.track_id, true).await
}
+80 -14
View File
@@ -19,6 +19,10 @@ pub struct User {
avatar_url: Option<String>, avatar_url: Option<String>,
role: LimitedString<32>, role: LimitedString<32>,
is_active: bool, is_active: bool,
local_role: Option<String>,
sso_role: Option<String>,
approved_by: Option<i64>,
approved_at: Option<String>,
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -50,6 +54,10 @@ impl User {
avatar_url: None, avatar_url: None,
role: LimitedString::new(role).unwrap(), role: LimitedString::new(role).unwrap(),
is_active: true, is_active: true,
local_role: Some(role.to_owned()),
sso_role: None,
approved_by: None,
approved_at: None,
}; };
user.insert(db).await?; user.insert(db).await?;
Ok(user) Ok(user)
@@ -72,8 +80,13 @@ impl User {
if let Some(pw) = new_password { if let Some(pw) = new_password {
self.password = Some(PasswordHash::from_password(&Password::new(pw)).into_string()); self.password = Some(PasswordHash::from_password(&Password::new(pw)).into_string());
} }
self.role = LimitedString::new(role).unwrap(); let local_role = (!role.is_empty()).then(|| role.to_owned());
self.save(db).await db.raw_with("UPDATE furumusic__user SET username = $1, email = $2, display_name = $3, password = $4, local_role = $5, role = COALESCE(sso_role, $5, 'user'), is_active = (sso_role IS NOT NULL OR $5 IS NOT NULL) WHERE id = $6",
&[&username.to_owned(), &self.email, &self.display_name, &self.password, &local_role, &self.id_val()]).await?;
if let Some(updated) = Self::get_by_id(db, self.id_val()).await? {
*self = updated;
}
Ok(())
} }
/// Look up a user by username. /// Look up a user by username.
@@ -126,13 +139,17 @@ impl User {
self.is_active self.is_active
} }
pub fn has_sso_admin_role(&self) -> bool {
self.sso_role.as_deref() == Some("admin")
}
/// Create a user without a password (for OIDC-only accounts). /// Create a user without a password (for OIDC-only accounts).
pub async fn create_oidc( pub async fn create_oidc(
db: &Database, db: &Database,
username: &str, username: &str,
email: Option<&str>, email: Option<&str>,
display_name: Option<&str>, display_name: Option<&str>,
role: &str, sso_role: Option<&str>,
) -> cot::db::Result<Self> { ) -> cot::db::Result<Self> {
let mut user = Self { let mut user = Self {
id: Auto::auto(), id: Auto::auto(),
@@ -141,24 +158,44 @@ impl User {
email: email.map(str::to_owned), email: email.map(str::to_owned),
display_name: display_name.map(str::to_owned), display_name: display_name.map(str::to_owned),
avatar_url: None, avatar_url: None,
role: LimitedString::new(role).unwrap(), role: LimitedString::new(sso_role.unwrap_or("user")).unwrap(),
is_active: true, is_active: sso_role.is_some(),
local_role: None,
sso_role: sso_role.map(str::to_owned),
approved_by: None,
approved_at: None,
}; };
user.insert(db).await?; user.insert(db).await?;
Ok(user) Ok(user)
} }
/// Update the user's role and persist the change. pub async fn sync_sso_role(
pub async fn update_role(&mut self, db: &Database, role: &str) -> cot::db::Result<()> { &mut self,
self.role = LimitedString::new(role).unwrap(); db: &Database,
self.save(db).await role: Option<&str>,
) -> cot::db::Result<()> {
let role = role.map(str::to_owned);
// Change just this grant atomically: a concurrent administrator approval
// must not be overwritten by a stale User loaded before the OIDC callback.
db.raw_with("UPDATE furumusic__user SET sso_role = $1, role = COALESCE($1, local_role, 'user'), is_active = ($1 IS NOT NULL OR local_role IS NOT NULL) WHERE id = $2", &[&role, &self.id_val()]).await?;
if let Some(updated) = Self::get_by_id(db, self.id_val()).await? {
*self = updated;
}
Ok(())
} }
/// Find a user by email address. pub async fn approve(
pub async fn get_by_email(db: &Database, email: &str) -> cot::db::Result<Option<Self>> { &mut self,
cot::db::query!(User, $email == Some(email.to_owned())) db: &Database,
.get(db) role: &str,
.await admin_id: i64,
) -> cot::db::Result<()> {
db.raw_with("UPDATE furumusic__user SET local_role = $1, role = COALESCE(sso_role, $1), is_active = true, approved_by = $2, approved_at = $3 WHERE id = $4",
&[&role.to_owned(), &admin_id, &chrono::Utc::now().to_rfc3339(), &self.id_val()]).await?;
if let Some(updated) = Self::get_by_id(db, self.id_val()).await? {
*self = updated;
}
Ok(())
} }
} }
@@ -393,9 +430,38 @@ pub mod db_migrations {
&[Operation::custom(create_oidc_link_indexes).build()]; &[Operation::custom(create_oidc_link_indexes).build()];
} }
#[cot::db::migrations::migration_op]
async fn add_local_approval(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> {
ctx.db.raw("ALTER TABLE furumusic__user ADD COLUMN local_role text, ADD COLUMN sso_role text, ADD COLUMN approved_by bigint, ADD COLUMN approved_at text").await?;
// Existing password accounts retain local access. OIDC-only accounts retain
// their last SSO role until the next verified login refreshes group membership.
ctx.db.raw("UPDATE furumusic__user SET local_role = CASE WHEN password IS NOT NULL AND is_active THEN role ELSE NULL END, sso_role = CASE WHEN password IS NULL AND is_active THEN role ELSE NULL END").await?;
ctx.db
.raw("DROP TABLE furumusic__playlist_share_link")
.await?;
ctx.db.raw("CREATE TABLE furumusic__share_link (token text PRIMARY KEY, creator_user_id bigint NOT NULL, title text NOT NULL, track_ids_json text NOT NULL, created_at text NOT NULL)").await?;
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub struct M0053LocalApprovalAndPublicShares;
impl migrations::Migration for M0053LocalApprovalAndPublicShares {
const APP_NAME: &'static str = "furumusic";
const MIGRATION_NAME: &'static str = "m_0053_local_approval_and_public_shares";
const DEPENDENCIES: &'static [migrations::MigrationDependency] = &[
migrations::MigrationDependency::migration("furumusic", "m_0005_oidc_link_indexes"),
migrations::MigrationDependency::migration(
"furumusic",
"m_0037_create_playlist_share_links",
),
];
const OPERATIONS: &'static [Operation] = &[Operation::custom(add_local_approval).build()];
}
pub const MIGRATIONS: &[&SyncDynMigration] = &[ pub const MIGRATIONS: &[&SyncDynMigration] = &[
&M0003CreateUser, &M0003CreateUser,
&M0004CreateOidcLink, &M0004CreateOidcLink,
&M0005OidcLinkIndexes, &M0005OidcLinkIndexes,
&M0053LocalApprovalAndPublicShares,
]; ];
} }
+25
View File
@@ -0,0 +1,25 @@
<aside class="sidebar" id="admin-navigation" :class="{'is-open': menuOpen}" :data-compact="isCompact" :inert="isCompact && !menuOpen" :role="isCompact ? 'dialog' : null" :aria-modal="isCompact && menuOpen ? 'true' : null" aria-label="Admin navigation" tabindex="-1" x-effect="adminOverlay.sync($el, isCompact && menuOpen)" @keydown="adminOverlay.keydown($event, $el)">
<div class="brand">
<div><div class="brand-title">FuruMusic <span class="version">v{{ version }}</span></div><div class="admin-user">{{ user_name }} · {{ user_role }}</div></div>
<button class="icon-btn nav-close" data-dialog-close aria-label="Close navigation" @click="closeMenu()"><i data-lucide="x"></i></button>
</div>
<nav aria-label="Administration" class="nav-sections" @click="if ($event.target.closest('.nav-btn')) closeMenu()">
<div class="nav-group">
<div class="nav-label">Operations</div>
<button class="nav-btn" :class="{active: activeView === 'reviews'}" :aria-current="activeView === 'reviews' ? 'page' : null" @click="openReviews()"><i data-lucide="inbox"></i><span>Review Queue</span><span class="nav-count" x-text="reviewTotalAll()"></span></button>
<button class="nav-btn" :class="{active: activeView === 'jobs'}" :aria-current="activeView === 'jobs' ? 'page' : null" @click="openJobs()"><i data-lucide="calendar-clock"></i><span>Tasks</span><span class="nav-count" x-text="jobs.length || 0"></span></button>
</div>
<div class="nav-group">
<div class="nav-label">Music</div>
<button class="nav-btn" :class="{active: activeView === 'library'}" :aria-current="activeView === 'library' ? 'page' : null" @click="openLibrary(libraryKind)"><i data-lucide="library"></i><span>Library Workbench</span><span class="nav-count" x-text="fmt(stats.tracks || 0)"></span></button>
<button class="nav-btn" :class="{active: activeView === 'tools'}" :aria-current="activeView === 'tools' ? 'page' : null" @click="openTools()"><i data-lucide="wrench"></i><span>Library Tools</span></button>
<button class="nav-btn" :class="{active: activeView === 'statistics'}" :aria-current="activeView === 'statistics' ? 'page' : null" @click="openStatistics()"><i data-lucide="chart-no-axes-combined"></i><span>Statistics</span></button>
</div>
<div class="nav-group">
<div class="nav-label">Instance</div>
<button class="nav-btn" :class="{active: activeView === 'users'}" :aria-current="activeView === 'users' ? 'page' : null" @click="openUsers()"><i data-lucide="users"></i><span>Users</span><span class="nav-count" x-text="users.online_count ? users.online_count + ' online' : ''"></span></button>
<button class="nav-btn" :class="{active: activeView === 'settings'}" :aria-current="activeView === 'settings' ? 'page' : null" @click="openSettings()"><i data-lucide="settings"></i><span>Settings</span></button>
</div>
</nav>
<a class="nav-player btn" href="/"><i data-lucide="music-2"></i>Back to player</a>
</aside>
+193
View File
@@ -0,0 +1,193 @@
<style>
/* Shared admin UI contract. Keep breakpoints in sync with admin/ui.html. */
:root { --admin-gap:16px; --admin-touch:44px; --admin-header:64px; --admin-radius:10px; }
html { overscroll-behavior:none; }
:focus-visible { outline:2px solid var(--accent); outline-offset:3px; }
.admin-shell { min-width:0; }
.sidebar { overflow:auto; overscroll-behavior:contain; padding-bottom:env(safe-area-inset-bottom); }
.brand { display:flex; align-items:center; justify-content:space-between; gap:12px; }
.nav-player { margin:12px; margin-top:auto; min-height:44px; flex:none; }
.nav-btn { min-height:44px; height:auto; padding-block:10px; }
.nav-group { padding-block:8px; }
.nav-label { letter-spacing:.08em; }
.nav-btn.active { background:rgba(29,185,84,.12); box-shadow:inset 3px 0 var(--accent); }
.menu-toggle, .nav-close, .nav-backdrop, .workspace-tabs, .section-jump { display:none; }
.main { overscroll-behavior:contain; scrollbar-gutter:stable; }
.main.is-locked { overflow:hidden; }
.topbar { min-height:var(--admin-header); height:auto; }
.top-actions { flex:none; }
.content { min-width:0; padding:var(--admin-gap); }
.content > *, .panel-head > *, .toolbar > *, .modal-body > *, .settings-section > *, .image-editor > * { min-width:0; }
.panel-head, .toolbar, .action-strip { flex-wrap:wrap; }
.panel-head > .toolbar { margin-left:auto; }
.toolbar { max-width:100%; }
.search { max-width:100%; min-width:0; }
.btn { text-decoration:none; white-space:normal; line-height:1.3; }
.icon-btn { flex:none; }
.segmented { max-width:100%; min-width:0; overflow:auto; flex-wrap:nowrap; }
.seg-btn { flex:none; }
.panel-title strong, .panel-title span, .setting-help, .selection-summary, .repair-context { overflow-wrap:anywhere; }
.table-wrap { max-width:100%; overscroll-behavior:contain; }
.table-wrap:focus-visible { outline-offset:-3px; }
.jobs-page { grid-template-columns:minmax(0,1fr) minmax(280px,340px); height:calc(100dvh - 100px); }
.run-row { width:100%; color:inherit; text-align:left; background:transparent; font:inherit; }
.row-link { display:block; max-width:100%; padding:0; background:transparent; color:inherit; text-align:left; cursor:pointer; }
.row-link:hover { text-decoration:underline; }
.job-fact > .btn { grid-column:2; justify-self:start; }
.job-fact > form { grid-column:1 / -1; }
.task-form { position:static; max-height:100%; }
.settings-section { scroll-margin-top:calc(var(--admin-header) + 70px); }
.settings-federation-body { grid-template-columns:minmax(0,4fr) minmax(0,8fr); }
.download-method-controls { grid-template-columns:minmax(0,.75fr) minmax(0,1.25fr); }
.proxy-row { grid-template-columns:minmax(0,1.4fr) minmax(0,.8fr) minmax(0,.8fr) auto; }
.field { display:block; min-width:0; }
.modal-backdrop { padding:24px; overscroll-behavior:contain; }
.modal { display:flex; flex-direction:column; width:min(760px,100%); max-width:100%; max-height:calc(100dvh - 48px); }
.modal.user-modal { width:min(860px,100%); }
.modal.merge-modal { width:min(1180px,100%); }
.modal-head { flex:none; min-width:0; padding:12px 16px; }
.modal-head [data-dialog-close] { flex:none; min-width:44px; min-height:44px; }
.modal-body { min-height:0; max-height:none; overflow:auto; overscroll-behavior:contain; padding:16px; }
.dialog-actions { position:sticky; bottom:-16px; z-index:4; display:flex; align-items:center; justify-content:flex-end; flex-wrap:wrap; gap:8px; margin:16px -16px -16px; padding:12px 16px; border-top:1px solid var(--border-color); background:var(--bg-secondary); }
.merge-footer.dialog-actions { justify-content:space-between; }
.track-field { min-width:0; margin:0; }
.track-field > span { display:none; }
.toast { z-index:50; max-width:min(420px,calc(100vw - 24px)); bottom:max(18px,env(safe-area-inset-bottom)); overflow-wrap:anywhere; }
.repair-plan-body { max-width:100%; }
.repair-work, .repair-side { min-width:0; }
.repair-manual { max-width:100%; overflow:auto; }
.repair-diff { table-layout:auto; }
.settings-actions { padding-bottom:max(12px,env(safe-area-inset-bottom)); }
@media (max-width:1279px) {
.workspace-tabs { display:flex; gap:4px; padding:4px; margin-bottom:12px; border:1px solid var(--border-color); border-radius:8px; background:var(--bg-secondary); }
.workspace-tabs button { flex:1; min-width:0; min-height:44px; padding:8px; border-radius:5px; background:transparent; color:var(--text-secondary); cursor:pointer; }
.workspace-tabs [aria-selected="true"] { background:var(--bg-active); color:var(--text-primary); }
.jobs-page { display:block; height:auto; }
.jobs-page .jobs-list-panel, .jobs-page .task-form, .jobs-page .run-log-panel { display:none; max-height:none; }
.jobs-page[data-task-pane="list"] .jobs-list-panel,
.jobs-page[data-task-pane="details"] .task-form,
.jobs-page[data-task-pane="logs"] .run-log-panel { display:flex; }
.task-form-body { overflow:visible; }
.run-log-body { min-height:300px; overflow:visible; }
.run-log-output { min-height:50dvh; max-height:70dvh; }
.settings-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"access" "oidc" "agent" "agentstatus" "similarity" "similaritystatus" "downloads" "federation" "lastfm" "developer" "actions"; }
.settings-federation-body { grid-template-columns:minmax(0,1fr); }
.repair-shell { grid-template-columns:250px minmax(0,1fr); }
}
@media (max-width:1023px) {
:root { --admin-gap:16px; }
.admin-shell { grid-template-columns:minmax(0,1fr); }
.sidebar { position:fixed; inset:0 auto 0 0; z-index:25; width:min(320px,calc(100vw - 48px)); height:100dvh; transform:translateX(-100%); visibility:hidden; transition:transform .18s ease, visibility .18s; padding-top:env(safe-area-inset-top); box-shadow:16px 0 48px #0006; }
.sidebar.is-open { transform:translateX(0); visibility:visible; }
.nav-backdrop { display:block; position:fixed; inset:0; z-index:24; background:#0009; }
.menu-toggle, .nav-close { display:inline-flex; align-items:center; justify-content:center; min-width:44px; min-height:44px; }
.topbar { display:grid; grid-template-columns:44px minmax(0,1fr) auto; gap:10px; padding:10px 16px; padding-top:max(10px,env(safe-area-inset-top)); }
.page-title h1 { font-size:18px; }
.page-title p { line-height:1.4; }
.panel-head { gap:12px; }
.panel-head > .toolbar { margin-left:0; }
.library-row { grid-template-columns:32px minmax(0,1fr) 110px; }
.library-row .tags { grid-column:2 / -1; grid-row:2; }
.library-row > .badge { grid-column:3; grid-row:1; justify-self:end; }
.section-jump { display:flex; align-items:center; gap:12px; margin-bottom:16px; font-size:13px; color:var(--text-secondary); }
.section-jump select { flex:1; width:auto; }
.primary-line, .secondary-line { white-space:normal; overflow-wrap:anywhere; }
.users-table, .statistics-table { min-width:700px; }
}
@media (max-width:767px) {
:root { --admin-gap:12px; }
.topbar { gap:8px; padding-inline:12px; }
.top-actions { gap:6px; }
.top-actions .btn { width:44px; height:44px; padding:0; justify-content:center; }
.top-action-label, .page-title p { display:none; }
.page-title h1 { font-size:17px; overflow-wrap:anywhere; }
.btn, .icon-btn, .seg-btn { min-height:44px; height:auto; }
.icon-btn { width:44px; }
.btn { padding:10px 12px; }
.search, .setting-field input, .setting-field select, .field input, .field select, .field textarea, .setting-field textarea, .proxy-row input, .download-method-controls select, .youtube-cookie-picker select, .repair-composer textarea { font-size:16px; min-height:44px; }
.search { width:100%; }
.toolbar { gap:8px; }
.panel-head { padding:12px; align-items:stretch; }
.panel-head > .toolbar { width:100%; }
.toolbar > input.search { flex:1 1 180px; }
.segmented { width:100%; }
.seg-btn { min-width:max-content; }
.action-strip { padding:12px; gap:12px; align-items:stretch; }
.action-strip > .toolbar { width:100%; }
.action-strip > .selection-summary { flex-basis:100%; }
.stats-strip, .statistics-summary, .user-summary-grid, .user-profile-facts, .user-stats-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }
.stat-cell { padding:12px; }
.stat-value { font-size:24px; }
.stats-strip { gap:8px; }
.table-wrap, .review-table-wrap, .users-table-wrap, .job-table-wrap { max-height:none; overflow:visible; }
.responsive-table { display:block; table-layout:auto; min-width:0; width:100%; }
.responsive-table thead { position:absolute; width:1px; height:1px; overflow:hidden; clip-path:inset(50%); }
.responsive-table tbody { display:block; }
.responsive-table tr { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; margin:0 12px 12px; padding:14px; border:1px solid var(--border-color); border-radius:8px; background:var(--bg-primary); }
.responsive-table tr.active { border-color:var(--accent); }
.responsive-table td { display:flex; flex-direction:column; align-items:flex-start; gap:5px; width:auto; height:auto; min-width:0; padding:0; border:0; overflow-wrap:anywhere; white-space:normal; }
.responsive-table td::before { content:attr(data-label); color:var(--text-subdued); font-size:10px; font-weight:750; text-transform:uppercase; letter-spacing:.04em; }
.responsive-table td[data-primary], .responsive-table td[data-label="Actions"], .responsive-table td[data-label="Account"], .responsive-table td[data-label="Tags"] { grid-column:1 / -1; }
.responsive-table td[data-primary] { font-size:15px; }
.responsive-table .primary-line { font-size:14px; }
.responsive-table .secondary-line { line-height:1.5; }
.responsive-table .tags { max-height:none; }
.responsive-table .inline-runs { flex-wrap:wrap; }
.responsive-table .run-chip { min-height:36px; max-width:none; }
.responsive-table .toolbar { justify-content:flex-start; flex-wrap:wrap; }
.row-link { min-height:44px; display:flex; align-items:center; }
.check { width:22px; height:22px; }
.library-row { grid-template-columns:26px minmax(0,1fr) auto; padding:12px; gap:10px; }
.library-row > .tags { max-height:none; }
.editor-grid, .settings-grid, .federation-status-grid, .download-method-controls, .proxy-row, .metadata-backfill-options .option-grid { grid-template-columns:minmax(0,1fr); }
.setting-field, .settings-wide, .setting-field.settings-short { max-width:none; }
.settings-grid, .settings-federation-body, .probe-body { padding:12px; }
.settings-federation-body .settings-grid, .settings-federation-body .probe-body { padding:0; }
.youtube-cookie-picker, .youtube-cookie-upload, .transport-log-head { align-items:stretch; flex-direction:column; }
.settings-actions { position:static; }
.settings-actions .toolbar { justify-content:flex-end; }
.modal-backdrop { padding:0; }
.modal, .modal.user-modal, .modal.merge-modal { width:100%; height:100dvh; max-height:100dvh; border:0; border-radius:0; }
.modal-head { padding-top:max(12px,env(safe-area-inset-top)); }
.modal-body { flex:1; padding-bottom:max(16px,env(safe-area-inset-bottom)); }
.dialog-actions { padding-bottom:max(12px,env(safe-area-inset-bottom)); }
.modal-body .toolbar { flex-wrap:wrap; }
.image-editor { grid-template-columns:96px minmax(0,1fr); }
.image-preview { width:96px; }
.image-actions { flex-wrap:wrap; }
.image-actions input[type="file"] { max-width:100%; }
.user-activity-row { grid-template-columns:44px minmax(0,1fr); }
.user-activity-cover { width:44px; height:44px; }
.user-activity-time { grid-column:2; min-width:0; text-align:left; }
.user-activity-title, .user-activity-meta, .user-activity-sub, .user-profile-facts strong { white-space:normal; overflow-wrap:anywhere; }
.release-track-head, .merge-track-head { display:none; }
.merge-track-list { min-width:0; }
.release-track-row, .merge-track-row { grid-template-columns:repeat(2,minmax(0,1fr)); padding:12px; gap:10px; }
.release-track-row > div, .merge-track-row > div { grid-column:1 / -1; }
.release-track-row .icon-btn { justify-self:end; grid-column:2; }
.track-field > span { display:block; color:var(--text-subdued); font-size:11px; margin-bottom:6px; }
.release-track-title, .release-track-meta { white-space:normal; overflow-wrap:anywhere; }
.merge-track-row > span { grid-column:1 / -1; }
.merge-order-actions { justify-content:flex-end; gap:8px; }
.merge-release-grid { grid-template-columns:minmax(0,1fr); }
.repair-shell { grid-template-columns:minmax(0,1fr); height:auto; min-height:0; }
.repair-side .panel:first-child .repair-scroll { max-height:260px; }
.repair-work .repair-chat { min-height:420px; height:65dvh; max-height:720px; }
.repair-plan-actions { align-items:stretch; flex-direction:column; }
.repair-message { max-width:100%; }
.repair-composer { flex-wrap:wrap; }
.repair-composer textarea { flex-basis:100%; }
.repair-composer .btn { margin-left:auto; }
.repair-diff { min-width:760px; }
.repair-manual { overscroll-behavior:contain; }
.statistics-ranking-head { align-items:stretch; flex-direction:column; }
.statistics-filters { padding:12px; }
.statistics-toolbar label { flex:1 1 140px; min-width:0; }
.statistics-toolbar .search { width:100%; }
.statistics-chart { padding:16px; }
.statistics-service-grid { grid-template-columns:minmax(0,1fr); padding:12px; }
.job-fact { grid-template-columns:70px minmax(0,1fr); }
.job-fact span:last-child { white-space:normal; overflow-wrap:anywhere; }
}
@media (prefers-reduced-motion:reduce) { .sidebar { transition:none; } }
</style>
+7 -7
View File
@@ -5,13 +5,13 @@
{% block head_extra %} {% block head_extra %}
<style> <style>
* { margin: 0; padding: 0; box-sizing: border-box; } * { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: system-ui, -apple-system, sans-serif; background: #f5f5f5; color: #333; display: flex; justify-content: center; align-items: center; min-height: 100vh; } body { font-family: system-ui, -apple-system, sans-serif; background: #f5f5f5; color: #333; display: flex; justify-content: center; align-items: center; min-height: 100dvh; padding: max(16px, env(safe-area-inset-top)) 16px max(16px, env(safe-area-inset-bottom)); }
.setup-card { background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.12); padding: 2rem 2.5rem; width: 100%; max-width: 400px; } .setup-card { background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.12); padding: clamp(20px, 5vw, 40px); width: 100%; max-width: 400px; }
.setup-card h1 { margin-bottom: 1.5rem; font-size: 1.5rem; text-align: center; } .setup-card h1 { margin-bottom: 1.5rem; font-size: 1.5rem; text-align: center; }
.setup-card label { display: block; margin-bottom: .25rem; font-weight: 600; font-size: .9rem; } .setup-card label { display: block; margin-bottom: .25rem; font-weight: 600; font-size: .9rem; }
.setup-card input[type="text"], .setup-card input[type="text"],
.setup-card input[type="password"] { width: 100%; padding: .5rem .7rem; margin-bottom: 1rem; border: 1px solid #ccc; border-radius: 4px; font-size: .95rem; } .setup-card input[type="password"] { width: 100%; padding: .5rem .7rem; margin-bottom: 1rem; border: 1px solid #ccc; border-radius: 4px; font-size: 16px; min-height: 44px; }
.setup-card button { display: block; width: 100%; padding: .6rem; border: none; border-radius: 4px; font-size: 1rem; cursor: pointer; background: #1a1a2e; color: #fff; } .setup-card button { display: block; width: 100%; padding: .6rem; min-height: 44px; border: none; border-radius: 4px; font-size: 1rem; cursor: pointer; background: #1a1a2e; color: #fff; }
.setup-card button:hover { background: #16213e; } .setup-card button:hover { background: #16213e; }
.setup-card .flash { color: #856404; background: #fff3cd; padding: .5rem .75rem; border-radius: 4px; margin-bottom: 1rem; text-align: center; font-size: .9rem; } .setup-card .flash { color: #856404; background: #fff3cd; padding: .5rem .75rem; border-radius: 4px; margin-bottom: 1rem; text-align: center; font-size: .9rem; }
</style> </style>
@@ -27,11 +27,11 @@
<form method="post" action="/admin/setup"> <form method="post" action="/admin/setup">
<label for="username">{{ t.setup_username }}</label> <label for="username">{{ t.setup_username }}</label>
<input type="text" name="username" id="username" required> <input type="text" name="username" id="username" autocomplete="username" required>
<label for="password">{{ t.setup_password }}</label> <label for="password">{{ t.setup_password }}</label>
<input type="password" name="password" id="password" required> <input type="password" name="password" id="password" autocomplete="new-password" required>
<label for="confirm_password">{{ t.setup_confirm }}</label> <label for="confirm_password">{{ t.setup_confirm }}</label>
<input type="password" name="confirm_password" id="confirm_password" required> <input type="password" name="confirm_password" id="confirm_password" autocomplete="new-password" required>
<button type="submit">{{ t.setup_submit }}</button> <button type="submit">{{ t.setup_submit }}</button>
</form> </form>
</div> </div>
File diff suppressed because it is too large. Load diff
+120
View File
@@ -0,0 +1,120 @@
<script>
// Shared responsive shell state. Business data stays in adminV2().
function adminUI() {
return {
menuOpen: false,
isCompact: false,
isTaskStacked: false,
taskPane: 'list',
initUI() {
const compact = window.matchMedia('(max-width: 1023px)');
const stacked = window.matchMedia('(max-width: 1279px)');
const update = () => {
this.isCompact = compact.matches;
this.isTaskStacked = stacked.matches;
if (!this.isCompact) this.menuOpen = false;
};
update();
compact.addEventListener('change', update);
stacked.addEventListener('change', update);
this._uiCleanup = () => {
compact.removeEventListener('change', update);
stacked.removeEventListener('change', update);
};
this.$watch('activeView', () => {
this.closeMenu();
if (this.$refs?.main) this.$refs.main.scrollTop = 0;
});
},
destroy() {
this._uiCleanup?.();
if (this.poller) clearInterval(this.poller);
},
openMenu() { this.menuOpen = true; },
closeMenu() { this.menuOpen = false; },
showTaskPane(pane) {
this.taskPane = pane;
if (this.isTaskStacked) this.$nextTick(() => document.getElementById('task-tab-' + pane)?.focus());
},
taskTabKeydown(event) {
const panes = ['list', 'details', 'logs'];
const index = panes.indexOf(this.taskPane);
const keys = {ArrowRight:(index + 1) % 3, ArrowLeft:(index + 2) % 3, Home:0, End:2};
if (!(event.key in keys)) return;
event.preventDefault();
this.showTaskPane(panes[keys[event.key]]);
},
jumpToSettings(section) {
const target = document.getElementById('settings-' + section);
if (!target) return;
target.scrollIntoView({behavior:window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth', block:'start'});
target.setAttribute('tabindex', '-1');
target.focus({preventScroll:true});
},
};
}
// All modal dialogs and the mobile navigation share one focus/scroll lifecycle.
// State is outside Alpine reactivity so opening a dialog does not retrigger x-effect.
const adminOverlay = (() => {
const states = new WeakMap();
const stack = [];
const frame = callback => window.requestAnimationFrame(callback);
const focusables = element => [...element.querySelectorAll('button:not(:disabled), a[href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex="0"]')]
.filter(node => node.getClientRects().length && !node.closest('[inert]'));
function updateBackground() {
const top = stack.at(-1);
const main = document.getElementById('admin-main');
const nav = document.getElementById('admin-navigation');
if (main) { main.inert = !!top; main.classList.toggle('is-locked', !!top); }
if (nav) nav.inert = (top && top !== nav) || (nav.dataset.compact === 'true' && !nav.classList.contains('is-open'));
for (const entry of stack) entry.inert = entry !== top;
}
function sync(element, open) {
const previous = states.get(element);
if (previous?.open === open) return;
states.set(element, {open, returnFocus:open ? document.activeElement : previous?.returnFocus});
if (open) {
stack.push(element);
frame(() => {
if (stack.at(-1) !== element) return;
updateBackground();
const dialog = element.querySelector('[role="dialog"]') || element;
dialog.focus({preventScroll:true});
});
} else {
const index = stack.indexOf(element);
if (index !== -1) stack.splice(index, 1);
element.inert = element.id !== 'admin-navigation';
frame(() => {
updateBackground();
const top = stack.at(-1);
if (top) {
if (!top.contains(document.activeElement)) (top.querySelector('[role="dialog"]') || top).focus({preventScroll:true});
} else if (previous?.open) {
const target = previous.returnFocus;
if (target?.isConnected && target.getClientRects().length && !target.closest('[inert]')) target.focus({preventScroll:true});
else document.querySelector('.menu-toggle')?.focus({preventScroll:true});
}
});
}
}
function keydown(event, element) {
if (stack.at(-1) !== element) return;
if (event.key === 'Escape' && !event.defaultPrevented) {
const close = element.querySelector('[data-dialog-close]');
if (close && !close.disabled) { event.preventDefault(); event.stopPropagation(); close.click(); }
} else if (event.key === 'Tab') {
const nodes = focusables(element);
const first = nodes[0], last = nodes.at(-1);
if (!first) { event.preventDefault(); return; }
if (event.shiftKey && (document.activeElement === first || !nodes.includes(document.activeElement))) {
event.preventDefault(); last.focus();
} else if (!event.shiftKey && (document.activeElement === last || !nodes.includes(document.activeElement))) {
event.preventDefault(); first.focus();
}
}
}
return {sync, keydown};
})();
</script>
+252 -2264
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
{% extends "base.html" %}
{% block title %}{{ t.approval_heading }} | {{ t.site_name }}{% endblock title %}
{% block head_extra %}
<style>
body { margin:0; min-height:100vh; display:grid; place-items:center; background:#121212; color:#eee; font-family:system-ui,sans-serif; }
.approval-card { max-width:440px; margin:24px; padding:36px; border:1px solid #333; border-radius:18px; background:#1b1b1b; }
h1 { font-size:24px; } p { line-height:1.6; color:#bbb; } a { color:#b7d79f; }
</style>
{% endblock head_extra %}
{% block body %}
<main class="approval-card"><h1>{{ t.approval_heading }}</h1><p>{{ t.approval_message }}</p><a href="/logout">{{ t.player_log_out }}</a></main>
<script>
setInterval(async () => {
try {
const response = await fetch('/auth/status', {cache:'no-store'});
if (!response.ok) return;
const {status} = await response.json();
if (status === 'active') location.replace('/');
else if (status === 'anonymous') location.replace('/login');
} catch {}
}, 5000);
</script>
{% endblock body %}
+83 -108
View File
@@ -1,9 +1,11 @@
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js"></script> <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js"></script>
<script> <script>
const GUEST = {{ guest }};
const SHARE_TOKEN = "{{ share_token }}";
// Handle expired sessions centrally, including background player requests. // Handle expired sessions centrally, including background player requests.
let loginRedirectStarted = false; let loginRedirectStarted = false;
function redirectOnUnauthorized(status) { function redirectOnUnauthorized(status) {
if (status !== 401 || loginRedirectStarted) return; if (GUEST || status !== 401 || loginRedirectStarted) return;
loginRedirectStarted = true; loginRedirectStarted = true;
window.location.replace('/login'); window.location.replace('/login');
} }
@@ -60,8 +62,8 @@ const T = {
lastfmDisconnectConfirm: "{{ t.player_lastfm_disconnect_confirm }}", lastfmDisconnectConfirm: "{{ t.player_lastfm_disconnect_confirm }}",
lastfmConnectFailed: "{{ t.player_lastfm_connect_failed }}", lastfmConnectFailed: "{{ t.player_lastfm_connect_failed }}",
lastfmDisconnectFailed: "{{ t.player_lastfm_disconnect_failed }}", lastfmDisconnectFailed: "{{ t.player_lastfm_disconnect_failed }}",
startRadio: "{{ t.player_start_radio }}", download: "{{ t.track_download }}",
radioFailed: "{{ t.player_radio_failed }}", shareUnavailable: "{{ t.share_unavailable }}",
searchSimilarTo: "{{ t.player_search_similar_to }}", searchSimilarTo: "{{ t.player_search_similar_to }}",
findSimilar: "{{ t.player_find_similar }}", findSimilar: "{{ t.player_find_similar }}",
similarityFailed: "{{ t.player_similarity_failed }}", similarityFailed: "{{ t.player_similarity_failed }}",
@@ -342,6 +344,7 @@ document.addEventListener('alpine:init', () => {
} }
}, },
navigate(link) { navigate(link) {
if (GUEST) return;
if (!link || !link.id) return; if (!link || !link.id) return;
this.close(); this.close();
const library = Alpine.store('library'); const library = Alpine.store('library');
@@ -388,35 +391,39 @@ document.addEventListener('alpine:init', () => {
return copied; return copied;
}, },
copyTrack(track, trigger = null) { async copyTrack(track, trigger = null) {
const id = Number(track?.id || track); const id = Number(track?.id || track);
if (!id) return; if (id) return this.copyTracks([{id}], track?.title || T.sharedPlaylist, trigger);
this.copyUrl(`/share/track/${id}`, trigger);
}, },
async copyQueue(trigger = null) { async copyQueue(trigger = null) {
const queue = Alpine.store('queue'); return this.copyTracks(Alpine.store('queue')?.tracks || [], T.sharedPlaylist, trigger);
return this.copyTracks(queue?.tracks || [], T.sharedPlaylist, trigger);
}, },
async copyRelease(release, trigger = null) { async copyRelease(release, trigger = null) {
const id = Number(release?.id || release || 0); try {
if (!id) return; const id = Number(release?.id || release || 0);
return this.copyUrl(`/share/release/${id}`, trigger); if (!id) return;
const response = await fetch(`/api/player/releases/${id}`);
if (!response.ok) throw new Error('release load failed');
const data = await response.json();
return this.copyTracks(data.tracks || [], data.title || T.sharedPlaylist, trigger);
} catch { this.flashTrigger(trigger, false); }
}, },
async copyTracks(tracks, title = T.sharedPlaylist, trigger = null) { async copyTracks(tracks, title = T.sharedPlaylist, trigger = null) {
if (GUEST) return this.copyUrl(`/share/${SHARE_TOKEN}`, trigger);
const trackIds = (tracks || []).map(track => Number(track.id)).filter(Boolean); const trackIds = (tracks || []).map(track => Number(track.id)).filter(Boolean);
if (!trackIds.length) return; if (!trackIds.length) return;
try { try {
const res = await fetch('/api/player/share-playlist', { const res = await fetch('/api/player/shares', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ track_ids: trackIds, title }), body: JSON.stringify({ track_ids: trackIds, title }),
}); });
if (!res.ok) throw new Error('share failed'); if (!res.ok) throw new Error('share failed');
const data = await res.json(); const data = await res.json();
await this.copyUrl(data.url || `/share/playlist/${data.token}`, trigger); await this.copyUrl(data.url || `/share/${data.token}`, trigger);
} catch (err) { } catch (err) {
this.flashTrigger(trigger, false); this.flashTrigger(trigger, false);
console.warn(err); console.warn(err);
@@ -468,84 +475,24 @@ document.addEventListener('alpine:init', () => {
}, },
async handleInitialShareLinks() { async handleInitialShareLinks() {
if (this._handledInitialLink) return; if (this._handledInitialLink || !SHARE_TOKEN) return;
this._handledInitialLink = true; this._handledInitialLink = true;
const params = new URLSearchParams(window.location.search);
const trackId = Number(params.get('track') || 0);
const releaseId = Number(params.get('release') || 0);
const playlistToken = (params.get('playlist_share') || '').trim();
if (trackId > 0) {
await this.openSharedTrack(trackId);
this._clearShareQuery();
} else if (releaseId > 0) {
await this.openSharedRelease(releaseId);
this._clearShareQuery();
} else if (playlistToken) {
await this.openSharedPlaylist(playlistToken);
this._clearShareQuery();
}
},
async openSharedTrack(trackId) {
try { try {
const res = await fetch('/api/player/tracks-by-ids', { const response = await fetch(`/api/player/shares/${SHARE_TOKEN}`);
method: 'POST', if (!response.ok) throw new Error('share unavailable');
headers: { 'Content-Type': 'application/json' }, const data = await response.json();
body: JSON.stringify({ ids: [Number(trackId)] }), const tracks = data.tracks || [];
}); Alpine.store('library').showSharedPlaylist(data);
if (!res.ok) throw new Error('track load failed'); if (!tracks.length) throw new Error('share empty');
const tracks = await res.json();
const track = Array.isArray(tracks) ? tracks[0] : null;
if (!track) return;
this.markSharedTrack(track.id);
if (track.release_id) {
await Alpine.store('library').openRelease(track.release_id, { focusSharedTrackId: track.id });
}
const queue = Alpine.store('queue');
queue.tracks = [track];
queue.currentIndex = 0;
Alpine.store('player')._playLocal(track, { paused: true });
this.focusSharedTrack(track.id);
} catch (err) {
console.warn(err);
}
},
async openSharedRelease(releaseId) {
const id = Number(releaseId || 0);
if (!id) return;
this.markSharedTrack(null);
await Alpine.store('library').openRelease(id);
},
async openSharedPlaylist(token) {
try {
const res = await fetch(`/api/player/share-playlist/${encodeURIComponent(token)}`);
if (!res.ok) throw new Error('playlist load failed');
const data = await res.json();
const tracks = Array.isArray(data.tracks) ? data.tracks : [];
if (!tracks.length) return;
const queue = Alpine.store('queue'); const queue = Alpine.store('queue');
queue.tracks = tracks; queue.tracks = tracks;
queue.currentIndex = 0; queue.currentIndex = 0;
Alpine.store('player')._playLocal(tracks[0], { paused: true }); Alpine.store('player')._playLocal(tracks[0], {paused:true});
Alpine.store('library').showSharedPlaylist(data); } catch {
} catch (err) { Alpine.store('library').showSharedPlaylist({title:T.shareUnavailable, tracks:[]});
console.warn(err);
} }
}, },
_clearShareQuery() {
const url = new URL(window.location.href);
url.searchParams.delete('track');
url.searchParams.delete('release');
url.searchParams.delete('playlist_share');
const query = url.searchParams.toString();
const next = `${url.pathname}${query ? '?' + query : ''}${window.location.hash}`;
history.replaceState({}, '', next);
},
}); });
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -553,17 +500,33 @@ document.addEventListener('alpine:init', () => {
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
Alpine.store('user', { Alpine.store('user', {
profile: null, profile: null,
accessStatus: "anonymous",
menuOpen: false, menuOpen: false,
settingsOpen: false, settingsOpen: false,
lastfm: { configured: false, connected: false, username: null, reauth_required: false, last_error: null }, lastfm: { configured: false, connected: false, username: null, reauth_required: false, last_error: null },
lastfmBusy: false, lastfmBusy: false,
init() { init() {
if (GUEST) {
this.checkAccess();
setInterval(() => this.checkAccess(), 5000);
return;
}
this.cleanLastfmQuery(); this.cleanLastfmQuery();
this.load(); this.load();
this.loadLastfm(); this.loadLastfm();
}, },
async checkAccess() {
try {
const response = await fetch('/auth/status', {cache:'no-store'});
if (!response.ok) return;
const data = await response.json();
this.accessStatus = data.status;
if (data.status === 'active') window.location.reload();
} catch {}
},
cleanLastfmQuery() { cleanLastfmQuery() {
const url = new URL(window.location.href); const url = new URL(window.location.href);
if (!url.searchParams.has('lastfm')) return; if (!url.searchParams.has('lastfm')) return;
@@ -799,11 +762,7 @@ document.addEventListener('alpine:init', () => {
_prefetchedQueueKey: null, _prefetchedQueueKey: null,
_baseDocumentTitle: '', _baseDocumentTitle: '',
_hasInitialShareLink() { _hasInitialShareLink() { return !!SHARE_TOKEN; },
const params = new URLSearchParams(window.location.search);
return Number(params.get('track') || 0) > 0
|| (params.get('playlist_share') || '').trim().length > 0;
},
init() { init() {
audio.volume = this.volume; audio.volume = this.volume;
@@ -1447,6 +1406,7 @@ document.addEventListener('alpine:init', () => {
}, },
_saveState() { _saveState() {
if (GUEST) return;
const queue = Alpine.store('queue'); const queue = Alpine.store('queue');
if (!this.currentTrack && queue.tracks.length === 0) return; if (!this.currentTrack && queue.tracks.length === 0) return;
const state = this._buildStatePayload(); const state = this._buildStatePayload();
@@ -1458,6 +1418,7 @@ document.addEventListener('alpine:init', () => {
}, },
_saveStateSync() { _saveStateSync() {
if (GUEST) return;
const queue = Alpine.store('queue'); const queue = Alpine.store('queue');
if (!this.currentTrack && queue.tracks.length === 0) return; if (!this.currentTrack && queue.tracks.length === 0) return;
const state = this._buildStatePayload(); const state = this._buildStatePayload();
@@ -1466,6 +1427,7 @@ document.addEventListener('alpine:init', () => {
}, },
async _restoreState() { async _restoreState() {
if (GUEST) return;
try { try {
const res = await fetch('/api/player/state'); const res = await fetch('/api/player/state');
if (!res.ok) return; if (!res.ok) return;
@@ -1521,6 +1483,7 @@ document.addEventListener('alpine:init', () => {
}, },
_recordHistory(endedReason, unloading = false) { _recordHistory(endedReason, unloading = false) {
if (GUEST) return;
const track = this._historyTrack; const track = this._historyTrack;
if (this._historyRecorded || !track || !this._playbackStartedAt) return; if (this._historyRecorded || !track || !this._playbackStartedAt) return;
if (!Number.isInteger(Number(track.id)) || track.federated_cache) return; if (!Number.isInteger(Number(track.id)) || track.federated_cache) return;
@@ -1603,6 +1566,7 @@ document.addEventListener('alpine:init', () => {
}, },
_sendNowPlaying() { _sendNowPlaying() {
if (GUEST) return;
if (this._nowPlayingSent || !this.currentTrack) return; if (this._nowPlayingSent || !this.currentTrack) return;
if (!Number.isInteger(Number(this.currentTrack.id)) || this.currentTrack.federated_cache) { if (!Number.isInteger(Number(this.currentTrack.id)) || this.currentTrack.federated_cache) {
return; return;
@@ -1652,6 +1616,7 @@ document.addEventListener('alpine:init', () => {
_lastPlaybackState: null, _lastPlaybackState: null,
init() { init() {
if (GUEST) return;
this.id = this._ensureId(); this.id = this._ensureId();
this.currentJamId = sessionStorage.getItem('furu_player_jam_id') || null; this.currentJamId = sessionStorage.getItem('furu_player_jam_id') || null;
this.heartbeat(); this.heartbeat();
@@ -1868,6 +1833,7 @@ document.addEventListener('alpine:init', () => {
}, },
isActive() { isActive() {
if (GUEST) return true;
if (this.isControllingRemoteJam()) return false; if (this.isControllingRemoteJam()) return false;
return !this.activeDeviceId || this.activeDeviceId === this.id; return !this.activeDeviceId || this.activeDeviceId === this.id;
}, },
@@ -2635,6 +2601,10 @@ document.addEventListener('alpine:init', () => {
_hashNav: false, // guard against circular hash updates _hashNav: false, // guard against circular hash updates
init() { init() {
if (GUEST) {
this.$nextTick(() => Alpine.store('sharing').handleInitialShareLinks());
return;
}
this._setupScroll(); this._setupScroll();
this.loadFederationLikes(); this.loadFederationLikes();
window.addEventListener('furumi:track-availability', event => { window.addEventListener('furumi:track-availability', event => {
@@ -2668,6 +2638,7 @@ document.addEventListener('alpine:init', () => {
}, },
_navigateFromHash(options = {}) { _navigateFromHash(options = {}) {
if (GUEST) return;
if (this._hashNav) return; if (this._hashNav) return;
const hash = location.hash || '#artists'; const hash = location.hash || '#artists';
const match = hash.match(/^#(\w+)(?:\/([-]?\d+))?(?:\?(.*))?$/); const match = hash.match(/^#(\w+)(?:\/([-]?\d+))?(?:\?(.*))?$/);
@@ -2778,6 +2749,7 @@ document.addEventListener('alpine:init', () => {
}, },
goArtists(options = {}) { goArtists(options = {}) {
if (GUEST) return;
this._beginNavigation('#artists', options); this._beginNavigation('#artists', options);
if (this.artistFilter !== 'all' || this.artistsPage === 0) { if (this.artistFilter !== 'all' || this.artistsPage === 0) {
this._resetArtistList('all'); this._resetArtistList('all');
@@ -2795,6 +2767,7 @@ document.addEventListener('alpine:init', () => {
}, },
goMyUploads(options = {}) { goMyUploads(options = {}) {
if (GUEST) return;
this._beginNavigation('#uploads', options); this._beginNavigation('#uploads', options);
if (this.artistFilter !== 'uploads' || this.artistsPage === 0) { if (this.artistFilter !== 'uploads' || this.artistsPage === 0) {
this._resetArtistList('uploads'); this._resetArtistList('uploads');
@@ -2854,6 +2827,7 @@ document.addEventListener('alpine:init', () => {
}, },
async openArtist(id, options = {}) { async openArtist(id, options = {}) {
if (GUEST) return;
this.stopArtistFederation(); this.stopArtistFederation();
this._beginNavigation('#artist/' + id, options); this._beginNavigation('#artist/' + id, options);
this.searchQuery = ''; this.searchQuery = '';
@@ -3145,26 +3119,22 @@ document.addEventListener('alpine:init', () => {
return `${T.lastfmRating}: ${Math.round(value)}\n${this.trackInfo(track)}`; return `${T.lastfmRating}: ${Math.round(value)}\n${this.trackInfo(track)}`;
}, },
async startRadio(kind, id) { downloadTrack(track) {
if (!kind || !id) return; if (!track?.id) return;
try { const link = document.createElement('a');
const res = await fetch(`/api/player/radio/${encodeURIComponent(kind)}/${encodeURIComponent(id)}`); link.href = GUEST ? `/api/player/shares/${SHARE_TOKEN}/download/${track.id}` : `/api/player/download/${track.id}`;
if (!res.ok) throw new Error('radio failed'); link.download = '';
const tracks = await res.json(); document.body.appendChild(link);
if (!Array.isArray(tracks) || tracks.length === 0) throw new Error('radio empty'); link.click();
Alpine.store('queue').playRelease(tracks, 0); link.remove();
Alpine.store('info').close();
} catch (err) {
console.warn(err);
window.alert(T.radioFailed);
}
}, },
openTrackInfo(track) { openTrackInfo(track) {
Alpine.store('info').openRows(T.trackInfoTitle, this.trackInfoRows(track), [ const rows = this.trackInfoRows(track).map(row => GUEST && row.links
{ label: T.startRadio, run: () => this.startRadio('track', track?.id) }, ? {...row, value: row.links.map(link => link.label).join(', '), links: null} : row);
{ label: T.findSimilar, run: () => this.searchSimilar(track) }, const actions = [{label:T.download, run:() => this.downloadTrack(track)}];
]); if (!GUEST) actions.push({label:T.findSimilar, run:() => this.searchSimilar(track)});
Alpine.store('info').openRows(T.trackInfoTitle, rows, actions);
}, },
uploadersInfo(uploaders) { uploadersInfo(uploaders) {
@@ -3188,9 +3158,7 @@ document.addEventListener('alpine:init', () => {
}, },
openReleaseInfo(release) { openReleaseInfo(release) {
Alpine.store('info').openRows(T.releaseInfoTitle, this.releaseInfoRows(release), [ Alpine.store('info').openRows(T.releaseInfoTitle, this.releaseInfoRows(release));
{ label: T.startRadio, run: () => this.startRadio('release', release?.id) },
]);
}, },
infoLinks(items, type) { infoLinks(items, type) {
@@ -3289,6 +3257,7 @@ document.addEventListener('alpine:init', () => {
}, },
async openRelease(id, options = {}) { async openRelease(id, options = {}) {
if (GUEST) return;
this.stopReleaseFederation(); this.stopReleaseFederation();
this._beginNavigation('#release/' + id, options); this._beginNavigation('#release/' + id, options);
this.searchQuery = ''; this.searchQuery = '';
@@ -3405,6 +3374,7 @@ document.addEventListener('alpine:init', () => {
}, },
async openPlaylist(id, options = {}) { async openPlaylist(id, options = {}) {
if (GUEST) return;
this._beginNavigation('#playlist/' + id, options); this._beginNavigation('#playlist/' + id, options);
Alpine.store('playlists')?.stopEdit?.(); Alpine.store('playlists')?.stopEdit?.();
this.view = 'playlist_detail'; this.view = 'playlist_detail';
@@ -3491,6 +3461,7 @@ document.addEventListener('alpine:init', () => {
}, },
async search(query, options = {}) { async search(query, options = {}) {
if (GUEST) return;
const q = (query || '').trim(); const q = (query || '').trim();
if (!q) { if (!q) {
this.clearSearch(); this.clearSearch();
@@ -3518,6 +3489,7 @@ document.addEventListener('alpine:init', () => {
}, },
async searchSimilar(trackOrId, options = {}) { async searchSimilar(trackOrId, options = {}) {
if (GUEST) return;
const id = Number(typeof trackOrId === 'object' ? trackOrId?.id : trackOrId); const id = Number(typeof trackOrId === 'object' ? trackOrId?.id : trackOrId);
if (!Number.isInteger(id) || id <= 0) return; if (!Number.isInteger(id) || id <= 0) return;
const track = typeof trackOrId === 'object' ? trackOrId : null; const track = typeof trackOrId === 'object' ? trackOrId : null;
@@ -4494,6 +4466,7 @@ document.addEventListener('alpine:init', () => {
_set: new Set(), _set: new Set(),
init() { init() {
if (GUEST) return;
this.reload(); this.reload();
}, },
@@ -4563,6 +4536,7 @@ document.addEventListener('alpine:init', () => {
artists: [], artists: [],
init() { init() {
if (GUEST) return;
this.reload(); this.reload();
}, },
@@ -6503,6 +6477,7 @@ document.addEventListener('alpine:init', () => {
_pointerDragEnd: null, _pointerDragEnd: null,
init() { init() {
if (GUEST) return;
this.reload(); this.reload();
}, },
+54 -45
View File
@@ -1,4 +1,4 @@
<div class="app-layout" <div class="app-layout{% if guest %} guest-player{% endif %}"
x-data x-data
@keydown.window.space="if (!['INPUT','TEXTAREA','SELECT'].includes(document.activeElement?.tagName)) { $event.preventDefault(); $store.player.toggle(); }" @keydown.window.space="if (!['INPUT','TEXTAREA','SELECT'].includes(document.activeElement?.tagName)) { $event.preventDefault(); $store.player.toggle(); }"
@keydown.window.arrow-left="if (!['INPUT','TEXTAREA','SELECT'].includes(document.activeElement?.tagName)) { $event.preventDefault(); $store.player.seekRelative(-5); }" @keydown.window.arrow-left="if (!['INPUT','TEXTAREA','SELECT'].includes(document.activeElement?.tagName)) { $event.preventDefault(); $store.player.seekRelative(-5); }"
@@ -7,6 +7,7 @@
> >
<div class="main-content"> <div class="main-content">
{% if !guest %}
<!-- Left Sidebar --> <!-- Left Sidebar -->
<div class="sidebar-left"> <div class="sidebar-left">
<div class="user-widget" x-show="$store.user.profile" x-cloak> <div class="user-widget" x-show="$store.user.profile" x-cloak>
@@ -119,17 +120,17 @@
</div> </div>
<template x-if="pl.is_own && pl.kind === 'user'"> <template x-if="pl.is_own && pl.kind === 'user'">
<div class="playlist-item-actions"> <div class="playlist-item-actions">
<button class="playlist-action-btn" @click.stop="$store.playlists.startRename(pl)" title="{{ t.player_rename }}"> <button data-member-only class="playlist-action-btn" @click.stop="$store.playlists.startRename(pl)" title="{{ t.player_rename }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
</button> </button>
<button class="playlist-action-btn" @click.stop="$store.playlists.deletePlaylist(pl.id)" title="{{ t.player_delete }}"> <button data-member-only class="playlist-action-btn" @click.stop="$store.playlists.deletePlaylist(pl.id)" title="{{ t.player_delete }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
</button> </button>
</div> </div>
</template> </template>
</div> </div>
</template> </template>
<button class="sidebar-create-btn" @click="$store.playlists.showCreate()"> <button data-member-only class="sidebar-create-btn" @click="$store.playlists.showCreate()">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
{{ t.player_new_playlist }} {{ t.player_new_playlist }}
</button> </button>
@@ -156,6 +157,7 @@
</div> </div>
</div> </div>
{% endif %}
<template x-if="$store.mobile.libraryOpen"> <template x-if="$store.mobile.libraryOpen">
<div class="mobile-library-backdrop" @click.self="$store.mobile.closeLibrary()" x-cloak> <div class="mobile-library-backdrop" @click.self="$store.mobile.closeLibrary()" x-cloak>
<aside class="mobile-library-drawer"> <aside class="mobile-library-drawer">
@@ -212,7 +214,7 @@
</div> </div>
<div class="following-name" x-text="artist.name"></div> <div class="following-name" x-text="artist.name"></div>
</div> </div>
<button class="mobile-list-action" <button data-member-only class="mobile-list-action"
@click.stop="$store.follows.toggle(artist.id)" @click.stop="$store.follows.toggle(artist.id)"
title="{{ t.player_unfollow_artist }}"> title="{{ t.player_unfollow_artist }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
@@ -244,17 +246,17 @@
</div> </div>
<template x-if="pl.is_own && pl.kind === 'user'"> <template x-if="pl.is_own && pl.kind === 'user'">
<div class="playlist-item-actions"> <div class="playlist-item-actions">
<button class="playlist-action-btn" @click.stop="$store.mobile.closeLibrary(); $store.playlists.startRename(pl)" title="{{ t.player_rename }}"> <button data-member-only class="playlist-action-btn" @click.stop="$store.mobile.closeLibrary(); $store.playlists.startRename(pl)" title="{{ t.player_rename }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
</button> </button>
<button class="playlist-action-btn" @click.stop="$store.playlists.deletePlaylist(pl.id)" title="{{ t.player_delete }}"> <button data-member-only class="playlist-action-btn" @click.stop="$store.playlists.deletePlaylist(pl.id)" title="{{ t.player_delete }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
</button> </button>
</div> </div>
</template> </template>
</div> </div>
</template> </template>
<button class="sidebar-create-btn" @click="$store.mobile.closeLibrary(); $store.playlists.showCreate()"> <button data-member-only class="sidebar-create-btn" @click="$store.mobile.closeLibrary(); $store.playlists.showCreate()">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
{{ t.player_new_playlist }} {{ t.player_new_playlist }}
</button> </button>
@@ -288,7 +290,7 @@
<div class="center-content" id="center-scroll"> <div class="center-content" id="center-scroll">
<!-- Search / account bar --> <!-- Search / account bar -->
<div class="content-topbar" @click.outside="$store.user.menuOpen = false"> <div class="content-topbar" @click.outside="$store.user.menuOpen = false">
<button class="mobile-library-btn" <button data-member-only class="mobile-library-btn"
@click="$store.user.menuOpen = false; $store.mobile.toggleLibrary()" @click="$store.user.menuOpen = false; $store.mobile.toggleLibrary()"
title="{{ t.player_library }}"> title="{{ t.player_library }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
@@ -310,6 +312,13 @@
</svg> </svg>
<span class="connection-alert-text">{{ t.player_connection_lost }}</span> <span class="connection-alert-text">{{ t.player_connection_lost }}</span>
</div> </div>
{% if guest %}
<div class="guest-account">
<strong>{{ t.guest_label }}</strong>
<div x-show="$store.user.accessStatus === 'pending'" x-cloak><span>{{ t.approval_heading }}</span> · <a href="/logout">{{ t.player_log_out }}</a></div>
<a x-show="$store.user.accessStatus === 'anonymous'" href="/login?next=/share/{{ share_token }}">{{ t.guest_login }}</a>
</div>
{% endif %}
<div class="search-bar"> <div class="search-bar">
<span class="search-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg></span> <span class="search-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg></span>
<input id="search-input" type="text" placeholder="{{ t.player_search_placeholder }}" <input id="search-input" type="text" placeholder="{{ t.player_search_placeholder }}"
@@ -518,7 +527,7 @@
<span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span> <span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span>
<span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span> <span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span>
</button> </button>
<button class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}"> <button data-member-only class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}">
<svg viewBox="0 0 24 24" :fill="$store.likes.has(track.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg> <svg viewBox="0 0 24 24" :fill="$store.likes.has(track.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg>
</button> </button>
<button class="track-action-btn queue-insert-btn queue-next-btn" @click.stop="$store.queue.addNextInQueue([track])" title="{{ t.player_play_next }}"> <button class="track-action-btn queue-insert-btn queue-next-btn" @click.stop="$store.queue.addNextInQueue([track])" title="{{ t.player_play_next }}">
@@ -527,10 +536,10 @@
<button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}"> <button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg>
</button> </button>
<button class="track-action-btn track-share-btn" @click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}"> <button data-member-only class="track-action-btn track-share-btn" @click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg>
</button> </button>
<button class="track-action-btn playlist-add-btn" @click.stop="$store.playlists.showPicker([track.id])" title="{{ t.player_add_to_playlist }}"> <button data-member-only class="track-action-btn playlist-add-btn" @click.stop="$store.playlists.showPicker([track.id])" title="{{ t.player_add_to_playlist }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>
</button> </button>
</div> </div>
@@ -670,7 +679,7 @@
title="{{ t.player_add_to_queue }}"> title="{{ t.player_add_to_queue }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg>
</button> </button>
<button class="track-action-btn playlist-add-btn" <button data-member-only class="track-action-btn playlist-add-btn"
@click.stop="$store.playlists.showFederationPicker(track)" @click.stop="$store.playlists.showFederationPicker(track)"
title="{{ t.player_add_to_playlist }}"> title="{{ t.player_add_to_playlist }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
@@ -714,7 +723,7 @@
<template x-if="!artist.image_url"> <template x-if="!artist.image_url">
<span class="placeholder-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg></span> <span class="placeholder-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg></span>
</template> </template>
<button class="artist-follow-card-btn" <button data-member-only class="artist-follow-card-btn"
:class="{ followed: $store.follows.has(artist.id) }" :class="{ followed: $store.follows.has(artist.id) }"
@click.stop="$store.follows.toggle(artist.id)" @click.stop="$store.follows.toggle(artist.id)"
:title="$store.follows.has(artist.id) ? '{{ t.player_unfollow_artist }}' : '{{ t.player_follow_artist }}'"> :title="$store.follows.has(artist.id) ? '{{ t.player_unfollow_artist }}' : '{{ t.player_follow_artist }}'">
@@ -794,7 +803,7 @@
</svg> </svg>
<span>{{ t.player_listen }}</span> <span>{{ t.player_listen }}</span>
</button> </button>
<button class="release-action-btn secondary artist-follow-action" <button data-member-only class="release-action-btn secondary artist-follow-action"
x-show="$store.library.currentArtist.id" x-show="$store.library.currentArtist.id"
:class="{ followed: $store.follows.has($store.library.currentArtist.id) }" :class="{ followed: $store.follows.has($store.library.currentArtist.id) }"
@click="$store.follows.toggle($store.library.currentArtist.id)" @click="$store.follows.toggle($store.library.currentArtist.id)"
@@ -881,7 +890,7 @@
<span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span> <span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span>
<span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span> <span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span>
</button> </button>
<button class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}"> <button data-member-only class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}">
<svg viewBox="0 0 24 24" :fill="$store.likes.has(track.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg> <svg viewBox="0 0 24 24" :fill="$store.likes.has(track.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg>
</button> </button>
<button class="track-action-btn queue-insert-btn queue-next-btn" @click.stop="$store.queue.addNextInQueue([track])" title="{{ t.player_play_next }}"> <button class="track-action-btn queue-insert-btn queue-next-btn" @click.stop="$store.queue.addNextInQueue([track])" title="{{ t.player_play_next }}">
@@ -890,10 +899,10 @@
<button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}"> <button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg>
</button> </button>
<button class="track-action-btn track-share-btn" @click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}"> <button data-member-only class="track-action-btn track-share-btn" @click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg>
</button> </button>
<button class="track-action-btn playlist-add-btn" @click.stop="$store.playlists.showPicker([track.id])" title="{{ t.player_add_to_playlist }}"> <button data-member-only class="track-action-btn playlist-add-btn" @click.stop="$store.playlists.showPicker([track.id])" title="{{ t.player_add_to_playlist }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>
</button> </button>
</div> </div>
@@ -1037,7 +1046,7 @@
title="{{ t.player_add_to_queue }}"> title="{{ t.player_add_to_queue }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg>
</button> </button>
<button class="track-action-btn playlist-add-btn" <button data-member-only class="track-action-btn playlist-add-btn"
@click.stop="$store.playlists.showFederationPicker(track)" @click.stop="$store.playlists.showFederationPicker(track)"
title="{{ t.player_add_to_playlist }}"> title="{{ t.player_add_to_playlist }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
@@ -1110,7 +1119,7 @@
<span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span> <span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span>
<span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span> <span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span>
</button> </button>
<button class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}"> <button data-member-only class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}">
<svg viewBox="0 0 24 24" :fill="$store.likes.has(track.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg> <svg viewBox="0 0 24 24" :fill="$store.likes.has(track.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg>
</button> </button>
<button class="track-action-btn queue-insert-btn queue-next-btn" @click.stop="$store.queue.addNextInQueue([track])" title="{{ t.player_play_next }}"> <button class="track-action-btn queue-insert-btn queue-next-btn" @click.stop="$store.queue.addNextInQueue([track])" title="{{ t.player_play_next }}">
@@ -1119,10 +1128,10 @@
<button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}"> <button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg>
</button> </button>
<button class="track-action-btn track-share-btn" @click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}"> <button data-member-only class="track-action-btn track-share-btn" @click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg>
</button> </button>
<button class="track-action-btn playlist-add-btn" @click.stop="$store.playlists.showPicker([track.id])" title="{{ t.player_add_to_playlist }}"> <button data-member-only class="track-action-btn playlist-add-btn" @click.stop="$store.playlists.showPicker([track.id])" title="{{ t.player_add_to_playlist }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>
</button> </button>
</div> </div>
@@ -1193,7 +1202,7 @@
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
{{ t.player_info }} {{ t.player_info }}
</button> </button>
<button class="release-action-btn secondary release-share-btn" <button data-member-only class="release-action-btn secondary release-share-btn"
x-show="!$store.library.currentRelease.federated" x-show="!$store.library.currentRelease.federated"
@click.stop="$store.sharing.copyRelease($store.library.currentRelease, $event.currentTarget)" @click.stop="$store.sharing.copyRelease($store.library.currentRelease, $event.currentTarget)"
title="{{ t.player_share }}" title="{{ t.player_share }}"
@@ -1290,7 +1299,7 @@
<span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span> <span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span>
<span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span> <span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span>
</button> </button>
<button class="like-btn" <button data-member-only class="like-btn"
:class="{ liked: track.federation_pending ? $store.library.federationIsLiked(track._federationTrack) : $store.likes.has(track.id) }" :class="{ liked: track.federation_pending ? $store.library.federationIsLiked(track._federationTrack) : $store.likes.has(track.id) }"
@click.stop="track.federation_pending ? $store.library.toggleFederationLike(track._federationTrack) : $store.likes.toggle(track.id)" @click.stop="track.federation_pending ? $store.library.toggleFederationLike(track._federationTrack) : $store.likes.toggle(track.id)"
title="{{ t.player_like }}"> title="{{ t.player_like }}">
@@ -1304,12 +1313,12 @@
<button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}"> <button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg>
</button> </button>
<button class="track-action-btn track-share-btn" <button data-member-only class="track-action-btn track-share-btn"
x-show="!track.federation_pending" x-show="!track.federation_pending"
@click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}"> @click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg>
</button> </button>
<button class="track-action-btn playlist-add-btn" <button data-member-only class="track-action-btn playlist-add-btn"
@click.stop="track.federation_pending ? $store.playlists.showFederationPicker(track._federationTrack) : $store.playlists.showPicker([track.id])" @click.stop="track.federation_pending ? $store.playlists.showFederationPicker(track._federationTrack) : $store.playlists.showPicker([track.id])"
title="{{ t.player_add_to_playlist }}"> title="{{ t.player_add_to_playlist }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>
@@ -1331,7 +1340,7 @@
</div> </div>
<div class="playlist-detail-heading"> <div class="playlist-detail-heading">
<h1 class="section-title" x-text="$store.playlists.displayTitle($store.library.currentPlaylist)"></h1> <h1 class="section-title" x-text="$store.playlists.displayTitle($store.library.currentPlaylist)"></h1>
<button class="release-action-btn secondary playlist-edit-toggle" <button data-member-only class="release-action-btn secondary playlist-edit-toggle"
x-show="$store.playlists.canEditCurrent()" x-show="$store.playlists.canEditCurrent()"
x-cloak x-cloak
@click="$store.playlists.toggleEditCurrent()" @click="$store.playlists.toggleEditCurrent()"
@@ -1379,7 +1388,7 @@
@dragover.prevent="$store.playlists.dragOver($event, idx)" @dragover.prevent="$store.playlists.dragOver($event, idx)"
@dragleave="$event.currentTarget.classList.remove('drag-over')" @dragleave="$event.currentTarget.classList.remove('drag-over')"
@drop.prevent="$event.currentTarget.classList.remove('drag-over'); $store.playlists.dropOn(idx)"> @drop.prevent="$event.currentTarget.classList.remove('drag-over'); $store.playlists.dropOn(idx)">
<button class="playlist-track-remove" <button data-member-only class="playlist-track-remove"
x-show="$store.playlists.isEditingCurrent()" x-show="$store.playlists.isEditingCurrent()"
x-cloak x-cloak
@click.stop="$store.playlists.removeCurrentTrack(track, idx)" @click.stop="$store.playlists.removeCurrentTrack(track, idx)"
@@ -1422,7 +1431,7 @@
</template> </template>
</span> </span>
<div class="track-info playlist-track-info"> <div class="track-info playlist-track-info">
<button class="playlist-drag-handle" <button data-member-only class="playlist-drag-handle"
x-show="$store.playlists.isEditingCurrent() && !!track.playlist_track_id" x-show="$store.playlists.isEditingCurrent() && !!track.playlist_track_id"
x-cloak x-cloak
@mousedown.stop @mousedown.stop
@@ -1457,7 +1466,7 @@
<span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span> <span x-show="$store.library.hasPopularity(track)" x-text="$store.library.popularityLabel(track)"></span>
<span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span> <span x-show="!$store.library.hasPopularity(track)" class="info-letter">i</span>
</button> </button>
<button class="like-btn" <button data-member-only class="like-btn"
:class="{ liked: track.federation_pending ? $store.library.federationIsLiked(track._federationTrack) : $store.likes.has(track.id) }" :class="{ liked: track.federation_pending ? $store.library.federationIsLiked(track._federationTrack) : $store.likes.has(track.id) }"
@click.stop="track.federation_pending ? $store.library.toggleFederationLike(track._federationTrack) : $store.likes.toggle(track.id)" @click.stop="track.federation_pending ? $store.library.toggleFederationLike(track._federationTrack) : $store.likes.toggle(track.id)"
title="{{ t.player_like }}"> title="{{ t.player_like }}">
@@ -1471,10 +1480,10 @@
<button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}"> <button class="track-action-btn queue-insert-btn queue-end-btn" @click.stop="$store.queue.addToEnd([track])" title="{{ t.player_add_to_queue }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 6h14M5 12h14M5 18h7"/><path d="M17 15l4 3-4 3" fill="currentColor" stroke="none"/></svg>
</button> </button>
<button class="track-action-btn track-share-btn" @click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}"> <button data-member-only class="track-action-btn track-share-btn" @click.stop="$store.sharing.copyTrack(track, $event.currentTarget)" title="{{ t.player_share_track }}" aria-label="{{ t.player_share_track }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg>
</button> </button>
<button class="track-action-btn playlist-add-btn" <button data-member-only class="track-action-btn playlist-add-btn"
@click.stop="track.federation_pending ? $store.playlists.showFederationPicker(track._federationTrack) : $store.playlists.showPicker([track.id])" @click.stop="track.federation_pending ? $store.playlists.showFederationPicker(track._federationTrack) : $store.playlists.showPicker([track.id])"
title="{{ t.player_add_to_playlist }}"> title="{{ t.player_add_to_playlist }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>
@@ -1496,7 +1505,7 @@
<div class="queue-header"> <div class="queue-header">
<h3>{{ t.player_queue }}</h3> <h3>{{ t.player_queue }}</h3>
<div class="queue-header-actions"> <div class="queue-header-actions">
<button class="queue-share-btn" @click="$store.sharing.copyQueue($event.currentTarget)" :disabled="$store.queue.tracks.length === 0" title="{{ t.player_share_queue }}" aria-label="{{ t.player_share_queue }}"> <button data-member-only class="queue-share-btn" @click="$store.sharing.copyQueue($event.currentTarget)" :disabled="$store.queue.tracks.length === 0" title="{{ t.player_share_queue }}" aria-label="{{ t.player_share_queue }}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg>
</button> </button>
<button class="queue-clear-btn" @click="$store.queue.clear()">{{ t.player_clear }}</button> <button class="queue-clear-btn" @click="$store.queue.clear()">{{ t.player_clear }}</button>
@@ -1620,14 +1629,14 @@
<div class="player-track-info"> <div class="player-track-info">
<div class="player-track-title-row"> <div class="player-track-title-row">
<div class="player-track-title" x-text="$store.player.currentTrack.title"></div> <div class="player-track-title" x-text="$store.player.currentTrack.title"></div>
<button class="like-btn player-current-like" <button data-member-only class="like-btn player-current-like"
:class="{ liked: $store.likes.has($store.player.currentTrack.id) }" :class="{ liked: $store.likes.has($store.player.currentTrack.id) }"
@click.stop="$store.likes.toggle($store.player.currentTrack.id)" @click.stop="$store.likes.toggle($store.player.currentTrack.id)"
title="{{ t.player_like }}" title="{{ t.player_like }}"
aria-label="{{ t.player_like }}"> aria-label="{{ t.player_like }}">
<svg viewBox="0 0 24 24" :fill="$store.likes.has($store.player.currentTrack.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg> <svg viewBox="0 0 24 24" :fill="$store.likes.has($store.player.currentTrack.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg>
</button> </button>
<button class="track-action-btn player-current-share" <button data-member-only class="track-action-btn player-current-share"
@click.stop="$store.sharing.copyTrack($store.player.currentTrack, $event.currentTarget)" @click.stop="$store.sharing.copyTrack($store.player.currentTrack, $event.currentTarget)"
title="{{ t.player_share_track }}" title="{{ t.player_share_track }}"
aria-label="{{ t.player_share_track }}"> aria-label="{{ t.player_share_track }}">
@@ -1727,7 +1736,7 @@
</button> </button>
<div class="device-picker" @click.outside="$store.devices.open = false"> <div class="device-picker" @click.outside="$store.devices.open = false">
<template x-if="$store.devices.remoteHintVisible"> <template x-if="$store.devices.remoteHintVisible">
<button class="remote-playback-hint" <button data-member-only class="remote-playback-hint"
type="button" type="button"
@click="$store.devices.dismissRemoteHint()" @click="$store.devices.dismissRemoteHint()"
x-transition x-transition
@@ -1736,7 +1745,7 @@
<span class="remote-playback-hint-progress"></span> <span class="remote-playback-hint-progress"></span>
</button> </button>
</template> </template>
<button class="queue-toggle-btn device-toggle-btn" <button data-member-only class="queue-toggle-btn device-toggle-btn"
:class="{ active: $store.devices.isActive() }" :class="{ active: $store.devices.isActive() }"
@click="$store.devices.toggle()" @click="$store.devices.toggle()"
:title="$store.devices.activeLabel()" :title="$store.devices.activeLabel()"
@@ -1757,7 +1766,7 @@
<div class="device-popover" x-show="$store.devices.open" x-transition x-cloak> <div class="device-popover" x-show="$store.devices.open" x-transition x-cloak>
<div class="device-section-label">Web players</div> <div class="device-section-label">Web players</div>
<template x-for="device in $store.devices.webDevices()" :key="device.id"> <template x-for="device in $store.devices.webDevices()" :key="device.id">
<button class="device-row" <button data-member-only class="device-row"
:class="{ active: device.is_active, 'current-device': device.is_current }" :class="{ active: device.is_active, 'current-device': device.is_current }"
@click="$store.devices.select(device.id)"> @click="$store.devices.select(device.id)">
<span class="device-row-icon"> <span class="device-row-icon">
@@ -1792,7 +1801,7 @@
</div> </div>
</template> </template>
<template x-for="device in $store.devices.playbackFedDevices()" :key="device.id"> <template x-for="device in $store.devices.playbackFedDevices()" :key="device.id">
<button class="device-row federation-device-row" <button data-member-only class="device-row federation-device-row"
:class="{ active: device.is_active }" :class="{ active: device.is_active }"
@click="$store.devices.select(device.id)"> @click="$store.devices.select(device.id)">
<span class="device-row-icon federation-device-icon"> <span class="device-row-icon federation-device-icon">
@@ -1818,7 +1827,7 @@
<div class="device-section-label jam-section-label">Jams</div> <div class="device-section-label jam-section-label">Jams</div>
</template> </template>
<template x-for="jam in $store.devices.jams" :key="jam.id"> <template x-for="jam in $store.devices.jams" :key="jam.id">
<button class="device-row jam-row" <button data-member-only class="device-row jam-row"
:class="{ active: jam.is_active, pending: jam.is_pending }" :class="{ active: jam.is_active, pending: jam.is_pending }"
@click="$store.devices.handleJamRowClick(jam)"> @click="$store.devices.handleJamRowClick(jam)">
<span class="device-row-icon"> <span class="device-row-icon">
@@ -1841,7 +1850,7 @@
</span> </span>
</button> </button>
</template> </template>
<button class="device-row start-jam-row" x-show="!$store.devices.hasJoinedJam()" @click="$store.devices.openJamPanel()"> <button data-member-only class="device-row start-jam-row" x-show="!$store.devices.hasJoinedJam()" @click="$store.devices.openJamPanel()">
<span class="device-row-icon"> <span class="device-row-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 5v14"/> <path d="M12 5v14"/>
@@ -1865,7 +1874,7 @@
</label> </label>
<div class="jam-selected-users" x-show="$store.devices.jamSelectedUsers.length > 0"> <div class="jam-selected-users" x-show="$store.devices.jamSelectedUsers.length > 0">
<template x-for="user in $store.devices.jamSelectedUsers" :key="user.id"> <template x-for="user in $store.devices.jamSelectedUsers" :key="user.id">
<button class="jam-user-chip" @click="$store.devices.removeJamInvitee(user.id)"> <button data-member-only class="jam-user-chip" @click="$store.devices.removeJamInvitee(user.id)">
<span x-text="user.display_name || user.username"></span> <span x-text="user.display_name || user.username"></span>
<span aria-hidden="true">×</span> <span aria-hidden="true">×</span>
</button> </button>
@@ -1878,18 +1887,18 @@
@input="$store.devices.queueJamSearch()"> @input="$store.devices.queueJamSearch()">
<div class="jam-search-results" x-show="$store.devices.jamUsers.length > 0"> <div class="jam-search-results" x-show="$store.devices.jamUsers.length > 0">
<template x-for="user in $store.devices.jamUsers" :key="user.id"> <template x-for="user in $store.devices.jamUsers" :key="user.id">
<button class="jam-search-row" @click="$store.devices.addJamInvitee(user)"> <button data-member-only class="jam-search-row" @click="$store.devices.addJamInvitee(user)">
<span x-text="user.display_name || user.username"></span> <span x-text="user.display_name || user.username"></span>
<small x-text="user.email || user.username"></small> <small x-text="user.email || user.username"></small>
</button> </button>
</template> </template>
</div> </div>
<div class="jam-panel-actions"> <div class="jam-panel-actions">
<button class="jam-create-btn" <button data-member-only class="jam-create-btn"
:disabled="$store.devices.jamSelectedUsers.length === 0 && $store.devices.jamPanelMode === 'manage'" :disabled="$store.devices.jamSelectedUsers.length === 0 && $store.devices.jamPanelMode === 'manage'"
@click="$store.devices.submitJamPanel()" @click="$store.devices.submitJamPanel()"
x-text="$store.devices.jamPanelMode === 'manage' ? 'Invite' : 'Create Jam'"></button> x-text="$store.devices.jamPanelMode === 'manage' ? 'Invite' : 'Create Jam'"></button>
<button class="jam-leave-btn" <button data-member-only class="jam-leave-btn"
x-show="$store.devices.jamPanelMode === 'manage'" x-show="$store.devices.jamPanelMode === 'manage'"
@click="$store.devices.leaveJam($store.devices.jamPanelJamId)">Leave</button> @click="$store.devices.leaveJam($store.devices.jamPanelJamId)">Leave</button>
</div> </div>
+17
View File
@@ -7002,3 +7002,20 @@ button.user-stat:hover {
.queue-tracks::-webkit-scrollbar-thumb, .queue-tracks::-webkit-scrollbar-thumb,
.playlist-list::-webkit-scrollbar-thumb { background: var(--bg-active); border-radius: 3px; } .playlist-list::-webkit-scrollbar-thumb { background: var(--bg-active); border-radius: 3px; }
</style> </style>
<style>
.guest-player [data-member-only], .guest-player .search-bar, .guest-player .breadcrumb,
.guest-player .device-picker, .guest-player .mobile-library-backdrop,
.guest-player .mobile-library-btn, .guest-player .mobile-library-toggle { display:none !important; }
.guest-player .artist-link, .guest-player .track-artist a, .guest-player .player-artist a { pointer-events:none; cursor:default; }
.guest-account { display:flex; align-items:center; justify-content:space-between; gap:16px; width:100%; font-size:14px; }
.guest-account a { color:var(--accent); text-decoration:none; }
.guest-account div { color:var(--text-secondary); }
@media(max-width:600px) { .guest-account { flex-wrap:wrap; gap:8px; font-size:12px; } }
@media(max-width:1100px) {
.guest-player .playlist-track-row > span:nth-child(4) { display:none; }
.guest-player .playlist-track-row .track-num { grid-column:1; grid-row:1; }
.guest-player .playlist-track-row .playlist-track-info { grid-column:2; grid-row:1; }
.guest-player .playlist-track-row .track-actions { grid-column:3; grid-row:1; }
}
</style>
+131
View File
@@ -0,0 +1,131 @@
const assert = require('node:assert/strict');
const { readFileSync } = require('node:fs');
const { test } = require('node:test');
const vm = require('node:vm');
const template = readFileSync(`${__dirname}/../templates/admin/v2.html`, 'utf8');
const ui = readFileSync(`${__dirname}/../templates/admin/ui.html`, 'utf8').match(/<script>([\s\S]*?)<\/script>/)[1];
const script = ui + '\n' + template.match(/<script>\s*(function adminV2\(\)[\s\S]*?)<\/script>/)[1];
function createApp() {
const context = vm.createContext({URLSearchParams});
vm.runInContext(script, context);
const app = context.adminV2();
app.showToast = message => { app.toastMessage = message; };
app.$nextTick = fn => fn();
app.$refs = {};
app.repairSelected = [{kind:'artists',id:1,title:'Artist'}];
app.repairExpanded = {snapshot:{artists:[{id:1,name:'Artist'}],releases:[{id:2,title:'#ИЗИРОК',year:2018}],tracks:[{id:3,title:'Actual song',release_id:2}]}};
return app;
}
const emptyPlan = () => ({artists:[],releases:[],tracks:[],questions:[],delete:{artists:[],releases:[],tracks:[]}});
test('deselect all retains related rows and allows selecting only the needed resources', async () => {
const app = createApp();
app.setAllRepairIncluded(false);
assert.equal(app.repairIncludedCount(),0);
assert.equal(app.repairRowsCount(),3);
app.setRepairIncluded('releases',2,true);
app.setRepairIncluded('tracks',3,true);
assert.equal(app.repairIncludedCount(),2);
app.repairDraft = 'Only these';
app.request = async (url,options) => {
assert.ok(url.endsWith('/plan'), 'must not re-expand exclusions');
const body = JSON.parse(options.body);
assert.deepEqual(body.selection,{artists:[],releases:[2],tracks:[3]});
return {plan:emptyPlan(),snapshot:app.repairExpanded.snapshot,message:'Done'};
};
await app.sendRepair();
assert.equal(app.repairChat.length,2);
app.setAllRepairIncluded(true);
assert.equal(app.repairIncludedCount(),3);
});
test('checking only releases includes their contents without selecting the artist', () => {
const app = createApp();
app.setAllRepairIncluded(false);
app.setRepairIncluded('releases',2,true);
assert.deepEqual(JSON.parse(JSON.stringify(app.repairSelection(true))),{artists:[],releases:[2],tracks:[3]});
assert.equal(app.repairIsIncluded('tracks',3),true);
assert.equal(app.repairIsIncluded('artists',1),false);
app.setRepairIncluded('tracks',3,false);
assert.equal(app.repairIsIncluded('tracks',3),false);
assert.deepEqual(JSON.parse(JSON.stringify(app.repairSelection(true))).tracks,[]);
assert.deepEqual(JSON.parse(JSON.stringify(app.repairExcludedTracks)),[3]);
app.setAllRepairIncluded(false);
app.setRepairIncluded('releases',2,true);
assert.equal(app.repairIsIncluded('tracks',3),true);
});
test('explicit track exclusions are sent to planning without re-expanding them', async () => {
const app=createApp();
app.setAllRepairIncluded(false);
app.setRepairIncluded('releases',2,true);
app.setRepairIncluded('tracks',3,false);
app.repairDraft='Edit release only';
app.request=async(url,options)=>{
assert.ok(url.endsWith('/plan'));
const body=JSON.parse(options.body);
assert.deepEqual(body.selection,{artists:[],releases:[2],tracks:[]});
assert.deepEqual(body.excluded_track_ids,[3]);
return {plan:emptyPlan(),snapshot:app.repairExpanded.snapshot,message:'Done'};
};
await app.sendRepair();
});
test('clarification replaces the single plan including removed changes and questions', async () => {
const app = createApp();
app.repairPlan = {...emptyPlan(),delete:{artists:[],releases:[],tracks:[3]},questions:['Which release?']};
app.repairChat = [{role:'user',content:'Delete song'},{role:'assistant',content:'Please review'}];
app.repairPlanOpen = true;
app.repairDraft = 'Keep song, cancel everything';
app.request = async (_url,options) => {
const body=JSON.parse(options.body);
assert.deepEqual(body.current_plan.delete.tracks,[3]);
assert.equal(body.conversation.length,2);
return {plan:emptyPlan(),snapshot:app.repairExpanded.snapshot,message:'Cancelled'};
};
await app.sendRepair();
assert.equal(app.repairChangeCount(),0);
assert.equal(app.repairPlan.questions.length,0);
assert.equal(app.repairPlanOpen,true);
assert.equal(app.repairChat.length,4);
});
test('failed revision preserves prior plan and retry avoids duplicate user messages', async () => {
const app = createApp();
const prior = {...emptyPlan(),delete:{artists:[],releases:[],tracks:[3]}};
app.repairPlan = prior;
app.repairDraft = 'Keep song';
app.request = async () => {throw Error('Offline');};
await app.sendRepair();
assert.equal(app.repairPlan,prior);
assert.equal(app.repairIncomplete,true);
assert.equal(app.repairChat.length,1);
app.request = async (_url,options) => {
assert.equal(JSON.parse(options.body).conversation.length,0);
return {plan:emptyPlan(),snapshot:app.repairExpanded.snapshot,message:'Kept'};
};
await app.sendRepair();
assert.equal(app.repairChat.length,2);
assert.equal(app.repairIncomplete,false);
});
test('incomplete plan cannot apply, deletion-only plan can apply and clears stale selection', async () => {
const app = createApp();
app.repairPlan = {...emptyPlan(),delete:{artists:[],releases:[],tracks:[3]}};
app.repairSnapshot = app.repairExpanded.snapshot;
app.repairIncomplete = true;
app.request = async () => assert.fail('must not apply incomplete plan');
await app.applyRepair();
app.repairIncomplete = false;
app.request = async (url,options) => {
assert.ok(url.endsWith('/apply'));
assert.deepEqual(JSON.parse(options.body).plan.delete.tracks,[3]);
return {history_id:7};
};
app.loadRepairHistory = async () => {};
app.loadLibrary = async () => {};
await app.applyRepair();
assert.equal(app.repairIncludedCount(),0);
assert.equal(app.repairPlan,null);
assert.equal(app.repairChat.at(-1).content.includes('#7'),true);
});
+2 -1
View File
@@ -3,7 +3,8 @@ const {readFileSync} = require('node:fs');
const {test} = require('node:test'); const {test} = require('node:test');
const vm = require('node:vm'); const vm = require('node:vm');
const template = readFileSync(`${__dirname}/../templates/admin/v2.html`, 'utf8'); const template = readFileSync(`${__dirname}/../templates/admin/v2.html`, 'utf8');
const script = template.match(/<script>\s*(function adminV2\(\)[\s\S]*?)<\/script>/)[1]; const ui = readFileSync(`${__dirname}/../templates/admin/ui.html`, 'utf8').match(/<script>([\s\S]*?)<\/script>/)[1];
const script = ui + '\n' + template.match(/<script>\s*(function adminV2\(\)[\s\S]*?)<\/script>/)[1];
function app() { function app() {
const context = vm.createContext({URLSearchParams, Date}); vm.runInContext(script, context); const context = vm.createContext({URLSearchParams, Date}); vm.runInContext(script, context);
const a = context.adminV2(); a.icons = () => {}; a.setRoute = () => {}; return a; const a = context.adminV2(); a.icons = () => {}; a.setRoute = () => {}; return a;
+2 -1
View File
@@ -4,7 +4,8 @@ const { test } = require('node:test');
const vm = require('node:vm'); const vm = require('node:vm');
const template = readFileSync(`${__dirname}/../templates/admin/v2.html`, 'utf8'); const template = readFileSync(`${__dirname}/../templates/admin/v2.html`, 'utf8');
const script = template.match(/<script>\s*(function adminV2\(\)[\s\S]*?)<\/script>/)[1]; const ui = readFileSync(`${__dirname}/../templates/admin/ui.html`, 'utf8').match(/<script>([\s\S]*?)<\/script>/)[1];
const script = ui + '\n' + template.match(/<script>\s*(function adminV2\(\)[\s\S]*?)<\/script>/)[1];
function createApp() { function createApp() {
const context = vm.createContext({}); const context = vm.createContext({});
+141
View File
@@ -0,0 +1,141 @@
// Run against a disposable, freshly migrated instance only.
// Requires Docker PostgreSQL (FURU_ACCESS_TEST_PG), Playwright and Chrome.
const assert = require('node:assert/strict');
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const {spawnSync} = require('node:child_process');
const {mkdirSync, writeFileSync} = require('node:fs');
const {createServer} = require('node:http');
const {generateKeyPairSync, sign, randomUUID, createHash} = require('node:crypto');
const base = process.env.FURU_TEST_URL || 'http://127.0.0.1:18048';
const issuer = 'http://127.0.0.1:18049';
const mediaRoot = process.env.FURU_ACCESS_TEST_MEDIA || '/tmp/furumi-access-media';
function sql(statement) {
const result = spawnSync('docker', ['exec', '-i', process.env.FURU_ACCESS_TEST_PG || 'furumi-access-test-pg', 'psql', '-U', 'postgres', '-d', 'furumi_access_test', '-At', '-v', 'ON_ERROR_STOP=1'], {input:statement, encoding:'utf8'});
assert.equal(result.status, 0, result.stderr); return result.stdout.trim();
}
const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url');
const {privateKey, publicKey} = generateKeyPairSync('rsa', {modulusLength:2048});
const jwk = {...publicKey.export({format:'jwk'}), kid:'test', use:'sig', alg:'RS256'};
let claims = {sub:'pending-test', email:'pending@example.test', name:'Pending Listener', groups:[]};
const codes = new Map();
const oidc = createServer(async (request, response) => {
const url = new URL(request.url, issuer);
let data;
if (url.pathname === '/.well-known/openid-configuration') {
data = {issuer, authorization_endpoint:issuer+'/authorize', token_endpoint:issuer+'/token', jwks_uri:issuer+'/jwks', response_types_supported:['code'], subject_types_supported:['public'], id_token_signing_alg_values_supported:['RS256'], token_endpoint_auth_methods_supported:['client_secret_basic'], scopes_supported:['openid','email','profile'], claims_supported:['sub','email','email_verified','name','groups']};
} else if (url.pathname === '/jwks') data = {keys:[jwk]};
else if (url.pathname === '/authorize') {
const code = randomUUID(); codes.set(code, {...claims, nonce:url.searchParams.get('nonce'), challenge:url.searchParams.get('code_challenge')});
const target = new URL(url.searchParams.get('redirect_uri'));
target.searchParams.set('code', code); target.searchParams.set('state', url.searchParams.get('state'));
response.writeHead(302, {Location:target.toString()}); response.end(); return;
} else if (url.pathname === '/token') {
let body=''; for await (const chunk of request) body += chunk;
const form = new URLSearchParams(body); const saved = codes.get(form.get('code')); codes.delete(form.get('code'));
assert.ok(saved); assert.equal(createHash('sha256').update(form.get('code_verifier')).digest('base64url'), saved.challenge);
const {challenge, ...identity} = saved;
const payload = {iss:issuer, aud:'furumi-test', iat:Math.floor(Date.now()/1000), exp:Math.floor(Date.now()/1000)+300, email_verified:true, ...identity};
const token = encode({alg:'RS256',kid:'test'})+'.'+encode(payload);
data = {access_token:'test-access', token_type:'Bearer', expires_in:300, id_token:token+'.'+sign('RSA-SHA256',Buffer.from(token),privateKey).toString('base64url')};
} else { response.writeHead(404); response.end(); return; }
response.writeHead(200, {'Content-Type':'application/json'}); response.end(JSON.stringify(data));
});
(async () => {
await new Promise(resolve => oidc.listen(18049,'127.0.0.1',resolve));
const browser = await chromium.launch({headless:true, executablePath:process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
const errors=[];
try {
const admin = await browser.newContext({viewport:{width:1440,height:1000}});
let response = await admin.request.post(base+'/admin/setup', {form:{username:'access-admin',password:'access-test-password',confirm_password:'access-test-password'}});
assert.ok(response.ok());
response = await admin.request.post(base+'/login',{form:{username:'access-admin',password:'access-test-password'}}); assert.ok(response.ok());
sql(`INSERT INTO furumusic__config_entry (key,value) VALUES ('auth_sso_enabled','true'),('oidc_issuer','${issuer}'),('oidc_client_id','furumi-test'),('oidc_client_secret','test-${randomUUID()}'),('oidc_admin_groups','admins'),('oidc_user_groups','listeners') ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value;`);
sql("UPDATE furumusic__user SET local_role=NULL, sso_role=NULL, is_active=false WHERE username IN ('pending','automatic','root-new');");
mkdirSync(mediaRoot,{recursive:true});
const wav=Buffer.alloc(44+8000*2*10); wav.write('RIFF'); wav.writeUInt32LE(wav.length-8,4); wav.write('WAVEfmt ',8); wav.writeUInt32LE(16,16); wav.writeUInt16LE(1,20); wav.writeUInt16LE(1,22); wav.writeUInt32LE(8000,24); wav.writeUInt32LE(16000,28); wav.writeUInt16LE(2,32); wav.writeUInt16LE(16,34); wav.write('data',36); wav.writeUInt32LE(wav.length-44,40);
writeFileSync(mediaRoot+'/shared-test.wav',wav);
const cover=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aPioAAAAASUVORK5CYII=','base64'); writeFileSync(mediaRoot+'/cover.png',cover);
sql(`INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,uploader_name,created_at) VALUES (9001,'audio','shared-test.wav','Shared test.wav','audio/wav',${wav.length},'${createHash('sha256').update(wav).digest('hex')}','Test','2026-11-18T00:00:00Z'),(9002,'cover_art','cover.png','cover.png','image/png',${cover.length},'${createHash('sha256').update(cover).digest('hex')}','Test','2026-11-18T00:00:00Z') ON CONFLICT (id) DO NOTHING;
INSERT INTO furumusic__artist (id,name,name_sort,is_hidden,created_at,updated_at) VALUES (9001,'Test Artist','test artist',false,'2026-11-18T00:00:00Z','2026-11-18T00:00:00Z') ON CONFLICT (id) DO NOTHING;
INSERT INTO furumusic__release (id,title,title_sort,release_type,is_hidden,cover_file_id,created_at,updated_at) VALUES (9001,'Shared Album','shared album','album',false,9002,'2026-11-18T00:00:00Z','2026-11-18T00:00:00Z') ON CONFLICT (id) DO NOTHING;
INSERT INTO furumusic__track (id,title,title_sort,release_id,duration_seconds,audio_file_id,is_hidden,created_at,updated_at) VALUES (9001,'Shared Song','shared song',9001,10,9001,false,'2026-11-18T00:00:00Z','2026-11-18T00:00:00Z'),(9002,'Private Song','private song',9001,10,9001,false,'2026-11-18T00:00:00Z','2026-11-18T00:00:00Z') ON CONFLICT (id) DO NOTHING;
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) SELECT id,9001,'main',0 FROM furumusic__track WHERE id IN (9001,9002) AND NOT EXISTS (SELECT 1 FROM furumusic__track_artist WHERE track_id=furumusic__track.id);`);
response=await admin.request.post(base+'/api/player/shares',{data:{track_ids:[9001],title:'Shared Song'}}); assert.equal(response.status(),200); const share=await response.json();
const guest=await browser.newContext({viewport:{width:1440,height:1000}});
const page=await guest.newPage(); page.on('pageerror',e=>errors.push(e.message));
const api=[]; page.on('request',r=>{if(r.url().includes('/api/'))api.push(new URL(r.url()).pathname);});
await page.goto(base+share.url); await page.waitForSelector('.playlist-track-row');
assert.equal(await page.locator('.playlist-track-row').count(),1);
assert.equal(await page.getByRole('link',{name:'Sign in / register'}).count(),1);
assert.equal(await page.locator('#search-input').isVisible(),false);
assert.equal(await page.locator('.sidebar-left').count(),0);
await page.locator('.player-btn-play').click(); await page.waitForFunction(()=>Alpine.store('player').currentTime>0);
assert.equal(await page.locator('.device-picker').isVisible(),false);
await page.locator('.playlist-track-row [aria-label="Track info"]').click();
assert.equal(await page.getByRole('button',{name:'Start radio',exact:true}).count(),0);
assert.equal(await page.getByRole('button',{name:'Find similar',exact:true}).count(),0);
const downloading=page.waitForEvent('download'); await page.getByRole('button',{name:'Download',exact:true}).click(); const download=await downloading;
assert.equal(download.suggestedFilename(),'Shared test.wav'); await download.saveAs('/tmp/furumi-access-download.wav');
await page.locator('.modal-overlay [title="Close"]').click(); await page.screenshot({path:'/tmp/furumi-guest-desktop.png',fullPage:true});
assert.ok(api.every(path=>path.startsWith('/api/player/shares/')),JSON.stringify(api));
for (const action of ['stream','download','cover']) {
assert.equal((await guest.request.get(`${base}/api/player/shares/${share.token}/${action}/9002`)).status(),404);
assert.equal((await guest.request.get(`${base}/api/player/shares/${'0'.repeat(32)}/${action}/9001`)).status(),404);
}
assert.equal((await guest.request.get(`${base}/api/player/stream/9001`)).status(),401);
assert.equal((await guest.request.get(`${base}/api/player/artists`)).status(),401);
response=await guest.request.get(`${base}/api/player/shares/${share.token}/stream/9001`,{headers:{Range:'bytes=0-43'}}); assert.equal(response.status(),206); assert.equal((await response.body()).length,44);
assert.equal((await guest.request.get(`${base}/api/player/shares/${share.token}/stream/9001`,{headers:{Range:'bytes=999999999-'}})).status(),416);
assert.equal((await guest.request.get(`${base}/api/player/shares/${share.token}/cover/9001`)).status(),200);
assert.equal((await guest.request.post(`${base}/api/player/shares`,{data:{track_ids:[9001]}})).status(),401);
await page.getByRole('link',{name:'Sign in / register'}).click(); await page.locator('.sso-btn').click();
await page.waitForURL(base+share.url); await page.getByText('Awaiting approval',{exact:true}).waitFor(); await page.waitForSelector('.playlist-track-row');
assert.equal(await page.locator('.playlist-track-row').count(),1);
const pendingId=Number(sql("SELECT id FROM furumusic__user WHERE username='pending'")); assert.ok(pendingId);
await page.goto(base+'/'); await page.getByRole('heading',{name:'Awaiting approval'}).waitFor();
assert.equal(await page.locator('.app-layout').count(),0);
assert.equal((await guest.request.get(`${base}/api/player/artists`)).status(),401);
assert.equal((await guest.request.post(`${base}/admin/v2/api/users/manage`,{data:{action:'approve',id:pendingId,role:'admin'}})).status(),401);
const adminPage=await admin.newPage(); adminPage.on('pageerror',e=>errors.push(e.message));
await adminPage.goto(base+'/admin/#users');
const pendingRow=adminPage.locator('.users-table tr').filter({hasText:'Pending Listener'});
await pendingRow.getByRole('button',{name:'Approve as user',exact:true}).click();
await page.waitForSelector('.app-layout',{timeout:15000});
assert.equal((await guest.request.get(`${base}/api/player/artists`)).status(),200);
assert.equal(sql(`SELECT local_role || ':' || role FROM furumusic__user WHERE id=${pendingId}`),'user:user');
// Priority: a user SSO group overrides even a local admin grant; losing
// that group restores the separate local grant.
response=await admin.request.post(base+'/admin/v2/api/users/manage',{data:{action:'approve',id:pendingId,role:'admin'}}); assert.equal(response.status(),200);
claims.groups=['listeners']; await page.goto(base+'/logout'); await page.locator('.sso-btn').click(); await page.waitForURL(base+'/');
assert.equal(sql(`SELECT local_role || ':' || role FROM furumusic__user WHERE id=${pendingId}`),'admin:user');
claims.groups=[]; await page.goto(base+'/logout'); await page.locator('.sso-btn').click(); await page.waitForURL(base+'/');
assert.equal(sql(`SELECT local_role || ':' || role FROM furumusic__user WHERE id=${pendingId}`),'admin:admin');
claims={sub:'automatic-test',email:'automatic@example.test',name:'Automatic Listener',groups:['admins']};
await page.goto(base+'/logout'); await page.locator('.sso-btn').click(); await page.waitForURL(base+'/');
assert.equal(sql("SELECT COALESCE(local_role,'none') || ':' || role FROM furumusic__user WHERE username='automatic'"),'none:admin');
const automaticId=Number(sql("SELECT id FROM furumusic__user WHERE username='automatic'"));
response=await admin.request.post(base+'/admin/v2/api/users/manage',{data:{action:'update',id:automaticId,username:'automatic',display_name:'Renamed Automatic Listener',email:'automatic@example.test',role:''}});
assert.equal(response.status(),200);
assert.equal(sql("SELECT COALESCE(local_role,'none') || ':' || role FROM furumusic__user WHERE username='automatic'"),'none:admin');
claims.groups=[]; await page.goto(base+'/logout'); await page.locator('.sso-btn').click(); await page.getByRole('heading',{name:'Awaiting approval'}).waitFor();
assert.equal(sql("SELECT is_active FROM furumusic__user WHERE username='automatic'"),'f');
// A completely new identity arriving at the root never sees a demo player.
claims={sub:'new-root-test',email:'root-new@example.test',name:'New Root Listener',groups:[]};
await page.goto(base+'/logout'); await page.locator('.sso-btn').click(); await page.getByRole('heading',{name:'Awaiting approval'}).waitFor();
assert.equal(await page.locator('.app-layout').count(),0);
// Queue snapshots preserve order and repeated tracks.
response=await admin.request.post(base+'/api/player/shares',{data:{track_ids:[9002,9001,9002],title:'Shared queue'}}); const queue=await response.json();
response=await guest.request.get(base+'/api/player/shares/'+queue.token); assert.deepEqual((await response.json()).tracks.map(t=>t.id),[9002,9001,9002]);
const mobile=await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true}); const mobilePage=await mobile.newPage(); mobilePage.on('pageerror',e=>errors.push(e.message));
await mobilePage.goto(base+queue.url); await mobilePage.waitForSelector('.playlist-track-row');
assert.equal(await mobilePage.getByRole('link',{name:'Sign in / register'}).isVisible(),true);
const info=mobilePage.locator('.playlist-track-row [aria-label="Track info"]').first();
const bounds=await info.boundingBox(); assert.ok(bounds && bounds.x>=0 && bounds.x+bounds.width<=390,JSON.stringify(bounds));
await info.click(); await mobilePage.getByRole('button',{name:'Download',exact:true}).waitFor();
await mobilePage.locator('.modal-overlay [title="Close"]').click();
await mobilePage.screenshot({path:'/tmp/furumi-guest-mobile.png',fullPage:true});
for (const old of ['/share/track/9001','/share/release/9001','/share/playlist/abc','/api/player/radio/track/9001','/api/player/share-playlist']) assert.equal((await guest.request.get(base+old)).status(),404);
assert.deepEqual(errors,[]);
console.log('PASS: OIDC approval, live activation, SSO precedence and removal, anonymous playback/download/cover, scope enforcement, queue snapshots, desktop and mobile, removal of legacy routes.');
} finally { await browser.close(); await new Promise(resolve=>oidc.close(resolve)); }
})().catch(error=>{console.error(error);process.exitCode=1;});
+164
View File
@@ -0,0 +1,164 @@
// Run against a disposable local instance with at least one admin and one release.
// Existing data is read only; long-content fixtures are injected into browser state.
// FURU_TEST_URL, FURU_TEST_USERNAME, FURU_TEST_PASSWORD, PLAYWRIGHT_MODULE,
// CHROME_PATH and FURU_TEST_SCREENSHOTS configure the runner.
const assert = require('node:assert/strict');
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const {mkdirSync} = require('node:fs');
const base = process.env.FURU_TEST_URL || 'http://127.0.0.1:18048';
(async () => {
const browser = await chromium.launch({headless:true, executablePath:process.env.CHROME_PATH});
try {
const context = await browser.newContext({viewport:{width:390,height:844}, reducedMotion:'reduce'});
const response = await context.request.post(base+'/login', {form:{username:process.env.FURU_TEST_USERNAME || 'access-admin', password:process.env.FURU_TEST_PASSWORD || 'access-test-password'}});
assert.ok(response.ok());
const page = await context.newPage();
const errors = []; page.on('pageerror', error => errors.push(error.message));
await page.goto(base+'/admin/v2');
await page.waitForFunction(() => window.Alpine && document.querySelector('.admin-shell')._x_dataStack);
const state = (fn, arg) => page.evaluate(({code,arg}) => Function('app','arg',`return (${code})(app,arg)`)(Alpine.$data(document.querySelector('.admin-shell')), arg), {code:fn.toString(),arg});
await state(async app => { clearInterval(app.poller); await app.refreshAll(); });
const screenshot = async name => {
if (!process.env.FURU_TEST_SCREENSHOTS) return;
mkdirSync(process.env.FURU_TEST_SCREENSHOTS, {recursive:true});
await page.screenshot({path:process.env.FURU_TEST_SCREENSHOTS+'/'+name+'.png'});
};
async function fits(label) {
const overflow = await page.evaluate(() => [...document.querySelectorAll('html, body, main, .content, .panel, .modal, .modal-body')]
.filter(el => el.getClientRects().length && el.scrollWidth > el.clientWidth + 2)
.map(el => `${el.tagName}.${el.className}: ${el.scrollWidth} > ${el.clientWidth}`));
assert.deepEqual(overflow, [], label);
}
async function settle() { await page.waitForTimeout(200); }
async function navigate(view) {
if (await page.locator('.menu-toggle').isVisible()) await page.locator('.menu-toggle').click();
await page.locator('.nav-btn').filter({hasText:{reviews:'Review Queue',jobs:'Tasks',library:'Library Workbench',tools:'Library Tools',statistics:'Statistics',users:'Users',settings:'Settings'}[view]}).click();
await page.waitForFunction(v => Alpine.$data(document.querySelector('.admin-shell')).activeView === v, view);
await settle();
assert.equal(await page.locator('main').evaluate(el => el.inert), false);
}
// Navigate through the actual menu, testing both permanent and drawer modes.
for (const width of [320,390,768,1024,1440]) {
await page.setViewportSize({width,height:844}); await settle();
for (const view of ['reviews','jobs','library','tools','statistics','users','settings']) {
await navigate(view); await fits(`${width}: ${view}`);
if (width === 390 || width === 1440) await screenshot(`${width}-${view}`);
}
}
await page.setViewportSize({width:390,height:844}); await settle();
await page.locator('.menu-toggle').click(); await settle();
assert.equal(await page.locator('main').evaluate(el => el.inert), true);
await screenshot('390-navigation');
await page.keyboard.press('Shift+Tab');
assert.equal(await page.evaluate(() => document.activeElement.classList.contains('nav-player')), true);
await page.keyboard.press('Tab');
assert.equal(await page.evaluate(() => document.activeElement.hasAttribute('data-dialog-close')), true);
await page.keyboard.press('Escape'); await settle();
assert.equal(await page.evaluate(() => document.activeElement.classList.contains('menu-toggle')), true);
await page.locator('.menu-toggle').click(); await page.setViewportSize({width:1440,height:844}); await settle();
assert.equal(await page.locator('main').evaluate(el => el.inert), false);
assert.equal(await page.locator('.sidebar').evaluate(el => el.inert), false);
await page.setViewportSize({width:390,height:844}); await settle();
await navigate('jobs');
await page.locator('#task-pane-list tbody tr').first().click(); await settle();
assert.equal(await page.locator('#task-pane-list').isVisible(), false);
assert.equal(await page.locator('#task-pane-details').isVisible(), true);
await page.getByRole('button', {name:'Edit schedule',exact:true}).click();
await page.getByRole('textbox', {name:'Cron schedule'}).fill('0 15 * * * *');
await page.locator('#task-tab-logs').click();
await page.keyboard.press('ArrowLeft');
assert.equal(await page.getByRole('textbox', {name:'Cron schedule'}).inputValue(), '0 15 * * * *');
await fits('task editor');
await navigate('settings');
await page.locator('.section-jump select').selectOption('federation'); await settle();
assert.equal(await page.evaluate(() => document.activeElement.id), 'settings-federation');
await page.getByRole('button',{name:'Save settings',exact:true}).scrollIntoViewIfNeeded();
await fits('settings footer');
// Shared dialog lifecycle: trap focus, lock background, retain close affordance,
// scroll long content and restore focus to its trigger.
async function checkDialog(name) {
const dialog = page.locator('.modal:visible'); await dialog.waitFor(); await settle();
assert.equal(await page.locator('main').evaluate(el => el.inert), true);
await fits(name);
assert.ok((await dialog.locator('.modal-body').innerText()).trim().length > 0, name+' body populated');
const box = await dialog.boundingBox();
if (page.viewportSize().width < 768) assert.ok(Math.abs(box.height-page.viewportSize().height)<2, name+' full height');
await dialog.focus(); await page.keyboard.press('Shift+Tab');
assert.equal(await dialog.evaluate(el => el.contains(document.activeElement)), true);
await page.keyboard.press('Tab');
assert.equal(await page.evaluate(() => document.activeElement.hasAttribute('data-dialog-close')), true);
await screenshot(name);
await dialog.locator('.modal-body').evaluate(el => { el.scrollTop=el.scrollHeight; });
await fits(name+' bottom');
const close = await dialog.locator('[data-dialog-close]').boundingBox();
assert.ok(close.y >= 0 && close.y+close.height <= page.viewportSize().height, name+' close reachable');
const footer = dialog.locator('.dialog-actions:visible');
if (await footer.count()) {
const bottom = await footer.boundingBox();
assert.ok(bottom.y >= -1 && bottom.y+bottom.height <= page.viewportSize().height+1, name+' actions reachable');
}
await page.keyboard.press('Escape'); await settle();
assert.equal(await page.locator('.modal:visible').count(),0);
assert.equal(await page.locator('main').evaluate(el => el.inert),false);
}
await navigate('users');
await page.getByRole('button',{name:'Add user',exact:true}).click();
await checkDialog('390-add-user');
assert.equal(await page.evaluate(() => document.activeElement.textContent.trim()), 'Add user');
await page.locator('.users-table tbody tr').first().click();
await checkDialog('390-user-profile');
const review = {id:987654,status:'pending',review_type:'metadata',filename:'Very long track title '.repeat(8),display_path:'/inbox/'+'album/'.repeat(20),tags:[],normalized:{title:'Long song title',artist:'Test artist',notes:'Notes\n'.repeat(40)}};
await navigate('reviews');
await state((app,row) => {app.reviews.items=[row]; app.reviews.total=1; app.openReview(row);}, review);
await checkDialog('390-review');
await fits('populated reviews');
await navigate('library');
await state(async app => {app.libraryKind='releases'; await app.loadLibrary(); app.openEditor(app.library.items[0]);});
await page.waitForFunction(() => !Alpine.$data(document.querySelector('.admin-shell')).editorLoading);
await state(app => {app.editorDraft.release_tracks = Array.from({length:12}, (_,i)=>({...app.editorDraft.release_tracks[0],id:700000+i,title:'Very long track title '.repeat(8),disc_number:1,track_number:i+1}));});
await page.locator('.modal:visible input[x-model="editorDraft.title"]').waitFor({state:'visible'});
assert.equal(await page.locator('.modal:visible .release-track-row:visible').count(),12);
await checkDialog('390-release-editor');
await state(app => {
const detail = app.editorDetail;
app.mergeDetails=[detail,{...detail,item:{...detail.item,id:700001},title:'Second release'}];
app.mergeDraft={release_ids:[detail.item.id,700001],target_release_id:detail.item.id,title:detail.title,release_type:'album',hidden:'false',year:'2026',artist_ids:[],cover_file_id:null,tracks:app.editorDraft.release_tracks};
app.mergeOpen=true;
});
await checkDialog('390-merge');
// Short landscape viewport and desktop dialog geometry use the same contract.
for (const viewport of [{width:320,height:568},{width:844,height:390},{width:1440,height:900}]) {
await page.setViewportSize(viewport); await settle();
await state((app,row)=>app.openReview(row),review);
await checkDialog(`${viewport.width}-review`);
}
await page.setViewportSize({width:320,height:700}); await settle();
await navigate('statistics');
await state(async app => {
await app.loadStatistics();
app.statisticsData.ranking.items=[{key:'fixture',label:'Very long artist name '.repeat(12),detail:'long_identifier_'.repeat(20),plays:42,listeners:10,listened_seconds:10000,last_play_ms:Date.now()}];
app.statisticsData.history.items=[{user_id:1,listen_id:'fixture',user_name:'Listener '.repeat(12),title:'Long song name '.repeat(12),content_id:'fixture',artist_names:['Artist '.repeat(20)],release_title:'Album '.repeat(20),started_at_ms:Date.now(),listened_ms:60000,track_duration_ms:90000,qualified:true,ended_reason:'ended',device_name:'LongDeviceName'.repeat(20),source:'instance'}];
});
await settle(); await fits('320 populated statistics');
await navigate('tools');
await state(app => {
app.repairExpanded={snapshot:{artists:[{id:1,name:'Artist'}],releases:[{id:2,title:'Album',year:2026,release_type:'album',artist_ids:[1]}],tracks:[]}};
app.repairPlan={artists:[],releases:[{id:2,title:'Album '.repeat(30),year:2026,release_type:'album',artist_ids:[1]}],tracks:[],questions:[],delete:{artists:[],releases:[],tracks:[]}};
app.repairPlanOpen=true;
});
await page.locator('.repair-manual summary').click(); await settle();
await fits('320 manual metadata comparison');
const comparison=page.locator('.repair-manual');
assert.ok(await comparison.evaluate(el=>el.scrollWidth>el.clientWidth), 'wide comparison scrolls within its own region');
await screenshot('320-manual-comparison');
await navigate('users');
await page.locator('.users-table tbody tr').first().click();
await page.getByRole('button',{name:'Edit user',exact:true}).click();
await checkDialog('320-edit-user');
await page.locator('.menu-toggle').click();
await page.goBack(); await settle();
assert.equal(await page.locator('main').evaluate(el=>el.inert),false, 'browser Back closes navigation');
assert.deepEqual(errors, []);
console.log('PASS: 7 sections × 5 widths; drawer, task tabs, settings jump and all 5 dialogs, keyboard and long content.');
} finally { await browser.close(); }
})().catch(error => {console.error(error); process.exitCode=1;});
+181
View File
@@ -0,0 +1,181 @@
// Run against a fresh disposable instance with tests/metadata_repair_fixture.sql.
// FURU_REPAIR_TEST_PG must name its disposable PostgreSQL container.
const {chromium}=require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const assert=require('node:assert/strict');
const {readFileSync}=require('node:fs');
const {spawnSync}=require('node:child_process');
const base=process.env.FURU_TEST_URL || 'http://127.0.0.1:3029';
const container=process.env.FURU_REPAIR_TEST_PG || 'furumi-repair-test-pg';
function sql(statement) {
const result=spawnSync('docker',['exec','-i',container,'psql','-U','postgres','-d','furumi_repair_test','-At','-v','ON_ERROR_STOP=1'],{input:statement,encoding:'utf8'});
assert.equal(result.status,0,result.stderr);
return result.stdout.trim();
}
const emptyPlan=()=>({artists:[],releases:[],tracks:[],questions:[],delete:{artists:[],releases:[],tracks:[]}});
(async()=>{
const browser=await chromium.launch({headless:true,executablePath:process.env.CHROME_PATH || '/run/current-system/sw/bin/chromium',args:['--no-sandbox']});
try {
const context=await browser.newContext({viewport:{width:1440,height:1000}});
if (process.env.FURU_TEST_ASSETS) {
for (const [url,file] of [['alpinejs@3/dist/cdn.min.js','alpine.js'],['lucide@latest/dist/umd/lucide.min.js','lucide.js']]) {
await context.route('https://cdn.jsdelivr.net/npm/'+url,route=>route.fulfill({path:process.env.FURU_TEST_ASSETS+'/'+file}));
}
}
const api=context.request;
assert.equal((await api.post(base+'/admin/v2/api/metadata-fix/apply',{data:{snapshot:{},plan:{},instruction:'test'}})).status()>=400,true);
const page=await context.newPage(); const errors=[]; page.on('pageerror',error=>errors.push(error.message));
await page.goto(base+'/admin/setup');
if (page.url().includes('/admin/setup')) {
await page.locator('[name=username]').fill('repair_admin');
await page.locator('[name=password]').fill('repair-test-password');
await page.locator('[name=confirm_password]').fill('repair-test-password');
await page.locator('button[type=submit]').click();
await page.waitForURL('**/admin/v2');
} else {
await page.goto(base+'/login');
await page.locator('[name=username]').fill('repair_admin');
await page.locator('[name=password]').fill('repair-test-password');
await page.locator('button[type=submit]').click();
await page.waitForURL(base+'/');
await page.goto(base+'/admin/v2');
}
if (!process.env.FURU_REPAIR_SKIP_SEED) sql(readFileSync(__dirname+'/metadata_repair_fixture.sql','utf8'));
const post=async(path,data,status=200)=>{
const response=await api.post(base+'/admin/v2/api/metadata-fix/'+path,{data,timeout:240000});
assert.equal(response.status(),status,await response.text());
return response.json();
};
const expanded=await post('expand',{selection:{artists:[2719],releases:[],tracks:[]}});
const before=expanded.snapshot;
assert.equal(before.releases.length,4); assert.equal(before.tracks.length,10);
// Reproduce the reported request using ONLY the four release checkboxes.
if (process.env.FURU_REPAIR_TEST_MODEL) {
const selection={artists:[],releases:before.releases.map(r=>r.id),tracks:[]};
const instruction=`релизы #ИЗИРОК на самом деле один релиз типа компиляция 2021 года. тебе нужно сделать план по объединению в один релиз. вот полный треклист по порядку 01. Старик и братья
02. Потрошитель
03. Последняя песня
04. Песня для твоей подруги
05. Просто я сегодня... (feat. Перегаз)
06. Отзвуки тьмы
07. Битва за Москву
08. Настроение лето
09. Пробил час
10. Цусима`;
const proposed=await post('plan',{selection,instruction});
assert.equal(proposed.snapshot.artists.length,0);
assert.equal(proposed.snapshot.tracks.length,10);
assert.deepEqual(proposed.plan.artists,[]);
assert.deepEqual(proposed.plan.delete.artists,[]);
assert.deepEqual(proposed.plan.delete.tracks,[]);
const destination=proposed.plan.releases.find(r=>r.release_type==='compilation' && r.year===2021);
assert.ok(destination,JSON.stringify(proposed.plan));
const target=destination.id ? 'existing:'+destination.id : 'new:'+destination.key;
for (const [index,track] of before.tracks.entries()) {
const edit=proposed.plan.tracks.find(t=>t.id===track.id);
assert.equal(edit?.target_release || 'existing:'+track.release_id,target);
assert.equal(edit?.track_number ?? track.track_number,index+1);
assert.deepEqual(edit?.artist_ids || [2719],[2719]);
}
const result=await post('apply',{snapshot:proposed.snapshot,plan:proposed.plan,instruction});
assert.equal(sql('SELECT count(*) FROM furumusic__track'),'10');
assert.equal(sql('SELECT count(*) FROM furumusic__release'),'1');
assert.equal(sql('SELECT name FROM furumusic__artist'),'Radio Tapok');
await post('undo',{history_id:result.history_id});
assert.deepEqual((await post('expand',{selection:expanded.selection})).snapshot,before);
const excluded=await post('plan',{selection,excluded_track_ids:[33683],instruction:'Ничего не меняй. Верни пустой план.'});
assert.equal(excluded.snapshot.tracks.length,9);
assert.equal(excluded.snapshot.tracks.some(t=>t.id===33683),false);
assert.deepEqual(excluded.plan.tracks,[]);
const recovered=await post('plan',{selection,instruction:'__TEST_INVALID_ARTIST__ Объедини четыре релиза в компиляцию 2021 года.'});
assert.deepEqual(recovered.plan.artists,[]);
assert.equal(recovered.plan.releases[0].year,2021);
console.log('Release-only scope, exact ordered tracklist, model correction and exclusions passed.');
}
const artistIds=track=>before.track_artists.filter(link=>link.owner_id===track.id).map(link=>link.artist_id);
const merge={...emptyPlan(),releases:[{id:null,key:'collection',title:'#ИЗИРОК Сборник',release_type:'compilation',year:2021,artist_ids:[2719]}],tracks:before.tracks.map(track=>({id:track.id,title:track.title,target_release:'new:collection',track_number:track.track_number,disc_number:track.disc_number,year:track.year,artist_ids:artistIds(track)})),delete:{artists:[],releases:before.releases.map(release=>release.id),tracks:[]}};
await page.getByRole('button',{name:'Library Tools',exact:true}).click();
const tools=page.locator('.content').filter({has:page.getByText('Metadata assistant',{exact:true})});
await tools.locator('select').first().selectOption('artists');
await tools.getByPlaceholder('Search library…').fill('Radio Tapok');
await tools.locator('.repair-search-results button').first().click();
await tools.getByRole('button',{name:'Show related',exact:true}).click();
await page.waitForFunction(()=>Alpine.$data(document.querySelector('.admin-shell')).repairRowsCount()===15);
await tools.getByRole('button',{name:'Deselect all',exact:true}).click();
assert.equal(await tools.locator('.repair-entity input:checked').count(),0);
assert.equal(await tools.locator('.repair-entity input[type=checkbox]').count(),15);
for (const release of before.releases) {
await tools.getByRole('checkbox',{name:new RegExp('^#ИЗИРОК #' + release.id + ' ')}).check();
}
assert.equal(await tools.locator('.repair-entity input:checked').count(),14);
assert.equal(await tools.getByRole('checkbox',{name:'Radio Tapok #2719',exact:true}).isChecked(),false);
let calls=0;
await page.route('**/metadata-fix/plan',async route=>{
const body=route.request().postDataJSON(); calls++;
assert.deepEqual(body.selection,{...expanded.selection,artists:[]});
if (calls===1) await route.fulfill({json:{snapshot:before,plan:merge,message:'Объединю все 10 треков в сборник 2021 года.'}});
else {
assert.equal(body.current_plan.releases[0].year,2021);
assert.equal(body.conversation.length,2);
await route.fulfill({json:{snapshot:before,plan:{...merge,releases:[{...merge.releases[0],year:2022}]},message:'Год сборника изменён на 2022.'}});
}
});
const composer=tools.getByRole('textbox',{name:'Message to metadata assistant'});
await composer.fill('Объедини #ИЗИРОК в #ИЗИРОК Сборник, год 2021');
await tools.getByRole('button',{name:'Send',exact:true}).click();
await tools.getByText('Объединю все 10 треков в сборник 2021 года.',{exact:true}).waitFor();
const plan=tools.locator('details.repair-plan');
assert.equal(await plan.getAttribute('open'),null);
await plan.locator(':scope > summary').click();
await plan.getByText('Edit fields manually',{exact:true}).click();
assert.equal(await plan.locator('.repair-diff').nth(1).locator('input[type=number]').inputValue(),'2021');
await composer.fill('Сделай год 2022');
await tools.getByRole('button',{name:'Send',exact:true}).click();
await tools.getByText('Год сборника изменён на 2022.',{exact:true}).waitFor();
assert.equal(await tools.locator('details.repair-plan').count(),1);
assert.equal(await plan.locator('.repair-diff').nth(1).locator('input[type=number]').inputValue(),'2022');
await plan.getByText('Edit fields manually',{exact:true}).click();
await plan.locator(':scope > summary').scrollIntoViewIfNeeded();
await page.screenshot({path:'/tmp/furumi-repair-desktop.png'});
await page.setViewportSize({width:390,height:844});
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
await page.screenshot({path:'/tmp/furumi-repair-mobile.png'});
await page.setViewportSize({width:1440,height:1000});
// Apply the 2021 plan against the original snapshot, then undo it.
const applied=await post('apply',{snapshot:before,plan:merge,instruction:'Merge #ИЗИРОК'});
assert.equal(sql("SELECT title || '|' || year || '|' || total_tracks FROM furumusic__release"),'#ИЗИРОК Сборник|2021|10');
assert.equal(sql('SELECT count(*) FROM furumusic__track'),'10');
assert.equal(sql('SELECT count(*) FROM furumusic__media_file'),'10');
assert.equal(sql('SELECT count(*) FROM furumusic__playlist_track'),'2');
await post('undo',{history_id:applied.history_id});
assert.deepEqual((await post('expand',{selection:expanded.selection})).snapshot,before);
const deletion={...emptyPlan(),delete:{artists:[],releases:[],tracks:[33683,33684]}};
const removed=await post('apply',{snapshot:before,plan:deletion,instruction:'Delete two tracks'});
assert.equal(sql('SELECT count(*) FROM furumusic__track'),'8');
assert.equal(sql('SELECT count(*) FROM furumusic__playlist_track'),'0');
assert.equal(sql('SELECT count(*) FROM furumusic__track_ref WHERE local_track_id IS NULL'),'2');
assert.equal(sql('SELECT queue_json FROM furumusic__playback_state'),'[33685]');
await post('undo',{history_id:removed.history_id});
assert.equal(sql('SELECT count(*) FROM furumusic__playlist_track'),'2');
assert.equal(sql('SELECT local_track_id FROM furumusic__track_ref ORDER BY content_id'),'33683\n33684');
assert.equal(sql('SELECT current_track_id || \'|\' || position_ms || \'|\' || queue_json FROM furumusic__playback_state'),'33683|1234|[33683,33684,33685]');
assert.deepEqual((await post('expand',{selection:expanded.selection})).snapshot,before);
const artistRemoval=await post('apply',{snapshot:before,plan:{...emptyPlan(),delete:{artists:[2719],releases:[],tracks:[]}},instruction:'Delete artist'});
assert.equal(sql('SELECT count(*) FROM furumusic__artist'),'0');
assert.equal(sql('SELECT count(*) FROM furumusic__track'),'10');
assert.equal(sql('SELECT count(*) FROM furumusic__track_artist'),'0');
await post('undo',{history_id:artistRemoval.history_id});
assert.deepEqual((await post('expand',{selection:expanded.selection})).snapshot,before);
const invalid={...emptyPlan(),delete:{artists:[],releases:[4256],tracks:[]}};
await post('apply',{snapshot:before,plan:invalid,instruction:'Invalid deletion'},400);
// A changed detached reference must block undo atomically.
const conflict=await post('apply',{snapshot:before,plan:deletion,instruction:'Delete before playback changes'});
sql("UPDATE furumusic__playback_state SET position_ms=9876");
await post('undo',{history_id:conflict.history_id},409);
assert.equal(sql('SELECT count(*) FROM furumusic__track'),'8');
sql('UPDATE furumusic__playback_state SET position_ms=0');
await post('undo',{history_id:conflict.history_id});
assert.equal(sql('SELECT count(*) FROM furumusic__track'),'10');
assert.deepEqual(errors,[]);
console.log('Metadata Repair browser, merge, deletion, undo and conflict checks passed.');
} finally { await browser.close(); }
})().catch(error=>{console.error(error);process.exit(1);});
+45
View File
@@ -0,0 +1,45 @@
INSERT INTO furumusic__artist (id,name,is_hidden,name_sort,model_name,updated_at,created_at) VALUES (2719,'Radio Tapok',false,'radio tapok','unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K','2026-11-15T23:13:56Z','2026-01-01T00:00:00Z');
INSERT INTO furumusic__release (id,year,title,is_hidden,model_name,title_sort,updated_at,total_discs,release_type,total_tracks,cover_file_id,created_at) VALUES (4256,2018,'#ИЗИРОК',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K','#изирок','2026-11-15T23:25:33Z',NULL,'album',NULL,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__release (id,year,title,is_hidden,model_name,title_sort,updated_at,total_discs,release_type,total_tracks,cover_file_id,created_at) VALUES (4257,2019,'#ИЗИРОК',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K','#изирок','2026-11-15T23:25:34Z',NULL,'album',NULL,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__release (id,year,title,is_hidden,model_name,title_sort,updated_at,total_discs,release_type,total_tracks,cover_file_id,created_at) VALUES (4258,2020,'#ИЗИРОК',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K','#изирок','2026-11-15T23:25:46Z',NULL,'ep',NULL,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__release (id,year,title,is_hidden,model_name,title_sort,updated_at,total_discs,release_type,total_tracks,cover_file_id,created_at) VALUES (4259,2021,'#ИЗИРОК',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K','#изирок','2026-11-15T23:25:47Z',NULL,'ep',NULL,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33683,'audio','/tmp/test-33683.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033683','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33683,2018,'Старик и братья',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4256,'старик и братья','2026-11-15T23:25:32Z',NULL,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33683,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33684,'audio','/tmp/test-33684.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033684','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33684,2018,'Потрошитель',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4256,'потрошитель','2026-11-15T23:25:33Z',NULL,2,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33684,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33685,'audio','/tmp/test-33685.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033685','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33685,2018,'Последняя песня',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4256,'последняя песня','2026-11-15T23:25:33Z',NULL,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33685,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33686,'audio','/tmp/test-33686.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033686','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33686,2018,'Песня для твоей подруги',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4256,'песня для твоей подруги','2026-11-15T23:25:33Z',NULL,4,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33686,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33687,'audio','/tmp/test-33687.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033687','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33687,2018,'Просто я сегодня...',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4256,'просто я сегодня...','2026-11-15T23:25:33Z',NULL,5,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33687,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33688,'audio','/tmp/test-33688.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033688','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33688,2019,'Отзвуки тьмы',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4257,'отзвуки тьмы','2026-11-15T23:25:34Z',NULL,6,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33688,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33689,'audio','/tmp/test-33689.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033689','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33689,2019,'Битва за Москву',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4257,'битва за москву','2026-11-15T23:25:34Z',NULL,7,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33689,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33690,'audio','/tmp/test-33690.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033690','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33690,2020,'Настроение лето',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4258,'настроение лето','2026-11-15T23:25:46Z',NULL,8,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33690,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33691,'audio','/tmp/test-33691.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033691','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33691,2020,'Пробил час',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4258,'пробил час','2026-11-15T23:25:47Z',NULL,9,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33691,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__media_file (id,file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES (33692,'audio','/tmp/test-33692.mp3','test.mp3','audio/mpeg',1,'0000000000000000000000000000000000000000000000000000000000033692','2026-01-01T00:00:00Z');
INSERT INTO furumusic__track (id,year,title,is_hidden,model_name,release_id,title_sort,updated_at,disc_number,track_number,lastfm_rating,lastfm_listeners,lastfm_playcount,lastfm_checked_at,lastfm_updated_at,lastfm_lookup_title,lastfm_lookup_artist,duration_seconds,audio_file_id,cover_file_id,created_at) VALUES (33692,2021,'Цусима',false,'unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q6_K',4259,'цусима','2026-11-15T23:25:47Z',NULL,10,NULL,NULL,NULL,NULL,NULL,NULL,NULL,180,33692,NULL,'2026-01-01T00:00:00Z');
INSERT INTO furumusic__release_artist (release_id,artist_id,position) VALUES (4256,2719,0);
INSERT INTO furumusic__release_artist (release_id,artist_id,position) VALUES (4257,2719,0);
INSERT INTO furumusic__release_artist (release_id,artist_id,position) VALUES (4258,2719,0);
INSERT INTO furumusic__release_artist (release_id,artist_id,position) VALUES (4259,2719,0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33683,2719,'main',0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33684,2719,'main',0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33685,2719,'main',0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33686,2719,'main',0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33687,2719,'main',0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33688,2719,'main',0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33689,2719,'main',0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33690,2719,'main',0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33691,2719,'main',0);
INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) VALUES (33692,2719,'main',0);
INSERT INTO furumusic__playlist (id,owner_id,title,is_public,created_at,updated_at) VALUES (1,1,'Repair test',false,'2026-01-01T00:00:00Z','2026-01-01T00:00:00Z');
INSERT INTO furumusic__playlist_track (playlist_id,track_id,position,added_at,added_by_user_id) VALUES (1,33683,0,'2026-01-01T00:00:00Z',1);
INSERT INTO furumusic__track_ref (content_id,local_track_id,title,created_at,updated_at) VALUES ('content-33683',33683,'Старик и братья','2026-01-01T00:00:00Z','2026-01-01T00:00:00Z');
INSERT INTO furumusic__playlist_track (playlist_id,track_id,position,added_at,added_by_user_id) VALUES (1,33684,1,'2026-01-01T00:00:00Z',1);
INSERT INTO furumusic__track_ref (content_id,local_track_id,title,created_at,updated_at) VALUES ('content-33684',33684,'Потрошитель','2026-01-01T00:00:00Z','2026-01-01T00:00:00Z');
INSERT INTO furumusic__playback_state (user_id,current_track_id,position_ms,queue_json,queue_position,shuffle,repeat_mode,volume,updated_at) VALUES (1,33683,1234,'[33683,33684,33685]',0,false,'off',1.0,'2026-01-01T00:00:00Z');
+9 -2
View File
@@ -3,11 +3,11 @@ const {readFileSync} = require('node:fs');
const {test} = require('node:test'); const {test} = require('node:test');
const vm = require('node:vm'); const vm = require('node:vm');
const template = readFileSync(`${__dirname}/../templates/player/scripts.html`, 'utf8'); const template = readFileSync(`${__dirname}/../templates/player/scripts.html`, 'utf8');
function player(fetchImpl = async () => ({ok:true}), beacon = () => true) { function player(fetchImpl = async () => ({ok:true}), beacon = () => true, guest = false) {
// Exercise the production methods with audio and network stubs. // Exercise the production methods with audio and network stubs.
const methods = template.slice(template.indexOf(' _recordHistory(endedReason'), template.indexOf(' _sendNowPlaying()')); const methods = template.slice(template.indexOf(' _recordHistory(endedReason'), template.indexOf(' _sendNowPlaying()'));
const audio = {currentTime:60}; const audio = {currentTime:60};
const context = vm.createContext({audio, fetch:fetchImpl, navigator:{sendBeacon:beacon}, Blob, const context = vm.createContext({GUEST:guest, audio, fetch:fetchImpl, navigator:{sendBeacon:beacon}, Blob,
globalThis:{crypto:{randomUUID:()=> 'uuid'}}, setTimeout: fn => { fn(); }, console}); globalThis:{crypto:{randomUUID:()=> 'uuid'}}, setTimeout: fn => { fn(); }, console});
vm.runInContext('this.methods = {' + methods + '};', context); vm.runInContext('this.methods = {' + methods + '};', context);
return Object.assign(context.methods, { return Object.assign(context.methods, {
@@ -50,3 +50,10 @@ test('unstarted tracks and sub-five-second interrupted sessions are not recorded
p._playbackStartedAt=123; p._listenedSeconds=4; p._recordHistory('skipped'); await flush(); p._playbackStartedAt=123; p._listenedSeconds=4; p._recordHistory('skipped'); await flush();
assert.equal(p._historyRecorded,false); assert.equal(p._historyRecorded,false);
}); });
test('guest listening never writes personal history or sends a beacon', async () => {
const calls = [];
const p = player(async () => {calls.push('fetch'); return {ok:true};}, () => {calls.push('beacon'); return true;}, true);
p._recordHistory('finished'); p._recordHistory('stopped', true);
await flush(); assert.deepEqual(calls, []);
});