Compare commits

..

21 Commits

Author SHA1 Message Date
Psychotoxical 05da369aad chore(aur): bump pkgver to 1.34.7
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 23:29:11 +02:00
Psychotoxical 9671f89a48 chore: bump version to 1.34.7, add changelog
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 23:28:54 +02:00
Psychotoxical 9567a94dea feat(windows): replace GDI taskbar icons with embedded .ico assets
Strips the legacy monochrome GDI drawing code and loads high-quality
icons from embedded .ico files via CreateIconFromResourceEx. Fixes
windows 0.58 import paths (Controls→Shell subclassing, TaskbarList CLSID)
and adds proper cleanup for all four HICONs on WM_NCDESTROY.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 23:14:21 +02:00
Psychotoxical 1ba8619a37 chore: remove preview-update debug button, add GDI features, add contributor
- Remove debug "Preview Update Modal" button from Settings/About
- Add Win32_Graphics/Win32_Graphics_Gdi features for taskbar GDI icons
- Add sorensiimSalling contributor credit for Russian translation (PR #140)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 22:30:23 +02:00
kilyabin 973b472c1f fix: not translated lyricsServer* string to RU locale (#140) 2026-04-09 22:24:03 +02:00
Psychotoxical 20bf93c344 feat(windows): taskbar thumbnail toolbar with GDI media icons
Implements ITaskbarList3::ThumbBarAddButtons for Prev/Play-Pause/Next
buttons in the Windows taskbar thumbnail preview. Icons are drawn at
runtime via GDI (no binary assets). WndProc subclass intercepts
THBN_CLICKED and emits the same media:* events as souvlaki/tray.
update_taskbar_icon command swaps Play↔Pause icon on state change.
Frontend syncs via playerStore subscribe alongside mpris_set_playback.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 22:12:35 +02:00
Psychotoxical fd834314ba fix(audio): VLC-style frame dropping for corrupt MP3s, silence logs in release
Replace the fixed DECODE_MAX_RETRIES (3) loop with a consecutive-error counter
that tolerates up to 100 bad frames before giving up — matching how VLC handles
files with a handful of invalid main_data offset frames. Frame-drop logs are
wrapped in #[cfg(debug_assertions)] so production builds stay silent.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 21:42:38 +02:00
Psychotoxical a78c0fe9ac fix: font switching, layout scaling, embedded lyrics, folder opening
- fix(fonts): update CSS var declarations to @fontsource-variable naming
  ('Inter Variable', 'Outfit Variable', etc.) so dynamic font switching works
- fix(layout): 100vh → 100% on .app-shell to fix Windows WebView2 playerbar drift;
  1fr → minmax(0,1fr) in all grid-template-rows + remove min-height: 720px to fix
  Linux playerbar disappearing at high zoom or small window sizes
- fix(updater): replace shell open() with Rust open_folder command to bypass
  shell:allow-open capability scope blocking local paths on Windows
- fix(lyrics): add get_embedded_lyrics Tauri command (id3 crate for MP3 SYLT/USLT,
  lofty for FLAC SYNCEDLYRICS/LYRICS); fix parseLrc regex for LRC without fractional
  seconds; fix SubsonicStructuredLyrics to accept both synced and issynced fields

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 16:52:27 +02:00
Psychotoxical 9c57d4f887 feat(updater): professional update modal with skip, changelog, and OS-aware downloader
Replaces the small corner toast with a centered modal that appears on
startup when a newer GitHub release is detected (4 s delay).

Features:
- Skip this Version: stores skipped tag in localStorage, reappears only
  for newer releases
- Collapsible changelog: renders GitHub release body as markdown accordion
- OS-aware download: Windows → .exe installer, macOS → .dmg (aarch64
  preferred), Linux Arch → AUR hint (yay/pacman), Linux other → .AppImage/.deb
- In-app downloader: Rust download_update command streams to ~/Downloads/,
  emits update:download:progress every 250 ms for a real-time progress bar
- Post-download: Show in Folder button opens Downloads dir via shell.open
- Buttons: Download Now / Skip this Version / Remind me Later

Rust: check_arch_linux() reads /etc/arch-release + /etc/os-release
platform.ts: adds IS_MACOS, IS_WINDOWS alongside existing IS_LINUX
Settings About: Preview Update Modal button for testing
Fixes: renderInline regex had nested capture group causing undefined entries
in split() result → TypeError → React crash → WebKit white-screen freeze

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:23:48 +02:00
Psychotoxical 5d067b1f8b fix(app): hide resize grips in native fullscreen on all platforms
Previously onResized only tracked fullscreen on Linux. Now all platforms
set isWindowFullscreen, and an initial check on mount catches windows
that start maximized/fullscreened. CSS: .app-shell[data-fullscreen] .resizer
{ display: none } added in layout.css (shipped with updater commit).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:23:48 +02:00
Psychotoxical 48d0145dc8 fix(albums): align year filter inputs to button height and font size
Input padding and font-size now match adjacent .btn elements so the
year filter row no longer has mixed heights.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:23:48 +02:00
Psychotoxical 0da92c2fa1 fix(radio): prevent macOS WKWebView crash + shuffle Artist Radio queue
- Remove currentTime from Zustand persist partialize: it caused 100ms
  localStorage writes that grew with the queue, crashing WKWebView SQLite
  after ~10 min of Artist Radio on macOS
- Trim old played radio tracks from queue (keep last 5) to cap localStorage
  payload size during proactive radio top-up in next()
- Add reconnect logic for internet radio stall events (max 5 retries)
- Shuffle initial Artist Radio queue via Fisher-Yates so positions 2+
  are drawn from similar-artist tracks, not predictable top-5 tracks

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:23:48 +02:00
Psychotoxical 4e3efa3814 feat: self-host fonts via @fontsource-variable, remove Google Fonts CDN
Replaces all Google Fonts CDN references (index.html preconnect/stylesheet
and theme.css @import) with local @fontsource-variable npm packages.
All 10 UI fonts now bundle as WOFF2 into dist/assets/ — app renders
correctly without any internet connection.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:23:48 +02:00
Psychotoxical 77085a544e chore(credits): add missing contributor PRs to Settings page
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:23:48 +02:00
Psychotoxical 8ffecb4b7c Merge pull request #138 from cucadmuh/fix/statistics-music-folder-totals
fix(statistics): scope album and song totals to selected music library
2026-04-09 12:48:02 +02:00
Maxim Isaev c569ff5f34 fix(statistics): scope album and song totals to selected music library
getGenres() is not musicFolder-scoped, so summing genre counts showed
global totals while other statistics respected the library filter.
Derive album and track counts from the same paginated getAlbumList
pass used for playtime, with the same 5000-album cap and ≥ prefix when
capped.
2026-04-09 00:59:16 +03:00
Psychotoxical d16a99a6f9 docs(help): add 11 new FAQ entries for undocumented features
Ratings (q37-q39): how to rate songs/albums/artists, click active star to
remove rating, Skip-to-1★ and rating filter for mixes. Folder Browser (q40).
Settings: Theme Scheduler (q41), UI Scale (q42), Seekbar styles (q43),
AutoEQ (q44), Replay Gain (q45), Hot Cache (q46). Offline: playlist
caching and toggle (q47). All 7 locales updated.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 22:52:36 +02:00
Psychotoxical 9b239892ef chore: bump version to 1.34.6, add changelog
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 22:36:59 +02:00
Psychotoxical ba670bd1e8 feat: fix UI freezes in ZIP and offline cache downloads
ZIP downloads (PlaylistDetail, Albums, NewReleases, RandomAlbums) now use
invoke('download_zip') via Rust streaming instead of fetch+blob+arrayBuffer,
eliminating JS heap saturation on large files. Progress shown in ZipDownloadOverlay.

Offline cache downloads (600+ songs) no longer freeze the UI: transient job
state moved to a separate non-persisted offlineJobStore, reducing localStorage
writes from ~1200 down to 2 for an entire download. Also adds playlist offline
toggle — clicking the cache button when already cached removes it from cache.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 22:33:23 +02:00
Psychotoxical c1e57b4c06 fix(home): recently added albums title links to /new-releases instead of /albums 2026-04-08 18:56:39 +02:00
Psychotoxical fbe68116cc chore(aur): bump pkgver to 1.34.5 2026-04-08 18:05:26 +02:00
49 changed files with 2668 additions and 411 deletions
+67
View File
@@ -5,6 +5,73 @@ 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.7] - 2026-04-09
### Added
- **Windows — Taskbar Thumbnail Toolbar**: Prev / Play-Pause / Next media buttons now appear in the Windows taskbar thumbnail preview (the popup that appears when hovering over the taskbar icon). Buttons emit the same `media:*` events as the tray menu and souvlaki. The Play/Pause icon swaps in real-time as playback state changes.
- **Windows — High-quality taskbar icons**: The taskbar thumbnail toolbar icons are now loaded from embedded `.ico` assets (`play.ico`, `pause.ico`, `prev.ico`, `next.ico`) via `CreateIconFromResourceEx`, replacing the previous monochrome GDI drawing code. All four icons are properly cleaned up on window destruction.
- **Professional update modal**: The in-app updater now shows a polished modal with the full release changelog, a **Skip this version** option, and an OS-aware direct download button (`.dmg` on macOS, `.exe` on Windows, `.deb`/`.rpm` on Linux) as a fallback if the auto-update fails. The modal is fully localised in all 7 supported languages.
- **Self-hosted fonts — no internet required**: All 10 UI fonts are now shipped as WOFF2 files bundled into the app via `@fontsource-variable` npm packages. The previous Google Fonts CDN dependency has been removed entirely — Psysonic now renders correctly with no internet connection and without any external requests on startup.
- **Help — 11 new FAQ entries**: The Help page covers previously undocumented features across Ratings (how to rate songs/albums/artists, removing a rating, Skip-to-1★, rating filter for mixes), Folder Browser, Theme Scheduler, UI Scale, Seekbar styles, AutoEQ, Replay Gain, Hot Cache, and offline playlist caching. All 7 locales updated.
### Fixed
- **Embedded lyrics (MP3 & FLAC)**: A new `get_embedded_lyrics` Tauri command reads lyrics tags directly from local files — `SYLT`/`USLT` frames for MP3 (via the `id3` crate) and `SYNCEDLYRICS`/`LYRICS` tags for FLAC (via `lofty`). Additionally: the LRC parser now correctly handles timestamps without fractional seconds (e.g. `[01:23]`), and the Subsonic structured-lyrics parser now accepts both `synced` and `issynced` field names for compatibility with different server versions.
- **Linux — player bar disappearing at high zoom / small window sizes**: All `grid-template-rows` definitions now use `minmax(0, 1fr)` instead of bare `1fr`, and the `min-height: 720px` constraint on the app shell has been removed. The player bar no longer gets pushed off-screen when the window is small or the UI scale is above 100 %.
- **Windows — "Open folder" in Settings crashing**: The Settings page uses a Rust `open_folder` command instead of the Tauri `shell:open` API, which was blocked by the capability scope on Windows for local paths.
- **macOS — Artist Radio crashing WKWebView after ~10 minutes**: Storing `currentTime` in the persisted Zustand state caused up to ~1,200 synchronous `localStorage.setItem` calls per radio session, eventually crashing the WKWebView SQLite backend. `currentTime` has been removed from the persist partializer. Old played radio tracks are also now trimmed from the queue (keeping the last 5) to cap the localStorage payload during queue top-up.
- **Artist Radio — predictable track order**: The initial Artist Radio queue is now shuffled via Fisher-Yates, so positions 2+ draw from similar-artist tracks in a random order rather than always playing the server's top-5 tracks in sequence.
- **Internet Radio — stall / buffering recovery**: Stall events on the HTML5 `<audio>` element now trigger automatic reconnection (up to 5 retries), recovering from transient network interruptions without requiring a manual restart.
- **Corrupt MP3s — VLC-style frame tolerance**: The audio decoder now tolerates up to 100 consecutive bad frames before giving up (previously 3), matching VLC's behavior for files with invalid `main_data` offset frames. Frame-drop log messages are suppressed in release builds.
- **Statistics — album/song totals respect selected music library**: Album and track counts on the Statistics page were previously derived from `getGenres()`, which is not scoped to the active music folder. Both counts are now derived from the same paginated `getAlbumList` pass used for playtime, with the same 5,000-album cap and a `≥` prefix when capped. *(PR [#138](https://github.com/Psychotoxical/psysonic/pull/138) by [@cucadmuh](https://github.com/cucadmuh))*
- **Fullscreen — resize grips visible in native fullscreen**: Resize grips are now hidden whenever the window enters native fullscreen on all platforms (previously only tracked on Linux). An initial check on mount also catches windows that start in a maximized or fullscreen state.
- **Albums page — year filter input height**: The "From year" / "To year" inputs in the Albums filter bar now match the height and font size of adjacent buttons, fixing the mixed-height row introduced in v1.34.4.
- **Russian locale — missing lyrics-source strings**: The `lyricsServerFirst` and related settings strings were not translated in the Russian locale. *(PR [#140](https://github.com/Psychotoxical/psysonic/pull/140) by [@kilyabin](https://github.com/kilyabin))*
### Contributors
Thank you to everyone who contributed to this release:
- [@cucadmuh](https://github.com/cucadmuh) — Statistics music-folder scope fix (PR [#138](https://github.com/Psychotoxical/psysonic/pull/138))
- [@kilyabin](https://github.com/kilyabin) — Russian locale lyrics strings (PR [#140](https://github.com/Psychotoxical/psysonic/pull/140))
---
## [1.34.6] - 2026-04-08
> I'm sorry this is already the third release today — every time we shipped a critical fix, another critical issue surfaced. Hopefully this one holds. 🤞
### 🚨 Critical Fix
- **ZIP downloads no longer freeze the UI**: All ZIP downloads (Album Detail, Playlist Detail, Albums, New Releases, Random Albums) previously buffered the entire file in the JS heap via `fetch + blob + arrayBuffer`, which caused the app to become completely unresponsive for large downloads (e.g. a 600-song, 7 GB playlist). Downloads now stream directly to disk via the Rust backend (`invoke('download_zip')`), matching the existing single-album download behavior. Progress is shown in the download overlay (bottom right).
- **Offline cache downloads no longer freeze the UI**: Caching a large playlist (600+ songs) triggered up to ~1,200 synchronous `localStorage.setItem` calls as Zustand's `persist` middleware wrote on every state update. Transient download job state has been moved to a new non-persisted store (`offlineJobStore`), reducing localStorage writes for an entire download to **2** regardless of playlist size.
### Added
- **Playlist offline toggle**: When a playlist is already cached offline, clicking the cache button now removes it from the offline cache (shown with a red trash icon) instead of re-downloading it.
### Fixed
- **Home page — "Recently Added" section title** now links to `/new-releases` instead of `/albums`.
---
## [1.34.5] - 2026-04-08
### 🚨 Critical Fix
-3
View File
@@ -6,9 +6,6 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Psysonic Dein Navidrome Desktop Player" />
<title>Psysonic</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet" />
</head>
<body>
<div id="root"></div>
+102 -2
View File
@@ -1,13 +1,23 @@
{
"name": "psysonic",
"version": "1.34.2",
"version": "1.34.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "psysonic",
"version": "1.34.2",
"version": "1.34.6",
"dependencies": {
"@fontsource-variable/dm-sans": "^5.2.8",
"@fontsource-variable/figtree": "^5.2.10",
"@fontsource-variable/inter": "^5.2.8",
"@fontsource-variable/lexend": "^5.2.11",
"@fontsource-variable/manrope": "^5.2.8",
"@fontsource-variable/nunito": "^5.2.7",
"@fontsource-variable/outfit": "^5.2.8",
"@fontsource-variable/plus-jakarta-sans": "^5.2.8",
"@fontsource-variable/rubik": "^5.2.8",
"@fontsource-variable/space-grotesk": "^5.2.10",
"@tanstack/react-virtual": "^3.13.23",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-dialog": "^2.6.0",
@@ -773,6 +783,96 @@
"node": ">=18"
}
},
"node_modules/@fontsource-variable/dm-sans": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource-variable/dm-sans/-/dm-sans-5.2.8.tgz",
"integrity": "sha512-AxkvMTvNWgfrmlyjiV05vlHYJa+nRQCf1EfvIrQAPBpFJW0O9VTz7oAFr9S3lvbWdmnFoBk7yFqQL86u64nl2g==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/figtree": {
"version": "5.2.10",
"resolved": "https://registry.npmjs.org/@fontsource-variable/figtree/-/figtree-5.2.10.tgz",
"integrity": "sha512-a5Gumbpy3mdd+Yg31g6Qb7CmjYbrfyutJa3bWfP5q8A4GclIOwX7mI+ZuSHsJnw/mHvW6r9oh1AHJcJTIxK4JA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/inter": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.2.8.tgz",
"integrity": "sha512-kOfP2D+ykbcX/P3IFnokOhVRNoTozo5/JxhAIVYLpea/UBmCQ/YWPBfWIDuBImXX/15KH+eKh4xpEUyS2sQQGQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/lexend": {
"version": "5.2.11",
"resolved": "https://registry.npmjs.org/@fontsource-variable/lexend/-/lexend-5.2.11.tgz",
"integrity": "sha512-0hgEQ4O7Nh8fxL/WWmspJf0BErbocRkZwtLRGey/V4mUUqxfF7QUwqhcdzwpjom3NYCniY4uzQ5wYD7r9/92tQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/manrope": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource-variable/manrope/-/manrope-5.2.8.tgz",
"integrity": "sha512-nc9lOuCRz73UHnovDE2bwXUdghE2SEOc7Aii0qGe3CLyE03W1a7VnY5Z6euRiapiKbCkGS+eXbY3s/kvWeGeSw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/nunito": {
"version": "5.2.7",
"resolved": "https://registry.npmjs.org/@fontsource-variable/nunito/-/nunito-5.2.7.tgz",
"integrity": "sha512-2N8QhatkyKgSUbAGZO2FYLioxA32+RyI1EplVLawbpkGjUeui9Qg9VMrpkCaik1ydjFjfLV+kzQ0cGEsMrMenQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/outfit": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource-variable/outfit/-/outfit-5.2.8.tgz",
"integrity": "sha512-4oUDCZx/Tcz6HZP423w/niqEH31Gks5IsqHV2ZZz1qKHaVIZdj2f0/S1IK2n8jl6Xo0o3N+3RjNHlV9R73ozQA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/plus-jakarta-sans": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource-variable/plus-jakarta-sans/-/plus-jakarta-sans-5.2.8.tgz",
"integrity": "sha512-iQecBizIdZxezODNHzOn4SvvRMrZL/S8k4MEXGDynCmUrImVW0VmX+tIAMqnADwH4haXlHSXqMgU6+kcfBQJdw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/rubik": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource-variable/rubik/-/rubik-5.2.8.tgz",
"integrity": "sha512-vGDExLzB4a2Fj9mca5LqNoA2ZKcU9o+x5FEBLte/nxYkCB9hOQwZS6ZlItUv+Ssn7YMzKauGuI/Po+YueFuZbg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/space-grotesk": {
"version": "5.2.10",
"resolved": "https://registry.npmjs.org/@fontsource-variable/space-grotesk/-/space-grotesk-5.2.10.tgz",
"integrity": "sha512-yJQO/o35/hAP3CFnpdFTwQku2yzJOae2HIpBmqkOVoxhhXJaQP3g+b6Jrz7u+eI7A5ZdCIf88uMWpBJdFiGr5w==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+11 -1
View File
@@ -1,6 +1,6 @@
{
"name": "psysonic",
"version": "1.34.5",
"version": "1.34.7",
"private": true,
"scripts": {
"dev": "vite",
@@ -12,6 +12,16 @@
"test": "vitest run"
},
"dependencies": {
"@fontsource-variable/dm-sans": "^5.2.8",
"@fontsource-variable/figtree": "^5.2.10",
"@fontsource-variable/inter": "^5.2.8",
"@fontsource-variable/lexend": "^5.2.11",
"@fontsource-variable/manrope": "^5.2.8",
"@fontsource-variable/nunito": "^5.2.7",
"@fontsource-variable/outfit": "^5.2.8",
"@fontsource-variable/plus-jakarta-sans": "^5.2.8",
"@fontsource-variable/rubik": "^5.2.8",
"@fontsource-variable/space-grotesk": "^5.2.10",
"@tanstack/react-virtual": "^3.13.23",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-dialog": "^2.6.0",
+1 -1
View File
@@ -1,6 +1,6 @@
# Maintainer: Psychotoxic <psychotoxic@gmx.de>
pkgname=psysonic
pkgver=1.34.4
pkgver=1.34.7
pkgrel=1
pkgdesc="Desktop music player for Subsonic API-compatible servers (Navidrome, Gonic, etc.)"
arch=('x86_64')
+132 -7
View File
@@ -907,6 +907,12 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
[[package]]
name = "data-encoding"
version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea"
[[package]]
name = "deranged"
version = "0.5.8"
@@ -2058,6 +2064,17 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "id3"
version = "1.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "965c5e6a62a241f2f673df956ea5f52c27780bc1031855890a551ed9b869e2d1"
dependencies = [
"bitflags 2.11.0",
"byteorder",
"flate2",
]
[[package]]
name = "ident_case"
version = "1.0.1"
@@ -2420,6 +2437,32 @@ dependencies = [
"scopeguard",
]
[[package]]
name = "lofty"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca260c51a9c71f823fbfd2e6fbc8eb2ee09834b98c00763d877ca8bfa85cde3e"
dependencies = [
"byteorder",
"data-encoding",
"flate2",
"lofty_attr",
"log",
"ogg_pager",
"paste",
]
[[package]]
name = "lofty_attr"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed9983e64b2358522f745c1251924e3ab7252d55637e80f6a0a3de642d6a9efc"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "log"
version = "0.4.29"
@@ -2881,6 +2924,15 @@ dependencies = [
"cc",
]
[[package]]
name = "ogg_pager"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d6d1ca8364b84e0cf725eed06b1460c44671e6c0fb28765f5262de3ece07fdc"
dependencies = [
"byteorder",
]
[[package]]
name = "once_cell"
version = "1.21.3"
@@ -2979,6 +3031,12 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pathdiff"
version = "0.2.3"
@@ -3339,11 +3397,13 @@ dependencies = [
[[package]]
name = "psysonic"
version = "1.34.5"
version = "1.34.6"
dependencies = [
"biquad",
"discord-rich-presence",
"futures-util",
"id3",
"lofty",
"md5",
"reqwest 0.12.28",
"ringbuf",
@@ -3365,6 +3425,7 @@ dependencies = [
"thread-priority",
"tokio",
"url",
"windows 0.58.0",
]
[[package]]
@@ -5865,8 +5926,8 @@ dependencies = [
"webview2-com-sys",
"windows 0.61.3",
"windows-core 0.61.2",
"windows-implement",
"windows-interface",
"windows-implement 0.60.2",
"windows-interface 0.59.3",
]
[[package]]
@@ -5956,6 +6017,16 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
dependencies = [
"windows-core 0.58.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.61.3"
@@ -5988,14 +6059,27 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
dependencies = [
"windows-implement 0.58.0",
"windows-interface 0.58.0",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
"windows-implement",
"windows-interface",
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
@@ -6007,8 +6091,8 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
@@ -6025,6 +6109,17 @@ dependencies = [
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
@@ -6036,6 +6131,17 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "windows-interface"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -6078,6 +6184,15 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-result"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-result"
version = "0.3.4"
@@ -6096,6 +6211,16 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
dependencies = [
"windows-result 0.2.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
+15 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "psysonic"
version = "1.34.5"
version = "1.34.7"
description = "Psysonic Desktop Music Player"
authors = []
license = ""
@@ -35,7 +35,7 @@ symphonia = { version = "0.5", default-features = false, features = ["flac", "mp
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"] }
tokio = { version = "1", features = ["rt", "time", "sync"] }
biquad = "0.4"
ringbuf = "0.3"
tauri-plugin-window-state = "2.4.1"
@@ -44,6 +44,19 @@ souvlaki = { version = "0.8", default-features = false, features = ["use_zbus"]
discord-rich-presence = "0.2"
url = "2"
thread-priority = "1"
lofty = "0.22"
id3 = "1.16.4"
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58", features = [
"Win32_Foundation",
"Win32_Graphics",
"Win32_Graphics_Gdi",
"Win32_System_Com",
"Win32_UI_Controls",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
[patch.crates-io]
# Local patch for Symphonia's isomp4 demuxer:
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

+58 -16
View File
@@ -890,7 +890,13 @@ impl MediaSource for SizedCursorSource {
// Implements Iterator<Item = i16> + Source — identical interface to
// rodio::Decoder, so the rest of the source chain is unchanged.
/// Max retries for IO/packet-read errors (fatal — network drop, truncated file).
const DECODE_MAX_RETRIES: usize = 3;
/// Max *consecutive* DecodeErrors before giving up on a file.
/// Non-fatal errors like "invalid main_data offset" are silently dropped up to
/// this limit so a handful of corrupt MP3 frames never aborts an otherwise
/// playable track (VLC-style frame dropping).
const MAX_CONSECUTIVE_DECODE_ERRORS: usize = 100;
struct SizedDecoder {
decoder: Box<dyn symphonia::core::codecs::Decoder>,
@@ -899,6 +905,9 @@ struct SizedDecoder {
total_duration: Option<Time>,
buffer: SampleBuffer<i16>,
spec: SignalSpec,
/// Counts consecutive DecodeErrors in the hot-path. Reset to 0 on every
/// successfully decoded frame. Used to detect fully undecodable streams.
consecutive_decode_errors: usize,
}
impl SizedDecoder {
@@ -983,6 +992,8 @@ impl SizedDecoder {
let mut format = probed.format;
// Decode the first packet to initialise spec + buffer.
// DecodeErrors (e.g. "invalid main_data offset") are non-fatal: drop the
// frame and try the next packet up to MAX_CONSECUTIVE_DECODE_ERRORS times.
let mut decode_errors: usize = 0;
let decoded = loop {
let packet = match format.next_packet() {
@@ -1002,10 +1013,10 @@ impl SizedDecoder {
match decoder.decode(&packet) {
Ok(decoded) => break decoded,
Err(symphonia::core::errors::Error::DecodeError(ref msg)) => {
eprintln!("[psysonic] decode error (retry {decode_errors}): {msg}");
decode_errors += 1;
if decode_errors > DECODE_MAX_RETRIES {
return Err("too many decode errors — file may be corrupt".into());
eprintln!("[psysonic] init: dropped corrupt frame #{decode_errors}: {msg}");
if decode_errors >= MAX_CONSECUTIVE_DECODE_ERRORS {
return Err("too many consecutive decode errors during init — file may be corrupt".into());
}
}
Err(e) => {
@@ -1025,6 +1036,7 @@ impl SizedDecoder {
total_duration,
buffer,
spec,
consecutive_decode_errors: 0,
})
}
@@ -1061,16 +1073,19 @@ impl SizedDecoder {
if packet.track_id() != track_id { continue; }
match decoder.decode(&packet) {
Ok(d) => break d,
Err(symphonia::core::errors::Error::DecodeError(_)) => {
Err(symphonia::core::errors::Error::DecodeError(ref msg)) => {
errors += 1;
if errors > DECODE_MAX_RETRIES { return Err("radio: too many decode errors".into()); }
eprintln!("[psysonic] radio init: dropped corrupt frame #{errors}: {msg}");
if errors >= MAX_CONSECUTIVE_DECODE_ERRORS {
return Err("radio: too many consecutive decode errors".into());
}
}
Err(e) => return Err(format!("radio: decode error: {e}")),
}
};
let spec = decoded.spec().to_owned();
let buffer = Self::make_buffer(decoded, &spec);
Ok(SizedDecoder { decoder, current_frame_offset: 0, format, total_duration, buffer, spec })
Ok(SizedDecoder { decoder, current_frame_offset: 0, format, total_duration, buffer, spec, consecutive_decode_errors: 0 })
}
#[inline]
@@ -1120,18 +1135,45 @@ impl Iterator for SizedDecoder {
#[inline]
fn next(&mut self) -> Option<i16> {
if self.current_frame_offset >= self.buffer.len() {
let packet = self.format.next_packet().ok()?;
let mut decoded = self.decoder.decode(&packet);
for _ in 0..DECODE_MAX_RETRIES {
if decoded.is_err() {
let p = self.format.next_packet().ok()?;
decoded = self.decoder.decode(&p);
// Loop until a decodable packet is found or the stream ends.
// DecodeErrors (e.g. MP3 "invalid main_data offset") are non-fatal:
// drop the frame and advance to the next packet. IO errors and a
// clean end-of-stream both terminate the iterator normally.
loop {
let packet = self.format.next_packet().ok()?;
match self.decoder.decode(&packet) {
Ok(decoded) => {
self.consecutive_decode_errors = 0;
decoded.spec().clone_into(&mut self.spec);
self.buffer = Self::make_buffer(decoded, &self.spec);
self.current_frame_offset = 0;
break;
}
Err(symphonia::core::errors::Error::DecodeError(ref msg)) => {
self.consecutive_decode_errors += 1;
// Log sparingly: first drop, then every 10th to avoid spam.
#[cfg(debug_assertions)]
if self.consecutive_decode_errors == 1
|| self.consecutive_decode_errors % 10 == 0
{
eprintln!(
"[psysonic] dropped corrupt frame #{}: {msg}",
self.consecutive_decode_errors
);
}
if self.consecutive_decode_errors >= MAX_CONSECUTIVE_DECODE_ERRORS {
#[cfg(debug_assertions)]
eprintln!(
"[psysonic] {MAX_CONSECUTIVE_DECODE_ERRORS} consecutive decode \
failures stream appears unrecoverable, stopping"
);
return None;
}
// continue → fetch next packet
}
Err(_) => return None, // IO error or fatal codec error → end of stream
}
}
let decoded = decoded.ok()?;
decoded.spec().clone_into(&mut self.spec);
self.buffer = Self::make_buffer(decoded, &self.spec);
self.current_frame_offset = 0;
}
let sample = *self.buffer.samples().get(self.current_frame_offset)?;
+405 -7
View File
@@ -3,9 +3,11 @@
mod audio;
mod discord;
#[cfg(target_os = "windows")]
mod taskbar_win;
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::{Arc, Mutex};
use std::sync::atomic::Ordering;
use tauri::{
@@ -18,6 +20,13 @@ use tauri::{
/// Prevents on_shortcut() accumulating duplicate handlers across JS reloads (HMR / StrictMode).
type ShortcutMap = Mutex<HashMap<String, String>>;
/// Maximum number of offline track downloads that can run concurrently.
/// The frontend queues more tasks than this; Rust is the real throttle.
const MAX_DL_CONCURRENCY: usize = 4;
/// Shared semaphore that caps simultaneous `download_track_offline` executions.
type DownloadSemaphore = Arc<tokio::sync::Semaphore>;
/// Holds the live system-tray icon handle. `None` means the tray is currently hidden/removed.
/// Dropping the inner `TrayIcon` fully removes it from the OS notification area on all platforms.
type TrayState = Mutex<Option<TrayIcon>>;
@@ -399,8 +408,32 @@ fn mpris_set_playback(
.map_err(|e| format!("MPRIS set_playback failed: {e:?}"))
}
/// Returns true if `path` is an accessible directory (used for pre-flight checks in the frontend).
#[tauri::command]
fn check_dir_accessible(path: String) -> bool {
std::path::Path::new(&path).is_dir()
}
// ─── Offline Track Cache ──────────────────────────────────────────────────────
/// Streams an HTTP response body directly to `dest_path` in small chunks.
/// Never buffers the full file in memory — keeps RAM flat regardless of file size.
async fn stream_to_file(response: reqwest::Response, dest_path: &std::path::Path) -> Result<(), String> {
use futures_util::StreamExt;
use tokio::io::AsyncWriteExt;
let mut file = tokio::fs::File::create(dest_path)
.await
.map_err(|e| e.to_string())?;
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| e.to_string())?;
file.write_all(&chunk).await.map_err(|e| e.to_string())?;
}
file.flush().await.map_err(|e| e.to_string())?;
Ok(())
}
/// Downloads a single track to the app's offline cache directory.
/// Returns the absolute file path so TypeScript can store it and later
/// construct a `psysonic-local://<path>` URL for the audio engine.
@@ -411,6 +444,7 @@ async fn download_track_offline(
url: String,
suffix: String,
custom_dir: Option<String>,
dl_sem: tauri::State<'_, DownloadSemaphore>,
app: tauri::AppHandle,
) -> Result<String, String> {
// Determine base cache directory.
@@ -436,11 +470,15 @@ async fn download_track_offline(
let file_path = cache_dir.join(format!("{}.{}", track_id, suffix));
let path_str = file_path.to_string_lossy().to_string();
// Already cached — skip re-download.
// Already cached — skip re-download (no semaphore needed).
if file_path.exists() {
return Ok(path_str);
}
// Acquire a download slot. The permit is held for the duration of the HTTP transfer
// and released automatically when this function returns (success or error).
let _permit = dl_sem.acquire().await.map_err(|e| e.to_string())?;
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(120))
.build()
@@ -450,8 +488,14 @@ async fn download_track_offline(
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)
// Stream directly to a .part file; rename on success to avoid partial files.
let part_path = file_path.with_extension(format!("{suffix}.part"));
if let Err(e) = stream_to_file(response, &part_path).await {
let _ = tokio::fs::remove_file(&part_path).await;
return Err(e);
}
tokio::fs::rename(&part_path, &file_path)
.await
.map_err(|e| e.to_string())?;
@@ -569,6 +613,331 @@ fn resolve_hot_cache_root(
}
}
/// Returns true if the current Linux system is Arch-based
/// (checks /etc/arch-release and /etc/os-release).
#[tauri::command]
fn check_arch_linux() -> bool {
#[cfg(target_os = "linux")]
{
if std::path::Path::new("/etc/arch-release").exists() {
return true;
}
if let Ok(content) = std::fs::read_to_string("/etc/os-release") {
for line in content.lines() {
let lower = line.to_lowercase();
if lower.starts_with("id=arch") { return true; }
if lower.starts_with("id_like=") && lower.contains("arch") { return true; }
}
}
false
}
#[cfg(not(target_os = "linux"))]
{ false }
}
/// Progress payload emitted during an update binary download.
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct UpdateDownloadProgress {
bytes: u64,
total: Option<u64>,
}
/// Downloads an update installer/package to the user's Downloads folder.
/// Emits `update:download:progress` events with `{ bytes, total }` every 250 ms.
/// Returns the final absolute file path on success.
#[tauri::command]
async fn download_update(url: String, filename: String, app: tauri::AppHandle) -> Result<String, String> {
use futures_util::StreamExt;
use std::time::{Duration, Instant};
use tokio::io::AsyncWriteExt;
const EMIT_INTERVAL: Duration = Duration::from_millis(250);
let dest_dir = app.path().download_dir().map_err(|e| e.to_string())?;
let dest_path = dest_dir.join(&filename);
let part_path = dest_dir.join(format!("{}.part", filename));
let client = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(30))
.timeout(Duration::from_secs(3600))
.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 total = response.content_length();
let result: Result<u64, String> = async {
let mut file = tokio::fs::File::create(&part_path)
.await
.map_err(|e| e.to_string())?;
let mut bytes_done: u64 = 0;
let mut stream = response.bytes_stream();
let mut last_emit = Instant::now();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| e.to_string())?;
file.write_all(&chunk).await.map_err(|e| e.to_string())?;
bytes_done += chunk.len() as u64;
if last_emit.elapsed() >= EMIT_INTERVAL {
let _ = app.emit("update:download:progress", UpdateDownloadProgress {
bytes: bytes_done,
total,
});
last_emit = Instant::now();
}
}
file.flush().await.map_err(|e| e.to_string())?;
Ok(bytes_done)
}.await;
match result {
Err(e) => {
let _ = tokio::fs::remove_file(&part_path).await;
Err(e)
}
Ok(bytes_done) => {
let _ = app.emit("update:download:progress", UpdateDownloadProgress {
bytes: bytes_done,
total: Some(bytes_done),
});
tokio::fs::rename(&part_path, &dest_path)
.await
.map_err(|e| e.to_string())?;
Ok(dest_path.to_string_lossy().into_owned())
}
}
}
/// Reads embedded synced / unsynced lyrics from a local audio file.
///
/// Priority order:
/// MP3 → ID3v2 SYLT (synchronized, ms timestamps) → ID3v2 USLT (plain)
/// FLAC → Vorbis SYNCEDLYRICS (LRC string) → Vorbis LYRICS (plain)
///
/// Returns a standard LRC string (`[mm:ss.cc]line\n…`) for synced lyrics,
/// or plain text for unsynced lyrics. Returns `None` when no lyrics are found.
/// Errors are silenced and mapped to `None` so the frontend falls through to the
/// next lyrics source without crashing.
#[tauri::command]
fn get_embedded_lyrics(path: String) -> Option<String> {
use lofty::file::FileType;
use lofty::prelude::*;
use lofty::probe::Probe;
let fpath = std::path::Path::new(&path);
if !fpath.exists() {
return None;
}
// Detect file type from magic bytes only — no full tag read yet.
// guess_file_type() consumes self and returns Self, so reassign.
let probe = Probe::open(fpath).ok()?;
let probe = probe.guess_file_type().ok()?;
let file_type = probe.file_type();
// ── MP3 / MPEG: use the `id3` crate for SYLT / USLT ─────────────────────
// lofty's MpegFile::id3v2_tag field is pub(crate) — not accessible here.
// The `id3` crate exposes a clean public API for typed ID3v2 frames.
if matches!(file_type, Some(FileType::Mpeg)) {
use id3::{Content, Tag as Id3Tag};
if let Ok(tag) = Id3Tag::read_from_path(fpath) {
// 1. SYLT — millisecond-timestamped synced lyrics.
for frame in tag.frames() {
if frame.id() != "SYLT" {
continue;
}
if let Content::SynchronisedLyrics(sylt) = frame.content() {
// Only accept millisecond timestamps — MPEG-frame-based
// timestamps can't be converted to wall-clock seconds.
if sylt.timestamp_format != id3::frame::TimestampFormat::Ms {
continue;
}
let lrc: String = sylt
.content
.iter()
.filter_map(|(ms, text)| {
let t = text.trim();
if t.is_empty() {
return None;
}
let mins = ms / 60_000;
let secs = (ms % 60_000) / 1_000;
let cs = (ms % 1_000) / 10;
// [mm:ss.cc] matches parseLrc's /\d+(?:\.\d*)?/ regex
Some(format!("[{:02}:{:02}.{:02}]{}\n", mins, secs, cs, t))
})
.collect();
if !lrc.is_empty() {
return Some(lrc.trim_end().to_owned());
}
}
}
// 2. USLT — unsynchronized lyrics, plain-text fallback.
for frame in tag.frames() {
if frame.id() != "USLT" {
continue;
}
if let Content::Lyrics(uslt) = frame.content() {
let text = uslt.text.trim();
if !text.is_empty() {
return Some(text.to_owned());
}
}
}
}
return None; // MPEG file but no usable lyrics found
}
// ── FLAC / Vorbis / Opus / M4A: generic lofty tag API ────────────────────
// Vorbis SYNCEDLYRICS stores a complete LRC string in a plain comment field.
// It is not a known lofty ItemKey, so access it via ItemKey::Unknown.
let tagged = probe.read().ok()?;
for tag in tagged.tags() {
if let Some(lrc) = tag.get_string(&ItemKey::Unknown("SYNCEDLYRICS".to_owned())) {
let lrc = lrc.trim();
if !lrc.is_empty() {
return Some(lrc.to_owned());
}
}
if let Some(plain) = tag.get_string(&ItemKey::Lyrics) {
let plain = plain.trim();
if !plain.is_empty() {
return Some(plain.to_owned());
}
}
}
None
}
/// Opens a directory in the OS file manager (Explorer / Finder / Nautilus).
/// Uses platform-specific process spawning — tauri-plugin-shell's open() only
/// allows https:// URLs per the capability scope and fails silently for paths.
#[tauri::command]
fn open_folder(path: String) -> Result<(), String> {
#[cfg(target_os = "windows")]
{
std::process::Command::new("explorer.exe")
.arg(&path)
.spawn()
.map_err(|e| e.to_string())?;
}
#[cfg(target_os = "macos")]
{
std::process::Command::new("open")
.arg(&path)
.spawn()
.map_err(|e| e.to_string())?;
}
#[cfg(target_os = "linux")]
{
std::process::Command::new("xdg-open")
.arg(&path)
.spawn()
.map_err(|e| e.to_string())?;
}
Ok(())
}
/// Progress payload emitted to the frontend during a ZIP download.
/// `total` is `None` when the server doesn't send a `Content-Length` header
/// (Navidrome on-the-fly ZIPs).
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct ZipProgress {
id: String,
bytes: u64,
total: Option<u64>,
}
/// Downloads a server-generated ZIP (album/playlist) directly to disk via streaming.
/// Emits `download:zip:progress` events every 500 ms so the frontend can show
/// live MB-counter without holding any binary data in the WebView process.
/// Returns the final destination path on success.
#[tauri::command]
async fn download_zip(
id: String,
url: String,
dest_path: String,
app: tauri::AppHandle,
) -> Result<String, String> {
use futures_util::StreamExt;
use std::time::{Duration, Instant};
use tokio::io::AsyncWriteExt;
const EMIT_INTERVAL: Duration = Duration::from_millis(500);
let client = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(30))
.timeout(Duration::from_secs(7200)) // up to 2 h for large on-the-fly ZIPs
.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 total = response.content_length(); // None for Navidrome on-the-fly ZIPs
let part_path = format!("{dest_path}.part");
// Stream to .part file; rename on success, delete on error.
let result: Result<u64, String> = async {
let mut file = tokio::fs::File::create(&part_path)
.await
.map_err(|e| e.to_string())?;
let mut bytes_done: u64 = 0;
let mut stream = response.bytes_stream();
let mut last_emit = Instant::now();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| e.to_string())?;
file.write_all(&chunk).await.map_err(|e| e.to_string())?;
bytes_done += chunk.len() as u64;
if last_emit.elapsed() >= EMIT_INTERVAL {
let _ = app.emit("download:zip:progress", ZipProgress {
id: id.clone(),
bytes: bytes_done,
total,
});
last_emit = Instant::now();
}
}
file.flush().await.map_err(|e| e.to_string())?;
Ok(bytes_done)
}.await;
match result {
Err(e) => {
let _ = tokio::fs::remove_file(&part_path).await;
Err(e)
}
Ok(bytes_done) => {
// Final emission so the frontend sees 100 % (or final MB count).
let _ = app.emit("download:zip:progress", ZipProgress {
id: id.clone(),
bytes: bytes_done,
total: Some(bytes_done),
});
tokio::fs::rename(&part_path, &dest_path)
.await
.map_err(|e| e.to_string())?;
Ok(dest_path)
}
}
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct HotCacheDownloadResult {
@@ -618,12 +987,21 @@ async fn download_track_hot_cache(
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)
// Stream directly to a .part file; rename on success to avoid partial files.
let part_path = file_path.with_extension(format!("{suffix}.part"));
if let Err(e) = stream_to_file(response, &part_path).await {
let _ = tokio::fs::remove_file(&part_path).await;
return Err(e);
}
tokio::fs::rename(&part_path, &file_path)
.await
.map_err(|e| e.to_string())?;
let size = bytes.len() as u64;
let size = tokio::fs::metadata(&file_path)
.await
.map(|m| m.len())
.unwrap_or(0);
Ok(HotCacheDownloadResult {
path: path_str,
size,
@@ -870,6 +1248,7 @@ pub fn run() {
.manage(audio_engine)
.manage(ShortcutMap::default())
.manage(discord::DiscordState::new())
.manage(Arc::new(tokio::sync::Semaphore::new(MAX_DL_CONCURRENCY)) as DownloadSemaphore)
.manage(TrayState::default())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_window_state::Builder::default().build())
@@ -996,6 +1375,17 @@ pub fn run() {
app.manage(MprisControls::new(maybe_controls));
}
// ── Windows Taskbar Thumbnail Toolbar ────────────────────────
#[cfg(target_os = "windows")]
{
use tauri::Manager;
if let Some(w) = app.get_webview_window("main") {
if let Ok(hwnd) = w.hwnd() {
taskbar_win::init(app.handle(), hwnd.0 as isize);
}
}
}
Ok(())
})
.on_window_event(|window, event| {
@@ -1062,6 +1452,14 @@ pub fn run() {
delete_hot_cache_track,
purge_hot_cache,
toggle_tray_icon,
check_dir_accessible,
download_zip,
check_arch_linux,
download_update,
open_folder,
get_embedded_lyrics,
#[cfg(target_os = "windows")]
taskbar_win::update_taskbar_icon,
])
.run(tauri::generate_context!())
.expect("error while running Psysonic");
+276
View File
@@ -0,0 +1,276 @@
//! Windows Taskbar Thumbnail Toolbar (ITaskbarList3::ThumbBarAddButtons).
//!
//! Adds Prev / Play-Pause / Next buttons to the taskbar thumbnail preview.
//! Button clicks are intercepted via SetWindowSubclass and routed to the same
//! `media:prev`, `media:play-pause`, `media:next` events as souvlaki / tray.
use std::sync::atomic::{AtomicIsize, Ordering};
use tauri::{AppHandle, Emitter};
use windows::{
Win32::{
Foundation::{HWND, LPARAM, LRESULT, WPARAM},
System::Com::{
CoCreateInstance, CoInitializeEx, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED,
},
UI::{
Shell::{
DefSubclassProc, ITaskbarList3, RemoveWindowSubclass, SetWindowSubclass,
TaskbarList, THUMBBUTTON, THUMBBUTTONFLAGS, THUMBBUTTONMASK, THBN_CLICKED,
THB_FLAGS, THB_ICON, THB_TOOLTIP,
},
WindowsAndMessaging::{
CreateIconFromResourceEx, DestroyIcon, HICON, LR_DEFAULTCOLOR,
WM_COMMAND, WM_NCDESTROY,
},
},
},
};
// ── Embedded ICO assets ──────────────────────────────────────────────────────
static PREV_ICO: &[u8] = include_bytes!("../icons/windows/prev.ico");
static PLAY_ICO: &[u8] = include_bytes!("../icons/windows/play.ico");
static PAUSE_ICO: &[u8] = include_bytes!("../icons/windows/pause.ico");
static NEXT_ICO: &[u8] = include_bytes!("../icons/windows/next.ico");
// Button IDs — arbitrary u32 values, must fit in WPARAM low-word.
const BTN_PREV: u32 = 0xE001;
const BTN_PLAY: u32 = 0xE002;
const BTN_NEXT: u32 = 0xE003;
// Unique subclass ID.
const SUBCLASS_ID: usize = 0xC0DE_7A8B;
// Raw pointers kept as atomics so `update_taskbar_icon` can reach the
// COM object and icons without managed state.
static TASKBAR_PTR: AtomicIsize = AtomicIsize::new(0);
static HWND_VAL: AtomicIsize = AtomicIsize::new(0);
// All four HICONs stored for WM_NCDESTROY cleanup and play/pause swapping.
static HICON_PREV: AtomicIsize = AtomicIsize::new(0);
static HICON_PLAY: AtomicIsize = AtomicIsize::new(0);
static HICON_PAUSE: AtomicIsize = AtomicIsize::new(0);
static HICON_NEXT: AtomicIsize = AtomicIsize::new(0);
// ── ICO resource loader ──────────────────────────────────────────────────────
/// Load the best-match image from a raw `.ico` file in memory and return an HICON.
///
/// Parses the ICO directory to pick the entry with the highest bit depth
/// (32 bpp = true-colour + alpha), then passes the image bits directly to
/// `CreateIconFromResourceEx`.
///
/// Note: `LookupIconIdFromDirectoryEx` operates on Win32 *resource* group-icon
/// format (GRPICONDIR), not raw `.ico` files, so we parse the ICO header ourselves.
unsafe fn load_icon_from_memory(bytes: &[u8]) -> HICON {
// ICO file layout:
// ICONDIR : reserved(2) + type(2) + count(2)
// ICONDIRENTRY[] : width(1) height(1) color_count(1) reserved(1)
// planes(2) bit_count(2) bytes_in_res(4) image_offset(4)
if bytes.len() < 6 {
return HICON::default();
}
let count = u16::from_le_bytes([bytes[4], bytes[5]]) as usize;
if count == 0 || bytes.len() < 6 + count * 16 {
return HICON::default();
}
// Pick the entry with the highest bit depth; 32 bpp carries alpha.
let mut best_idx = 0usize;
let mut best_bpp = 0u16;
for i in 0..count {
let base = 6 + i * 16;
let bpp = u16::from_le_bytes([bytes[base + 6], bytes[base + 7]]);
if bpp >= best_bpp {
best_bpp = bpp;
best_idx = i;
}
}
let entry = &bytes[6 + best_idx * 16..];
let img_size = u32::from_le_bytes(entry[8..12].try_into().unwrap_or([0; 4]));
let img_offset = u32::from_le_bytes(entry[12..16].try_into().unwrap_or([0; 4])) as usize;
if img_size == 0 || img_offset + img_size as usize > bytes.len() {
return HICON::default();
}
CreateIconFromResourceEx(
&bytes[img_offset..img_offset + img_size as usize],
true, // fIcon = TRUE
0x0003_0000, // dwVer = 3.0 (required by the API)
0, 0, // cxDesired / cyDesired — 0 lets the system choose
LR_DEFAULTCOLOR,
)
.unwrap_or_default()
}
// ── Button descriptors ───────────────────────────────────────────────────────
fn copy_tip(dest: &mut [u16], src: &str) {
let wide: Vec<u16> = src.encode_utf16().chain(std::iter::once(0)).collect();
let len = wide.len().min(dest.len());
dest[..len].copy_from_slice(&wide[..len]);
}
unsafe fn make_buttons(
h_prev: HICON,
h_play: HICON,
h_next: HICON,
) -> [THUMBBUTTON; 3] {
let mask = THUMBBUTTONMASK(THB_ICON.0 | THB_TOOLTIP.0 | THB_FLAGS.0);
let flags = THUMBBUTTONFLAGS(0); // THBF_ENABLED
let mut prev = THUMBBUTTON::default();
prev.dwMask = mask; prev.iId = BTN_PREV;
prev.hIcon = h_prev; prev.dwFlags = flags;
copy_tip(&mut prev.szTip, "Previous");
let mut play = THUMBBUTTON::default();
play.dwMask = mask; play.iId = BTN_PLAY;
play.hIcon = h_play; play.dwFlags = flags;
copy_tip(&mut play.szTip, "Play");
let mut next = THUMBBUTTON::default();
next.dwMask = mask; next.iId = BTN_NEXT;
next.hIcon = h_next; next.dwFlags = flags;
copy_tip(&mut next.szTip, "Next");
[prev, play, next]
}
// ── WndProc subclass ─────────────────────────────────────────────────────────
struct SubclassData {
app: AppHandle,
}
unsafe extern "system" fn subclass_proc(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
_uid: usize,
data: usize,
) -> LRESULT {
if msg == WM_COMMAND {
let hi = (wparam.0 >> 16) as u32;
let lo = (wparam.0 & 0xFFFF) as u32;
if hi == THBN_CLICKED as u32 {
if data != 0 {
let state = &*(data as *const SubclassData);
let _ = match lo {
x if x == BTN_PREV => state.app.emit("media:prev", ()),
x if x == BTN_PLAY => state.app.emit("media:play-pause", ()),
x if x == BTN_NEXT => state.app.emit("media:next", ()),
_ => Ok(()),
};
}
return LRESULT(0);
}
}
if msg == WM_NCDESTROY {
let _ = RemoveWindowSubclass(hwnd, Some(subclass_proc), SUBCLASS_ID);
if data != 0 {
drop(Box::from_raw(data as *mut SubclassData));
}
let raw = TASKBAR_PTR.swap(0, Ordering::SeqCst);
if raw != 0 {
drop(Box::from_raw(raw as *mut ITaskbarList3));
}
HWND_VAL.store(0, Ordering::SeqCst);
// Destroy all stored HICONs.
for cell in [&HICON_PREV, &HICON_PLAY, &HICON_PAUSE, &HICON_NEXT] {
let h = cell.swap(0, Ordering::SeqCst);
if h != 0 { let _ = DestroyIcon(HICON(h as *mut _)); }
}
}
DefSubclassProc(hwnd, msg, wparam, lparam)
}
// ── Public init ──────────────────────────────────────────────────────────────
pub fn init(app: &AppHandle, hwnd_raw: isize) {
unsafe {
let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
let hwnd = HWND(hwnd_raw as *mut _);
let taskbar: ITaskbarList3 = match CoCreateInstance(
&TaskbarList, None, CLSCTX_INPROC_SERVER,
) {
Ok(t) => t,
Err(e) => { eprintln!("[psysonic] taskbar: CoCreateInstance failed: {e}"); return; }
};
if let Err(e) = taskbar.HrInit() {
eprintln!("[psysonic] taskbar: HrInit failed: {e}");
return;
}
let h_prev = load_icon_from_memory(PREV_ICO);
let h_play = load_icon_from_memory(PLAY_ICO);
let h_pause = load_icon_from_memory(PAUSE_ICO);
let h_next = load_icon_from_memory(NEXT_ICO);
// Store all HICONs for cleanup and play/pause swapping.
HICON_PREV .store(h_prev .0 as isize, Ordering::SeqCst);
HICON_PLAY .store(h_play .0 as isize, Ordering::SeqCst);
HICON_PAUSE.store(h_pause.0 as isize, Ordering::SeqCst);
HICON_NEXT .store(h_next .0 as isize, Ordering::SeqCst);
let mut buttons = make_buttons(h_prev, h_play, h_next);
if let Err(e) = taskbar.ThumbBarAddButtons(hwnd, &mut buttons) {
eprintln!("[psysonic] taskbar: ThumbBarAddButtons failed: {e}");
return;
}
let raw = Box::into_raw(Box::new(taskbar));
TASKBAR_PTR.store(raw as isize, Ordering::SeqCst);
HWND_VAL .store(hwnd_raw, Ordering::SeqCst);
let data = Box::into_raw(Box::new(SubclassData { app: app.clone() }));
if !SetWindowSubclass(hwnd, Some(subclass_proc), SUBCLASS_ID, data as usize).as_bool() {
eprintln!("[psysonic] taskbar: SetWindowSubclass failed");
drop(Box::from_raw(data));
}
}
}
// ── Tauri command ────────────────────────────────────────────────────────────
#[tauri::command]
pub fn update_taskbar_icon(is_playing: bool) {
let taskbar_raw = TASKBAR_PTR.load(Ordering::SeqCst);
let hwnd_raw = HWND_VAL .load(Ordering::SeqCst);
if taskbar_raw == 0 || hwnd_raw == 0 { return; }
let icon_raw = if is_playing {
HICON_PAUSE.load(Ordering::SeqCst)
} else {
HICON_PLAY.load(Ordering::SeqCst)
};
if icon_raw == 0 { return; }
unsafe {
let taskbar = &*(taskbar_raw as *const ITaskbarList3);
let hwnd = HWND(hwnd_raw as *mut _);
let mut btn = THUMBBUTTON::default();
btn.dwMask = THUMBBUTTONMASK(THB_ICON.0 | THB_TOOLTIP.0 | THB_FLAGS.0);
btn.iId = BTN_PLAY;
btn.hIcon = HICON(icon_raw as *mut _);
btn.dwFlags = THUMBBUTTONFLAGS(0);
copy_tip(&mut btn.szTip, if is_playing { "Pause" } else { "Play" });
let mut btns = [btn];
if let Err(e) = taskbar.ThumbBarUpdateButtons(hwnd, &mut btns) {
#[cfg(debug_assertions)]
eprintln!("[psysonic] taskbar: ThumbBarUpdateButtons failed: {e}");
let _ = e;
}
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Psysonic",
"version": "1.34.5",
"version": "1.34.7",
"identifier": "dev.psysonic.player",
"build": {
"beforeDevCommand": "npm run dev",
+18 -1
View File
@@ -67,6 +67,8 @@ import { useFontStore } from './store/fontStore';
import { useEqStore } from './store/eqStore';
import { useKeybindingsStore } from './store/keybindingsStore';
import { useGlobalShortcutsStore } from './store/globalShortcutsStore';
import { useZipDownloadStore } from './store/zipDownloadStore';
import ZipDownloadOverlay from './components/ZipDownloadOverlay';
function RequireAuth({ children }: { children: React.ReactNode }) {
const { isLoggedIn, servers, activeServerId } = useAuthStore();
@@ -86,9 +88,13 @@ function AppShell() {
}, []);
useEffect(() => {
if (!IS_LINUX) return;
const win = getCurrentWindow();
// Check initial state (e.g. app launched maximised / already fullscreen).
win.isFullscreen().then(setIsWindowFullscreen).catch(() => {});
let unlisten: (() => void) | undefined;
// onResized fires on every size change, including fullscreen enter/exit on
// all platforms. We re-query isFullscreen() rather than inferring from
// the size so the flag is always accurate regardless of platform quirks.
win.onResized(() => {
win.isFullscreen().then(setIsWindowFullscreen).catch(() => {});
}).then(u => { unlisten = u; });
@@ -297,6 +303,7 @@ function AppShell() {
data-mobile={isMobile || undefined}
data-mobile-player={isMobilePlayer || undefined}
data-titlebar={(IS_LINUX && useCustomTitlebar && !isWindowFullscreen && !isTilingWm) || undefined}
data-fullscreen={isWindowFullscreen || undefined}
style={{
'--sidebar-width': isMobile ? '0px' : (isSidebarCollapsed ? '72px' : 'clamp(200px, 15vw, 220px)'),
'--queue-width': isMobile ? '0px' : (isQueueVisible ? `${queueWidth}px` : '0px')
@@ -397,6 +404,15 @@ function TauriEventBridge() {
const next = usePlayerStore(s => s.next);
const previous = usePlayerStore(s => s.previous);
// ZIP download progress events from Rust
useEffect(() => {
let unlisten: (() => void) | undefined;
listen<{ id: string; bytes: number; total: number | null }>('download:zip:progress', e => {
useZipDownloadStore.getState().updateProgress(e.payload.id, e.payload.bytes, e.payload.total);
}).then(u => { unlisten = u; });
return () => { unlisten?.(); };
}, []);
// Sync tray-icon visibility with the user's stored setting.
// Runs once on mount (initial sync) and again whenever the setting changes.
const showTrayIcon = useAuthStore(s => s.showTrayIcon);
@@ -609,6 +625,7 @@ export default function App() {
/>
</Routes>
{exportPickerOpen && <ExportPickerModal onConfirm={handleExport} onClose={() => setExportPickerOpen(false)} />}
<ZipDownloadOverlay />
</BrowserRouter>
);
}
+3 -1
View File
@@ -36,7 +36,9 @@ export async function fetchLyrics(
export function parseLrc(lrc: string): LrcLine[] {
const lines: LrcLine[] = [];
for (const line of lrc.split('\n')) {
const match = line.match(/^\[(\d+):(\d+\.\d+)\](.*)/);
// \d+(?:\.\d*)? — decimal part is optional so [mm:ss] (no fraction) also matches.
// parseFloat handles all forms: "15", "15.", "15.3", "15.32" correctly.
const match = line.match(/^\[(\d+):(\d+(?:\.\d*)?)\](.*)/);
if (!match) continue;
const mins = parseInt(match[1], 10);
const secs = parseFloat(match[2]);
+5 -2
View File
@@ -856,7 +856,10 @@ export interface SubsonicLyricLine {
}
export interface SubsonicStructuredLyrics {
issynced: boolean;
/** OpenSubsonic spec field name (Navidrome ≥ 0.50.0 / any OpenSubsonic server). */
synced?: boolean;
/** Legacy / alternate casing used by some older Subsonic-compatible servers. */
issynced?: boolean;
lang?: string;
offset?: number;
displayArtist?: string;
@@ -878,7 +881,7 @@ export async function getLyricsBySongId(id: string): Promise<SubsonicStructuredL
);
const list = data.lyricsList?.structuredLyrics;
if (!list || list.length === 0) return null;
return list.find(l => l.issynced) ?? list[0];
return list.find(l => l.synced || l.issynced) ?? list[0];
} catch {
// Server doesn't support the endpoint or track has no embedded lyrics
return null;
+318 -42
View File
@@ -1,9 +1,15 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useState, useRef } from 'react';
import { createPortal } from 'react-dom';
import { open } from '@tauri-apps/plugin-shell';
import { RefreshCw, X } from 'lucide-react';
import { listen } from '@tauri-apps/api/event';
import { dirname } from '@tauri-apps/api/path';
import { invoke } from '@tauri-apps/api/core';
import { ArrowUpCircle, ChevronDown, Download, FolderOpen, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { version as currentVersion } from '../../package.json';
import { IS_LINUX, IS_MACOS, IS_WINDOWS } from '../utils/platform';
const SKIP_KEY = 'psysonic_skipped_update_version';
// Semver comparison: returns true if `a` is newer than `b`
function isNewer(a: string, b: string): boolean {
@@ -16,57 +22,327 @@ function isNewer(a: string, b: string): boolean {
return false;
}
function fmtBytes(n: number): string {
if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;
return `${(n / 1024 / 1024).toFixed(1)} MB`;
}
// Minimal inline-markdown renderer (bold, italic, code)
// IMPORTANT: regex must have NO nested capture groups — split() includes captured
// groups in the result, and nested groups produce undefined entries that crash on .startsWith()
function renderInline(text: string): React.ReactNode[] {
const parts = text.split(/(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`)/g);
return parts.map((part, i) => {
if (!part) return null;
if (part.startsWith('**') && part.endsWith('**'))
return <strong key={i}>{part.slice(2, -2)}</strong>;
if (part.startsWith('*') && part.endsWith('*'))
return <em key={i}>{part.slice(1, -1)}</em>;
if (part.startsWith('`') && part.endsWith('`'))
return <code key={i} className="changelog-code">{part.slice(1, -1)}</code>;
return part;
});
}
function renderChangelog(body: string) {
return body.split('\n').map((line, i) => {
if (line.startsWith('### '))
return <div key={i} className="changelog-h3">{renderInline(line.slice(4))}</div>;
if (line.startsWith('#### '))
return <div key={i} className="changelog-h4">{renderInline(line.slice(5))}</div>;
if (line.startsWith('## '))
return null; // skip nested release headers in body
if (line.startsWith('- '))
return <div key={i} className="changelog-item">{renderInline(line.slice(2))}</div>;
if (line.trim() === '') return null;
return <div key={i} className="changelog-text">{renderInline(line)}</div>;
});
}
interface GithubAsset {
name: string;
browser_download_url: string;
size: number;
}
interface ReleaseData {
version: string;
tag: string;
body: string;
assets: GithubAsset[];
}
function pickAsset(assets: GithubAsset[]): GithubAsset | undefined {
if (IS_WINDOWS) {
return assets.find(a => a.name.endsWith('-setup.exe'))
?? assets.find(a => a.name.endsWith('.exe'));
}
if (IS_MACOS) {
// Prefer Apple Silicon, fall back to Intel
return assets.find(a => a.name.endsWith('.dmg') && a.name.includes('aarch64'))
?? assets.find(a => a.name.endsWith('.dmg'));
}
if (IS_LINUX) {
// AppImage > deb > rpm
return assets.find(a => a.name.endsWith('.AppImage'))
?? assets.find(a => a.name.endsWith('.deb'))
?? assets.find(a => a.name.endsWith('.rpm'));
}
return undefined;
}
type DlState = 'idle' | 'downloading' | 'done' | 'error';
export default function AppUpdater() {
const { t } = useTranslation();
const [newVersion, setNewVersion] = useState<string | null>(null);
const [release, setRelease] = useState<ReleaseData | null>(null);
const [dismissed, setDismissed] = useState(false);
const [changelogOpen, setChangelogOpen] = useState(false);
const [isArch, setIsArch] = useState(false);
const [dlState, setDlState] = useState<DlState>('idle');
const [dlProgress, setDlProgress] = useState({ bytes: 0, total: 0 });
const [dlPath, setDlPath] = useState('');
const [dlError, setDlError] = useState('');
const unlistenRef = useRef<(() => void) | null>(null);
const fetchRelease = async (preview = false) => {
try {
const res = await fetch('https://api.github.com/repos/Psychotoxical/psysonic/releases/latest');
if (!res.ok) return;
const data = await res.json();
const tag: string = data.tag_name ?? '';
const version = tag.replace(/^[^0-9]*/, '');
if (!version) return;
if (!preview) {
if (!isNewer(version, currentVersion)) return;
const skipped = localStorage.getItem(SKIP_KEY);
if (skipped === version) return;
}
setDismissed(false);
setDlState('idle');
setRelease({
version,
tag,
body: (data.body ?? '').trim(),
assets: data.assets ?? [],
});
if (IS_LINUX) {
const arch = await invoke<boolean>('check_arch_linux');
setIsArch(arch);
}
} catch {
// No network or rate-limited — stay idle
}
};
useEffect(() => {
let cancelled = false;
const timer = setTimeout(async () => {
if (cancelled) return;
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)) {
setNewVersion(tag.replace(/^[^0-9]*/, ''));
}
} catch {
// No network or rate-limited — stay idle
}
}, 4000);
return () => { cancelled = true; clearTimeout(timer); };
const timer = setTimeout(() => { if (!cancelled) fetchRelease(); }, 4000);
const handler = () => fetchRelease(true);
window.addEventListener('psysonic:preview-update', handler);
return () => {
cancelled = true;
clearTimeout(timer);
window.removeEventListener('psysonic:preview-update', handler);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (!newVersion || dismissed) return null;
// Clean up download listener when component unmounts
useEffect(() => {
return () => { unlistenRef.current?.(); };
}, []);
if (!release || dismissed) return null;
const asset = pickAsset(release.assets);
const showAurHint = IS_LINUX && isArch;
const handleSkip = () => {
localStorage.setItem(SKIP_KEY, release.version);
setDismissed(true);
};
const handleDownload = async () => {
if (!asset) return;
setDlState('downloading');
setDlProgress({ bytes: 0, total: asset.size });
setDlError('');
const unlisten = await listen<{ bytes: number; total: number | null }>(
'update:download:progress',
e => {
setDlProgress({
bytes: e.payload.bytes,
total: e.payload.total ?? asset.size,
});
}
);
unlistenRef.current = unlisten;
try {
const finalPath = await invoke<string>('download_update', {
url: asset.browser_download_url,
filename: asset.name,
});
unlisten();
unlistenRef.current = null;
setDlPath(finalPath);
setDlState('done');
} catch (e) {
unlisten();
unlistenRef.current = null;
setDlError(String(e));
setDlState('error');
}
};
const handleShowFolder = async () => {
// tauri-plugin-shell's open() only allows https:// per capability scope —
// local paths are blocked and fail silently. Delegate to Rust instead.
const dir = await dirname(dlPath);
await invoke('open_folder', { path: dir });
};
const pct = dlProgress.total > 0
? Math.min(100, Math.round((dlProgress.bytes / dlProgress.total) * 100))
: 0;
return createPortal(
<div className="app-updater-toast">
<div className="app-updater-header">
<RefreshCw size={13} />
<span className="app-updater-label">{t('common.updaterAvailable')}</span>
<button className="app-updater-dismiss" onClick={() => setDismissed(true)} aria-label="Dismiss">
<X size={12} />
</button>
<>
<div className="eq-popup-backdrop" onClick={() => setDismissed(true)} style={{ zIndex: 3000 }} />
<div
className="eq-popup update-modal"
style={{ zIndex: 3001 }}
onClick={e => e.stopPropagation()}
>
{/* Header */}
<div className="eq-popup-header update-modal-header">
<ArrowUpCircle size={16} style={{ color: 'var(--accent)', flexShrink: 0 }} />
<div style={{ flex: 1, minWidth: 0 }}>
<span className="eq-popup-title">{t('common.updaterModalTitle')}</span>
<span className="update-modal-versions">
v{currentVersion} <strong>v{release.version}</strong>
</span>
</div>
<button
className="app-updater-dismiss"
onClick={() => setDismissed(true)}
data-tooltip={t('common.updaterRemindBtn')}
data-tooltip-pos="bottom"
>
<X size={14} />
</button>
</div>
{/* Scrollable body: changelog + download area — single overflow container */}
<div className="update-modal-body">
{/* Collapsible Changelog */}
{release.body && (
<div className="update-modal-changelog">
<button
type="button"
className="update-modal-changelog-toggle"
onClick={() => setChangelogOpen(v => !v)}
>
<ChevronDown
size={13}
style={{
transform: changelogOpen ? 'rotate(180deg)' : 'none',
transition: 'transform 0.2s',
flexShrink: 0,
}}
/>
{t('common.updaterChangelog')}
</button>
{changelogOpen && (
<div className="update-modal-changelog-body">
{renderChangelog(release.body)}
</div>
)}
</div>
)}
{/* Download / AUR area */}
<div className="update-modal-download-area">
{showAurHint ? (
<div className="update-modal-aur">
<div className="update-modal-aur-title">{t('common.updaterAurHint')}</div>
<code className="update-modal-aur-cmd">yay -S psysonic-bin</code>
<code className="update-modal-aur-cmd update-modal-aur-alt">sudo pacman -Syu psysonic-bin</code>
</div>
) : asset ? (
<>
{dlState === 'idle' && (
<div className="update-modal-asset">
<span className="update-modal-asset-name">{asset.name}</span>
<span className="update-modal-asset-size">{fmtBytes(asset.size)}</span>
</div>
)}
{dlState === 'downloading' && (
<div className="update-modal-progress">
<div className="app-updater-progress-bar">
<div className="app-updater-progress-fill" style={{ width: `${pct}%` }} />
</div>
<span className="app-updater-pct">{pct}%</span>
<span className="update-modal-dl-bytes">
{fmtBytes(dlProgress.bytes)}
{dlProgress.total > 0 && ` / ${fmtBytes(dlProgress.total)}`}
</span>
</div>
)}
{dlState === 'done' && (
<div className="update-modal-done">
<div className="update-modal-done-title">{t('common.updaterDone')}</div>
<div className="update-modal-done-hint">{t('common.updaterInstallHint')}</div>
<button className="btn btn-surface update-modal-folder-btn" onClick={handleShowFolder}>
<FolderOpen size={14} />
{t('common.updaterShowFolder')}
</button>
</div>
)}
{dlState === 'error' && (
<div className="app-updater-error">{dlError || t('common.updaterErrorMsg')}</div>
)}
</>
) : (
<div className="update-modal-asset-none">
<button
className="app-updater-btn-primary"
onClick={() => open(`https://github.com/Psychotoxical/psysonic/releases/tag/${release.tag}`)}
>
{t('common.updaterOpenGitHub')}
</button>
</div>
)}
</div>
</div>{/* end update-modal-body */}
{/* Footer buttons */}
<div className="update-modal-footer">
<button className="btn btn-ghost update-modal-skip" onClick={handleSkip}>
{t('common.updaterSkipBtn')}
</button>
<div style={{ flex: 1 }} />
<button className="btn btn-surface" onClick={() => setDismissed(true)}>
{t('common.updaterRemindBtn')}
</button>
{!showAurHint && asset && dlState === 'idle' && (
<button className="btn btn-primary" onClick={handleDownload}>
<Download size={14} />
{t('common.updaterDownloadBtn')}
</button>
)}
{dlState === 'error' && (
<button className="btn btn-primary" onClick={handleDownload}>
{t('common.updaterRetryBtn')}
</button>
)}
</div>
</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
);
}
+58 -27
View File
@@ -10,8 +10,9 @@ import { useAuthStore } from '../store/authStore';
import { useDownloadModalStore } from '../store/downloadModalStore';
import { usePlaylistStore } from '../store/playlistStore';
import { open } from '@tauri-apps/plugin-shell';
import { writeFile } from '@tauri-apps/plugin-fs';
import { join } from '@tauri-apps/api/path';
import { invoke } from '@tauri-apps/api/core';
import { useZipDownloadStore } from '../store/zipDownloadStore';
import { useTranslation } from 'react-i18next';
function sanitizeFilename(name: string): string {
@@ -22,6 +23,16 @@ function sanitizeFilename(name: string): string {
.substring(0, 200) || 'download';
}
/** Fisher-Yates in-place shuffle — returns a new array, does not mutate the input. */
function shuffleArray<T>(arr: T[]): T[] {
const result = [...arr];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
// ── Add-to-Playlist submenu ───────────────────────────────────────
export function AddToPlaylistSubmenu({ songIds, onDone, dropDown }: { songIds: string[]; onDone: () => void; dropDown?: boolean }) {
const { t } = useTranslation();
@@ -220,12 +231,16 @@ export default function ContextMenu() {
}
// Load radio queue in background — enqueueRadio replaces any pending radio
// tracks so clicking "Start Radio" again never stacks duplicate batches.
// Shuffle so the follow-up tracks feel fresh instead of always being the
// same "Top 5" in the same order every time.
try {
const [similar, top] = await Promise.all([getSimilarSongs2(artistId), getTopSongs(artistName)]);
const radioTracks = [...top, ...similar]
.map(songToTrack)
.filter(t => t.id !== seedTrack.id)
.map(t => ({ ...t, radioAdded: true as const }));
const radioTracks = shuffleArray(
[...top, ...similar]
.map(songToTrack)
.filter(t => t.id !== seedTrack.id)
.map(t => ({ ...t, radioAdded: true as const }))
);
if (radioTracks.length > 0) usePlayerStore.getState().enqueueRadio(radioTracks, artistId);
} catch (e) {
console.error('Failed to load radio queue', e);
@@ -237,11 +252,17 @@ export default function ContextMenu() {
const similarPromise = getSimilarSongs2(artistId).catch(() => [] as Awaited<ReturnType<typeof getSimilarSongs2>>);
try {
const top = await getTopSongs(artistName);
const topTracks = top.map(t => ({ ...songToTrack(t), radioAdded: true as const }));
// Shuffle so each Radio session starts from a different track rather
// than always kicking off with the #1 most-played song.
const topTracks = shuffleArray(
top.map(t => ({ ...songToTrack(t), radioAdded: true as const }))
);
if (topTracks.length === 0) {
// No local top songs — fall back to waiting for similar tracks
const similar = await similarPromise;
const fallback = similar.map(t => ({ ...songToTrack(t), radioAdded: true as const }));
const fallback = shuffleArray(
similar.map(t => ({ ...songToTrack(t), radioAdded: true as const }))
);
if (fallback.length === 0) return;
const state = usePlayerStore.getState();
if (state.currentTrack) {
@@ -252,22 +273,29 @@ export default function ContextMenu() {
}
return;
}
// Start playback immediately from top songs
// Start playback from the first shuffled top track only.
// No other tracks are queued yet — positions 2+ will be filled
// exclusively by the similar-songs result below.
const state = usePlayerStore.getState();
if (state.currentTrack) {
state.enqueueRadio(topTracks, artistId);
state.enqueueRadio([topTracks[0]], artistId);
} else {
state.setRadioArtistId(artistId);
playTrack(topTracks[0], topTracks);
playTrack(topTracks[0], [topTracks[0]]);
}
// Enrich with similar tracks in the background
// Populate positions 2+ from similar songs only — never from the
// remaining top tracks. Mixing in topTracks.slice(1) meant that when
// getSimilarSongs2 returned nothing (no Last.fm, small library, etc.)
// the queue fell back to the same top-4 the user just heard.
// If similarTracks is also empty, the proactive top-up in next()
// will refill the queue when the first track nears its end.
similarPromise.then(similar => {
const similarTracks = similar
.map(t => ({ ...songToTrack(t), radioAdded: true as const }))
.filter(t => !topTracks.some(top => top.id === t.id));
const similarTracks = shuffleArray(
similar
.map(t => ({ ...songToTrack(t), radioAdded: true as const }))
.filter(t => t.id !== topTracks[0].id)
);
if (similarTracks.length === 0) return;
// Collect pending (upcoming) radio tracks so enqueueRadio re-inserts them
// together with the new similar tracks rather than losing them.
const { queue, queueIndex } = usePlayerStore.getState();
const pendingRadio = queue.slice(queueIndex + 1).filter(t => t.radioAdded);
usePlayerStore.getState().enqueueRadio([...pendingRadio, ...similarTracks], artistId);
@@ -279,19 +307,22 @@ export default function ContextMenu() {
};
const downloadAlbum = async (albumName: string, albumId: string) => {
try {
const folder = auth.downloadFolder || await requestDownloadFolder();
if (!folder) return;
const folder = auth.downloadFolder || await requestDownloadFolder();
if (!folder) return;
const url = buildDownloadUrl(albumId);
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blob = await response.blob();
const buffer = await blob.arrayBuffer();
const path = await join(folder, `${sanitizeFilename(albumName)}.zip`);
await writeFile(path, new Uint8Array(buffer));
const filename = `${sanitizeFilename(albumName)}.zip`;
const destPath = await join(folder, filename);
const url = buildDownloadUrl(albumId);
const id = crypto.randomUUID();
const { start, complete, fail } = useZipDownloadStore.getState();
start(id, filename);
try {
await invoke('download_zip', { id, url, destPath });
complete(id);
} catch (e) {
console.error('Download failed:', e);
fail(id);
console.error('ZIP download failed:', e);
}
};
+13 -2
View File
@@ -2,6 +2,7 @@ import React, { useState, useRef, useLayoutEffect, useEffect, useCallback } from
import { createPortal } from 'react-dom';
import { usePlayerStore } from '../store/playerStore';
import { useOfflineStore } from '../store/offlineStore';
import { useOfflineJobStore } from '../store/offlineJobStore';
import { useAuthStore } from '../store/authStore';
import { useSidebarStore } from '../store/sidebarStore';
import { NavLink } from 'react-router-dom';
@@ -9,7 +10,7 @@ import { useTranslation } from 'react-i18next';
import {
Disc3, Users, Music4, Radio, Settings, Heart, BarChart3, Shuffle,
PanelLeftClose, PanelLeft, HelpCircle, Dices, AudioLines, HardDriveDownload, Tags, ListMusic, Cast,
ChevronDown, Check, Music2, TrendingUp, FolderOpen,
ChevronDown, Check, Music2, TrendingUp, FolderOpen, X,
} from 'lucide-react';
import PsysonicLogo from './PsysonicLogo';
import PSmallLogo from './PSmallLogo';
@@ -44,7 +45,8 @@ export default function Sidebar({
const { t } = useTranslation();
const isPlaying = usePlayerStore(s => s.isPlaying);
const currentTrack = usePlayerStore(s => s.currentTrack);
const offlineJobs = useOfflineStore(s => s.jobs);
const offlineJobs = useOfflineJobStore(s => s.jobs);
const cancelAllDownloads = useOfflineJobStore(s => s.cancelAllDownloads);
const activeJobs = offlineJobs.filter(j => j.status === 'queued' || j.status === 'downloading');
const offlineAlbums = useOfflineStore(s => s.albums);
const serverId = useAuthStore(s => s.activeServerId ?? '');
@@ -288,6 +290,15 @@ export default function Sidebar({
{!isCollapsed && (
<span>{t('sidebar.downloadingTracks', { n: activeJobs.length })}</span>
)}
<button
className="sidebar-offline-cancel"
onClick={cancelAllDownloads}
data-tooltip={t('sidebar.cancelDownload')}
data-tooltip-pos="right"
aria-label={t('sidebar.cancelDownload')}
>
<X size={12} />
</button>
</div>
)}
</nav>
+1 -2
View File
@@ -3,9 +3,8 @@ import { getCurrentWindow } from '@tauri-apps/api/window';
import { X, Minus, Square } from 'lucide-react';
import { usePlayerStore } from '../store/playerStore';
const win = getCurrentWindow();
export default function TitleBar() {
const win = getCurrentWindow();
const currentTrack = usePlayerStore(s => s.currentTrack);
const isPlaying = usePlayerStore(s => s.isPlaying);
+78
View File
@@ -0,0 +1,78 @@
import { useEffect } from 'react';
import { createPortal } from 'react-dom';
import { HardDriveDownload, Check, X } from 'lucide-react';
import { useZipDownloadStore } from '../store/zipDownloadStore';
function formatMB(bytes: number): string {
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function ZipDownloadItem({ id }: { id: string }) {
const dismiss = useZipDownloadStore(s => s.dismiss);
const item = useZipDownloadStore(s => s.downloads.find(d => d.id === id));
// Auto-dismiss 3 s after completion or error.
useEffect(() => {
if (!item?.done && !item?.error) return;
const timer = setTimeout(() => dismiss(id), 3000);
return () => clearTimeout(timer);
}, [item?.done, item?.error, id, dismiss]);
if (!item) return null;
const pct = item.total && item.total > 0
? Math.min(100, (item.bytes / item.total) * 100)
: null;
const isIndeterminate = !item.done && !item.error && (item.total === null || item.total === 0);
return (
<div className={`zip-dl-item${item.done ? ' zip-dl-done' : item.error ? ' zip-dl-error' : ''}`}>
<div className="zip-dl-header">
{item.done
? <Check size={13} />
: item.error
? <X size={13} />
: <HardDriveDownload size={13} className="spin-slow" />
}
<span className="zip-dl-name" data-tooltip={item.filename} data-tooltip-pos="top">{item.filename}</span>
{(item.done || item.error) && (
<button className="zip-dl-close" onClick={() => dismiss(id)} aria-label="Close">
<X size={10} />
</button>
)}
</div>
{!item.done && !item.error && (
<>
<div className="zip-dl-info">
{formatMB(item.bytes)}
{item.total !== null && item.total > 0 && (
<> / {formatMB(item.total)} &nbsp;({pct!.toFixed(0)}%)</>
)}
</div>
<div className={`zip-dl-track${isIndeterminate ? ' zip-dl-indeterminate' : ''}`}>
{!isIndeterminate && pct !== null && (
<div className="zip-dl-fill" style={{ width: `${pct}%` }} />
)}
</div>
</>
)}
</div>
);
}
export default function ZipDownloadOverlay() {
// Subscribe to the array reference directly — never derive a new array in the selector
// (selector returning new array on every call causes an infinite re-render loop).
const downloads = useZipDownloadStore(s => s.downloads);
if (downloads.length === 0) return null;
return createPortal(
<div className="zip-dl-overlay">
{downloads.map(d => <ZipDownloadItem key={d.id} id={d.id} />)}
</div>,
document.body,
);
}
+42 -2
View File
@@ -1,10 +1,13 @@
import { useEffect, useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { fetchLyrics, parseLrc, LrcLine } from '../api/lrclib';
import { getLyricsBySongId, SubsonicStructuredLyrics } from '../api/subsonic';
import { useAuthStore } from '../store/authStore';
import { useOfflineStore } from '../store/offlineStore';
import { useHotCacheStore } from '../store/hotCacheStore';
import type { Track } from '../store/playerStore';
export type LyricsSource = 'server' | 'lrclib';
export type LyricsSource = 'server' | 'lrclib' | 'embedded';
export interface CachedLyrics {
syncedLines: LrcLine[] | null;
@@ -20,7 +23,9 @@ export const lyricsCache = new Map<string, CachedLyrics>();
export function parseStructuredLyrics(
lyrics: SubsonicStructuredLyrics,
): Pick<CachedLyrics, 'syncedLines' | 'plainLyrics'> {
if (lyrics.issynced && lyrics.line.length > 0) {
// Accept both `synced` (OpenSubsonic spec) and `issynced` (legacy servers).
const isSynced = !!(lyrics.synced ?? lyrics.issynced);
if (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() }))
@@ -79,6 +84,37 @@ export function useLyrics(currentTrack: Track | null): UseLyricsResult {
setLoading(false);
};
// For offline / hot-cached tracks we have the file locally — read SYLT /
// SYNCEDLYRICS directly via Rust instead of relying on Navidrome's parsing.
// Fast path: both store lookups are synchronous; returns false immediately
// for streaming tracks so it has zero impact on the normal fetch sequence.
const fetchEmbedded = async (): Promise<boolean> => {
const serverId = useAuthStore.getState().activeServerId ?? '';
const localUrl =
useOfflineStore.getState().getLocalUrl(currentTrack.id, serverId) ??
useHotCacheStore.getState().getLocalUrl(currentTrack.id, serverId);
if (!localUrl) return false;
const prefix = 'psysonic-local://';
const filePath = localUrl.startsWith(prefix) ? localUrl.slice(prefix.length) : null;
if (!filePath) return false;
try {
const lrcString = await invoke<string | null>('get_embedded_lyrics', { path: filePath });
if (!lrcString) return false;
const lines = parseLrc(lrcString);
const synced = lines.length > 0 ? lines : null;
const plain = synced ? null : (lrcString.trim() || null);
if (!synced && !plain) return false;
store({ syncedLines: synced, plainLyrics: plain, source: 'embedded', notFound: false });
return true;
} catch {
return false;
}
};
const fetchServer = async (): Promise<boolean> => {
const structured = await getLyricsBySongId(currentTrack.id);
if (!structured) return false;
@@ -107,6 +143,10 @@ export function useLyrics(currentTrack: Track | null): UseLyricsResult {
};
(async () => {
// Embedded lyrics from local file always win (most accurate SYLT data).
if (cancelled) return;
if (await fetchEmbedded()) return;
const [first, second] = lyricsServerFirst
? [fetchServer, fetchLrclibFn]
: [fetchLrclibFn, fetchServer];
+36
View File
@@ -16,6 +16,7 @@ export const deTranslation = {
expand: 'Sidebar einblenden',
collapse: 'Sidebar ausblenden',
downloadingTracks: '{{n}} Tracks werden gecacht…',
cancelDownload: 'Download abbrechen',
offlineLibrary: 'Offline-Bibliothek',
genres: 'Genres',
playlists: 'Playlists',
@@ -349,6 +350,18 @@ export const deTranslation = {
updaterAvailable: 'Update verfügbar',
updaterVersion: 'v{{version}} verfügbar',
updaterWebsite: 'Website',
updaterModalTitle: 'Neue Version verfügbar',
updaterChangelog: 'Was ist neu',
updaterDownloadBtn: 'Jetzt herunterladen',
updaterSkipBtn: 'Version überspringen',
updaterRemindBtn: 'Später erinnern',
updaterDone: 'Download abgeschlossen',
updaterShowFolder: 'Im Ordner anzeigen',
updaterInstallHint: 'Psysonic schließen und das Installationsprogramm manuell ausführen.',
updaterAurHint: 'Update über AUR installieren:',
updaterErrorMsg: 'Download fehlgeschlagen',
updaterRetryBtn: 'Erneut versuchen',
updaterOpenGitHub: 'Auf GitHub öffnen',
},
settings: {
title: 'Einstellungen',
@@ -667,6 +680,28 @@ export const deTranslation = {
a35: 'Album öffnen und auf das Download-Symbol im Album-Header klicken. Psysonic lädt alle Tracks im Hintergrund herunter. Der Fortschritt wird am Button angezeigt. Nach dem Download wird das Symbol grün. Gecachte Alben können in der Offline-Bibliothek (Seitenleiste) verwaltet und gelöscht werden.',
q36: 'Wie viel Speicherplatz darf der Cache belegen?',
a36: 'In Einstellungen → Bibliothek kann eine maximale Cache-Größe festgelegt werden. Wird das Limit erreicht, erscheint ein Warnbanner auf der Albumseite. Einzelne Alben können in der Offline-Bibliothek gelöscht werden, um Speicherplatz freizugeben.',
q37: 'Wie bewerte ich Songs, Alben und Künstler?',
a37: 'Psysonic unterstützt 15-Sterne-Bewertungen über die OpenSubsonic-API (erfordert Navidrome ≥ 0.53). Songs können in der Trackliste eines Albums oder einer Playlist (Spalte „Bewertung"), über das Rechtsklick-Kontextmenü oder direkt in der Playerleiste unterhalb des Künstlernamens bewertet werden. Alben werden auf der Albumdetailseite bewertet, Künstler auf der Künstlerseite. Bewertungen werden sofort an den Server übertragen.',
q38: 'Kann ich eine Bewertung entfernen oder ändern?',
a38: 'Ja. Ein erneuter Klick auf den bereits aktiven Stern entfernt die Bewertung vollständig der zweite Klick auf denselben Stern löscht sie also. Um eine Bewertung zu ändern, einfach einen anderen Stern anklicken.',
q39: 'Was ist Skip-to-1★ und der Bewertungsfilter?',
a39: 'Skip-to-1★ vergibt automatisch eine 1-Stern-Bewertung, wenn ein Song mehrfach hintereinander manuell übersprungen wird. Aktivierung und Schwellenwert in Einstellungen → Bewertungen. Dort lässt sich auch eine Mindestbewertung für Zufalls-Mix und Zufallsalben festlegen so werden nur Songs, Alben oder Künstler ab einer bestimmten Sternzahl in generierten Mixes berücksichtigt.',
q40: 'Was ist der Ordner-Browser?',
a40: 'Der Ordner-Browser (Sidebar) ermöglicht die Navigation im Musikverzeichnis des Servers über ein Miller-Column-Layout. Ein Klick auf einen Ordner öffnet dessen Inhalt; über das Play-Symbol lassen sich Ordner direkt abspielen oder zur Warteschlange hinzufügen.',
q41: 'Was ist der Theme-Scheduler?',
a41: 'Einstellungen → Darstellung → Theme automatisch wechseln: Tagesthema und Nachtthema mit Startzeiten konfigurieren. Psysonic wechselt automatisch zur eingestellten Uhrzeit. Ist der Scheduler aktiv, erscheint im Theme-Picker ein Hinweis, warum manuelle Änderungen keine sofortige Wirkung haben.',
q42: 'Kann ich die Benutzeroberfläche vergrößern oder verkleinern?',
a42: 'Ja. Einstellungen → Darstellung → Anzeigeskalierung ermöglicht eine Skalierung der gesamten Oberfläche zwischen 80 % und 125 %, unabhängig von der Systemschriftgröße.',
q43: 'Kann ich den Stil der Seekbar ändern?',
a43: 'Ja. Einstellungen → Darstellung → Seekbar-Stil bietet 10 Stile: Wellenform, Linie & Punkt, Balken, Dicker Balken, Segmentiert, Neon-Glow, Pulswelle, Partikelspur, Flüssigfüllung und Retro-Tape.',
q44: 'Was ist AutoEQ?',
a44: 'Der 10-Band-EQ in Einstellungen → Audio enthält eine AutoEQ-Suche. Kopfhörermodell eingeben Psysonic lädt das Korrekturprofil aus der AutoEQ-Datenbank und überträgt es automatisch auf die EQ-Bänder.',
q45: 'Was ist Replay Gain?',
a45: 'Replay Gain normalisiert die Lautstärke, sodass laute und leise Alben auf einem gleichmäßigen Pegel wiedergegeben werden. Aktivierung in Einstellungen → Audio → Replay Gain; Modus Track (pro Song) oder Album (behält die relative Dynamik innerhalb eines Albums).',
q46: 'Was ist der Hot Cache?',
a46: 'Der Hot Cache (Alpha, Einstellungen → Bibliothek) lädt die nächsten Songs der Warteschlange vorab auf die Festplatte, damit die Wiedergabe ohne Pufferverzögerung startet besonders nützlich bei langsamen oder entfernten Servern. Psysonic hält den aktuellen Track und die nächsten 5 im Cache und verdrängt ältere Einträge, wenn das Größenlimit erreicht wird. Cache-Größe und Debounce-Verzögerung sind konfigurierbar.',
q47: 'Kann ich eine Playlist offline cachen?',
a47: 'Ja. In den Playlist-Details auf das Download-Symbol klicken alle Tracks werden im Hintergrund heruntergeladen. Ist die Playlist vollständig gecacht, wechselt das Symbol zu einem roten Papierkorb; ein erneuter Klick entfernt die Playlist aus dem Offline-Cache.',
},
queue: {
title: 'Warteschlange',
@@ -823,6 +858,7 @@ export const deTranslation = {
addSong: 'Zur Playlist hinzufügen',
cacheOffline: 'Playlist offline speichern',
offlineCached: 'Playlist gecacht',
removeOffline: 'Aus Offline-Cache entfernen',
offlineDownloading: 'Wird gecacht… ({{done}}/{{total}} Alben)',
publicLabel: 'Öffentlich',
privateLabel: 'Privat',
+36
View File
@@ -17,6 +17,7 @@ export const enTranslation = {
collapse: 'Collapse Sidebar',
downloadingTracks: 'Caching {{n}} tracks…',
cancelDownload: 'Cancel download',
offlineLibrary: 'Offline Library',
genres: 'Genres',
playlists: 'Playlists',
@@ -350,6 +351,18 @@ export const enTranslation = {
updaterAvailable: 'Update available',
updaterVersion: 'v{{version}} is available',
updaterWebsite: 'Website',
updaterModalTitle: 'New Version Available',
updaterChangelog: "What's New",
updaterDownloadBtn: 'Download Now',
updaterSkipBtn: 'Skip this Version',
updaterRemindBtn: 'Remind me Later',
updaterDone: 'Download complete',
updaterShowFolder: 'Show in Folder',
updaterInstallHint: 'Close Psysonic and run the installer manually.',
updaterAurHint: 'Install the update via AUR:',
updaterErrorMsg: 'Download failed',
updaterRetryBtn: 'Retry',
updaterOpenGitHub: 'Open on GitHub',
},
settings: {
title: 'Settings',
@@ -668,6 +681,28 @@ export const enTranslation = {
a35: 'Open any album and click the download icon in the album header. Psysonic downloads all tracks in the background. Progress is shown on the button. Once cached, the icon turns green. You can view and remove cached albums in the Offline Library page (sidebar).',
q36: 'How much storage can offline caching use?',
a36: 'You can set a maximum cache size in Settings → Library. When the limit is reached, a warning banner appears on the album page. You can delete individual albums from the Offline Library to free up space.',
q37: 'How do I rate songs, albums, and artists?',
a37: 'Psysonic supports 15 star ratings via the OpenSubsonic API (requires Navidrome ≥ 0.53). Rate songs in the album or playlist track list using the star column, in the right-click context menu, or directly in the player bar below the artist name. Albums can be rated on their detail page; artists on their artist page. Ratings are saved to the server immediately.',
q38: 'Can I remove or change a rating?',
a38: 'Yes. Click the currently active star to clear the rating entirely — clicking the same star a second time removes it. To change a rating, simply click a different star.',
q39: 'What is Skip-to-1★ and the rating filter?',
a39: 'Skip-to-1★ automatically assigns a 1-star rating to a song after you manually skip it a configurable number of consecutive times. Enable it and set the skip threshold in Settings → Ratings. The same settings panel lets you set a minimum star rating for Random Mix and Random Albums, so only songs, albums, or artists above a certain rating are included in generated mixes.',
q40: 'What is the Folder Browser?',
a40: 'The Folder Browser (sidebar) lets you navigate your server\'s music directory tree using a Miller-column layout. Click a folder to drill into it; click a track or the play icon on a folder to play or enqueue its contents directly.',
q41: 'What is the Theme Scheduler?',
a41: 'Settings → Appearance → Auto-Switch Theme: define a day theme and a night theme with start times. Psysonic switches automatically at the configured hours. When the scheduler is active, a hint in the theme picker explains why manual theme selection has no immediate effect.',
q42: 'Can I resize the interface?',
a42: 'Yes. Settings → Appearance → Interface Scale lets you scale the entire UI between 80 % and 125 % without affecting your system font size.',
q43: 'Can I change the seekbar style?',
a43: 'Yes. Settings → Appearance → Seekbar Style offers 10 styles: Waveform, Line & Dot, Bar, Thick Bar, Segmented, Neon Glow, Pulse Wave, Particle Trail, Liquid Fill, and Retro Tape.',
q44: 'What is AutoEQ?',
a44: 'The 10-band EQ in Settings → Audio includes an AutoEQ lookup. Enter your headphone model and Psysonic fetches a correction profile from the AutoEQ database and applies it automatically to the equalizer bands.',
q45: 'What is Replay Gain?',
a45: 'Replay Gain normalizes track volume so loud and quiet albums play at a consistent level. Enable it in Settings → Audio → Replay Gain and choose Track mode (per-song normalization) or Album mode (preserves relative dynamics within an album).',
q46: 'What is the Hot Cache?',
a46: 'Hot Cache (Alpha, Settings → Library) preloads the next several tracks in your queue to disk so playback starts instantly with no buffering delay — especially useful on slow or remote servers. Psysonic keeps the current track and the next 5 in cache and evicts older entries when the size limit is reached. You can set the maximum cache size and a debounce delay to avoid unnecessary fetches when skipping quickly.',
q47: 'Can I cache a playlist for offline use?',
a47: 'Yes. Open any playlist and click the download icon in the playlist header. All tracks are downloaded in the background — progress is shown in the offline download indicator. Once fully cached, the icon changes to a red trash icon; clicking it removes the playlist from the offline cache.',
},
queue: {
title: 'Queue',
@@ -824,6 +859,7 @@ export const enTranslation = {
addSong: 'Add to playlist',
cacheOffline: 'Cache playlist offline',
offlineCached: 'Playlist cached',
removeOffline: 'Remove from offline cache',
offlineDownloading: 'Caching… ({{done}}/{{total}} albums)',
publicLabel: 'Public',
privateLabel: 'Private',
+36
View File
@@ -16,6 +16,7 @@ export const frTranslation = {
expand: 'Développer la barre latérale',
collapse: 'Réduire la barre latérale',
downloadingTracks: '{{n}} pistes en cache…',
cancelDownload: 'Annuler le téléchargement',
offlineLibrary: 'Bibliothèque hors ligne',
genres: 'Genres',
playlists: 'Playlists',
@@ -349,6 +350,18 @@ export const frTranslation = {
updaterAvailable: 'Mise à jour disponible',
updaterVersion: 'v{{version}} est disponible',
updaterWebsite: 'Site Web',
updaterModalTitle: 'Nouvelle version disponible',
updaterChangelog: 'Nouveautés',
updaterDownloadBtn: 'Télécharger maintenant',
updaterSkipBtn: 'Ignorer cette version',
updaterRemindBtn: 'Me rappeler plus tard',
updaterDone: 'Téléchargement terminé',
updaterShowFolder: 'Afficher dans le dossier',
updaterInstallHint: 'Fermez Psysonic et lancez le programme d\'installation manuellement.',
updaterAurHint: 'Installer la mise à jour via AUR :',
updaterErrorMsg: 'Échec du téléchargement',
updaterRetryBtn: 'Réessayer',
updaterOpenGitHub: 'Ouvrir sur GitHub',
},
settings: {
title: 'Paramètres',
@@ -665,6 +678,28 @@ export const frTranslation = {
a35: 'Ouvrez un album et cliquez sur l\'icône de téléchargement dans l\'en-tête de l\'album. Psysonic télécharge toutes les pistes en arrière-plan. La progression est affichée sur le bouton. Une fois en cache, l\'icône devient verte. Les albums mis en cache peuvent être consultés et supprimés dans la page Bibliothèque hors ligne (barre latérale).',
q36: 'Quelle quantité de stockage le cache hors ligne peut-il utiliser ?',
a36: 'Vous pouvez définir une taille de cache maximale dans Paramètres → Bibliothèque. Lorsque la limite est atteinte, une bannière d\'avertissement s\'affiche sur la page de l\'album. Vous pouvez supprimer des albums individuels dans la Bibliothèque hors ligne pour libérer de l\'espace.',
q37: 'Comment noter des morceaux, albums et artistes ?',
a37: 'Psysonic prend en charge les notes de 1 à 5 étoiles via l\'API OpenSubsonic (Navidrome ≥ 0.53 requis). Notez les morceaux dans la liste de pistes d\'un album ou d\'une playlist, via le menu contextuel ou directement dans la barre du lecteur. Les albums sont notés sur leur page de détail, les artistes sur leur page.',
q38: 'Puis-je supprimer ou modifier une note ?',
a38: 'Oui. Cliquer à nouveau sur l\'étoile active supprime entièrement la note — un second clic sur la même étoile l\'efface. Pour modifier une note, cliquez simplement sur une étoile différente.',
q39: 'Qu\'est-ce que Skip-to-1★ et le filtre de notes ?',
a39: 'Skip-to-1★ attribue automatiquement une note d\'une étoile à un morceau après un certain nombre de sauts consécutifs. Activez-le dans Paramètres → Notes. Vous pouvez également y définir une note minimale pour les mix aléatoires.',
q40: 'Qu\'est-ce que le Navigateur de dossiers ?',
a40: 'Le Navigateur de dossiers (barre latérale) permet de parcourir l\'arborescence musicale du serveur en colonnes Miller. Cliquez sur un dossier pour l\'explorer ; utilisez l\'icône lecture pour jouer ou ajouter son contenu à la file.',
q41: 'Qu\'est-ce que le planificateur de thème ?',
a41: 'Paramètres → Apparence → Changer de thème automatiquement : définissez un thème de jour et un thème de nuit avec des heures de début. Psysonic bascule automatiquement à l\'heure configurée.',
q42: 'Puis-je redimensionner l\'interface ?',
a42: 'Oui. Paramètres → Apparence → Échelle de l\'interface permet de régler l\'interface entre 80 % et 125 %.',
q43: 'Puis-je changer le style de la barre de progression ?',
a43: 'Oui. Paramètres → Apparence → Style de la barre de progression offre 10 styles : Waveform, Ligne & Point, Barre, Barre épaisse, Segmenté, Neon Glow, Pulse Wave, Particle Trail, Liquid Fill et Retro Tape.',
q44: 'Qu\'est-ce qu\'AutoEQ ?',
a44: 'L\'égaliseur 10 bandes dans Paramètres → Audio comprend une recherche AutoEQ. Saisissez le modèle de votre casque pour charger automatiquement le profil de correction.',
q45: 'Qu\'est-ce que le Replay Gain ?',
a45: 'Le Replay Gain normalise le volume afin que les albums forts et doux soient lus à un niveau cohérent. Activez-le dans Paramètres → Audio → Replay Gain ; mode Piste ou Album.',
q46: 'Qu\'est-ce que le Hot Cache ?',
a46: 'Le Hot Cache (Alpha, Paramètres → Bibliothèque) précharge les prochains morceaux de la file sur le disque pour une lecture instantanée. Psysonic conserve le morceau actuel et les 5 suivants et évince les anciens quand la limite est atteinte.',
q47: 'Puis-je mettre en cache une playlist hors ligne ?',
a47: 'Oui. Dans les détails d\'une playlist, cliquez sur l\'icône de téléchargement. Une fois entièrement mis en cache, l\'icône se transforme en corbeille rouge ; cliquer dessus supprime la playlist du cache hors ligne.',
},
queue: {
title: 'File d\'attente',
@@ -821,6 +856,7 @@ export const frTranslation = {
addSong: 'Ajouter à la playlist',
cacheOffline: 'Mettre la playlist hors ligne',
offlineCached: 'Playlist en cache',
removeOffline: 'Retirer du cache hors ligne',
offlineDownloading: 'En cache… ({{done}}/{{total}} albums)',
publicLabel: 'Publique',
privateLabel: 'Privée',
+36
View File
@@ -16,6 +16,7 @@ export const nbTranslation = {
expand: 'Utvid sidefelt',
collapse: 'Skjul sidefelt',
downloadingTracks: 'Bufre {{n}} spor…',
cancelDownload: 'Avbryt nedlasting',
offlineLibrary: 'Frakoblet bibliotek',
genres: 'Sjangere',
playlists: 'Spillelister',
@@ -349,6 +350,18 @@ export const nbTranslation = {
updaterAvailable: 'Ny versjon er tilgjengelig',
updaterVersion: 'v{{version}} er tilgjengelig',
updaterWebsite: 'Nettsted',
updaterModalTitle: 'Ny versjon tilgjengelig',
updaterChangelog: 'Hva er nytt',
updaterDownloadBtn: 'Last ned nå',
updaterSkipBtn: 'Hopp over denne versjonen',
updaterRemindBtn: 'Påminn meg senere',
updaterDone: 'Nedlasting fullført',
updaterShowFolder: 'Vis i mappe',
updaterInstallHint: 'Lukk Psysonic og kjør installasjonsprogrammet manuelt.',
updaterAurHint: 'Installer oppdateringen via AUR:',
updaterErrorMsg: 'Nedlasting mislyktes',
updaterRetryBtn: 'Prøv igjen',
updaterOpenGitHub: 'Åpne på GitHub',
},
settings: {
title: 'Innstillinger',
@@ -664,6 +677,28 @@ export const nbTranslation = {
a35: 'Åpne et hvilket som helst album og klikk på nedlastingsikonet i albumoverskriften. Psysonic laster ned alle spor i bakgrunnen. Fremdrift vises på knappen. Når bufren er lagret, blir ikonet grønt. Du kan vise og fjerne bufrede album på siden Offline bibliotek (sidefelt).',
q36: 'Hvor mye lagringsplass kan frakoblet mellomlagring bruke?',
a36: 'Du kan angi en maksimal mellomlagringsstørrelse i Innstillinger → Bibliotek. Når grensen er nådd, vises et advarselsbanner på albumsiden. Du kan slette individuelle album fra frakoblet bibliotek for å frigjøre plass.',
q37: 'Hvordan vurderer jeg sanger, album og artister?',
a37: 'Psysonic støtter 15 stjernevurderinger via OpenSubsonic API (krever Navidrome ≥ 0.53). Vurder sanger i sporlistene, via høyreklikk-menyen eller i spillerlinjen. Album vurderes på detaljsiden, artister på artistsiden.',
q38: 'Kan jeg fjerne eller endre en vurdering?',
a38: 'Ja. Klikk på den aktive stjernen igjen for å slette vurderingen — et andre klikk på samme stjerne fjerner den. Klikk på en annen stjerne for å endre vurderingen.',
q39: 'Hva er Skip-to-1★ og vurderingsfilter?',
a39: 'Skip-to-1★ tildeler automatisk en 1-stjernevurdering etter et visst antall påfølgende manuelle hopp. Aktiver det i Innstillinger → Vurderinger. Der kan du også angi minimum stjerner for tilfeldige mikser.',
q40: 'Hva er mappebrowseren?',
a40: 'Mappebrowseren (sidepanel) lar deg navigere i serverens musikkmappe med Miller-kolonner. Klikk på en mappe for å utforske innholdet; bruk avspillingsikonen for å spille eller legge til i køen.',
q41: 'Hva er temaplanleggeren?',
a41: 'Innstillinger → Utseende → Bytt tema automatisk: angi et dagstema og et nattstema med starttider. Psysonic bytter automatisk på de angitte tidspunktene.',
q42: 'Kan jeg skalere grensesnittet?',
a42: 'Ja. Innstillinger → Utseende → Grensesnittskala lar deg skalere hele grensesnittet mellom 80 % og 125 %.',
q43: 'Kan jeg endre søkelinjesstilen?',
a43: 'Ja. Innstillinger → Utseende → Søkelinjestil tilbyr 10 stiler: Bølgeform, Linje & Punkt, Stolpe, Tykk stolpe, Segmentert, Neon Glow, Pulsbølge, Partikkelspor, Væskefylling og Retro Tape.',
q44: 'Hva er AutoEQ?',
a44: '10-bånds equalizer i Innstillinger → Lyd inkluderer AutoEQ-oppslag. Skriv inn hodetelefon-modellen for å laste inn en korreksjonsprofil automatisk.',
q45: 'Hva er Replay Gain?',
a45: 'Replay Gain normaliserer volumet slik at høye og stille album spilles av på et konsistent nivå. Aktiver det i Innstillinger → Lyd → Replay Gain; velg modus Spor eller Album.',
q46: 'Hva er hurtigbufferen?',
a46: 'Hurtigbuffer (Alpha, Innstillinger → Bibliotek) forhåndslaster de neste sporene i køen til disk for umiddelbar avspilling. Psysonic beholder gjeldende spor og de neste 5 og fjerner eldre innslag når grensen nås.',
q47: 'Kan jeg mellomlagre en spilleliste frakoblet?',
a47: 'Ja. Åpne spillelistedetaljene og klikk på nedlastingsikonen. Når alle spor er mellomlagret, endres ikonet til en rød søppelbøtte; klikk på den for å fjerne spillelisten fra frakoblet hurtigbuffer.',
},
queue: {
title: 'Kø',
@@ -820,6 +855,7 @@ export const nbTranslation = {
addSong: 'Legg til i spilleliste',
cacheOffline: 'Bufre spilleliste offline',
offlineCached: 'Spilleliste bufret',
removeOffline: 'Fjern fra offline-buffer',
offlineDownloading: 'Bufre… ({{done}}/{{total}} album)',
publicLabel: 'Offentlig',
privateLabel: 'Privat',
+36
View File
@@ -16,6 +16,7 @@ export const nlTranslation = {
expand: 'Zijbalk uitklappen',
collapse: 'Zijbalk inklappen',
downloadingTracks: '{{n}} nummers worden gecached…',
cancelDownload: 'Download annuleren',
offlineLibrary: 'Offline bibliotheek',
genres: 'Genres',
playlists: 'Playlists',
@@ -349,6 +350,18 @@ export const nlTranslation = {
updaterAvailable: 'Update beschikbaar',
updaterVersion: 'v{{version}} beschikbaar',
updaterWebsite: 'Website',
updaterModalTitle: 'Nieuwe versie beschikbaar',
updaterChangelog: 'Wat is er nieuw',
updaterDownloadBtn: 'Nu downloaden',
updaterSkipBtn: 'Deze versie overslaan',
updaterRemindBtn: 'Later herinneren',
updaterDone: 'Download voltooid',
updaterShowFolder: 'Tonen in map',
updaterInstallHint: 'Sluit Psysonic en voer het installatieprogramma handmatig uit.',
updaterAurHint: 'Update installeren via AUR:',
updaterErrorMsg: 'Downloaden mislukt',
updaterRetryBtn: 'Opnieuw proberen',
updaterOpenGitHub: 'Openen op GitHub',
},
settings: {
title: 'Instellingen',
@@ -665,6 +678,28 @@ export const nlTranslation = {
a35: 'Open een album en klik op het downloadpictogram in de albumkoptekst. Psysonic downloadt alle nummers op de achtergrond. De voortgang wordt op de knop weergegeven. Na het cachen wordt het pictogram groen. Gecachte albums zijn te bekijken en verwijderen via de Offline bibliotheek (zijbalk).',
q36: 'Hoeveel opslagruimte mag de offlinecache gebruiken?',
a36: 'Je kunt een maximale cachegrootte instellen via Instellingen → Bibliotheek. Als de limiet is bereikt, verschijnt er een waarschuwingsbanner op de albumpagina. Je kunt afzonderlijke albums verwijderen in de Offline bibliotheek om ruimte vrij te maken.',
q37: 'Hoe beoordeel ik nummers, albums en artiesten?',
a37: 'Psysonic ondersteunt 15 sterrenwaarderingen via de OpenSubsonic API (vereist Navidrome ≥ 0.53). Beoordeel nummers in de tracklist van een album of afspeellijst, via het rechtsklikmenu of in de spelersbalk. Albums worden beoordeeld op hun detailpagina, artiesten op hun artiestenpagina.',
q38: 'Kan ik een beoordeling verwijderen of wijzigen?',
a38: 'Ja. Klik opnieuw op de actieve ster om de beoordeling volledig te verwijderen — een tweede klik op dezelfde ster wist hem. Klik op een andere ster om de beoordeling te wijzigen.',
q39: 'Wat is Skip-to-1★ en het beoordelingsfilter?',
a39: 'Skip-to-1★ kent automatisch een 1-sterrenbeoordeling toe na een bepaald aantal opeenvolgende skips. Activeer het in Instellingen → Beoordelingen. Stel daar ook een minimale sterrenbeoordeling in voor willekeurige mixen.',
q40: 'Wat is de Mappenverkenner?',
a40: 'De Mappenverkenner (zijbalk) laat je de muziekmap van de server navigeren via Miller-kolommen. Klik op een map om de inhoud te bekijken; gebruik het afspeelpictogram om de inhoud direct af te spelen of toe te voegen aan de wachtrij.',
q41: 'Wat is de themasplanner?',
a41: 'Instellingen → Uiterlijk → Thema automatisch wisselen: stel een dagthema en een nachtthema in met starttijden. Psysonic wisselt automatisch op de ingestelde tijden.',
q42: 'Kan ik de interface schalen?',
a42: 'Ja. Instellingen → Uiterlijk → Interfaceschaal laat je de volledige UI schalen tussen 80 % en 125 %.',
q43: 'Kan ik de zoekbalkstijl wijzigen?',
a43: 'Ja. Instellingen → Uiterlijk → Zoekbalkstijl biedt 10 stijlen: Golfvorm, Lijn & Punt, Balk, Dikke balk, Gesegmenteerd, Neon Glow, Pulsgolf, Partikelspoor, Vloeistofvulling en Retro Tape.',
q44: 'Wat is AutoEQ?',
a44: 'De 10-bands equalizer in Instellingen → Audio bevat een AutoEQ-zoekopdracht. Voer je hoofdtelefoonmodel in om automatisch een correctieprofiel te laden.',
q45: 'Wat is Replay Gain?',
a45: 'Replay Gain normaliseert het volume zodat harde en stille albums op een consistent niveau worden afgespeeld. Activeer het in Instellingen → Audio → Replay Gain; kies modus Track of Album.',
q46: 'Wat is de Hot Cache?',
a46: 'De Hot Cache (Alpha, Instellingen → Bibliotheek) laadt de volgende nummers in de wachtrij vooraf naar de schijf voor directe weergave. Psysonic bewaart het huidige nummer en de volgende 5 en verwijdert oudere items wanneer de limiet is bereikt.',
q47: 'Kan ik een afspeellijst offline cachen?',
a47: 'Ja. Open de afspeellijstdetails en klik op het downloadpictogram. Zodra alle tracks zijn gecached, verandert het pictogram in een rode prullenbak; klik erop om de afspeellijst uit de offlinecache te verwijderen.',
},
queue: {
title: 'Wachtrij',
@@ -821,6 +856,7 @@ export const nlTranslation = {
addSong: 'Toevoegen aan playlist',
cacheOffline: 'Playlist offline opslaan',
offlineCached: 'Playlist gecached',
removeOffline: 'Verwijder uit offline cache',
offlineDownloading: 'Cachen… ({{done}}/{{total}} albums)',
publicLabel: 'Openbaar',
privateLabel: 'Privé',
+38
View File
@@ -17,6 +17,7 @@ export const ruTranslation = {
expand: 'Развернуть боковую панель',
collapse: 'Свернуть боковую панель',
downloadingTracks: 'Кэширование {{n}} треков…',
cancelDownload: 'Отменить загрузку',
offlineLibrary: 'Офлайн-библиотека',
genres: 'Жанры',
playlists: 'Плейлисты',
@@ -363,6 +364,18 @@ export const ruTranslation = {
updaterAvailable: 'Доступно обновление',
updaterVersion: 'Версия {{version}} доступна',
updaterWebsite: 'Сайт',
updaterModalTitle: 'Доступна новая версия',
updaterChangelog: 'Что нового',
updaterDownloadBtn: 'Скачать сейчас',
updaterSkipBtn: 'Пропустить эту версию',
updaterRemindBtn: 'Напомнить позже',
updaterDone: 'Загрузка завершена',
updaterShowFolder: 'Показать в папке',
updaterInstallHint: 'Закройте Psysonic и запустите установщик вручную.',
updaterAurHint: 'Установить обновление через AUR:',
updaterErrorMsg: 'Ошибка загрузки',
updaterRetryBtn: 'Повторить',
updaterOpenGitHub: 'Открыть на GitHub',
},
settings: {
title: 'Настройки',
@@ -483,6 +496,8 @@ export const ruTranslation = {
nowPlayingEnabled: 'Показывать в «Сейчас играет»',
nowPlayingEnabledDesc:
'Отправлять на сервер, что вы сейчас слушаете. Отключите, чтобы не делиться этим.',
lyricsServerFirst: 'Предпочитать серверные тексты',
lyricsServerFirstDesc: 'Проверять тексты песен, предоставленные сервером (встроенные теги, sidecar-файлы) перед запросом LRCLIB. Отключите, чтобы использовать LRCLIB сначала.',
downloadsTitle: 'Экспорт ZIP и архивы',
downloadsFolderDesc: 'Куда сохранять альбомы в ZIP архиве на диск.',
downloadsDefault: 'Папка «Загрузки» по умолчанию',
@@ -714,6 +729,28 @@ export const ruTranslation = {
q36: 'Сколько места занимает офлайн?',
a36:
'Лимит задаётся в настройках. При переполнении на странице альбома появится предупреждение; удалить можно из офлайн-библиотеки.',
q37: 'Как ставить оценки трекам, альбомам и исполнителям?',
a37: 'Psysonic поддерживает оценки от 1 до 5 звёзд через OpenSubsonic API (требует Navidrome ≥ 0.53). Треки оцениваются в списке треков альбома или плейлиста, в контекстном меню или прямо в панели плеера. Альбомы — на странице альбома, исполнители — на странице исполнителя.',
q38: 'Можно ли удалить или изменить оценку?',
a38: 'Да. Повторный клик по активной звезде полностью удаляет оценку — второй клик по той же звезде её стирает. Для изменения оценки просто нажмите другую звезду.',
q39: 'Что такое Skip-to-1★ и фильтр по рейтингу?',
a39: 'Skip-to-1★ автоматически присваивает оценку 1 звезда после заданного числа последовательных пропусков. Включается в Настройки → Рейтинги. Там же задаётся минимальный рейтинг для случайных миксов.',
q40: 'Что такое браузер папок?',
a40: 'Браузер папок (боковая панель) позволяет навигировать по музыкальному каталогу сервера в колонках Миллера. Клик по папке открывает содержимое; иконка воспроизведения запускает или добавляет в очередь.',
q41: 'Что такое планировщик тем?',
a41: 'Настройки → Внешний вид → Авто-смена темы: задайте дневную и ночную тему со временем начала. Psysonic переключается автоматически в указанное время.',
q42: 'Можно ли масштабировать интерфейс?',
a42: 'Да. Настройки → Внешний вид → Масштаб интерфейса позволяет масштабировать весь UI от 80 % до 125 %.',
q43: 'Можно ли изменить стиль seekbar?',
a43: 'Да. Настройки → Внешний вид → Стиль seekbar предлагает 10 стилей: Осциллограмма, Линия и точка, Полоса, Толстая полоса, Сегментированная, Неоновое свечение, Пульсовая волна, Частицы, Жидкое заполнение и Ретро кассета.',
q44: 'Что такое AutoEQ?',
a44: '10-полосный эквалайзер в Настройки → Аудио включает поиск AutoEQ. Введите модель наушников — Psysonic автоматически загрузит и применит профиль коррекции.',
q45: 'Что такое Replay Gain?',
a45: 'Replay Gain нормализует громкость, чтобы громкие и тихие альбомы воспроизводились на одинаковом уровне. Включается в Настройки → Аудио → Replay Gain; режим трека или альбома.',
q46: 'Что такое горячий кэш?',
a46: 'Горячий кэш (Alpha, Настройки → Библиотека) предзагружает следующие треки очереди на диск для мгновенного воспроизведения. Psysonic хранит текущий трек и следующие 5, вытесняя старые записи при достижении лимита.',
q47: 'Можно ли кэшировать плейлист для офлайн?',
a47: 'Да. Откройте детали плейлиста и нажмите иконку загрузки. После полного кэширования иконка сменяется на красную корзину; нажмите её, чтобы удалить плейлист из офлайн-кэша.',
},
queue: {
title: 'Очередь',
@@ -878,6 +915,7 @@ export const ruTranslation = {
addSong: 'В плейлист',
cacheOffline: 'Сохранить плейлист офлайн',
offlineCached: 'Плейлист сохранён',
removeOffline: 'Удалить из офлайн-кэша',
offlineDownloading: 'Кэширование… ({{done}} из {{total}} альбомов)',
publicLabel: 'Публичный',
privateLabel: 'Личный',
+36
View File
@@ -16,6 +16,7 @@ export const zhTranslation = {
expand: '展开侧边栏',
collapse: '收起侧边栏',
downloadingTracks: '正在缓存 {{n}} 首歌曲…',
cancelDownload: '取消下载',
offlineLibrary: '离线音乐库',
genres: '流派',
playlists: '播放列表',
@@ -345,6 +346,18 @@ export const zhTranslation = {
updaterAvailable: '有可用更新',
updaterVersion: 'v{{version}} 已发布',
updaterWebsite: '官网',
updaterModalTitle: '有新版本可用',
updaterChangelog: '更新内容',
updaterDownloadBtn: '立即下载',
updaterSkipBtn: '跳过此版本',
updaterRemindBtn: '稍后提醒',
updaterDone: '下载完成',
updaterShowFolder: '在文件夹中显示',
updaterInstallHint: '请关闭 Psysonic 并手动运行安装程序。',
updaterAurHint: '通过 AUR 安装更新:',
updaterErrorMsg: '下载失败',
updaterRetryBtn: '重试',
updaterOpenGitHub: '在 GitHub 上打开',
},
settings: {
title: '设置',
@@ -661,6 +674,28 @@ export const zhTranslation = {
a35: '打开任意专辑并点击专辑标题栏的下载图标。Psysonic 会在后台下载所有曲目。按钮上会显示进度。缓存完成后,图标变为绿色。您可以在离线音乐库页面(侧边栏)查看和移除缓存的专辑。',
q36: '离线缓存可以使用多少存储空间?',
a36: '您可以在 设置 → 音乐库 中设置最大缓存大小。达到限制时,专辑页面会显示警告横幅。您可以从离线音乐库中删除单个专辑以释放空间。',
q37: '如何对歌曲、专辑和艺术家评分?',
a37: 'Psysonic 通过 OpenSubsonic API 支持 15 星评分(需要 Navidrome ≥ 0.53)。可在专辑或播放列表曲目列表、右键菜单或播放器栏中对歌曲评分。专辑在详情页评分,艺术家在艺术家页评分。',
q38: '可以删除或更改评分吗?',
a38: '可以。再次点击当前激活的星星即可完全删除评分——第二次点击同一颗星即可清除。点击其他星星可更改评分。',
q39: '什么是 Skip-to-1★ 和评分过滤器?',
a39: 'Skip-to-1★ 会在歌曲被连续手动跳过一定次数后自动赋予 1 星评分。在 设置 → 评分 中启用并设置阈值。同样可在此设置随机混音的最低星级过滤条件。',
q40: '什么是文件夹浏览器?',
a40: '文件夹浏览器(侧边栏)使用 Miller 列布局浏览服务器音乐目录。点击文件夹查看内容;点击播放图标直接播放或添加到队列。',
q41: '什么是主题调度器?',
a41: '设置 → 外观 → 自动切换主题:设置日间主题和夜间主题及开始时间,Psysonic 将在指定时间自动切换主题。',
q42: '可以调整界面缩放吗?',
a42: '可以。设置 → 外观 → 界面缩放 可将整个界面缩放至 80%–125%。',
q43: '可以更改进度条样式吗?',
a43: '可以。设置 → 外观 → 进度条样式 提供 10 种样式:波形、线条与点、条形、粗条形、分段、霓虹辉光、脉冲波、粒子轨迹、液体填充和复古磁带。',
q44: '什么是 AutoEQ',
a44: '设置 → 音频 中的 10 频段均衡器包含 AutoEQ 查找功能。输入耳机型号即可自动加载校正配置文件。',
q45: '什么是 Replay Gain',
a45: 'Replay Gain 标准化音量,使响亮和安静的专辑以一致的音量播放。在 设置 → 音频 → Replay Gain 中启用;选择曲目模式或专辑模式。',
q46: '什么是热缓存?',
a46: '热缓存(Alpha,设置 → 音乐库)将队列中后续曲目预加载到磁盘,实现即时播放,对于慢速或远程服务器尤为有用。Psysonic 保留当前曲目和后续 5 首,达到大小限制时淘汰旧条目。',
q47: '可以将播放列表缓存到离线吗?',
a47: '可以。在播放列表详情中点击下载图标,所有曲目将在后台下载。完全缓存后图标变为红色垃圾桶;再次点击即可从离线缓存中删除该播放列表。',
},
queue: {
title: '队列',
@@ -817,6 +852,7 @@ export const zhTranslation = {
addSong: '添加到播放列表',
cacheOffline: '离线缓存播放列表',
offlineCached: '播放列表已缓存',
removeOffline: '从离线缓存中移除',
offlineDownloading: '正在缓存… ({{done}}/{{total}} 张专辑)',
publicLabel: '公开',
privateLabel: '私有',
+49 -61
View File
@@ -6,8 +6,9 @@ import { usePlayerStore, songToTrack } from '../store/playerStore';
import { useAuthStore } from '../store/authStore';
import { useDownloadModalStore } from '../store/downloadModalStore';
import { useOfflineStore } from '../store/offlineStore';
import { writeFile } from '@tauri-apps/plugin-fs';
import { useOfflineJobStore } from '../store/offlineJobStore';
import { join } from '@tauri-apps/api/path';
import { useZipDownloadStore } from '../store/zipDownloadStore';
import AlbumCard from '../components/AlbumCard';
import AlbumHeader from '../components/AlbumHeader';
import AlbumTrackList from '../components/AlbumTrackList';
@@ -44,15 +45,12 @@ export default function AlbumDetail() {
const [bio, setBio] = useState<string | null>(null);
const [bioOpen, setBioOpen] = useState(false);
const [loading, setLoading] = useState(true);
const [downloadProgress, setDownloadProgress] = useState<number | null>(null);
const [isStarred, setIsStarred] = useState(false);
const [starredSongs, setStarredSongs] = useState<Set<string>>(new Set());
const [offlineStorageFull, setOfflineStorageFull] = useState(false);
const { downloadAlbum, deleteAlbum } = useOfflineStore();
const offlineTracks = useOfflineStore(s => s.tracks);
const offlineAlbums = useOfflineStore(s => s.albums);
const offlineJobs = useOfflineStore(s => s.jobs);
const downloadAlbum = useOfflineStore(s => s.downloadAlbum);
const deleteAlbum = useOfflineStore(s => s.deleteAlbum);
const serverId = auth.activeServerId ?? '';
const entityRatingSupportByServer = useAuthStore(s => s.entityRatingSupportByServer);
const setEntityRatingSupport = useAuthStore(s => s.setEntityRatingSupport);
@@ -60,22 +58,32 @@ export default function AlbumDetail() {
const [albumEntityRating, setAlbumEntityRating] = useState(0);
const offlineStatus: 'none' | 'downloading' | 'cached' = (() => {
if (!album) return 'none';
const meta = offlineAlbums[`${serverId}:${album.album.id}`];
const isDownloaded = meta && meta.trackIds.length > 0 && meta.trackIds.every(tid => !!offlineTracks[`${serverId}:${tid}`]);
if (isDownloaded) return 'cached';
const isDownloading = offlineJobs.some(j => j.albumId === album.album.id && (j.status === 'queued' || j.status === 'downloading'));
return isDownloading ? 'downloading' : 'none';
})();
// Derive a stable albumId for the selectors below (empty string when not yet loaded).
const albumId = album?.album.id ?? '';
const offlineProgress = (() => {
if (!album) return null;
const albumJobs = offlineJobs.filter(j => j.albumId === album.album.id);
if (albumJobs.length === 0) return null;
const done = albumJobs.filter(j => j.status === 'done' || j.status === 'error').length;
return { done, total: albumJobs.length };
})();
// Selectors return primitives so Zustand only triggers a re-render when the VALUE
// actually changes — not on every `jobs` array mutation during batch downloads.
const offlineStatus = useOfflineStore((s): 'none' | 'downloading' | 'cached' => {
if (!albumId) return 'none';
const meta = s.albums[`${serverId}:${albumId}`];
const isDownloaded = meta && meta.trackIds.length > 0 && meta.trackIds.every(tid => !!s.tracks[`${serverId}:${tid}`]);
return isDownloaded ? 'cached' : 'none';
});
const isOfflineDownloading = useOfflineJobStore(s =>
!!albumId && s.jobs.some(j => j.albumId === albumId && (j.status === 'queued' || j.status === 'downloading'))
);
const offlineProgressDone = useOfflineJobStore(s => {
if (!albumId) return 0;
return s.jobs.filter(j => j.albumId === albumId && (j.status === 'done' || j.status === 'error')).length;
});
const offlineProgressTotal = useOfflineJobStore(s => {
if (!albumId) return 0;
return s.jobs.filter(j => j.albumId === albumId).length;
});
const resolvedOfflineStatus = isOfflineDownloading ? 'downloading' : offlineStatus;
const offlineProgress = offlineProgressTotal > 0
? { done: offlineProgressDone, total: offlineProgressTotal }
: null;
useEffect(() => {
if (!id) return;
@@ -181,45 +189,22 @@ const handleEnqueueAll = () => {
if (!album) return;
const { name, id: albumId } = album.album;
// Ask for folder before starting download if not already set
const folder = auth.downloadFolder || await requestDownloadFolder();
if (!folder) return;
setDownloadProgress(0);
const filename = `${sanitizeFilename(name)}.zip`;
const destPath = await join(folder, filename);
const url = buildDownloadUrl(albumId);
const downloadId = crypto.randomUUID();
const { start, complete, fail } = useZipDownloadStore.getState();
start(downloadId, filename);
try {
const url = buildDownloadUrl(albumId);
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const contentLength = response.headers.get('Content-Length');
const total = contentLength ? parseInt(contentLength, 10) : 0;
const chunks: Uint8Array<ArrayBuffer>[] = [];
if (total && response.body) {
const reader = response.body.getReader();
let received = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
received += value.length;
setDownloadProgress(Math.round((received / total) * 100));
}
} else {
const buffer = await response.arrayBuffer() as ArrayBuffer;
chunks.push(new Uint8Array(buffer));
setDownloadProgress(100);
}
const blob = new Blob(chunks);
const buffer = await blob.arrayBuffer();
const path = await join(folder, `${sanitizeFilename(name)}.zip`);
await writeFile(path, new Uint8Array(buffer));
await invoke('download_zip', { id: downloadId, url, destPath });
complete(downloadId);
} catch (e) {
console.error('Download failed:', e);
setDownloadProgress(null);
} finally {
setTimeout(() => setDownloadProgress(null), 60000);
fail(downloadId);
console.error('ZIP download failed:', e);
}
};
@@ -282,6 +267,12 @@ const handleEnqueueAll = () => {
const coverKey = useMemo(() => album?.album.coverArt ? coverArtCacheKey(album.album.coverArt, 400) : '', [album?.album.coverArt]);
const resolvedCoverUrl = useCachedUrl(coverUrl, coverKey);
// Must be before early returns — hooks must be called unconditionally.
const mergedStarredSongs = useMemo(() => new Set([
...[...starredSongs].filter(id => starredOverrides[id] !== false),
...Object.entries(starredOverrides).filter(([, v]) => v).map(([k]) => k),
]), [starredSongs, starredOverrides]);
if (loading) return <div className="loading-center"><div className="spinner" /></div>;
if (!album) return <div className="empty-state">{t('albumDetail.notFound')}</div>;
@@ -297,7 +288,7 @@ const handleEnqueueAll = () => {
coverKey={coverKey}
resolvedCoverUrl={resolvedCoverUrl}
isStarred={isStarred}
downloadProgress={downloadProgress}
downloadProgress={null}
bio={bio}
bioOpen={bioOpen}
onToggleStar={toggleStar}
@@ -306,7 +297,7 @@ const handleEnqueueAll = () => {
onEnqueueAll={handleEnqueueAll}
onBio={handleBio}
onCloseBio={() => setBioOpen(false)}
offlineStatus={offlineStatus}
offlineStatus={resolvedOfflineStatus}
offlineProgress={offlineProgress}
onCacheOffline={handleCacheOffline}
onRemoveOffline={handleRemoveOffline}
@@ -334,10 +325,7 @@ const handleEnqueueAll = () => {
isPlaying={isPlaying}
ratings={ratings}
userRatingOverrides={userRatingOverrides}
starredSongs={new Set([
...[...starredSongs].filter(id => starredOverrides[id] !== false),
...Object.entries(starredOverrides).filter(([, v]) => v).map(([k]) => k),
])}
starredSongs={mergedStarredSongs}
onPlaySong={handlePlaySong}
onRate={handleRate}
onToggleSongStar={toggleSongStar}
+18 -21
View File
@@ -6,9 +6,10 @@ import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { useOfflineStore } from '../store/offlineStore';
import { useDownloadModalStore } from '../store/downloadModalStore';
import { writeFile } from '@tauri-apps/plugin-fs';
import { invoke } from '@tauri-apps/api/core';
import { join } from '@tauri-apps/api/path';
import { showToast } from '../utils/toast';
import { useZipDownloadStore } from '../store/zipDownloadStore';
import { X, CheckSquare2, Download, HardDriveDownload } from 'lucide-react';
type SortType = 'alphabeticalByName' | 'alphabeticalByArtist';
@@ -31,7 +32,7 @@ export default function Albums() {
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const auth = useAuthStore();
const serverId = useAuthStore(s => s.activeServerId ?? '');
const { downloadAlbum } = useOfflineStore();
const downloadAlbum = useOfflineStore(s => s.downloadAlbum);
const requestDownloadFolder = useDownloadModalStore(s => s.requestFolder);
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
@@ -72,26 +73,23 @@ export default function Albums() {
if (selectedAlbums.length === 0) return;
const folder = auth.downloadFolder || await requestDownloadFolder();
if (!folder) return;
let done = 0;
const { start, complete, fail } = useZipDownloadStore.getState();
clearSelection();
for (const album of selectedAlbums) {
showToast(t('albums.downloadingZip', { current: done + 1, total: selectedAlbums.length, name: album.name }), 8000, 'info');
const downloadId = crypto.randomUUID();
const filename = `${sanitizeFilename(album.name)}.zip`;
const destPath = await join(folder, filename);
const url = buildDownloadUrl(album.id);
start(downloadId, filename);
try {
const url = buildDownloadUrl(album.id);
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blob = await response.blob();
const buffer = await blob.arrayBuffer();
const path = await join(folder, `${sanitizeFilename(album.name)}.zip`);
await writeFile(path, new Uint8Array(buffer));
done++;
await invoke('download_zip', { id: downloadId, url, destPath });
complete(downloadId);
} catch (e) {
fail(downloadId);
console.error('ZIP download failed for', album.name, e);
showToast(t('albums.downloadZipFailed', { name: album.name }), 4000, 'error');
}
}
showToast(t('albums.downloadZipDone', { count: done }), 4000, 'info');
clearSelection();
};
const handleAddOffline = async () => {
@@ -220,7 +218,7 @@ export default function Albums() {
))}
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<span style={{ fontSize: 12, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>
<span style={{ fontSize: 14, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>
{t('albums.yearFilterLabel')}
</span>
<input
@@ -231,9 +229,9 @@ export default function Albums() {
placeholder={t('albums.yearFrom')}
value={yearFrom}
onChange={e => setYearFrom(e.target.value)}
style={{ width: 68, padding: '4px 6px', fontSize: 12 }}
style={{ width: 76, padding: 'var(--space-2) var(--space-2)' }}
/>
<span style={{ fontSize: 12, color: 'var(--text-muted)' }}></span>
<span style={{ fontSize: 14, color: 'var(--text-muted)' }}></span>
<input
className="input"
type="number"
@@ -242,16 +240,15 @@ export default function Albums() {
placeholder={t('albums.yearTo')}
value={yearTo}
onChange={e => setYearTo(e.target.value)}
style={{ width: 68, padding: '4px 6px', fontSize: 12 }}
style={{ width: 76, padding: 'var(--space-2) var(--space-2)' }}
/>
{yearActive && (
<button
className="btn btn-ghost"
onClick={clearYear}
data-tooltip={t('albums.yearFilterClear')}
style={{ padding: '4px 6px' }}
>
<X size={13} />
<X size={14} />
</button>
)}
</div>
+3 -1
View File
@@ -8,6 +8,7 @@ import { ArrowLeft, Users, ExternalLink, Heart, Play, Shuffle, Radio, HardDriveD
import { open } from '@tauri-apps/plugin-shell';
import { usePlayerStore, songToTrack } from '../store/playerStore';
import { useOfflineStore } from '../store/offlineStore';
import { useOfflineJobStore } from '../store/offlineJobStore';
import { useAuthStore } from '../store/authStore';
import { useTranslation } from 'react-i18next';
import { lastfmGetSimilarArtists, lastfmIsConfigured } from '../api/lastfm';
@@ -69,7 +70,8 @@ export default function ArtistDetail() {
const openContextMenu = usePlayerStore(state => state.openContextMenu);
const currentTrack = usePlayerStore(state => state.currentTrack);
const isPlaying = usePlayerStore(state => state.isPlaying);
const { downloadArtist, bulkProgress } = useOfflineStore();
const downloadArtist = useOfflineStore(s => s.downloadArtist);
const bulkProgress = useOfflineJobStore(s => s.bulkProgress);
const activeServerId = useAuthStore(s => s.activeServerId) ?? '';
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const entityRatingSupportByServer = useAuthStore(s => s.entityRatingSupportByServer);
+11
View File
@@ -54,6 +54,10 @@ export default function Help() {
items: [
{ q: t('help.q9'), a: t('help.a9') },
{ q: t('help.q10'), a: t('help.a10') },
{ q: t('help.q37'), a: t('help.a37') },
{ q: t('help.q38'), a: t('help.a38') },
{ q: t('help.q39'), a: t('help.a39') },
{ q: t('help.q40'), a: t('help.a40') },
{ q: t('help.q11'), a: t('help.a11') },
{ q: t('help.q25'), a: t('help.a25') },
],
@@ -63,10 +67,16 @@ export default function Help() {
title: t('help.s4'),
items: [
{ q: t('help.q12'), a: t('help.a12') },
{ q: t('help.q41'), a: t('help.a41') },
{ q: t('help.q42'), a: t('help.a42') },
{ q: t('help.q43'), a: t('help.a43') },
{ q: t('help.q13'), a: t('help.a13') },
{ q: t('help.q15'), a: t('help.a15') },
{ q: t('help.q31'), a: t('help.a31') },
{ q: t('help.q32'), a: t('help.a32') },
{ q: t('help.q44'), a: t('help.a44') },
{ q: t('help.q45'), a: t('help.a45') },
{ q: t('help.q46'), a: t('help.a46') },
],
},
{
@@ -92,6 +102,7 @@ export default function Help() {
items: [
{ q: t('help.q34'), a: t('help.a34') },
{ q: t('help.q35'), a: t('help.a35') },
{ q: t('help.q47'), a: t('help.a47') },
{ q: t('help.q36'), a: t('help.a36') },
],
},
+1 -1
View File
@@ -111,7 +111,7 @@ export default function Home() {
{isVisible('recent') && (
<AlbumRow
title={t('home.recent')}
titleLink="/albums"
titleLink="/new-releases"
albums={recent}
onLoadMore={() => loadMore('newest', recent, setRecent)}
moreText={t('home.loadMore')}
+13 -10
View File
@@ -7,9 +7,10 @@ import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { useOfflineStore } from '../store/offlineStore';
import { useDownloadModalStore } from '../store/downloadModalStore';
import { writeFile } from '@tauri-apps/plugin-fs';
import { invoke } from '@tauri-apps/api/core';
import { join } from '@tauri-apps/api/path';
import { showToast } from '../utils/toast';
import { useZipDownloadStore } from '../store/zipDownloadStore';
const PAGE_SIZE = 30;
@@ -29,7 +30,7 @@ export default function NewReleases() {
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const auth = useAuthStore();
const serverId = useAuthStore(s => s.activeServerId ?? '');
const { downloadAlbum } = useOfflineStore();
const downloadAlbum = useOfflineStore(s => s.downloadAlbum);
const requestDownloadFolder = useDownloadModalStore(s => s.requestFolder);
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
@@ -54,21 +55,23 @@ export default function NewReleases() {
if (selectedAlbums.length === 0) return;
const folder = auth.downloadFolder || await requestDownloadFolder();
if (!folder) return;
let done = 0;
const { start, complete, fail } = useZipDownloadStore.getState();
clearSelection();
for (const album of selectedAlbums) {
showToast(t('albums.downloadingZip', { current: done + 1, total: selectedAlbums.length, name: album.name }), 8000, 'info');
const downloadId = crypto.randomUUID();
const filename = `${sanitizeFilename(album.name)}.zip`;
const destPath = await join(folder, filename);
const url = buildDownloadUrl(album.id);
start(downloadId, filename);
try {
const blob = await fetch(buildDownloadUrl(album.id)).then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.blob(); });
const path = await join(folder, `${sanitizeFilename(album.name)}.zip`);
await writeFile(path, new Uint8Array(await blob.arrayBuffer()));
done++;
await invoke('download_zip', { id: downloadId, url, destPath });
complete(downloadId);
} catch (e) {
fail(downloadId);
console.error('ZIP download failed for', album.name, e);
showToast(t('albums.downloadZipFailed', { name: album.name }), 4000, 'error');
}
}
showToast(t('albums.downloadZipDone', { count: done }), 4000, 'info');
clearSelection();
};
const handleAddOffline = async () => {
+59 -55
View File
@@ -12,10 +12,12 @@ import { usePlayerStore, songToTrack } from '../store/playerStore';
import { useShallow } from 'zustand/react/shallow';
import { usePlaylistStore } from '../store/playlistStore';
import { useOfflineStore } from '../store/offlineStore';
import { useOfflineJobStore } from '../store/offlineJobStore';
import { useAuthStore } from '../store/authStore';
import { useDownloadModalStore } from '../store/downloadModalStore';
import { writeFile } from '@tauri-apps/plugin-fs';
import { invoke } from '@tauri-apps/api/core';
import { join } from '@tauri-apps/api/path';
import { useZipDownloadStore } from '../store/zipDownloadStore';
import { useDragDrop } from '../contexts/DragDropContext';
import CachedImage, { useCachedUrl } from '../components/CachedImage';
import { coverArtCacheKey, buildCoverArtUrl } from '../api/subsonic';
@@ -83,8 +85,24 @@ export default function PlaylistDetail() {
);
const touchPlaylist = usePlaylistStore((s) => s.touchPlaylist);
const { startDrag, isDragging } = useDragDrop();
const { downloadPlaylist, isAlbumDownloading, isAlbumDownloaded, getAlbumProgress } = useOfflineStore();
const downloadPlaylist = useOfflineStore(s => s.downloadPlaylist);
const deleteAlbum = useOfflineStore(s => s.deleteAlbum);
const activeServerId = useAuthStore(s => s.activeServerId) ?? '';
const isDownloading = useOfflineJobStore(s =>
!!id && s.jobs.some(j => j.albumId === id && (j.status === 'queued' || j.status === 'downloading'))
);
const isCached = useOfflineStore(s => {
if (!id) return false;
const meta = s.albums[`${activeServerId}:${id}`];
if (!meta || meta.trackIds.length === 0) return false;
return meta.trackIds.every(tid => !!s.tracks[`${activeServerId}:${tid}`]);
});
const offlineProgressDone = useOfflineJobStore(s => {
if (!id) return 0;
return s.jobs.filter(j => j.albumId === id && (j.status === 'done' || j.status === 'error')).length;
});
const offlineProgressTotal = useOfflineJobStore(s => (!id ? 0 : s.jobs.filter(j => j.albumId === id).length));
const offlineProgress = offlineProgressTotal > 0 ? { done: offlineProgressDone, total: offlineProgressTotal } : null;
const downloadFolder = useAuthStore(s => s.downloadFolder);
const setDownloadFolder = useAuthStore(s => s.setDownloadFolder);
const requestDownloadFolder = useDownloadModalStore(s => s.requestFolder);
@@ -100,7 +118,9 @@ export default function PlaylistDetail() {
const [hoveredSuggestionId, setHoveredSuggestionId] = useState<string | null>(null);
const [contextMenuSongId, setContextMenuSongId] = useState<string | null>(null);
const contextMenuOpen = usePlayerStore(s => s.contextMenu.isOpen);
const [downloadProgress, setDownloadProgress] = useState<number | null>(null);
const zipDownloads = useZipDownloadStore(s => s.downloads);
const [zipDownloadId, setZipDownloadId] = useState<string | null>(null);
const activeZip = zipDownloadId ? zipDownloads.find(d => d.id === zipDownloadId) : undefined;
// ── Bulk select ───────────────────────────────────────────────────
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
@@ -299,38 +319,21 @@ export default function PlaylistDetail() {
if (!playlist || !id) return;
const folder = downloadFolder || await requestDownloadFolder();
if (!folder) return;
setDownloadProgress(0);
const filename = `${sanitizeFilename(playlist.name)}.zip`;
const destPath = await join(folder, filename);
const url = buildDownloadUrl(id);
const downloadId = crypto.randomUUID();
const { start, complete, fail } = useZipDownloadStore.getState();
start(downloadId, filename);
setZipDownloadId(downloadId);
try {
const url = buildDownloadUrl(id);
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const contentLength = response.headers.get('Content-Length');
const total = contentLength ? parseInt(contentLength, 10) : 0;
const chunks: Uint8Array<ArrayBuffer>[] = [];
if (total && response.body) {
const reader = response.body.getReader();
let received = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
received += value.length;
setDownloadProgress(Math.round((received / total) * 100));
}
} else {
const buffer = await response.arrayBuffer() as ArrayBuffer;
chunks.push(new Uint8Array(buffer));
setDownloadProgress(100);
}
const blob = new Blob(chunks);
const buffer = await blob.arrayBuffer();
const path = await join(folder, `${sanitizeFilename(playlist.name)}.zip`);
await writeFile(path, new Uint8Array(buffer));
await invoke('download_zip', { id: downloadId, url, destPath });
complete(downloadId);
} catch (e) {
console.error('Download failed:', e);
setDownloadProgress(null);
} finally {
setTimeout(() => setDownloadProgress(null), 60000);
fail(downloadId);
console.error('ZIP download failed:', e);
}
};
@@ -587,33 +590,34 @@ export default function PlaylistDetail() {
>
<Search size={16} /> {t('playlists.addSongs')}
</button>
{songs.length > 0 && id && (() => {
const isDownloading = isAlbumDownloading(id);
const isCached = isAlbumDownloaded(id, activeServerId);
const progress = isDownloading ? getAlbumProgress(id) : null;
return (
<button
className="btn btn-ghost"
disabled={isDownloading}
onClick={() => { if (playlist) downloadPlaylist(id, playlist.name, playlist.coverArt, songs, activeServerId); }}
data-tooltip={isDownloading
? t('albumDetail.offlineDownloading', { n: progress?.done ?? 0, total: progress?.total ?? 0 })
: isCached ? t('playlists.offlineCached') : t('playlists.cacheOffline')}
>
{isDownloading
? <div className="spinner" style={{ width: 14, height: 14, borderTopColor: 'currentColor' }} />
: isCached ? <Check size={16} /> : <HardDriveDownload size={16} />}
</button>
);
})()}
{songs.length > 0 && id && (
<button
className={`btn btn-ghost${isCached ? ' btn-danger' : ''}`}
disabled={isDownloading}
onClick={() => {
if (isCached) {
deleteAlbum(id, activeServerId);
} else if (playlist) {
downloadPlaylist(id, playlist.name, playlist.coverArt, songs, activeServerId);
}
}}
data-tooltip={isDownloading
? t('albumDetail.offlineDownloading', { n: offlineProgress?.done ?? 0, total: offlineProgress?.total ?? 0 })
: isCached ? t('playlists.removeOffline') : t('playlists.cacheOffline')}
>
{isDownloading
? <div className="spinner" style={{ width: 14, height: 14, borderTopColor: 'currentColor' }} />
: isCached ? <Trash2 size={16} /> : <HardDriveDownload size={16} />}
</button>
)}
{songs.length > 0 && (
downloadProgress !== null ? (
activeZip && !activeZip.done && !activeZip.error ? (
<div className="download-progress-wrap">
<Download size={14} />
<div className="download-progress-bar">
<div className="download-progress-fill" style={{ width: `${downloadProgress}%` }} />
<div className="download-progress-fill" style={{ width: `${activeZip.total ? Math.round((activeZip.bytes / activeZip.total) * 100) : 0}%` }} />
</div>
<span className="download-progress-pct">{downloadProgress}%</span>
<span className="download-progress-pct">{activeZip.total ? Math.round((activeZip.bytes / activeZip.total) * 100) : '…'}%</span>
</div>
) : (
<button className="btn btn-ghost" onClick={handleDownload} data-tooltip={t('playlists.downloadZip')}>
+13 -10
View File
@@ -8,9 +8,10 @@ import { useAuthStore } from '../store/authStore';
import { filterAlbumsByMixRatings, getMixMinRatingsConfigFromAuth } from '../utils/mixRatingFilter';
import { useOfflineStore } from '../store/offlineStore';
import { useDownloadModalStore } from '../store/downloadModalStore';
import { writeFile } from '@tauri-apps/plugin-fs';
import { invoke } from '@tauri-apps/api/core';
import { join } from '@tauri-apps/api/path';
import { showToast } from '../utils/toast';
import { useZipDownloadStore } from '../store/zipDownloadStore';
const ALBUM_COUNT = 30;
/** Extra pool when mix rating filter is on so we can still fill the grid after filtering. */
@@ -43,7 +44,7 @@ export default function RandomAlbums() {
const mixMinRatingAlbum = auth.mixMinRatingAlbum;
const mixMinRatingArtist = auth.mixMinRatingArtist;
const serverId = auth.activeServerId ?? '';
const { downloadAlbum } = useOfflineStore();
const downloadAlbum = useOfflineStore(s => s.downloadAlbum);
const requestDownloadFolder = useDownloadModalStore(s => s.requestFolder);
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
const [loading, setLoading] = useState(true);
@@ -65,21 +66,23 @@ export default function RandomAlbums() {
if (selectedAlbums.length === 0) return;
const folder = auth.downloadFolder || await requestDownloadFolder();
if (!folder) return;
let done = 0;
const { start, complete, fail } = useZipDownloadStore.getState();
clearSelection();
for (const album of selectedAlbums) {
showToast(t('albums.downloadingZip', { current: done + 1, total: selectedAlbums.length, name: album.name }), 8000, 'info');
const downloadId = crypto.randomUUID();
const filename = `${sanitizeFilename(album.name)}.zip`;
const destPath = await join(folder, filename);
const url = buildDownloadUrl(album.id);
start(downloadId, filename);
try {
const blob = await fetch(buildDownloadUrl(album.id)).then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.blob(); });
const path = await join(folder, `${sanitizeFilename(album.name)}.zip`);
await writeFile(path, new Uint8Array(await blob.arrayBuffer()));
done++;
await invoke('download_zip', { id: downloadId, url, destPath });
complete(downloadId);
} catch (e) {
fail(downloadId);
console.error('ZIP download failed for', album.name, e);
showToast(t('albums.downloadZipFailed', { name: album.name }), 4000, 'error');
}
}
showToast(t('albums.downloadZipDone', { count: done }), 4000, 'info');
clearSelection();
};
const handleAddOffline = async () => {
+18 -9
View File
@@ -91,8 +91,12 @@ const CONTRIBUTORS = [
since: '1.33.0',
contributions: [
'Russian translation & i18n locale split (PR #106)',
'Russian locale refinements using phrasing from ru2 (PR #113)',
'Gapless manual skip: honor user-initiated play over pre-chained track (PR #119)',
'Per-server music folder filter and sidebar library picker (PR #125)',
'Hot playback cache — queue prefetch (PR #123)',
'Per-server music folder filter and sidebar library picker (PR #124, PR #125)',
'Richer star ratings, skip threshold, and library filtering (PR #130)',
'Statistics: scope album and song totals to selected music library (PR #138)',
],
},
{
@@ -101,6 +105,9 @@ const CONTRIBUTORS = [
contributions: [
'Russian locale improvements (PR #107, PR #120)',
'Auto-install script for Debian / RHEL (PR #121)',
'Album cover art in Discord Rich Presence via iTunes API (PR #111)',
'Tiling WM detection: hide custom TitleBar on Hyprland/Sway/i3/etc. (PR #134)',
'Russian translation: lyricsServerFirst settings strings (PR #140)',
],
},
{
@@ -1856,14 +1863,16 @@ export default function Settings() {
</div>
</div>
<button
className="btn btn-ghost"
style={{ marginTop: '1.25rem', alignSelf: 'flex-start' }}
onClick={() => openUrl('https://github.com/Psychotoxical/psysonic')}
>
<ExternalLink size={14} />
{t('settings.aboutRepo')}
</button>
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '1.25rem', flexWrap: 'wrap' }}>
<button
className="btn btn-ghost"
style={{ alignSelf: 'flex-start' }}
onClick={() => openUrl('https://github.com/Psychotoxical/psysonic')}
>
<ExternalLink size={14} />
{t('settings.aboutRepo')}
</button>
</div>
</div>
</section>
+22 -8
View File
@@ -70,19 +70,24 @@ export default function Statistics() {
setFrequent(fr);
setHighest(hi);
setArtistCount(a.length);
setTotalSongs(g.reduce((acc: number, genre: SubsonicGenre) => acc + genre.songCount, 0));
setTotalAlbums(g.reduce((acc: number, genre: SubsonicGenre) => acc + genre.albumCount, 0));
// Album/song totals come from paginated getAlbumList (see playtime effect) — getGenres is not musicFolder-scoped.
const sorted = [...g].sort((a, b) => b.songCount - a.songCount);
setGenres(sorted);
setLoading(false);
}).catch(() => setLoading(false));
}, [musicLibraryFilterVersion]);
// Background fetch: total playtime (paginate getAlbumList up to 10 pages of 500)
// Background: playtime + album/song counts (same paginated list as library filter; caps at 5000 albums)
useEffect(() => {
let cancelled = false;
setTotalPlaytime(null);
setTotalAlbums(null);
setTotalSongs(null);
setPlaytimeCapped(false);
(async () => {
let total = 0;
let playtimeSec = 0;
let albumsCounted = 0;
let songsCounted = 0;
let offset = 0;
const pageSize = 500;
const maxPages = 10;
@@ -91,7 +96,11 @@ export default function Statistics() {
try {
const albums = await getAlbumList('newest', pageSize, offset);
if (cancelled) return;
for (const a of albums) total += (a.duration ?? 0);
for (const a of albums) {
playtimeSec += a.duration ?? 0;
albumsCounted += 1;
songsCounted += a.songCount ?? 0;
}
if (albums.length < pageSize) break;
if (page === maxPages - 1) capped = true;
offset += pageSize;
@@ -100,7 +109,9 @@ export default function Statistics() {
}
}
if (!cancelled) {
setTotalPlaytime(total);
setTotalPlaytime(playtimeSec);
setTotalAlbums(albumsCounted);
setTotalSongs(songsCounted);
setPlaytimeCapped(capped);
}
})();
@@ -167,10 +178,13 @@ export default function Statistics() {
? t('statistics.computing')
: (playtimeCapped ? '≥ ' : '') + formatPlaytime(totalPlaytime);
const countDisplay = (n: number | null) =>
n === null ? t('statistics.computing') : (playtimeCapped ? '≥ ' : '') + n.toLocaleString();
const stats = [
{ label: t('statistics.statArtists'), value: artistCount?.toLocaleString() ?? '—' },
{ label: t('statistics.statAlbums'), value: totalAlbums?.toLocaleString() ?? '—' },
{ label: t('statistics.statSongs'), value: totalSongs?.toLocaleString() ?? '—' },
{ label: t('statistics.statAlbums'), value: countDisplay(totalAlbums) },
{ label: t('statistics.statSongs'), value: countDisplay(totalSongs) },
{ label: t('statistics.statPlaytime'), value: playtimeDisplay },
];
+46
View File
@@ -0,0 +1,46 @@
import { create } from 'zustand';
export interface DownloadJob {
trackId: string;
albumId: string;
albumName: string;
trackTitle: string;
trackIndex: number;
totalTracks: number;
status: 'queued' | 'downloading' | 'done' | 'error';
}
interface OfflineJobState {
jobs: DownloadJob[];
bulkProgress: Record<string, { done: number; total: number }>;
cancelDownload: (albumId: string) => void;
cancelAllDownloads: () => void;
}
// Module-level cancellation set — checked by downloadAlbum before each batch.
export const cancelledDownloads = new Set<string>();
export const useOfflineJobStore = create<OfflineJobState>()((set, get) => ({
jobs: [],
bulkProgress: {},
cancelDownload: (albumId) => {
cancelledDownloads.add(albumId);
// Remove queued (not yet started) jobs immediately so the counter drops.
set(state => ({
jobs: state.jobs.filter(j => !(j.albumId === albumId && j.status === 'queued')),
}));
},
cancelAllDownloads: () => {
const unique = [...new Set(
get().jobs
.filter(j => j.status === 'queued' || j.status === 'downloading')
.map(j => j.albumId),
)];
unique.forEach(id => cancelledDownloads.add(id));
set(state => ({
jobs: state.jobs.filter(j => j.status !== 'queued'),
}));
},
}));
+99 -76
View File
@@ -5,6 +5,7 @@ import { buildStreamUrl, getArtist, getAlbum } from '../api/subsonic';
import type { SubsonicSong } from '../api/subsonic';
import { useAuthStore } from './authStore';
import { showToast } from '../utils/toast';
import { useOfflineJobStore, cancelledDownloads } from './offlineJobStore';
export interface OfflineTrackMeta {
id: string;
@@ -38,22 +39,12 @@ export interface OfflineAlbumMeta {
type?: 'album' | 'playlist' | 'artist';
}
export interface DownloadJob {
trackId: string;
albumId: string;
albumName: string;
trackTitle: string;
trackIndex: number;
totalTracks: number;
status: 'queued' | 'downloading' | 'done' | 'error';
}
// Re-export for components that import DownloadJob from offlineStore.
export type { DownloadJob } from './offlineJobStore';
interface OfflineState {
tracks: Record<string, OfflineTrackMeta>; // key: `${serverId}:${trackId}`
albums: Record<string, OfflineAlbumMeta>; // key: `${serverId}:${albumId}`
jobs: DownloadJob[];
/** Progress for bulk (playlist / artist) downloads. Key = playlistId or artistId. */
bulkProgress: Record<string, { done: number; total: number }>;
isDownloaded: (trackId: string, serverId: string) => boolean;
isAlbumDownloaded: (albumId: string, serverId: string) => boolean;
@@ -81,8 +72,6 @@ export const useOfflineStore = create<OfflineState>()(
(set, get) => ({
tracks: {},
albums: {},
jobs: [],
bulkProgress: {},
isDownloaded: (trackId, serverId) =>
!!get().tracks[`${serverId}:${trackId}`],
@@ -94,7 +83,7 @@ export const useOfflineStore = create<OfflineState>()(
},
isAlbumDownloading: (albumId) =>
get().jobs.some(
useOfflineJobStore.getState().jobs.some(
j => j.albumId === albumId && (j.status === 'queued' || j.status === 'downloading')
),
@@ -113,22 +102,40 @@ export const useOfflineStore = create<OfflineState>()(
},
getAlbumProgress: (albumId) => {
const albumJobs = get().jobs.filter(j => j.albumId === albumId);
const albumJobs = useOfflineJobStore.getState().jobs.filter(j => j.albumId === albumId);
if (albumJobs.length === 0) return null;
const done = albumJobs.filter(j => j.status === 'done' || j.status === 'error').length;
return { done, total: albumJobs.length };
},
downloadAlbum: async (albumId, albumName, albumArtist, coverArt, year, songs, serverId, type = 'album') => {
const CONCURRENCY = 2;
// Frontend fires up to 8 invoke calls at a time so Rust always has work queued.
// The backend Semaphore (MAX_DL_CONCURRENCY = 4) is the real throttle —
// at most 4 HTTP streams run simultaneously regardless of this value.
const CONCURRENCY = 8;
const trackIds = songs.map(s => s.id);
const jobStore = useOfflineJobStore;
// Register album shell + queue jobs
// Pre-flight: verify the target directory is accessible before queuing anything.
const customDir = useAuthStore.getState().offlineDownloadDir || null;
if (customDir) {
const ok = await invoke<boolean>('check_dir_accessible', { path: customDir }).catch(() => false);
if (!ok) {
showToast('Speichermedium nicht gefunden. Bitte Verzeichnis in den Einstellungen prüfen.', 6000, 'error');
return;
}
}
// Register album in persisted store — 1 localStorage write.
set(state => ({
albums: {
...state.albums,
[`${serverId}:${albumId}`]: { id: albumId, serverId, name: albumName, artist: albumArtist, coverArt, year, trackIds, type },
},
}));
// Queue jobs in the non-persisted job store — zero localStorage writes.
jobStore.setState(state => ({
jobs: [
...state.jobs.filter(j => j.albumId !== albumId),
...songs.map((s, i) => ({
@@ -143,82 +150,97 @@ export const useOfflineStore = create<OfflineState>()(
],
}));
// Download in batches of CONCURRENCY
// Accumulate completed tracks locally — persisted in ONE write at the very end.
const completedTracks: Record<string, OfflineTrackMeta> = {};
for (let i = 0; i < songs.length; i += CONCURRENCY) {
// Abort if the user cancelled this download.
if (cancelledDownloads.has(albumId)) {
cancelledDownloads.delete(albumId);
jobStore.setState(state => ({ jobs: state.jobs.filter(j => j.albumId !== albumId) }));
return;
}
const batch = songs.slice(i, i + CONCURRENCY);
await Promise.all(
const batchIds = new Set(batch.map(s => s.id));
// Mark batch as downloading — job store only, no localStorage write.
jobStore.setState(state => ({
jobs: state.jobs.map(j =>
j.albumId === albumId && batchIds.has(j.trackId)
? { ...j, status: 'downloading' }
: j,
),
}));
// Run all downloads concurrently, collect results without touching any store.
const results = await Promise.all(
batch.map(async song => {
set(state => ({
jobs: state.jobs.map(j =>
j.trackId === song.id && j.albumId === albumId
? { ...j, status: 'downloading' }
: j,
),
}));
const suffix = song.suffix || 'mp3';
const url = buildStreamUrl(song.id);
const customDir = useAuthStore.getState().offlineDownloadDir || null;
try {
const localPath = await invoke<string>('download_track_offline', {
trackId: song.id,
serverId,
url,
url: buildStreamUrl(song.id),
suffix,
customDir,
});
set(state => ({
tracks: {
...state.tracks,
[`${serverId}:${song.id}`]: {
id: song.id,
serverId,
localPath,
title: song.title,
artist: song.artist,
album: song.album,
albumId: song.albumId,
artistId: song.artistId,
suffix,
duration: song.duration,
bitRate: song.bitRate,
coverArt: song.coverArt,
year: song.year,
genre: song.genre,
replayGainTrackDb: song.replayGain?.trackGain,
replayGainAlbumDb: song.replayGain?.albumGain,
replayGainPeak: song.replayGain?.trackPeak,
cachedAt: new Date().toISOString(),
},
},
jobs: state.jobs.map(j =>
j.trackId === song.id && j.albumId === albumId
? { ...j, status: 'done' }
: j,
),
}));
return { song, suffix, localPath, error: null as string | null };
} catch (err) {
const msg = typeof err === 'string' ? err : (err instanceof Error ? err.message : '');
if (msg === 'VOLUME_NOT_FOUND') {
if (msg === 'VOLUME_NOT_FOUND' && !cancelledDownloads.has(albumId)) {
cancelledDownloads.add(albumId);
showToast('Speichermedium nicht gefunden. Bitte Verzeichnis in den Einstellungen prüfen.', 6000, 'error');
}
set(state => ({
jobs: state.jobs.map(j =>
j.trackId === song.id && j.albumId === albumId
? { ...j, status: 'error' }
: j,
),
}));
return { song, suffix, localPath: null as string | null, error: msg };
}
}),
);
// Accumulate completed tracks locally (no store write yet).
for (const { song, suffix, localPath } of results) {
if (localPath) {
completedTracks[`${serverId}:${song.id}`] = {
id: song.id,
serverId,
localPath,
title: song.title,
artist: song.artist,
album: song.album,
albumId: song.albumId,
artistId: song.artistId,
suffix,
duration: song.duration,
bitRate: song.bitRate,
coverArt: song.coverArt,
year: song.year,
genre: song.genre,
replayGainTrackDb: song.replayGain?.trackGain,
replayGainAlbumDb: song.replayGain?.albumGain,
replayGainPeak: song.replayGain?.trackPeak,
cachedAt: new Date().toISOString(),
};
}
}
// Update job statuses — job store only, no localStorage write.
const resultMap = new Map(results.map(r => [r.song.id, r]));
jobStore.setState(state => ({
jobs: state.jobs.map(j => {
if (j.albumId !== albumId) return j;
const r = resultMap.get(j.trackId);
if (!r) return j;
return { ...j, status: r.localPath ? 'done' : 'error' };
}),
}));
}
// Clear completed jobs after a short delay
// Persist all completed tracks in ONE localStorage write.
set(state => ({ tracks: { ...state.tracks, ...completedTracks } }));
// Clear completed jobs after a short delay.
setTimeout(() => {
set(state => ({
jobStore.setState(state => ({
jobs: state.jobs.filter(
j => j.albumId !== albumId || (j.status !== 'done' && j.status !== 'error'),
),
@@ -236,12 +258,13 @@ export const useOfflineStore = create<OfflineState>()(
},
downloadArtist: async (artistId, artistName, serverId) => {
const jobStore = useOfflineJobStore;
let albums: { id: string; name: string; artist: string; coverArt?: string; year?: number }[] = [];
try {
const res = await getArtist(artistId);
albums = res.albums;
} catch { return; }
set(state => ({
jobStore.setState(state => ({
bulkProgress: { ...state.bulkProgress, [artistId]: { done: 0, total: albums.length } },
}));
for (let i = 0; i < albums.length; i++) {
@@ -250,12 +273,12 @@ export const useOfflineStore = create<OfflineState>()(
const { songs } = await getAlbum(album.id);
await get().downloadAlbum(album.id, album.name, album.artist || artistName, album.coverArt, album.year, songs, serverId, 'artist');
} catch { /* skip failed album */ }
set(state => ({
jobStore.setState(state => ({
bulkProgress: { ...state.bulkProgress, [artistId]: { done: i + 1, total: albums.length } },
}));
}
setTimeout(() => {
set(state => {
jobStore.setState(state => {
const { [artistId]: _removed, ...rest } = state.bulkProgress;
return { bulkProgress: rest };
});
+48 -6
View File
@@ -203,6 +203,11 @@ radioAudio.preload = 'none';
let radioStopping = false;
// Pending reconnect timer for stalled streams — null when no reconnect is scheduled.
let radioReconnectTimer: ReturnType<typeof setTimeout> | null = null;
// Counts how many stalled-reconnects have been attempted for the current station.
// Reset to 0 on successful playback. Hard-stop after MAX_RADIO_RECONNECTS so a
// dead stream doesn't loop forever and leak resources in the background.
let radioReconnectCount = 0;
const MAX_RADIO_RECONNECTS = 5;
function clearRadioReconnectTimer() {
if (radioReconnectTimer) { clearTimeout(radioReconnectTimer); radioReconnectTimer = null; }
@@ -211,23 +216,40 @@ function clearRadioReconnectTimer() {
radioAudio.addEventListener('ended', () => {
// Stream disconnected unexpectedly — clear radio state.
clearRadioReconnectTimer();
radioReconnectCount = 0;
usePlayerStore.setState({ isPlaying: false, currentRadio: null, progress: 0, currentTime: 0 });
});
radioAudio.addEventListener('error', () => {
clearRadioReconnectTimer();
if (radioStopping) { radioStopping = false; return; }
if (radioStopping) { radioStopping = false; radioReconnectCount = 0; return; }
radioReconnectCount = 0;
usePlayerStore.setState({ isPlaying: false, currentRadio: null });
showToast('Radio stream error', 3000, 'error');
});
// Playing: stream is delivering audio — reset the reconnect counter.
radioAudio.addEventListener('playing', () => {
radioReconnectCount = 0;
});
// Stalled: stream stopped delivering data — try to reconnect after 4 s.
// On macOS/WKWebView, reassigning src during a stall can itself trigger
// another stall event before the new connection is established. The
// radioReconnectTimer guard prevents stacking, and MAX_RADIO_RECONNECTS
// ensures we don't loop forever on a dead stream.
radioAudio.addEventListener('stalled', () => {
if (radioReconnectTimer) return; // already scheduled
if (radioReconnectCount >= MAX_RADIO_RECONNECTS) {
radioReconnectCount = 0;
usePlayerStore.setState({ isPlaying: false, currentRadio: null });
showToast('Radio stream disconnected', 4000, 'error');
return;
}
radioReconnectTimer = setTimeout(() => {
radioReconnectTimer = null;
if (!usePlayerStore.getState().currentRadio) return;
// Re-assign src to force a fresh connection, then resume playback.
const src = radioAudio.src;
radioAudio.src = src;
radioReconnectCount++;
// Use load() + play() instead of src reassignment — more reliable on
// macOS WKWebView where setting src can fire a premature error event.
radioAudio.load();
radioAudio.play().catch(console.error);
}, 4000);
});
@@ -521,6 +543,7 @@ export function initAudioListeners(): () => void {
playing: isPlaying,
positionSecs: currentTime > 0 ? currentTime : null,
}).catch(() => {});
invoke('update_taskbar_icon', { isPlaying }).catch(() => {});
return;
}
@@ -719,6 +742,7 @@ export const usePlayerStore = create<PlayerState>()(
++playGeneration;
isAudioPaused = false;
clearRadioReconnectTimer();
radioReconnectCount = 0;
gaplessPreloadingId = null;
if (seekDebounce) { clearTimeout(seekDebounce); seekDebounce = null; } seekTarget = null;
// Stop Rust engine in case a regular track was playing.
@@ -973,7 +997,19 @@ export const usePlayerStore = create<PlayerState>()(
.slice(0, 10)
.map(t => ({ ...t, radioAdded: true as const }));
if (fresh.length > 0) {
set(state => ({ queue: [...state.queue, ...fresh] }));
// Trim played tracks from the front to keep the queue bounded.
// Without trimming the queue grows unboundedly, making every
// Zustand persist write larger and causing UI freezes over time.
// Keep the last HISTORY_KEEP played tracks so the user can still
// navigate backwards a few songs.
const HISTORY_KEEP = 5;
set(state => {
const trimStart = Math.max(0, state.queueIndex - HISTORY_KEEP);
return {
queue: [...state.queue.slice(trimStart), ...fresh],
queueIndex: state.queueIndex - trimStart,
};
});
}
})
.catch(() => {})
@@ -1254,7 +1290,13 @@ export const usePlayerStore = create<PlayerState>()(
currentTrack: state.currentTrack,
queue: state.queue,
queueIndex: state.queueIndex,
currentTime: state.currentTime,
// currentTime is intentionally NOT persisted here.
// handleAudioProgress fires every 100ms and each setState with a
// persisted field triggers a full JSON serialisation of the queue to
// localStorage. After ~10 minutes of Artist Radio the queue grows to
// 50+ tracks; 6 000+ synchronous SQLite writes cause WKWebView's
// storage process to crash on macOS → black screen + audio stop.
// Resume position is recovered from Subsonic savePlayQueue (5s debounce).
lastfmLovedCache: state.lastfmLovedCache,
}),
}
+46
View File
@@ -0,0 +1,46 @@
import { create } from 'zustand';
export interface ZipDownload {
id: string;
filename: string;
bytes: number;
/** null = Content-Length unbekannt (Navidrome on-the-fly ZIP) */
total: number | null;
done: boolean;
error: boolean;
}
interface ZipDownloadState {
downloads: ZipDownload[];
start: (id: string, filename: string) => void;
updateProgress: (id: string, bytes: number, total: number | null) => void;
complete: (id: string) => void;
fail: (id: string) => void;
dismiss: (id: string) => void;
}
export const useZipDownloadStore = create<ZipDownloadState>((set) => ({
downloads: [],
start: (id, filename) => set(state => ({
downloads: [...state.downloads, { id, filename, bytes: 0, total: null, done: false, error: false }],
})),
updateProgress: (id, bytes, total) => set(state => ({
downloads: state.downloads.map(d =>
d.id === id ? { ...d, bytes, total: total ?? d.total } : d
),
})),
complete: (id) => set(state => ({
downloads: state.downloads.map(d => d.id === id ? { ...d, done: true } : d),
})),
fail: (id) => set(state => ({
downloads: state.downloads.map(d => d.id === id ? { ...d, error: true } : d),
})),
dismiss: (id) => set(state => ({
downloads: state.downloads.filter(d => d.id !== id),
})),
}));
+122
View File
@@ -6887,3 +6887,125 @@
color: var(--text-muted);
margin-left: auto;
}
/* ─── ZIP Download Overlay ─── */
.zip-dl-overlay {
position: fixed;
bottom: 24px;
right: 24px;
z-index: 9000;
display: flex;
flex-direction: column;
gap: 8px;
pointer-events: none;
}
.zip-dl-item {
pointer-events: all;
width: 280px;
padding: 10px 12px;
border-radius: var(--radius-md);
background: var(--bg-sidebar);
border: 1px solid color-mix(in srgb, var(--accent) 30%, transparent);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);
display: flex;
flex-direction: column;
gap: 6px;
animation: zip-dl-slide-in 0.2s ease;
}
@keyframes zip-dl-slide-in {
from { opacity: 0; transform: translateX(20px); }
to { opacity: 1; transform: translateX(0); }
}
.zip-dl-item.zip-dl-done {
border-color: color-mix(in srgb, var(--accent) 20%, transparent);
opacity: 0.8;
}
.zip-dl-item.zip-dl-error {
border-color: color-mix(in srgb, var(--danger, #e05555) 40%, transparent);
opacity: 0.85;
}
.zip-dl-header {
display: flex;
align-items: center;
gap: 7px;
color: var(--accent);
font-size: 12px;
}
.zip-dl-item.zip-dl-error .zip-dl-header {
color: var(--danger, #e05555);
}
.zip-dl-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text-primary);
font-size: 12px;
}
.zip-dl-close {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
border: none;
background: transparent;
color: var(--text-muted);
cursor: pointer;
padding: 0;
border-radius: 50%;
transition: color 0.15s, background 0.15s;
}
.zip-dl-close:hover {
color: var(--text-primary);
background: var(--bg-hover);
}
.zip-dl-info {
font-size: 11px;
color: var(--text-muted);
padding-left: 20px;
}
.zip-dl-track {
height: 3px;
border-radius: 2px;
background: var(--bg-hover);
overflow: hidden;
position: relative;
}
.zip-dl-fill {
height: 100%;
border-radius: 2px;
background: var(--accent);
transition: width 0.4s linear;
}
/* Indeterminate sliding animation */
.zip-dl-indeterminate::after {
content: '';
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 40%;
border-radius: 2px;
background: var(--accent);
animation: zip-dl-shimmer 1.4s ease-in-out infinite;
}
@keyframes zip-dl-shimmer {
0% { transform: translateX(-100%); }
100% { transform: translateX(350%); }
}
+194 -11
View File
@@ -13,16 +13,22 @@
position: relative;
display: grid;
grid-template-columns: var(--sidebar-width) 1fr var(--queue-width);
grid-template-rows: 1fr var(--player-height);
/* minmax(0, 1fr) instead of plain 1fr: CSS Grid spec treats 1fr as
minmax(auto, 1fr), meaning the row won't shrink below its min-content
size. With minmax(0, 1fr) the row can collapse to zero, keeping the
player bar row always visible regardless of content size or zoom level. */
grid-template-rows: minmax(0, 1fr) var(--player-height);
grid-template-areas:
"sidebar main queue"
"player player player";
height: 100vh;
/* overflow: hidden keeps the player bar pinned at the bottom even when the
window is dragged below the OS minHeight constraint (ignored on some
Linux WMs/compositors). Without this, the 1fr row's implicit auto
min-height can push the grid taller than 100vh, scrolling the player
bar out of view. */
/* height: 100% inherits from html/body/#root (all 100%) so the grid
tracks actual window resize events on every platform.
100vh was used previously but WebView2 (Windows) does not update the
CSS viewport synchronously on resize, causing the player-bar grid row
to drift off-screen. overflow: hidden still prevents the 1fr row from
pushing the grid taller than the window on Linux WMs that ignore
the OS minHeight constraint. */
height: 100%;
overflow: hidden;
background: var(--bg-app);
}
@@ -33,7 +39,7 @@
}
.app-shell[data-titlebar] {
grid-template-rows: var(--titlebar-height) 1fr var(--player-height);
grid-template-rows: var(--titlebar-height) minmax(0, 1fr) var(--player-height);
grid-template-areas:
"titlebar titlebar titlebar"
"sidebar main queue"
@@ -154,6 +160,10 @@
.resizer-queue { right: calc(var(--queue-width) - 3px); }
/* In native fullscreen the resizer sits flush against the screen edge and
would interfere with OS edge-swipe gestures hide it entirely. */
.app-shell[data-fullscreen] .resizer { display: none; }
/* ─── Sidebar ─── */
.sidebar {
grid-area: sidebar;
@@ -651,6 +661,157 @@
font-style: italic;
}
/* ── Update Modal ────────────────────────────────────────────────────────── */
.update-modal {
width: min(520px, 94vw);
gap: 0;
padding: 0;
max-height: 85vh;
display: flex;
flex-direction: column;
}
.update-modal-header {
padding: 14px 16px 14px 18px;
}
.update-modal-versions {
font-size: 12px;
color: var(--text-muted);
display: block;
margin-top: 2px;
}
/* Scrollable middle section (changelog + download area combined) */
.update-modal-body {
flex: 1;
overflow-y: auto;
min-height: 0;
}
/* Changelog accordion */
.update-modal-changelog {
border-top: 1px solid var(--border-subtle);
border-bottom: 1px solid var(--border-subtle);
}
.update-modal-changelog-toggle {
width: 100%;
display: flex;
align-items: center;
gap: var(--space-2);
padding: 9px 18px;
background: none;
border: none;
cursor: pointer;
color: var(--text-secondary);
font-size: 12px;
font-weight: 600;
text-align: left;
letter-spacing: 0.03em;
transition: color var(--transition-fast), background var(--transition-fast);
}
.update-modal-changelog-toggle:hover {
color: var(--text-primary);
background: var(--bg-glass);
}
.update-modal-changelog-body {
padding: 4px 18px 12px;
}
/* Download area */
.update-modal-download-area {
padding: 14px 18px;
}
.update-modal-asset {
display: flex;
align-items: center;
gap: var(--space-2);
background: var(--bg-glass);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-md);
padding: 8px 12px;
}
.update-modal-asset-name {
font-size: 12px;
color: var(--text-secondary);
flex: 1;
word-break: break-all;
}
.update-modal-asset-size {
font-size: 11px;
color: var(--text-muted);
flex-shrink: 0;
}
.update-modal-progress {
display: flex;
align-items: center;
gap: var(--space-2);
}
.update-modal-progress .app-updater-progress-bar { flex: 1; height: 4px; }
.update-modal-dl-bytes {
font-size: 11px;
color: var(--text-muted);
white-space: nowrap;
}
.update-modal-done {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.update-modal-done-title {
font-size: 13px;
font-weight: 600;
color: var(--accent);
}
.update-modal-done-hint {
font-size: 12px;
color: var(--text-secondary);
}
.update-modal-folder-btn {
align-self: flex-start;
display: inline-flex;
align-items: center;
gap: var(--space-2);
font-size: 12px;
}
/* AUR hint */
.update-modal-aur {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.update-modal-aur-title {
font-size: 13px;
color: var(--text-secondary);
}
.update-modal-aur-cmd {
display: block;
background: var(--bg-glass);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-sm);
padding: 6px 10px;
font-size: 12px;
color: var(--accent);
font-family: monospace;
user-select: all;
}
.update-modal-aur-alt {
color: var(--text-muted);
}
.update-modal-asset-none {
padding: 4px 0;
}
/* Footer */
.update-modal-footer {
display: flex;
align-items: center;
gap: var(--space-2);
padding: 12px 18px;
border-top: 1px solid var(--border-subtle);
flex-shrink: 0;
}
.update-modal-skip {
font-size: 12px;
color: var(--text-muted);
padding: var(--space-1) var(--space-2);
}
.update-modal-skip:hover { color: var(--text-secondary); }
.update-toast {
margin: 0 var(--space-1) var(--space-2);
padding: var(--space-3) var(--space-3);
@@ -729,6 +890,28 @@
padding: 6px;
}
.sidebar-offline-cancel {
margin-left: auto;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
border-radius: 50%;
border: none;
background: transparent;
color: var(--accent);
cursor: pointer;
opacity: 0.6;
padding: 0;
transition: opacity 0.15s, background 0.15s;
}
.sidebar-offline-cancel:hover {
opacity: 1;
background: color-mix(in srgb, var(--accent) 20%, transparent);
}
@keyframes spin-slow {
to { transform: rotate(360deg); }
}
@@ -1571,7 +1754,7 @@
/* ─── Grid Overrides ─── */
.app-shell[data-mobile] {
grid-template-columns: 1fr;
grid-template-rows: 1fr auto auto;
grid-template-rows: minmax(0, 1fr) auto auto;
grid-template-areas:
"main"
"bottomnav"
@@ -1581,7 +1764,7 @@
}
.app-shell[data-mobile][data-titlebar] {
grid-template-rows: var(--titlebar-height) 1fr auto auto;
grid-template-rows: var(--titlebar-height) minmax(0, 1fr) auto auto;
grid-template-areas:
"titlebar"
"main"
@@ -1656,7 +1839,7 @@
/* When the mobile player is active, the app-shell becomes a single full-screen
area with no BottomNav or PlayerBar just the main content. */
.app-shell[data-mobile-player] {
grid-template-rows: 1fr;
grid-template-rows: minmax(0, 1fr);
grid-template-areas: "main";
}
+44 -23
View File
@@ -3,7 +3,22 @@
Catppuccin Mocha Color Palette + Inter Typography
*/
@import url('https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Space+Grotesk:wght@400;500;600;700&family=Outfit:wght@300..700&family=DM+Sans:ital,opsz,wght@0,9..40,300..700;1,9..40,300..700&family=Nunito:ital,wght@0,300..800;1,300..800&family=Rubik:ital,wght@0,300..700;1,300..700&family=Figtree:ital,wght@0,300..800;1,300..800&family=Manrope:wght@300..800&family=Plus+Jakarta+Sans:ital,wght@0,300..800;1,300..800&family=Lexend:wght@300..700&display=swap');
@import '@fontsource-variable/inter';
@import '@fontsource-variable/inter/wght-italic.css';
@import '@fontsource-variable/space-grotesk';
@import '@fontsource-variable/outfit';
@import '@fontsource-variable/dm-sans';
@import '@fontsource-variable/dm-sans/wght-italic.css';
@import '@fontsource-variable/nunito';
@import '@fontsource-variable/nunito/wght-italic.css';
@import '@fontsource-variable/rubik';
@import '@fontsource-variable/rubik/wght-italic.css';
@import '@fontsource-variable/figtree';
@import '@fontsource-variable/figtree/wght-italic.css';
@import '@fontsource-variable/manrope';
@import '@fontsource-variable/plus-jakarta-sans';
@import '@fontsource-variable/plus-jakarta-sans/wght-italic.css';
@import '@fontsource-variable/lexend';
/* ─── Catppuccin Mocha Variables ─── */
:root,
@@ -3129,8 +3144,8 @@
/* ─── Global Base Settings ─── */
:root {
/* Typography */
--font-sans: 'Inter', system-ui, -apple-system, sans-serif;
--font-display: 'Space Grotesk', 'Inter', sans-serif;
--font-sans: 'Inter Variable', system-ui, -apple-system, sans-serif;
--font-display: 'Space Grotesk Variable', 'Inter Variable', sans-serif;
/* Spacing */
--space-1: 4px;
@@ -3499,8 +3514,9 @@ html,
body,
#root {
height: 100%;
min-width: 1280px;
min-height: 720px;
/* min-height removed: Tauri enforces the real window minimum (minHeight: 480).
A CSS min-height larger than the effective CSS viewport (which shrinks at
zoom > 1) pushes html taller than the window, clipping the player bar. */
overflow: hidden;
}
@@ -6303,49 +6319,54 @@ input[type="range"]:hover::-webkit-slider-thumb {
}
/* ─── Font overrides ─── */
[data-font='inter'] {
--font-sans: 'Inter Variable', system-ui, -apple-system, sans-serif;
--font-display: 'Inter Variable', sans-serif;
}
[data-font='outfit'] {
--font-sans: 'Outfit', system-ui, sans-serif;
--font-display: 'Outfit', sans-serif;
--font-sans: 'Outfit Variable', system-ui, sans-serif;
--font-display: 'Outfit Variable', sans-serif;
}
[data-font='dm-sans'] {
--font-sans: 'DM Sans', system-ui, sans-serif;
--font-display: 'DM Sans', sans-serif;
--font-sans: 'DM Sans Variable', system-ui, sans-serif;
--font-display: 'DM Sans Variable', sans-serif;
}
[data-font='nunito'] {
--font-sans: 'Nunito', system-ui, sans-serif;
--font-display: 'Nunito', sans-serif;
--font-sans: 'Nunito Variable', system-ui, sans-serif;
--font-display: 'Nunito Variable', sans-serif;
}
[data-font='rubik'] {
--font-sans: 'Rubik', system-ui, sans-serif;
--font-display: 'Rubik', sans-serif;
--font-sans: 'Rubik Variable', system-ui, sans-serif;
--font-display: 'Rubik Variable', sans-serif;
}
[data-font='space-grotesk'] {
--font-sans: 'Space Grotesk', system-ui, sans-serif;
--font-display: 'Space Grotesk', sans-serif;
--font-sans: 'Space Grotesk Variable', system-ui, sans-serif;
--font-display: 'Space Grotesk Variable', sans-serif;
}
[data-font='figtree'] {
--font-sans: 'Figtree', system-ui, sans-serif;
--font-display: 'Figtree', sans-serif;
--font-sans: 'Figtree Variable', system-ui, sans-serif;
--font-display: 'Figtree Variable', sans-serif;
}
[data-font='manrope'] {
--font-sans: 'Manrope', system-ui, sans-serif;
--font-display: 'Manrope', sans-serif;
--font-sans: 'Manrope Variable', system-ui, sans-serif;
--font-display: 'Manrope Variable', sans-serif;
}
[data-font='plus-jakarta-sans'] {
--font-sans: 'Plus Jakarta Sans', system-ui, sans-serif;
--font-display: 'Plus Jakarta Sans', sans-serif;
--font-sans: 'Plus Jakarta Sans Variable', system-ui, sans-serif;
--font-display: 'Plus Jakarta Sans Variable', sans-serif;
}
[data-font='lexend'] {
--font-sans: 'Lexend', system-ui, sans-serif;
--font-display: 'Lexend', sans-serif;
--font-sans: 'Lexend Variable', system-ui, sans-serif;
--font-display: 'Lexend Variable', sans-serif;
}
/* ─── Equalizer bars animation ─── */
+4
View File
@@ -1,2 +1,6 @@
/** True when running on Linux (WebKitGTK). Used to show the custom title bar. */
export const IS_LINUX = navigator.platform.toLowerCase().includes('linux');
/** True when running on macOS (WKWebView). */
export const IS_MACOS = navigator.platform.toLowerCase().includes('mac');
/** True when running on Windows (WebView2). */
export const IS_WINDOWS = navigator.platform.toLowerCase().includes('win');