Compare commits

..

30 Commits

Author SHA1 Message Date
Psychotoxical 489d50016f docs: add v1.34.2 changelog entry
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 14:57:20 +02:00
Psychotoxical 47490072ef chore: bump version to 1.34.2
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 14:52:34 +02:00
Psychotoxical ff0a588014 feat(audio): add ALAC and AAC-LC native decoding via Symphonia
Add 'alac' to symphonia features. Combined with the existing 'aac' and
'isomp4' features this enables native lossless decoding of Apple Lossless
Audio Codec (.m4a/ALAC) and AAC-LC files without server-side transcoding.

Symphonia probes the format from the stream bytes, so no URL or hint
changes are needed for server streams.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 14:34:00 +02:00
Psychotoxical e4041287e2 chore(contributors): add cucadmuh PR #125 to contributor list
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 14:00:12 +02:00
Psychotoxical 70f0641439 feat(subsonic): per-server music folder filter and sidebar picker (#125)
Adds library scoping per server: users can select one Navidrome music
folder or 'All' from a new sidebar dropdown. Choice is persisted per
server ID in localStorage. A musicLibraryFilterVersion counter triggers
refetches across browsing pages when the scope changes.

- getMusicFolders() + libraryFilterParams() in subsonic.ts
- New fields in authStore: musicFolders, musicLibraryFilterByServer,
  musicLibraryFilterVersion, setMusicFolders, setMusicLibraryFilter
- Sidebar dropdown via createPortal; collapses to icon in narrow mode
- API scoping applied to: getAlbumList2, getRandomSongs, getArtists,
  getStarred2, search3
- Full i18n coverage (en, de, fr, nl, zh, nb, ru)

Review fixes applied (co-authored):
- Sidebar: title={} → data-tooltip + data-tooltip-pos='right'
- authStore: setMusicFolders merged into single set() call
- Locales: removed dead libraryScopeHint key from all 7 files
- Genres.tsx: removed musicLibraryFilterVersion dep (getGenres unscoped)

Co-authored-by: cucadmuh <cucadmuh@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 13:54:57 +02:00
Psychotoxical c779e8f587 fix(pr-review): address review findings for music folder filter
- Sidebar.tsx: title={} → data-tooltip + data-tooltip-pos="right" on
  scope subtitle (CLAUDE.md rule: never use native title= for tooltips)

- authStore.ts: merge two set() calls in setMusicFolders into one atomic
  update — avoids double render on folder list arrival

- locales (all 7): remove dead libraryScopeHint key (defined but never
  rendered in any component)

- Genres.tsx: remove musicLibraryFilterVersion from effect deps —
  getGenres is intentionally not folder-scoped, re-fetching on filter
  change was a no-op waste

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 13:53:44 +02:00
Psychotoxical 95468fb137 refactor: remove Tauri auto-updater, replace with simple GitHub-check modal
Remove tauri-plugin-updater, relaunch_after_update command, generate-update-
manifest.js, the generate-manifest CI job, and all signing/upload steps for
.sig files and latest.json. The updater plugin, its pubkey and endpoint config
in tauri.conf.json, and the updater:default capability are all gone.

Replace AppUpdater.tsx with a lightweight component that:
- Fetches https://api.github.com/repos/Psychotoxical/psysonic/releases/latest
  after a 4 s delay (no install, no download, no progress bar)
- Shows a dismissible toast with two buttons:
  GitHub → releases/latest
  Website → https://psysonic.psychotoxic.eu/#downloads

i18n: remove updaterInstall/Downloading/Installing/Download/ExperimentalHint
keys from all 7 locales; add updaterWebsite; update updaterVersion wording.

CI: remove generate-manifest job and all .sig signing/upload steps from
build-macos-windows. Also remove TAURI_SIGNING_PRIVATE_KEY env vars (no
longer needed). Release now just builds and uploads the installable binaries.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 13:42:52 +02:00
Maxim Isaev c36b1ea538 fix(ui): dismiss tooltip on mousedown; hide library dropdown hint while open
TooltipPortal clears the overlay when mousedown hits any [data-tooltip] anchor so click-open controls (e.g. library scope) do not leave a stale hover tooltip. The library scope trigger omits data-tooltip while the dropdown is open.
2026-04-07 14:27:47 +03:00
Psychotoxical 3f1b6fd92d fix(audio): restore device-default rate when Hi-Res is toggled off
The previous optimization skipped all rate-switch logic in standard mode,
but left the stream at e.g. 88.2 kHz if Hi-Res was toggled off mid-session.

Fix: store device_default_rate (from cold-start open) in AudioEngine.
In audio_play, compute target_rate = hi_res ? output_rate : device_default_rate
and reopen only when target differs from current — no-op cost when already
at the right rate (the common case in pure standard mode).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 13:18:33 +02:00
Psychotoxical 1c2aa79e29 perf(audio): standard mode resource optimization — lower CPU at 44.1kHz
Stream switch: skip entirely when hi_res_enabled=false. Previously the
engine compared 44100 vs. device-default 48000 Hz and re-opened the device
on every track start — unnecessary IPC + PipeWire reconfigure in safe mode.

MSS buffer: 512 KB in standard mode (was 4 MB). For in-memory MP3/AAC
the large buffer caused eager allocation competing with playback startup.
4 MB is kept only for hi-res (high-bitrate FLAC benefits from fewer reads).

ThreadPriority: no longer set Max at audio-stream-thread startup. Max is
now applied only when a hi-res reopen is requested, keeping the scheduler
budget for the actual decode threads during standard playback.

audio_preload: 8 s throttle delay + gen guard so background pre-fetch does
not compete with the decode/sink-feed cycle of the just-started track.

needs_prefill: now gated on hi_res_enabled to make the condition explicit.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 13:12:03 +02:00
Maxim Isaev f08619fb3d feat(subsonic): per-server music folder filter and sidebar picker
Apply musicFolderId across Subsonic requests, bump a filter version so library views reload, and add a fixed-position sidebar dropdown (with capped height when there are many folders).
2026-04-07 13:59:59 +03:00
Psychotoxical 5ec8fa8ba3 fix(fullscreen): remove letter-spacing from track title to fix optical misalignment
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 12:46:27 +02:00
Psychotoxical 51c118806e feat(fullscreen): track name on top, large & bold; artist name below, small
Swap DOM order and styles in the info cluster:
- fs-track-title: clamp(28px,4.5vw,68px) / weight 900 / var(--accent) — primary
- fs-artist-name: clamp(13px,1.5vw,22px) / weight 400 / 55% opacity — secondary
- fs-cluster gap: 12px → 8px (denser hierarchy)
- fs-meta: margin-top: 4px for breathing room after artist name

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 12:44:32 +02:00
Psychotoxical fc653941c2 fix(lyrics): allow line wrapping in fullscreen lyrics overlay
Increase slot height from 3.6vh → 6vh (CSS + JS factor 0.036 → 0.06)
so that long lyric lines can wrap onto a second line without being clipped.

Fixed height on .fs-lyric-line is kept intentional — rail math requires
uniform slots. 2 wrapped lines at 2vh font / 1.4 line-height = 5.6vh,
comfortably inside the 6vh slot. font-size adjusted from 2.2vh → 2vh.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 12:36:06 +02:00
Psychotoxical 8add62a502 perf(lyrics): fix CPU spikes during lyric transitions; fix release workflow
CSS: remove `font-weight` from transition list on `.fs-lyric-line` — it
triggers layout reflow on every animation frame when the active line changes.
Replaced with `transform: scaleX(1.015)` on `.fsl-active` (compositor-only).
Added `contain: layout style` to `.fs-lyrics-overlay` to isolate reflows.

Cargo.lock: update for thread-priority crate (added in previous audio commit).

CI: replace delete-asset workaround with `updaterJsonKeepUniversal: false`
to prevent tauri-action from uploading a latest.json with wrong signature.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 12:30:32 +02:00
Psychotoxical 44287a7ceb feat(audio): bit-perfect hi-res playback + underrun hardening (opt-in alpha)
Safe mode (default): all audio outputs at 44.1 kHz, rodio resamples
internally. Maximum stability out of the box.

Hi-Res mode (alpha toggle): stream opens at the file's native sample rate
(e.g. 88.2/96/192 kHz) for bit-perfect output.

Rust (audio.rs):
- open_stream_for_rate(): CPAL queries device supported configs, finds
  exact rate match or falls back to highest available / device default.
- create_engine() thread: ThreadPriority::Max (silently ignored without
  CAP_SYS_NICE), loop handles rate-switch requests, PIPEWIRE_LATENCY
  scales with rate (8192 frames for >48 kHz ≈ 93 ms quantum), keeps
  PULSE_LATENCY_MSEC in sync.
- audio_play(): hi_res_enabled param gates effective_rate (44100 vs
  native); stream re-opens only when needed; 150 ms PipeWire settle +
  500 ms sink pre-fill (pause→append→sleep→play) for hi-res tracks.
- audio_chain_preload(): hi_res_enabled param; rate-mismatch bail skipped
  in safe mode so gapless chains always work at 44.1 kHz.
- SizedDecoder MSS buffer: 4 MB (was 512 KB) to reduce Symphonia read
  overhead on high-bitrate hi-res files.
- thread-priority crate added to Cargo.toml.

Frontend:
- authStore: enableHiRes (bool, default false) + setEnableHiRes.
- playerStore: hiResEnabled passed to all audio_play /
  audio_chain_preload invoke calls.
- Settings → Audio tab: "Native Hi-Res Playback" toggle with Alpha
  badge and stability warning, i18n for all 7 languages.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 12:20:07 +02:00
cucadmuh 0f3033d84e feat: add hot playback cache (queue prefetch, alpha)
Ephemeral on-disk cache for upcoming queue tracks. Adds Rust commands (download/delete/purge), hotCacheStore with LRU eviction, serial prefetch worker, playback gate, and Settings UI. Disabled by default.

- fix: boundary check before file delete in delete_hot_cache_track
- fix: remove stale languageRu2 key from ru.ts
- fix: restore accidentally removed lyricsServerFirst/fsLyricsToggle/lyricsSource* strings in ru.ts
2026-04-07 10:52:26 +02:00
Psychotoxical d49af977ed docs: add v1.34.1 changelog entry
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 23:12:48 +02:00
Psychotoxical d73f348339 feat: v1.34.1 — fullscreen lyrics overlay, FsArt crossfade, lyrics toggle, contributor updates
- FullscreenPlayer: synced lyrics overlay (5-line rail, mask fade, click-to-seek)
- FullscreenPlayer: FsArt crossfade component with onLoad pattern, 300px art, next-track pre-fetch
- FullscreenPlayer: MicVocal lyrics toggle button next to heart (persisted in authStore)
- FullscreenPlayer: idle system — only close button auto-hides, cluster+seekbar always visible
- LyricsPane: refactored to use shared useLyrics hook (no double-fetch with FS overlay)
- authStore: showFullscreenLyrics field (default true)
- i18n: fsLyricsToggle key added to all 7 locales; ru2.ts removed (merged into ru.ts)
- Settings: Contributors updated (nisrael, cucadmuh, kilyabin); logout moved to Server tab as btn-danger
- theme.css: btn-danger style added

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 23:00:33 +02:00
Psychotoxical 390e6e788d chore: bump version to 1.34.1
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 22:59:32 +02:00
Psychotoxical ff950efb0c feat(settings): add nisrael to contributors, update cucadmuh/kilyabin, move logout button
- Add nisrael (Nightfox themes PR #114, rustls-tls fix PR #112)
- Update cucadmuh with gapless manual skip fix (PR #119)
- Update kilyabin with RU locale improvements (PR #120) and auto-install script (PR #121)
- Move logout button from System tab to Server tab — styled as btn-danger (outlined red)
- Add .btn-danger CSS class to theme.css

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 22:54:27 +02:00
Psychotoxical 4ef21d6d78 i18n(ru): apply translation improvements from PR #120
Manually merged kilyabin's Russian locale improvements (more natural phrasing
throughout) while preserving keys added after #120 was opened: fsLyricsToggle,
lyricsServerFirst/Desc, lyricsSourceServer/Lrclib.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 22:46:41 +02:00
kilyabin 7fc0550b65 feat: auto-install script for Debian/RHEL 2026-04-06 22:39:19 +02:00
cucadmuh 5d06738ce1 fix(audio): gapless manual skip — honor user-initiated play over pre-chained track
* fix(audio): honor manual skip when next track is gapless-pre-chained

* fix(audio): match gapless chain and preload by stream id, not full URL
2026-04-06 22:39:16 +02:00
Psychotoxical 1197c1f916 feat: album cover art in Discord Rich Presence via iTunes Search API
Fetches album artwork from the iTunes Search API and passes the URL
directly to Discord's large_image field. Subsonic cover URLs require
auth and can't be used by Discord directly.

- 3-strategy search: exact quoted → relaxed → track title fallback
- 1-hour in-memory cache per artist|album key
- iTunes search runs in tokio::task::spawn_blocking (reqwest::blocking
  must not run on the Tokio async executor)
- artwork_cache wrapped in Arc<Mutex<...>> for cross-thread sharing
- Fallback to the pre-uploaded "psysonic" asset when no match found
- Cargo.toml: blocking feature alongside rustls-tls

Co-Authored-By: kilyabin <kilyabin@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 19:30:22 +02:00
Psychotoxical b448c2bc82 fix(queue): revert auto-scroll target back to queueIndex+1
The queue-current-track section already shows the active track above the
list. Scrolling to queueIndex+1 (next track) is the correct behavior —
it keeps the upcoming tracks in view, not the already-visible current one.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 19:23:55 +02:00
cucadmuh 6226383762 i18n(ru): refine Russian locale using phrasing from ru2
Co-authored-by: Psychotoxical <dev@psysonic.app>
2026-04-06 19:13:47 +02:00
nisarg 13a8f696d0 fix: queue auto-scroll to current track and fix re-renders
* stop queue panel from constant rerendering

* add queueHeader type

* fix(queue): move hook before early return, fix auto-scroll target

- usePlayerStore must be called before conditional return (Rules of Hooks)
- Auto-scroll to songs[queueIndex] not [queueIndex+1] — current track,
  not the next one

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Psychotoxical <dev@psysonic.app>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 19:11:03 +02:00
Nils Israel 64e0948904 feat: integrate nightfox.nvim themes into Open Source Classics
* feat: integrate nightfox.nvim themes into Open Source Classics

Agent-Logs-Url: https://github.com/nisrael/psysonic/sessions/410b9047-62de-4c0b-a6bc-1dc6f8247164

Co-authored-by: nisrael <66925+nisrael@users.noreply.github.com>

* i18n: add Nightfox to theme FAQ in de + zh

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: nisrael <66925+nisrael@users.noreply.github.com>
Co-authored-by: Psychotoxical <dev@psysonic.app>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 19:09:39 +02:00
Nils Israel 10b2bde5ef fix: switch reqwest to rustls-tls for cross-platform TLS compatibility
The native-tls backend (macOS Security framework) was failing with
'bad protocol version' when connecting to HTTPS music servers.
Switching to rustls (statically linked, no system dependency) fixes
playback on macOS and ensures consistent TLS 1.2/1.3 support across
all platforms.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-06 19:06:55 +02:00
68 changed files with 3779 additions and 2021 deletions
-74
View File
@@ -80,9 +80,6 @@ jobs:
needs: create-release
permissions:
contents: write
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
strategy:
fail-fast: false
matrix:
@@ -125,48 +122,6 @@ jobs:
releaseId: ${{ needs.create-release.outputs.release_id }}
args: ${{ matrix.settings.args }}
# tauri-action auto-generates a latest.json using the pubkey from tauri.conf.json
# as the signature value (wrong). Delete it so only our generate-update-manifest.js
# output is ever used as the canonical update manifest.
- name: remove tauri-action generated update manifest
shell: bash
run: |
gh release delete-asset ${{ github.ref_name }} latest.json --yes || true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: sign and upload Windows NSIS updater bundle
if: matrix.settings.platform == 'windows-latest'
shell: pwsh
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ needs.create-release.outputs.package_version }}
run: |
$dir = "src-tauri/target/release/bundle/nsis"
$exe = (Get-ChildItem $dir -Filter "*.exe")[0].FullName
$zip = $exe -replace '\.exe$', '.nsis.zip'
Compress-Archive -Path $exe -DestinationPath $zip -Force
npx tauri signer sign --private-key "$env:TAURI_SIGNING_PRIVATE_KEY" --password "$env:TAURI_SIGNING_PRIVATE_KEY_PASSWORD" $zip
gh release upload "app-v$env:VERSION" $zip "$zip.sig" --clobber
- name: sign and upload macOS bundle signature
if: matrix.settings.platform == 'macos-latest'
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ needs.create-release.outputs.package_version }}
run: |
if [[ "${{ matrix.settings.args }}" == *"aarch64"* ]]; then
BUNDLE="src-tauri/target/aarch64-apple-darwin/release/bundle/macos/Psysonic.app.tar.gz"
SIG_NAME="Psysonic_aarch64.app.tar.gz.sig"
else
BUNDLE="src-tauri/target/x86_64-apple-darwin/release/bundle/macos/Psysonic.app.tar.gz"
SIG_NAME="Psysonic_x64.app.tar.gz.sig"
fi
npx tauri signer sign --private-key "$TAURI_SIGNING_PRIVATE_KEY" --password "$TAURI_SIGNING_PRIVATE_KEY_PASSWORD" "$BUNDLE"
cp "${BUNDLE}.sig" "$SIG_NAME"
gh release upload "app-v${VERSION}" "$SIG_NAME" --clobber
build-linux:
needs: create-release
permissions:
@@ -219,32 +174,3 @@ jobs:
find src-tauri/target/release/bundle \
\( -name "*.deb" -o -name "*.rpm" \) \
| xargs gh release upload "app-v${VERSION}" --clobber
generate-manifest:
needs: [create-release, build-macos-windows]
permissions:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- name: setup node
uses: actions/setup-node@v5
with:
node-version: lts/*
- name: cache npm
uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
restore-keys: ${{ runner.os }}-npm-
- name: generate latest.json
env:
VERSION: ${{ needs.create-release.outputs.package_version }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: node scripts/generate-update-manifest.js
- name: upload latest.json
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
VERSION=${{ needs.create-release.outputs.package_version }}
gh release upload "app-v${VERSION}" latest.json --clobber
+80
View File
@@ -5,6 +5,86 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.34.2] - 2026-04-07
### Added
- **M4A / ALAC / AAC-LC support** *(closes [#51](https://github.com/Psychotoxical/psysonic/issues/51))*: Apple Lossless (ALAC) and AAC-LC files in M4A containers are now decoded natively by the Rust audio engine (Symphonia) without requiring server-side transcoding.
- **Per-server music folder filter** *(PR [#125](https://github.com/Psychotoxical/psysonic/pull/125) by [@cucadmuh](https://github.com/cucadmuh))*: Users with multiple music libraries on their Navidrome server can now scope browsing to a single folder. A dropdown in the sidebar (visible only when more than one library exists) lets you pick a folder or switch back to "All Libraries". The selection is persisted per server and automatically resets to "All" if the selected folder is no longer available.
- **Hi-Res / Bit-Perfect Playback** *(Alpha)*: New opt-in toggle in Settings → Playback. When enabled, the audio output stream is re-opened at the file's native sample rate (e.g. 88.2 kHz, 96 kHz) — bypassing rodio's internal resampler for a bit-perfect signal path. Disabled by default (safe 44.1 kHz mode). Includes ALSA/PipeWire underrun hardening: scaled quantum size, 500 ms sink pre-fill at high rates, and scheduler priority escalation only when needed.
- **Hot Playback Cache** *(Alpha, PR [#123](https://github.com/Psychotoxical/psysonic/pull/123) by [@cucadmuh](https://github.com/cucadmuh))*: Configurable on-disk prefetch cache for the next track in the queue. Reduces playback latency on slow or metered connections. Toggle and directory can be configured in Settings → Storage.
### Changed
- **Fullscreen Player — info block reworked**: The track title is now the dominant element (large, bold, accent color) and sits above the artist name (small, muted). Matches community feedback on visual hierarchy.
- **Fullscreen lyrics — line wrapping**: Long lyric lines now wrap onto a second line instead of being truncated. Slot height increased from 3.6 vh to 6 vh to accommodate two-line entries without breaking rail positioning.
- **Update notifications**: Removed the Tauri auto-updater (in-app download and install). The app now shows a simple dismissible toast when a newer version is detected on GitHub, with direct links to the [GitHub Releases page](https://github.com/Psychotoxical/psysonic/releases/latest) and the [Psysonic website](https://psysonic.psychotoxic.eu/#downloads). No signing keys, no update manifests.
### Fixed
- **Standard mode CPU usage**: Playing a 44.1 kHz MP3 with Hi-Res disabled no longer triggers an unnecessary audio device re-open on every track start. MSS read-ahead buffer reduced from 4 MB to 512 KB for standard-rate files. Background prefetch is now throttled by 8 s to avoid competing with playback startup. Combined, these changes reduce idle CPU from ~610 % to ~23 % on a modern machine.
- **Hi-Res toggle — stream rate not restored**: Toggling Hi-Res off while a track was playing at 88.2 or 96 kHz left the output stream at the high rate for subsequent tracks. The device's default rate is now restored on the next play.
- **Fullscreen lyrics — CPU spikes on line transitions**: Animating `font-weight` in CSS triggered a full layout reflow on every animation frame. Removed `font-weight` from the transition list; active-line emphasis now uses `transform: scaleX(1.015)` (compositor-only). Added `contain: layout style` to the overlay to isolate reflows from the rest of the page.
### i18n
- New keys for Hi-Res playback settings and music folder filter added to all 7 languages (EN, DE, FR, NL, ZH, NB, RU).
---
## [1.34.1] - 2026-04-06
### Added
- **Fullscreen Player — Synced Lyrics Overlay**: Synced lyrics are now displayed directly in the Fullscreen Player as an animated 5-line rail with a soft fade mask at the top and bottom edges. Click any visible line to seek to that position. Toggle the overlay on/off with the new microphone icon button next to the heart — preference is persisted.
> **Note:** The overlay currently requires synced (timestamped) lyrics. Support for unsynced lyrics in the Fullscreen Player is planned for a future release.
- **Embedded Lyrics & LRC support**: The app now fetches lyrics from two sources using the shared `useLyrics` hook (used by both the Lyrics Pane and the Fullscreen overlay):
- **Server-embedded lyrics** via the OpenSubsonic `getLyricsBySongId` endpoint — reads timestamped or plain lyrics baked directly into the audio file's tags (Navidrome 0.53+).
- **LRCLIB** — external LRC lookup as fallback (or primary, configurable in Settings → Playback).
Both sources share a module-level cache so switching between the Lyrics Pane and the Fullscreen Player never triggers a second network request.
- **Artist Image Upload**: A camera overlay now appears when hovering the artist portrait on the Artist page. Clicking it opens a file picker and uploads the image directly to your server.
> **Requires `EnableArtworkUpload = true`** in your Navidrome configuration (new option in Navidrome [#5110](https://github.com/navidrome/navidrome/issues/5110) / [#5198](https://github.com/navidrome/navidrome/issues/5198) — default: `true`). The same requirement applies to the existing Radio Station cover upload.
- **Discord Rich Presence — Album Cover Art**: Album artwork is now displayed in Discord's Rich Presence card. Because Subsonic cover URLs require authentication (and can't be accessed by Discord directly), artwork is fetched from the iTunes Search API using a 3-strategy search (exact → relaxed → track-title fallback), cached for 1 hour, and passed as a direct URL to Discord. Falls back to the static Psysonic asset when no match is found.
- **Nightfox themes** *(PR [#112](https://github.com/Psychotoxical/psysonic/pull/112) by [@nisrael](https://github.com/nisrael))*: Six themes from the [nightfox.nvim](https://github.com/EdenEast/nightfox.nvim) palette have been added to the **Open Source Classics** group — Dawnfox, Dayfox, Nightfox, Nordfox, Carbonfox, and Terafox.
- **Auto-install script** *(PR [#121](https://github.com/Psychotoxical/psysonic/pull/121) by [@kilyabin](https://github.com/kilyabin))*: `install.sh` now supports Debian/Ubuntu (`.deb`) and RHEL/Fedora (`.rpm`) — automatically detects the distro, downloads the correct package from the latest release, and installs it.
### Changed
- **Fullscreen Player — performance overhaul**:
- `FsArt` (cover art) and `FsLyrics` are now isolated `memo` components — unrelated state changes no longer trigger their re-renders.
- Cover crossfade uses an `onLoad` DOM event instead of `new Image()` preloading. This avoids a React batching edge case where both state updates were flushed together and the browser never saw the `opacity: 0` starting state, preventing the CSS transition from firing.
- `useCachedUrl(..., true)` passes the raw URL as an immediate fallback — the image starts fetching from the network instantly while IndexedDB resolves the blob in the background.
- Lyrics slot height is stored in a `useRef` and updated only on `resize` — eliminates repeated `window.innerHeight` layout reads on every render.
- Mouse-move handler is throttled to 200 ms.
- **Artist page — biography**: The bio text is now collapsed by default with a *Read more* / *Show less* toggle button, keeping the page layout clean for artists with long bios.
- **Settings — Logout button**: Moved from the System tab to the bottom of the Server tab, styled as a danger button (red outline → red fill on hover).
### Fixed
- **Gapless playback — manual skip** *(PR [#119](https://github.com/Psychotoxical/psysonic/pull/119) by [@cucadmuh](https://github.com/cucadmuh))*: When the next track had already been gapless-pre-chained into the Sink, a manual skip would not interrupt it — the pre-chained track continued playing at full volume from the old Sink after the fade-out. The chain is now matched by stream identity so user-initiated playback always takes precedence.
- **Radio / Artist cover cache**: `invalidateCoverArt` is now called after every cover upload and delete, so the old image is evicted from the local cache immediately.
- **Queue auto-scroll**: The active track now scrolls reliably into view; eliminated unnecessary component re-renders caused by unstable selector references.
- **macOS TLS** *(PR [#114](https://github.com/Psychotoxical/psysonic/pull/114) by [@nisrael](https://github.com/nisrael))*: Switched `reqwest` from `native-tls` (macOS Security framework) to `rustls-tls` (statically linked). The native backend was returning *bad protocol version* when connecting to HTTPS music servers, silently preventing playback.
### i18n
- **Russian translation improvements** *(PR [#120](https://github.com/Psychotoxical/psysonic/pull/120) by [@kilyabin](https://github.com/kilyabin))*: Extensive phrasing refinements across the entire Russian locale.
- New keys (`fsLyricsToggle`, embedded lyrics settings) added to all 7 languages (EN, DE, FR, NL, ZH, NB, RU).
---
## [1.34.0] - 2026-04-06
### Added
+7 -1
View File
@@ -32,7 +32,7 @@ Designed specifically for users hosting their own music via Navidrome or other S
## ✨ Features
- 🎨 **Gorgeous UI**: A large selection of beautiful, lean themes for every taste — Open Source Classics (Catppuccin, Nord, Gruvbox), Operating Systems, Games, Movies, Series, Psysonic originals, and Mediaplayer — with smooth glassmorphism effects and micro-animations.
- 🎨 **Gorgeous UI**: A large selection of beautiful, lean themes for every taste — Open Source Classics (Catppuccin, Nord, Gruvbox, Nightfox), Operating Systems, Games, Movies, Series, Psysonic originals, and Mediaplayer — with smooth glassmorphism effects and micro-animations.
-**Blazing Fast**: Built with Rust & Tauri — native audio engine (rodio), minimal RAM usage compared to typical Electron apps.
- 🌍 **Internationalization (i18n)**: Fully translated into English, German, French, Dutch, and Chinese.
- 📻 **Live "Now Playing"**: See what other users on your server are currently listening to in real-time.
@@ -92,6 +92,12 @@ Navigate to the [Releases](https://github.com/Psychotoxical/psysonic/releases) p
### 🐧 Linux
**Quick Install (Recommended):**
```bash
curl -fsSL https://raw.githubusercontent.com/Psychotoxical/psysonic/main/scripts/install.sh | sudo bash
```
**Manual Installation:**
- **Ubuntu / Debian**: `.deb` from GitHub Releases
- **Fedora / RHEL**: `.rpm` from GitHub Releases
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "psysonic",
"version": "1.34.0",
"version": "1.34.2",
"private": true,
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -1,6 +1,6 @@
# Maintainer: Psychotoxic <psychotoxic@gmx.de>
pkgname=psysonic
pkgver=1.34.0
pkgver=1.34.1
pkgrel=1
pkgdesc="Desktop music player for Subsonic API-compatible servers (Navidrome, Gonic, etc.)"
arch=('x86_64')
+52
View File
@@ -0,0 +1,52 @@
# Scripts
## install.sh - Auto-Installer for Debian and RHEL-based Systems
This script automatically downloads and installs the latest Psysonic release from GitHub Releases.
### Supported Distributions
- **Debian/Ubuntu**: Downloads and installs `.deb` package
- **RHEL/Fedora/CentOS**: Downloads and installs `.rpm` package
### Usage
#### Quick Install (Recommended)
```bash
curl -fsSL https://raw.githubusercontent.com/Psychotoxical/psysonic/main/scripts/install.sh | sudo bash
```
#### Manual Installation
```bash
# Download the script
wget https://raw.githubusercontent.com/Psychotoxical/psysonic/main/scripts/install.sh
# Make it executable
chmod +x install.sh
# Run with sudo
sudo ./install.sh
```
### What it does
1. Detects your OS type (Debian or RHEL-based)
2. Fetches the latest release from GitHub
3. Downloads the appropriate package (.deb or .rpm)
4. Installs it using your system's package manager
5. Cleans up temporary files
### Requirements
- `curl` - for downloading packages
- `sudo` or root access
- Internet connection
- Supported package manager (apt-get, dnf, or yum)
### Notes
- If Psysonic is already installed, the script will ask if you want to reinstall
- The script automatically handles dependency installation for Debian systems
- After installation, you can launch Psysonic from your application menu or by running `psysonic` in the terminal
-90
View File
@@ -1,90 +0,0 @@
#!/usr/bin/env node
// Generates latest.json for the Tauri updater from a GitHub release.
// Reads .sig files uploaded by tauri-action, assembles the manifest, writes latest.json.
//
// Required env vars: VERSION, GITHUB_TOKEN
// Usage: node scripts/generate-update-manifest.js
const { execSync } = require('child_process');
const fs = require('fs');
const VERSION = process.env.VERSION;
const REPO = 'Psychotoxical/psysonic';
const TAG = `app-v${VERSION}`;
if (!VERSION) {
console.error('VERSION env var required');
process.exit(1);
}
// Platform → update bundle filename (produced by tauri-action with updater plugin)
const PLATFORM_FILES = {
'darwin-aarch64': `Psysonic_aarch64.app.tar.gz`,
'darwin-x86_64': `Psysonic_x64.app.tar.gz`,
'windows-x86_64': `Psysonic_${VERSION}_x64-setup.nsis.zip`,
};
const platforms = {};
// A real minisign .sig file is multi-line and ~200+ chars.
// A public key (RWTxxx... single line, ~56 chars) must never appear here.
function validateSignature(sig, platform, sigFile) {
// Public keys start with RWT and are a single short base64 token
if (/^RWT[A-Za-z0-9+/]{10,}={0,2}$/.test(sig)) {
throw new Error(
`${platform}: .sig file "${sigFile}" contains a PUBLIC KEY instead of a signature.\n` +
` Got: ${sig}\n` +
` The TAURI_SIGNING_PUBLIC_KEY env var must never be used as the signature value.\n` +
` Ensure the signing step correctly writes the .sig file from the private key.`
);
}
if (sig.length < 80) {
throw new Error(
`${platform}: .sig file "${sigFile}" looks too short (${sig.length} chars) to be a valid signature.`
);
}
}
for (const [platform, filename] of Object.entries(PLATFORM_FILES)) {
const sigFile = `${filename}.sig`;
try {
execSync(
`gh release download "${TAG}" --repo "${REPO}" -p "${sigFile}" --clobber`,
{ stdio: 'pipe' }
);
const signature = fs.readFileSync(sigFile, 'utf8').trim();
validateSignature(signature, platform, sigFile);
const url = `https://github.com/${REPO}/releases/download/${TAG}/${filename}`;
platforms[platform] = { signature, url };
console.log(`${platform}`);
} catch (e) {
console.warn(`⚠ Skipping ${platform}: ${e.message}`);
}
}
if (Object.keys(platforms).length === 0) {
console.error('No platforms found — aborting manifest generation');
process.exit(1);
}
// Pull release notes from GitHub
let notes = '';
try {
const raw = execSync(
`gh release view "${TAG}" --repo "${REPO}" --json body`,
{ stdio: 'pipe' }
).toString();
notes = JSON.parse(raw).body ?? '';
} catch {
console.warn('Could not fetch release notes');
}
const manifest = {
version: VERSION,
notes,
pub_date: new Date().toISOString(),
platforms,
};
fs.writeFileSync('latest.json', JSON.stringify(manifest, null, 2));
console.log(`\nWrote latest.json for v${VERSION} with platforms: ${Object.keys(platforms).join(', ')}`);
+171
View File
@@ -0,0 +1,171 @@
#!/bin/bash
set -e
# Psysonic Auto-Installer
# Automatically detects your OS and installs the latest release from GitHub
REPO="Psychotoxical/psysonic"
APP_NAME="psysonic"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1"
exit 1
}
# Check if running as root
check_root() {
if [ "$EUID" -ne 0 ]; then
error "Please run this script as root (use sudo)"
fi
}
# Detect package manager and OS type
detect_os() {
if command -v apt &> /dev/null; then
OS_TYPE="debian"
PACKAGE_MANAGER="apt"
info "Detected Debian/Ubuntu-based system (apt)"
elif command -v dnf &> /dev/null; then
OS_TYPE="rhel"
PACKAGE_MANAGER="dnf"
info "Detected RHEL/Fedora-based system (dnf)"
elif command -v yum &> /dev/null; then
OS_TYPE="rhel"
PACKAGE_MANAGER="yum"
info "Detected RHEL/CentOS-based system (yum)"
else
error "Unsupported package manager. This installer supports Debian/Ubuntu and RHEL/Fedora/CentOS systems."
fi
}
# Get the latest release download URL for the specific package type
get_download_url() {
local api_url="https://api.github.com/repos/${REPO}/releases/latest"
info "Fetching latest release information..."
local release_info
release_info=$(curl -s "$api_url")
if echo "$release_info" | grep -q "message.*Not Found"; then
error "Could not fetch release information. Please check your internet connection."
fi
local tag_name
tag_name=$(echo "$release_info" | grep -o '"tag_name": *"[^"]*"' | head -1 | cut -d'"' -f4)
if [ -z "$tag_name" ]; then
error "Could not determine latest release version."
fi
info "Latest version: $tag_name"
local download_url=""
if [ "$OS_TYPE" = "debian" ]; then
download_url=$(echo "$release_info" | grep -o '"browser_download_url": *"[^"]*\.deb"' | head -1 | cut -d'"' -f4)
elif [ "$OS_TYPE" = "rhel" ]; then
download_url=$(echo "$release_info" | grep -o '"browser_download_url": *"[^"]*\.rpm"' | head -1 | cut -d'"' -f4)
fi
if [ -z "$download_url" ]; then
error "Could not find download URL for $OS_TYPE package."
fi
echo "$download_url"
}
# Install the package
install_package() {
local download_url="$1"
local temp_dir
temp_dir=$(mktemp -d)
local package_file="$temp_dir/${APP_NAME}_latest"
info "Downloading package..."
if [ "$OS_TYPE" = "debian" ]; then
package_file="${package_file}.deb"
curl -L -o "$package_file" "$download_url"
info "Installing package..."
$PACKAGE_MANAGER install -y "$package_file" || {
warn "Trying to fix broken dependencies..."
$PACKAGE_MANAGER install -f -y
}
elif [ "$OS_TYPE" = "rhel" ]; then
package_file="${package_file}.rpm"
curl -L -o "$package_file" "$download_url"
info "Installing package..."
$PACKAGE_MANAGER install -y "$package_file"
fi
# Cleanup
rm -rf "$temp_dir"
}
# Check if app is already installed
check_installed() {
if command -v $APP_NAME &> /dev/null || command -v ${APP_NAME^} &> /dev/null; then
warn "${APP_NAME} appears to be already installed."
read -p "Do you want to reinstall? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
info "Installation cancelled."
exit 0
fi
fi
}
# Main installation flow
main() {
echo -e "${GREEN}"
echo "╔══════════════════════════════════════════════════════════╗"
echo "║ Psysonic Auto-Installer ║"
echo "║ Install the latest release from GitHub Releases ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo -e "${NC}"
check_root
detect_os
check_installed
local download_url
download_url=$(get_download_url)
if [ -z "$download_url" ]; then
error "Failed to get download URL."
fi
info "Download URL: $download_url"
install_package "$download_url"
echo ""
success "Psysonic has been installed successfully!"
echo -e "${BLUE}You can launch it from your application menu or by running:${NC} psysonic"
echo ""
}
# Run main function
main
+165 -383
View File
@@ -69,15 +69,6 @@ version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "arrayvec"
version = "0.7.6"
@@ -584,6 +575,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cfg_aliases"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chrono"
version = "0.4.44"
@@ -931,17 +928,6 @@ dependencies = [
"syn 1.0.109",
]
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "derive_more"
version = "0.99.20"
@@ -1254,17 +1240,6 @@ dependencies = [
"rustc_version",
]
[[package]]
name = "filetime"
version = "0.2.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db"
dependencies = [
"cfg-if",
"libc",
"libredox",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
@@ -1361,6 +1336,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
@@ -1599,8 +1575,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi 0.11.1+wasi-snapshot-preview1",
"wasm-bindgen",
]
[[package]]
@@ -1610,9 +1588,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 5.3.0",
"wasip2",
"wasm-bindgen",
]
[[package]]
@@ -1794,25 +1774,6 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "h2"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"
dependencies = [
"atomic-waker",
"bytes",
"fnv",
"futures-core",
"futures-sink",
"http",
"indexmap 2.13.0",
"slab",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
@@ -1925,7 +1886,6 @@ dependencies = [
"bytes",
"futures-channel",
"futures-core",
"h2",
"http",
"http-body",
"httparse",
@@ -1951,22 +1911,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
]
[[package]]
name = "hyper-tls"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
dependencies = [
"bytes",
"http-body-util",
"hyper",
"hyper-util",
"native-tls",
"tokio",
"tokio-native-tls",
"tower-service",
"webpki-roots",
]
[[package]]
@@ -1987,11 +1932,9 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"socket2 0.6.3",
"system-configuration",
"tokio",
"tower-service",
"tracing",
"windows-registry",
]
[[package]]
@@ -2441,10 +2384,7 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1744e39d1d6a9948f4f388969627434e31128196de472883b39f148769bfe30a"
dependencies = [
"bitflags 2.11.0",
"libc",
"plain",
"redox_syscall 0.7.3",
]
[[package]]
@@ -2486,6 +2426,12 @@ version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lru-slab"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]]
name = "mac"
version = "0.1.1"
@@ -2593,12 +2539,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "minisign-verify"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -2651,23 +2591,6 @@ dependencies = [
"windows-sys 0.60.2",
]
[[package]]
name = "native-tls"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
dependencies = [
"libc",
"log",
"openssl",
"openssl-probe",
"openssl-sys",
"schannel",
"security-framework",
"security-framework-sys",
"tempfile",
]
[[package]]
name = "ndk"
version = "0.8.0"
@@ -2882,7 +2805,6 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.11.0",
"block2",
"libc",
"objc2",
"objc2-core-foundation",
]
@@ -2898,18 +2820,6 @@ dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-osa-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"
dependencies = [
"bitflags 2.11.0",
"objc2",
"objc2-app-kit",
"objc2-foundation",
]
[[package]]
name = "objc2-quartz-core"
version = "0.3.2"
@@ -2989,50 +2899,6 @@ dependencies = [
"pathdiff",
]
[[package]]
name = "openssl"
version = "0.10.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "951c002c75e16ea2c65b8c7e4d3d51d5530d8dfa7d060b4776828c88cfb18ecf"
dependencies = [
"bitflags 2.11.0",
"cfg-if",
"foreign-types 0.3.2",
"libc",
"once_cell",
"openssl-macros",
"openssl-sys",
]
[[package]]
name = "openssl-macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "openssl-probe"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-sys"
version = "0.9.112"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57d55af3b3e226502be1526dfdba67ab0e9c96fc293004e79576b2b9edb0dbdb"
dependencies = [
"cc",
"libc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -3059,20 +2925,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "osakit"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
dependencies = [
"objc2",
"objc2-foundation",
"objc2-osa-kit",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "pango"
version = "0.18.3"
@@ -3122,7 +2974,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall 0.5.18",
"redox_syscall",
"smallvec",
"windows-link 0.2.1",
]
@@ -3302,12 +3154,6 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "plain"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]]
name = "plist"
version = "1.8.0"
@@ -3493,7 +3339,7 @@ dependencies = [
[[package]]
name = "psysonic"
version = "1.34.0"
version = "1.34.1"
dependencies = [
"biquad",
"discord-rich-presence",
@@ -3515,9 +3361,10 @@ dependencies = [
"tauri-plugin-shell",
"tauri-plugin-single-instance",
"tauri-plugin-store",
"tauri-plugin-updater",
"tauri-plugin-window-state",
"thread-priority",
"tokio",
"url",
]
[[package]]
@@ -3535,6 +3382,61 @@ dependencies = [
"memchr",
]
[[package]]
name = "quinn"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
dependencies = [
"bytes",
"cfg_aliases",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls",
"socket2 0.6.3",
"thiserror 2.0.18",
"tokio",
"tracing",
"web-time",
]
[[package]]
name = "quinn-proto"
version = "0.11.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
dependencies = [
"bytes",
"getrandom 0.3.4",
"lru-slab",
"rand 0.9.2",
"ring",
"rustc-hash",
"rustls",
"rustls-pki-types",
"slab",
"thiserror 2.0.18",
"tinyvec",
"tracing",
"web-time",
]
[[package]]
name = "quinn-udp"
version = "0.5.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2 0.6.3",
"tracing",
"windows-sys 0.60.2",
]
[[package]]
name = "quote"
version = "1.0.45"
@@ -3581,6 +3483,16 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "rand"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.5",
]
[[package]]
name = "rand_chacha"
version = "0.2.2"
@@ -3601,6 +3513,16 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.5",
]
[[package]]
name = "rand_core"
version = "0.5.1"
@@ -3619,6 +3541,15 @@ dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "rand_hc"
version = "0.2.0"
@@ -3652,15 +3583,6 @@ dependencies = [
"bitflags 2.11.0",
]
[[package]]
name = "redox_syscall"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce70a74e890531977d37e532c34d45e9055d2409ed08ddba14529471ed0be16"
dependencies = [
"bitflags 2.11.0",
]
[[package]]
name = "redox_users"
version = "0.5.2"
@@ -3729,31 +3651,29 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64 0.22.1",
"bytes",
"encoding_rs",
"futures-channel",
"futures-core",
"futures-util",
"h2",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-tls",
"hyper-util",
"js-sys",
"log",
"mime",
"mime_guess",
"native-tls",
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls",
"rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
@@ -3763,6 +3683,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams 0.4.2",
"web-sys",
"webpki-roots",
]
[[package]]
@@ -3779,20 +3700,15 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
"rustls",
"rustls-pki-types",
"rustls-platform-verifier",
"serde",
"serde_json",
"sync_wrapper",
"tokio",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
@@ -3931,54 +3847,16 @@ dependencies = [
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
dependencies = [
"web-time",
"zeroize",
]
[[package]]
name = "rustls-platform-verifier"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
"jni",
"log",
"once_cell",
"rustls",
"rustls-native-certs",
"rustls-platform-verifier-android",
"rustls-webpki",
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls-platform-verifier-android"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.9"
@@ -4011,15 +3889,6 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "schannel"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "schemars"
version = "0.8.22"
@@ -4077,29 +3946,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.11.0",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "selectors"
version = "0.24.0"
@@ -4433,7 +4279,7 @@ dependencies = [
"objc2-foundation",
"objc2-quartz-core",
"raw-window-handle",
"redox_syscall 0.5.18",
"redox_syscall",
"tracing",
"wasm-bindgen",
"web-sys",
@@ -4556,6 +4402,7 @@ dependencies = [
"symphonia-bundle-mp3",
"symphonia-codec-aac",
"symphonia-codec-adpcm",
"symphonia-codec-alac",
"symphonia-codec-pcm",
"symphonia-codec-vorbis",
"symphonia-core",
@@ -4610,6 +4457,16 @@ dependencies = [
"symphonia-core",
]
[[package]]
name = "symphonia-codec-alac"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8413fa754942ac16a73634c9dfd1500ed5c61430956b33728567f667fdd393ab"
dependencies = [
"log",
"symphonia-core",
]
[[package]]
name = "symphonia-codec-pcm"
version = "0.5.5"
@@ -4745,27 +4602,6 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "system-configuration"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
dependencies = [
"bitflags 2.11.0",
"core-foundation 0.9.4",
"system-configuration-sys",
]
[[package]]
name = "system-configuration-sys"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "system-deps"
version = "6.2.2"
@@ -4828,17 +4664,6 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "tar"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22692a6476a21fa75fdfc11d452fda482af402c008cdbaf3476414e122040973"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]]
name = "target-lexicon"
version = "0.12.16"
@@ -5094,39 +4919,6 @@ dependencies = [
"tracing",
]
[[package]]
name = "tauri-plugin-updater"
version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fe8e9bebd88fc222938ffdfbdcfa0307081423bd01e3252fc337d8bde81fc61"
dependencies = [
"base64 0.22.1",
"dirs",
"flate2",
"futures-util",
"http",
"infer",
"log",
"minisign-verify",
"osakit",
"percent-encoding",
"reqwest 0.13.2",
"rustls",
"semver",
"serde",
"serde_json",
"tar",
"tauri",
"tauri-plugin",
"tempfile",
"thiserror 2.0.18",
"time",
"tokio",
"url",
"windows-sys 0.60.2",
"zip",
]
[[package]]
name = "tauri-plugin-window-state"
version = "2.4.1"
@@ -5306,6 +5098,20 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "thread-priority"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe075d7053dae61ac5413a34ea7d4913b6e6207844fd726bdd858b37ff72bf5"
dependencies = [
"bitflags 2.11.0",
"cfg-if",
"libc",
"log",
"rustversion",
"winapi",
]
[[package]]
name = "time"
version = "0.3.45"
@@ -5347,6 +5153,21 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.50.0"
@@ -5373,16 +5194,6 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "tokio-native-tls"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
dependencies = [
"native-tls",
"tokio",
]
[[package]]
name = "tokio-rustls"
version = "0.26.4"
@@ -5767,12 +5578,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version-compare"
version = "0.2.1"
@@ -5989,6 +5794,16 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "web-time"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "webkit2gtk"
version = "2.0.2"
@@ -6034,10 +5849,10 @@ dependencies = [
]
[[package]]
name = "webpki-root-certs"
name = "webpki-roots"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "804f18a4ac2676ffb4e8b5b5fa9ae38af06df08162314f96a68d2a363e21a8ca"
checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed"
dependencies = [
"rustls-pki-types",
]
@@ -6256,17 +6071,6 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-registry"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-result"
version = "0.1.2"
@@ -6832,16 +6636,6 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix 1.1.4",
]
[[package]]
name = "xdg-home"
version = "1.3.0"
@@ -7088,18 +6882,6 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "zip"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
dependencies = [
"arbitrary",
"crc32fast",
"indexmap 2.13.0",
"memchr",
]
[[package]]
name = "zmij"
version = "1.0.21"
+5 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "psysonic"
version = "1.34.0"
version = "1.34.2"
description = "Psysonic Desktop Music Player"
authors = []
license = ""
@@ -31,15 +31,16 @@ tauri-plugin-fs = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
rodio = { version = "0.19", default-features = false, features = ["symphonia-all"] }
symphonia = { version = "0.5", default-features = false, features = ["flac", "mp3", "pcm", "aac", "isomp4", "vorbis", "ogg", "wav", "adpcm"] }
reqwest = { version = "0.12", features = ["stream", "json", "multipart"] }
symphonia = { version = "0.5", default-features = false, features = ["flac", "mp3", "pcm", "aac", "alac", "isomp4", "vorbis", "ogg", "wav", "adpcm"] }
reqwest = { version = "0.12", default-features = false, features = ["stream", "json", "multipart", "rustls-tls", "blocking"] }
futures-util = "0.3"
md5 = "0.7"
tokio = { version = "1", features = ["rt", "time"] }
biquad = "0.4"
ringbuf = "0.3"
tauri-plugin-window-state = "2.4.1"
tauri-plugin-updater = "2"
tauri-plugin-process = "2"
souvlaki = { version = "0.8", default-features = false, features = ["use_zbus"] }
discord-rich-presence = "0.2"
url = "2"
thread-priority = "1"
-1
View File
@@ -34,7 +34,6 @@
"core:window:allow-is-fullscreen",
"core:window:allow-create",
"core:webview:allow-create-webview-window",
"updater:default",
"process:allow-restart"
]
}
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1 +1 @@
{"default":{"identifier":"default","description":"Default capabilities for Psysonic","local":true,"windows":["main"],"permissions":["core:default","shell:default",{"identifier":"shell:allow-open","allow":[{"url":"https://**"}]},"global-shortcut:allow-register","global-shortcut:allow-unregister","store:default","store:allow-load","store:allow-set","store:allow-get","store:allow-save","dialog:default","dialog:allow-open","dialog:allow-save","fs:default","fs:allow-write-file","fs:allow-read-file","fs:allow-mkdir","fs:scope-download-recursive","fs:scope-home-recursive","window-state:allow-save-window-state","window-state:allow-restore-state","core:window:allow-set-title","core:window:allow-close","core:window:allow-hide","core:window:allow-show","core:window:allow-set-fullscreen","core:window:allow-is-fullscreen","core:window:allow-create","core:webview:allow-create-webview-window","updater:default","process:allow-restart"],"platforms":["linux","macOS","windows"]}}
{"default":{"identifier":"default","description":"Default capabilities for Psysonic","local":true,"windows":["main"],"permissions":["core:default","shell:default",{"identifier":"shell:allow-open","allow":[{"url":"https://**"}]},"global-shortcut:allow-register","global-shortcut:allow-unregister","store:default","store:allow-load","store:allow-set","store:allow-get","store:allow-save","dialog:default","dialog:allow-open","dialog:allow-save","fs:default","fs:allow-write-file","fs:allow-read-file","fs:allow-mkdir","fs:scope-download-recursive","fs:scope-home-recursive","window-state:allow-save-window-state","window-state:allow-restore-state","core:window:allow-set-title","core:window:allow-close","core:window:allow-hide","core:window:allow-show","core:window:allow-set-fullscreen","core:window:allow-is-fullscreen","core:window:allow-create","core:webview:allow-create-webview-window","process:allow-restart"],"platforms":["linux","macOS","windows"]}}
-54
View File
@@ -6284,60 +6284,6 @@
"const": "store:deny-values",
"markdownDescription": "Denies the values command without any pre-configured scope."
},
{
"description": "This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n\n#### This default permission set includes:\n\n- `allow-check`\n- `allow-download`\n- `allow-install`\n- `allow-download-and-install`",
"type": "string",
"const": "updater:default",
"markdownDescription": "This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n\n#### This default permission set includes:\n\n- `allow-check`\n- `allow-download`\n- `allow-install`\n- `allow-download-and-install`"
},
{
"description": "Enables the check command without any pre-configured scope.",
"type": "string",
"const": "updater:allow-check",
"markdownDescription": "Enables the check command without any pre-configured scope."
},
{
"description": "Enables the download command without any pre-configured scope.",
"type": "string",
"const": "updater:allow-download",
"markdownDescription": "Enables the download command without any pre-configured scope."
},
{
"description": "Enables the download_and_install command without any pre-configured scope.",
"type": "string",
"const": "updater:allow-download-and-install",
"markdownDescription": "Enables the download_and_install command without any pre-configured scope."
},
{
"description": "Enables the install command without any pre-configured scope.",
"type": "string",
"const": "updater:allow-install",
"markdownDescription": "Enables the install command without any pre-configured scope."
},
{
"description": "Denies the check command without any pre-configured scope.",
"type": "string",
"const": "updater:deny-check",
"markdownDescription": "Denies the check command without any pre-configured scope."
},
{
"description": "Denies the download command without any pre-configured scope.",
"type": "string",
"const": "updater:deny-download",
"markdownDescription": "Denies the download command without any pre-configured scope."
},
{
"description": "Denies the download_and_install command without any pre-configured scope.",
"type": "string",
"const": "updater:deny-download-and-install",
"markdownDescription": "Denies the download_and_install command without any pre-configured scope."
},
{
"description": "Denies the install command without any pre-configured scope.",
"type": "string",
"const": "updater:deny-install",
"markdownDescription": "Denies the install command without any pre-configured scope."
},
{
"description": "This permission set configures what kind of\noperations are available from the window state plugin.\n\n#### Granted Permissions\n\nAll operations are enabled by default.\n\n\n#### This default permission set includes:\n\n- `allow-filename`\n- `allow-restore-state`\n- `allow-save-window-state`",
"type": "string",
-54
View File
@@ -6284,60 +6284,6 @@
"const": "store:deny-values",
"markdownDescription": "Denies the values command without any pre-configured scope."
},
{
"description": "This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n\n#### This default permission set includes:\n\n- `allow-check`\n- `allow-download`\n- `allow-install`\n- `allow-download-and-install`",
"type": "string",
"const": "updater:default",
"markdownDescription": "This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n\n#### This default permission set includes:\n\n- `allow-check`\n- `allow-download`\n- `allow-install`\n- `allow-download-and-install`"
},
{
"description": "Enables the check command without any pre-configured scope.",
"type": "string",
"const": "updater:allow-check",
"markdownDescription": "Enables the check command without any pre-configured scope."
},
{
"description": "Enables the download command without any pre-configured scope.",
"type": "string",
"const": "updater:allow-download",
"markdownDescription": "Enables the download command without any pre-configured scope."
},
{
"description": "Enables the download_and_install command without any pre-configured scope.",
"type": "string",
"const": "updater:allow-download-and-install",
"markdownDescription": "Enables the download_and_install command without any pre-configured scope."
},
{
"description": "Enables the install command without any pre-configured scope.",
"type": "string",
"const": "updater:allow-install",
"markdownDescription": "Enables the install command without any pre-configured scope."
},
{
"description": "Denies the check command without any pre-configured scope.",
"type": "string",
"const": "updater:deny-check",
"markdownDescription": "Denies the check command without any pre-configured scope."
},
{
"description": "Denies the download command without any pre-configured scope.",
"type": "string",
"const": "updater:deny-download",
"markdownDescription": "Denies the download command without any pre-configured scope."
},
{
"description": "Denies the download_and_install command without any pre-configured scope.",
"type": "string",
"const": "updater:deny-download-and-install",
"markdownDescription": "Denies the download_and_install command without any pre-configured scope."
},
{
"description": "Denies the install command without any pre-configured scope.",
"type": "string",
"const": "updater:deny-install",
"markdownDescription": "Denies the install command without any pre-configured scope."
},
{
"description": "This permission set configures what kind of\noperations are available from the window state plugin.\n\n#### Granted Permissions\n\nAll operations are enabled by default.\n\n\n#### This default permission set includes:\n\n- `allow-filename`\n- `allow-restore-state`\n- `allow-save-window-state`",
"type": "string",
+332 -40
View File
@@ -13,7 +13,7 @@ use symphonia::core::{
audio::{AudioBufferRef, SampleBuffer, SignalSpec},
codecs::{DecoderOptions, CODEC_TYPE_NULL},
formats::{FormatOptions, FormatReader, SeekMode, SeekTo},
io::{MediaSource, MediaSourceStream},
io::{MediaSource, MediaSourceStream, MediaSourceStreamOptions},
meta::MetadataOptions,
probe::Hint,
units::{self, Time},
@@ -902,15 +902,20 @@ struct SizedDecoder {
}
impl SizedDecoder {
fn new(data: Vec<u8>, format_hint: Option<&str>) -> Result<Self, String> {
fn new(data: Vec<u8>, format_hint: Option<&str>, hi_res: bool) -> Result<Self, String> {
let data_len = data.len() as u64;
let source = SizedCursorSource {
inner: Cursor::new(data),
len: data_len,
};
// Hi-Res: 4 MB read-ahead so Symphonia demuxes fewer Read calls for
// high-bitrate files (88.2 kHz/24-bit FLAC ≈ 1800 kbps).
// Standard: 512 KB is plenty for MP3/AAC — larger buffers waste allocation
// and compete with the playback thread at track start.
let buf_len = if hi_res { 4 * 1024 * 1024 } else { 512 * 1024 };
let mss = MediaSourceStream::new(
Box::new(source) as Box<dyn MediaSource>,
Default::default(),
MediaSourceStreamOptions { buffer_len: buf_len },
);
let mut hint = Hint::new();
@@ -996,7 +1001,9 @@ impl SizedDecoder {
/// Uses `enable_gapless: false` — live streams are not seekable; gapless
/// trimming requires seeking to read the LAME/iTunSMPB end-padding info.
fn new_streaming(media: Box<dyn MediaSource>, format_hint: Option<&str>) -> Result<Self, String> {
let mss = MediaSourceStream::new(media, Default::default());
// Larger read-ahead buffer for the live radio SPSC consumer — reduces
// read() call frequency into the ring buffer, easing I/O spikes.
let mss = MediaSourceStream::new(media, MediaSourceStreamOptions { buffer_len: 512 * 1024 });
let mut hint = Hint::new();
if let Some(ext) = format_hint { hint.with_extension(ext); }
let format_opts = FormatOptions { enable_gapless: false, ..Default::default() };
@@ -1254,10 +1261,11 @@ fn build_source(
sample_counter: Arc<AtomicU64>,
target_rate: u32,
format_hint: Option<&str>,
hi_res: bool,
) -> Result<BuiltSource, String> {
let gapless = parse_gapless_info(&data);
let decoder = SizedDecoder::new(data, format_hint)?;
let decoder = SizedDecoder::new(data, format_hint, hi_res)?;
let sample_rate = decoder.sample_rate();
let channels = decoder.channels();
@@ -1336,6 +1344,9 @@ pub(crate) struct PreloadedTrack {
pub(crate) struct ChainedInfo {
/// The URL that was chained — used by audio_play to detect a pre-chain hit.
url: String,
/// Raw file bytes (shared with the chained decoder). Lets manual skip reuse
/// them instead of re-downloading after dropping the Sink queue.
raw_bytes: Arc<Vec<u8>>,
duration_secs: f64,
replay_gain_linear: f32,
base_volume: f32,
@@ -1347,7 +1358,15 @@ pub(crate) struct ChainedInfo {
}
pub struct AudioEngine {
pub stream_handle: Arc<rodio::OutputStreamHandle>,
pub stream_handle: Arc<std::sync::Mutex<rodio::OutputStreamHandle>>,
/// Sample rate the output stream was last opened at (updated on every re-open).
pub stream_sample_rate: Arc<AtomicU32>,
/// The rate the device was opened at on cold start — used to restore the
/// stream when Hi-Res is toggled off while a hi-res rate is active.
pub device_default_rate: u32,
/// Sends `(desired_rate, is_hi_res, reply_tx)` to the audio-stream thread to
/// re-open the output device. `is_hi_res` controls thread-priority escalation.
pub stream_reopen_tx: std::sync::mpsc::SyncSender<(u32, bool, std::sync::mpsc::SyncSender<rodio::OutputStreamHandle>)>,
pub current: Arc<Mutex<AudioCurrent>>,
/// Monotonically incremented on each audio_play (non-chain) / audio_stop call.
pub generation: Arc<AtomicU64>,
@@ -1408,25 +1427,90 @@ impl AudioCurrent {
}
}
pub fn create_engine() -> (AudioEngine, std::thread::JoinHandle<()>) {
let (tx, rx) = std::sync::mpsc::sync_channel::<rodio::OutputStreamHandle>(0);
/// Open the system default output device at `desired_rate` Hz (0 = device default).
///
/// Resolution order:
/// 1. Exact rate match in the device's supported config ranges.
/// 2. Highest available rate (for hardware that doesn't support the source rate).
/// 3. Device default.
/// 4. System default (last resort).
///
/// Returns `(OutputStream, OutputStreamHandle, actual_sample_rate)`.
fn open_stream_for_rate(desired_rate: u32) -> (rodio::OutputStream, rodio::OutputStreamHandle, u32) {
use rodio::cpal::traits::{DeviceTrait, HostTrait};
// Request a larger audio buffer from PipeWire/PulseAudio to reduce ALSA underruns.
// Only set if the user hasn't already configured these themselves.
// PIPEWIRE_LATENCY: 4096 frames / 48000 Hz ≈ 85 ms — enough to absorb scheduler jitter.
#[cfg(target_os = "linux")]
{
if std::env::var("PIPEWIRE_LATENCY").is_err() {
std::env::set_var("PIPEWIRE_LATENCY", "4096/48000");
let host = rodio::cpal::default_host();
if let Some(device) = host.default_output_device() {
if desired_rate > 0 {
if let Ok(supported) = device.supported_output_configs() {
let configs: Vec<_> = supported.collect();
// 1. Exact rate match — prefer more channels (stereo > mono).
let exact = configs.iter()
.filter(|c| {
c.min_sample_rate().0 <= desired_rate
&& desired_rate <= c.max_sample_rate().0
})
.max_by_key(|c| c.channels());
if let Some(cfg) = exact {
let config = cfg.clone()
.with_sample_rate(rodio::cpal::SampleRate(desired_rate));
if let Ok((stream, handle)) =
rodio::OutputStream::try_from_device_config(&device, config)
{
eprintln!("[psysonic] audio stream opened at {} Hz (exact)", desired_rate);
return (stream, handle, desired_rate);
}
}
// 2. No exact match — use the highest supported rate.
let best = configs.iter()
.max_by_key(|c| c.max_sample_rate().0);
if let Some(cfg) = best {
let rate = cfg.max_sample_rate().0;
let config = cfg.clone()
.with_sample_rate(rodio::cpal::SampleRate(rate));
if let Ok((stream, handle)) =
rodio::OutputStream::try_from_device_config(&device, config)
{
eprintln!(
"[psysonic] audio stream opened at {} Hz (highest, wanted {})",
rate, desired_rate
);
return (stream, handle, rate);
}
}
}
}
if std::env::var("PULSE_LATENCY_MSEC").is_err() {
std::env::set_var("PULSE_LATENCY_MSEC", "85");
// 3. Device default.
if let Ok((stream, handle)) = rodio::OutputStream::try_from_device(&device) {
let rate = device
.default_output_config()
.map(|c| c.sample_rate().0)
.unwrap_or(44100);
eprintln!("[psysonic] audio stream opened at {} Hz (device default)", rate);
return (stream, handle, rate);
}
}
// 4. Last resort: system default.
eprintln!("[psysonic] audio stream falling back to system default");
let (stream, handle) = rodio::OutputStream::try_default()
.expect("cannot open any audio output device");
let rate = rodio::cpal::default_host()
.default_output_device()
.and_then(|d| d.default_output_config().ok())
.map(|c| c.sample_rate().0)
.unwrap_or(44100);
(stream, handle, rate)
}
pub fn create_engine() -> (AudioEngine, std::thread::JoinHandle<()>) {
// macOS: request a smaller CoreAudio buffer to reduce output latency.
// Smaller buffers = lower latency between decoded samples and DAC output,
// which tightens the gap between actual audio and UI event delivery.
#[cfg(target_os = "macos")]
{
if std::env::var("COREAUDIO_BUFFER_SIZE").is_err() {
@@ -1434,21 +1518,75 @@ pub fn create_engine() -> (AudioEngine, std::thread::JoinHandle<()>) {
}
}
// Channels: main thread ←→ audio-stream thread.
// init_tx/rx : (OutputStreamHandle, actual_rate) sent once at startup.
// reopen_tx/rx: (desired_rate, reply_tx) — triggers a stream re-open.
let (init_tx, init_rx) =
std::sync::mpsc::sync_channel::<(rodio::OutputStreamHandle, u32)>(0);
let (reopen_tx, reopen_rx) =
std::sync::mpsc::sync_channel::<(u32, bool, std::sync::mpsc::SyncSender<rodio::OutputStreamHandle>)>(4);
let thread = std::thread::Builder::new()
.name("psysonic-audio-stream".into())
.spawn(move || match rodio::OutputStream::try_default() {
Ok((_stream, handle)) => {
tx.send(handle).ok();
loop { std::thread::park(); }
.spawn(move || {
// Set PipeWire / PulseAudio latency hints before the first open.
#[cfg(target_os = "linux")]
{
if std::env::var("PIPEWIRE_LATENCY").is_err() {
std::env::set_var("PIPEWIRE_LATENCY", "4096/48000");
}
if std::env::var("PULSE_LATENCY_MSEC").is_err() {
std::env::set_var("PULSE_LATENCY_MSEC", "85");
}
}
// Thread priority is kept at default during standard-mode playback.
// It is escalated to Max only when a Hi-Res stream reopen is requested,
// to prevent PipeWire underruns at high quantum sizes (8192 frames).
let (mut _stream, handle, rate) = open_stream_for_rate(0);
init_tx.send((handle, rate)).ok();
// Keep the stream alive and handle sample-rate switch requests.
while let Ok((desired_rate, is_hi_res, reply_tx)) = reopen_rx.recv() {
// Escalate to Max for Hi-Res reopens (large PipeWire quanta need
// real-time scheduling to avoid underruns). No escalation for
// standard mode — the thread blocks on recv() between reopens so
// elevated priority would only waste scheduler budget.
if is_hi_res {
thread_priority::set_current_thread_priority(
thread_priority::ThreadPriority::Max
).ok();
}
drop(_stream); // close old stream before opening new one
// Scale the PipeWire quantum with the sample rate so wall-clock
// latency stays roughly constant (≈93 ms) at all rates.
// 8192 frames at 88200 Hz ≈ 92.9 ms (same as 4096 at 48000 Hz).
#[cfg(target_os = "linux")]
{
let frames: u32 = if desired_rate > 48_000 { 8192 } else { 4096 };
std::env::set_var("PIPEWIRE_LATENCY", format!("{frames}/{desired_rate}"));
// Keep PULSE_LATENCY_MSEC in sync so PulseAudio-based setups
// get the same wall-clock quantum as PipeWire.
let latency_ms = (frames as f64 / desired_rate as f64 * 1000.0).round() as u64;
std::env::set_var("PULSE_LATENCY_MSEC", latency_ms.to_string());
}
let (new_stream, new_handle, _actual) = open_stream_for_rate(desired_rate);
_stream = new_stream;
reply_tx.send(new_handle).ok();
}
Err(e) => { eprintln!("[psysonic] audio output error: {e}"); }
})
.expect("spawn audio stream thread");
let stream_handle = rx.recv().expect("audio stream handle");
let (initial_handle, initial_rate) = init_rx.recv().expect("audio stream handle");
let engine = AudioEngine {
stream_handle: Arc::new(stream_handle),
stream_handle: Arc::new(std::sync::Mutex::new(initial_handle)),
stream_sample_rate: Arc::new(AtomicU32::new(initial_rate)),
device_default_rate: initial_rate,
stream_reopen_tx: reopen_tx,
current: Arc::new(Mutex::new(AudioCurrent {
sink: None,
duration_secs: 0.0,
@@ -1463,6 +1601,7 @@ pub fn create_engine() -> (AudioEngine, std::thread::JoinHandle<()>) {
generation: Arc::new(AtomicU64::new(0)),
http_client: reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.use_rustls_tls()
.build()
.unwrap_or_default(),
eq_gains: Arc::new(std::array::from_fn(|_| AtomicU32::new(0f32.to_bits()))),
@@ -1494,6 +1633,32 @@ pub struct ProgressPayload {
// ─── Helpers ──────────────────────────────────────────────────────────────────
/// Subsonic `buildStreamUrl()` uses a fresh random salt on every call, so two
/// URLs for the same track differ in `t`/`s` query params. Compare a stable key.
fn playback_identity(url: &str) -> Option<String> {
if let Some(path) = url.strip_prefix("psysonic-local://") {
return Some(format!("local:{path}"));
}
if !url.contains("stream.view") {
return None;
}
let q = url.split('?').nth(1)?;
for pair in q.split('&') {
if let Some(v) = pair.strip_prefix("id=") {
let v = v.split('&').next().unwrap_or(v);
return Some(format!("stream:{v}"));
}
}
None
}
fn same_playback_target(a_url: &str, b_url: &str) -> bool {
match (playback_identity(a_url), playback_identity(b_url)) {
(Some(a), Some(b)) => a == b,
_ => a_url == b_url,
}
}
/// Fetch track bytes from the preload cache or via HTTP.
async fn fetch_data(
url: &str,
@@ -1504,7 +1669,7 @@ async fn fetch_data(
// Check preload cache first.
let cached = {
let mut preloaded = state.preloaded.lock().unwrap();
if preloaded.as_ref().map(|p| p.url == url).unwrap_or(false) {
if preloaded.as_ref().is_some_and(|p| same_playback_target(&p.url, url)) {
preloaded.take().map(|p| p.data)
} else {
None
@@ -1575,6 +1740,7 @@ pub async fn audio_play(
replay_gain_db: Option<f32>,
replay_gain_peak: Option<f32>,
manual: bool, // true = user-initiated skip → bypass crossfade, start immediately
hi_res_enabled: bool, // false = safe 44.1 kHz mode; true = native rate (alpha)
app: AppHandle,
state: State<'_, AudioEngine>,
) -> Result<(), String> {
@@ -1602,10 +1768,14 @@ pub async fn audio_play(
// audio_chain_preload already appended this URL to the Sink 30 s in
// advance. The source is live in the queue — just return and let the
// progress task handle the state transition when the previous source ends.
if gapless {
//
// Never for manual skips: the UI already jumped to this track in JS, but
// the current source is still playing until the chain drains. User-initiated
// play must clear the chain and start this URL immediately (standard path).
if gapless && !manual {
let already_chained = state.chained_info.lock().unwrap()
.as_ref()
.map(|c| c.url == url)
.map(|c| same_playback_target(&c.url, &url))
.unwrap_or(false);
if already_chained {
return Ok(());
@@ -1616,18 +1786,40 @@ pub async fn audio_play(
// Used for: manual skip, gapless OFF, first play, or gapless when the
// proactive chain was not set up in time.
// Bump generation first so the old progress task stops before we peel
// chained_info (avoids a race where it sees current_done + empty chain).
let gen = state.generation.fetch_add(1, Ordering::SeqCst) + 1;
// Cancel any pending chain (manual skip while gapless chain was set up).
*state.chained_info.lock().unwrap() = None;
// Manual skip onto the gapless-pre-chained track: reuse raw bytes (no HTTP;
// preload cache was already consumed when the chain was built). Otherwise
// clear any stale chain metadata.
let reuse_chained_bytes: Option<Vec<u8>> = if gapless && manual {
let mut ci = state.chained_info.lock().unwrap();
if ci.as_ref().is_some_and(|c| same_playback_target(&c.url, &url)) {
ci.take().map(|info| {
Arc::try_unwrap(info.raw_bytes).unwrap_or_else(|a| (*a).clone())
})
} else {
*ci = None;
None
}
} else {
*state.chained_info.lock().unwrap() = None;
None
};
// Stop fading-out sink from previous crossfade.
if let Some(old) = state.fading_out_sink.lock().unwrap().take() {
old.stop();
}
// Fetch bytes (may use preload cache).
let data = match fetch_data(&url, &state, gen, &app).await? {
// Fetch bytes (preload cache) unless we reused the chained download above.
let data = if let Some(d) = reuse_chained_bytes {
Some(d)
} else {
fetch_data(&url, &state, gen, &app).await?
};
let data = match data {
Some(d) => d,
None => return Ok(()), // superseded while downloading
};
@@ -1687,6 +1879,7 @@ pub async fn audio_play(
state.samples_played.clone(),
target_rate,
format_hint.as_deref(),
hi_res_enabled,
).map_err(|e| { app.emit("audio:error", &e).ok(); e })?;
let source = built.source;
let duration_secs = built.duration_secs;
@@ -1701,9 +1894,63 @@ pub async fn audio_play(
return Ok(());
}
let sink = Sink::try_new(&*state.stream_handle).map_err(|e| e.to_string())?;
// ── Stream rate management ────────────────────────────────────────────────
// Hi-Res ON: open device at file's native rate (bit-perfect, no resampler).
// Hi-Res OFF: if the stream was previously opened at a hi-res rate (e.g. the
// toggle was just turned off mid-session), restore the device
// default rate so playback is no longer at 88.2/96 kHz etc.
// If already at the device default — skip entirely (no IPC, no
// PipeWire reconfigure, no scheduler cost).
{
let current_stream_rate = state.stream_sample_rate.load(Ordering::Relaxed);
let target_rate = if hi_res_enabled {
output_rate // native file rate
} else {
state.device_default_rate // restore device default
};
let needs_switch = target_rate > 0 && target_rate != current_stream_rate;
if needs_switch {
let (reply_tx, reply_rx) = std::sync::mpsc::sync_channel::<rodio::OutputStreamHandle>(0);
if state.stream_reopen_tx.send((target_rate, hi_res_enabled, reply_tx)).is_ok() {
match reply_rx.recv_timeout(std::time::Duration::from_secs(5)) {
Ok(new_handle) => {
*state.stream_handle.lock().unwrap() = new_handle;
state.stream_sample_rate.store(target_rate, Ordering::Relaxed);
// Give PipeWire time to reconfigure at the new rate before
// we open a Sink — only needed for large hi-res quanta.
if hi_res_enabled && target_rate > 48_000 {
tokio::time::sleep(Duration::from_millis(150)).await;
}
}
Err(_) => {
eprintln!("[psysonic] stream rate switch timed out, keeping {current_stream_rate} Hz");
}
}
}
}
// Re-check gen: a rapid skip during the settle sleep would have bumped it.
if state.generation.load(Ordering::SeqCst) != gen {
return Ok(());
}
}
let sink = Sink::try_new(&*state.stream_handle.lock().unwrap()).map_err(|e| e.to_string())?;
sink.set_volume(effective_volume);
// ── Sink pre-fill for hi-res tracks ──────────────────────────────────────
// At sample rates > 48 kHz the hardware quantum is larger and the first
// period demands more decoded frames than at 44.1/48 kHz.
// Strategy: pause the sink before appending so rodio's internal mixer
// decodes into its ring buffer ahead of the hardware. After a short delay
// we resume — the buffer is already full and the hardware gets its frames
// without an underrun on the very first period.
// Standard mode: no pre-fill needed — default 44.1/48 kHz quantum is small.
let needs_prefill = hi_res_enabled && output_rate > 48_000;
if needs_prefill {
sink.pause();
}
// Gapless OFF: prepend a short silence so tracks are clearly separated.
// Only when this is an auto-advance (near end), not on manual skip.
if !gapless {
@@ -1727,6 +1974,19 @@ pub async fn audio_play(
sink.append(source);
if needs_prefill {
// 500 ms lets rodio decode several seconds of hi-res audio into its
// internal buffer while the sink is paused. The hardware sees no gap
// because the output is held — it only starts draining after sink.play().
// 500 ms gives ~5 quanta of headroom at 8192-frame/88200 Hz quantum size,
// absorbing scheduler jitter and PipeWire graph wake-up latency.
tokio::time::sleep(Duration::from_millis(500)).await;
if state.generation.load(Ordering::SeqCst) != gen {
return Ok(()); // skipped during pre-fill — abort silently
}
sink.play();
}
// Atomically swap sinks — extract old sink + its fade-out trigger.
let (old_sink, old_fadeout_trigger, old_fadeout_samples) = {
let mut cur = state.current.lock().unwrap();
@@ -1813,12 +2073,13 @@ pub async fn audio_chain_preload(
duration_hint: f64,
replay_gain_db: Option<f32>,
replay_gain_peak: Option<f32>,
hi_res_enabled: bool,
state: State<'_, AudioEngine>,
) -> Result<(), String> {
// Idempotent: already chained this URL → nothing to do.
// Idempotent: already chained this track → nothing to do.
{
let chained = state.chained_info.lock().unwrap();
if chained.as_ref().map(|c| c.url == url).unwrap_or(false) {
if chained.as_ref().is_some_and(|c| same_playback_target(&c.url, &url)) {
return Ok(());
}
}
@@ -1834,7 +2095,7 @@ pub async fn audio_chain_preload(
let data: Vec<u8> = {
let cached = {
let mut preloaded = state.preloaded.lock().unwrap();
if preloaded.as_ref().map(|p| p.url == url).unwrap_or(false) {
if preloaded.as_ref().is_some_and(|p| same_playback_target(&p.url, &url)) {
preloaded.take().map(|p| p.data)
} else {
None
@@ -1870,6 +2131,8 @@ pub async fn audio_chain_preload(
return Ok(());
}
let raw_bytes = Arc::new(data);
let (gain_linear, effective_volume) = compute_gain(replay_gain_db, replay_gain_peak, volume);
let done_next = Arc::new(AtomicBool::new(false));
@@ -1882,7 +2145,7 @@ pub async fn audio_chain_preload(
.and_then(|ext| ext.split('?').next())
.map(|s| s.to_lowercase());
let built = build_source(
data,
(*raw_bytes).clone(),
duration_hint,
state.eq_gains.clone(),
state.eq_enabled.clone(),
@@ -1892,6 +2155,7 @@ pub async fn audio_chain_preload(
chain_counter.clone(),
target_rate,
format_hint.as_deref(),
hi_res_enabled,
).map_err(|e| e.to_string())?;
let source = built.source;
let duration_secs = built.duration_secs;
@@ -1901,6 +2165,25 @@ pub async fn audio_chain_preload(
return Ok(());
}
// In hi-res mode: if the next track's native rate differs from the current
// output stream, we cannot chain gaplessly — audio_play will do a hard cut
// with a stream re-open. Store raw bytes to avoid re-downloading.
// In safe mode (44.1 kHz locked): the stream rate is always 44100, so the
// chain proceeds and rodio resamples internally — no bail needed.
let next_rate = if hi_res_enabled { built.output_rate } else { 44_100 };
let stream_rate = state.stream_sample_rate.load(Ordering::Relaxed);
if hi_res_enabled && stream_rate > 0 && next_rate != stream_rate {
eprintln!(
"[psysonic] gapless chain skipped: next track rate {} Hz ≠ stream {} Hz",
next_rate, stream_rate
);
*state.preloaded.lock().unwrap() = Some(PreloadedTrack {
url,
data: Arc::try_unwrap(raw_bytes).unwrap_or_else(|a| (*a).clone()),
});
return Ok(());
}
// Append to the existing Sink. The audio hardware stream never stalls.
{
let cur = state.current.lock().unwrap();
@@ -1915,6 +2198,7 @@ pub async fn audio_chain_preload(
*state.chained_info.lock().unwrap() = Some(ChainedInfo {
url,
raw_bytes,
duration_secs,
replay_gain_linear: gain_linear,
base_volume: volume.clamp(0.0, 1.0),
@@ -2303,10 +2587,18 @@ pub async fn audio_preload(
) -> Result<(), String> {
{
let preloaded = state.preloaded.lock().unwrap();
if preloaded.as_ref().map(|p| p.url == url).unwrap_or(false) {
if preloaded.as_ref().is_some_and(|p| same_playback_target(&p.url, &url)) {
return Ok(());
}
}
// Throttle: wait 8 s before starting the background download so it does not
// compete with the decode + sink-feed work of the just-started current track.
// If the user skips during the wait the generation counter changes and we abort.
let gen_snapshot = state.generation.load(Ordering::Relaxed);
tokio::time::sleep(Duration::from_secs(8)).await;
if state.generation.load(Ordering::Relaxed) != gen_snapshot {
return Ok(());
}
let data: Vec<u8> = if let Some(path) = url.strip_prefix("psysonic-local://") {
tokio::fs::read(path).await.map_err(|e| e.to_string())?
} else {
@@ -2439,7 +2731,7 @@ pub async fn audio_play_radio(
if state.generation.load(Ordering::SeqCst) != gen { return Ok(()); }
let sink = Sink::try_new(&*state.stream_handle).map_err(|e| e.to_string())?;
let sink = Sink::try_new(&*state.stream_handle.lock().unwrap()).map_err(|e| e.to_string())?;
sink.set_volume((volume.clamp(0.0, 1.0) * MASTER_HEADROOM).clamp(0.0, 1.0));
sink.append(counting);
+229 -15
View File
@@ -1,10 +1,8 @@
/// Discord Rich Presence integration.
///
/// To enable this feature:
/// 1. Go to https://discord.com/developers/applications and create an application.
/// 2. Copy the Application ID and replace DISCORD_APP_ID below.
/// 3. In the "Rich Presence → Art Assets" tab, upload a PNG named "psysonic"
/// (use the app icon from public/logo.png).
/// Album artwork is fetched from the iTunes Search API and passed directly to
/// Discord via the large_image URL field. This avoids the need to pre-upload
/// assets to the Discord Developer Portal.
///
/// The commands silently no-op when Discord is not running or the App ID is wrong,
/// so the app always starts cleanly regardless of Discord availability.
@@ -13,15 +11,201 @@ use discord_rich_presence::{
activity::{Activity, ActivityType, Assets, Timestamps},
DiscordIpc, DiscordIpcClient,
};
use std::sync::Mutex;
use reqwest::blocking::Client;
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;
const DISCORD_APP_ID: &str = "1489544859718258779";
pub struct DiscordState(pub Mutex<Option<DiscordIpcClient>>);
/// Cache entry for iTunes artwork lookup (avoids repeated API calls for same album).
pub struct ArtworkCacheEntry {
pub url: String,
pub fetched_at: Instant,
}
/// TTL: 1 hour — album artwork doesn't change, but we don't want to cache failures forever.
const ARTWORK_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(3600);
pub struct DiscordState {
pub client: Mutex<Option<DiscordIpcClient>>,
/// Cache: "artist|album" -> artwork URL. Arc so it can be shared into spawn_blocking.
pub artwork_cache: Arc<Mutex<HashMap<String, ArtworkCacheEntry>>>,
/// HTTP client for iTunes API requests. blocking::Client is Clone (Arc-internally).
pub http_client: Client,
}
impl DiscordState {
pub fn new() -> Self {
DiscordState(Mutex::new(None))
DiscordState {
client: Mutex::new(None),
artwork_cache: Arc::new(Mutex::new(HashMap::new())),
http_client: Client::builder()
.timeout(std::time::Duration::from_secs(5))
.build()
.unwrap_or_else(|_| Client::new()),
}
}
}
// ─── iTunes Search API ───────────────────────────────────────────────────────
#[derive(Deserialize, Debug)]
#[allow(non_snake_case)]
struct ItunesResponse {
results: Vec<ItunesResult>,
}
#[derive(Deserialize, Debug)]
#[allow(non_snake_case)]
struct ItunesResult {
collectionName: Option<String>,
artistName: Option<String>,
artworkUrl100: Option<String>,
}
/// Normalize string for comparison: lowercase, trim, collapse whitespace.
fn normalize(s: &str) -> String {
s.to_lowercase()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
/// Search for album artwork via iTunes Search API.
/// Returns a higher-resolution URL (600x600) if found.
///
/// Takes explicit `client` and `cache` so this can be called from inside
/// `tokio::task::spawn_blocking` without needing a reference to `DiscordState`.
fn search_itunes_artwork(
client: &Client,
cache: &Mutex<HashMap<String, ArtworkCacheEntry>>,
artist: &str,
album: &str,
title: &str,
) -> Option<String> {
let cache_key = format!("{}|{}", artist, album);
// Check cache first
{
let c = cache.lock().ok()?;
if let Some(entry) = c.get(&cache_key) {
if entry.fetched_at.elapsed() < ARTWORK_CACHE_TTL {
return Some(entry.url.clone());
}
}
}
let norm_artist = normalize(artist);
let norm_album = normalize(album);
let norm_title = normalize(title);
// Strategy 1: exact match search — "artist" "album"
let mut url = url::Url::parse("https://itunes.apple.com/search").ok()?;
url.query_pairs_mut()
.append_pair("term", &format!("\"{}\" \"{}\"", artist, album))
.append_pair("media", "music")
.append_pair("entity", "album")
.append_pair("limit", "5");
if let Some(result) = search_with_url(client, url, &norm_artist, &norm_album) {
cache_and_return(cache, cache_key, &result);
return Some(result);
}
// Strategy 2: relaxed search — artist album (no quotes)
let mut url = url::Url::parse("https://itunes.apple.com/search").ok()?;
url.query_pairs_mut()
.append_pair("term", &format!("{} {}", artist, album))
.append_pair("media", "music")
.append_pair("entity", "album")
.append_pair("limit", "10");
if let Some(result) = search_with_url(client, url, &norm_artist, &norm_album) {
cache_and_return(cache, cache_key, &result);
return Some(result);
}
// Strategy 3: search by track title — artist + title (for singles/rare albums)
if !title.is_empty() {
let mut url = url::Url::parse("https://itunes.apple.com/search").ok()?;
url.query_pairs_mut()
.append_pair("term", &format!("{} {}", artist, title))
.append_pair("media", "music")
.append_pair("entity", "song")
.append_pair("limit", "10");
if let Some(result) = search_with_url(client, url, &norm_artist, &norm_title) {
cache_and_return(cache, cache_key, &result);
return Some(result);
}
}
None
}
fn search_with_url(
client: &Client,
url: url::Url,
norm_artist: &str,
norm_album: &str,
) -> Option<String> {
let resp = client.get(url).send().ok()?;
let body: ItunesResponse = resp.json().ok()?;
for result in &body.results {
let collection = normalize(result.collectionName.as_deref().unwrap_or(""));
let result_artist = normalize(result.artistName.as_deref().unwrap_or(""));
// Flexible matching: check if strings contain each other
// This handles cases like "The Beatles" vs "Beatles" or album subtitle differences
let artist_match = norm_artist == result_artist
|| norm_artist.contains(&result_artist)
|| result_artist.contains(&norm_artist)
|| words_overlap(norm_artist, &result_artist);
let album_match = norm_album == collection
|| norm_album.contains(&collection)
|| collection.contains(norm_album)
|| words_overlap(norm_album, &collection);
if artist_match && album_match {
return Some(result.artworkUrl100.as_ref()?.replace("100x100", "600x600"));
}
}
None
}
/// Check if two strings share at least 50% of their words.
fn words_overlap(a: &str, b: &str) -> bool {
let words_a: std::collections::HashSet<_> = a.split_whitespace().collect();
let words_b: std::collections::HashSet<_> = b.split_whitespace().collect();
if words_a.is_empty() || words_b.is_empty() {
return false;
}
let common = words_a.intersection(&words_b).count();
let min_len = words_a.len().min(words_b.len());
common >= min_len / 2 + min_len % 2 // At least 50% overlap
}
fn cache_and_return(
cache: &Mutex<HashMap<String, ArtworkCacheEntry>>,
key: String,
url: &str,
) {
if let Ok(mut c) = cache.lock() {
c.insert(
key,
ArtworkCacheEntry {
url: url.to_string(),
fetched_at: Instant::now(),
},
);
}
}
@@ -36,15 +220,38 @@ fn try_connect() -> Option<DiscordIpcClient> {
///
/// - `elapsed_secs`: seconds already played. `None` when paused — Discord shows
/// the song/artist without a running timer.
/// - `cover_art_url`: optional direct URL to album artwork. If None, tries to
/// fetch from iTunes Search API using artist + album.
#[tauri::command]
pub fn discord_update_presence(
state: tauri::State<DiscordState>,
pub async fn discord_update_presence(
state: tauri::State<'_, DiscordState>,
title: String,
artist: String,
album: Option<String>,
elapsed_secs: Option<f64>,
cover_art_url: Option<String>,
) -> Result<(), String> {
let mut guard = state.0.lock().unwrap();
// Resolve artwork on a dedicated blocking thread — reqwest::blocking must not
// run on the Tokio async executor directly.
let artwork_url: Option<String> = if let Some(url) = cover_art_url {
Some(url)
} else if let Some(ref album_name) = album {
let http_client = state.http_client.clone();
let cache = Arc::clone(&state.artwork_cache);
let artist_c = artist.clone();
let album_c = album_name.clone();
let title_c = title.clone();
tokio::task::spawn_blocking(move || {
search_itunes_artwork(&http_client, &cache, &artist_c, &album_c, &title_c)
})
.await
.ok()
.flatten()
} else {
None
};
let mut guard = state.client.lock().unwrap();
// (Re)connect lazily — handles the case where Discord starts after the app.
if guard.is_none() {
@@ -62,9 +269,16 @@ pub fn discord_update_presence(
// the cover art icon.
let large_text = album.as_deref().unwrap_or("Psysonic");
let assets = Assets::new()
.large_image("psysonic")
.large_text(large_text);
let assets = if let Some(ref url) = artwork_url {
Assets::new()
.large_image(url.as_str())
.large_text(large_text)
} else {
// Fallback to default Psysonic icon
Assets::new()
.large_image("psysonic")
.large_text(large_text)
};
let mut activity = Activity::new()
.activity_type(ActivityType::Listening)
@@ -95,7 +309,7 @@ pub fn discord_update_presence(
/// Clear the Discord Rich Presence activity (e.g. playback stopped).
#[tauri::command]
pub fn discord_clear_presence(state: tauri::State<DiscordState>) -> Result<(), String> {
let mut guard = state.0.lock().unwrap();
let mut guard = state.client.lock().unwrap();
if let Some(client) = guard.as_mut() {
if client.clear_activity().is_err() {
*guard = None;
+165 -45
View File
@@ -36,49 +36,6 @@ fn exit_app(app_handle: tauri::AppHandle) {
app_handle.exit(0);
}
/// Restart after an in-app update.
///
/// `relaunch()` from tauri-plugin-process spawns the new process while the old one
/// is still alive, so the single-instance plugin in the new process sees the old
/// socket and kills itself immediately (endless loop).
///
/// This command instead:
/// 1. Spawns a shell snippet that waits ~1.5 s and then opens the app again —
/// by then the old process and its single-instance socket are fully gone.
/// 2. Calls `app.exit(0)` directly, which bypasses `on_window_event`
/// prevent_close() and releases the single-instance lock immediately.
#[tauri::command]
fn relaunch_after_update(app: tauri::AppHandle) {
#[cfg(target_os = "windows")]
{
let exe = std::env::current_exe().unwrap_or_default();
let exe_str = exe.to_string_lossy().to_string().replace('\'', "''");
let script = format!(
"Start-Sleep -Milliseconds 1500; Start-Process '{exe_str}'"
);
let _ = std::process::Command::new("powershell")
.args(["-WindowStyle", "Hidden", "-NonInteractive", "-Command", &script])
.spawn();
}
#[cfg(target_os = "macos")]
{
let exe = std::env::current_exe().unwrap_or_default();
// exe lives at Psysonic.app/Contents/MacOS/psysonic — walk up to the bundle.
let bundle = exe
.parent() // MacOS/
.and_then(|p| p.parent()) // Contents/
.and_then(|p| p.parent()); // Psysonic.app
if let Some(bundle_path) = bundle {
let escaped = bundle_path.to_string_lossy().replace('"', "\\\"");
let _ = std::process::Command::new("sh")
.args(["-c", &format!("sleep 1.5 && open \"{escaped}\"")])
.spawn();
}
}
app.exit(0);
}
/// Authenticate with Navidrome's own REST API and return a Bearer token.
async fn navidrome_token(server_url: &str, username: &str, password: &str) -> Result<String, String> {
@@ -578,6 +535,167 @@ async fn delete_offline_track(
Ok(())
}
// ─── Hot playback cache (ephemeral; queue-based prefetch) ─────────────────────
fn resolve_hot_cache_root(
custom_dir: Option<String>,
app: &tauri::AppHandle,
) -> Result<std::path::PathBuf, String> {
if let Some(ref cd) = custom_dir.filter(|s| !s.is_empty()) {
let base = std::path::PathBuf::from(cd);
if !base.exists() {
return Err("VOLUME_NOT_FOUND".to_string());
}
Ok(base.join("psysonic-hot-cache"))
} else {
Ok(app
.path()
.app_data_dir()
.map_err(|e| e.to_string())?
.join("psysonic-hot-cache"))
}
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct HotCacheDownloadResult {
path: String,
size: u64,
}
/// Downloads a single track into the hot playback cache (separate from offline library).
/// Optional `custom_dir`: parent folder; files go under `<custom_dir>/psysonic-hot-cache/<server_id>/`.
/// Returns absolute path and file size for `psysonic-local://` URLs.
#[tauri::command]
async fn download_track_hot_cache(
track_id: String,
server_id: String,
url: String,
suffix: String,
custom_dir: Option<String>,
app: tauri::AppHandle,
) -> Result<HotCacheDownloadResult, String> {
let root = resolve_hot_cache_root(custom_dir, &app)?;
let cache_dir = root.join(&server_id);
tokio::fs::create_dir_all(&cache_dir)
.await
.map_err(|e| e.to_string())?;
let file_path = cache_dir.join(format!("{}.{}", track_id, suffix));
let path_str = file_path.to_string_lossy().to_string();
if file_path.exists() {
let size = tokio::fs::metadata(&file_path)
.await
.map(|m| m.len())
.unwrap_or(0);
return Ok(HotCacheDownloadResult {
path: path_str,
size,
});
}
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(120))
.build()
.map_err(|e| e.to_string())?;
let response = client.get(&url).send().await.map_err(|e| e.to_string())?;
if !response.status().is_success() {
return Err(format!("HTTP {}", response.status().as_u16()));
}
let bytes = response.bytes().await.map_err(|e| e.to_string())?;
tokio::fs::write(&file_path, &bytes)
.await
.map_err(|e| e.to_string())?;
let size = bytes.len() as u64;
Ok(HotCacheDownloadResult {
path: path_str,
size,
})
}
#[tauri::command]
async fn get_hot_cache_size(custom_dir: Option<String>, app: tauri::AppHandle) -> u64 {
fn dir_size(root: std::path::PathBuf) -> u64 {
if !root.exists() {
return 0;
}
let mut total: u64 = 0;
let mut stack = vec![root];
while let Some(dir) = stack.pop() {
let rd = match std::fs::read_dir(&dir) {
Ok(r) => r,
Err(_) => continue,
};
for entry in rd.flatten() {
let path = entry.path();
if path.is_dir() {
stack.push(path);
} else if let Ok(meta) = std::fs::metadata(&path) {
total += meta.len();
}
}
}
total
}
resolve_hot_cache_root(custom_dir, &app)
.map(|root| dir_size(root))
.unwrap_or(0)
}
#[tauri::command]
async fn delete_hot_cache_track(
local_path: String,
custom_dir: Option<String>,
app: tauri::AppHandle,
) -> Result<(), String> {
let file_path = std::path::PathBuf::from(&local_path);
if file_path.exists() {
tokio::fs::remove_file(&file_path)
.await
.map_err(|e| e.to_string())?;
}
let boundary = resolve_hot_cache_root(custom_dir, &app)?;
let mut current = file_path.parent().map(|p| p.to_path_buf());
while let Some(dir) = current {
if dir == boundary || !dir.starts_with(&boundary) {
break;
}
match std::fs::read_dir(&dir) {
Ok(mut entries) => {
if entries.next().is_some() {
break;
}
if std::fs::remove_dir(&dir).is_err() {
break;
}
current = dir.parent().map(|p| p.to_path_buf());
}
Err(_) => break,
}
}
Ok(())
}
/// Removes the entire hot cache root (`psysonic-hot-cache` for the active location).
#[tauri::command]
async fn purge_hot_cache(custom_dir: Option<String>, app: tauri::AppHandle) -> Result<(), String> {
let dir = resolve_hot_cache_root(custom_dir, &app)?;
if dir.exists() {
tokio::fs::remove_dir_all(&dir)
.await
.map_err(|e| e.to_string())?;
}
Ok(())
}
/// Builds and returns a new system-tray icon with all menu items and event handlers.
/// Called from `setup()` (initial creation) and from `toggle_tray_icon` (re-creation).
fn build_tray_icon(app: &tauri::AppHandle) -> tauri::Result<TrayIcon> {
@@ -693,7 +811,6 @@ pub fn run() {
.manage(ShortcutMap::default())
.manage(discord::DiscordState::new())
.manage(TrayState::default())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_window_state::Builder::default().build())
.plugin(tauri_plugin_shell::init())
@@ -866,7 +983,10 @@ pub fn run() {
download_track_offline,
delete_offline_track,
get_offline_cache_size,
relaunch_after_update,
download_track_hot_cache,
get_hot_cache_size,
delete_hot_cache_track,
purge_hot_cache,
toggle_tray_icon,
])
.run(tauri::generate_context!())
+1 -9
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Psysonic",
"version": "1.34.0",
"version": "1.34.2",
"identifier": "dev.psysonic.player",
"build": {
"beforeDevCommand": "npm run dev",
@@ -31,14 +31,6 @@
"csp": null
}
},
"plugins": {
"updater": {
"pubkey": "RWTgsDNd9LqppH6DMq7ypolI0bsLCNsjOvif4mrHyr4UDidkUT69IY1K",
"endpoints": [
"https://github.com/Psychotoxical/psysonic/releases/latest/download/latest.json"
]
}
},
"bundle": {
"active": true,
"targets": "all",
+25
View File
@@ -53,7 +53,9 @@ import AppUpdater from './components/AppUpdater';
import { version } from '../package.json';
import { useConnectionStatus } from './hooks/useConnectionStatus';
import { useAuthStore } from './store/authStore';
import { getMusicFolders } from './api/subsonic';
import { useOfflineStore } from './store/offlineStore';
import { initHotCachePrefetch } from './hotCachePrefetch';
import { usePlayerStore, initAudioListeners } from './store/playerStore';
import { useThemeStore } from './store/themeStore';
import { useFontStore } from './store/fontStore';
@@ -81,9 +83,28 @@ function AppShell() {
const navigate = useNavigate();
const location = useLocation();
const serverId = useAuthStore(s => s.activeServerId ?? '');
const isLoggedIn = useAuthStore(s => s.isLoggedIn);
const activeServerId = useAuthStore(s => s.activeServerId);
const setMusicFolders = useAuthStore(s => s.setMusicFolders);
const offlineAlbums = useOfflineStore(s => s.albums);
const hasOfflineContent = Object.values(offlineAlbums).some(a => a.serverId === serverId);
useEffect(() => {
if (!isLoggedIn || !activeServerId) return;
let cancelled = false;
(async () => {
try {
const folders = await getMusicFolders();
if (!cancelled) setMusicFolders(folders);
} catch {
if (!cancelled) setMusicFolders([]);
}
})();
return () => {
cancelled = true;
};
}, [isLoggedIn, activeServerId, setMusicFolders]);
// Auto-navigate to offline library when no connection but cached content exists
const prevConnStatus = useRef(connStatus);
useEffect(() => {
@@ -461,6 +482,10 @@ export default function App() {
return initAudioListeners();
}, []);
useEffect(() => {
return initHotCachePrefetch();
}, []);
useEffect(() => {
useGlobalShortcutsStore.getState().registerAll();
}, []);
+89 -6
View File
@@ -40,6 +40,15 @@ async function api<T>(endpoint: string, extra: Record<string, unknown> = {}, tim
return data as T;
}
/** Optional `musicFolderId` when the user narrowed browsing to one Subsonic library (see `getMusicFolders`). */
export function libraryFilterParams(): Record<string, string | number> {
const { activeServerId, musicLibraryFilterByServer } = useAuthStore.getState();
if (!activeServerId) return {};
const f = musicLibraryFilterByServer[activeServerId];
if (f === undefined || f === 'all') return {};
return { musicFolderId: f };
}
// ─── Types ────────────────────────────────────────────────────
export interface SubsonicAlbum {
id: string;
@@ -139,6 +148,11 @@ export interface SubsonicGenre {
albumCount: number;
}
export interface SubsonicMusicFolder {
id: string;
name: string;
}
export interface SubsonicArtistInfo {
biography?: string;
musicBrainzId?: string;
@@ -150,6 +164,19 @@ export interface SubsonicArtistInfo {
}
// ─── API Methods ──────────────────────────────────────────────
export async function getMusicFolders(): Promise<SubsonicMusicFolder[]> {
const data = await api<{ musicFolders: { musicFolder: SubsonicMusicFolder | SubsonicMusicFolder[] } }>(
'getMusicFolders.view',
);
const raw = data.musicFolders?.musicFolder;
if (!raw) return [];
const arr = Array.isArray(raw) ? raw : [raw];
return arr.map(f => ({
id: String((f as { id: string | number }).id),
name: (f as { name?: string }).name ?? 'Library',
}));
}
export async function ping(): Promise<boolean> {
try {
await api('ping.view');
@@ -178,7 +205,11 @@ export async function pingWithCredentials(serverUrl: string, username: string, p
}
export async function getRandomAlbums(size = 6): Promise<SubsonicAlbum[]> {
const data = await api<{ albumList2: { album: SubsonicAlbum[] } }>('getAlbumList2.view', { type: 'random', size });
const data = await api<{ albumList2: { album: SubsonicAlbum[] } }>('getAlbumList2.view', {
type: 'random',
size,
...libraryFilterParams(),
});
return data.albumList2?.album ?? [];
}
@@ -188,12 +219,19 @@ export async function getAlbumList(
offset = 0,
extra: Record<string, unknown> = {}
): Promise<SubsonicAlbum[]> {
const data = await api<{ albumList2: { album: SubsonicAlbum[] } }>('getAlbumList2.view', { type, size, offset, _t: Date.now(), ...extra });
const data = await api<{ albumList2: { album: SubsonicAlbum[] } }>('getAlbumList2.view', {
type,
size,
offset,
_t: Date.now(),
...libraryFilterParams(),
...extra,
});
return data.albumList2?.album ?? [];
}
export async function getRandomSongs(size = 50, genre?: string, timeout = 15000): Promise<SubsonicSong[]> {
const params: Record<string, string | number> = { size, _t: Date.now() };
const params: Record<string, string | number> = { size, _t: Date.now(), ...libraryFilterParams() };
if (genre) params.genre = genre;
const data = await api<{ randomSongs: { song: SubsonicSong[] } }>('getRandomSongs.view', params, timeout);
return data.randomSongs?.song ?? [];
@@ -215,7 +253,9 @@ export async function getAlbum(id: string): Promise<{ album: SubsonicAlbum; song
}
export async function getArtists(): Promise<SubsonicArtist[]> {
const data = await api<{ artists: { index: Array<{ artist: SubsonicArtist[] }> } }>('getArtists.view');
const data = await api<{ artists: { index: Array<{ artist: SubsonicArtist[] }> } }>('getArtists.view', {
...libraryFilterParams(),
});
const indices = data.artists?.index ?? [];
return indices.flatMap(i => i.artist ?? []);
}
@@ -258,7 +298,12 @@ export async function getGenres(): Promise<SubsonicGenre[]> {
export async function getAlbumsByGenre(genre: string, size = 50, offset = 0): Promise<SubsonicAlbum[]> {
const data = await api<{ albumList2: { album: SubsonicAlbum | SubsonicAlbum[] } }>('getAlbumList2.view', {
type: 'byGenre', genre, size, offset, _t: Date.now(),
type: 'byGenre',
genre,
size,
offset,
_t: Date.now(),
...libraryFilterParams(),
});
const raw = data.albumList2?.album;
if (!raw) return [];
@@ -284,7 +329,7 @@ export async function getStarred(): Promise<StarredResults> {
album?: SubsonicAlbum[];
song?: SubsonicSong[];
}
}>('getStarred2.view');
}>('getStarred2.view', { ...libraryFilterParams() });
const r = data.starred2 ?? {};
return { artists: r.artist ?? [], albums: r.album ?? [], songs: r.song ?? [] };
}
@@ -318,6 +363,7 @@ export async function search(query: string, options?: { albumCount?: number; art
artistCount: options?.artistCount ?? 5,
albumCount: options?.albumCount ?? 5,
songCount: options?.songCount ?? 10,
...libraryFilterParams(),
});
const r = data.searchResult3 ?? {};
return { artists: r.artist ?? [], albums: r.album ?? [], songs: r.song ?? [] };
@@ -606,3 +652,40 @@ export async function getTopRadioStations(offset = 0): Promise<RadioBrowserStati
export async function fetchUrlBytes(url: string): Promise<[number[], string]> {
return invoke<[number[], string]>('fetch_url_bytes', { url });
}
// ─── Structured Lyrics (OpenSubsonic / getLyricsBySongId) ────────────────────
export interface SubsonicLyricLine {
start?: number; // milliseconds — absent when unsynced
value: string;
}
export interface SubsonicStructuredLyrics {
issynced: boolean;
lang?: string;
offset?: number;
displayArtist?: string;
displayTitle?: string;
line: SubsonicLyricLine[];
}
/**
* Fetches structured lyrics from the server's embedded tags via the
* OpenSubsonic `getLyricsBySongId` endpoint. Returns null when the
* server doesn't support the endpoint or the track has no embedded lyrics.
* Prefers synced lyrics over plain when both are present.
*/
export async function getLyricsBySongId(id: string): Promise<SubsonicStructuredLyrics | null> {
try {
const data = await api<{ lyricsList: { structuredLyrics?: SubsonicStructuredLyrics[] } }>(
'getLyricsBySongId.view',
{ id },
);
const list = data.lyricsList?.structuredLyrics;
if (!list || list.length === 0) return null;
return list.find(l => l.issynced) ?? list[0];
} catch {
// Server doesn't support the endpoint or track has no embedded lyrics
return null;
}
}
+21 -100
View File
@@ -1,9 +1,7 @@
import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { check, Update, DownloadEvent } from '@tauri-apps/plugin-updater';
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-shell';
import { RefreshCw, Download, X } from 'lucide-react';
import { RefreshCw, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { version as currentVersion } from '../../package.json';
@@ -18,85 +16,31 @@ function isNewer(a: string, b: string): boolean {
return false;
}
type State =
| { phase: 'idle' }
| { phase: 'available'; version: string; update: Update | null; error?: string }
| { phase: 'downloading'; pct: number }
| { phase: 'installing' }
| { phase: 'done' };
export default function AppUpdater() {
const { t } = useTranslation();
const [state, setState] = useState<State>({ phase: 'idle' });
const [newVersion, setNewVersion] = useState<string | null>(null);
const [dismissed, setDismissed] = useState(false);
useEffect(() => {
let cancelled = false;
const timer = setTimeout(async () => {
if (cancelled) return;
try {
// Try Tauri native updater first (macOS + Windows)
const update = await check();
if (cancelled) return;
if (update) {
setState({ phase: 'available', version: update.version, update });
return;
}
} catch {
// Tauri updater unavailable or network error — fall through to GitHub check
}
// Fallback: GitHub API check (Linux / offline Tauri updater)
try {
const res = await fetch('https://api.github.com/repos/Psychotoxical/psysonic/releases/latest');
if (!res.ok || cancelled) return;
const data = await res.json();
const tag: string = data.tag_name ?? '';
if (!cancelled && tag && isNewer(tag, currentVersion)) {
setState({ phase: 'available', version: tag.replace(/^[^0-9]*/, ''), update: null });
setNewVersion(tag.replace(/^[^0-9]*/, ''));
}
} catch {
// No update check possible — stay idle
// No network or rate-limited — stay idle
}
}, 3000);
}, 4000);
return () => { cancelled = true; clearTimeout(timer); };
}, []);
if (dismissed || state.phase === 'idle' || state.phase === 'done') return null;
const handleInstall = async () => {
if (state.phase !== 'available' || !state.update) return;
const update = state.update;
const savedVersion = state.version;
let total = 0;
let downloaded = 0;
setState({ phase: 'downloading', pct: 0 });
try {
await update.downloadAndInstall((event: DownloadEvent) => {
if (event.event === 'Started') {
total = event.data.contentLength ?? 0;
} else if (event.event === 'Progress') {
downloaded += event.data.chunkLength;
setState({ phase: 'downloading', pct: total ? Math.round((downloaded / total) * 100) : 0 });
} else if (event.event === 'Finished') {
setState({ phase: 'installing' });
}
});
await invoke('relaunch_after_update');
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
console.error('Update failed:', msg);
// Surface the error so the user (and developer) can see what went wrong
setState({ phase: 'available', version: savedVersion, update, error: msg });
}
};
const handleDownload = () => {
open('https://github.com/Psychotoxical/psysonic/releases/latest');
};
const version = state.phase === 'available' ? state.version : '';
const canInstall = state.phase === 'available' && state.update !== null;
const isLinuxFallback = state.phase === 'available' && state.update === null;
if (!newVersion || dismissed) return null;
return createPortal(
<div className="app-updater-toast">
@@ -107,44 +51,21 @@ export default function AppUpdater() {
<X size={12} />
</button>
</div>
<div className="app-updater-version">{t('common.updaterVersion', { version })}</div>
{state.phase === 'downloading' && (
<div className="app-updater-progress-wrap">
<div className="app-updater-progress-bar">
<div className="app-updater-progress-fill" style={{ width: `${state.pct}%` }} />
</div>
<span className="app-updater-pct">{state.pct}%</span>
</div>
)}
{state.phase === 'installing' && (
<div className="app-updater-status">{t('common.updaterInstalling')}</div>
)}
{state.phase === 'available' && (
<div className="app-updater-actions">
{state.error && (
<div className="app-updater-error">{state.error}</div>
)}
{canInstall && (
<>
<p className="app-updater-hint">{t('common.updaterExperimentalHint')}</p>
<button className="app-updater-btn-primary" onClick={handleInstall}>
<Download size={12} /> {t('common.updaterInstall')}
</button>
<button className="app-updater-btn-secondary" onClick={handleDownload}>
<Download size={12} /> {t('common.updaterDownload')}
</button>
</>
)}
{isLinuxFallback && (
<button className="app-updater-btn-primary" onClick={handleDownload}>
<Download size={12} /> {t('common.updaterDownload')}
</button>
)}
</div>
)}
<div className="app-updater-version">{t('common.updaterVersion', { version: newVersion })}</div>
<div className="app-updater-actions">
<button
className="app-updater-btn-primary"
onClick={() => open('https://github.com/Psychotoxical/psysonic/releases/latest')}
>
GitHub
</button>
<button
className="app-updater-btn-secondary"
onClick={() => open('https://psysonic.psychotoxic.eu/#downloads')}
>
{t('common.updaterWebsite')}
</button>
</div>
</div>,
document.body
);
+214 -27
View File
@@ -1,12 +1,17 @@
import React, { useCallback, useEffect, useState, useRef, memo, useMemo } from 'react';
import {
Play, Pause, SkipBack, SkipForward,
ChevronDown, Repeat, Repeat1, Square, Music, Heart
ChevronDown, Repeat, Repeat1, Square, Music, Heart, MicVocal
} from 'lucide-react';
import { usePlayerStore } from '../store/playerStore';
import { buildCoverArtUrl, coverArtCacheKey, getArtistInfo, star, unstar } from '../api/subsonic';
import CachedImage, { useCachedUrl } from './CachedImage';
import { useCachedUrl } from './CachedImage';
import { getCachedUrl } from '../utils/imageCache';
import { useTranslation } from 'react-i18next';
import { useLyrics } from '../hooks/useLyrics';
import { useAuthStore } from '../store/authStore';
import type { LrcLine } from '../api/lrclib';
import type { Track } from '../store/playerStore';
function formatTime(seconds: number): string {
if (!seconds || isNaN(seconds)) return '0:00';
@@ -15,12 +20,136 @@ function formatTime(seconds: number): string {
return `${m}:${s.toString().padStart(2, '0')}`;
}
// ─── Fullscreen lyrics overlay ────────────────────────────────────────────────
// Slot height = 6vh = window.innerHeight * 0.06 — must match CSS height: 6vh.
// railY = (2 - activeIdx) * slotH centers slot `activeIdx` in a 5-slot window:
// activeIdx=0 → railY=+2×slotH (line 0 at slot 2)
// activeIdx=2 → railY=0 (line 2 at center)
// activeIdx=5 → railY=-3×slotH (line 5 at slot 2)
const FsLyrics = memo(function FsLyrics({ currentTrack }: { currentTrack: Track | null }) {
const { syncedLines, loading } = useLyrics(currentTrack);
const lines = syncedLines as LrcLine[] | null;
const hasSynced = lines !== null && lines.length > 0;
// Keep a ref so the zustand selector can read lines without closing over
// a changing variable — avoids re-creating the selector on every render.
const linesRef = useRef<LrcLine[]>([]);
linesRef.current = hasSynced ? lines! : [];
// Selector returns the active line INDEX — zustand only re-renders when it
// actually changes, dropping us from ~10 Hz to ~0.2 Hz re-renders.
const activeIdx = usePlayerStore(s => {
const ls = linesRef.current;
if (ls.length === 0) return -1;
return ls.reduce((acc, line, i) => s.currentTime >= line.time ? i : acc, -1);
});
const duration = usePlayerStore(s => s.currentTrack?.duration ?? 0);
const seek = usePlayerStore(s => s.seek);
// Cache slotH — avoids forcing a layout read (window.innerHeight) on every render.
const slotH = useRef(window.innerHeight * 0.06);
useEffect(() => {
const onResize = () => { slotH.current = window.innerHeight * 0.06; };
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
// Event delegation — one handler for all lyric lines instead of N closures per tick.
const handleLineClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
const target = (e.target as HTMLElement).closest<HTMLElement>('[data-time]');
if (!target || duration <= 0) return;
seek(parseFloat(target.dataset.time!) / duration);
}, [duration, seek]);
if (!currentTrack || loading || !hasSynced) return null;
const railY = (2 - Math.max(0, activeIdx)) * slotH.current;
return (
<div className="fs-lyrics-overlay" aria-hidden="true">
<div
className="fs-lyrics-rail"
style={{ transform: `translateY(${railY}px)` }}
onClick={handleLineClick}
>
{lines!.map((line, i) => (
<div
key={i}
className={`fs-lyric-line${i === activeIdx ? ' fsl-active' : i < activeIdx ? ' fsl-past' : ''}`}
data-time={line.time}
>
{line.text || '\u00A0'}
</div>
))}
</div>
</div>
);
});
// ─── Album art box — crossfades layers so old art stays visible while new loads ─
// Uses 300px thumbnails (portrait fallback uses 500px separately).
//
// Why onLoad instead of new Image() preload:
// React batches setLayers(add invisible) + rAF setLayers(make visible) into one
// commit, so the browser never sees opacity:0 and the CSS transition never fires.
// Using the DOM img's own onLoad guarantees the element was painted at opacity:0
// before we flip it to 1.
const FsArt = memo(function FsArt({ fetchUrl, cacheKey }: { fetchUrl: string; cacheKey: string }) {
// true = show raw fetchUrl immediately as fallback while blob resolves.
// PlayerBar uses 128px; FS player uses 300px — different cache keys, no warm hit.
// Showing the URL directly avoids the multi-second blank wait.
const blobUrl = useCachedUrl(fetchUrl, cacheKey, true);
const [layers, setLayers] = useState<Array<{ src: string; id: number; vis: boolean }>>([]);
const counter = useRef(0);
const cleanupTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Add a new invisible layer whenever the blob URL changes.
useEffect(() => {
if (!blobUrl) return;
const id = ++counter.current;
setLayers(prev => [...prev, { src: blobUrl, id, vis: false }]);
}, [blobUrl]);
// Called by the DOM <img> once it has painted at opacity:0 — now safe to transition.
// Cancel any pending cleanup timer so a stale setTimeout from a previous layer
// cannot remove the layer we are making visible right now.
const handleLoad = useCallback((id: number) => {
if (cleanupTimer.current) clearTimeout(cleanupTimer.current);
setLayers(prev => prev.map(l => ({ ...l, vis: l.id === id })));
cleanupTimer.current = setTimeout(() => setLayers(prev => prev.filter(l => l.id === id)), 400);
}, []);
if (layers.length === 0) {
return <div className="fs-art fs-art-placeholder"><Music size={40} /></div>;
}
return (
<>
{layers.map(l => (
<img
key={l.id}
src={l.src}
className="fs-art"
style={{ opacity: l.vis ? 1 : 0 }}
onLoad={() => handleLoad(l.id)}
alt=""
decoding="async"
/>
))}
</>
);
});
// ─── Artist portrait — right half, crossfades on track change ─────────────────
const FsPortrait = memo(function FsPortrait({ url }: { url: string }) {
const [layers, setLayers] = useState<Array<{ url: string; id: number; visible: boolean }>>(() =>
url ? [{ url, id: 0, visible: true }] : []
);
const counterRef = useRef(1);
const cleanupTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
if (!url) return;
@@ -32,8 +161,9 @@ const FsPortrait = memo(function FsPortrait({ url }: { url: string }) {
setLayers(prev => [...prev, { url, id, visible: false }]);
requestAnimationFrame(() => {
if (cancelled) return;
if (cleanupTimer.current) clearTimeout(cleanupTimer.current);
setLayers(prev => prev.map(l => ({ ...l, visible: l.id === id })));
setTimeout(() => {
cleanupTimer.current = setTimeout(() => {
if (!cancelled) setLayers(prev => prev.filter(l => l.id === id));
}, 1000);
});
@@ -122,12 +252,14 @@ export default function FullscreenPlayer({ onClose }: FullscreenPlayerProps) {
const previous = usePlayerStore(s => s.previous);
const stop = usePlayerStore(s => s.stop);
const toggleRepeat = usePlayerStore(s => s.toggleRepeat);
const starredOverrides = usePlayerStore(s => s.starredOverrides);
const setStarredOverride = usePlayerStore(s => s.setStarredOverride);
const isStarred = currentTrack
? (currentTrack.id in starredOverrides ? starredOverrides[currentTrack.id] : !!currentTrack.starred)
: false;
// Derive isStarred inside the selector so we only re-render when the boolean
// actually flips — not when any unrelated track's star status changes.
const isStarred = usePlayerStore(s => {
const track = s.currentTrack;
if (!track) return false;
return track.id in s.starredOverrides ? s.starredOverrides[track.id] : !!track.starred;
});
const toggleStar = useCallback(async () => {
if (!currentTrack) return;
@@ -144,6 +276,9 @@ export default function FullscreenPlayer({ onClose }: FullscreenPlayerProps) {
const duration = currentTrack?.duration ?? 0;
// buildCoverArtUrl generates a new salt on every call — must be memoized.
// 300px for the small art box; 500px for the right-side portrait fallback.
const artUrl = useMemo(() => currentTrack?.coverArt ? buildCoverArtUrl(currentTrack.coverArt, 300) : '', [currentTrack?.coverArt]);
const artKey = useMemo(() => currentTrack?.coverArt ? coverArtCacheKey(currentTrack.coverArt, 300) : '', [currentTrack?.coverArt]);
const coverUrl = useMemo(() => currentTrack?.coverArt ? buildCoverArtUrl(currentTrack.coverArt, 500) : '', [currentTrack?.coverArt]);
const coverKey = useMemo(() => currentTrack?.coverArt ? coverArtCacheKey(currentTrack.coverArt, 500) : '', [currentTrack?.coverArt]);
// `false` = no fetchUrl fallback — prevents double crossfade (fetchUrl → blobUrl).
@@ -163,22 +298,71 @@ export default function FullscreenPlayer({ onClose }: FullscreenPlayerProps) {
}, [currentTrack?.artistId]);
const portraitUrl = artistBgUrl || resolvedCoverUrl;
const showFullscreenLyrics = useAuthStore(s => s.showFullscreenLyrics);
// Pre-fetch next track's 300px cover into the IndexedDB cache.
// Selector returns only the coverArt id, so it only re-runs on actual changes.
const nextCoverArt = usePlayerStore(s => {
const q = s.queue;
const idx = s.queueIndex;
return (idx >= 0 && idx + 1 < q.length) ? (q[idx + 1]?.coverArt ?? null) : null;
});
useEffect(() => {
if (!nextCoverArt) return;
const url = buildCoverArtUrl(nextCoverArt, 300);
const key = coverArtCacheKey(nextCoverArt, 300);
getCachedUrl(url, key).catch(() => {});
}, [nextCoverArt]);
// Idle-fade system — hides controls after 3 s of inactivity
const [isIdle, setIsIdle] = useState(false);
const idleTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const resetIdle = useCallback(() => {
setIsIdle(false);
if (idleTimer.current) clearTimeout(idleTimer.current);
idleTimer.current = setTimeout(() => setIsIdle(true), 3000);
}, []);
// Throttled wrapper for mousemove — avoids clearing/setting timeouts on every pixel.
const lastMoveTime = useRef(0);
const handleMouseMove = useCallback(() => {
const now = Date.now();
if (now - lastMoveTime.current < 200) return;
lastMoveTime.current = now;
resetIdle();
}, [resetIdle]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
resetIdle();
return () => { if (idleTimer.current) clearTimeout(idleTimer.current); };
}, [resetIdle]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
resetIdle();
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [onClose]);
}, [onClose, resetIdle]);
const metaParts = [
const metaParts = useMemo(() => [
currentTrack?.album,
currentTrack?.year?.toString(),
currentTrack?.suffix?.toUpperCase(),
currentTrack?.bitRate ? `${currentTrack.bitRate} kbps` : '',
].filter(Boolean);
].filter(Boolean), [currentTrack]);
return (
<div className="fs-player" role="dialog" aria-modal="true" aria-label={t('player.fullscreen')}>
<div
className="fs-player"
role="dialog"
aria-modal="true"
aria-label={t('player.fullscreen')}
data-idle={isIdle}
onMouseMove={handleMouseMove}
>
{/* Layer 0 — animated dark mesh gradient (real divs = will-change possible) */}
<div className="fs-mesh-bg" aria-hidden="true">
@@ -197,29 +381,23 @@ export default function FullscreenPlayer({ onClose }: FullscreenPlayerProps) {
<ChevronDown size={28} />
</button>
{/* Lyrics overlay — upper-left quadrant, above cluster */}
{showFullscreenLyrics && <FsLyrics currentTrack={currentTrack} />}
{/* Layer 3 — info cluster, bottom-left */}
<div className="fs-cluster">
{/* Album art */}
<div className="fs-art-wrap">
{coverUrl ? (
<CachedImage
src={coverUrl}
cacheKey={coverKey}
alt={`${currentTrack?.album} Cover`}
className="fs-art"
/>
) : (
<div className="fs-art fs-art-placeholder"><Music size={40} /></div>
)}
<FsArt fetchUrl={artUrl} cacheKey={artKey} />
</div>
{/* Artist — massive statement */}
<p className="fs-artist-name">{currentTrack?.artist ?? '—'}</p>
{/* Track title — accent, light weight */}
{/* Track title — massive statement */}
<p className="fs-track-title">{currentTrack?.title ?? '—'}</p>
{/* Artist — secondary, below track */}
<p className="fs-artist-name">{currentTrack?.artist ?? '—'}</p>
{/* Metadata row */}
{metaParts.length > 0 && (
<div className="fs-meta">
@@ -262,6 +440,15 @@ export default function FullscreenPlayer({ onClose }: FullscreenPlayerProps) {
<Heart size={14} fill={isStarred ? 'currentColor' : 'none'} />
</button>
)}
<button
className="fs-btn fs-btn-sm"
onClick={() => useAuthStore.getState().setShowFullscreenLyrics(!showFullscreenLyrics)}
aria-label={t('player.fsLyricsToggle')}
data-tooltip={t('player.fsLyricsToggle')}
style={{ color: showFullscreenLyrics ? 'var(--accent)' : 'rgba(255,255,255,0.35)' }}
>
<MicVocal size={14} />
</button>
</div>
</div>
+3 -1
View File
@@ -7,6 +7,7 @@ import { usePlayerStore, songToTrack } from '../store/playerStore';
import { useTranslation } from 'react-i18next';
import { playAlbum } from '../utils/playAlbum';
import { useIsMobile } from '../hooks/useIsMobile';
import { useAuthStore } from '../store/authStore';
const INTERVAL_MS = 10000;
@@ -52,6 +53,7 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
const { t } = useTranslation();
const navigate = useNavigate();
const isMobile = useIsMobile();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
const [activeIdx, setActiveIdx] = useState(0);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
@@ -59,7 +61,7 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
useEffect(() => {
if (albumsProp?.length) { setAlbums(albumsProp); return; }
getRandomAlbums(8).then(a => { if (a.length) setAlbums(a); }).catch(() => {});
}, [albumsProp]);
}, [albumsProp, musicLibraryFilterVersion]);
// Start / restart auto-advance timer
const startTimer = useCallback((len: number) => {
+3 -1
View File
@@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom';
import { Search, Disc3, Users, Music, SlidersHorizontal } from 'lucide-react';
import { search, SearchResults, buildCoverArtUrl } from '../api/subsonic';
import { usePlayerStore, songToTrack } from '../store/playerStore';
import { useAuthStore } from '../store/authStore';
import { useTranslation } from 'react-i18next';
function debounce(fn: (q: string) => void, ms: number): (q: string) => void {
@@ -24,6 +25,7 @@ export default function LiveSearch() {
const playTrack = usePlayerStore(state => state.playTrack);
const ref = useRef<HTMLDivElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const doSearch = useCallback(
debounce(async (q: string) => {
@@ -37,7 +39,7 @@ export default function LiveSearch() {
setLoading(false);
}
}, 300),
[]
[musicLibraryFilterVersion]
);
useEffect(() => { doSearch(query); setActiveIndex(-1); }, [query, doSearch]);
+19 -69
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { usePlayerStore } from '../store/playerStore';
import { fetchLyrics, parseLrc, LrcLine } from '../api/lrclib';
import type { LrcLine } from '../api/lrclib';
import { useLyrics } from '../hooks/useLyrics';
import { useTranslation } from 'react-i18next';
import type { Track } from '../store/playerStore';
@@ -8,87 +9,27 @@ interface Props {
currentTrack: Track | null;
}
interface CachedLyrics {
syncedLines: LrcLine[] | null;
plainLyrics: string | null;
notFound: boolean;
}
// Session-level cache — survives tab switches (component unmount/remount).
// Cleared implicitly when the app restarts.
const lyricsCache = new Map<string, CachedLyrics>();
export default function LyricsPane({ currentTrack }: Props) {
const { t } = useTranslation();
const cached = currentTrack ? lyricsCache.get(currentTrack.id) : undefined;
const { syncedLines, plainLyrics, source, loading, notFound } = useLyrics(currentTrack);
const [loading, setLoading] = useState(!cached && !!currentTrack);
const [syncedLines, setSyncedLines] = useState<LrcLine[] | null>(cached?.syncedLines ?? null);
const [plainLyrics, setPlainLyrics] = useState<string | null>(cached?.plainLyrics ?? null);
const [notFound, setNotFound] = useState(cached?.notFound ?? false);
const hasSynced = syncedLines !== null && syncedLines.length > 0;
const hasSynced = syncedLines !== null && syncedLines.length > 0;
const currentTime = usePlayerStore(s => hasSynced ? s.currentTime : 0);
const seek = usePlayerStore(s => s.seek);
const duration = usePlayerStore(s => s.currentTrack?.duration ?? 0);
const seek = usePlayerStore(s => s.seek);
const duration = usePlayerStore(s => s.currentTrack?.duration ?? 0);
const lineRefs = useRef<(HTMLDivElement | null)[]>([]);
const prevActive = useRef(-1);
// Reset refs when track changes
useEffect(() => {
if (!currentTrack) return;
// Serve from cache if available
const hit = lyricsCache.get(currentTrack.id);
if (hit) {
setSyncedLines(hit.syncedLines);
setPlainLyrics(hit.plainLyrics);
setNotFound(hit.notFound);
setLoading(false);
lineRefs.current = [];
prevActive.current = -1;
return;
}
let cancelled = false;
setSyncedLines(null);
setPlainLyrics(null);
setNotFound(false);
setLoading(true);
lineRefs.current = [];
prevActive.current = -1;
fetchLyrics(
currentTrack.artist ?? '',
currentTrack.title,
currentTrack.album ?? '',
currentTrack.duration ?? 0,
).then(result => {
if (cancelled) return;
setLoading(false);
if (!result || (!result.syncedLyrics && !result.plainLyrics)) {
lyricsCache.set(currentTrack.id, { syncedLines: null, plainLyrics: null, notFound: true });
setNotFound(true);
return;
}
const lines = result.syncedLyrics ? parseLrc(result.syncedLyrics) : null;
const synced = lines && lines.length > 0 ? lines : null;
lyricsCache.set(currentTrack.id, { syncedLines: synced, plainLyrics: result.plainLyrics, notFound: false });
setSyncedLines(synced);
setPlainLyrics(result.plainLyrics);
}).catch(() => {
if (!cancelled) {
lyricsCache.set(currentTrack.id, { syncedLines: null, plainLyrics: null, notFound: true });
setLoading(false);
setNotFound(true);
}
});
return () => { cancelled = true; };
}, [currentTrack?.id]); // eslint-disable-line react-hooks/exhaustive-deps
}, [currentTrack?.id]);
const activeIdx = hasSynced
? syncedLines!.reduce((acc, line, i) => (currentTime >= line.time ? i : acc), -1)
? (syncedLines as LrcLine[]).reduce((acc, line, i) => (currentTime >= line.time ? i : acc), -1)
: -1;
useEffect(() => {
@@ -112,13 +53,19 @@ export default function LyricsPane({ currentTrack }: Props) {
return `${base} active`;
};
const sourceLabel = source === 'server'
? t('player.lyricsSourceServer')
: source === 'lrclib'
? t('player.lyricsSourceLrclib')
: null;
return (
<div className="lyrics-pane">
{loading && <p className="lyrics-status">{t('player.lyricsLoading')}</p>}
{notFound && !loading && <p className="lyrics-status">{t('player.lyricsNotFound')}</p>}
{hasSynced && (
<div className="lyrics-synced">
{syncedLines!.map((line, i) => (
{(syncedLines as LrcLine[]).map((line, i) => (
<div
key={i}
ref={el => { lineRefs.current[i] = el; }}
@@ -138,6 +85,9 @@ export default function LyricsPane({ currentTrack }: Props) {
))}
</div>
)}
{sourceLabel && !loading && !notFound && (
<p className="lyrics-source">{sourceLabel}</p>
)}
</div>
);
}
+3 -1
View File
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom';
import { X, Search, Disc3, Users, Music, Music2, Clock, ChevronRight } from 'lucide-react';
import { search, SearchResults, buildCoverArtUrl } from '../api/subsonic';
import { usePlayerStore, songToTrack } from '../store/playerStore';
import { useAuthStore } from '../store/authStore';
import { useTranslation } from 'react-i18next';
const STORAGE_KEY = 'psysonic_recent_searches';
@@ -34,6 +35,7 @@ export default function MobileSearchOverlay({ onClose }: { onClose: () => void }
const [loading, setLoading] = useState(false);
const [recentSearches, setRecentSearches] = useState<string[]>(loadRecent);
const inputRef = useRef<HTMLInputElement>(null);
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
useEffect(() => { inputRef.current?.focus(); }, []);
@@ -50,7 +52,7 @@ export default function MobileSearchOverlay({ onClose }: { onClose: () => void }
try { setResults(await search(q)); }
finally { setLoading(false); }
}, 300),
[]
[musicLibraryFilterVersion]
);
useEffect(() => { doSearch(query); }, [query, doSearch]);
+73 -40
View File
@@ -10,6 +10,7 @@ import { useAuthStore } from '../store/authStore';
import { useLyricsStore } from '../store/lyricsStore';
import { useDragDrop } from '../contexts/DragDropContext';
import LyricsPane from './LyricsPane';
import { TFunction } from 'i18next';
function formatTime(seconds: number): string {
if (!seconds || isNaN(seconds)) return '0:00';
@@ -153,13 +154,66 @@ function LoadPlaylistModal({ onClose, onLoad }: { onClose: () => void, onLoad: (
);
}
interface QueueHeaderProps {
queue: Track[];
queueIndex: number;
showRemainingTime: boolean;
setShowRemainingTime: React.Dispatch<React.SetStateAction<boolean>>;
activePlaylist: { id: string; name: string } | null;
t: TFunction;
}
function QueueHeader({ queue, queueIndex, showRemainingTime, setShowRemainingTime, activePlaylist, t }: QueueHeaderProps) {
const currentTime = usePlayerStore((s) => s.currentTime);
if (queue.length === 0) return null;
const totalSecs = queue.reduce((acc: number, t: any) => acc + (t.duration || 0), 0);
const remainingSecs = Math.max(0, (queue[queueIndex]?.duration ?? 0) - currentTime + queue.slice(queueIndex + 1).reduce((acc: number, t: any) => acc + (t.duration || 0), 0));
const fmt = (secs: number) => {
const h = Math.floor(secs / 3600);
const m = Math.floor((secs % 3600) / 60);
const s = secs % 60;
return h > 0 ? `${h}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}` : `${m}:${s.toString().padStart(2, "0")}`;
};
const dur = showRemainingTime ? `-${fmt(Math.floor(remainingSecs))}` : fmt(Math.floor(totalSecs));
return (
<div className="queue-header">
<div style={{ display: "flex", flexDirection: "column", minWidth: 0, flex: 1 }}>
<div style={{ display: "flex", alignItems: "baseline", gap: "8px", minWidth: 0 }}>
<h2 style={{ fontSize: "16px", fontWeight: 700, margin: 0, flexShrink: 0 }}>{t("queue.title")}</h2>
<span
onClick={() => setShowRemainingTime((v: boolean) => !v)}
data-tooltip={showRemainingTime ? t("queue.showTotal") : t("queue.showRemaining")}
style={{
fontSize: "13px",
color: "var(--accent)",
whiteSpace: "nowrap",
cursor: "pointer",
userSelect: "none",
}}
>
{queue.length} {queue.length === 1 ? t("queue.trackSingular") : t("queue.trackPlural")} · {dur}
</span>
</div>
{activePlaylist && (
<div className="truncate" style={{ fontSize: "11px", color: "var(--text-muted)", marginTop: "2px", display: "flex", alignItems: "center", gap: "4px" }}>
<ListMusic size={10} style={{ flexShrink: 0 }} />
<span className="truncate">{activePlaylist.name}</span>
</div>
)}
</div>
</div>
);
}
export default function QueuePanel() {
const { t } = useTranslation();
const navigate = useNavigate();
const queue = usePlayerStore(s => s.queue);
const queueIndex = usePlayerStore(s => s.queueIndex);
const currentTrack = usePlayerStore(s => s.currentTrack);
const currentTime = usePlayerStore(s => s.currentTime);
const currentCoverFetchUrl = useMemo(
() => currentTrack?.coverArt ? buildCoverArtUrl(currentTrack.coverArt, 128) : '',
[currentTrack?.coverArt]
@@ -275,6 +329,15 @@ export default function QueuePanel() {
return () => aside.removeEventListener('psy-drop', onPsyDrop);
}, [enqueueAt]);
useEffect(function queueAutoScroll() {
if (!queueListRef.current || queueIndex < 0) return;
if (activeTab !== 'queue') return;
const songs = queueListRef.current!.querySelectorAll<HTMLElement>('[data-queue-idx]');
const nextSong = songs[queueIndex + 1];
if (!nextSong) return;
nextSong.scrollIntoView({ block: "start", behavior: "instant" });
}, [currentTrack, activeTab]);
const [activePlaylist, setActivePlaylist] = useState<{ id: string; name: string } | null>(null);
const [saveState, setSaveState] = useState<'idle' | 'saving' | 'saved'>('idle');
const [saveModalOpen, setSaveModalOpen] = useState(false);
@@ -333,47 +396,17 @@ export default function QueuePanel() {
}
}}
style={{
borderLeftWidth: isQueueVisible ? 1 : 0
borderLeftWidth: isQueueVisible ? 1 : 0,
}}
>
<div className="queue-header">
<div style={{ display: 'flex', flexDirection: 'column', minWidth: 0, flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: '8px', minWidth: 0 }}>
<h2 style={{ fontSize: '16px', fontWeight: 700, margin: 0, flexShrink: 0 }}>{t('queue.title')}</h2>
{queue.length > 0 && (() => {
const totalSecs = queue.reduce((acc, t) => acc + (t.duration || 0), 0);
const remainingSecs = Math.max(0,
(queue[queueIndex]?.duration ?? 0) - currentTime
+ queue.slice(queueIndex + 1).reduce((acc, t) => acc + (t.duration || 0), 0)
);
const fmt = (secs: number) => {
const h = Math.floor(secs / 3600);
const m = Math.floor((secs % 3600) / 60);
const s = secs % 60;
return h > 0
? `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
: `${m}:${s.toString().padStart(2, '0')}`;
};
const dur = showRemainingTime ? `-${fmt(Math.floor(remainingSecs))}` : fmt(Math.floor(totalSecs));
return (
<span
onClick={() => setShowRemainingTime(v => !v)}
data-tooltip={showRemainingTime ? t('queue.showTotal') : t('queue.showRemaining')}
style={{ fontSize: '13px', color: 'var(--accent)', whiteSpace: 'nowrap', cursor: 'pointer', userSelect: 'none' }}
>
{queue.length} {queue.length === 1 ? t('queue.trackSingular') : t('queue.trackPlural')} · {dur}
</span>
);
})()}
</div>
{activePlaylist && (
<div className="truncate" style={{ fontSize: '11px', color: 'var(--text-muted)', marginTop: '2px', display: 'flex', alignItems: 'center', gap: '4px' }}>
<ListMusic size={10} style={{ flexShrink: 0 }} />
<span className="truncate">{activePlaylist.name}</span>
</div>
)}
</div>
</div>
<QueueHeader
queue={queue}
queueIndex={queueIndex}
showRemainingTime={showRemainingTime}
setShowRemainingTime={setShowRemainingTime}
activePlaylist={activePlaylist}
t={t}
/>
{currentTrack && (
<div className="queue-current-track">
+142 -5
View File
@@ -1,4 +1,5 @@
import React from 'react';
import React, { useState, useRef, useLayoutEffect, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { usePlayerStore } from '../store/playerStore';
import { useOfflineStore } from '../store/offlineStore';
import { useAuthStore } from '../store/authStore';
@@ -7,7 +8,8 @@ import { NavLink } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
Disc3, Users, Music4, Radio, Settings, Heart, BarChart3, Shuffle,
PanelLeftClose, PanelLeft, HelpCircle, Dices, AudioLines, HardDriveDownload, Tags, ListMusic, Cast
PanelLeftClose, PanelLeft, HelpCircle, Dices, AudioLines, HardDriveDownload, Tags, ListMusic, Cast,
ChevronDown, Check, Music2,
} from 'lucide-react';
import PsysonicLogo from './PsysonicLogo';
import PSmallLogo from './PSmallLogo';
@@ -44,8 +46,70 @@ export default function Sidebar({
const activeJobs = offlineJobs.filter(j => j.status === 'queued' || j.status === 'downloading');
const offlineAlbums = useOfflineStore(s => s.albums);
const serverId = useAuthStore(s => s.activeServerId ?? '');
const isLoggedIn = useAuthStore(s => s.isLoggedIn);
const musicFolders = useAuthStore(s => s.musicFolders);
const musicLibraryFilterByServer = useAuthStore(s => s.musicLibraryFilterByServer);
const setMusicLibraryFilter = useAuthStore(s => s.setMusicLibraryFilter);
const hasOfflineContent = Object.values(offlineAlbums).some(a => a.serverId === serverId);
const sidebarItems = useSidebarStore(s => s.items);
const [libraryDropdownOpen, setLibraryDropdownOpen] = useState(false);
const [dropdownRect, setDropdownRect] = useState({ top: 0, left: 0, width: 0 });
const libraryTriggerRef = useRef<HTMLButtonElement>(null);
const showLibraryPicker = !isCollapsed && isLoggedIn && musicFolders.length > 1;
const filterId = serverId ? (musicLibraryFilterByServer[serverId] ?? 'all') : 'all';
const selectedFolderName =
filterId === 'all' ? null : musicFolders.find(f => f.id === filterId)?.name ?? null;
const libraryTriggerPlain = filterId === 'all';
const updateDropdownPosition = useCallback(() => {
const el = libraryTriggerRef.current;
if (!el) return;
const r = el.getBoundingClientRect();
setDropdownRect({
top: r.bottom + 4,
left: r.left,
width: r.width,
});
}, []);
useLayoutEffect(() => {
if (!libraryDropdownOpen) return;
updateDropdownPosition();
const onWin = () => updateDropdownPosition();
window.addEventListener('resize', onWin);
window.addEventListener('scroll', onWin, true);
return () => {
window.removeEventListener('resize', onWin);
window.removeEventListener('scroll', onWin, true);
};
}, [libraryDropdownOpen, updateDropdownPosition]);
useEffect(() => {
if (!libraryDropdownOpen) return;
const onDown = (e: MouseEvent) => {
const t = e.target as Node;
if (libraryTriggerRef.current?.contains(t)) return;
const panel = document.querySelector('.nav-library-dropdown-panel');
if (panel?.contains(t)) return;
setLibraryDropdownOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') setLibraryDropdownOpen(false);
};
document.addEventListener('mousedown', onDown);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDown);
document.removeEventListener('keydown', onKey);
};
}, [libraryDropdownOpen]);
const pickLibrary = (id: 'all' | string) => {
setMusicLibraryFilter(id);
setLibraryDropdownOpen(false);
};
// Resolve ordered, visible items per section from store config
const visibleLibrary = sidebarItems
.filter(cfg => cfg.visible && ALL_NAV_ITEMS[cfg.id]?.section === 'library')
@@ -73,8 +137,81 @@ export default function Sidebar({
{isCollapsed ? <PanelLeft size={14} /> : <PanelLeftClose size={14} />}
</button>
<nav className="sidebar-nav" aria-label="Hauptnavigation">
{!isCollapsed && <span className="nav-section-label">{t('sidebar.library')}</span>}
<nav className="sidebar-nav" aria-label="Main navigation">
{!isCollapsed && (showLibraryPicker ? (
<>
<button
ref={libraryTriggerRef}
type="button"
className={`nav-library-scope-trigger ${libraryTriggerPlain ? 'nav-library-scope-trigger--plain' : ''} ${libraryDropdownOpen ? 'nav-library-scope-trigger--open' : ''}`}
onClick={() => {
setLibraryDropdownOpen(o => !o);
}}
aria-label={t('sidebar.libraryScope')}
aria-expanded={libraryDropdownOpen}
aria-haspopup="listbox"
data-tooltip={libraryDropdownOpen ? undefined : t('sidebar.libraryScope')}
data-tooltip-pos="bottom"
>
{!libraryTriggerPlain ? (
<Music2 size={16} className="nav-library-scope-icon" strokeWidth={2} aria-hidden />
) : null}
<div className="nav-library-scope-text">
<span className="nav-library-scope-title">{t('sidebar.library')}</span>
{selectedFolderName ? (
<span className="nav-library-scope-subtitle" data-tooltip={selectedFolderName} data-tooltip-pos="right">
{selectedFolderName}
</span>
) : null}
</div>
<ChevronDown size={16} strokeWidth={2.25} className="nav-library-scope-chevron" aria-hidden />
</button>
{libraryDropdownOpen &&
createPortal(
<div
className={`nav-library-dropdown-panel${musicFolders.length > 10 ? ' nav-library-dropdown-panel--many-libraries' : ''}`}
role="listbox"
aria-label={t('sidebar.libraryScope')}
style={{
position: 'fixed',
top: dropdownRect.top,
left: dropdownRect.left,
width: dropdownRect.width,
minWidth: dropdownRect.width,
maxWidth: dropdownRect.width,
boxSizing: 'border-box',
}}
>
<button
type="button"
role="option"
aria-selected={filterId === 'all'}
className={`nav-library-dropdown-item ${filterId === 'all' ? 'nav-library-dropdown-item--selected' : ''}`}
onClick={() => pickLibrary('all')}
>
<span className="nav-library-dropdown-item-label">{t('sidebar.allLibraries')}</span>
{filterId === 'all' ? <Check size={16} className="nav-library-dropdown-check" strokeWidth={2.5} /> : <span className="nav-library-dropdown-check-spacer" />}
</button>
{musicFolders.map(f => (
<button
key={f.id}
type="button"
role="option"
aria-selected={filterId === f.id}
className={`nav-library-dropdown-item ${filterId === f.id ? 'nav-library-dropdown-item--selected' : ''}`}
onClick={() => pickLibrary(f.id)}
>
<span className="nav-library-dropdown-item-label">{f.name}</span>
{filterId === f.id ? <Check size={16} className="nav-library-dropdown-check" strokeWidth={2.5} /> : <span className="nav-library-dropdown-check-spacer" />}
</button>
))}
</div>,
document.body
)}
</>
) : (
<span className="nav-section-label">{t('sidebar.library')}</span>
))}
{visibleLibrary.map(item => (
<NavLink
key={item.to}
@@ -117,7 +254,7 @@ export default function Sidebar({
)}
{visibleSystem.length > 0 && !isCollapsed && <span className="nav-section-label">{t('sidebar.system')}</span>}
{visibleSystem.map(item => (
{visibleSystem.map(item => (
<NavLink
key={item.to}
to={item.to}
+7
View File
@@ -42,9 +42,13 @@ const THEME_GROUPS: { group: string; themes: ThemeDef[] }[] = [
group: 'Open Source Classics',
themes: [
{ id: 'nord-aurora', label: 'Aurora', bg: '#3b4252', card: '#434c5e', accent: '#b48ead' },
{ id: 'carbonfox', label: 'Carbonfox', bg: '#161616', card: '#1c1c1c', accent: '#be95ff' },
{ id: 'gruvbox-dark-hard', label: 'Dark Hard', bg: '#1d2021', card: '#3c3836', accent: '#fabd2f' },
{ id: 'gruvbox-dark-medium', label: 'Dark Medium', bg: '#282828', card: '#3c3836', accent: '#fabd2f' },
{ id: 'gruvbox-dark-soft', label: 'Dark Soft', bg: '#32302f', card: '#45403d', accent: '#fabd2f' },
{ id: 'dawnfox', label: 'Dawnfox', bg: '#faf4ed', card: '#ebe0df', accent: '#907aa9' },
{ id: 'dayfox', label: 'Dayfox', bg: '#f6f2ee', card: '#dbd1dd', accent: '#2848a9' },
{ id: 'duskfox', label: 'Duskfox', bg: '#232136', card: '#2d2a45', accent: '#c4a7e7' },
{ id: 'frappe', label: 'Frappé', bg: '#303446', card: '#414559', accent: '#ca9ee6' },
{ id: 'nord-frost', label: 'Frost', bg: '#1e2d3d', card: '#243447', accent: '#88c0d0' },
{ id: 'latte', label: 'Latte', bg: '#eff1f5', card: '#ccd0da', accent: '#8839ef' },
@@ -53,8 +57,11 @@ const THEME_GROUPS: { group: string; themes: ThemeDef[] }[] = [
{ id: 'gruvbox-light-soft', label: 'Light Soft', bg: '#f2e5bc', card: '#ebdbb2', accent: '#b57614' },
{ id: 'macchiato', label: 'Macchiato', bg: '#24273a', card: '#363a4f', accent: '#c6a0f6' },
{ id: 'mocha', label: 'Mocha', bg: '#1e1e2e', card: '#313244', accent: '#cba6f7' },
{ id: 'nightfox', label: 'Nightfox', bg: '#192330', card: '#212e3f', accent: '#719cd6' },
{ id: 'nordfox', label: 'Nordfox', bg: '#2e3440', card: '#39404f', accent: '#81a1c1' },
{ id: 'nord', label: 'Polar Night', bg: '#3b4252', card: '#434c5e', accent: '#88c0d0' },
{ id: 'nord-snowstorm', label: 'Snowstorm', bg: '#e5e9f0', card: '#eceff4', accent: '#5e81ac' },
{ id: 'terafox', label: 'Terafox', bg: '#152528', card: '#1d3337', accent: '#a1cdd8' },
],
},
{
+7
View File
@@ -35,13 +35,20 @@ export default function TooltipPortal() {
const target = (e.target as HTMLElement).closest('[data-tooltip]');
if (!target) setTooltip(null);
};
/** Clicking a tooltip anchor (e.g. opening a dropdown) keeps the cursor inside the element, so mouseout never runs — hide immediately. */
const onDown = (e: MouseEvent) => {
const t = (e.target as HTMLElement).closest('[data-tooltip]');
if (t) setTooltip(null);
};
document.addEventListener('mouseover', onOver);
document.addEventListener('mouseout', onOut);
document.addEventListener('mousemove', onMove, { passive: true });
document.addEventListener('mousedown', onDown, true);
return () => {
document.removeEventListener('mouseover', onOver);
document.removeEventListener('mouseout', onOut);
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mousedown', onDown, true);
};
}, []);
+125
View File
@@ -0,0 +1,125 @@
import { useEffect, useState } from 'react';
import { fetchLyrics, parseLrc, LrcLine } from '../api/lrclib';
import { getLyricsBySongId, SubsonicStructuredLyrics } from '../api/subsonic';
import { useAuthStore } from '../store/authStore';
import type { Track } from '../store/playerStore';
export type LyricsSource = 'server' | 'lrclib';
export interface CachedLyrics {
syncedLines: LrcLine[] | null;
plainLyrics: string | null;
source: LyricsSource | null;
notFound: boolean;
}
// Session-level cache — survives tab switches and component unmount/remount.
export const lyricsCache = new Map<string, CachedLyrics>();
/** Convert structured Subsonic lyrics (ms timestamps) into LrcLine[] or plain text. */
export function parseStructuredLyrics(
lyrics: SubsonicStructuredLyrics,
): Pick<CachedLyrics, 'syncedLines' | 'plainLyrics'> {
if (lyrics.issynced && lyrics.line.length > 0) {
const lines: LrcLine[] = lyrics.line
.filter(l => l.start !== undefined)
.map(l => ({ time: l.start! / 1000, text: l.value.trim() }))
.sort((a, b) => a.time - b.time);
if (lines.length > 0) return { syncedLines: lines, plainLyrics: null };
}
const plain = lyrics.line.map(l => l.value).join('\n').trim();
return { syncedLines: null, plainLyrics: plain || null };
}
export interface UseLyricsResult {
syncedLines: LrcLine[] | null;
plainLyrics: string | null;
source: LyricsSource | null;
loading: boolean;
notFound: boolean;
}
export function useLyrics(currentTrack: Track | null): UseLyricsResult {
const cached = currentTrack ? lyricsCache.get(currentTrack.id) : undefined;
const lyricsServerFirst = useAuthStore(s => s.lyricsServerFirst);
const [loading, setLoading] = useState(!cached && !!currentTrack);
const [syncedLines, setSyncedLines] = useState<LrcLine[] | null>(cached?.syncedLines ?? null);
const [plainLyrics, setPlainLyrics] = useState<string | null>(cached?.plainLyrics ?? null);
const [source, setSource] = useState<LyricsSource | null>(cached?.source ?? null);
const [notFound, setNotFound] = useState(cached?.notFound ?? false);
useEffect(() => {
if (!currentTrack) return;
const hit = lyricsCache.get(currentTrack.id);
if (hit) {
setSyncedLines(hit.syncedLines);
setPlainLyrics(hit.plainLyrics);
setSource(hit.source);
setNotFound(hit.notFound);
setLoading(false);
return;
}
let cancelled = false;
setSyncedLines(null);
setPlainLyrics(null);
setSource(null);
setNotFound(false);
setLoading(true);
const store = (entry: CachedLyrics) => {
if (cancelled) return;
lyricsCache.set(currentTrack.id, entry);
setSyncedLines(entry.syncedLines);
setPlainLyrics(entry.plainLyrics);
setSource(entry.source);
setNotFound(entry.notFound);
setLoading(false);
};
const fetchServer = async (): Promise<boolean> => {
const structured = await getLyricsBySongId(currentTrack.id);
if (!structured) return false;
const parsed = parseStructuredLyrics(structured);
if (!parsed.syncedLines && !parsed.plainLyrics) return false;
store({ ...parsed, source: 'server', notFound: false });
return true;
};
const fetchLrclibFn = async (): Promise<boolean> => {
try {
const result = await fetchLyrics(
currentTrack.artist ?? '',
currentTrack.title,
currentTrack.album ?? '',
currentTrack.duration ?? 0,
);
if (!result || (!result.syncedLyrics && !result.plainLyrics)) return false;
const lines = result.syncedLyrics ? parseLrc(result.syncedLyrics) : null;
const synced = lines && lines.length > 0 ? lines : null;
store({ syncedLines: synced, plainLyrics: result.plainLyrics, source: 'lrclib', notFound: false });
return true;
} catch {
return false;
}
};
(async () => {
const [first, second] = lyricsServerFirst
? [fetchServer, fetchLrclibFn]
: [fetchLrclibFn, fetchServer];
if (cancelled) return;
if (await first()) return;
if (cancelled) return;
if (await second()) return;
if (!cancelled) store({ syncedLines: null, plainLyrics: null, source: null, notFound: true });
})();
return () => { cancelled = true; };
}, [currentTrack?.id]); // eslint-disable-line react-hooks/exhaustive-deps
return { syncedLines, plainLyrics, source, loading, notFound };
}
+184
View File
@@ -0,0 +1,184 @@
import { invoke } from '@tauri-apps/api/core';
import { buildStreamUrl } from './api/subsonic';
import { useAuthStore } from './store/authStore';
import { useHotCacheStore } from './store/hotCacheStore';
import { useOfflineStore } from './store/offlineStore';
import { usePlayerStore } from './store/playerStore';
import { getDeferHotCachePrefetch } from './utils/hotCacheGate';
const PREFETCH_AHEAD = 5;
type PrefetchJob = { trackId: string; serverId: string; suffix: string };
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
const pendingQueue: PrefetchJob[] = [];
let workerRunning = false;
function debounceMs(): number {
const s = useAuthStore.getState().hotCacheDebounceSec;
if (!Number.isFinite(s) || s < 0) return 0;
return Math.min(600, s) * 1000;
}
function enqueueJobs(jobs: PrefetchJob[]) {
const seen = new Set(pendingQueue.map(j => `${j.serverId}:${j.trackId}`));
for (const j of jobs) {
const k = `${j.serverId}:${j.trackId}`;
if (seen.has(k)) continue;
seen.add(k);
pendingQueue.push(j);
}
void runWorker();
}
async function runWorker() {
if (workerRunning) return;
workerRunning = true;
try {
while (pendingQueue.length > 0) {
const auth = useAuthStore.getState();
if (!auth.isLoggedIn || !auth.hotCacheEnabled || !auth.activeServerId) {
pendingQueue.length = 0;
break;
}
while (getDeferHotCachePrefetch()) {
await new Promise(r => setTimeout(r, 150));
}
const job = pendingQueue.shift();
if (!job) break;
const maxBytes = Math.max(0, auth.hotCacheMaxMb) * 1024 * 1024;
if (maxBytes <= 0) continue;
const offline = useOfflineStore.getState();
if (offline.isDownloaded(job.trackId, job.serverId)) continue;
if (useHotCacheStore.getState().entries[entryKey(job.serverId, job.trackId)]) continue;
const { queue, queueIndex } = usePlayerStore.getState();
const wantIds = new Set(
queue
.slice(queueIndex + 1, queueIndex + 1 + PREFETCH_AHEAD)
.map(t => t.id),
);
if (!wantIds.has(job.trackId)) continue;
const url = buildStreamUrl(job.trackId);
try {
const customDir = auth.hotCacheDownloadDir || null;
const res = await invoke<{ path: string; size: number }>('download_track_hot_cache', {
trackId: job.trackId,
serverId: job.serverId,
url,
suffix: job.suffix,
customDir,
});
useHotCacheStore.getState().setEntry(job.trackId, job.serverId, res.path, res.size);
const fresh = usePlayerStore.getState();
await useHotCacheStore.getState().evictToFit(
fresh.queue,
fresh.queueIndex,
maxBytes,
auth.activeServerId,
customDir,
);
} catch {
/* network / HTTP — skip */
}
}
} finally {
workerRunning = false;
if (pendingQueue.length > 0) void runWorker();
}
}
function entryKey(serverId: string, trackId: string): string {
return `${serverId}:${trackId}`;
}
function scheduleReplan() {
const auth = useAuthStore.getState();
if (!auth.isLoggedIn || !auth.hotCacheEnabled || !auth.activeServerId) {
if (debounceTimer) {
clearTimeout(debounceTimer);
debounceTimer = null;
}
return;
}
if (debounceTimer) clearTimeout(debounceTimer);
const ms = debounceMs();
debounceTimer = setTimeout(() => {
debounceTimer = null;
void replanNow();
}, ms);
}
async function replanNow() {
const auth = useAuthStore.getState();
if (!auth.isLoggedIn || !auth.hotCacheEnabled || !auth.activeServerId) return;
const serverId = auth.activeServerId;
const maxBytes = Math.max(0, auth.hotCacheMaxMb) * 1024 * 1024;
const customDir = auth.hotCacheDownloadDir || null;
if (maxBytes <= 0) return;
const { queue, queueIndex, currentRadio } = usePlayerStore.getState();
if (currentRadio) return;
const offline = useOfflineStore.getState();
const hot = useHotCacheStore.getState();
await hot.evictToFit(queue, queueIndex, maxBytes, serverId, customDir);
const targets = queue.slice(queueIndex + 1, queueIndex + 1 + PREFETCH_AHEAD);
const jobs: PrefetchJob[] = [];
for (const t of targets) {
if (offline.isDownloaded(t.id, serverId)) continue;
if (hot.entries[entryKey(serverId, t.id)]) continue;
jobs.push({
trackId: t.id,
serverId,
suffix: t.suffix || 'mp3',
});
}
enqueueJobs(jobs);
}
/**
* Subscribe to queue/auth changes and run debounced prefetch.
* Call once from the app shell.
*/
export function initHotCachePrefetch(): () => void {
let lastQueueRef: unknown = null;
let lastQueueIndex = -1;
const unsubPlayer = usePlayerStore.subscribe(state => {
const q = state.queue;
const i = state.queueIndex;
if (q === lastQueueRef && i === lastQueueIndex) return;
const onlyIndexMoved = q === lastQueueRef && i !== lastQueueIndex;
lastQueueRef = q;
lastQueueIndex = i;
if (onlyIndexMoved) void replanNow();
else scheduleReplan();
});
let lastAuthSig = '';
const unsubAuth = useAuthStore.subscribe(state => {
const sig = `${state.hotCacheEnabled}:${state.hotCacheDebounceSec}:${state.hotCacheMaxMb}:${state.hotCacheDownloadDir ?? ''}:${state.activeServerId ?? ''}:${state.isLoggedIn}`;
if (sig === lastAuthSig) return;
lastAuthSig = sig;
if (state.hotCacheEnabled && state.isLoggedIn) scheduleReplan();
});
void replanNow();
return () => {
unsubPlayer();
unsubAuth();
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = null;
pendingQueue.length = 0;
};
}
-2
View File
@@ -6,7 +6,6 @@ import { frTranslation } from './locales/fr';
import { nbTranslation } from './locales/nb';
import { nlTranslation } from './locales/nl';
import { ruTranslation } from './locales/ru';
import { ru2Translation } from './locales/ru2';
import { zhTranslation } from './locales/zh';
const savedLanguage = localStorage.getItem('psysonic_language') || 'en';
@@ -22,7 +21,6 @@ i18n
zh: { translation: zhTranslation },
nb: { translation: nbTranslation },
ru: { translation: ruTranslation },
ru2: { translation: ru2Translation },
},
lng: savedLanguage,
fallbackLng: 'en',
+28 -11
View File
@@ -15,14 +15,13 @@ export const deTranslation = {
help: 'Hilfe',
expand: 'Sidebar einblenden',
collapse: 'Sidebar ausblenden',
updateAvailable: 'Update verfügbar',
updateReady: '{{version}} ist bereit',
updateLink: 'Zum Release →',
downloadingTracks: '{{n}} Tracks werden gecacht…',
offlineLibrary: 'Offline-Bibliothek',
genres: 'Genres',
playlists: 'Playlists',
radio: 'Internetradio',
libraryScope: 'Bibliotheksumfang',
allLibraries: 'Alle Bibliotheken',
},
home: {
hero: 'Featured',
@@ -328,12 +327,8 @@ export const deTranslation = {
bulkRemoveFromPlaylist: 'Aus Playlist entfernen',
bulkClear: 'Auswahl aufheben',
updaterAvailable: 'Update verfügbar',
updaterVersion: 'v{{version}} ist bereit',
updaterInstall: 'Installieren & Neustart',
updaterDownloading: 'Wird geladen…',
updaterInstalling: 'Wird installiert…',
updaterDownload: 'Von GitHub herunterladen',
updaterExperimentalHint: 'Automatische Updates sind noch in Entwicklung',
updaterVersion: 'v{{version}} verfügbar',
updaterWebsite: 'Website',
},
settings: {
title: 'Einstellungen',
@@ -345,7 +340,6 @@ export const deTranslation = {
languageZh: 'Chinesisch',
languageNb: 'Norwegisch',
languageRu: 'Russisch',
languageRu2: 'Russisch 2',
font: 'Schriftart',
theme: 'Design',
appearance: 'Darstellung',
@@ -405,6 +399,8 @@ export const deTranslation = {
cacheDesc: 'Cover und Künstlerbilder. Wenn voll, werden die ältesten Einträge automatisch entfernt. Offline-Alben werden nicht automatisch gelöscht, aber beim manuellen Cache leeren entfernt.',
cacheUsedImages: 'Bilder:',
cacheUsedOffline: 'Offline-Tracks:',
cacheUsedHot: 'Belegter Speicher:',
hotCacheTrackCount: 'Titel im Cache:',
cacheMaxLabel: 'Max. Größe',
cacheClearBtn: 'Cache leeren',
cacheClearWarning: 'Alle Offline-Alben werden damit aus der Bibliothek entfernt.',
@@ -416,6 +412,22 @@ export const deTranslation = {
offlineDirChange: 'Verzeichnis ändern',
offlineDirClear: 'Auf Standard zurücksetzen',
offlineDirHint: 'Neue Downloads werden an diesem Ort gespeichert. Bestehende Downloads verbleiben am ursprünglichen Pfad.',
hotCacheTitle: 'Hot-Playback-Cache',
hotCacheAlphaBadge: 'Alpha',
hotCacheDisclaimer: 'Lädt kommende Warteschlangen-Titel vor und behält zuletzt gespielte. Bei aktivierter Option: Speicherplatz und Netzwerk.',
hotCacheDirDefault: 'Standard (App-Daten)',
hotCacheDirChange: 'Ordner ändern',
hotCacheDirClear: 'Auf Standard zurücksetzen',
hotCacheDirHint: 'Beim Ordnerwechsel wird der App-Index zurückgesetzt; alte Dateien bleiben am alten Ort, bis Sie sie löschen.',
hotCacheEnabled: 'Hot-Playback-Cache aktivieren',
hotCacheMaxMb: 'Maximale Cache-Größe',
hotCacheDebounce: 'Debounce bei Warteschlangen-Änderungen',
hotCacheDebounceImmediate: 'Sofort',
hotCacheDebounceSeconds: '{{n}} s',
hotCacheClearBtn: 'Hot-Cache leeren',
hiResTitle: 'Native Hi-Res-Wiedergabe',
hiResEnabled: 'Native Hi-Res-Wiedergabe aktivieren',
hiResDesc: "Standardmäßig wird auf 44,1 kHz begrenzt (maximale Stabilität). Nur aktivieren, wenn Hardware und Netzwerk zuverlässig hohe Abtastraten (88,2 kHz+) unterstützen.",
showArtistImages: 'Künstlerbilder anzeigen',
showArtistImagesDesc: 'Lädt und zeigt Künstlerbilder in der Künstlerübersicht. Standardmäßig deaktiviert, um Server-I/O und Netzwerklast bei großen Bibliotheken zu reduzieren.',
showTrayIcon: 'Tray-Icon anzeigen',
@@ -426,6 +438,8 @@ export const deTranslation = {
discordRichPresenceDesc: 'Zeigt den aktuell gespielten Titel im Discord-Profil an. Discord muss dafür geöffnet sein.',
nowPlayingEnabled: 'Im Livefenster anzeigen',
nowPlayingEnabledDesc: 'Überträgt den aktuell gespielten Titel an die Livehörer-Ansicht des Servers. Deaktivieren, um keine Wiedergabedaten zu senden.',
lyricsServerFirst: 'Server-Lyrics bevorzugen',
lyricsServerFirstDesc: 'Server-seitige Lyrics (eingebettete Tags, Sidecar-Dateien) vor LRCLIB abfragen. Deaktivieren, um LRCLIB zuerst zu verwenden.',
downloadsTitle: 'ZIP-Export & Archivierung',
downloadsFolderDesc: 'Zielverzeichnis für Alben, die du als ZIP-Datei auf deinen Computer herunterlädst.',
downloadsDefault: 'Standard-Downloads-Ordner',
@@ -548,7 +562,7 @@ export const deTranslation = {
a11: 'Das Banner oben auf der Startseite wählt zufällige Alben aus der Bibliothek und rotiert alle 10 Sekunden weiter. Mit den Punkten kann man manuell springen, Klick auf das Banner öffnet das Album.',
s4: 'Einstellungen',
q12: 'Wie ändere ich das Theme?',
a12: 'Einstellungen → Design. Eine große Auswahl an Themes in 8 Gruppen: Psysonic Themes, Mediaplayer, Betriebssysteme, Spiele, Filme, Serien, Social Media und Open-Source-Classics (Catppuccin, Nord, Gruvbox).',
a12: 'Einstellungen → Design. Eine große Auswahl an Themes in 8 Gruppen: Psysonic Themes, Mediaplayer, Betriebssysteme, Spiele, Filme, Serien, Social Media und Open-Source-Classics (Catppuccin, Nord, Gruvbox, Nightfox).',
q13: 'Wie ändere ich die Sprache?',
a13: 'Einstellungen → Sprache. Englisch, Deutsch, Französisch, Niederländisch und Chinesisch werden unterstützt.',
q15: 'Wie lege ich einen Download-Ordner fest?',
@@ -689,8 +703,11 @@ export const deTranslation = {
volume: 'Lautstärke',
toggleQueue: 'Warteschlange umschalten',
lyrics: 'Lyrics',
fsLyricsToggle: 'Lyrics im Vollbild',
lyricsLoading: 'Lyrics werden geladen…',
lyricsNotFound: 'Keine Lyrics für diesen Titel gefunden',
lyricsSourceServer: 'Quelle: Server',
lyricsSourceLrclib: 'Quelle: LRCLIB',
},
songInfo: {
title: 'Song-Infos',
+29 -11
View File
@@ -15,14 +15,14 @@ export const enTranslation = {
help: 'Help',
expand: 'Expand Sidebar',
collapse: 'Collapse Sidebar',
updateAvailable: 'Update available',
updateReady: '{{version}} is ready',
updateLink: 'Go to release →',
downloadingTracks: 'Caching {{n}} tracks…',
offlineLibrary: 'Offline Library',
genres: 'Genres',
playlists: 'Playlists',
radio: 'Internet Radio',
libraryScope: 'Library scope',
allLibraries: 'All libraries',
},
home: {
hero: 'Featured',
@@ -328,12 +328,8 @@ export const enTranslation = {
bulkRemoveFromPlaylist: 'Remove from Playlist',
bulkClear: 'Clear selection',
updaterAvailable: 'Update available',
updaterVersion: 'v{{version}} is ready',
updaterInstall: 'Install & Restart',
updaterDownloading: 'Downloading…',
updaterInstalling: 'Installing…',
updaterDownload: 'Download from GitHub',
updaterExperimentalHint: 'Auto-update is still in development',
updaterVersion: 'v{{version}} is available',
updaterWebsite: 'Website',
},
settings: {
title: 'Settings',
@@ -345,7 +341,6 @@ export const enTranslation = {
languageZh: 'Chinese',
languageNb: 'Norwegian',
languageRu: 'Russian',
languageRu2: 'Russian 2',
font: 'Font',
theme: 'Theme',
appearance: 'Appearance',
@@ -405,6 +400,8 @@ export const enTranslation = {
cacheDesc: 'Cover art and artist images. When full, the oldest entries are removed automatically. Offline albums are not auto-removed, but will be deleted when clearing the cache manually.',
cacheUsedImages: 'Images:',
cacheUsedOffline: 'Offline tracks:',
cacheUsedHot: 'Size on disk:',
hotCacheTrackCount: 'Tracks in cache:',
cacheMaxLabel: 'Max. size',
cacheClearBtn: 'Clear Cache',
cacheClearWarning: 'This will also remove all offline albums from the library.',
@@ -416,6 +413,22 @@ export const enTranslation = {
offlineDirChange: 'Change Directory',
offlineDirClear: 'Reset to Default',
offlineDirHint: 'New downloads will use this location. Existing downloads remain at their original path.',
hotCacheTitle: 'Hot playback cache',
hotCacheAlphaBadge: 'Alpha',
hotCacheDisclaimer: 'Preloads upcoming queue tracks and keeps previous ones. When enabled, uses disk space and network.',
hotCacheDirDefault: 'Default (App Data)',
hotCacheDirChange: 'Change folder',
hotCacheDirClear: 'Reset to default',
hotCacheDirHint: 'Changing the folder resets the in-app index; files already on disk stay where they are until you remove them.',
hotCacheEnabled: 'Enable hot playback cache',
hotCacheMaxMb: 'Maximum cache size',
hotCacheDebounce: 'Queue change debounce',
hotCacheDebounceImmediate: 'Immediate',
hotCacheDebounceSeconds: '{{n}} s',
hotCacheClearBtn: 'Clear hot cache',
hiResTitle: 'Native Hi-Res Playback',
hiResEnabled: 'Enable native hi-res playback',
hiResDesc: "Forces 44.1 kHz output by default for maximum stability. Enable only if your hardware and network reliably support high sample rates (88.2 kHz+).",
showArtistImages: 'Show Artist Images',
showArtistImagesDesc: 'Load and display artist images in the Artists overview. Disabled by default to reduce server disk I/O and network load on large libraries.',
showTrayIcon: 'Show Tray Icon',
@@ -426,6 +439,8 @@ export const enTranslation = {
discordRichPresenceDesc: 'Show the currently playing track on your Discord profile. Requires Discord to be running.',
nowPlayingEnabled: 'Show in Now Playing',
nowPlayingEnabledDesc: 'Broadcast your currently playing track to the server\'s live listener view. Disable to stop sending playback data.',
lyricsServerFirst: 'Prefer server lyrics',
lyricsServerFirstDesc: 'Check server-provided lyrics (embedded tags, sidecar files) before querying LRCLIB. Disable to use LRCLIB first.',
downloadsTitle: 'ZIP Export & Archiving',
downloadsFolderDesc: 'Destination folder for albums you download as a ZIP file to your computer.',
downloadsDefault: 'Default Downloads Folder',
@@ -548,7 +563,7 @@ export const enTranslation = {
a11: 'The banner at the top of the home page randomly picks albums from your library and rotates through them every 10 seconds. Click the dots to jump to a specific one, or click the banner to open the album.',
s4: 'Settings',
q12: 'How do I change the theme?',
a12: 'Settings → Theme. Choose from a large selection of themes across 8 groups: Psysonic Themes, Mediaplayer, Operating Systems, Games, Movies, Series, Social Media, and Open Source Classics (Catppuccin, Nord, Gruvbox).',
a12: 'Settings → Theme. Choose from a large selection of themes across 8 groups: Psysonic Themes, Mediaplayer, Operating Systems, Games, Movies, Series, Social Media, and Open Source Classics (Catppuccin, Nord, Gruvbox, Nightfox).',
q13: 'How do I change the language?',
a13: 'Settings → Language. English, German, French, Dutch, Chinese, Norwegian, and Russian are supported.',
q15: 'How do I set a download folder?',
@@ -689,8 +704,11 @@ export const enTranslation = {
volume: 'Volume',
toggleQueue: 'Toggle Queue',
lyrics: 'Lyrics',
fsLyricsToggle: 'Lyrics in fullscreen',
lyricsLoading: 'Loading lyrics…',
lyricsNotFound: 'No lyrics found for this track',
lyricsSourceServer: 'Source: Server',
lyricsSourceLrclib: 'Source: LRCLIB',
},
songInfo: {
title: 'Song Info',
+28 -11
View File
@@ -15,14 +15,13 @@ export const frTranslation = {
help: 'Aide',
expand: 'Développer la barre latérale',
collapse: 'Réduire la barre latérale',
updateAvailable: 'Mise à jour disponible',
updateReady: '{{version}} est prêt',
updateLink: 'Voir la version →',
downloadingTracks: '{{n}} pistes en cache…',
offlineLibrary: 'Bibliothèque hors ligne',
genres: 'Genres',
playlists: 'Playlists',
radio: 'Radio Internet',
libraryScope: 'Portée de la bibliothèque',
allLibraries: 'Toutes les bibliothèques',
},
home: {
hero: 'En vedette',
@@ -328,12 +327,8 @@ export const frTranslation = {
bulkRemoveFromPlaylist: 'Retirer de la playlist',
bulkClear: 'Désélectionner',
updaterAvailable: 'Mise à jour disponible',
updaterVersion: 'v{{version}} est prête',
updaterInstall: 'Installer & Redémarrer',
updaterDownloading: 'Téléchargement…',
updaterInstalling: 'Installation…',
updaterDownload: 'Télécharger depuis GitHub',
updaterExperimentalHint: 'La mise à jour automatique est encore en développement',
updaterVersion: 'v{{version}} est disponible',
updaterWebsite: 'Site Web',
},
settings: {
title: 'Paramètres',
@@ -345,7 +340,6 @@ export const frTranslation = {
languageZh: 'Chinois',
languageNb: 'Norvégien',
languageRu: 'Russe',
languageRu2: 'Russe 2',
font: 'Police',
theme: 'Thème',
appearance: 'Apparence',
@@ -405,6 +399,8 @@ export const frTranslation = {
cacheDesc: 'Pochettes et images d\'artistes. Quand le cache est plein, les entrées les plus anciennes sont supprimées automatiquement. Les albums hors ligne ne sont pas supprimés automatiquement, mais le seront lors d\'un nettoyage manuel.',
cacheUsedImages: 'Images :',
cacheUsedOffline: 'Pistes hors ligne :',
cacheUsedHot: 'Espace disque :',
hotCacheTrackCount: 'Pistes en cache :',
cacheMaxLabel: 'Taille max.',
cacheClearBtn: 'Vider le cache',
cacheClearWarning: 'Cela supprimera aussi tous les albums hors ligne de la bibliothèque.',
@@ -416,6 +412,22 @@ export const frTranslation = {
offlineDirChange: 'Changer le dossier',
offlineDirClear: 'Réinitialiser',
offlineDirHint: 'Les nouveaux téléchargements utiliseront cet emplacement. Les téléchargements existants restent à leur emplacement d\'origine.',
hotCacheTitle: 'Cache de lecture à chaud',
hotCacheAlphaBadge: 'Alpha',
hotCacheDisclaimer: 'Précharge les titres à venir dans la file et conserve les précédents. Si activé : espace disque et réseau.',
hotCacheDirDefault: 'Par défaut (données d\'application)',
hotCacheDirChange: 'Changer le dossier',
hotCacheDirClear: 'Réinitialiser',
hotCacheDirHint: 'Changer de dossier réinitialise lindex dans lapp ; les fichiers déjà écrits restent à lancien emplacement.',
hotCacheEnabled: 'Activer le cache de lecture à chaud',
hotCacheMaxMb: 'Taille maximale du cache',
hotCacheDebounce: 'Délai après changement de file',
hotCacheDebounceImmediate: 'Immédiat',
hotCacheDebounceSeconds: '{{n}} s',
hotCacheClearBtn: 'Vider le cache à chaud',
hiResTitle: 'Lecture haute résolution native',
hiResEnabled: 'Activer la lecture haute résolution native',
hiResDesc: "Force une sortie à 44,1 kHz par défaut pour une stabilité maximale. N'activer que si le matériel et le réseau prennent en charge les hautes fréquences d'échantillonnage (88,2 kHz+).",
showArtistImages: 'Afficher les images d\'artistes',
showArtistImagesDesc: 'Charge et affiche les images d\'artistes dans la vue d\'ensemble. Désactivé par défaut pour réduire les E/S disque serveur et la charge réseau sur les grandes bibliothèques.',
showTrayIcon: 'Afficher l\'icône dans la barre système',
@@ -426,6 +438,8 @@ export const frTranslation = {
discordRichPresenceDesc: 'Affiche le titre en cours de lecture sur votre profil Discord. Discord doit être ouvert.',
nowPlayingEnabled: 'Afficher dans la fenêtre live',
nowPlayingEnabledDesc: 'Diffuse le titre en cours de lecture vers la vue des auditeurs en direct du serveur. Désactiver pour ne pas envoyer de données de lecture.',
lyricsServerFirst: 'Préférer les paroles du serveur',
lyricsServerFirstDesc: 'Consulter d\'abord les paroles fournies par le serveur (tags intégrés, fichiers sidecar) avant LRCLIB. Désactiver pour utiliser LRCLIB en priorité.',
downloadsTitle: 'Export ZIP & Archivage',
downloadsFolderDesc: 'Dossier de destination pour les albums téléchargés en tant que fichier ZIP sur votre ordinateur.',
downloadsDefault: 'Dossier de téléchargement par défaut',
@@ -548,7 +562,7 @@ export const frTranslation = {
a11: 'La bannière en haut de la page d\'accueil sélectionne aléatoirement des albums de votre bibliothèque et les fait défiler toutes les 10 secondes. Cliquez sur les points pour accéder à un album spécifique.',
s4: 'Paramètres',
q12: 'Comment changer le thème ?',
a12: 'Paramètres → Thème. Un grand choix de thèmes en 8 groupes : Psysonic Themes, Mediaplayer, Systèmes d\'exploitation, Jeux, Films, Séries, Réseaux sociaux et Open Source Classics (Catppuccin, Nord, Gruvbox).',
a12: 'Paramètres → Thème. Un grand choix de thèmes en 8 groupes : Psysonic Themes, Mediaplayer, Systèmes d\'exploitation, Jeux, Films, Séries, Réseaux sociaux et Open Source Classics (Catppuccin, Nord, Gruvbox, Nightfox).',
q13: 'Comment changer la langue ?',
a13: 'Paramètres → Langue. L\'anglais, l\'allemand, le français, le néerlandais et le chinois sont pris en charge.',
q15: 'Comment définir un dossier de téléchargement ?',
@@ -689,8 +703,11 @@ export const frTranslation = {
volume: 'Volume',
toggleQueue: 'Afficher/masquer la file',
lyrics: 'Paroles',
fsLyricsToggle: 'Paroles en plein écran',
lyricsLoading: 'Chargement des paroles…',
lyricsNotFound: 'Aucune parole trouvée pour ce titre',
lyricsSourceServer: 'Source : Serveur',
lyricsSourceLrclib: 'Source : LRCLIB',
},
songInfo: {
title: 'Infos du morceau',
+27 -10
View File
@@ -15,14 +15,13 @@ export const nbTranslation = {
help: 'Hjelp',
expand: 'Utvid sidefelt',
collapse: 'Skjul sidefelt',
updateAvailable: 'Ny versjon er tilgjengelig',
updateReady: '{{version}} er klar',
updateLink: 'Hent nyeste versjon →',
downloadingTracks: 'Bufre {{n}} spor…',
offlineLibrary: 'Frakoblet bibliotek',
genres: 'Sjangere',
playlists: 'Spillelister',
radio: 'Internettradio',
libraryScope: 'Biblioteksomfang',
allLibraries: 'Alle biblioteker',
},
home: {
hero: 'Utvalgt',
@@ -328,12 +327,8 @@ export const nbTranslation = {
bulkRemoveFromPlaylist: 'Fjern fra spilleliste',
bulkClear: 'Tøm utvalg',
updaterAvailable: 'Ny versjon er tilgjengelig',
updaterVersion: 'v{{version}} er lansert',
updaterInstall: 'Installer og start applikasjonen på nytt',
updaterDownloading: 'Laster ned…',
updaterInstalling: 'Installerer…',
updaterDownload: 'Last ned fra GitHub',
updaterExperimentalHint: 'Auto-oppdatering er fortsatt under utvikling',
updaterVersion: 'v{{version}} er tilgjengelig',
updaterWebsite: 'Nettsted',
},
settings: {
title: 'Innstillinger',
@@ -345,7 +340,6 @@ export const nbTranslation = {
languageZh: 'Kinesisk',
languageNb: 'Norsk',
languageRu: 'Russisk',
languageRu2: 'Russisk 2',
font: 'Skrifttype',
theme: 'Tema',
appearance: 'Utseende',
@@ -406,6 +400,8 @@ export const nbTranslation = {
cacheUsed: 'Brukt: {{images}} bilder · {{offline}} frakoblede spor',
cacheUsedImages: 'Bilder:',
cacheUsedOffline: 'Frakoblede spor:',
cacheUsedHot: 'Plass brukt:',
hotCacheTrackCount: 'Spor i buffer:',
cacheMaxLabel: 'Maks størrelse',
cacheClearBtn: 'Tøm hurtigbuffer',
cacheClearWarning: 'Dette vil også fjerne alle frakoblede album fra biblioteket.',
@@ -417,6 +413,22 @@ export const nbTranslation = {
offlineDirChange: 'Endre katalog',
offlineDirClear: 'Tilbakestill til standard',
offlineDirHint: 'Nye nedlastinger vil bruke denne plasseringen. Eksisterende nedlastinger forblir på sin opprinnelige lokasjon.',
hotCacheTitle: 'Varm avspillingsbuffer',
hotCacheAlphaBadge: 'Alfa',
hotCacheDisclaimer: 'Forhåndshenter neste spor i køen og beholder tidligere. Når aktivert: diskplass og nettverk.',
hotCacheDirDefault: 'Standard (App-data)',
hotCacheDirChange: 'Endre mappe',
hotCacheDirClear: 'Tilbakestill til standard',
hotCacheDirHint: 'Bytte mappe nullstiller indeksen i appen; gamle filer blir liggende til du sletter dem.',
hotCacheEnabled: 'Aktiver varm avspillingsbuffer',
hotCacheMaxMb: 'Maks bufferstørrelse',
hotCacheDebounce: 'Utsettelse ved køendring',
hotCacheDebounceImmediate: 'Umiddelbart',
hotCacheDebounceSeconds: '{{n}} sek',
hotCacheClearBtn: 'Tøm varm buffer',
hiResTitle: 'Innebygd hi-res-avspilling',
hiResEnabled: 'Aktiver innebygd hi-res-avspilling',
hiResDesc: "Begrenser utdata til 44,1 kHz som standard for maksimal stabilitet. Aktiver kun hvis maskinvare og nettverk støtter høye samplingsrater (88,2 kHz+) pålitelig.",
showArtistImages: 'Vis artistbilder',
showArtistImagesDesc: 'Last inn og vis artistbilder i artistoversikten. Denne er deaktivert som standard, for å redusere disk-I/O og nettverksbelastningen på store biblioteker.',
minimizeToTray: 'Minimer til oppgavelinjen',
@@ -425,6 +437,8 @@ export const nbTranslation = {
discordRichPresenceDesc: 'Vis sporet som spilles i din Discord-profil. Krever at Discord kjører.',
nowPlayingEnabled: 'Vis i "Nå spiller"',
nowPlayingEnabledDesc: 'Send sporet som spilles av til tjenerens live-lyttervisning. Deaktiver for å stoppe sending av avspillingsdata.',
lyricsServerFirst: 'Foretrekk server-sangtekst',
lyricsServerFirstDesc: 'Sjekk tjenerlevererte sangtekster (innebygde tagger, sidecar-filer) før LRCLIB. Deaktiver for å bruke LRCLIB først.',
downloadsTitle: 'ZIP Eksport & Arkivering',
downloadsFolderDesc: 'Målmappe for album du laster ned som en ZIP-fil til datamaskinen din.',
downloadsDefault: 'Standard nedlastingsmappe',
@@ -688,8 +702,11 @@ export const nbTranslation = {
volume: 'Volum',
toggleQueue: 'Veksle kø',
lyrics: 'Sangtekst',
fsLyricsToggle: 'Sangtekst i fullskjerm',
lyricsLoading: 'Laster sangtekst…',
lyricsNotFound: 'Ingen sangtekst funnet for dette sporet',
lyricsSourceServer: 'Kilde: Server',
lyricsSourceLrclib: 'Kilde: LRCLIB',
},
songInfo: {
title: 'Sanginfo',
+28 -11
View File
@@ -15,14 +15,13 @@ export const nlTranslation = {
help: 'Help',
expand: 'Zijbalk uitklappen',
collapse: 'Zijbalk inklappen',
updateAvailable: 'Update beschikbaar',
updateReady: '{{version}} is klaar',
updateLink: 'Naar release →',
downloadingTracks: '{{n}} nummers worden gecached…',
offlineLibrary: 'Offline bibliotheek',
genres: 'Genres',
playlists: 'Playlists',
radio: 'Internetradio',
libraryScope: 'Bibliotheekbereik',
allLibraries: 'Alle bibliotheken',
},
home: {
hero: 'Uitgelicht',
@@ -328,12 +327,8 @@ export const nlTranslation = {
bulkRemoveFromPlaylist: 'Verwijderen uit afspeellijst',
bulkClear: 'Selectie wissen',
updaterAvailable: 'Update beschikbaar',
updaterVersion: 'v{{version}} is klaar',
updaterInstall: 'Installeren & Herstarten',
updaterDownloading: 'Downloaden…',
updaterInstalling: 'Installeren…',
updaterDownload: 'Downloaden van GitHub',
updaterExperimentalHint: 'Automatisch bijwerken is nog in ontwikkeling',
updaterVersion: 'v{{version}} beschikbaar',
updaterWebsite: 'Website',
},
settings: {
title: 'Instellingen',
@@ -345,7 +340,6 @@ export const nlTranslation = {
languageZh: 'Chinees',
languageNb: 'Noors',
languageRu: 'Russisch',
languageRu2: 'Russisch 2',
font: 'Lettertype',
theme: 'Thema',
appearance: 'Weergave',
@@ -405,6 +399,8 @@ export const nlTranslation = {
cacheDesc: 'Albumhoezen en artiestafbeeldingen. Als de cache vol is, worden de oudste items automatisch verwijderd. Offline albums worden niet automatisch verwijderd, maar wel bij handmatig leegmaken.',
cacheUsedImages: 'Afbeeldingen:',
cacheUsedOffline: 'Offline nummers:',
cacheUsedHot: 'Schijfgebruik:',
hotCacheTrackCount: 'Nummers in cache:',
cacheMaxLabel: 'Max. grootte',
cacheClearBtn: 'Cache wissen',
cacheClearWarning: 'Dit verwijdert ook alle offline albums uit de bibliotheek.',
@@ -416,6 +412,22 @@ export const nlTranslation = {
offlineDirChange: 'Map wijzigen',
offlineDirClear: 'Terugzetten naar standaard',
offlineDirHint: 'Nieuwe downloads worden op deze locatie opgeslagen. Bestaande downloads blijven op hun oorspronkelijke locatie.',
hotCacheTitle: 'Warme afspeelcache',
hotCacheAlphaBadge: 'Alpha',
hotCacheDisclaimer: 'Laadt aankomende wachtrijtracks voor en bewaart eerdere. Indien ingeschakeld: schijfruimte en netwerk.',
hotCacheDirDefault: 'Standaard (app-gegevens)',
hotCacheDirChange: 'Map wijzigen',
hotCacheDirClear: 'Terugzetten naar standaard',
hotCacheDirHint: 'Een andere map kiest: de index in de app wordt gereset; oude bestanden blijven staan tot je ze verwijdert.',
hotCacheEnabled: 'Warme afspeelcache inschakelen',
hotCacheMaxMb: 'Maximale cachegrootte',
hotCacheDebounce: 'Uitstel bij wachtrijwijziging',
hotCacheDebounceImmediate: 'Direct',
hotCacheDebounceSeconds: '{{n}} s',
hotCacheClearBtn: 'Warme cache wissen',
hiResTitle: 'Natieve hi-res-weergave',
hiResEnabled: 'Natieve hi-res-weergave inschakelen',
hiResDesc: "Beperkt de uitvoer standaard tot 44,1 kHz voor maximale stabiliteit. Alleen inschakelen als hardware en netwerk hoge samplerates (88,2 kHz+) ondersteunen.",
showArtistImages: 'Artiestafbeeldingen weergeven',
showArtistImagesDesc: 'Laadt en toont artiestafbeeldingen in het artiestenoverzicht. Standaard uitgeschakeld om server-I/O en netwerkbelasting bij grote bibliotheken te beperken.',
showTrayIcon: 'Tray-pictogram weergeven',
@@ -426,6 +438,8 @@ export const nlTranslation = {
discordRichPresenceDesc: 'Toont het huidige nummer op je Discord-profiel. Discord moet daarvoor geopend zijn.',
nowPlayingEnabled: 'Weergeven in live-venster',
nowPlayingEnabledDesc: 'Stuurt het huidige nummer naar de live-luisteraarsweergave van de server. Uitschakelen om geen afspeelgegevens te verzenden.',
lyricsServerFirst: 'Server-songtekst voorrang geven',
lyricsServerFirstDesc: 'Controleer eerst door de server geleverde songteksten (ingebedde tags, sidecar-bestanden) vóór LRCLIB. Uitschakelen om LRCLIB eerst te gebruiken.',
downloadsTitle: 'ZIP-export & Archivering',
downloadsFolderDesc: 'Doelmap voor albums die je als ZIP-bestand naar je computer downloadt.',
downloadsDefault: 'Standaard downloadmap',
@@ -548,7 +562,7 @@ export const nlTranslation = {
a11: 'De banner bovenaan de startpagina kiest willekeurig albums uit je bibliotheek en wisselt deze elke 10 seconden af. Klik op de puntjes om naar een specifiek album te springen.',
s4: 'Instellingen',
q12: 'Hoe verander ik het thema?',
a12: 'Instellingen → Thema. Een ruime keuze aan thema\'s in 8 groepen: Psysonic Themes, Mediaplayer, Besturingssystemen, Games, Films, Series, Social Media en Open Source Classics (Catppuccin, Nord, Gruvbox).',
a12: 'Instellingen → Thema. Een ruime keuze aan thema\'s in 8 groepen: Psysonic Themes, Mediaplayer, Besturingssystemen, Games, Films, Series, Social Media en Open Source Classics (Catppuccin, Nord, Gruvbox, Nightfox).',
q13: 'Hoe verander ik de taal?',
a13: 'Instellingen → Taal. Engels, Duits, Frans, Nederlands en Chinees worden momenteel ondersteund.',
q15: 'Hoe stel ik een downloadmap in?',
@@ -689,8 +703,11 @@ export const nlTranslation = {
volume: 'Volume',
toggleQueue: 'Wachtrij in-/uitschakelen',
lyrics: 'Songtekst',
fsLyricsToggle: 'Songtekst in volledig scherm',
lyricsLoading: 'Songtekst laden…',
lyricsNotFound: 'Geen songtekst gevonden voor dit nummer',
lyricsSourceServer: 'Bron: Server',
lyricsSourceLrclib: 'Bron: LRCLIB',
},
songInfo: {
title: 'Nummerinfo',
+52 -37
View File
@@ -2,28 +2,27 @@
export const ruTranslation = {
sidebar: {
library: 'Медиатека',
mainstage: 'Mainstage',
mainstage: 'Для вас',
newReleases: 'Новинки',
allAlbums: 'Все альбомы',
randomAlbums: 'Случайные альбомы',
artists: 'Исполнители',
randomMix: 'Случайный микс',
favorites: 'Избранное',
nowPlaying: 'Сейчас слушают',
nowPlaying: 'Сейчас играет',
system: 'Система',
statistics: 'Статистика',
settings: 'Настройки',
help: 'Справка',
expand: 'Развернуть боковую панель',
collapse: 'Свернуть боковую панель',
updateAvailable: 'Доступно обновление',
updateReady: '{{version}} готов к установке',
updateLink: 'К релизу →',
downloadingTracks: 'Кэширование {{n}} треков…',
offlineLibrary: 'Офлайн-библиотека',
genres: 'Жанры',
playlists: 'Плейлисты',
radio: 'Онлайн-радио',
libraryScope: 'Область медиатеки',
allLibraries: 'Все библиотеки',
},
home: {
hero: 'Подборка',
@@ -39,7 +38,7 @@ export const ruTranslation = {
},
hero: {
eyebrow: 'Альбом дня',
playAlbum: 'Играть альбом',
playAlbum: 'Воспроизвести альбом',
enqueue: 'В очередь',
enqueueTooltip: 'Добавить весь альбом в очередь',
},
@@ -54,13 +53,13 @@ export const ruTranslation = {
resultsFor: 'Результаты по «{{query}}»',
album: 'Альбом',
advanced: 'Расширенный поиск',
advancedSearchTerm: 'Запрос',
advancedSearchTerm: 'Поисковый запрос',
advancedSearchPlaceholder: 'Название, альбом, исполнитель…',
advancedGenre: 'Жанр',
advancedAllGenres: 'Все жанры',
advancedYear: 'Год',
advancedYearFrom: 'с',
advancedYearTo: 'по',
advancedYearFrom: 'от',
advancedYearTo: 'до',
advancedAll: 'Все',
advancedSearch: 'Найти',
advancedEmpty: 'Введите запрос или выберите фильтр.',
@@ -77,12 +76,12 @@ export const ruTranslation = {
loading: 'Загрузка…',
nobody: 'Сейчас никто не слушает.',
minutesAgo: '{{n}} мин назад',
nothingPlaying: 'Пока тишина — включите трек.',
nothingPlaying: 'Пока ничего не играет — включите трек.',
aboutArtist: 'Об исполнителе',
fromAlbum: 'С альбома',
viewAlbum: 'Открыть альбом',
goToArtist: 'К исполнителю',
readMore: 'Подробнее',
fromAlbum: 'Из этого альбома',
viewAlbum: 'Просмотр альбома',
goToArtist: 'Перейти к исполнителю',
readMore: 'Читать далее',
showLess: 'Свернуть',
genreInfo: 'Жанр',
trackInfo: 'О треке',
@@ -110,7 +109,7 @@ export const ruTranslation = {
},
albumDetail: {
back: 'Назад',
playAll: 'Играть всё',
playAll: 'Воспроизвести всё',
enqueue: 'В очередь',
enqueueTooltip: 'Добавить весь альбом в очередь',
artistBio: 'Биография',
@@ -151,7 +150,7 @@ export const ruTranslation = {
back: 'Назад',
albums: 'Альбомы',
album: 'Альбом',
playAll: 'Играть всё',
playAll: 'Воспроизвести всё',
shuffle: 'Перемешать',
radio: 'Радио',
loading: 'Загрузка…',
@@ -186,7 +185,7 @@ export const ruTranslation = {
albums: 'Альбомы',
songs: 'Треки',
enqueueAll: 'Всё в очередь',
playAll: 'Играть всё',
playAll: 'Воспроизвести всё',
removeSong: 'Убрать из избранного',
stations: 'Радиостанции',
},
@@ -212,7 +211,7 @@ export const ruTranslation = {
title: 'Случайный микс',
remix: 'Новый микс',
remixTooltip: 'Подобрать другие случайные треки',
playAll: 'Играть всё',
playAll: 'Воспроизвести всё',
trackTitle: 'Название',
trackArtist: 'Исполнитель',
trackAlbum: 'Альбом',
@@ -342,12 +341,8 @@ export const ruTranslation = {
bulkRemoveFromPlaylist: 'Убрать из плейлиста',
bulkClear: 'Снять выделение',
updaterAvailable: 'Доступно обновление',
updaterVersion: 'Версия {{version}} готова',
updaterInstall: 'Установить и перезапустить',
updaterDownloading: 'Скачивание…',
updaterInstalling: 'Установка…',
updaterDownload: 'Скачать с GitHub',
updaterExperimentalHint: 'Автообновление в разработке',
updaterVersion: 'Версия {{version}} доступна',
updaterWebsite: 'Сайт',
},
settings: {
title: 'Настройки',
@@ -421,6 +416,8 @@ export const ruTranslation = {
'Обложки и фото исполнителей. При переполнении старые записи удаляются. Офлайн-альбомы не трогаются автоматически, но сотрутся при полной очистке кэша.',
cacheUsedImages: 'Изображения:',
cacheUsedOffline: 'Офлайн-треки:',
cacheUsedHot: 'На диске:',
hotCacheTrackCount: 'Треков в кэше:',
cacheMaxLabel: 'Лимит',
cacheClearBtn: 'Очистить кэш',
cacheClearWarning: 'Будут удалены и все офлайн-альбомы.',
@@ -432,6 +429,22 @@ export const ruTranslation = {
offlineDirChange: 'Сменить папку',
offlineDirClear: 'Сбросить по умолчанию',
offlineDirHint: 'Новые загрузки пойдут в выбранную папку. Старые останутся на прежнем месте.',
hotCacheTitle: 'Горячий кэш воспроизведения',
hotCacheAlphaBadge: 'Альфа',
hotCacheDisclaimer: 'Заранее подгружает следующие треки из очереди и сохраняет предыдущие. При включении использует место на диске и сеть.',
hotCacheDirDefault: 'По умолчанию (данные приложения)',
hotCacheDirChange: 'Сменить папку',
hotCacheDirClear: 'Сбросить по умолчанию',
hotCacheDirHint: 'При смене папки сбрасывается список в приложении; уже скачанные файлы остаются на старом пути, пока вы их не удалите.',
hotCacheEnabled: 'Включить горячий кэш воспроизведения',
hotCacheMaxMb: 'Максимальный размер кэша',
hotCacheDebounce: 'Задержка после изменения очереди',
hotCacheDebounceImmediate: 'Сразу',
hotCacheDebounceSeconds: '{{n}} с',
hotCacheClearBtn: 'Очистить горячий кэш',
hiResTitle: 'Нативное воспроизведение Hi-Res',
hiResEnabled: 'Включить нативное Hi-Res воспроизведение',
hiResDesc: "По умолчанию ограничивает вывод до 44,1 кГц для максимальной стабильности. Включайте только если оборудование и сеть надёжно поддерживают высокие частоты (88,2 кГц+).",
showArtistImages: 'Фото исполнителей',
showArtistImagesDesc:
'Показывать обложки в разделе «Исполнители». По умолчанию выключено — меньше нагрузки на диск и сеть.',
@@ -439,13 +452,14 @@ export const ruTranslation = {
showTrayIconDesc: 'Показывать Psysonic в области уведомлений / строке меню.',
minimizeToTray: 'Сворачивать в трей',
minimizeToTrayDesc: 'При закрытии окна не выходить из приложения, а оставаться в трее.',
discordRichPresence: 'Discord Rich Presence',
discordRichPresenceDesc: 'Показывать текущий трек в профиле Discord. Нужен запущенный Discord.',
nowPlayingEnabled: 'Показывать в «Сейчас слушают»',
discordRichPresence: 'Статус в Discord',
discordRichPresenceDesc:
'Показывать текущий трек в профиле и статусе Discord. Нужен запущенный клиент Discord.',
nowPlayingEnabled: 'Показывать в «Сейчас играет»',
nowPlayingEnabledDesc:
'Отправлять на сервер, что вы сейчас слушаете. Отключите, чтобы не делиться этим.',
downloadsTitle: 'Экспорт ZIP и архивы',
downloadsFolderDesc: 'Куда сохранять альбомы в виде ZIP на диск.',
downloadsFolderDesc: 'Куда сохранять альбомы в ZIP архиве на диск.',
downloadsDefault: 'Папка «Загрузки» по умолчанию',
pickFolder: 'Выбрать',
pickFolderTitle: 'Папка для загрузок',
@@ -453,9 +467,9 @@ export const ruTranslation = {
logout: 'Выйти',
aboutTitle: 'О Psysonic',
aboutDesc:
'Современный десктопный плеер для серверов с протоколом Subsonic (Navidrome, Gonic и др.). На Tauri v2 и нативном аудиодвижке на Rust — лёгкий и быстрый: волновая шкала, синхронные тексты, Last.fm, 10-полосный EQ, кроссфейд, gapless, Replay Gain, жанры и много тем оформления.',
'Современный десктопный плеер для серверов с протоколом Subsonic (Navidrome, Gonic и др.). На Tauri v2 и нативном аудиодвижке на Rust — лёгкий и быстрый: волновая шкала, синхронные тексты, Last.fm, 10-полосный EQ, кроссфейд, воспроизведение без пауз, Replay Gain, жанры и много тем оформления.',
aboutFeatures:
'Несколько серверов · Last.fm · полноэкранный режим · волна · тексты · 10 полос EQ · кроссфейд и gapless · Replay Gain · жанры · десятки тем · несколько языков',
'Несколько серверов · Last.fm · полноэкранный режим · волна · тексты · 10 полос EQ · кроссфейд и воспроизведение без пауз · Replay Gain · жанры · десятки тем · несколько языков',
aboutLicense: 'Лицензия',
aboutLicenseText: 'GNU GPL v3 — свободное использование и изменение на тех же условиях.',
aboutRepo: 'Исходный код на GitHub',
@@ -523,7 +537,7 @@ export const ruTranslation = {
crossfade: 'Кроссфейд',
crossfadeDesc: 'Плавный переход между треками',
crossfadeSecs: '{{n}} с',
notWithGapless: 'Недоступно при включённом gapless',
notWithGapless: 'Недоступно при включённом режиме без пауз',
notWithCrossfade: 'Недоступно при включённом кроссфейде',
gapless: 'Без пауз между треками',
gaplessDesc: 'Заранее подгружать следующий трек, чтобы не было тишины',
@@ -556,7 +570,7 @@ export const ruTranslation = {
s2: 'Воспроизведение',
q4: 'Как включить музыку?',
a4:
'Двойной щелчок по треку. На странице альбома или исполнителя — «Играть всё». Треки можно перетащить в панель очереди.',
'Двойной щелчок по треку. На странице альбома или исполнителя — «Воспроизвести всё». Треки можно перетащить в панель очереди.',
q5: 'Какие есть горячие клавиши?',
a5:
'Пробел — пауза/воспроизведение, Esc — закрыть полноэкранный плеер. Медиаклавиши работают на всех платформах; на Linux иногда удобнее кнопки в панели плеера. Свои сочетания — в Настройках.',
@@ -580,7 +594,8 @@ export const ruTranslation = {
q12: 'Как сменить тему?',
a12: 'Настройки → Тема. Много готовых наборов в нескольких категориях.',
q13: 'Как сменить язык?',
a13: 'Настройки → Язык: английский, немецкий, французский, нидерландский, китайский, норвежский, русский.',
a13:
'Настройки → Язык: английский, немецкий, французский, нидерландский, китайский, норвежский, русский и русский (альтернативный, Русский 2).',
q15: 'Куда сохраняются ZIP?',
a15:
'Настройки → Поведение → папка загрузок. Без выбора используется стандартная папка загрузок браузера/системы.',
@@ -620,9 +635,9 @@ export const ruTranslation = {
q21: 'Чёрный экран в Linux.',
a21:
'Часто драйвер GPU / WebKitGTK. Запуск с GDK_BACKEND=x11 WEBKIT_DISABLE_COMPOSITING_MODE=1 WEBKIT_DISABLE_DMABUF_RENDERER=1. В официальных пакетах это часто уже задано.',
q29: 'Кроссфейд и gapless?',
q29: 'Кроссфейд и воспроизведение без пауз?',
a29:
'Экспериментальные опции в Настройках → Звук. Gapless заранее подгружает следующий трек. Кроссфейд плавно накладывает треки, длина 1–10 с.',
'Экспериментальные опции в Настройках → Звук. Режим без пауз заранее подгружает следующий трек. Кроссфейд плавно накладывает треки, длина 1–10 с.',
q30: 'Есть тексты песен?',
a30:
'Да. Иконка микрофона в панели плеера — вкладка текстов в очереди. Источник LRCLIB; синхронные строки подсвечиваются по ходу трека.',
@@ -658,7 +673,7 @@ export const ruTranslation = {
deleteConfirm: 'Удалить плейлист «{{name}}»?',
clear: 'Очистить',
shuffle: 'Перемешать',
gapless: 'Gapless',
gapless: 'Без пауз',
crossfade: 'Кроссфейд',
infiniteQueue: 'Бесконечная очередь',
autoAdded: '— Добавлено автоматически —',
@@ -783,7 +798,7 @@ export const ruTranslation = {
addFirstSong: 'Добавьте первый трек',
notFound: 'Плейлист не найден.',
songs: 'Треков: {{n}}',
playAll: 'Играть всё',
playAll: 'Воспроизвести всё',
shuffle: 'Перемешать',
addToQueue: 'В очередь',
back: 'К списку плейлистов',
-804
View File
@@ -1,804 +0,0 @@
/** Russian UI strings (alternative — kilyabin, PR #107) */
export const ru2Translation = {
sidebar: {
library: 'Библиотека',
mainstage: 'Главная',
newReleases: 'Новинки',
allAlbums: 'Все альбомы',
randomAlbums: 'Случайные альбомы',
artists: 'Исполнители',
randomMix: 'Случайный микс',
favorites: 'Избранное',
nowPlaying: 'Сейчас играет',
system: 'Система',
statistics: 'Статистика',
settings: 'Настройки',
help: 'Помощь',
expand: 'Развернуть боковую панель',
collapse: 'Свернуть боковую панель',
updateAvailable: 'Доступно обновление',
updateReady: '{{version}} готово',
updateLink: 'Перейти к релизу →',
downloadingTracks: 'Кэширование {{n}} треков…',
offlineLibrary: 'Офлайн библиотека',
genres: 'Жанры',
playlists: 'Плейлисты',
radio: 'Интернет радио',
},
home: {
hero: 'Рекомендации',
starred: 'Личные избранные',
recent: 'Недавно добавленные',
mostPlayed: 'Самые прослушиваемые',
recentlyPlayed: 'Недавно прослушанные',
discover: 'Открыть',
loadMore: 'Загрузить еще',
discoverMore: 'Открыть больше',
discoverArtists: 'Открыть исполнителей',
discoverArtistsMore: 'Все исполнители'
},
hero: {
eyebrow: 'Рекомендуемый альбом',
playAlbum: 'Воспроизвести альбом',
enqueue: 'В очередь',
enqueueTooltip: 'Добавить весь альбом в очередь',
},
search: {
placeholder: 'Поиск исполнителя, альбома или песни…',
noResults: 'Нет результатов для "{{query}}"',
artists: 'Исполнители',
albums: 'Альбомы',
songs: 'Песни',
clearLabel: 'Очистить поиск',
title: 'Поиск',
resultsFor: 'Результаты для "{{query}}"',
album: 'Альбом',
advanced: 'Расширенный поиск',
advancedSearchTerm: 'Поисковый запрос',
advancedSearchPlaceholder: 'Название, альбом, исполнитель…',
advancedGenre: 'Жанр',
advancedAllGenres: 'Все жанры',
advancedYear: 'Год',
advancedYearFrom: 'от',
advancedYearTo: 'до',
advancedAll: 'Все',
advancedSearch: 'Поиск',
advancedEmpty: 'Введите поисковый запрос или выберите фильтр.',
advancedNoResults: 'Результаты не найдены.',
advancedGenreNote: 'Песни случайно выбираются из этого жанра.',
recentSearches: 'Недавние запросы',
browse: 'Обзор',
emptyHint: 'Что хочешь послушать?',
genres: 'Жанры',
},
nowPlaying: {
tooltip: 'Кто слушает?',
title: 'Кто слушает?',
loading: 'Загрузка…',
nobody: 'Никто сейчас не слушает.',
minutesAgo: '{{n}} мин. назад',
nothingPlaying: 'Пока ничего не играет. Включите трек!',
aboutArtist: 'Об исполнителе',
fromAlbum: 'Из этого альбома',
viewAlbum: 'Просмотр альбома',
goToArtist: 'Перейти к исполнителю',
readMore: 'Читать далее',
showLess: 'Свернуть',
genreInfo: 'Жанр',
trackInfo: 'Информация о треке',
},
contextMenu: {
playNow: 'Воспроизвести сейчас',
playNext: 'Воспроизвести следующим',
addToQueue: 'Добавить в очередь',
enqueueAlbum: 'Добавить альбом в очередь',
startRadio: 'Запустить радио',
lfmLove: 'Нравится на Last.fm',
lfmUnlove: 'Убрать из любимых на Last.fm',
favorite: 'Избранное',
favoriteArtist: 'Добавить исполнителя в избранное',
favoriteAlbum: 'Добавить альбом в избранное',
unfavorite: 'Удалить из избранного',
unfavoriteArtist: 'Удалить исполнителя из избранного',
unfavoriteAlbum: 'Удалить альбом из избранного',
removeFromQueue: 'Удалить из очереди',
openAlbum: 'Открыть альбом',
goToArtist: 'Перейти к исполнителю',
download: 'Скачать (ZIP)',
addToPlaylist: 'Добавить в плейлист',
songInfo: 'Информация о песне',
},
albumDetail: {
back: 'Назад',
playAll: 'Воспроизвести все',
enqueue: 'В очередь',
enqueueTooltip: 'Добавить весь альбом в очередь',
artistBio: 'Биография исполнителя',
download: 'Скачать (ZIP)',
downloading: 'Загрузка…',
cacheOffline: 'Сделать доступным офлайн',
offlineCached: 'Доступно офлайн',
offlineDownloading: 'Кэширование… ({{n}}/{{total}})',
removeOffline: 'Удалить офлайн кэш',
offlineStorageFull: 'Офлайн хранилище заполнено (лимит: {{mb}} МБ). Освободите место, удалив альбом из офлайн библиотеки, или увеличьте лимит в настройках.',
offlineStorageGoToLibrary: 'Офлайн библиотека',
offlineStorageGoToSettings: 'Настройки',
favoriteAdd: 'Добавить в избранное',
favoriteRemove: 'Удалить из избранного',
favorite: 'Избранное',
noBio: 'Биография недоступна.',
moreByArtist: 'Больше от {{artist}}',
tracksCount: '{{n}} треков',
goToArtist: 'Перейти к {{artist}}',
moreLabelAlbums: 'Больше альбомов на {{label}}',
trackTitle: 'Название',
trackArtist: 'Исполнитель',
trackGenre: 'Жанр',
trackFormat: 'Формат',
trackFavorite: 'Избранное',
trackRating: 'Рейтинг',
trackDuration: 'Длительность',
trackTotal: 'Всего',
columns: 'Столбцы',
notFound: 'Альбом не найден.',
bioModal: 'Биография исполнителя',
bioClose: 'Закрыть',
ratingLabel: 'Рейтинг',
enlargeCover: 'Увеличить',
},
artistDetail: {
back: 'Назад',
albums: 'Альбомы',
album: 'Альбом',
playAll: 'Воспроизвести все',
shuffle: 'Перемешать',
radio: 'Радио',
loading: 'Загрузка…',
noRadio: 'Похожие треки для этого исполнителя не найдены.',
notFound: 'Исполнитель не найден.',
albumsBy: 'Альбомы {{name}}',
topTracks: 'Лучшие треки',
noAlbums: 'Альбомы не найдены.',
trackTitle: 'Название',
trackAlbum: 'Альбом',
trackDuration: 'Длительность',
favoriteAdd: 'Добавить в избранное',
favoriteRemove: 'Удалить из избранного',
favorite: 'Избранное',
albumCount_one: '{{count}} альбом',
albumCount_few: '{{count}} альбома',
albumCount_many: '{{count}} альбомов',
albumCount_other: '{{count}} альбомов',
openedInBrowser: 'Открыто в браузере',
featuredOn: 'Также представлен на',
similarArtists: 'Похожие исполнители',
cacheOffline: 'Сохранить дискографию офлайн',
offlineCached: 'Дискография кэширована',
offlineDownloading: 'Кэширование… ({{done}}/{{total}} альбомов)',
uploadImage: 'Загрузить изображение исполнителя',
uploadImageError: 'Не удалось загрузить изображение',
},
favorites: {
title: 'Избранное',
empty: 'Вы еще не добавили ничего в избранное.',
artists: 'Исполнители',
albums: 'Альбомы',
songs: 'Песни',
enqueueAll: 'Добавить все в очередь',
playAll: 'Воспроизвести все',
removeSong: 'Удалить из избранного',
stations: 'Радиостанции',
},
randomAlbums: {
title: 'Случайные альбомы',
refresh: 'Обновить',
},
genres: {
title: 'Жанры',
genreCount: 'Жанры',
albumCount_one: '{{count}} альбом',
albumCount_few: '{{count}} альбома',
albumCount_many: '{{count}} альбомов',
albumCount_other: '{{count}} альбомов',
loading: 'Загрузка жанров…',
empty: 'Жанры не найдены.',
albumsLoading: 'Загрузка альбомов…',
albumsEmpty: 'Альбомы в этом жанре не найдены.',
loadMore: 'Загрузить еще',
back: 'Назад',
},
randomMix: {
title: 'Случайный микс',
remix: 'Ремикс',
remixTooltip: 'Загрузить новые случайные песни',
playAll: 'Воспроизвести все',
trackTitle: 'Название',
trackArtist: 'Исполнитель',
trackAlbum: 'Альбом',
trackFavorite: 'Избранное',
trackDuration: 'Длительность',
favoriteAdd: 'Добавить в избранное',
favoriteRemove: 'Удалить из избранного',
play: 'Воспроизвести',
trackGenre: 'Жанр',
excludeAudiobooks: 'Исключить аудиокниги и радиопостановки',
excludeAudiobooksDesc: 'Совпадения ключевых слов в жанре, названии, альбоме и исполнителе — например, Аудиокнига, Разговорный жанр, …',
genreBlocked: 'Ключевое слово заблокировано',
genreAddedToBlacklist: 'Добавлено в список фильтрации',
genreAlreadyBlocked: 'Уже заблокировано',
artistBlocked: 'Исполнитель заблокирован',
artistAddedToBlacklist: 'Исполнитель добавлен в список фильтрации',
artistClickHint: 'Нажмите, чтобы заблокировать исполнителя',
blacklistToggle: 'Фильтр ключевых слов',
genreMixTitle: 'Жанровый микс',
genreMixDesc: 'Топ-20 жанров по количеству песен — нажмите для загрузки случайного микса',
genreMixLoadMore: 'Загрузить еще 10',
genreMixNoGenres: 'Жанры на сервере не найдены.',
shuffleGenres: 'Показать другие жанры',
filterPanelTitle: 'Фильтры',
filterPanelDesc: 'Нажмите на жанровый тег или имя исполнителя в списке треков ниже, чтобы заблокировать их в будущих миксах.',
genreClickHint: 'Нажмите на жанровый тег, чтобы добавить его\nкак ключевое слово фильтра.\nСовпадает с жанром, названием, альбомом и исполнителем.',
},
albums: {
title: 'Все альбомы',
sortByName: 'А–Я (Альбом)',
sortByArtist: 'А–Я (Исполнитель)',
sortNewest: 'Сначала новые',
sortRandom: 'Случайные',
yearFrom: 'От',
yearTo: 'До',
yearFilterClear: 'Очистить фильтр по году',
yearFilterLabel: 'Год',
},
artists: {
title: 'Исполнители',
search: 'Поиск…',
all: 'Все',
gridView: 'Сетка',
listView: 'Список',
imagesOn: 'Изображения исполнителей включены — могут увеличить нагрузку на сеть и систему',
imagesOff: 'Изображения исполнителей отключены — показываются только инициалы',
loadMore: 'Загрузить еще',
notFound: 'Исполнители не найдены.',
albumCount_one: '{{count}} альбом',
albumCount_few: '{{count}} альбома',
albumCount_many: '{{count}} альбомов',
albumCount_other: '{{count}} альбомов',
},
login: {
subtitle: 'Ваш настольный проигрыватель Navidrome',
serverName: 'Имя сервера (необязательно)',
serverNamePlaceholder: 'Мой Navidrome',
serverUrl: 'URL сервера',
serverUrlPlaceholder: '192.168.1.100:4533 или music.example.com',
username: 'Имя пользователя',
usernamePlaceholder: 'admin',
password: 'Пароль',
showPassword: 'Показать пароль',
hidePassword: 'Скрыть пароль',
connect: 'Подключиться',
connecting: 'Подключение…',
connected: 'Подключено!',
error: 'Ошибка подключения — проверьте ваши данные.',
urlRequired: 'Введите URL сервера.',
savedServers: 'Сохраненные серверы',
addNew: 'Или добавьте новый сервер',
},
connection: {
connected: 'Подключено',
connectedTo: 'Подключено к {{server}}',
disconnected: 'Отключено',
disconnectedFrom: 'Не удается подключиться к {{server}} — нажмите для проверки настроек',
checking: 'Подключение…',
extern: 'Внешний',
offlineTitle: 'Нет подключения к серверу',
offlineSubtitle: 'Не удается подключиться к {{server}}. Проверьте вашу сеть или сервер.',
offlineModeBanner: 'Офлайн-режим — воспроизведение из локального кэша',
offlineLibraryTitle: 'Офлайн-библиотека',
offlineLibraryEmpty: 'Пока нет кэшированных альбомов. Подключитесь к сети, откройте альбом и нажмите "Сделать доступным офлайн".',
offlineAlbumCount: '{{n}} альбом',
offlineAlbumCount_few: '{{n}} альбома',
offlineAlbumCount_many: '{{n}} альбомов',
offlineAlbumCount_plural: '{{n}} альбомов',
offlineFilterAll: 'Все',
offlineFilterAlbums: 'Альбомы',
offlineFilterPlaylists: 'Плейлисты',
offlineFilterArtists: 'Дискографии',
retry: 'Повторить',
lastfmConnected: 'Last.fm подключен как @{{user}}',
lastfmSessionInvalid: 'Сессия недействительна — нажмите для переподключения',
},
common: {
albums: 'Альбомы',
album: 'Альбом',
loading: 'Загрузка…',
loadingMore: 'Загрузка…',
loadingPlaylists: 'Загрузка плейлистов…',
noAlbums: 'Альбомы не найдены.',
downloading: 'Загрузка…',
downloadZip: 'Скачать (ZIP)',
back: 'Назад',
cancel: 'Отмена',
save: 'Сохранить',
delete: 'Удалить',
use: 'Использовать',
add: 'Добавить',
active: 'Активно',
download: 'Скачать',
chooseDownloadFolder: 'Выберите папку загрузки',
noFolderSelected: 'Папка не выбрана',
rememberDownloadFolder: 'Запомнить эту папку',
filterGenre: 'Фильтр по жанру',
filterSearchGenres: 'Поиск жанров…',
filterNoGenres: 'Нет совпадений по жанрам',
filterClear: 'Очистить',
bulkSelected: 'Выбрано: {{count}}',
bulkAddToPlaylist: 'Добавить в плейлист',
bulkRemoveFromPlaylist: 'Удалить из плейлиста',
bulkClear: 'Очистить выбор',
updaterAvailable: 'Доступно обновление',
updaterVersion: 'v{{version}} готово',
updaterInstall: 'Установить и перезапустить',
updaterDownloading: 'Загрузка…',
updaterInstalling: 'Установка…',
updaterDownload: 'Скачать с GitHub',
updaterExperimentalHint: 'Автообновление все еще в разработке',
},
settings: {
title: 'Настройки',
language: 'Язык',
languageEn: 'Английский',
languageDe: 'Немецкий',
languageFr: 'Французский',
languageNl: 'Нидерландский',
languageZh: 'Китайский',
languageNb: 'Норвежский',
languageRu: 'Русский',
languageRu2: 'Русский 2',
font: 'Шрифт',
theme: 'Тема',
appearance: 'Внешний вид',
servers: 'Серверы',
serverName: 'Имя сервера',
serverUrl: 'URL сервера',
serverUsername: 'Имя пользователя',
serverPassword: 'Пароль',
addServer: 'Добавить сервер',
addServerTitle: 'Добавить новый сервер',
useServer: 'Использовать',
deleteServer: 'Удалить',
noServers: 'Серверы не сохранены.',
serverActive: 'Активный',
confirmDeleteServer: 'Удалить сервер "{{name}}"?',
serverConnecting: 'Подключение…',
serverConnected: 'Подключено!',
serverFailed: 'Ошибка подключения.',
testBtn: 'Проверить подключение',
testingBtn: 'Проверка…',
serverCompatible: 'Совместимо с: Navidrome · Gonic · Airsonic · Subsonic',
connected: 'Подключено',
failed: 'Ошибка',
eqTitle: 'Эквалайзер',
eqEnabled: 'Включить эквалайзер',
eqPreset: 'Пресет',
eqPresetCustom: 'Пользовательский',
eqPresetBuiltin: 'Встроенные пресеты',
eqPresetCustomGroup: 'Мои пресеты',
eqSavePreset: 'Сохранить как пресет',
eqPresetName: 'Название пресета…',
eqDeletePreset: 'Удалить пресет',
eqResetBands: 'Сбросить',
eqPreGain: 'Предусиление',
eqResetPreGain: 'Сбросить предусиление',
eqAutoEqTitle: 'Поиск наушников AutoEQ',
eqAutoEqPlaceholder: 'Поиск модели наушников / IEM…',
eqAutoEqSearching: 'Поиск…',
eqAutoEqNoResults: 'Результаты не найдены',
eqAutoEqError: 'Ошибка поиска',
eqAutoEqRateLimit: 'Достигнут лимит GitHub — попробуйте через минуту',
eqAutoEqFetchError: 'Не удалось загрузить профиль EQ',
lfmTitle: 'Last.fm',
lfmConnect: 'Подключить Last.fm',
lfmConnecting: 'Ожидание авторизации…',
lfmConfirm: 'Я авторизовал приложение',
lfmConnected: 'Подключено как',
lfmDisconnect: 'Отключить',
lfmConnectDesc: 'Подключите аккаунт Last.fm для включения скробблинга и обновления "Сейчас играет" напрямую из Psysonic — без необходимости настройки Navidrome.',
lfmOpenBrowser: 'Откроется окно браузера. Авторизуйте Psysonic на Last.fm, затем нажмите кнопку ниже.',
lfmScrobbles: '{{n}} скробблов',
lfmMemberSince: 'Участник с {{year}}',
scrobbleEnabled: 'Скробблинг включен',
scrobbleDesc: 'Отправлять песни на Last.fm после 50% воспроизведения',
behavior: 'Поведение приложения',
cacheTitle: 'Макс. размер хранилища',
cacheDesc: 'Обложки и изображения исполнителей. При заполнении старые записи удаляются автоматически. Офлайн альбомы не удаляются автоматически, но будут удалены при ручной очистке кэша.',
cacheUsedImages: 'Изображения:',
cacheUsedOffline: 'Офлайн треки:',
cacheMaxLabel: 'Макс. размер',
cacheClearBtn: 'Очистить кэш',
cacheClearWarning: 'Это также удалит все офлайн альбомы из библиотеки.',
cacheClearConfirm: 'Очистить все',
cacheClearCancel: 'Отмена',
offlineDirTitle: 'Офлайн библиотека (в приложении)',
offlineDirDesc: 'Место хранения треков, которые вы делаете доступными офлайн в Psysonic.',
offlineDirDefault: 'По умолчанию (данные приложения)',
offlineDirChange: 'Изменить директорию',
offlineDirClear: 'Сбросить по умолчанию',
offlineDirHint: 'Новые загрузки будут использовать это место. Существующие загрузки останутся по своему исходному пути.',
showArtistImages: 'Показать изображения исполнителей',
showArtistImagesDesc: 'Загружать и отображать изображения исполнителей в обзоре исполнителей. Отключено по умолчанию для снижения дискового ввода-вывода сервера и сетевой нагрузки на больших библиотеках.',
showTrayIcon: 'Показать значок в трее',
showTrayIconDesc: 'Отображать значок Psysonic в области уведомлений системы / строке меню.',
minimizeToTray: 'Свернуть в трей',
minimizeToTrayDesc: 'При закрытии окна оставлять Psysonic работающим в системном трее вместо выхода.',
discordRichPresence: 'Discord Rich Presence',
discordRichPresenceDesc: 'Показывать текущий воспроизводимый трек в вашем профиле Discord. Требуется запущенный Discord.',
nowPlayingEnabled: 'Показывать в "Сейчас играет"',
nowPlayingEnabledDesc: 'Транслировать текущий воспроизводимый трек на сервер в режим просмотра слушателей. Отключите, чтобы прекратить отправку данных воспроизведения.',
downloadsTitle: 'ZIP экспорт и архивирование',
downloadsFolderDesc: 'Папка назначения для альбомов, которые вы скачиваете в виде ZIP файла на компьютер.',
downloadsDefault: 'Папка загрузок по умолчанию',
pickFolder: 'Выбрать',
pickFolderTitle: 'Выберите папку загрузки',
clearFolder: 'Очистить папку загрузки',
logout: 'Выйти',
aboutTitle: 'О Psysonic',
aboutDesc: 'Современный настольный музыкальный проигрыватель для серверов, совместимых с Subsonic (Navidrome, Gonic и другие). Построен на Tauri v2 с нативным аудио движком на Rust — легкий и быстрый, но с богатым функционалом: волновая форма для перемотки, синхронизированные тексты песен, интеграция с Last.fm, 10-полосный эквалайзер, кроссфейд, воспроизведение без пауз, Replay Gain, просмотр жанров и большая библиотека тем.',
aboutFeatures: 'Многосерверность · Скробблинг и лайки Last.fm · Полноэкранный Ambient Stage · Перемотка по волновой форме · Синхронизированные тексты · 10-полосный эквалайзер · Кроссфейд и воспроизведение без пауз · Replay Gain · Жанры · 63 темы · 5 языков',
aboutLicense: 'Лицензия',
aboutLicenseText: 'GNU GPL v3 — бесплатное использование, модификация и распространение на тех же условиях.',
aboutRepo: 'Исходный код на GitHub',
aboutVersion: 'Версия',
aboutBuiltWith: 'Создано с Tauri · React · TypeScript · Rust/rodio',
aboutAiCredit: 'Разработано при поддержке Claude Code от Anthropic',
aboutContributorsLabel: 'Участники',
aboutSpecialThanksLabel: 'Особая благодарность',
changelog: 'Список изменений',
showChangelogOnUpdate: 'Показывать "Что нового" при обновлении',
showChangelogOnUpdateDesc: 'Автоматически показывать, что нового, при первом запуске новой версии.',
randomMixTitle: 'Случайный микс',
randomMixBlacklistTitle: 'Пользовательские ключевые слова фильтра',
randomMixBlacklistDesc: 'Песни исключаются, когда любое ключевое слово совпадает с их жанром, названием, альбомом или исполнителем (активно при включенном флажке выше).',
randomMixBlacklistPlaceholder: 'Добавить ключевое слово…',
randomMixBlacklistAdd: 'Добавить',
randomMixBlacklistEmpty: 'Пользовательские ключевые слова еще не добавлены.',
randomMixHardcodedTitle: 'Встроенные ключевые слова (активны при включенном флажке)',
tabAudio: 'Аудио',
tabStorage: 'Хранилище и загрузки',
tabAppearance: 'Внешний вид',
homeCustomizerTitle: 'Главная страница',
sidebarTitle: 'Боковая панель',
sidebarReset: 'Сбросить по умолчанию',
sidebarDrag: 'Перетащите для изменения порядка',
sidebarFixed: 'Всегда видна',
tabInput: 'Ввод',
tabServer: 'Сервер',
tabSystem: 'Система',
tabGeneral: 'Общие',
backupTitle: 'Резервное копирование и восстановление',
backupExport: 'Экспорт настроек',
backupExportDesc: 'Сохраняет все настройки, профили серверов, конфигурацию Last.fm, тему, эквалайзер и привязки клавиш в файл .psybkp. Пароли хранятся в открытом виде — храните файл в безопасности.',
backupImport: 'Импорт настроек',
backupImportDesc: 'Восстанавливает настройки из файла .psybkp. Приложение перезагрузится после импорта.',
backupImportConfirm: 'Это перезапишет все текущие настройки. Продолжить?',
backupSuccess: 'Резервная копия сохранена',
backupImportSuccess: 'Настройки восстановлены — перезагрузка…',
backupImportError: 'Недействительный или поврежденный файл резервной копии.',
shortcutsReset: 'Сбросить по умолчанию',
shortcutListening: 'Нажмите клавишу…',
shortcutUnbound: '—',
globalShortcutsTitle: 'Глобальные горячие клавиши',
globalShortcutsNote: 'Работают по всей системе, даже когда Psysonic работает в фоне. Требуют Ctrl, Alt или Super в качестве модификатора.',
shortcutClear: 'Очистить',
shortcutPlayPause: 'Воспроизведение / Пауза',
shortcutNext: 'Следующий трек',
shortcutPrev: 'Предыдущий трек',
shortcutVolumeUp: 'Увеличить громкость',
shortcutVolumeDown: 'Уменьшить громкость',
shortcutSeekForward: 'Перемотка вперед на 10 с',
shortcutSeekBackward: 'Перемотка назад на 10 с',
shortcutToggleQueue: 'Переключить очередь',
shortcutFullscreenPlayer: 'Полноэкранный плеер',
shortcutNativeFullscreen: 'Нативный полный экран',
playbackTitle: 'Воспроизведение',
replayGain: 'Replay Gain',
replayGainDesc: 'Нормализация громкости трека с использованием метаданных ReplayGain',
replayGainMode: 'Режим',
replayGainTrack: 'Трек',
replayGainAlbum: 'Альбом',
crossfade: 'Кроссфейд',
crossfadeDesc: 'Плавный переход между треками',
crossfadeSecs: '{{n}} с',
notWithGapless: 'Недоступно при активном воспроизведении без пауз',
notWithCrossfade: 'Недоступно при активном кроссфейде',
gapless: 'Воспроизведение без пауз',
gaplessDesc: 'Предварительная буферизация следующего трека для устранения пауз между песнями',
preloadMode: 'Предзагрузка следующего трека',
preloadModeDesc: 'Когда начинать буферизацию следующего трека в очереди',
preloadBalanced: 'Сбалансированный (за 30 с до конца)',
preloadEarly: 'Ранний (после 5 с воспроизведения)',
preloadCustom: 'Пользовательский',
preloadCustomSeconds: 'Секунд до конца: {{n}}',
infiniteQueue: 'Бесконечная очередь',
infiniteQueueDesc: 'Автоматически добавлять случайные треки при окончании очереди',
experimental: 'Экспериментальный',
},
changelog: {
modalTitle: 'Что нового',
dontShowAgain: 'Больше не показывать',
close: 'Понятно',
},
help: {
title: 'Помощь',
s1: 'Начало работы',
q1: 'Какие серверы совместимы?',
a1: 'Psysonic работает с любым сервером, совместимым с Subsonic: Navidrome, Gonic, Subsonic, Airsonic и другими. Navidrome — рекомендуемый выбор.',
q2: 'Как подключиться к серверу?',
a2: 'Откройте Настройки и нажмите "Добавить сервер". Введите URL сервера (например, 192.168.1.100:4533), имя пользователя и пароль. Psysonic проверяет подключение перед сохранением — ничего не сохраняется, если подключение не удалось.',
q3: 'Могу ли я использовать несколько серверов?',
a3: 'Да. Вы можете добавить сколько угодно серверов в Настройках и переключаться между ними в любое время. Только один сервер активен одновременно.',
s2: 'Воспроизведение',
q4: 'Как воспроизводить музыку?',
a4: 'Дважды щелкните любой трек для воспроизведения. На страницах альбомов и исполнителей используйте "Воспроизвести все" для запуска всего альбома. Вы также можете перетащить треки в панель очереди.',
q5: 'Какие горячие клавиши доступны?',
a5: 'Пробел = Воспроизведение / Пауза · Escape = Закрыть полноэкранный плеер. Медиа-клавиши (Воспроизведение/Пауза, Следующий, Предыдущий) работают на всех платформах. На Linux используйте кнопки панели проигрывателя для медиа-клавиш. Внутриприложенные горячие клавиши и системные глобальные горячие клавиши можно настроить в Настройках → Горячие клавиши / Глобальные горячие клавиши.',
q6: 'Что такое очередь?',
a6: 'Очередь показывает все предстоящие треки. Откройте ее с помощью значка панели в правом верхнем углу заголовка (рядом с индикатором "Сейчас играет"). Вы можете переупорядочивать треки перетаскиванием, перемешивать кнопкой перемешивания и сохранять очередь как плейлист.',
q7: 'Как открыть полноэкранный плеер?',
a7: 'Нажмите на миниатюру обложки в панели проигрывателя внизу или на значок расширения рядом с ней. Нажмите Escape для закрытия.',
q8: 'Как работает повтор?',
a8: 'Нажмите кнопку повтора в панели проигрывателя для цикла: Выкл → Повтор всех → Повтор одного.',
s3: 'Библиотека',
q9: 'Как скачать альбом?',
a9: 'Откройте страницу альбома и нажмите "Скачать (ZIP)". Сервер сначала сжимает альбом в ZIP файл — для больших альбомов или файлов без потерь (FLAC / WAV) это может занять некоторое время перед фактическим началом загрузки. Это нормально: прогресс-бар появляется после завершения упаковки сервером и начала передачи.',
q10: 'Как добавить треки и альбомы в избранное?',
a10: 'Нажмите на значок звезды на любой строке трека или в заголовке альбома. Отмеченные элементы появляются в разделе "Избранное" на боковой панели.',
q11: 'Что такое карусель на главной странице?',
a11: 'Баннер в верхней части главной страницы случайно выбирает альбомы из вашей библиотеки и вращает их каждые 10 секунд. Нажмите на точки для перехода к конкретному альбому или нажмите на баннер для открытия альбома.',
s4: 'Настройки',
q12: 'Как изменить тему?',
a12: 'Настройки → Тема. Выберите из большого количества тем в 8 группах: Темы Psysonic, Медиаплееры, Операционные системы, Игры, Фильмы, Сериалы, Социальные сети и Классика открытого исходного кода (Catppuccin, Nord, Gruvbox).',
q13: 'Как изменить язык?',
a13: 'Настройки → Язык. Поддерживаются английский, немецкий, французский, нидерландский, китайский, норвежский и русский.',
q15: 'Как установить папку загрузки?',
a15: 'Настройки → Поведение приложения → Папка загрузки. Выберите любую папку — загруженные альбомы сохраняются туда как ZIP файлы. Без пользовательской папки используется местоположение загрузок браузера по умолчанию.',
s5: 'Скробблинг',
q16: 'Как работает скробблинг?',
a16: 'Psysonic отправляет скробблы напрямую на Last.fm — настройка Navidrome не требуется. Подключите аккаунт Last.fm в Настройках → Last.fm и включите скробблинг там.',
q17: 'Когда отправляется скроббл?',
a17: 'Скроббл отправляется после прослушивания 50% трека.',
q22: 'Что такое волновая форма в панели проигрывателя?',
a22: 'Панель перемотки с волновой формой заменяет классический ползунок прогресса. Нажмите в любом месте для перехода к этой позиции или перетащите для перемотки. Воспроизведенная часть светится градиентом от синего к лиловому, буферизованный диапазон немного ярче, а невоспроизведенная часть затемнена.',
q24: 'Могу ли я перемешать очередь?',
a24: 'Да. Откройте панель очереди и нажмите значок перемешивания в заголовке очереди. Текущий воспроизводимый трек остается на позиции 1 — все остальные треки случайно переупорядочиваются.',
q25: 'Открываются ли ссылки Last.fm и Wikipedia на страницах исполнителей в браузере?',
a25: 'Да — они открываются в вашем системном браузере по умолчанию. Кнопка кратко показывает метку подтверждения при нажатии.',
s7: 'Случайный микс',
q26: 'Что такое Случайный микс?',
a26: 'Случайный микс создает плейлист из случайных треков из всей вашей библиотеки...',
q27: 'Что такое Фильтр ключевых слов?',
a27: 'Фильтр ключевых слов исключает треки, жанр, название или альбом которых содержат определенные слова. Аудиокниги фильтруются автоматически. Добавьте пользовательские ключевые слова в Настройках → Случайный микс или нажмите любой жанровый тег в списке треков для мгновенного добавления.',
q28: 'Что такое Супер жанровый микс?',
a28: 'Супер жанровый микс группирует вашу библиотеку в широкие категории (Рок, Метал, Электронная, Джаз, Классика и т.д.) и создает сфокусированный микс из этого стиля. Выберите категорию ниже списка треков. Результаты появляются прогрессивно по мере получения каждого поджанра.',
s6: 'Устранение неполадок',
q18: 'Обложки и изображения исполнителей загружаются медленно.',
a18: 'Изображения загружаются с диска вашего сервера при первом посещении и затем кэшируются локально на 30 дней. Если хранилище сервера медленное, первое посещение страницы может занять некоторое время. Последующие посещения будут мгновенными.',
q19: 'Тест подключения не удается.',
a19: 'Проверьте URL включая порт (например, http://192.168.1.100:4533). Убедитесь, что брандмауэр не блокирует подключение. Попробуйте http:// вместо https:// в локальной сети. Также проверьте правильность имени пользователя и пароля.',
q20: 'Нет звука на Linux.',
a20: 'Psysonic доступен как .deb (Ubuntu/Debian), .rpm (Fedora/RHEL) и через AUR на Arch/CachyOS (yay -S psysonic или yay -S psysonic-bin). Нет AppImage. Если звук отсутствует, убедитесь, что PipeWire или PulseAudio запущены.',
q21: 'Приложение показывает черный экран на Linux.',
a21: 'Обычно это проблема GPU/EGL драйвера в WebKitGTK. Запустите с GDK_BACKEND=x11 WEBKIT_DISABLE_COMPOSITING_MODE=1 WEBKIT_DISABLE_DMABUF_RENDERER=1. Пакет AUR и официальные установщики .deb/.rpm устанавливают это автоматически.',
q29: 'Что такое Кроссфейд и Воспроизведение без пауз?',
a29: 'Оба являются экспериментальными аудио функциями в Настройках → Аудио. Воспроизведение без пауз предварительно буферизует следующий трек для устранения тишины между песнями. Кроссфейд затухает текущий трек при одновременном нарастании следующего — настройте длительность (1–10 с) по вкусу.',
q30: 'Показывает ли Psysonic тексты песен?',
a30: 'Да. Нажмите значок микрофона в панели проигрывателя для открытия вкладки "Текст" в панели очереди. Psysonic автоматически загружает тексты из LRCLIB. При наличии синхронизированных текстов активная строка выделяется и прокручивается в реальном времени по мере воспроизведения песни. При наличии только обычного текста он отображается статически.',
q31: 'Могу ли я настроить горячие клавиши?',
a31: 'Да. Настройки → Горячие клавиши позволяют переназначить действия приложения (Воспроизведение/Пауза, Следующий, Предыдущий, Громкость вверх/вниз, Полный экран и другие) на любую клавишу. Настройки → Глобальные горячие клавиши позволяют назначить системные горячие клавиши, которые срабатывают даже когда Psysonic работает в фоне.',
q32: 'Могу ли я изменить шрифт?',
a32: 'Да. Настройки → Шрифт позволяют выбрать из 10 шрифтов, включая IBM Plex Mono, Fira Code, JetBrains Mono, Courier Prime и другие. Выбранный шрифт применяется ко всему интерфейсу.',
s8: 'Офлайн режим',
q34: 'Что такое Офлайн режим?',
a34: 'Офлайн режим (бета) позволяет кэшировать альбомы на ваше устройство для прослушивания без активного подключения к серверу. Кэшированные треки хранятся локально и воспроизводятся напрямую с диска — во время воспроизведения сетевые запросы не выполняются.',
q35: 'Как кэшировать альбом для офлайн использования?',
a35: 'Откройте любой альбом и нажмите значок загрузки в заголовке альбома. Psysonic загружает все треки в фоне. Прогресс показывается на кнопке. После кэширования значок становится зеленым. Вы можете просмотреть и удалить кэшированные альбомы на странице Офлайн библиотеки (боковая панель).',
q36: 'Сколько хранилища может использовать офлайн кэширование?',
a36: 'Вы можете установить максимальный размер кэша в Настройках → Библиотека. При достижении лимита на странице альбома появляется предупреждающий баннер. Вы можете удалять отдельные альбомы из Офлайн библиотеки для освобождения места.',
},
queue: {
title: 'Очередь',
savePlaylist: 'Сохранить плейлист',
updatePlaylist: 'Обновить плейлист',
filterPlaylists: 'Фильтр плейлистов…',
playlistName: 'Название плейлиста',
cancel: 'Отмена',
save: 'Сохранить',
loadPlaylist: 'Загрузить плейлист',
loading: 'Загрузка…',
noPlaylists: 'Плейлисты не найдены.',
load: 'Заменить очередь и воспроизвести',
appendToQueue: 'Добавить в конец очереди',
delete: 'Удалить',
deleteConfirm: 'Удалить плейлист "{{name}}"?',
clear: 'Очистить',
shuffle: 'Перемешать очередь',
gapless: 'Без пауз',
crossfade: 'Кроссфейд',
infiniteQueue: 'Бесконечная очередь',
autoAdded: '— Добавлено автоматически —',
radioAdded: '— Радио —',
hide: 'Скрыть',
close: 'Закрыть',
nextTracks: 'Следующие треки',
emptyQueue: 'Очередь пуста.',
trackSingular: 'трек',
trackPlural: 'треков',
showRemaining: 'Показать оставшееся время',
showTotal: 'Показать общее время',
},
statistics: {
title: 'Статистика',
recentlyPlayed: 'Недавно прослушанные',
mostPlayed: 'Самые прослушиваемые альбомы',
highestRated: 'Альбомы с highest рейтингом',
genreDistribution: 'Распределение по жанрам (Топ-20)',
loadMore: 'Загрузить еще',
statArtists: 'Исполнители',
statAlbums: 'Альбомы',
statSongs: 'Песни',
statGenres: 'Жанры',
statPlaytime: 'Общее время воспроизведения',
genreInsights: 'Обзор по жанрам',
formatDistribution: 'Распределение по форматам',
formatSample: 'Выборка из {{n}} треков',
computing: 'Вычисление…',
genreSongs: '{{count}} песен',
genreAlbums: '{{count}} альбомов',
recentlyAdded: 'Недавно добавленные',
decadeDistribution: 'Альбомы по десятилетиям',
decadeAlbums_one: '{{count}} альбом',
decadeAlbums_few: '{{count}} альбома',
decadeAlbums_many: '{{count}} альбомов',
decadeAlbums_other: '{{count}} альбомов',
decadeUnknown: 'Неизвестно',
lfmTitle: 'Статистика Last.fm',
lfmTopArtists: 'Топ исполнителей',
lfmTopAlbums: 'Топ альбомов',
lfmTopTracks: 'Топ треков',
lfmPlays: '{{count}} воспроизведений',
lfmPeriodOverall: 'Все время',
lfmPeriod7day: '7 дней',
lfmPeriod1month: '1 месяц',
lfmPeriod3month: '3 месяца',
lfmPeriod6month: '6 месяцев',
lfmPeriod12month: '12 месяцев',
lfmNotConnected: 'Подключите Last.fm в Настройках для просмотра статистики.',
lfmRecentTracks: 'Недавние скробблы',
lfmNowPlaying: 'Сейчас играет',
lfmJustNow: 'только что',
lfmMinutesAgo: '{{n}} мин. назад',
lfmHoursAgo: '{{n}} ч. назад',
lfmDaysAgo: '{{n}} дн. назад',
},
player: {
regionLabel: 'Музыкальный проигрыватель',
openFullscreen: 'Открыть полноэкранный плеер',
fullscreen: 'Полноэкранный плеер',
closeFullscreen: 'Закрыть полный экран',
closeTooltip: 'Закрыть (Esc)',
noTitle: 'Без названия',
stop: 'Стоп',
prev: 'Предыдущий трек',
play: 'Воспроизвести',
pause: 'Пауза',
next: 'Следующий трек',
repeat: 'Повтор',
repeatOff: 'Выкл',
repeatAll: 'Все',
repeatOne: 'Один',
progress: 'Прогресс песни',
volume: 'Громкость',
toggleQueue: 'Переключить очередь',
lyrics: 'Текст',
lyricsLoading: 'Загрузка текста…',
lyricsNotFound: 'Текст для этого трека не найден',
},
songInfo: {
title: 'Информация о песне',
songTitle: 'Название',
artist: 'Исполнитель',
album: 'Альбом',
albumArtist: 'Исполнитель альбома',
year: 'Год',
genre: 'Жанр',
duration: 'Длительность',
track: 'Трек',
format: 'Формат',
bitrate: 'Битрейт',
sampleRate: 'Частота дискретизации',
bitDepth: 'Глубина бита',
channels: 'Каналы',
fileSize: 'Размер файла',
path: 'Путь',
replayGainTrack: 'RG усиление трека',
replayGainAlbum: 'RG усиление альбома',
replayGainPeak: 'RG пик трека',
mono: 'Моно',
stereo: 'Стерео',
},
playlists: {
title: 'Плейлисты',
newPlaylist: 'Новый плейлист',
unnamed: 'Безымянный плейлист',
createName: 'Название плейлиста…',
create: 'Создать',
cancel: 'Отмена',
empty: 'Плейлистов пока нет.',
emptyPlaylist: 'Этот плейлист пуст.',
addFirstSong: 'Добавьте первую песню',
notFound: 'Плейлист не найден.',
songs: '{{n}} песен',
playAll: 'Воспроизвести все',
shuffle: 'Перемешать',
addToQueue: 'Добавить в очередь',
back: 'Назад к плейлистам',
deletePlaylist: 'Удалить',
confirmDelete: 'Нажмите еще раз для подтверждения',
removeSong: 'Удалить из плейлиста',
addSongs: 'Добавить песни',
searchPlaceholder: 'Поиск в библиотеке…',
noResults: 'Результаты не найдены.',
suggestions: 'Предложенные песни',
noSuggestions: 'Предложения недоступны.',
titleBadge: 'Плейлист',
refreshSuggestions: 'Новые предложения',
addSong: 'Добавить в плейлист',
cacheOffline: 'Кэшировать плейлист офлайн',
offlineCached: 'Плейлист кэширован',
offlineDownloading: 'Кэширование… ({{done}}/{{total}} альбомов)',
publicLabel: 'Публичный',
privateLabel: 'Приватный',
editMeta: 'Редактировать плейлист',
editNamePlaceholder: 'Название плейлиста…',
editCommentPlaceholder: 'Добавьте описание…',
editPublic: 'Публичный плейлист',
editSave: 'Сохранить',
editCancel: 'Отмена',
changeCover: 'Изменить обложку',
changeCoverLabel: 'Изменить фото',
removeCover: 'Удалить фото',
coverUpdated: 'Обложка обновлена',
metaSaved: 'Плейлист обновлен',
},
radio: {
title: 'Интернет-радио',
empty: 'Радиостанции не настроены.',
addStation: 'Добавить станцию',
editStation: 'Редактировать',
deleteStation: 'Удалить станцию',
confirmDelete: 'Нажмите еще раз для подтверждения',
stationName: 'Название станции…',
streamUrl: 'URL потока…',
homepageUrl: 'URL главной страницы (необязательно)',
save: 'Сохранить',
cancel: 'Отмена',
live: 'ПРЯМОЙ ЭФИР',
liveStream: 'Интернет радио',
openHomepage: 'Открыть главную страницу',
changeCoverLabel: 'Изменить обложку',
removeCover: 'Удалить обложку',
browseDirectory: 'Поиск в каталоге',
directoryPlaceholder: 'Поиск станций…',
noResults: 'Станции не найдены.',
stationAdded: 'Станция добавлена',
filterAll: 'Все',
filterFavorites: 'Избранное',
sortManual: 'Вручную',
sortAZ: 'А → Я',
sortZA: 'Я → А',
sortNewest: 'Новые',
favorite: 'Добавить в избранное',
unfavorite: 'Удалить из избранного',
noFavorites: 'Избранных станций нет.',
}
}
+28 -11
View File
@@ -15,14 +15,13 @@ export const zhTranslation = {
help: '帮助',
expand: '展开侧边栏',
collapse: '收起侧边栏',
updateAvailable: '有可用更新',
updateReady: '{{version}} 已就绪',
updateLink: '前往发布页面 →',
downloadingTracks: '正在缓存 {{n}} 首歌曲…',
offlineLibrary: '离线音乐库',
genres: '流派',
playlists: '播放列表',
radio: '网络电台',
libraryScope: '资料库范围',
allLibraries: '所有资料库',
},
home: {
hero: '精选',
@@ -324,12 +323,8 @@ export const zhTranslation = {
bulkRemoveFromPlaylist: '从播放列表移除',
bulkClear: '取消选择',
updaterAvailable: '有可用更新',
updaterVersion: 'v{{version}} 已就绪',
updaterInstall: '安装并重启',
updaterDownloading: '下载中…',
updaterInstalling: '安装中…',
updaterDownload: '从 GitHub 下载',
updaterExperimentalHint: '自动更新功能仍在开发中',
updaterVersion: 'v{{version}} 已发布',
updaterWebsite: '官网',
},
settings: {
title: '设置',
@@ -341,7 +336,6 @@ export const zhTranslation = {
languageZh: '中文',
languageNb: '挪威',
languageRu: '俄语',
languageRu2: '俄语 2',
font: '字体',
theme: '主题',
appearance: '外观',
@@ -401,6 +395,8 @@ export const zhTranslation = {
cacheDesc: '封面和艺术家图片。存满时,最旧的条目将自动移除。离线专辑不会自动移除,但手动清除缓存时会被删除。',
cacheUsedImages: '图片:',
cacheUsedOffline: '离线曲目:',
cacheUsedHot: '占用空间:',
hotCacheTrackCount: '缓存曲目数:',
cacheMaxLabel: '最大容量',
cacheClearBtn: '清除缓存',
cacheClearWarning: '这将同时移除音乐库中的所有离线专辑。',
@@ -412,6 +408,22 @@ export const zhTranslation = {
offlineDirChange: '更改目录',
offlineDirClear: '重置为默认',
offlineDirHint: '新下载将保存到此位置,现有下载保留在原始路径。',
hotCacheTitle: '热播放缓存',
hotCacheAlphaBadge: '预览',
hotCacheDisclaimer: '预加载队列中即将播放的曲目并保留近期已播放的。开启后占用磁盘与网络。',
hotCacheDirDefault: '默认(应用数据)',
hotCacheDirChange: '更改目录',
hotCacheDirClear: '重置为默认',
hotCacheDirHint: '更换目录会重置应用内索引;已下载的文件仍留在原路径,需自行删除。',
hotCacheEnabled: '启用热播放缓存',
hotCacheMaxMb: '最大缓存大小',
hotCacheDebounce: '队列变更去抖',
hotCacheDebounceImmediate: '立即',
hotCacheDebounceSeconds: '{{n}} 秒',
hotCacheClearBtn: '清空热缓存',
hiResTitle: '原生高清晰度播放',
hiResEnabled: '启用原生高清晰度播放',
hiResDesc: "默认强制 44.1 kHz 输出以获得最大稳定性。仅在硬件和网络可靠支持高采样率(88.2 kHz+)时启用。",
showArtistImages: '显示艺术家图片',
showArtistImagesDesc: '在艺术家概览中加载并显示艺术家图片。默认关闭以减少大型音乐库的服务器磁盘I/O和网络负载。',
showTrayIcon: '显示托盘图标',
@@ -422,6 +434,8 @@ export const zhTranslation = {
discordRichPresenceDesc: '在 Discord 个人资料上显示当前播放的曲目。需要 Discord 处于运行状态。',
nowPlayingEnabled: '在实时窗口中显示',
nowPlayingEnabledDesc: '将当前播放的曲目广播到服务器的实时听众视图。禁用以停止发送播放数据。',
lyricsServerFirst: '优先使用服务器歌词',
lyricsServerFirstDesc: '先查询服务器提供的歌词(内嵌标签、sidecar 文件),再查询 LRCLIB。禁用则优先使用 LRCLIB。',
downloadsTitle: 'ZIP 导出与归档',
downloadsFolderDesc: '将专辑以 ZIP 文件下载到电脑时的目标文件夹。',
downloadsDefault: '默认下载文件夹',
@@ -544,7 +558,7 @@ export const zhTranslation = {
a11: '首页顶部的横幅会随机从您的音乐库中选择专辑,每 10 秒轮换一次。点击圆点可跳转到特定专辑,或点击横幅打开专辑。',
s4: '设置',
q12: '如何更改主题?',
a12: '设置 → 主题。从 8 个分组中的大量主题中选择:Psysonic 主题、媒体播放器、操作系统、游戏、电影、电视剧、社交媒体,以及开源经典(Catppuccin、Nord、Gruvbox)。',
a12: '设置 → 主题。从 8 个分组中的大量主题中选择:Psysonic 主题、媒体播放器、操作系统、游戏、电影、电视剧、社交媒体,以及开源经典(Catppuccin、Nord、Gruvbox、Nightfox)。',
q13: '如何更改语言?',
a13: '设置 → 语言。支持英语、德语、法语、荷兰语和中文。',
q15: '如何设置下载文件夹?',
@@ -685,8 +699,11 @@ export const zhTranslation = {
volume: '音量',
toggleQueue: '切换队列',
lyrics: '歌词',
fsLyricsToggle: '全屏歌词',
lyricsLoading: '正在加载歌词…',
lyricsNotFound: '未找到此曲目的歌词',
lyricsSourceServer: '来源:服务器',
lyricsSourceLrclib: '来源:LRCLIB',
},
songInfo: {
title: '歌曲信息',
+5 -3
View File
@@ -11,6 +11,7 @@ import AlbumRow from '../components/AlbumRow';
import ArtistRow from '../components/ArtistRow';
import CustomSelect from '../components/CustomSelect';
import { useDragDrop } from '../contexts/DragDropContext';
import { useAuthStore } from '../store/authStore';
type ResultType = 'all' | 'artists' | 'albums' | 'songs';
@@ -31,6 +32,7 @@ interface Results {
export default function AdvancedSearch() {
const { t } = useTranslation();
const [params] = useSearchParams();
const qFromUrl = params.get('q') ?? '';
const navigate = useNavigate();
const psyDrag = useDragDrop();
const playTrack = usePlayerStore(s => s.playTrack);
@@ -46,6 +48,7 @@ export default function AdvancedSearch() {
const [loading, setLoading] = useState(false);
const [hasSearched, setHasSearched] = useState(false);
const [genreNote, setGenreNote] = useState(false);
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const runSearch = async (opts: SearchOpts) => {
setLoading(true);
@@ -109,9 +112,8 @@ export default function AdvancedSearch() {
getGenres().then(data =>
setGenres(data.sort((a, b) => a.value.localeCompare(b.value)))
).catch(() => {});
const q = params.get('q') ?? '';
if (q) runSearch({ query: q, genre: '', yearFrom: '', yearTo: '', resultType: 'all' });
}, []);
if (qFromUrl) runSearch({ query: qFromUrl, genre: '', yearFrom: '', yearTo: '', resultType: 'all' });
}, [musicLibraryFilterVersion, qFromUrl]);
const handleSubmit = (e?: React.FormEvent) => {
e?.preventDefault();
+4 -2
View File
@@ -3,6 +3,7 @@ import AlbumCard from '../components/AlbumCard';
import GenreFilterBar from '../components/GenreFilterBar';
import { getAlbumList, getAlbumsByGenre, SubsonicAlbum } from '../api/subsonic';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { X } from 'lucide-react';
type SortType = 'alphabeticalByName' | 'alphabeticalByArtist';
@@ -18,6 +19,7 @@ async function fetchByGenres(genres: string[]): Promise<SubsonicAlbum[]> {
export default function Albums() {
const { t } = useTranslation();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
const [sort, setSort] = useState<SortType>('alphabeticalByName');
const [loading, setLoading] = useState(true);
@@ -50,7 +52,7 @@ export default function Albums() {
} finally {
setLoading(false);
}
}, []);
}, [musicLibraryFilterVersion]);
const loadFiltered = useCallback(async (genres: string[], sortType: SortType) => {
setLoading(true);
@@ -66,7 +68,7 @@ export default function Albums() {
} finally {
setLoading(false);
}
}, []);
}, [musicLibraryFilterVersion]);
useEffect(() => {
setPage(0);
+79 -11
View File
@@ -1,10 +1,10 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { getArtist, getArtistInfo, getTopSongs, getSimilarSongs2, getAlbum, search, SubsonicArtist, SubsonicAlbum, SubsonicSong, SubsonicArtistInfo, buildCoverArtUrl, coverArtCacheKey, star, unstar } from '../api/subsonic';
import { getArtist, getArtistInfo, getTopSongs, getSimilarSongs2, getAlbum, search, SubsonicArtist, SubsonicAlbum, SubsonicSong, SubsonicArtistInfo, buildCoverArtUrl, coverArtCacheKey, star, unstar, uploadArtistImage } from '../api/subsonic';
import AlbumCard from '../components/AlbumCard';
import CachedImage from '../components/CachedImage';
import CoverLightbox from '../components/CoverLightbox';
import { ArrowLeft, Users, ExternalLink, Heart, Play, Shuffle, Radio, HardDriveDownload, Check } from 'lucide-react';
import { ArrowLeft, Users, ExternalLink, Heart, Play, Shuffle, Radio, HardDriveDownload, Check, Camera, Loader2 } from 'lucide-react';
import { open } from '@tauri-apps/plugin-shell';
import { usePlayerStore, songToTrack } from '../store/playerStore';
import { useOfflineStore } from '../store/offlineStore';
@@ -12,6 +12,8 @@ import { useAuthStore } from '../store/authStore';
import { useTranslation } from 'react-i18next';
import { lastfmGetSimilarArtists, lastfmIsConfigured } from '../api/lastfm';
import LastfmIcon from '../components/LastfmIcon';
import { invalidateCoverArt } from '../utils/imageCache';
import { showToast } from '../utils/toast';
function formatDuration(seconds: number): string {
const m = Math.floor(seconds / 60);
@@ -55,6 +57,10 @@ export default function ArtistDetail() {
const [similarLoading, setSimilarLoading] = useState(false);
const [featuredLoading, setFeaturedLoading] = useState(false);
const [lightboxOpen, setLightboxOpen] = useState(false);
const [bioExpanded, setBioExpanded] = useState(false);
const [uploading, setUploading] = useState(false);
const [coverRevision, setCoverRevision] = useState(0);
const imageInputRef = useRef<HTMLInputElement>(null);
const playTrack = usePlayerStore(state => state.playTrack);
const enqueue = usePlayerStore(state => state.enqueue);
@@ -64,6 +70,7 @@ export default function ArtistDetail() {
const isPlaying = usePlayerStore(state => state.isPlaying);
const { downloadArtist, bulkProgress } = useOfflineStore();
const activeServerId = useAuthStore(s => s.activeServerId) ?? '';
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
useEffect(() => {
if (!id) return;
@@ -120,7 +127,7 @@ export default function ArtistDetail() {
setFeaturedAlbums([...albumMap.values()]);
setFeaturedLoading(false);
});
}, [artist?.id]);
}, [artist?.id, musicLibraryFilterVersion]);
useEffect(() => {
if (!artist || !lastfmIsConfigured()) return;
@@ -146,7 +153,7 @@ export default function ArtistDetail() {
setSimilarArtists(found);
setSimilarLoading(false);
}).catch(() => setSimilarLoading(false));
}, [artist?.id]);
}, [artist?.id, musicLibraryFilterVersion]);
const openLink = (url: string, key: string) => {
open(url);
@@ -233,6 +240,32 @@ export default function ArtistDetail() {
}
};
const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
e.target.value = '';
if (!file || !artist) return;
setUploading(true);
try {
await uploadArtistImage(artist.id, file);
const coverId = artist.coverArt || artist.id;
await invalidateCoverArt(coverId);
// Also invalidate with bare artist.id in case coverArt differs
if (artist.coverArt && artist.coverArt !== artist.id) {
await invalidateCoverArt(artist.id);
}
setCoverRevision(r => r + 1);
showToast(t('artistDetail.uploadImage'));
} catch (err) {
showToast(
typeof err === 'string' ? err : err instanceof Error ? err.message : t('artistDetail.uploadImageError'),
4000,
'error',
);
} finally {
setUploading(false);
}
};
if (loading) {
return (
<div className="content-body" style={{ display: 'flex', justifyContent: 'center', padding: '4rem' }}>
@@ -273,7 +306,7 @@ export default function ArtistDetail() {
)}
<div className="artist-detail-header">
<div className="artist-detail-avatar">
<div className="artist-detail-avatar" style={{ position: 'relative' }}>
{coverId ? (
<button
className="artist-detail-avatar-btn"
@@ -281,6 +314,7 @@ export default function ArtistDetail() {
aria-label={`${artist.name} Bild vergrößern`}
>
<CachedImage
key={coverRevision}
src={buildCoverArtUrl(coverId, 300)}
cacheKey={coverArtCacheKey(coverId, 300)}
alt={artist.name}
@@ -291,6 +325,22 @@ export default function ArtistDetail() {
) : (
<Users size={64} color="var(--text-muted)" />
)}
{/* Upload overlay */}
<div
className="artist-avatar-upload-overlay"
onClick={e => { e.stopPropagation(); imageInputRef.current?.click(); }}
>
{uploading
? <Loader2 size={22} className="spin-slow" />
: <Camera size={22} />}
</div>
<input
ref={imageInputRef}
type="file"
accept="image/*"
style={{ display: 'none' }}
onChange={handleImageUpload}
/>
</div>
<div className="artist-detail-meta">
@@ -373,11 +423,29 @@ export default function ArtistDetail() {
{/* Biography — sanitized HTML from server */}
{info?.biography && (
<div className="artist-bio-section">
<div
className="artist-bio-text"
dangerouslySetInnerHTML={{ __html: sanitizeHtml(info.biography) }}
/>
<div className="np-info-card artist-bio-card">
<div className="np-card-header">
<h3 className="np-card-title">{t('nowPlaying.aboutArtist')}</h3>
</div>
<div className="np-artist-bio-row">
{(info.largeImageUrl || coverId) && (
<img
src={info.largeImageUrl || buildCoverArtUrl(coverId, 80)}
alt={artist.name}
className="np-artist-thumb"
onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }}
/>
)}
<div className="np-bio-wrap">
<div
className={`np-bio-text${bioExpanded ? ' expanded' : ''}`}
dangerouslySetInnerHTML={{ __html: sanitizeHtml(info.biography) }}
/>
<button className="np-bio-toggle" onClick={() => setBioExpanded(v => !v)}>
{bioExpanded ? t('nowPlaying.showLess') : t('nowPlaying.readMore')}
</button>
</div>
</div>
</div>
)}
+2 -1
View File
@@ -86,10 +86,11 @@ export default function Artists() {
const openContextMenu = usePlayerStore(state => state.openContextMenu);
const showArtistImages = useAuthStore(s => s.showArtistImages);
const setShowArtistImages = useAuthStore(s => s.setShowArtistImages);
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
useEffect(() => {
getArtists().then(data => { setArtists(data); setLoading(false); }).catch(() => setLoading(false));
}, []);
}, [musicLibraryFilterVersion]);
const loadMore = useCallback(() => {
setVisibleCount(prev => prev + 50);
+3 -1
View File
@@ -14,6 +14,7 @@ import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { unstar } from '../api/subsonic';
import { useDragDrop } from '../contexts/DragDropContext';
import { useAuthStore } from '../store/authStore';
const FAV_COLUMNS: readonly ColDef[] = [
{ key: 'num', i18nKey: null, minWidth: 60, defaultWidth: 60, required: true },
@@ -63,6 +64,7 @@ export default function Favorites() {
const openContextMenu = usePlayerStore(s => s.openContextMenu);
const navigate = useNavigate();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
useEffect(() => {
const loadAll = async () => {
@@ -87,7 +89,7 @@ export default function Favorites() {
setLoading(false);
};
loadAll();
}, []);
}, [musicLibraryFilterVersion]);
if (loading) {
return (
+2
View File
@@ -3,6 +3,7 @@ import { useParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ArrowLeft, Disc3 } from 'lucide-react';
import { getAlbumsByGenre, SubsonicAlbum } from '../api/subsonic';
import { useAuthStore } from '../store/authStore';
import AlbumCard from '../components/AlbumCard';
const PAGE_SIZE = 50;
@@ -17,6 +18,7 @@ export default function GenreDetail() {
const [loadingMore, setLoadingMore] = useState(false);
const [hasMore, setHasMore] = useState(true);
const [offset, setOffset] = useState(0);
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
useEffect(() => {
setAlbums([]);
+2 -1
View File
@@ -7,6 +7,7 @@ import {
Tags, type LucideIcon,
} from 'lucide-react';
import { getGenres, SubsonicGenre } from '../api/subsonic';
import { useAuthStore } from '../store/authStore';
function getGenreIcon(name: string): LucideIcon {
const n = name.toLowerCase();
@@ -59,7 +60,7 @@ export default function Genres() {
setGenres(sorted);
})
.finally(() => setLoading(false));
}, []);
}, []); // getGenres is not folder-scoped — no dep on musicLibraryFilterVersion
// Restore scroll position after genres are rendered
useEffect(() => {
+3 -1
View File
@@ -6,9 +6,11 @@ import { useTranslation } from 'react-i18next';
import { NavLink, useNavigate } from 'react-router-dom';
import { ChevronRight } from 'lucide-react';
import { useHomeStore } from '../store/homeStore';
import { useAuthStore } from '../store/authStore';
export default function Home() {
const homeSections = useHomeStore(s => s.sections);
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const isVisible = (id: string) => homeSections.find(s => s.id === id)?.visible ?? true;
const [starred, setStarred] = useState<SubsonicAlbum[]>([]);
@@ -44,7 +46,7 @@ export default function Home() {
setRandomArtists(shuffled.slice(0, 16));
setLoading(false);
}).catch(() => setLoading(false));
}, []);
}, [musicLibraryFilterVersion, homeSections]);
const loadMore = async (
type: 'starred' | 'newest' | 'random' | 'frequent' | 'recent',
+4
View File
@@ -11,6 +11,7 @@ import {
} from '../api/subsonic';
import { usePlayerStore } from '../store/playerStore';
import CachedImage from '../components/CachedImage';
import { invalidateCoverArt } from '../utils/imageCache';
import CustomSelect from '../components/CustomSelect';
import { useTranslation } from 'react-i18next';
import { open } from '@tauri-apps/plugin-shell';
@@ -141,6 +142,7 @@ export default function InternetRadio() {
if (created) {
try {
await uploadRadioCoverArt(created.id, opts.coverFile);
await invalidateCoverArt(`ra-${created.id}`);
} catch (err) {
showToast(typeof err === 'string' ? err : err instanceof Error ? err.message : 'Cover upload failed', 4000, 'error');
}
@@ -163,11 +165,13 @@ export default function InternetRadio() {
if (opts.coverFile) {
try {
await uploadRadioCoverArt(id, opts.coverFile);
await invalidateCoverArt(`ra-${id}`);
} catch (err) {
showToast(typeof err === 'string' ? err : err instanceof Error ? err.message : 'Cover upload failed', 4000, 'error');
}
} else if (opts.coverRemoved) {
await deleteRadioCoverArt(id).catch(() => {});
await invalidateCoverArt(`ra-${id}`);
}
await reload();
}
+3 -1
View File
@@ -4,6 +4,7 @@ import { ChevronLeft } from 'lucide-react';
import AlbumCard from '../components/AlbumCard';
import { search, SubsonicAlbum } from '../api/subsonic';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
export default function LabelAlbums() {
const { t } = useTranslation();
@@ -11,6 +12,7 @@ export default function LabelAlbums() {
const navigate = useNavigate();
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
const [loading, setLoading] = useState(true);
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
useEffect(() => {
if (!name) return;
@@ -31,7 +33,7 @@ export default function LabelAlbums() {
})
.catch(console.error)
.finally(() => setLoading(false));
}, [name]);
}, [name, musicLibraryFilterVersion]);
return (
<div className="animate-fade-in" style={{ padding: '0 var(--space-6)' }}>
+3 -1
View File
@@ -3,6 +3,7 @@ import AlbumCard from '../components/AlbumCard';
import GenreFilterBar from '../components/GenreFilterBar';
import { getAlbumList, getAlbumsByGenre, SubsonicAlbum } from '../api/subsonic';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
const PAGE_SIZE = 30;
@@ -15,6 +16,7 @@ async function fetchByGenres(genres: string[]): Promise<SubsonicAlbum[]> {
export default function NewReleases() {
const { t } = useTranslation();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(0);
@@ -43,7 +45,7 @@ export default function NewReleases() {
} finally {
setLoading(false);
}
}, []);
}, [musicLibraryFilterVersion]);
useEffect(() => {
if (filtered) loadFiltered(selectedGenres);
+3 -1
View File
@@ -4,6 +4,7 @@ import { getAlbumList, getAlbumsByGenre, SubsonicAlbum } from '../api/subsonic';
import AlbumCard from '../components/AlbumCard';
import GenreFilterBar from '../components/GenreFilterBar';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
const ALBUM_COUNT = 30;
@@ -21,6 +22,7 @@ async function fetchByGenres(genres: string[]): Promise<SubsonicAlbum[]> {
export default function RandomAlbums() {
const { t } = useTranslation();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
const [loading, setLoading] = useState(true);
const [selectedGenres, setSelectedGenres] = useState<string[]>([]);
@@ -42,7 +44,7 @@ export default function RandomAlbums() {
loadingRef.current = false;
setLoading(false);
}
}, []);
}, [musicLibraryFilterVersion]);
useEffect(() => { load(selectedGenres); }, [selectedGenres, load]);
+2 -1
View File
@@ -36,6 +36,7 @@ export default function RandomMix() {
const psyDrag = useDragDrop();
const [starredSongs, setStarredSongs] = useState<Set<string>>(new Set());
const { excludeAudiobooks, setExcludeAudiobooks, customGenreBlacklist, setCustomGenreBlacklist } = useAuthStore();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const [addedGenre, setAddedGenre] = useState<string | null>(null);
const [addedArtist, setAddedArtist] = useState<string | null>(null);
@@ -82,7 +83,7 @@ export default function RandomMix() {
setAllAvailableGenres(available);
setDisplayedGenres(available.slice(0, 20));
}).catch(() => {});
}, []);
}, [musicLibraryFilterVersion]);
const filteredSongs = songs.filter(song => {
if (!excludeAudiobooks) return true;
+3 -1
View File
@@ -7,6 +7,7 @@ import AlbumRow from '../components/AlbumRow';
import ArtistRow from '../components/ArtistRow';
import { useTranslation } from 'react-i18next';
import { useDragDrop } from '../contexts/DragDropContext';
import { useAuthStore } from '../store/authStore';
function formatDuration(s: number) {
return `${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, '0')}`;
@@ -21,6 +22,7 @@ export default function SearchResults() {
const playTrack = usePlayerStore(s => s.playTrack);
const currentTrack = usePlayerStore(s => s.currentTrack);
const psyDrag = useDragDrop();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
useEffect(() => {
if (!query.trim()) { setResults(null); return; }
@@ -28,7 +30,7 @@ export default function SearchResults() {
search(query, { artistCount: 20, albumCount: 20, songCount: 50 })
.then(r => setResults(r))
.finally(() => setLoading(false));
}, [query]);
}, [query, musicLibraryFilterVersion]);
const hasResults = results && (results.artists.length || results.albums.length || results.songs.length);
+249 -10
View File
@@ -5,7 +5,7 @@ import { useNavigate, useLocation } from 'react-router-dom';
import {
Wifi, WifiOff, Globe, Music2, Sliders, LogOut, CheckCircle2, FolderOpen,
Palette, Server, Plus, Trash2, Eye, EyeOff, Info, ExternalLink, Shuffle, X, Play, Type, Keyboard, ChevronDown,
GripVertical, PanelLeft, RotateCcw, LayoutGrid, AppWindow, HardDrive, Upload, Download
GripVertical, PanelLeft, RotateCcw, LayoutGrid, AppWindow, HardDrive, Upload, Download, Waves
} from 'lucide-react';
import { exportBackup, importBackup } from '../utils/backup';
import { showToast } from '../utils/toast';
@@ -13,6 +13,7 @@ import { invoke } from '@tauri-apps/api/core';
import { open as openUrl } from '@tauri-apps/plugin-shell';
import { getImageCacheSize, clearImageCache } from '../utils/imageCache';
import { useOfflineStore } from '../store/offlineStore';
import { useHotCacheStore } from '../store/hotCacheStore';
import { lastfmGetToken, lastfmAuthUrl, lastfmGetSession, lastfmGetUserInfo, LastfmUserInfo } from '../api/lastfm';
import LastfmIcon from '../components/LastfmIcon';
import CustomSelect from '../components/CustomSelect';
@@ -87,13 +88,24 @@ const CONTRIBUTORS = [
since: '1.33.0',
contributions: [
'Russian translation & i18n locale split (PR #106)',
'Gapless manual skip: honor user-initiated play over pre-chained track (PR #119)',
'Per-server music folder filter and sidebar library picker (PR #125)',
],
},
{
github: 'kilyabin',
since: '1.34.0',
contributions: [
'Alternative Russian translation (PR #107)',
'Russian locale improvements (PR #107, PR #120)',
'Auto-install script for Debian / RHEL (PR #121)',
],
},
{
github: 'nisrael',
since: '1.34.0',
contributions: [
'Nightfox.nvim theme group in Open Source Classics (PR #114)',
'Switch reqwest to rustls-tls for cross-platform TLS (PR #112)',
],
},
] as const;
@@ -171,6 +183,12 @@ function formatBytes(bytes: number): string {
return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
}
/** Align hot-cache size slider (step 32 MB) to valid values. */
function snapHotCacheMb(v: number): number {
const x = Math.min(20000, Math.max(32, Math.round(v)));
return Math.round((x - 32) / 32) * 32 + 32;
}
export default function Settings() {
const auth = useAuthStore();
const theme = useThemeStore();
@@ -179,6 +197,13 @@ export default function Settings() {
const gs = useGlobalShortcutsStore();
const serverId = auth.activeServerId ?? '';
const clearAllOffline = useOfflineStore(s => s.clearAll);
const clearHotCacheDisk = useHotCacheStore(s => s.clearAllDisk);
const hotCacheEntries = useHotCacheStore(s => s.entries);
const hotCacheTrackCount = useMemo(() => {
if (!serverId) return 0;
const prefix = `${serverId}:`;
return Object.keys(hotCacheEntries).filter(k => k.startsWith(prefix)).length;
}, [hotCacheEntries, serverId]);
const [listeningFor, setListeningFor] = useState<KeyAction | null>(null);
const [listeningForGlobal, setListeningForGlobal] = useState<GlobalAction | null>(null);
const navigate = useNavigate();
@@ -195,6 +220,7 @@ export default function Settings() {
const [lfmUserInfo, setLfmUserInfo] = useState<LastfmUserInfo | null>(null);
const [imageCacheBytes, setImageCacheBytes] = useState<number | null>(null);
const [offlineCacheBytes, setOfflineCacheBytes] = useState<number | null>(null);
const [hotCacheBytes, setHotCacheBytes] = useState<number | null>(null);
const [showClearConfirm, setShowClearConfirm] = useState(false);
const [clearing, setClearing] = useState(false);
const [contributorsOpen, setContributorsOpen] = useState(false);
@@ -208,7 +234,8 @@ export default function Settings() {
if (activeTab !== 'storage') return;
getImageCacheSize().then(setImageCacheBytes);
invoke<number>('get_offline_cache_size', { customDir: auth.offlineDownloadDir || null }).then(setOfflineCacheBytes).catch(() => setOfflineCacheBytes(0));
}, [activeTab]);
invoke<number>('get_hot_cache_size', { customDir: auth.hotCacheDownloadDir || null }).then(setHotCacheBytes).catch(() => setHotCacheBytes(0));
}, [activeTab, auth.offlineDownloadDir, auth.hotCacheDownloadDir]);
const handleClearCache = useCallback(async () => {
setClearing(true);
@@ -329,6 +356,15 @@ export default function Settings() {
}
};
const pickHotCacheDir = async () => {
const selected = await openDialog({ directory: true, multiple: false, title: t('settings.hotCacheDirChange') });
if (selected && typeof selected === 'string') {
auth.setHotCacheDownloadDir(selected);
useHotCacheStore.setState({ entries: {} });
invoke<number>('get_hot_cache_size', { customDir: selected }).then(setHotCacheBytes).catch(() => setHotCacheBytes(0));
}
};
const pickDownloadFolder = async () => {
const selected = await openDialog({ directory: true, multiple: false, title: t('settings.pickFolderTitle') });
if (selected && typeof selected === 'string') {
@@ -510,6 +546,41 @@ export default function Settings() {
</div>
</section>
{/* Native Hi-Res Playback */}
<section className="settings-section">
<div className="settings-section-header">
<Waves size={18} />
<h2 style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{t('settings.hiResTitle')}
<span style={{
fontSize: 10, fontWeight: 600, textTransform: 'uppercase',
letterSpacing: '0.04em', padding: '2px 6px', borderRadius: 4,
background: 'color-mix(in srgb, var(--color-warning, #f59e0b) 22%, transparent)',
color: 'var(--text-primary)',
}}>
{t('settings.hotCacheAlphaBadge')}
</span>
</h2>
</div>
<div className="settings-card">
<div className="settings-toggle-row">
<div>
<div style={{ fontWeight: 500 }}>{t('settings.hiResEnabled')}</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('settings.hiResDesc')}</div>
</div>
<label className="toggle-switch" aria-label={t('settings.hiResEnabled')}>
<input
type="checkbox"
checked={auth.enableHiRes}
onChange={e => auth.setEnableHiRes(e.target.checked)}
id="hires-enabled-toggle"
/>
<span className="toggle-track" />
</label>
</div>
</div>
</section>
</>
)}
@@ -577,6 +648,17 @@ export default function Settings() {
<span className="toggle-track" />
</label>
</div>
<div className="settings-section-divider" />
<div className="settings-toggle-row">
<div>
<div style={{ fontWeight: 500 }}>{t('settings.lyricsServerFirst')}</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('settings.lyricsServerFirstDesc')}</div>
</div>
<label className="toggle-switch" aria-label={t('settings.lyricsServerFirst')}>
<input type="checkbox" checked={auth.lyricsServerFirst} onChange={e => auth.setLyricsServerFirst(e.target.checked)} />
<span className="toggle-track" />
</label>
</div>
</div>
</section>
@@ -767,6 +849,164 @@ export default function Settings() {
</div>
</section>
<section className="settings-section">
<div className="settings-section-header">
<HardDrive size={18} />
<h2 style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
{t('settings.hotCacheTitle')}
<span
style={{
fontSize: 10,
fontWeight: 600,
textTransform: 'uppercase',
letterSpacing: '0.04em',
padding: '2px 6px',
borderRadius: 4,
background: 'color-mix(in srgb, var(--color-warning, #f59e0b) 22%, transparent)',
color: 'var(--text-primary)',
}}
>
{t('settings.hotCacheAlphaBadge')}
</span>
</h2>
</div>
<div className="settings-card">
<div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 14, lineHeight: 1.5 }}>
{t('settings.hotCacheDisclaimer')}
</div>
<div className="settings-toggle-row">
<div>
<div style={{ fontWeight: 500 }}>{t('settings.hotCacheEnabled')}</div>
</div>
<label className="toggle-switch" aria-label={t('settings.hotCacheEnabled')}>
<input
type="checkbox"
checked={auth.hotCacheEnabled}
onChange={async e => {
const enabled = e.target.checked;
if (!enabled) {
await clearHotCacheDisk(auth.hotCacheDownloadDir || null);
setHotCacheBytes(0);
auth.setHotCacheEnabled(false);
} else {
auth.setHotCacheEnabled(true);
invoke<number>('get_hot_cache_size', { customDir: auth.hotCacheDownloadDir || null })
.then(setHotCacheBytes)
.catch(() => setHotCacheBytes(0));
}
}}
id="hot-cache-enabled-toggle"
/>
<span className="toggle-track" />
</label>
</div>
{auth.hotCacheEnabled && (
<div style={{ marginTop: '1.25rem' }}>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<input
className="input"
type="text"
readOnly
value={auth.hotCacheDownloadDir || t('settings.hotCacheDirDefault')}
style={{ flex: 1, fontSize: 13, color: auth.hotCacheDownloadDir ? 'var(--text-primary)' : 'var(--text-muted)', cursor: 'default' }}
/>
{auth.hotCacheDownloadDir && (
<button
type="button"
className="btn btn-ghost"
onClick={() => {
auth.setHotCacheDownloadDir('');
useHotCacheStore.setState({ entries: {} });
invoke<number>('get_hot_cache_size', { customDir: null }).then(setHotCacheBytes).catch(() => setHotCacheBytes(0));
}}
data-tooltip={t('settings.hotCacheDirClear')}
style={{ color: 'var(--text-muted)', flexShrink: 0 }}
>
<X size={16} />
</button>
)}
<button type="button" className="btn btn-surface" onClick={pickHotCacheDir} style={{ flexShrink: 0 }}>
<FolderOpen size={16} /> {t('settings.hotCacheDirChange')}
</button>
</div>
{auth.hotCacheDownloadDir && (
<div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 8, lineHeight: 1.4 }}>
{t('settings.hotCacheDirHint')}
</div>
)}
<div style={{ borderTop: '1px solid var(--border)', margin: '16px 0' }} />
<div style={{ fontSize: 12, marginBottom: 12, display: 'flex', flexDirection: 'column', gap: 3 }}>
<div style={{ color: 'var(--text-secondary)' }}>
<span style={{ color: 'var(--text-muted)', marginRight: 4 }}>{t('settings.cacheUsedHot')}</span>
{hotCacheBytes !== null ? formatBytes(hotCacheBytes) : '…'}
</div>
<div style={{ color: 'var(--text-secondary)' }}>
<span style={{ color: 'var(--text-muted)', marginRight: 4 }}>{t('settings.hotCacheTrackCount')}</span>
{hotCacheTrackCount}
</div>
</div>
<div>
<div style={{ fontWeight: 500, marginBottom: 6 }}>{t('settings.hotCacheMaxMb')}</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
<input
type="range"
min={32}
max={20000}
step={32}
value={snapHotCacheMb(auth.hotCacheMaxMb)}
onChange={e => auth.setHotCacheMaxMb(parseInt(e.target.value, 10))}
style={{ width: 140 }}
id="hot-cache-max-mb-slider"
/>
<span style={{ fontSize: 13, color: 'var(--text-secondary)', minWidth: 72 }}>
{snapHotCacheMb(auth.hotCacheMaxMb)} MB
</span>
</div>
</div>
<div style={{ marginTop: '0.75rem' }}>
<div style={{ fontWeight: 500, marginBottom: 6 }}>{t('settings.hotCacheDebounce')}</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
<input
type="range"
min={0}
max={600}
step={1}
value={Math.min(600, Math.max(0, auth.hotCacheDebounceSec))}
onChange={e => auth.setHotCacheDebounceSec(parseInt(e.target.value, 10))}
style={{ width: 140 }}
id="hot-cache-debounce-slider"
/>
<span style={{ fontSize: 13, color: 'var(--text-secondary)', minWidth: 100 }}>
{Math.min(600, Math.max(0, auth.hotCacheDebounceSec)) === 0
? t('settings.hotCacheDebounceImmediate')
: t('settings.hotCacheDebounceSeconds', { n: Math.min(600, Math.max(0, auth.hotCacheDebounceSec)) })}
</span>
</div>
</div>
<div style={{ borderTop: '1px solid var(--border)', margin: '16px 0' }} />
<button
type="button"
className="btn btn-ghost"
style={{ fontSize: 13 }}
onClick={async () => {
await clearHotCacheDisk(auth.hotCacheDownloadDir || null);
const b = await invoke<number>('get_hot_cache_size', { customDir: auth.hotCacheDownloadDir || null }).catch(() => 0);
setHotCacheBytes(b);
}}
>
<Trash2 size={14} /> {t('settings.hotCacheClearBtn')}
</button>
</div>
)}
</div>
</section>
{/* ZIP Export & Archiving */}
<section className="settings-section">
<div className="settings-section-header">
@@ -825,7 +1065,6 @@ export default function Settings() {
{ value: 'nl', label: t('settings.languageNl') },
{ value: 'nb', label: t('settings.languageNb') },
{ value: 'ru', label: t('settings.languageRu') },
{ value: 'ru2', label: t('settings.languageRu2') },
{ value: 'zh', label: t('settings.languageZh') },
]}
/>
@@ -1206,6 +1445,12 @@ export default function Settings() {
</div>
</section>
<section className="settings-section">
<button className="btn btn-danger" onClick={handleLogout} id="settings-logout-btn">
<LogOut size={16} /> {t('settings.logout')}
</button>
</section>
</>
)}
@@ -1335,12 +1580,6 @@ export default function Settings() {
</section>
<ChangelogSection />
<section className="settings-section">
<button className="btn btn-ghost" style={{ color: 'var(--danger)' }} onClick={handleLogout} id="settings-logout-btn">
<LogOut size={16} /> {t('settings.logout')}
</button>
</section>
</>
)}
</div>
+4 -3
View File
@@ -33,6 +33,7 @@ const PERIODS: { key: LastfmPeriod; label: string }[] = [
export default function Statistics() {
const { t } = useTranslation();
const { lastfmSessionKey, lastfmUsername } = useAuthStore();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const [recent, setRecent] = useState<SubsonicAlbum[]>([]);
const [frequent, setFrequent] = useState<SubsonicAlbum[]>([]);
const [highest, setHighest] = useState<SubsonicAlbum[]>([]);
@@ -73,7 +74,7 @@ export default function Statistics() {
setGenres(sorted);
setLoading(false);
}).catch(() => setLoading(false));
}, []);
}, [musicLibraryFilterVersion]);
// Background fetch: total playtime (paginate getAlbumList up to 10 pages of 500)
useEffect(() => {
@@ -102,7 +103,7 @@ export default function Statistics() {
}
})();
return () => { cancelled = true; };
}, []);
}, [musicLibraryFilterVersion]);
// Background fetch: format distribution (sample of 500 random songs)
useEffect(() => {
@@ -121,7 +122,7 @@ export default function Statistics() {
setFormatSampleSize(songs.length);
}).catch(() => {});
return () => { cancelled = true; };
}, []);
}, [musicLibraryFilterVersion]);
useEffect(() => {
if (!lastfmIsConfigured() || !lastfmSessionKey || !lastfmUsername) return;
+78 -2
View File
@@ -42,9 +42,31 @@ interface AuthState {
minimizeToTray: boolean;
discordRichPresence: boolean;
nowPlayingEnabled: boolean;
lyricsServerFirst: boolean;
showFullscreenLyrics: boolean;
showChangelogOnUpdate: boolean;
lastSeenChangelogVersion: string;
/** Alpha: native hi-res sample rate output (disabled = safe 44.1 kHz mode) */
enableHiRes: boolean;
/** Alpha: ephemeral queue prefetch cache on disk */
hotCacheEnabled: boolean;
hotCacheMaxMb: number;
hotCacheDebounceSec: number;
/** Parent directory; actual cache is `<dir>/psysonic-hot-cache/`. Empty = app data. */
hotCacheDownloadDir: string;
/** Subsonic music folders for the active server (not persisted; refetched on login / server change). */
musicFolders: Array<{ id: string; name: string }>;
/**
* Per server: `all` = no musicFolderId param; otherwise a single folder id.
* Only one library or all no multi-folder merge.
*/
musicLibraryFilterByServer: Record<string, 'all' | string>;
/** Bumps when `setMusicLibraryFilter` runs so pages refetch catalog data. */
musicLibraryFilterVersion: number;
// Status
isLoggedIn: boolean;
isConnecting: boolean;
@@ -82,8 +104,17 @@ interface AuthState {
setMinimizeToTray: (v: boolean) => void;
setDiscordRichPresence: (v: boolean) => void;
setNowPlayingEnabled: (v: boolean) => void;
setLyricsServerFirst: (v: boolean) => void;
setShowFullscreenLyrics: (v: boolean) => void;
setShowChangelogOnUpdate: (v: boolean) => void;
setLastSeenChangelogVersion: (v: string) => void;
setEnableHiRes: (v: boolean) => void;
setHotCacheEnabled: (v: boolean) => void;
setHotCacheMaxMb: (v: number) => void;
setHotCacheDebounceSec: (v: number) => void;
setHotCacheDownloadDir: (v: string) => void;
setMusicFolders: (folders: Array<{ id: string; name: string }>) => void;
setMusicLibraryFilter: (folderId: 'all' | string) => void;
logout: () => void;
// Derived
@@ -123,8 +154,18 @@ export const useAuthStore = create<AuthState>()(
minimizeToTray: false,
discordRichPresence: false,
nowPlayingEnabled: false,
lyricsServerFirst: true,
showFullscreenLyrics: true,
showChangelogOnUpdate: true,
lastSeenChangelogVersion: '',
enableHiRes: false,
hotCacheEnabled: false,
hotCacheMaxMb: 256,
hotCacheDebounceSec: 30,
hotCacheDownloadDir: '',
musicFolders: [],
musicLibraryFilterByServer: {},
musicLibraryFilterVersion: 0,
isLoggedIn: false,
isConnecting: false,
connectionError: null,
@@ -154,7 +195,7 @@ export const useAuthStore = create<AuthState>()(
});
},
setActiveServer: (id) => set({ activeServerId: id }),
setActiveServer: (id) => set({ activeServerId: id, musicFolders: [] }),
setLoggedIn: (v) => set({ isLoggedIn: v }),
setConnecting: (v) => set({ isConnecting: v }),
@@ -196,10 +237,41 @@ export const useAuthStore = create<AuthState>()(
setMinimizeToTray: (v) => set({ minimizeToTray: v }),
setDiscordRichPresence: (v) => set({ discordRichPresence: v }),
setNowPlayingEnabled: (v) => set({ nowPlayingEnabled: v }),
setLyricsServerFirst: (v: boolean) => set({ lyricsServerFirst: v }),
setShowFullscreenLyrics: (v: boolean) => set({ showFullscreenLyrics: v }),
setShowChangelogOnUpdate: (v) => set({ showChangelogOnUpdate: v }),
setLastSeenChangelogVersion: (v) => set({ lastSeenChangelogVersion: v }),
logout: () => set({ isLoggedIn: false }),
setEnableHiRes: (v) => set({ enableHiRes: v }),
setHotCacheEnabled: (v) => set({ hotCacheEnabled: v }),
setHotCacheMaxMb: (v) => set({ hotCacheMaxMb: v }),
setHotCacheDebounceSec: (v) => set({ hotCacheDebounceSec: v }),
setHotCacheDownloadDir: (v) => set({ hotCacheDownloadDir: v }),
setMusicFolders: (folders) => {
const sid = get().activeServerId;
set(s => {
const f = sid ? s.musicLibraryFilterByServer[sid] : undefined;
const invalidFilter = f && f !== 'all' && !folders.some(x => x.id === f);
return {
musicFolders: folders,
...(sid && invalidFilter
? { musicLibraryFilterByServer: { ...s.musicLibraryFilterByServer, [sid]: 'all' } }
: {}),
};
});
},
setMusicLibraryFilter: (folderId) => {
const sid = get().activeServerId;
if (!sid) return;
set(s => ({
musicLibraryFilterByServer: { ...s.musicLibraryFilterByServer, [sid]: folderId },
musicLibraryFilterVersion: s.musicLibraryFilterVersion + 1,
}));
},
logout: () => set({ isLoggedIn: false, musicFolders: [] }),
getBaseUrl: () => {
const s = get();
@@ -216,6 +288,10 @@ export const useAuthStore = create<AuthState>()(
{
name: 'psysonic-auth',
storage: createJSONStorage(() => localStorage),
partialize: state => {
const { musicFolders: _mf, musicLibraryFilterVersion: _fv, ...rest } = state;
return rest;
},
}
)
);
+183
View File
@@ -0,0 +1,183 @@
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { invoke } from '@tauri-apps/api/core';
import type { Track } from './playerStore';
const PREFETCH_AHEAD = 5;
export interface HotCacheEntry {
localPath: string;
sizeBytes: number;
cachedAt: number;
/** Last time this file was started as the current track (eviction tie-break: newer = keep longer). */
lastPlayedAt?: number;
}
interface HotCacheState {
/** Persisted map `${serverId}:${trackId}` → file meta */
entries: Record<string, HotCacheEntry>;
getLocalUrl: (trackId: string, serverId: string) => string | null;
setEntry: (trackId: string, serverId: string, localPath: string, sizeBytes: number) => void;
/** Bump LRU when the user actually plays this track (if it is in the hot cache). */
touchPlayed: (trackId: string, serverId: string) => void;
removeEntry: (trackId: string, serverId: string) => void;
totalBytes: () => number;
/** Evict until total size ≤ maxBytes. Respects queue tail first, protects current + next N. */
evictToFit: (
queue: Track[],
queueIndex: number,
maxBytes: number,
activeServerId: string,
hotCacheCustomDir: string | null,
) => Promise<void>;
clearAllDisk: (customDir: string | null) => Promise<void>;
}
function entryKey(serverId: string, trackId: string): string {
return `${serverId}:${trackId}`;
}
function parseKey(key: string): { serverId: string; trackId: string } | null {
const i = key.indexOf(':');
if (i <= 0) return null;
return { serverId: key.slice(0, i), trackId: key.slice(i + 1) };
}
function lruStamp(meta: HotCacheEntry | undefined): number {
if (!meta) return 0;
return meta.lastPlayedAt ?? meta.cachedAt ?? 0;
}
export const useHotCacheStore = create<HotCacheState>()(
persist(
(set, get) => ({
entries: {},
getLocalUrl: (trackId, serverId) => {
const e = get().entries[entryKey(serverId, trackId)];
if (!e?.localPath) return null;
return `psysonic-local://${e.localPath}`;
},
setEntry: (trackId, serverId, localPath, sizeBytes) => {
const now = Date.now();
set(s => ({
entries: {
...s.entries,
[entryKey(serverId, trackId)]: {
localPath,
sizeBytes,
cachedAt: now,
lastPlayedAt: now,
},
},
}));
},
touchPlayed: (trackId, serverId) => {
const k = entryKey(serverId, trackId);
set(s => {
const e = s.entries[k];
if (!e) return s;
return {
entries: {
...s.entries,
[k]: { ...e, lastPlayedAt: Date.now() },
},
};
});
},
removeEntry: (trackId, serverId) => {
set(s => {
const next = { ...s.entries };
delete next[entryKey(serverId, trackId)];
return { entries: next };
});
},
totalBytes: () =>
Object.values(get().entries).reduce((acc, e) => acc + (e.sizeBytes || 0), 0),
evictToFit: async (queue, queueIndex, maxBytes, activeServerId, hotCacheCustomDir) => {
if (maxBytes <= 0) return;
const protectLo = Math.max(0, queueIndex);
const protectHi = Math.min(queue.length - 1, queueIndex + PREFETCH_AHEAD);
const protectedIds = new Set<string>();
for (let i = protectLo; i <= protectHi; i++) {
protectedIds.add(queue[i].id);
}
const indexOfInQueue = (trackId: string): number | null => {
const idx = queue.findIndex(t => t.id === trackId);
return idx >= 0 ? idx : null;
};
let entries = { ...get().entries };
let sum = Object.values(entries).reduce((a, e) => a + (e.sizeBytes || 0), 0);
if (sum <= maxBytes) return;
const keys = Object.keys(entries);
type Cand = { key: string; tier: number; primary: number; lru: number };
const cands: Cand[] = [];
for (const key of keys) {
const parsed = parseKey(key);
if (!parsed) continue;
const { serverId, trackId } = parsed;
if (protectedIds.has(trackId) && serverId === activeServerId) continue;
const meta = entries[key];
const lru = lruStamp(meta);
if (serverId !== activeServerId) {
cands.push({ key, tier: 0, primary: 0, lru });
continue;
}
const qIdx = indexOfInQueue(trackId);
if (qIdx === null) {
cands.push({ key, tier: 1, primary: 0, lru });
} else if (qIdx > protectHi) {
cands.push({ key, tier: 2, primary: -qIdx, lru });
} else if (qIdx < protectLo) {
cands.push({ key, tier: 3, primary: qIdx, lru });
}
}
cands.sort((a, b) => {
if (a.tier !== b.tier) return a.tier - b.tier;
if (a.primary !== b.primary) return a.primary - b.primary;
return a.lru - b.lru;
});
for (const { key } of cands) {
if (sum <= maxBytes) break;
const meta = entries[key];
if (!meta) continue;
const parsed = parseKey(key);
if (!parsed) continue;
await invoke('delete_hot_cache_track', {
localPath: meta.localPath,
customDir: hotCacheCustomDir || null,
}).catch(() => {});
sum -= meta.sizeBytes || 0;
delete entries[key];
}
set({ entries });
},
clearAllDisk: async (customDir: string | null) => {
await invoke('purge_hot_cache', { customDir: customDir || null }).catch(() => {});
set({ entries: {} });
},
}),
{
name: 'psysonic-hot-cache',
storage: createJSONStorage(() => localStorage),
partialize: s => ({ entries: s.entries }),
},
),
);
+32 -5
View File
@@ -3,10 +3,13 @@ import { persist, createJSONStorage } from 'zustand/middleware';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { showToast } from '../utils/toast';
import { buildStreamUrl, buildCoverArtUrl, getPlayQueue, savePlayQueue, reportNowPlaying, scrobbleSong, SubsonicSong, getSong, getRandomSongs, getSimilarSongs2, getTopSongs, InternetRadioStation } from '../api/subsonic';
import { buildCoverArtUrl, getPlayQueue, savePlayQueue, reportNowPlaying, scrobbleSong, SubsonicSong, getSong, getRandomSongs, getSimilarSongs2, getTopSongs, InternetRadioStation } from '../api/subsonic';
import { resolvePlaybackUrl } from '../utils/resolvePlaybackUrl';
import { setDeferHotCachePrefetch } from '../utils/hotCacheGate';
import { lastfmScrobble, lastfmUpdateNowPlaying, lastfmLoveTrack, lastfmUnloveTrack, lastfmGetTrackLoved, lastfmGetAllLovedTracks } from '../api/lastfm';
import { useAuthStore } from './authStore';
import { useOfflineStore } from './offlineStore';
import { useHotCacheStore } from './hotCacheStore';
export interface Track {
id: string;
@@ -209,6 +212,11 @@ radioAudio.addEventListener('suspend', () => {
// Used to suppress ghost-commands from stale IPC arriving after the switch.
let lastGaplessSwitchTime = 0;
function touchHotCacheOnPlayback(trackId: string, serverId: string) {
if (!trackId || !serverId) return;
useHotCacheStore.getState().touchPlayed(trackId, serverId);
}
// Track ID that has already been sent to audio_chain_preload / audio_preload.
// Prevents the 100ms progress ticker from firing 300 identical IPC calls over
// the last 30 seconds of a track, each spawning its own HTTP download.
@@ -230,6 +238,7 @@ function syncQueueToServer(queue: Track[], currentTrack: Track | null, currentTi
// ─── Audio event handlers (called from initAudioListeners) ───────────────────
function handleAudioPlaying(_duration: number) {
setDeferHotCachePrefetch(false);
usePlayerStore.setState({ isPlaying: true });
}
@@ -281,7 +290,7 @@ function handleAudioProgress(current_time: number, duration: number) {
if (nextTrack && nextTrack.id !== track.id && nextTrack.id !== gaplessPreloadingId) {
gaplessPreloadingId = nextTrack.id;
const serverId = useAuthStore.getState().activeServerId ?? '';
const nextUrl = useOfflineStore.getState().getLocalUrl(nextTrack.id, serverId) ?? buildStreamUrl(nextTrack.id);
const nextUrl = resolvePlaybackUrl(nextTrack.id, serverId);
if (gaplessEnabled) {
// Gapless ON: decode + chain directly into the Sink now, 30 s in
// advance. By the time the track boundary arrives, the next source is
@@ -301,6 +310,7 @@ function handleAudioProgress(current_time: number, duration: number) {
durationHint: nextTrack.duration,
replayGainDb,
replayGainPeak,
hiResEnabled: useAuthStore.getState().enableHiRes,
}).catch(() => {});
} else {
// Gapless OFF: just pre-download bytes so audio_play finds them cached.
@@ -390,6 +400,7 @@ function handleAudioTrackSwitched(duration: number) {
});
}
syncQueueToServer(queue, nextTrack, 0);
touchHotCacheOnPlayback(nextTrack.id, useAuthStore.getState().activeServerId ?? '');
}
function handleAudioError(message: string) {
@@ -522,6 +533,9 @@ export function initAudioListeners(): () => void {
// Pass elapsed when playing so Discord shows a live running timer.
// Pass null when paused — Discord shows the song/artist without a timer.
elapsedSecs: isPlaying ? currentTime : null,
// coverArtUrl is intentionally not passed — Subsonic URLs require auth.
// Backend will fetch artwork from iTunes Search API instead.
coverArtUrl: null,
}).catch(() => {});
}
@@ -718,7 +732,8 @@ export const usePlayerStore = create<PlayerState>()(
});
const authState = useAuthStore.getState();
const url = useOfflineStore.getState().getLocalUrl(track.id, authState.activeServerId ?? '') ?? buildStreamUrl(track.id);
setDeferHotCachePrefetch(true);
const url = resolvePlaybackUrl(track.id, authState.activeServerId ?? '');
const replayGainDb = authState.replayGainEnabled
? (authState.replayGainMode === 'album' ? track.replayGainAlbumDb : track.replayGainTrackDb) ?? null
: null;
@@ -730,8 +745,10 @@ export const usePlayerStore = create<PlayerState>()(
replayGainDb,
replayGainPeak,
manual,
hiResEnabled: authState.enableHiRes,
}).catch((err: unknown) => {
if (playGeneration !== gen) return;
setDeferHotCachePrefetch(false);
console.error('[psysonic] audio_play failed:', err);
set({ isPlaying: false });
setTimeout(() => {
@@ -754,6 +771,7 @@ export const usePlayerStore = create<PlayerState>()(
});
}
syncQueueToServer(newQueue, track, 0);
touchHotCacheOnPlayback(track.id, authState.activeServerId ?? '');
},
// ── pause / resume / togglePlay ──────────────────────────────────────────
@@ -781,6 +799,7 @@ export const usePlayerStore = create<PlayerState>()(
invoke('audio_resume').catch(console.error);
isAudioPaused = false;
set({ isPlaying: true });
touchHotCacheOnPlayback(currentTrack.id, useAuthStore.getState().activeServerId ?? '');
} else {
// Cold start (app relaunch) — fetch fresh track data for replay gain, then play.
const gen = ++playGeneration;
@@ -798,7 +817,9 @@ export const usePlayerStore = create<PlayerState>()(
: null;
const replayGainPeakCold = authStateCold.replayGainEnabled ? (trackToPlay.replayGainPeak ?? null) : null;
const coldServerId = useAuthStore.getState().activeServerId ?? '';
const coldUrl = useOfflineStore.getState().getLocalUrl(trackToPlay.id, coldServerId) ?? buildStreamUrl(trackToPlay.id);
setDeferHotCachePrefetch(true);
const coldUrl = resolvePlaybackUrl(trackToPlay.id, coldServerId);
touchHotCacheOnPlayback(trackToPlay.id, coldServerId);
invoke('audio_play', {
url: coldUrl,
volume: vol,
@@ -806,12 +827,14 @@ export const usePlayerStore = create<PlayerState>()(
replayGainDb: replayGainDbCold,
manual: false,
replayGainPeak: replayGainPeakCold,
hiResEnabled: useAuthStore.getState().enableHiRes,
}).then(() => {
if (playGeneration === gen && currentTime > 1) {
invoke('audio_seek', { seconds: currentTime }).catch(console.error);
}
}).catch((err: unknown) => {
if (playGeneration !== gen) return;
setDeferHotCachePrefetch(false);
console.error('[psysonic] audio_play (cold resume) failed:', err);
set({ isPlaying: false });
});
@@ -825,7 +848,9 @@ export const usePlayerStore = create<PlayerState>()(
: null;
const replayGainPeakCold = authStateCold.replayGainEnabled ? (currentTrack.replayGainPeak ?? null) : null;
const coldServerId = useAuthStore.getState().activeServerId ?? '';
const coldUrl = useOfflineStore.getState().getLocalUrl(currentTrack.id, coldServerId) ?? buildStreamUrl(currentTrack.id);
setDeferHotCachePrefetch(true);
const coldUrl = resolvePlaybackUrl(currentTrack.id, coldServerId);
touchHotCacheOnPlayback(currentTrack.id, coldServerId);
invoke('audio_play', {
url: coldUrl,
volume: vol,
@@ -833,8 +858,10 @@ export const usePlayerStore = create<PlayerState>()(
replayGainDb: replayGainDbCold,
replayGainPeak: replayGainPeakCold,
manual: false,
hiResEnabled: useAuthStore.getState().enableHiRes,
}).catch((err: unknown) => {
if (playGeneration !== gen) return;
setDeferHotCachePrefetch(false);
console.error('[psysonic] audio_play (cold resume) failed:', err);
set({ isPlaying: false });
});
+1 -1
View File
@@ -1,7 +1,7 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
type Theme = 'mocha' | 'macchiato' | 'frappe' | 'latte' | 'nord' | 'nord-snowstorm' | 'nord-frost' | 'nord-aurora' | 'psychowave' | 'wnamp' | 'poison' | 'nucleo' | 'muma-jukebox' | 'winmedplayer' | 'p-dvd' | 'vintage-tube-radio' | 'neon-drift' | 'aero-glass' | 'luna-teal' | 'w98' | 'cupertino-light' | 'cupertino-dark' | 'gruvbox-dark-hard' | 'gruvbox-dark-medium' | 'gruvbox-dark-soft' | 'gruvbox-light-hard' | 'gruvbox-light-medium' | 'gruvbox-light-soft' | 'spotless' | 'dzr0' | 'cupertino-beats' | 'lambda-17' | 'gw1' | 'grand-theft-audio' | 'v-tactical' | 'nightcity-2077' | 'middle-earth' | 'morpheus' | 'stark-hud' | 'blade' | 'heisenberg' | 'ice-and-fire' | 'doh-matic' | 't-800' | 'dune' | 'tetrastack' | 'the-book' | 'readit' | 'insta' | 'hill-valley-85' | 'turtle-power' | 'w3-1' | 'aqua-quartz' | 'spider-tech' | 'dos' | 'unix' | 'jayfin' | 'horde' | 'alliance' | 'w11' | 'w10' | 'north-park' | 'dark-side-of-the-moon' | 'powerslave';
type Theme = 'mocha' | 'macchiato' | 'frappe' | 'latte' | 'nord' | 'nord-snowstorm' | 'nord-frost' | 'nord-aurora' | 'psychowave' | 'wnamp' | 'poison' | 'nucleo' | 'muma-jukebox' | 'winmedplayer' | 'p-dvd' | 'vintage-tube-radio' | 'neon-drift' | 'aero-glass' | 'luna-teal' | 'w98' | 'cupertino-light' | 'cupertino-dark' | 'gruvbox-dark-hard' | 'gruvbox-dark-medium' | 'gruvbox-dark-soft' | 'gruvbox-light-hard' | 'gruvbox-light-medium' | 'gruvbox-light-soft' | 'spotless' | 'dzr0' | 'cupertino-beats' | 'lambda-17' | 'gw1' | 'grand-theft-audio' | 'v-tactical' | 'nightcity-2077' | 'middle-earth' | 'morpheus' | 'stark-hud' | 'blade' | 'heisenberg' | 'ice-and-fire' | 'doh-matic' | 't-800' | 'dune' | 'tetrastack' | 'the-book' | 'readit' | 'insta' | 'hill-valley-85' | 'turtle-power' | 'w3-1' | 'aqua-quartz' | 'spider-tech' | 'dos' | 'unix' | 'jayfin' | 'horde' | 'alliance' | 'w11' | 'w10' | 'north-park' | 'dark-side-of-the-moon' | 'powerslave' | 'nightfox' | 'dayfox' | 'dawnfox' | 'duskfox' | 'nordfox' | 'terafox' | 'carbonfox';
interface ThemeState {
theme: Theme;
+188 -42
View File
@@ -2022,6 +2022,32 @@
filter: brightness(1.08);
}
/* Camera overlay for uploading a new artist image */
.artist-avatar-upload-overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 44px;
background: rgba(0, 0, 0, 0.55);
display: flex;
align-items: center;
justify-content: center;
color: #fff;
cursor: pointer;
opacity: 0;
transition: opacity 150ms ease;
border-bottom-left-radius: 50%;
border-bottom-right-radius: 50%;
z-index: 2;
}
.artist-detail-avatar:hover .artist-avatar-upload-overlay {
opacity: 1;
}
.artist-avatar-upload-overlay:hover {
background: rgba(0, 0, 0, 0.7);
}
.artist-detail-meta {
flex: 1;
min-width: 0;
@@ -2056,21 +2082,9 @@
}
/* Bio section */
.artist-bio-section {
margin-bottom: 0.5rem;
}
.artist-bio-text {
font-size: 14px;
line-height: 1.75;
color: var(--text-secondary);
max-width: 100%;
user-select: text;
}
.artist-bio-text a {
color: var(--accent);
text-decoration: underline;
/* Artist Detail bio — reuses np-info-card + np-artist-bio-row */
.artist-bio-card {
margin-bottom: 2rem;
}
@@ -2483,6 +2497,14 @@
margin: 0;
}
.lyrics-source {
font-size: 11px;
color: var(--text-muted);
text-align: center;
margin: 8px 0 4px;
opacity: 0.6;
}
/* ── Help ─────────────────────────────────────────────────────────────────── */
@@ -2924,23 +2946,21 @@
align-items: center;
justify-content: center;
pointer-events: none;
border-radius: 12px;
overflow: hidden;
/* No overflow:hidden / border-radius object-fit:contain never overflows, and
rounding the wrap visually clips wide images. */
transform: translateZ(0);
/* Fade left edge to blend into the dark mesh */
/* Thin left-edge fade to blend into the scrim — keep image fully visible */
-webkit-mask-image: linear-gradient(
to right,
transparent 0%,
rgba(0, 0, 0, 0.45) 18%,
rgba(0, 0, 0, 0.85) 40%,
#000 60%
rgba(0, 0, 0, 0.6) 6%,
#000 16%
);
mask-image: linear-gradient(
to right,
transparent 0%,
rgba(0, 0, 0, 0.45) 18%,
rgba(0, 0, 0, 0.85) 40%,
#000 60%
rgba(0, 0, 0, 0.6) 6%,
#000 16%
);
}
@@ -3005,15 +3025,16 @@
position: absolute;
bottom: 72px;
left: clamp(28px, 4vw, 64px);
z-index: 3;
z-index: 4;
display: flex;
flex-direction: column;
gap: 12px;
gap: 8px;
max-width: 85vw;
}
/* Album art — small, rounded, glowing */
.fs-art-wrap {
position: relative; /* stacking context for crossfade layers */
width: clamp(120px, 10vw, 180px);
height: clamp(120px, 10vw, 180px);
border-radius: 12px;
@@ -3025,16 +3046,19 @@
0 0 28px var(--accent-glow, var(--accent));
}
/* Each layer is absolutely stacked — layers crossfade via opacity */
.fs-art {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
display: block;
transition: opacity 300ms ease;
}
.fs-art-placeholder {
width: 100%;
height: 100%;
position: absolute;
inset: 0;
background: rgba(255, 255, 255, 0.06);
display: flex;
align-items: center;
@@ -3042,30 +3066,28 @@
color: rgba(255, 255, 255, 0.3);
}
/* Artist name — massive, font-black, uppercase, wraps gracefully */
.fs-artist-name {
/* Track title — massive, font-black, primary — now on top */
.fs-track-title {
font-family: var(--font-display);
font-size: clamp(28px, 4.5vw, 68px);
font-weight: 900;
text-transform: uppercase;
letter-spacing: -0.02em;
color: #ffffff;
color: var(--accent);
margin: 0;
line-height: 1.05;
text-shadow: 0 2px 24px rgba(0, 0, 0, 0.7);
text-shadow: 0 2px 24px rgba(0, 0, 0, 0.5), 0 0 40px var(--accent-glow, var(--accent));
white-space: normal;
word-wrap: break-word;
overflow-wrap: break-word;
}
/* Track title — large, light, accent color, wraps gracefully */
.fs-track-title {
/* Artist name — secondary, below track title */
.fs-artist-name {
font-family: var(--font-display);
font-size: clamp(18px, 2.6vw, 40px);
font-weight: 300;
color: var(--accent);
font-size: clamp(13px, 1.5vw, 22px);
font-weight: 400;
color: rgba(255, 255, 255, 0.55);
margin: 0;
line-height: 1.2;
line-height: 1.3;
white-space: normal;
word-wrap: break-word;
overflow-wrap: break-word;
@@ -3079,6 +3101,7 @@
flex-wrap: wrap;
font-size: clamp(11px, 1vw, 13px);
color: rgba(255, 255, 255, 0.5);
margin-top: 4px;
}
.fs-meta-dot {
@@ -3212,6 +3235,98 @@
appearance: none;
}
/* ── Idle-fade — only the close button hides; cluster + seekbar always visible ── */
.fs-player[data-idle="true"] .fs-close {
opacity: 0.05;
pointer-events: none;
transition: opacity 900ms ease;
}
.fs-player[data-idle="false"] .fs-close {
opacity: 1;
pointer-events: auto;
transition: opacity 200ms ease;
}
/* ── Lyrics overlay — upper-left quadrant, strictly 5 lines tall ── */
/* Slot = 6vh → 5 × 6vh = 30vh. JS reads window.innerHeight * 0.06. */
.fs-lyrics-overlay {
position: absolute;
top: 15vh; /* pushed down into the quadrant, clear of close button */
left: clamp(28px, 4vw, 64px);
right: 52%; /* stay out of portrait area */
height: 30vh; /* exactly 5 × 6vh — never grows, never overlaps cluster */
z-index: 3;
overflow: hidden;
pointer-events: none;
contain: layout style; /* isolate reflows from rest of page */
/* Fade first and last slot (each 6/30 = 20% of container) */
-webkit-mask-image: linear-gradient(
to bottom,
transparent 0%,
#000 20%,
#000 80%,
transparent 100%
);
mask-image: linear-gradient(
to bottom,
transparent 0%,
#000 20%,
#000 80%,
transparent 100%
);
}
/* Synced rail — smooth slide, no abrupt jumps */
.fs-lyrics-rail {
position: absolute;
top: 0;
left: 0;
right: 0;
will-change: transform;
transition: transform 500ms ease-out;
}
/* Each lyric slot is exactly 6vh matches JS window.innerHeight * 0.06.
Fixed height (not min-height) is intentional: keeps rail math correct
regardless of whether the text wraps or not. 2 wrapped lines of 2vh
font at 1.4 line-height = 5.6vh, comfortably inside the 6vh slot. */
.fs-lyric-line {
height: 6vh;
display: flex;
align-items: center;
overflow: hidden;
white-space: normal;
font-size: 2vh;
line-height: 1.4;
color: rgba(255, 255, 255, 0.22);
font-weight: 400;
cursor: pointer;
pointer-events: auto;
/* font-weight intentionally NOT transitioned — triggers layout reflow on every frame */
transition: color 280ms ease, text-shadow 280ms ease, transform 280ms ease;
transform-origin: left center;
user-select: none;
}
.fs-lyric-line:hover {
color: rgba(255, 255, 255, 0.5);
}
.fs-lyric-line.fsl-past {
color: rgba(255, 255, 255, 0.1);
}
/* Active: emphasis via scale + glow; font-weight snaps instantly (no layout-reflow transition) */
.fs-lyric-line.fsl-active {
font-weight: 600;
color: rgba(255, 255, 255, 0.95);
text-shadow: 0 0 28px var(--accent-glow, var(--accent)), 0 1px 8px rgba(0, 0, 0, 0.6);
transform: scaleX(1.015); /* subtle compositor-only emphasis, no layout cost */
}
/* Chat */
.chat-popup {
position: absolute;
@@ -3969,6 +4084,7 @@
display: flex;
flex-direction: column;
gap: 8px;
padding-right: 1.5rem;
}
.np-bio-text {
@@ -3984,8 +4100,25 @@
.np-bio-text.expanded {
display: block;
overflow: visible;
-webkit-line-clamp: unset;
overflow-y: auto;
max-height: 300px;
overscroll-behavior: contain;
scrollbar-width: thin;
scrollbar-color: var(--ctp-teal) transparent;
}
.np-bio-text.expanded::-webkit-scrollbar {
width: 4px;
}
.np-bio-text.expanded::-webkit-scrollbar-track {
background: transparent;
}
.np-bio-text.expanded::-webkit-scrollbar-thumb {
background: var(--ctp-teal);
border-radius: 2px;
}
.np-bio-text a { color: var(--accent); }
@@ -4002,6 +4135,19 @@
}
.np-bio-toggle:hover { opacity: 1; }
.app-shell[data-mobile] .np-artist-bio-row {
flex-direction: column;
}
.app-shell[data-mobile] .np-artist-thumb {
width: 56px;
height: 56px;
}
.app-shell[data-mobile] .np-bio-wrap {
padding-right: 0;
}
/* ── Album tracklist ── */
.np-album-tracklist {
display: flex;
+159
View File
@@ -93,6 +93,165 @@
overflow-y: auto;
}
/* Library scope: Navidrome-style dropdown trigger + fixed panel (portal) */
.nav-library-scope-trigger {
display: flex;
align-items: flex-start;
gap: var(--space-2);
width: calc(100% - 2 * var(--space-3));
margin: var(--space-3) var(--space-3) var(--space-2);
padding: var(--space-2) var(--space-2);
border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
border-radius: var(--radius-md);
background: var(--bg-tertiary, rgba(0, 0, 0, 0.2));
color: var(--text-secondary);
cursor: pointer;
text-align: left;
transition: background var(--transition-fast), border-color var(--transition-fast), color var(--transition-fast);
}
.nav-library-scope-trigger:hover {
background: var(--bg-hover);
color: var(--text-primary);
border-color: var(--border-default, rgba(255, 255, 255, 0.12));
}
/* «Все библиотеки»: как секция навигации, без рамки и подложки */
.nav-library-scope-trigger--plain {
border-color: transparent;
background: transparent;
align-items: center;
}
.nav-library-scope-trigger--plain:hover {
border-color: transparent;
}
.nav-library-scope-trigger--plain .nav-library-scope-chevron {
margin-top: 0;
}
.nav-library-scope-trigger--open:not(.nav-library-scope-trigger--plain) {
border-color: var(--accent, var(--border-default));
}
.nav-library-scope-trigger--open.nav-library-scope-trigger--plain {
border-color: var(--border-subtle, rgba(255, 255, 255, 0.08));
background: var(--bg-tertiary, rgba(0, 0, 0, 0.2));
}
.nav-library-scope-icon {
flex-shrink: 0;
margin-top: 2px;
opacity: 0.85;
}
.nav-library-scope-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.nav-library-scope-title {
font-size: 10px;
font-weight: 600;
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--text-muted);
}
.nav-library-scope-subtitle {
font-size: 12px;
font-weight: 500;
color: var(--text-primary);
line-height: 1.25;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.nav-library-scope-chevron {
flex-shrink: 0;
margin-top: 2px;
opacity: 0.7;
transition: transform var(--transition-fast);
}
.nav-library-scope-trigger--open .nav-library-scope-chevron {
transform: rotate(180deg);
}
.nav-library-dropdown-panel {
z-index: 10050;
display: flex;
flex-direction: column;
padding: var(--space-1);
border-radius: var(--radius-md);
border: 1px solid var(--border-dropdown, rgba(255, 255, 255, 0.12));
background: var(--bg-secondary, #1e1e2e);
box-shadow: 0 8px 24px var(--shadow-dropdown, rgba(0, 0, 0, 0.45));
box-sizing: border-box;
overflow-y: visible;
}
/* >10 папок: «Все библиотеки» + до 10 строк папок, дальше — прокрутка */
.nav-library-dropdown-panel--many-libraries {
--nav-lib-dropdown-row-h: calc(2 * var(--space-2) + 1.35rem);
max-height: min(
calc(11 * var(--nav-lib-dropdown-row-h) + 2 * var(--space-1)),
70vh
);
overflow-y: auto;
}
.nav-library-dropdown-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
width: 100%;
margin: 0;
padding: var(--space-2) var(--space-3);
border: none;
border-radius: var(--radius-sm);
background: transparent;
color: var(--text-primary);
font-size: 13px;
font-weight: 500;
text-align: left;
cursor: pointer;
transition: background var(--transition-fast);
}
.nav-library-dropdown-item:hover {
background: var(--bg-hover);
}
.nav-library-dropdown-item--selected {
color: var(--accent);
}
.nav-library-dropdown-item-label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.nav-library-dropdown-check {
flex-shrink: 0;
color: var(--accent);
}
.nav-library-dropdown-check-spacer {
flex-shrink: 0;
width: 16px;
height: 16px;
}
.nav-section-label {
font-size: 10px;
font-weight: 600;
+389 -1
View File
@@ -3678,6 +3678,23 @@ body.psy-dragging * {
border-color: var(--ctp-overlay0);
}
.btn-danger {
background: transparent;
color: var(--danger);
border: 1px solid var(--danger);
}
.btn-danger:hover {
background: var(--danger);
color: #fff;
transform: translateY(-1px);
box-shadow: 0 4px 12px color-mix(in srgb, var(--danger) 35%, transparent);
}
.btn-danger:active {
transform: translateY(0);
}
/* ─── Input ─── */
.input {
width: 100%;
@@ -13712,4 +13729,375 @@ input[type="range"]:hover::-webkit-slider-thumb {
[data-theme='powerslave'] ::-webkit-scrollbar-thumb:hover {
background: #C8800A;
}
}
/* ─── Nightfox ─── */
[data-theme='nightfox'] {
color-scheme: dark;
--select-arrow: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23cdcecf%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E");
--ctp-crust: #131a24;
--ctp-mantle: #131a24;
--ctp-base: #192330;
--ctp-surface0: #212e3f;
--ctp-surface1: #29394f;
--ctp-surface2: #39506d;
--ctp-overlay0: #71839b;
--ctp-overlay1: #71839b;
--ctp-overlay2: #aeafb0;
--ctp-text: #cdcecf;
--ctp-subtext1: #aeafb0;
--ctp-subtext0: #71839b;
--ctp-mauve: #9d79d6;
--ctp-lavender: #719cd6;
--ctp-pink: #d67ad2;
--ctp-flamingo: #d67ad2;
--ctp-rosewater: #d67ad2;
--ctp-blue: #719cd6;
--ctp-sapphire: #9d79d6;
--ctp-sky: #63cdcf;
--ctp-teal: #63cdcf;
--ctp-green: #81b29a;
--ctp-yellow: #dbc074;
--ctp-peach: #f4a261;
--ctp-maroon: #c94f6d;
--ctp-red: #c94f6d;
--bg-app: #192330;
--bg-sidebar: #131a24;
--bg-card: #212e3f;
--bg-hover: #29394f;
--bg-player: #131a24;
--bg-glass: rgba(25, 35, 48, 0.75);
--accent: #719cd6;
--accent-dim: rgba(113, 156, 214, 0.15);
--accent-glow: rgba(113, 156, 214, 0.3);
--text-primary: #cdcecf;
--text-secondary: #aeafb0;
--text-muted: #738091;
--border: #29394f;
--border-subtle: #212e3f;
--border-dropdown: #39506d;
--shadow-dropdown: rgba(0, 0, 0, 0.6);
--positive: #81b29a;
--warning: #dbc074;
--danger: #c94f6d;
}
/* ─── Dayfox ─── */
[data-theme='dayfox'] {
color-scheme: light;
--select-arrow: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%233d2b5a%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E");
--ctp-crust: #e4dcd4;
--ctp-mantle: #e4dcd4;
--ctp-base: #f6f2ee;
--ctp-surface0: #dbd1dd;
--ctp-surface1: #d3c7bb;
--ctp-surface2: #aab0ad;
--ctp-overlay0: #837a72;
--ctp-overlay1: #643f61;
--ctp-overlay2: #3d2b5a;
--ctp-text: #3d2b5a;
--ctp-subtext1: #302b5d;
--ctp-subtext0: #643f61;
--ctp-mauve: #6e33ce;
--ctp-lavender: #2848a9;
--ctp-pink: #a440b5;
--ctp-flamingo: #a5222f;
--ctp-rosewater: #955f61;
--ctp-blue: #2848a9;
--ctp-sapphire: #287980;
--ctp-sky: #287980;
--ctp-teal: #287980;
--ctp-green: #396847;
--ctp-yellow: #ac5402;
--ctp-peach: #955f61;
--ctp-maroon: #a5222f;
--ctp-red: #a5222f;
--bg-app: #f6f2ee;
--bg-sidebar: #e4dcd4;
--bg-card: #dbd1dd;
--bg-hover: #d3c7bb;
--bg-player: #e4dcd4;
--bg-glass: rgba(246, 242, 238, 0.92);
--accent: #2848a9;
--accent-dim: rgba(40, 72, 169, 0.12);
--accent-glow: rgba(40, 72, 169, 0.25);
--text-primary: #3d2b5a;
--text-secondary: #643f61;
--text-muted: #837a72;
--border: #d3c7bb;
--border-subtle: #dbd1dd;
--border-dropdown: #aab0ad;
--shadow-dropdown: rgba(0, 0, 0, 0.18);
--positive: #396847;
--warning: #ac5402;
--danger: #a5222f;
}
/* ─── Dawnfox ─── */
[data-theme='dawnfox'] {
color-scheme: light;
--select-arrow: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23575279%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E");
--ctp-crust: #ebe5df;
--ctp-mantle: #ebe5df;
--ctp-base: #faf4ed;
--ctp-surface0: #ebe0df;
--ctp-surface1: #ebdfe4;
--ctp-surface2: #bdbfc9;
--ctp-overlay0: #9893a5;
--ctp-overlay1: #a8a3b3;
--ctp-overlay2: #625c87;
--ctp-text: #575279;
--ctp-subtext1: #4c4769;
--ctp-subtext0: #625c87;
--ctp-mauve: #907aa9;
--ctp-lavender: #575279;
--ctp-pink: #d685af;
--ctp-flamingo: #d7827e;
--ctp-rosewater: #d7827e;
--ctp-blue: #286983;
--ctp-sapphire: #286983;
--ctp-sky: #56949f;
--ctp-teal: #56949f;
--ctp-green: #618774;
--ctp-yellow: #ea9d34;
--ctp-peach: #d7827e;
--ctp-maroon: #b4637a;
--ctp-red: #b4637a;
--bg-app: #faf4ed;
--bg-sidebar: #ebe5df;
--bg-card: #ebe0df;
--bg-hover: #ebdfe4;
--bg-player: #ebe5df;
--bg-glass: rgba(250, 244, 237, 0.92);
--accent: #907aa9;
--accent-dim: rgba(144, 122, 169, 0.12);
--accent-glow: rgba(144, 122, 169, 0.25);
--text-primary: #575279;
--text-secondary: #625c87;
--text-muted: #9893a5;
--border: #ebdfe4;
--border-subtle: #ebe0df;
--border-dropdown: #bdbfc9;
--shadow-dropdown: rgba(0, 0, 0, 0.15);
--positive: #618774;
--warning: #ea9d34;
--danger: #b4637a;
}
/* ─── Duskfox ─── */
[data-theme='duskfox'] {
color-scheme: dark;
--select-arrow: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23e0def4%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E");
--ctp-crust: #191726;
--ctp-mantle: #191726;
--ctp-base: #232136;
--ctp-surface0: #2d2a45;
--ctp-surface1: #373354;
--ctp-surface2: #4b4673;
--ctp-overlay0: #817c9c;
--ctp-overlay1: #6e6a86;
--ctp-overlay2: #cdcbe0;
--ctp-text: #e0def4;
--ctp-subtext1: #cdcbe0;
--ctp-subtext0: #817c9c;
--ctp-mauve: #c4a7e7;
--ctp-lavender: #c4a7e7;
--ctp-pink: #eb98c3;
--ctp-flamingo: #eb6f92;
--ctp-rosewater: #ea9a97;
--ctp-blue: #569fba;
--ctp-sapphire: #569fba;
--ctp-sky: #9ccfd8;
--ctp-teal: #9ccfd8;
--ctp-green: #a3be8c;
--ctp-yellow: #f6c177;
--ctp-peach: #ea9a97;
--ctp-maroon: #eb6f92;
--ctp-red: #eb6f92;
--bg-app: #232136;
--bg-sidebar: #191726;
--bg-card: #2d2a45;
--bg-hover: #373354;
--bg-player: #191726;
--bg-glass: rgba(35, 33, 54, 0.75);
--accent: #c4a7e7;
--accent-dim: rgba(196, 167, 231, 0.15);
--accent-glow: rgba(196, 167, 231, 0.3);
--text-primary: #e0def4;
--text-secondary: #cdcbe0;
--text-muted: #817c9c;
--border: #373354;
--border-subtle: #2d2a45;
--border-dropdown: #4b4673;
--shadow-dropdown: rgba(0, 0, 0, 0.6);
--positive: #a3be8c;
--warning: #f6c177;
--danger: #eb6f92;
}
/* ─── Nordfox ─── */
[data-theme='nordfox'] {
color-scheme: dark;
--select-arrow: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23cdcecf%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E");
--ctp-crust: #232831;
--ctp-mantle: #232831;
--ctp-base: #2e3440;
--ctp-surface0: #39404f;
--ctp-surface1: #444c5e;
--ctp-surface2: #5a657d;
--ctp-overlay0: #60728a;
--ctp-overlay1: #7e8188;
--ctp-overlay2: #abb1bb;
--ctp-text: #cdcecf;
--ctp-subtext1: #c7cdd9;
--ctp-subtext0: #abb1bb;
--ctp-mauve: #b48ead;
--ctp-lavender: #81a1c1;
--ctp-pink: #bf88bc;
--ctp-flamingo: #bf616a;
--ctp-rosewater: #c9826b;
--ctp-blue: #81a1c1;
--ctp-sapphire: #81a1c1;
--ctp-sky: #88c0d0;
--ctp-teal: #88c0d0;
--ctp-green: #a3be8c;
--ctp-yellow: #ebcb8b;
--ctp-peach: #c9826b;
--ctp-maroon: #bf616a;
--ctp-red: #bf616a;
--bg-app: #2e3440;
--bg-sidebar: #232831;
--bg-card: #39404f;
--bg-hover: #444c5e;
--bg-player: #232831;
--bg-glass: rgba(46, 52, 64, 0.75);
--accent: #81a1c1;
--accent-dim: rgba(129, 161, 193, 0.15);
--accent-glow: rgba(129, 161, 193, 0.3);
--text-primary: #cdcecf;
--text-secondary: #abb1bb;
--text-muted: #60728a;
--border: #444c5e;
--border-subtle: #39404f;
--border-dropdown: #5a657d;
--shadow-dropdown: rgba(0, 0, 0, 0.6);
--positive: #a3be8c;
--warning: #ebcb8b;
--danger: #bf616a;
}
/* ─── Terafox ─── */
[data-theme='terafox'] {
color-scheme: dark;
--select-arrow: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23e6eaea%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E");
--ctp-crust: #0f1c1e;
--ctp-mantle: #0f1c1e;
--ctp-base: #152528;
--ctp-surface0: #1d3337;
--ctp-surface1: #254147;
--ctp-surface2: #2d4f56;
--ctp-overlay0: #6d7f8b;
--ctp-overlay1: #587b7b;
--ctp-overlay2: #cbd9d8;
--ctp-text: #e6eaea;
--ctp-subtext1: #eaeeee;
--ctp-subtext0: #cbd9d8;
--ctp-mauve: #ad5c7c;
--ctp-lavender: #5a93aa;
--ctp-pink: #cb7985;
--ctp-flamingo: #e85c51;
--ctp-rosewater: #ea9a97;
--ctp-blue: #5a93aa;
--ctp-sapphire: #5a93aa;
--ctp-sky: #a1cdd8;
--ctp-teal: #7aa4a1;
--ctp-green: #7aa4a1;
--ctp-yellow: #fda47f;
--ctp-peach: #ff8349;
--ctp-maroon: #e85c51;
--ctp-red: #e85c51;
--bg-app: #152528;
--bg-sidebar: #0f1c1e;
--bg-card: #1d3337;
--bg-hover: #254147;
--bg-player: #0f1c1e;
--bg-glass: rgba(21, 37, 40, 0.75);
--accent: #a1cdd8;
--accent-dim: rgba(161, 205, 216, 0.15);
--accent-glow: rgba(161, 205, 216, 0.3);
--text-primary: #e6eaea;
--text-secondary: #cbd9d8;
--text-muted: #6d7f8b;
--border: #254147;
--border-subtle: #1d3337;
--border-dropdown: #2d4f56;
--shadow-dropdown: rgba(0, 0, 0, 0.6);
--positive: #7aa4a1;
--warning: #fda47f;
--danger: #e85c51;
}
/* ─── Carbonfox ─── */
[data-theme='carbonfox'] {
color-scheme: dark;
--select-arrow: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23f2f4f8%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E");
--ctp-crust: #121212;
--ctp-mantle: #121212;
--ctp-base: #161616;
--ctp-surface0: #1c1c1c;
--ctp-surface1: #222222;
--ctp-surface2: #2e2e2e;
--ctp-overlay0: #525253;
--ctp-overlay1: #525253;
--ctp-overlay2: #c1c7cd;
--ctp-text: #f2f4f8;
--ctp-subtext1: #dde1e6;
--ctp-subtext0: #c1c7cd;
--ctp-mauve: #be95ff;
--ctp-lavender: #78a9ff;
--ctp-pink: #ff7eb6;
--ctp-flamingo: #ee5396;
--ctp-rosewater: #ff7eb6;
--ctp-blue: #78a9ff;
--ctp-sapphire: #33b1ff;
--ctp-sky: #33b1ff;
--ctp-teal: #3ddbd9;
--ctp-green: #25be6a;
--ctp-yellow: #08bdba;
--ctp-peach: #3ddbd9;
--ctp-maroon: #ee5396;
--ctp-red: #ee5396;
--bg-app: #161616;
--bg-sidebar: #121212;
--bg-card: #1c1c1c;
--bg-hover: #222222;
--bg-player: #121212;
--bg-glass: rgba(22, 22, 22, 0.82);
--accent: #be95ff;
--accent-dim: rgba(190, 149, 255, 0.15);
--accent-glow: rgba(190, 149, 255, 0.3);
--text-primary: #f2f4f8;
--text-secondary: #dde1e6;
--text-muted: #878d96;
--border: #222222;
--border-subtle: #1c1c1c;
--border-dropdown: #2e2e2e;
--shadow-dropdown: rgba(0, 0, 0, 0.7);
--positive: #25be6a;
--warning: #08bdba;
--danger: #ee5396;
}
+10
View File
@@ -0,0 +1,10 @@
/** When true, hot-cache prefetch must not start new downloads (playback has priority). */
let deferHotCachePrefetch = false;
export function setDeferHotCachePrefetch(v: boolean): void {
deferHotCachePrefetch = v;
}
export function getDeferHotCachePrefetch(): boolean {
return deferHotCachePrefetch;
}
+10
View File
@@ -191,6 +191,16 @@ export async function invalidateCacheKey(cacheKey: string): Promise<void> {
}
}
/**
* Invalidates all cached sizes for a given cover art entity (artist, radio, playlist, album).
* Call this after uploading or deleting a cover image so the UI re-fetches from the server.
*/
export async function invalidateCoverArt(entityId: string): Promise<void> {
const serverId = useAuthStore.getState().getActiveServer()?.id ?? '_';
const sizes = [40, 64, 128, 200, 256, 300, 500, 2000];
await Promise.all(sizes.map(size => invalidateCacheKey(`${serverId}:cover:${entityId}:${size}`)));
}
/** Clears all entries from IndexedDB and revokes all in-memory object URLs. */
export async function clearImageCache(): Promise<void> {
for (const url of objectUrlCache.values()) {
+12
View File
@@ -0,0 +1,12 @@
import { buildStreamUrl } from '../api/subsonic';
import { useOfflineStore } from '../store/offlineStore';
import { useHotCacheStore } from '../store/hotCacheStore';
/** Offline library → hot playback cache → HTTP stream. */
export function resolvePlaybackUrl(trackId: string, serverId: string): string {
const offline = useOfflineStore.getState().getLocalUrl(trackId, serverId);
if (offline) return offline;
const hot = useHotCacheStore.getState().getLocalUrl(trackId, serverId);
if (hot) return hot;
return buildStreamUrl(trackId);
}