A CD-shaped music player for Linux, with local playback and Cider integration.
Add native Navidrome and Subsonic music support
yappologistic46bb8c8dd203
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 3aa2de9..feafe5c 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -46,7 +46,7 @@ qt_add_library(spun_core STATICsrc/listening.cpp src/listening.h src/tapesound.cpp src/tapesound.h src/vinylnoise.cpp src/vinylnoise.hsrc/musicactions.cpp src/musicactions.hsrc/library.cpp src/library.h src/lyrics.cpp src/lyrics.h src/artwork.cpp src/artwork.h- src/tx6.cpp src/tx6.h src/youtube.cpp src/youtube.h src/jellyfinapi.cpp src/jellyfinapi.h src/jellyfin.cpp src/jellyfin.h+ src/tx6.cpp src/tx6.h src/youtube.cpp src/youtube.h src/jellyfinapi.cpp src/jellyfinapi.h src/remotemusicapi.h src/remotelibrary.cpp src/remotelibrary.h src/jellyfin.h src/subsonicapi.cpp src/subsonicapi.hsrc/player.cpp src/player.h src/disc.cpp src/disc.h src/recorder.cpp src/recorder.h src/playerbody.cpp src/playerbody.h src/mpris.cpp src/mpris.hsrc/theme.cpp src/theme.h src/cider.cpp src/cider.h src/ciderevents.cpp src/ciderevents.h)target_link_libraries(spun_core PUBLIC Qt6::Core Qt6::Gui Qt6::Quick Qt6::Qml Qt6::QuickControls2@@ -79,7 +79,7 @@ function(spun_application target)# Compile QML at build time, preserving existing resource URLs and the UI.qt_add_qml_module(${target} URI SpunUi VERSION 1.0 NO_PLUGINNO_RESOURCE_TARGET_PATH RESOURCE_PREFIX "/" OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${target}-qml"- QML_FILES qml/JellyfinPanel.qml qml/SpunChoiceButton.qml qml/SpunLoading.qml qml/YoutubePanel.qml ${SPUN_3D_QML} qml/Recorder.qml qml/RecorderDisplay.qml qml/Tx6Controls.qml qml/Tx6Labels.qml qml/Tx6Display.qml qml/CassetteControls.qml qml/CdControls.qml qml/CdDisplay.qml qml/SpunButton.qml qml/SpunSlider.qml qml/SeekSlider.qml qml/QuickJump.qml qml/NextTrackTip.qml qml/SavedQueuePicker.qml qml/Tonearm.qml qml/CassetteReels.qml qml/SpunText.qml qml/FontPicker.qml qml/SpunStateLayer.qml qml/SpunSpring.qml qml/SpunPopupEnter.qml qml/SpunStyle.qml qml/TrackContent.qml qml/SpunSearchField.qml qml/MenuEntry.qml qml/PreferenceSwitch.qml qml/TrackMenu.qml qml/Main.qml qml/LibraryPanel.qml qml/SpunToolTip.qml qml/IconButton.qml qml/Glyph.qml)+ QML_FILES qml/RemoteLibraryPanel.qml qml/SpunChoiceButton.qml qml/SpunLoading.qml qml/YoutubePanel.qml ${SPUN_3D_QML} qml/Recorder.qml qml/RecorderDisplay.qml qml/Tx6Controls.qml qml/Tx6Labels.qml qml/Tx6Display.qml qml/CassetteControls.qml qml/CdControls.qml qml/CdDisplay.qml qml/SpunButton.qml qml/SpunSlider.qml qml/SeekSlider.qml qml/QuickJump.qml qml/NextTrackTip.qml qml/SavedQueuePicker.qml qml/Tonearm.qml qml/CassetteReels.qml qml/SpunText.qml qml/FontPicker.qml qml/SpunStateLayer.qml qml/SpunSpring.qml qml/SpunPopupEnter.qml qml/SpunStyle.qml qml/TrackContent.qml qml/SpunSearchField.qml qml/MenuEntry.qml qml/PreferenceSwitch.qml qml/TrackMenu.qml qml/Main.qml qml/LibraryPanel.qml qml/SpunToolTip.qml qml/IconButton.qml qml/Glyph.qml)# Preserve the exact SVGs and URLs; Qt's default threshold leaves many of# these small resources uncompressed. Parsed symbols are already cached.if(QT_FEATURE_zstd)@@ -106,7 +106,7 @@ endif()if(BUILD_TESTING)find_package(Qt6 REQUIRED COMPONENTS Test)spun_application(spun-diagnostics)- target_sources(spun-diagnostics PRIVATE src/jellyfintest.cpp src/youtubetest.cpp src/librarytest.cpp src/librarytest.h src/eventstest.cpp src/mediauitest.cpp src/threedtest.cpp src/artworktest.cpp src/recordertest.cpp src/turntabletest.cpp src/cassettedecktest.cpp src/cddecktest.cpp src/tx6test.cpp)+ target_sources(spun-diagnostics PRIVATE src/subsonictest.cpp src/jellyfintest.cpp src/youtubetest.cpp src/librarytest.cpp src/librarytest.h src/eventstest.cpp src/mediauitest.cpp src/threedtest.cpp src/artworktest.cpp src/recordertest.cpp src/turntabletest.cpp src/cassettedecktest.cpp src/cddecktest.cpp src/tx6test.cpp)target_sources(spun-diagnostics PRIVATE src/performancetest.cpp src/performancetest.h)target_compile_definitions(spun-diagnostics PRIVATE SPUN_DIAGNOSTICS)target_link_libraries(spun-diagnostics PRIVATE Qt6::Test)@@ -141,3 +141,10 @@ if(BUILD_TESTING)add_test(NAME spun-jellyfin-protocol COMMAND spun-jellyfin-protocol-test)set_tests_properties(spun-jellyfin-protocol PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QPA_PLATFORMTHEME=")endif()++if(BUILD_TESTING)+ qt_add_executable(spun-subsonic-protocol-test src/subsonicprotocoltest.cpp)+ target_link_libraries(spun-subsonic-protocol-test PRIVATE spun_core Qt6::Test)+ add_test(NAME spun-subsonic-protocol COMMAND spun-subsonic-protocol-test)+ set_tests_properties(spun-subsonic-protocol PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QPA_PLATFORMTHEME=")+endif()diff --git a/NOTICE b/NOTICEindex 884118c..9ff2268 100644--- a/NOTICE+++ b/NOTICE@@ -53,3 +53,8 @@ The Jellyfin client, LRC parser, protocol tests and disposable-server fixture insrc/jellyfinapi.*, src/jellyfinlrc.h, src/jellyfinprotocoltest.cpp andscripts/test-jellyfin-server.py are adapted from Sung, Copyright (c) 2026 Sungcontributors, under the MIT license. See licenses/Sung-MIT.txt.++The Subsonic client and protocol tests in src/subsonicapi.* and+src/subsonicprotocoltest.cpp, and the Navidrome fixture in+scripts/test-subsonic-server.py are adapted from Sung, Copyright (c) 2026+Sung contributors, under the MIT license. See licenses/Sung-MIT.txt.diff --git a/README.md b/README.mdindex 0078231..3750b3b 100644--- a/README.md+++ b/README.md@@ -22,7 +22,7 @@<a href="#license">License</a></p>-Play local music, browse YouTube Music anonymously, connect to Jellyfin, or control Apple Music through Cider. Spun puts your album artwork on a spinning CD, vinyl record, cassette or TP-7-inspired recorder, with an interface inspired by Material Design 3. Optional 3D players add physical depth and lighting that follows Noctalia's wallpaper palette.+Play local music, browse YouTube Music anonymously, connect to Jellyfin, Navidrome or Subsonic, or control Apple Music through Cider. Spun puts your album artwork on a spinning CD, vinyl record, cassette or TP-7-inspired recorder, with an interface inspired by Material Design 3. Optional 3D players add physical depth and lighting that follows Noctalia's wallpaper palette.**Source-available · PolyForm Noncommercial 1.0.0.** Personal and other permitted noncommercial use is free. This is not an OSI-approved open-source license. [Read the license details](#license).@@ -136,7 +136,7 @@ Choose a medium in **More → Preferences**. All four share playback controls, aIn the TP-7 view, toggle **TX–6** beside the player. It works in 2D and 3D, with a modeled USB-C cable between the devices.-- Channel 1 carries Local, YouTube or Jellyfin TP-7 audio. Right-click channels 2–6 to load additional local files; all channels follow TP-7 playback and seeking.+- Channel 1 carries Local, YouTube, Jellyfin or Subsonic TP-7 audio. Right-click channels 2–6 to load additional local files; all channels follow TP-7 playback and seeking.- The knob rows adjust high, mid and low EQ. Drag a fader or click its track to set the level. Press a channel key to mute; Shift-click to solo, or press the mixer's Shift button first.- The master knob controls player volume. FX I adds stereo delay; FX II enables compression. Hide or power off the mixer to bypass it.- The paired 3D view expands to make controls easier to reach. Buttons press inward and spring back on release.@@ -193,6 +193,14 @@ Jellyfin uses the same transport, queue, desktop media controls, timed lyrics anPlayback currently buffers one song to a temporary file before it starts, with a 512 MiB limit per song. Transcoding requires permission on your server. Collections are limited to 20,000 entries. This integration is for music; video, offline downloads and server administration are not included.+### Connect to Navidrome or Subsonic++Choose **Subsonic**, then **Connect**. Enter the server root URL (including any base path, without `/rest`), username and password. Use HTTPS for remote servers. **Remember connection** stores the password in the desktop keyring through `secret-tool`; without a working keyring, sign in each time. Requests use salted token authentication.++Albums, artists, songs, genres, search, favorites, playlists, artwork and lyrics use the same library UI and native 2D/3D players as Jellyfin, including TX-6 and desktop media controls. Each account has a separate queue that restores paused. Settings offer music-folder selection, original audio or 128/192/320 kbps transcoding, and optional now-playing/listening reports. Timed lyrics use OpenSubsonic when available, with a legacy lyrics fallback. Only playlist owners can edit; stale playlist orders must be refreshed before removing or moving tracks.++The same 512 MiB temporary audio buffer and 20,000-entry collection limits apply. This is a music integration, using Subsonic 1.16.1 and supported OpenSubsonic extensions. Server capabilities and permissions determine available transcoding and lyrics; original Subsonic servers may require Premium. Listening reports count elapsed playback, not seeks; the protocol has no pause/stop session endpoint.+### Browse through CiderUse the top-left search button to browse songs, albums, playlists and artists without leaving Spun.@@ -223,7 +231,7 @@ Cider changes refresh the visible queue and relevant details. Temporary connectiChoose your font, interface size, background blur, animations and media appearance in **More → Preferences**. Spun follows Noctalia's colors and reduced-motion setting when available. Reduced motion also skips loading sequences and perspective tilt.-Spun's desktop media entry follows the selected Local, Cider, YouTube or Jellyfin source, including artwork, playback state, volume and seeking. Cider may also expose its own entry. Hyprland integration depends on the compositor's supported interfaces.+Spun's desktop media entry follows the selected Local, Cider, YouTube, Jellyfin or Subsonic source, including artwork, playback state, volume and seeking. Cider may also expose its own entry. Hyprland integration depends on the compositor's supported interfaces.**Audio settings** contains crossfade and, where supported by Cider, Automix and listening modes. **Audio quality** in the current song's menu shows what Cider reports and labels device output separately.@@ -318,6 +326,15 @@ python3 scripts/test-jellyfin-server.py --server-binary /path/to/jellyfin \This creates a private, disposable server with generated FLAC, MP3 and Opus music, two libraries and test accounts. It tests authentication, browsing, pagination, playlists, favorites, playback, seeking, lyrics, artwork, reporting and source isolation, then stops the server. Add `--renderer 3d` for software-rendered 3D checks, or `--renderer native` in a separate Wayland test session. Test output contains temporary credentials and must not be committed or shared. Jellyfin 10.11 and 12 are tested; other server versions and plugins may behave differently.+For Navidrome integration checks, use a Navidrome server binary with the same disposable fixture workflow:++```bash+python3 scripts/test-subsonic-server.py --server-binary /path/to/navidrome \+ --test-binary ./build/spun --output /tmp/spun-subsonic-test+```++The fixture generates 105 tracks and owner/reader accounts, tests the full music workflow, and stops the server afterward. `--renderer native` belongs in a separate Wayland test session. Protocol tests cover classic Subsonic responses, OpenSubsonic extensions, authentication, permissions, cancellation and stale playlist edits. Keep fixture output private; it contains temporary test credentials.+For the complete 3D interaction and Cider-fixture suites, run `SPUN_TEST_RENDERER=native ./scripts/test-3d.sh` in a separate Wayland or X11 test session. This includes projected seeking, tonearm gestures, lid transitions, scaling and mode combinations. Set `SPUN_TEST_SCREEN` to the dedicated output name and `SPUN_TEST_OUTPUT` to a local capture directory. Missing 3D rendering fails the checks instead of silently skipping them.For large imports, run `QT_QPA_PLATFORM=offscreen QT_QPA_PLATFORMTHEME= ./build/spun-import-test --stress`. This creates 20,000 temporary sparse WAV files representing 625 GiB of audio without allocating that much disk space, then removes them.diff --git a/qml/Main.qml b/qml/Main.qmlindex 1006f2e..922fbec 100644--- a/qml/Main.qml+++ b/qml/Main.qml@@ -87,17 +87,22 @@ ApplicationWindow {readonly property bool vinyl: player.vinylonVinylChanged: Qt.callLater(updateMask)property bool useJellyfin: false- onUseJellyfinChanged: {- if (useJellyfin) { useYoutube=false; useCider=false; player.pause(); if(ciderService.playing)ciderService.pause() }- jellyfin.enabled=useJellyfin+ property bool useSubsonic: false+ readonly property bool useServer: useJellyfin || useSubsonic+ readonly property var serverLibrary: useSubsonic ? subsonic : jellyfin+ function serverSourceChanged() {+ if (useServer) { useYoutube=false; useCider=false; player.pause(); if(ciderService.playing)ciderService.pause() }+ jellyfin.enabled=useJellyfin; subsonic.enabled=useSubsonicstopSwap(); presentation.clear(); cancel3DPointer(); cancelSeekPreview(); discFlipped=false; libraryOpen=falseclearQueueSelection(); cancelQueueDrag(); queueMenu.close(); songMenu.close(); musicBrowser.closeActions()Qt.callLater(function(){presentDisc();syncLyrics();updateMask()})}+ onUseJellyfinChanged: { if(useJellyfin)useSubsonic=false; serverSourceChanged() }+ onUseSubsonicChanged: { if(useSubsonic)useJellyfin=false; serverSourceChanged() }property bool useYoutube: false- readonly property var lyricService: useJellyfin ? jellyfin : useYoutube ? youtube : lyrics+ readonly property var lyricService: useServer ? serverLibrary : useYoutube ? youtube : lyricsonUseYoutubeChanged: {- if (useYoutube) { useJellyfin=false; if (ciderService.playing) ciderService.pause(); useCider=false; player.pause() }+ if (useYoutube) { useJellyfin=false;useSubsonic=false; if (ciderService.playing) ciderService.pause(); useCider=false; player.pause() }youtube.enabled=useYoutubestopSwap(); presentation.clear(); cancel3DPointer(); cancelSeekPreview(); discFlipped=false; libraryOpen=falseclearQueueSelection(); cancelQueueDrag(); queueMenu.close(); songMenu.close(); musicBrowser.closeActions()@@ -122,11 +127,11 @@ ApplicationWindow {running: root.useCider && root.visible && root.visibility !== Window.Minimized && (songMenu.visible || crossfadeMenu.visible || qualityPopup.visible)onTriggered: root.refreshOpenCiderDetails()}- property var deckPlayer: useCider ? root.ciderService : useJellyfin ? jellyfin.transport : useYoutube ? youtube.transport : player- onDeckPlayerChanged: tx6.setPlayer(useJellyfin ? jellyfin.transport : useYoutube ? youtube.transport : player)- readonly property string cassetteTrackIdentity: (useCider ? "cider:" : useJellyfin ? "jellyfin:" : useYoutube ? "youtube:" : "local:") + (deckPlayer.trackKey || "")+ property var deckPlayer: useCider ? root.ciderService : useServer ? serverLibrary.transport : useYoutube ? youtube.transport : player+ onDeckPlayerChanged: tx6.setPlayer(useServer ? serverLibrary.transport : useYoutube ? youtube.transport : player)+ readonly property string cassetteTrackIdentity: (useCider ? "cider:" : useServer ? (useSubsonic ? "subsonic:" : "jellyfin:") : useYoutube ? "youtube:" : "local:") + (deckPlayer.trackKey || "")onCassetteTrackIdentityChanged: { cancel3DPointer(); Qt.callLater(syncTapeSound) }- function syncTapeSound() { tapeSound.observe(useCider ? "cider" : useJellyfin ? "jellyfin" : useYoutube ? "youtube" : "local", deckPlayer.trackKey || "") }+ function syncTapeSound() { tapeSound.observe(useCider ? "cider" : useServer ? serverLibrary.server.scheme : useYoutube ? "youtube" : "local", deckPlayer.trackKey || "") }Binding { target: tapeSound; property: "enabled"; value: root.cassette && player.cassetteSounds }Binding { target: tapeSound; property: "volume"; value: root.deckPlayer.volume }Binding { target: vinylNoise; property: "active"; value: root.vinyl && root.deckPlayer.playing && !root.needleDragging }@@ -147,7 +152,7 @@ ApplicationWindow {running: root.vinyl && player.vinylSkips && root.deckPlayer.playing && !root.needleDraggingonTriggered: { root.skipGroove(); interval = 45000 + Math.floor(Math.random()*35000) }}- onUseCiderChanged: { if(useCider){useYoutube=false;useJellyfin=false;} stopSwap(); presentation.clear(); cancel3DPointer(); if (!useCider) root.listeningService.cancelAlbumPosition(); cancelSeekPreview(); artworkPopup.close(); recoveryPopup.close(); quickJump.close(); savedQueuePicker.close(); clearQueueSelection(); cleanupPopup.close(); qualityPopup.close(); if(libraryDragging)endLibraryDrag(false); preferences.close(); crossfadeMenu.close(); queueMenu.close(); cancelQueueDrag(); songMenu.close(); musicBrowser.closeActions(); if (!useCider) libraryOpen = false; if (useCider) player.pause(); root.ciderService.queueVisible = queueOpen && useCider; discFlipped = false; closeQueueSearch(); Qt.callLater(presentDisc); syncLyrics() }+ onUseCiderChanged: { if(useCider){useYoutube=false;useJellyfin=false;useSubsonic=false;} stopSwap(); presentation.clear(); cancel3DPointer(); if (!useCider) root.listeningService.cancelAlbumPosition(); cancelSeekPreview(); artworkPopup.close(); recoveryPopup.close(); quickJump.close(); savedQueuePicker.close(); clearQueueSelection(); cleanupPopup.close(); qualityPopup.close(); if(libraryDragging)endLibraryDrag(false); preferences.close(); crossfadeMenu.close(); queueMenu.close(); cancelQueueDrag(); songMenu.close(); musicBrowser.closeActions(); if (!useCider) libraryOpen = false; if (useCider) player.pause(); root.ciderService.queueVisible = queueOpen && useCider; discFlipped = false; closeQueueSearch(); Qt.callLater(presentDisc); syncLyrics() }property bool lyricsView: falseproperty real swapOffset: 0property real outgoingOffset: 0@@ -159,11 +164,11 @@ ApplicationWindow {function resetSwap() { swapOffset = 0; outgoingOffset = 0; outgoingOpacity = 0; incomingOpacity = 1; lidOpen = 0; packageOpacity = 0 }function stopSwap() { discSwap.stop(); resetSwap(); presentation.releaseOutgoing() }function presentDisc() {- const albumKey = deckPlayer.count ? (useCider ? "cider:" : useJellyfin ? "jellyfin:" : useYoutube ? "youtube:" : "local:") + (deckPlayer.albumKey || deckPlayer.title) : ""+ const albumKey = deckPlayer.count ? (useCider ? "cider:" : useServer ? (useSubsonic ? "subsonic:" : "jellyfin:") : useYoutube ? "youtube:" : "local:") + (deckPlayer.albumKey || deckPlayer.title) : ""presentation.present(deckPlayer.artwork, albumKey, animate && !recorder && !discFlipped && visible && platformNative.exposed)}function syncLibrary() { if (!visible || visibility === Window.Minimized) { songMenu.close(); musicBrowser.closeActions() }; library.active = libraryOpen && useCider && visible && visibility !== Window.Minimized }- function syncLyrics() { jellyfin.active = useJellyfin && discFlipped && lyricsView && visible && visibility !== Window.Minimized; lyrics.remote = useCider; lyrics.active = !useJellyfin && !useYoutube && discFlipped && lyricsView && visible && visibility !== Window.Minimized; youtube.active = useYoutube && discFlipped && lyricsView && visible && visibility !== Window.Minimized }+ function syncLyrics() { jellyfin.active = useJellyfin && discFlipped && lyricsView && visible && visibility !== Window.Minimized; subsonic.active = useSubsonic && discFlipped && lyricsView && visible && visibility !== Window.Minimized; lyrics.remote = useCider; lyrics.active = !useServer && !useYoutube && discFlipped && lyricsView && visible && visibility !== Window.Minimized; youtube.active = useYoutube && discFlipped && lyricsView && visible && visibility !== Window.Minimized }onLyricsViewChanged: { syncLyrics(); if (discFlipped) Qt.callLater(focusDiscDetails) }onVisibilityChanged: { syncLibrary(); syncLyrics(); if (root.visibility === Window.Minimized) { stopSwap(); cancelSeekPreview() } }onVisibleChanged: { syncLibrary(); syncLyrics(); if (!root.visible) { stopSwap(); cancelSeekPreview() } }@@ -184,7 +189,7 @@ ApplicationWindow {if (current < 0 || (useCider && (!discDetails.albumId || ciderService.discLoading || ciderService.discError.length))) return nullreturn {rows: rows, total: total, current: current}}- readonly property string recordKey: recordMap ? (useCider ? "cider:" : useJellyfin ? "jellyfin:" : useYoutube ? "youtube:" : "local:") + recordMap.rows.map(row => (row.track.id || row.track.path) + ":" + row.duration).join("|") : ""+ readonly property string recordKey: recordMap ? (useCider ? "cider:" : useServer ? (useSubsonic ? "subsonic:" : "jellyfin:") : useYoutube ? "youtube:" : "local:") + recordMap.rows.map(row => (row.track.id || row.track.path) + ":" + row.duration).join("|") : ""onRecordKeyChanged: { cancelSeekPreview(); scrubber.cancelScrub() }readonly property real recordProgress: recordMap ? Math.max(0, Math.min(1, (recordMap.rows[recordMap.current].start + deckPlayer.position) / recordMap.total)) : progressreadonly property bool seekPreviewActive: !!activeSeekControl || scrubber.scrubbing || !!(tonearm && tonearm.dragging)@@ -329,7 +334,7 @@ ApplicationWindow {useCider = true; libraryOpen = truereturn true}- function openArtistName(name) { if(useJellyfin){libraryOpen=true;jellyfin.search(name,"artists");return}; if(useYoutube){libraryOpen=true;youtube.search(name,"artists");return}; useCider = true; libraryOpen = true; library.showArtist(name) }+ function openArtistName(name) { if(useServer){libraryOpen=true;serverLibrary.search(name,"artists");return}; if(useYoutube){libraryOpen=true;youtube.search(name,"artists");return}; useCider = true; libraryOpen = true; library.showArtist(name) }function openLibrary() { libraryOpen = !libraryOpen }readonly property bool queueControlsReady: !useCider || (!root.actionService.busy && root.ciderService.queueReady && !root.ciderService.queueBusy && !root.ciderService.controlBusy && !root.ciderService.queueError.length)readonly property bool queueReorderAllowed: queueControlsReady && !queueQuery.trim().length@@ -446,7 +451,7 @@ ApplicationWindow {}property bool queueOpen: falseproperty bool helpOpen: false- readonly property bool menuOpen: !!(jellyfinBrowser.item && jellyfinBrowser.item.actionsOpen) || !!(youtubeBrowser.item && youtubeBrowser.item.actionsOpen) || !!(tx6Controls && tx6Controls.popupOpen) || artworkPopup.visible || helpOpen || recoveryPopup.visible || quickJump.visible || savedQueuePicker.visible || cleanupPopup.visible || qualityPopup.visible || savedQueueMenu.visible || saveQueuePopup.visible || deleteQueuePopup.visible || fontPicker.shown || fontPicker.opening || menu.visible || preferences.visible || crossfadeMenu.visible || queueMenu.visible || songMenu.visible || musicBrowser.actionsOpen+ readonly property bool menuOpen: !!(serverBrowser.item && serverBrowser.item.actionsOpen) || !!(youtubeBrowser.item && youtubeBrowser.item.actionsOpen) || !!(tx6Controls && tx6Controls.popupOpen) || artworkPopup.visible || helpOpen || recoveryPopup.visible || quickJump.visible || savedQueuePicker.visible || cleanupPopup.visible || qualityPopup.visible || savedQueueMenu.visible || saveQueuePopup.visible || deleteQueuePopup.visible || fontPicker.shown || fontPicker.opening || menu.visible || preferences.visible || crossfadeMenu.visible || queueMenu.visible || songMenu.visible || musicBrowser.actionsOpenproperty bool backgroundBlur: player.backgroundBlur && platformNative.supportsBluronBackgroundBlurChanged: { platformNative.effects(root, backgroundBlur); Qt.callLater(updateMask) }property bool muted: false@@ -479,7 +484,7 @@ ApplicationWindow {readonly property int feedbackTime: SpunStyle.feedbackreadonly property int transitionTime: SpunStyle.navigateproperty int tick: 0- function useLocal() { useJellyfin=false;+ function useLocal() { useJellyfin=false;useSubsonic=false;useYoutube=falseif (useCider && root.ciderService.playing) root.ciderService.pause()useCider = false@@ -536,13 +541,13 @@ ApplicationWindow {Shortcut { sequence: "Alt+G"; enabled: actionNotice.shown && actionNotice.canUndo && !root.menuOpen; onActivated: noticeUndo.forceActiveFocus(Qt.ShortcutFocusReason) }Shortcut { sequence: "Ctrl+K"; enabled: !root.menuOpen || quickJump.visible; onActivated: quickJump.visible ? quickJump.close() : root.openQuickJump() }- Shortcut { sequence: "Space"; enabled: !(root.activeFocusItem instanceof AbstractButton) && !(root.useCider && root.queueOpen && trackList.activeFocus) && !(root.libraryOpen && musicBrowser.item && musicBrowser.item.trackListFocused) && !root.editingText && !root.menuOpen; onActivated: root.deckPlayer.count ? root.deckPlayer.toggle() : (root.useYoutube || root.useJellyfin) ? root.openLibrary() : root.useCider ? root.ciderService.toggle() : files.open() }+ Shortcut { sequence: "Space"; enabled: !(root.activeFocusItem instanceof AbstractButton) && !(root.useCider && root.queueOpen && trackList.activeFocus) && !(root.libraryOpen && musicBrowser.item && musicBrowser.item.trackListFocused) && !root.editingText && !root.menuOpen; onActivated: root.deckPlayer.count ? root.deckPlayer.toggle() : (root.useYoutube || root.useServer) ? root.openLibrary() : root.useCider ? root.ciderService.toggle() : files.open() }Shortcut { sequence: "Ctrl+V"; enabled: !root.editingText && !root.menuOpen; onActivated: root.openMusicLink("", true) }Shortcut { sequence: "Ctrl+O"; enabled: !root.menuOpen; onActivated: files.open() }Shortcut { sequence: "Ctrl+Shift+O"; enabled: !root.menuOpen; onActivated: folder.open() }Shortcut { sequence: "Ctrl+Q"; onActivated: Qt.quit() }- Shortcut { sequence: "Ctrl+F"; enabled: !root.menuOpen; onActivated: root.libraryOpen ? (root.useJellyfin ? jellyfinBrowser.item.focusSearch() : root.useYoutube ? youtubeBrowser.item.focusSearch() : musicBrowser.focusSearch()) : root.openQueueSearch() }- Shortcut { sequence: "Ctrl+B"; enabled: (root.useCider || root.useYoutube || root.useJellyfin) && !root.menuOpen; onActivated: root.openLibrary() }+ Shortcut { sequence: "Ctrl+F"; enabled: !root.menuOpen; onActivated: root.libraryOpen ? (root.useServer ? serverBrowser.item.focusSearch() : root.useYoutube ? youtubeBrowser.item.focusSearch() : musicBrowser.focusSearch()) : root.openQueueSearch() }+ Shortcut { sequence: "Ctrl+B"; enabled: (root.useCider || root.useYoutube || root.useServer) && !root.menuOpen; onActivated: root.openLibrary() }Shortcut { sequence: "Ctrl+L"; enabled: !root.menuOpen; onActivated: root.toggleQueue() }Shortcut { sequence: "Ctrl+M"; enabled: !root.menuOpen; onActivated: player.miniMode = !player.miniMode }Shortcut { sequence: "Right"; enabled: !(root.activeFocusItem instanceof Slider) && !root.editingText && !root.menuOpen; onActivated: root.deckPlayer.seek(root.deckPlayer.position + 5000) }@@ -552,7 +557,7 @@ ApplicationWindow {Shortcut { sequence: "Up"; enabled: !(root.activeFocusItem instanceof Slider) && !root.libraryOpen && !trackList.activeFocus && !root.menuOpen && !root.editingText && !(root.discFlipped && (albumList.activeFocus || lyricList.activeFocus)); onActivated: root.deckPlayer.volume = Math.min(1, root.deckPlayer.volume + .05) }Shortcut { sequence: "Down"; enabled: !(root.activeFocusItem instanceof Slider) && !root.libraryOpen && !trackList.activeFocus && !root.menuOpen && !root.editingText && !(root.discFlipped && (albumList.activeFocus || lyricList.activeFocus)); onActivated: root.deckPlayer.volume = Math.max(0, root.deckPlayer.volume - .05) }Shortcut { sequence: "M"; enabled: !root.editingText && !root.menuOpen; onActivated: root.toggleMute() }- Shortcut { sequence: "Escape"; onActivated: { if(root.threeDPointer || root.threeDHardwarePressed) { root.cancel3DPointer();return }; if(artworkPopup.visible) { artworkPopup.close();return }; if(root.activeSeekControl) { root.cancelSeekPreview();return }; if(scrubber.scrubbing) { scrubber.cancelScrub();return }; if(root.libraryDragging) { root.endLibraryDrag(false);return }; if(quickJump.visible) { quickJump.close();return }; if(savedQueuePicker.visible) { savedQueuePicker.close();return }; if(cleanupPopup.visible) { cleanupPopup.close();return }; if(qualityPopup.visible) { qualityPopup.close();return }; if (saveQueuePopup.visible) { saveQueuePopup.close(); return }; if (deleteQueuePopup.visible) { deleteQueuePopup.close(); return }; if (savedQueueMenu.visible) { savedQueueMenu.close(); return }; if (fontPicker.shown || fontPicker.opening) { fontPicker.close(); return }; if (preferences.visible) { preferences.close(); return }; if (crossfadeMenu.visible) { crossfadeMenu.close(); return }; if (queueMenu.visible) { queueMenu.close(); return }; if (songMenu.visible) { songMenu.close(); return }; if (jellyfinBrowser.item && jellyfinBrowser.item.actionsOpen) { jellyfinBrowser.item.closeActions(); return }; if (youtubeBrowser.item && youtubeBrowser.item.actionsOpen) { youtubeBrowser.item.closeActions(); return }; if (musicBrowser.actionsOpen) { musicBrowser.closeActions(); return }; if (menu.visible) { menu.close(); return }; if (root.queueSelectionCount > 0) { root.clearQueueSelection(); return }; if (root.queueSearchOpen) { root.closeQueueSearch(); return }; if (root.libraryOpen) { if(root.useYoutube || root.useJellyfin){root.libraryOpen=false;return}; if (musicBrowser.item && musicBrowser.item.selectionCount > 0) musicBrowser.item.clearSelection(); else if (musicBrowser.detail && musicBrowser.browser.collectionQuery.length) musicBrowser.browser.collectionQuery = ""; else if (musicBrowser.detail) musicBrowser.browser.back(); else root.libraryOpen = false; return }; if (root.discFlipped) { root.discFlipped = false; return }; root.queueOpen = false; root.helpOpen = false; menu.close(); if (root.miniMode) player.miniMode = false } }+ Shortcut { sequence: "Escape"; onActivated: { if(root.threeDPointer || root.threeDHardwarePressed) { root.cancel3DPointer();return }; if(artworkPopup.visible) { artworkPopup.close();return }; if(root.activeSeekControl) { root.cancelSeekPreview();return }; if(scrubber.scrubbing) { scrubber.cancelScrub();return }; if(root.libraryDragging) { root.endLibraryDrag(false);return }; if(quickJump.visible) { quickJump.close();return }; if(savedQueuePicker.visible) { savedQueuePicker.close();return }; if(cleanupPopup.visible) { cleanupPopup.close();return }; if(qualityPopup.visible) { qualityPopup.close();return }; if (saveQueuePopup.visible) { saveQueuePopup.close(); return }; if (deleteQueuePopup.visible) { deleteQueuePopup.close(); return }; if (savedQueueMenu.visible) { savedQueueMenu.close(); return }; if (fontPicker.shown || fontPicker.opening) { fontPicker.close(); return }; if (preferences.visible) { preferences.close(); return }; if (crossfadeMenu.visible) { crossfadeMenu.close(); return }; if (queueMenu.visible) { queueMenu.close(); return }; if (songMenu.visible) { songMenu.close(); return }; if (serverBrowser.item && serverBrowser.item.actionsOpen) { serverBrowser.item.closeActions(); return }; if (youtubeBrowser.item && youtubeBrowser.item.actionsOpen) { youtubeBrowser.item.closeActions(); return }; if (musicBrowser.actionsOpen) { musicBrowser.closeActions(); return }; if (menu.visible) { menu.close(); return }; if (root.queueSelectionCount > 0) { root.clearQueueSelection(); return }; if (root.queueSearchOpen) { root.closeQueueSearch(); return }; if (root.libraryOpen) { if(root.useYoutube || root.useServer){root.libraryOpen=false;return}; if (musicBrowser.item && musicBrowser.item.selectionCount > 0) musicBrowser.item.clearSelection(); else if (musicBrowser.detail && musicBrowser.browser.collectionQuery.length) musicBrowser.browser.collectionQuery = ""; else if (musicBrowser.detail) musicBrowser.browser.back(); else root.libraryOpen = false; return }; if (root.discFlipped) { root.discFlipped = false; return }; root.queueOpen = false; root.helpOpen = false; menu.close(); if (root.miniMode) player.miniMode = false } }Shortcut { sequence: "Y"; enabled: !root.editingText && !root.menuOpen; onActivated: { if (root.deckPlayer.count) { root.discFlipped = true; root.lyricsView = !root.lyricsView } } }Shortcut { sequence: "F"; enabled: !root.editingText && !root.menuOpen; onActivated: root.flipDisc() }Shortcut { sequence: "F1"; enabled: !root.menuOpen; onActivated: root.helpOpen = !root.helpOpen }@@ -608,37 +613,38 @@ ApplicationWindow {id: badgeobjectName: "sourceBar"visible: !root.miniMode- x: (root.playerWidth - width) / 2; y: 13; width: platformNative.hyprland ? 424 : 512; height: 48; radius: 24+ x: (root.playerWidth - width) / 2; y: 13; width: platformNative.hyprland ? 504 : 512; height: 48; radius: 24+ readonly property real tabWidth: platformNative.hyprland ? 80 : 64color: root.surfaceborder.width: 0MouseArea { anchors.fill: parent; onPressed: root.startSystemMove() }Rectangle {objectName: "sourceIndicator"- SpunSpring { id: sourceMotion; targetValue: root.useJellyfin ? 296 : root.useYoutube ? 216 : root.useCider ? 136 : 56 }- x: sourceMotion.value; y: 6; width: 80; height: 36; radius: 18+ SpunSpring { id: sourceMotion; targetValue: 56 + badge.tabWidth * (root.useSubsonic ? 4 : root.useJellyfin ? 3 : root.useYoutube ? 2 : root.useCider ? 1 : 0) }+ x: sourceMotion.value; y: 6; width: badge.tabWidth; height: 36; radius: 18color: root.inset}Row {id: sourceTabsfunction focusTab(index) {- const button = sourceTabItems.itemAt(Math.max(0, Math.min(3, index)))+ const button = sourceTabItems.itemAt(Math.max(0, Math.min(4, index)))if (button) button.forceActiveFocus(Qt.TabFocusReason)}x: 56; y: 6; spacing: 0Repeater {id: sourceTabItems- model: ["Local", "Cider", "YouTube", "Jellyfin"]+ model: ["Local", "Cider", "YouTube", "Jellyfin", "Subsonic"]AbstractButton {id: sourceTab- objectName: index === 0 ? "localSourceButton" : index === 1 ? "ciderSourceButton" : index === 2 ? "youtubeSourceButton" : "jellyfinSourceButton"+ objectName: index === 0 ? "localSourceButton" : index === 1 ? "ciderSourceButton" : index === 2 ? "youtubeSourceButton" : index === 3 ? "jellyfinSourceButton" : "subsonicSourceButton"required property string modelDatarequired property int index- width: 80; height: 36+ width: badge.tabWidth; height: 36focusPolicy: Qt.StrongFocushoverEnabled: trueAccessible.name: modelDataAccessible.role: Accessible.PageTab- Accessible.selectable: true; Accessible.selected: (root.useJellyfin ? 3 : root.useYoutube ? 2 : root.useCider ? 1 : 0) === index+ Accessible.selectable: true; Accessible.selected: (root.useSubsonic ? 4 : root.useJellyfin ? 3 : root.useYoutube ? 2 : root.useCider ? 1 : 0) === indexKeys.onShortcutOverride: event => {if (event.modifiers === Qt.NoModifier && [Qt.Key_Left, Qt.Key_Right, Qt.Key_Home, Qt.Key_End].includes(event.key)) event.accepted = true}@@ -646,7 +652,7 @@ ApplicationWindow {Keys.onRightPressed: sourceTabs.focusTab(index + 1)Keys.onPressed: event => {if (event.key === Qt.Key_Home) { sourceTabs.focusTab(0); event.accepted = true }- else if (event.key === Qt.Key_End) { sourceTabs.focusTab(3); event.accepted = true }+ else if (event.key === Qt.Key_End) { sourceTabs.focusTab(4); event.accepted = true }else event.accepted = false}@@ -658,26 +664,26 @@ ApplicationWindow {SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: root.ink; pressed: sourceTab.down; focused: sourceTab.visualFocus; hovered: sourceTab.hovered }border.width: sourceTab.visualFocus ? 2 : 0; border.color: root.accent}- contentItem: SpunText { text: parent.modelData; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter; color: ((root.useJellyfin ? 3 : root.useYoutube ? 2 : root.useCider ? 1 : 0) === parent.index) ? root.accent : root.mutedInk; font.pixelSize: SpunStyle.body; font.weight: Font.Medium }- onClicked: { if(index===0)root.useLocal(); else if(index===1){root.useYoutube=false;root.useCider=true;if(player.ciderAutoStart)root.ciderService.ensureRunning()} else if(index===2){root.useYoutube=true;root.libraryOpen=true} else {root.useJellyfin=true;root.libraryOpen=true} }+ contentItem: SpunText { text: parent.modelData; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter; color: ((root.useSubsonic ? 4 : root.useJellyfin ? 3 : root.useYoutube ? 2 : root.useCider ? 1 : 0) === parent.index) ? root.accent : root.mutedInk; font.pixelSize: SpunStyle.body; font.weight: Font.Medium }+ onClicked: { if(index===0)root.useLocal(); else if(index===1){root.useYoutube=false;root.useCider=true;if(player.ciderAutoStart)root.ciderService.ensureRunning()} else if(index===2){root.useYoutube=true;root.libraryOpen=true} else if(index===3){root.useJellyfin=true;root.libraryOpen=true} else {root.useSubsonic=true;root.libraryOpen=true} }}}}IconButton {objectName: "addMusicButton"- x: 4; y: 4; glyphName: root.useCider || root.useYoutube || root.useJellyfin ? "search" : "plus"; tip: root.useCider || root.useYoutube || root.useJellyfin ? "Browse music · Ctrl+B" : "Add music · Ctrl+O"+ x: 4; y: 4; glyphName: root.useCider || root.useYoutube || root.useServer ? "search" : "plus"; tip: root.useCider || root.useYoutube || root.useServer ? "Browse music · Ctrl+B" : "Add music · Ctrl+O"selected: root.libraryOpen; fill: root.libraryOpen ? root.inset : "transparent"- ink: root.libraryOpen ? root.accent : root.ink; hoverFill: root.hoverFill; onClicked: root.useCider || root.useYoutube || root.useJellyfin ? root.openLibrary() : files.open()+ ink: root.libraryOpen ? root.accent : root.ink; hoverFill: root.hoverFill; onClicked: root.useCider || root.useYoutube || root.useServer ? root.openLibrary() : files.open()}IconButton {objectName: "queueButton"- x: 380; y: 4; glyphName: "queue"; tip: "Queue · Ctrl+L"+ x: 60 + 5 * badge.tabWidth; y: 4; glyphName: "queue"; tip: "Queue · Ctrl+L"selected: root.queueOpen; fill: root.queueOpen ? root.inset : "transparent"ink: root.queueOpen ? root.accent : root.ink; hoverFill: root.hoverFillonClicked: root.queueOpen = !root.queueOpen}- IconButton { visible: !platformNative.hyprland; x: 424; y: 4; glyphName: "minus"; tip: "Minimize"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: root.showMinimized() }- IconButton { visible: !platformNative.hyprland; x: 468; y: 4; glyphName: "close"; tip: "Close Spun"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: Qt.quit() }+ IconButton { visible: !platformNative.hyprland; x: 104 + 5 * badge.tabWidth; y: 4; glyphName: "minus"; tip: "Minimize"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: root.showMinimized() }+ IconButton { visible: !platformNative.hyprland; x: 148 + 5 * badge.tabWidth; y: 4; glyphName: "close"; tip: "Close Spun"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: Qt.quit() }}Item {@@ -1375,7 +1381,7 @@ ApplicationWindow {Row {x: 8; y: 4; spacing: 0IconButton { id: miniPrevious; objectName: "miniPrevious"; glyphName: "previous"; tip: "Previous track"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canPrevious : root.deckPlayer.count > 0; onClicked: root.deckPlayer.previous() }- IconButton { id: miniPlay; objectName: "miniPlay"; glyphSize: 26; width: 48; glyphName: root.deckPlayer.playing ? "pause" : "play"; tip: root.deckPlayer.playing ? "Pause" : "Play"; fill: root.accent; ink: theme.colors.onAccent; hoverFill: Qt.lighter(root.accent,1.08); onClicked: root.deckPlayer.count ? root.deckPlayer.toggle() : (root.useYoutube || root.useJellyfin) ? root.openLibrary() : root.useCider ? root.ciderService.toggle() : files.open() }+ IconButton { id: miniPlay; objectName: "miniPlay"; glyphSize: 26; width: 48; glyphName: root.deckPlayer.playing ? "pause" : "play"; tip: root.deckPlayer.playing ? "Pause" : "Play"; fill: root.accent; ink: theme.colors.onAccent; hoverFill: Qt.lighter(root.accent,1.08); onClicked: root.deckPlayer.count ? root.deckPlayer.toggle() : (root.useYoutube || root.useServer) ? root.openLibrary() : root.useCider ? root.ciderService.toggle() : files.open() }IconButton { id: miniNext; objectName: "miniNext"; Accessible.description: miniPeek.visible ? miniPeek.summary : ""; showTip: false; glyphName: "next"; tip: "Next track"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canNext : root.deckPlayer.count > 0; onClicked: root.deckPlayer.next()NextTrackTip { id: miniPeek; app: root; visible: root.miniMode && miniNext.enabled && (miniNext.hovered || miniNext.visualFocus) && !miniNext.down && !quickJump.visible }}@@ -1392,22 +1398,22 @@ ApplicationWindow {MouseArea { anchors.fill: parent; onPressed: root.startSystemMove() }SpunText {id: playerSongTitle; objectName: "songTitle"- x: 24; y: 16; width: root.useCider || root.useYoutube || root.useJellyfin ? 238 : 272+ x: 24; y: 16; width: root.useCider || root.useYoutube || root.useServer ? 238 : 272text: root.deckPlayer.title; color: root.ink; elide: Text.ElideRightfont.pixelSize: SpunStyle.title; font.weight: Font.Normal}IconButton {objectName: "currentSongActions"- visible: root.useCider || root.useYoutube || root.useJellyfin; enabled: root.deckPlayer.count > 0+ visible: root.useCider || root.useYoutube || root.useServer; enabled: root.deckPlayer.count > 0x: 264; y: 12; width: 40; height: 40glyphName: "more"; tip: "Song actions"; ink: root.mutedInk; hoverFill: root.hoverFill- onClicked: { if(root.useJellyfin){root.libraryOpen=true;Qt.callLater(function(){if(jellyfinBrowser.item)jellyfinBrowser.item.menuFor(jellyfin.current,-1)});return}; if(root.useYoutube){root.libraryOpen=true;Qt.callLater(function(){if(youtubeBrowser.item)youtubeBrowser.item.menuFor(youtube.current,-1)});return}; menu.close(); songMenu.x = deck.x + deck.width - songMenu.width; songMenu.y = Qt.binding(function() { return deck.y - songMenu.height - 8 }); songMenu.open() }+ onClicked: { if(root.useServer){root.libraryOpen=true;Qt.callLater(function(){if(serverBrowser.item)serverBrowser.item.menuFor(serverLibrary.current,-1)});return}; if(root.useYoutube){root.libraryOpen=true;Qt.callLater(function(){if(youtubeBrowser.item)youtubeBrowser.item.menuFor(youtube.current,-1)});return}; menu.close(); songMenu.x = deck.x + deck.width - songMenu.width; songMenu.y = Qt.binding(function() { return deck.y - songMenu.height - 8 }); songMenu.open() }}AbstractButton {id: playerArtistobjectName: "playerArtistLink"x: 24; y: 44; width: 284; height: 28- enabled: (root.useCider || root.useYoutube || root.useJellyfin) && root.deckPlayer.artist.length > 0; hoverEnabled: true+ enabled: (root.useCider || root.useYoutube || root.useServer) && root.deckPlayer.artist.length > 0; hoverEnabled: trueAccessible.name: "View artist " + root.deckPlayer.artistbackground: nullonClicked: root.openArtistName(root.deckPlayer.artist)@@ -1436,7 +1442,7 @@ ApplicationWindow {glyphName: root.deckPlayer.playing ? "pause" : "play"tip: root.deckPlayer.playing ? "Pause · Space" : "Play · Space"fill: root.accent; ink: theme.colors.onAccent; hoverFill: Qt.lighter(root.accent, 1.08)- onClicked: root.deckPlayer.count ? root.deckPlayer.toggle() : (root.useYoutube || root.useJellyfin) ? root.openLibrary() : root.useCider ? root.ciderService.toggle() : files.open()+ onClicked: root.deckPlayer.count ? root.deckPlayer.toggle() : (root.useYoutube || root.useServer) ? root.openLibrary() : root.useCider ? root.ciderService.toggle() : files.open()}IconButton { objectName: "nextButton"; y: 4; glyphName: "next"; tip: "Next track · Ctrl+→"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canNext : root.deckPlayer.count > 0; onClicked: root.deckPlayer.next() }IconButton {@@ -1466,7 +1472,7 @@ ApplicationWindow {objectName: "demoHint"x: deck.x + 3; y: 705 + root.mixerHeightExtra; width: 400; horizontalAlignment: Text.AlignHCentervisible: !root.miniMode- text: root.useCider || root.useYoutube || root.useJellyfin || player.count ? "" : "Play demo"+ text: root.useCider || root.useYoutube || root.useServer || player.count ? "" : "Play demo"color: root.mutedInk; font.pixelSize: SpunStyle.captionMouseArea { anchors.fill: parent; cursorShape: Qt.PointingHandCursor; onClicked: { root.useLocal(); player.demo() } }}@@ -1767,8 +1773,8 @@ ApplicationWindow {}onClicked: root.ciderService.raise()}- IconButton { visible: !root.useCider && !root.useYoutube && !root.useJellyfin; x: 0; anchors.verticalCenter: parent.verticalCenter; glyphName: "plus"; tip: "Add tracks"; ink: root.ink; hoverFill: root.hoverFill; onClicked: files.open() }- IconButton { visible: !root.useCider && !root.useYoutube && !root.useJellyfin; x: SpunStyle.target + SpunStyle.smallGap; anchors.verticalCenter: parent.verticalCenter; glyphName: "folder"; tip: "Add music folder"; ink: root.ink; hoverFill: root.hoverFill; onClicked: folder.open() }+ IconButton { visible: !root.useCider && !root.useYoutube && !root.useServer; x: 0; anchors.verticalCenter: parent.verticalCenter; glyphName: "plus"; tip: "Add tracks"; ink: root.ink; hoverFill: root.hoverFill; onClicked: files.open() }+ IconButton { visible: !root.useCider && !root.useYoutube && !root.useServer; x: SpunStyle.target + SpunStyle.smallGap; anchors.verticalCenter: parent.verticalCenter; glyphName: "folder"; tip: "Add music folder"; ink: root.ink; hoverFill: root.hoverFill; onClicked: folder.open() }Button {id: clearQueueButtonvisible: !root.useCider; anchors.right: parent.right; anchors.verticalCenter: parent.verticalCenter; width: 76; height: SpunStyle.target@@ -1790,7 +1796,7 @@ ApplicationWindow {Loader {id: musicBrowserx: jewelCase.x; anchors.top: jewelCase.top; width: jewelCase.width; anchors.bottom: deck.bottom- visible: root.libraryOpen && !root.useYoutube && !root.useJellyfin+ visible: root.libraryOpen && !root.useYoutube && !root.useServeractive: false// Build the browser on its first opening, then retain its scroll, search,// focus and transition state for every subsequent visit.@@ -1811,12 +1817,13 @@ ApplicationWindow {sourceComponent: YoutubePanel { app: root }}Loader {- id: jellyfinBrowser+ id: serverBrowserx: youtubeBrowser.x; y: youtubeBrowser.y; width: youtubeBrowser.width; height: youtubeBrowser.height- active: root.useJellyfin; visible: root.useJellyfin && root.libraryOpen- sourceComponent: JellyfinPanel { app: root }+ active: root.useServer; visible: root.useServer && root.libraryOpen+ sourceComponent: RemoteLibraryPanel { app: root; provider: root.serverLibrary }}Connections { target: jellyfin; function onFeedback(message,error){root.notifyAction(message,error)} }+ Connections { target: subsonic; function onFeedback(message,error){root.notifyAction(message,error)} }Connections { target: youtube; function onFeedback(message,error){root.notifyAction(message,error)} }function previewQueueCleanup(mode) {@@ -2130,7 +2137,7 @@ ApplicationWindow {SettingsAction { text: "Add tracks"; glyphName: "plus"; hint: "Ctrl+O"; onTriggered: files.open() }SettingsAction { text: "Add music folder"; glyphName: "folder"; hint: "Ctrl+Shift+O"; onTriggered: folder.open() }- SettingsAction { text: "Change artwork"; glyphName: "artwork"; enabled: !root.useCider && !root.useYoutube && !root.useJellyfin && player.count > 0; onTriggered: cover.open() }+ SettingsAction { text: "Change artwork"; glyphName: "artwork"; enabled: !root.useCider && !root.useYoutube && !root.useServer && player.count > 0; onTriggered: cover.open() }SettingsGap {}SettingsAction { objectName: "quickJumpAction"; text: "Quick jump"; hint: "Ctrl+K"; glyphName: "search"; onTriggered: root.openQuickJump() }SettingsAction { objectName: "flipDiscAction"; text: root.discFlipped ? "Show artwork" : "Flip disc"; glyphName: "flip"; hint: "F"; enabled: root.deckPlayer.count > 0; onTriggered: root.flipDisc() }diff --git a/qml/JellyfinPanel.qml b/qml/RemoteLibraryPanel.qmlsimilarity index 81%rename from qml/JellyfinPanel.qmlrename to qml/RemoteLibraryPanel.qmlindex f9b8025..3c17dbb 100644--- a/qml/JellyfinPanel.qml+++ b/qml/RemoteLibraryPanel.qml@@ -4,9 +4,12 @@ import QtQml.ModelsRectangle {id: panel- objectName: "jellyfinPanel"+ objectName: panel.prefix + "Panel"+ required property var provider+ readonly property string prefix: provider.server.scheme+ readonly property string serviceLabel: prefix === "subsonic" ? "Navidrome / Subsonic" : provider.server.serviceNamerequired property var app- readonly property var server: jellyfin.server+ readonly property var server: provider.serverproperty string searchFilter: "albums"property var selected: ({})property int selectedIndex: -1@@ -14,10 +17,15 @@ Rectangle {property int revision: 0property int artworkRevision: 0readonly property bool actionsOpen: actions.visible || pageActions.visible || connection.visible || nameDialog.visible || playlistPicker.visible || deleteDialog.visible || folderMenu.visible || qualityMenu.visible- readonly property bool playlistPage: jellyfin.page === "playlist"- readonly property string selectedPage: jellyfin.page === "album" ? "albums" : jellyfin.page === "artist" ? "artists" : playlistPage ? "playlists" : jellyfin.page+ readonly property bool playlistPage: provider.page === "playlist"+ readonly property string selectedPage: provider.page === "album" ? "albums" : provider.page === "artist" ? "artists" : playlistPage ? "playlists" : provider.page+ onSelectedPageChanged: {+ if (["albums", "artists", "songs", "playlists"].includes(selectedPage))+ searchFilter = selectedPage;+ }color: app.surfaceradius: SpunStyle.panelRadius+ onProviderChanged: { closeActions(); search.text = ""; selected = ({}); selectedIndex = -1; searchFilter = "albums" }function closeActions() {actions.close();pageActions.close();@@ -69,7 +77,7 @@ Rectangle {}}Connections {- target: jellyfin+ target: providerfunction onChanged() {panel.revision++;}@@ -107,14 +115,14 @@ Rectangle {tabItems.itemAt(Math.max(0, Math.min(tabItems.count - 1, i))).forceActiveFocus(Qt.TabFocusReason);}Accessible.role: Accessible.PageTabList- Accessible.name: "Jellyfin library"+ Accessible.name: "Jellyfin library".replace("Jellyfin", panel.serviceLabel)Repeater {id: tabItemsmodel: ["albums", "artists", "songs", "playlists"]SpunChoiceButton {required property string modelDatarequired property int index- objectName: "jellyfinTab_" + modelData+ objectName: panel.prefix + "Tab_" + modelDatawidth: (panel.width - 24) / 4text: modelData.charAt(0).toUpperCase() + modelData.slice(1)ink: panel.app.ink@@ -145,7 +153,7 @@ Rectangle {onClicked: {panel.searchFilter = modelData;search.text = "";- jellyfin.show(modelData);+ provider.show(modelData);}}}@@ -154,13 +162,13 @@ Rectangle {visible: !server.connectedx: 24y: 24- text: "Jellyfin"+ text: "Jellyfin".replace("Jellyfin", panel.serviceLabel)font.pixelSize: SpunStyle.titlecolor: panel.app.ink}SpunSearchField {id: search- objectName: "jellyfinSearch"+ objectName: panel.prefix + "Search"app: panel.appvisible: server.connectedx: 16@@ -169,7 +177,7 @@ Rectangle {height: 44maximumLength: 512placeholderText: "Search " + panel.searchFilter- onAccepted: jellyfin.search(text, panel.searchFilter)+ onAccepted: provider.search(text, panel.searchFilter)Keys.onDownPressed: {list.forceActiveFocus();if (list.count)@@ -183,8 +191,8 @@ Rectangle {glyphName: "back"tip: "Back"ink: panel.app.ink- enabled: jellyfin.canBack- onClicked: jellyfin.back()+ enabled: provider.canBack+ onClicked: provider.back()}SpunText {visible: server.connected@@ -193,14 +201,14 @@ Rectangle {width: parent.width - 104height: 28verticalAlignment: Text.AlignVCenter- text: jellyfin.heading+ text: provider.headingfont.pixelSize: SpunStyle.bodyfont.weight: Font.Mediumcolor: panel.app.inkelide: Text.ElideRight}IconButton {- objectName: "jellyfinPageActions"+ objectName: panel.prefix + "PageActions"x: parent.width - 48y: server.connected ? 114 : 16glyphName: "more"@@ -223,7 +231,7 @@ Rectangle {}SpunButton {id: connectButton- objectName: "jellyfinConnect"+ objectName: panel.prefix + "Connect"text: server.connecting ? "Connecting…" : "Connect"enabled: !server.connectingtonal: true@@ -232,39 +240,39 @@ Rectangle {SpunLoading {width: parent.widthvisible: server.connecting- label: "Connecting to Jellyfin"+ label: "Connecting to Jellyfin".replace("Jellyfin", panel.serviceLabel)}}SpunLoading {- objectName: "jellyfinLoading"+ objectName: panel.prefix + "Loading"x: 24y: 160width: parent.width - 48- visible: server.connected && jellyfin.busy+ visible: server.connected && provider.busylabel: "Loading music"}ListView {id: list- objectName: "jellyfinResults"+ objectName: panel.prefix + "Results"x: 8y: 164width: parent.width - 16height: parent.height - y - 56- visible: server.connected && !jellyfin.error.length- model: jellyfin.items+ visible: server.connected && !provider.error.length+ model: provider.itemsclip: truespacing: 2boundsBehavior: Flickable.StopAtBoundsScrollBar.vertical: ScrollBar {}Keys.onReturnPressed: if (currentIndex >= 0)- jellyfin.open(jellyfin.items[currentIndex])+ provider.open(provider.items[currentIndex])Keys.onEnterPressed: if (currentIndex >= 0)- jellyfin.open(jellyfin.items[currentIndex])+ provider.open(provider.items[currentIndex])delegate: ItemDelegate {id: rowrequired property var modelDatarequired property int index- objectName: "jellyfinResult_" + index+ objectName: panel.prefix + "Result_" + indexwidth: list.widthheight: 68focusPolicy: Qt.StrongFocus@@ -286,7 +294,7 @@ Rectangle {}onClicked: {list.currentIndex = index;- jellyfin.open(modelData);+ provider.open(modelData);}Image {x: 8@@ -295,7 +303,7 @@ Rectangle {height: 44source: {panel.artworkRevision;- return jellyfin.artwork(row.modelData.id || "");+ return provider.artwork(row.modelData.id || "");}sourceSize: Qt.size(88, 88)asynchronous: true@@ -333,7 +341,7 @@ Rectangle {elide: Text.ElideRight}IconButton {- objectName: "jellyfinRowMenu_" + row.index+ objectName: panel.prefix + "RowMenu_" + row.indexx: parent.width - 44y: 12glyphName: "more"@@ -348,28 +356,28 @@ Rectangle {y: 210width: parent.width - 48spacing: 12- visible: server.connected && !jellyfin.busy && (!!jellyfin.error.length || !jellyfin.items.length)+ visible: server.connected && !provider.busy && (!!provider.error.length || !provider.items.length)SpunText {width: parent.width- text: jellyfin.error || "No results"+ text: provider.error || "No results"wrapMode: Text.WordWrap- color: jellyfin.error.length ? theme.colors.error : panel.app.mutedInk+ color: provider.error.length ? theme.colors.error : panel.app.mutedInkfont.pixelSize: SpunStyle.body}SpunButton {text: "Retry"- visible: !!jellyfin.error.length- onClicked: jellyfin.reload()+ visible: !!provider.error.length+ onClicked: provider.reload()}}SpunButton {- objectName: "jellyfinMore"- visible: server.connected && jellyfin.more- enabled: !jellyfin.busy+ objectName: panel.prefix + "More"+ visible: server.connected && provider.more+ enabled: !provider.busyanchors.horizontalCenter: parent.horizontalCentery: parent.height - 48- text: jellyfin.busy ? "Loading…" : "Load more"- onClicked: jellyfin.loadMore()+ text: provider.busy ? "Loading…" : "Load more"+ onClicked: provider.loadMore()}component Action: MenuItem {id: action@@ -417,24 +425,24 @@ Rectangle {PopupMenu {id: pageActionsAction {- text: jellyfin.more ? "Play listed songs" : "Play songs"- enabled: !jellyfin.busy && jellyfin.items.some(row => row.kind === "song")- onTriggered: jellyfin.playItems(jellyfin.items)+ text: provider.more ? "Play listed songs" : "Play songs"+ enabled: !provider.busy && provider.items.some(row => row.kind === "song")+ onTriggered: provider.playItems(provider.items)}Action {text: "Favorites"- onTriggered: jellyfin.show("favorites")+ onTriggered: provider.show("favorites")}Action {text: "Genres"- onTriggered: jellyfin.show("genres")+ onTriggered: provider.show("genres")}Action {text: "Recently played"- onTriggered: jellyfin.show("recent")+ onTriggered: provider.show("recent")}Action {- objectName: "jellyfinNewPlaylist"+ objectName: panel.prefix + "NewPlaylist"text: "New playlist…"onTriggered: {panel.renameId = "";@@ -444,29 +452,29 @@ Rectangle {}Action {text: "Rename playlist…"- visible: panel.playlistPage && !!jellyfin.collection.editable+ visible: panel.playlistPage && !!provider.collection.editableheight: visible ? 40 : 0- enabled: !jellyfin.actionBusy+ enabled: !provider.actionBusyonTriggered: {- panel.renameId = jellyfin.collection.remoteId;- nameField.text = jellyfin.heading;+ panel.renameId = provider.collection.remoteId;+ nameField.text = provider.heading;nameDialog.open();}}Action {text: "Delete playlist…"- visible: panel.playlistPage && !!jellyfin.collection.deletable+ visible: panel.playlistPage && !!provider.collection.deletableheight: visible ? 40 : 0- enabled: !jellyfin.actionBusy+ enabled: !provider.actionBusyonTriggered: deleteDialog.open()}Action {text: "Refresh"- enabled: !jellyfin.busy- onTriggered: jellyfin.reload()+ enabled: !provider.busy+ onTriggered: provider.reload()}Action {- objectName: "jellyfinSettings"+ objectName: panel.prefix + "Settings"text: "Server settings…"onTriggered: connection.open()}@@ -475,20 +483,20 @@ Rectangle {id: actionsAction {text: panel.selected.kind === "song" ? "Play" : "Open"- onTriggered: jellyfin.open(panel.selected)+ onTriggered: provider.open(panel.selected)}Action {text: "Add to queue"enabled: panel.selected.kind === "song"- onTriggered: jellyfin.enqueue(panel.selected)+ onTriggered: provider.enqueue(panel.selected)}Action {text: {panel.revision;- return jellyfin.favorite(panel.selected.id || "") ? "Remove from favorites" : "Add to favorites";+ return provider.favorite(panel.selected.id || "") ? "Remove from favorites" : "Add to favorites";}- enabled: !jellyfin.actionBusy- onTriggered: jellyfin.toggleFavorite(panel.selected)+ enabled: !provider.actionBusy+ onTriggered: provider.toggleFavorite(panel.selected)}Action {text: "Add to playlist…"@@ -498,8 +506,8 @@ Rectangle {Action {text: "Open album"enabled: !!panel.selected.albumId- onTriggered: jellyfin.open({- source: "jellyfin",+ onTriggered: provider.open({+ source: "provider",server: panel.selected.server,kind: "album",remoteId: panel.selected.albumId,@@ -509,8 +517,8 @@ Rectangle {Action {text: "Open artist"enabled: !!panel.selected.artistId- onTriggered: jellyfin.open({- source: "jellyfin",+ onTriggered: provider.open({+ source: "provider",server: panel.selected.server,kind: "artist",remoteId: panel.selected.artistId,@@ -519,28 +527,28 @@ Rectangle {}Action {text: "Remove from playlist"- visible: panel.playlistPage && !!jellyfin.collection.editable+ visible: panel.playlistPage && !!provider.collection.editableheight: visible ? 40 : 0- enabled: !jellyfin.actionBusy- onTriggered: jellyfin.removeFromPlaylist(panel.selected)+ enabled: !provider.actionBusy+ onTriggered: provider.removeFromPlaylist(panel.selected)}Action {text: "Move up"- visible: panel.playlistPage && !!jellyfin.collection.editable+ visible: panel.playlistPage && !!provider.collection.editableheight: visible ? 40 : 0- enabled: !jellyfin.actionBusy && panel.selectedIndex > 0- onTriggered: jellyfin.movePlaylistItem(panel.selectedIndex, panel.selectedIndex - 1)+ enabled: !provider.actionBusy && panel.selectedIndex > 0+ onTriggered: provider.movePlaylistItem(panel.selectedIndex, panel.selectedIndex - 1)}Action {text: "Move down"- visible: panel.playlistPage && !!jellyfin.collection.editable+ visible: panel.playlistPage && !!provider.collection.editableheight: visible ? 40 : 0- enabled: !jellyfin.actionBusy && panel.selectedIndex >= 0 && panel.selectedIndex < jellyfin.items.length - 1- onTriggered: jellyfin.movePlaylistItem(panel.selectedIndex, panel.selectedIndex + 1)+ enabled: !provider.actionBusy && panel.selectedIndex >= 0 && panel.selectedIndex < provider.items.length - 1+ onTriggered: provider.movePlaylistItem(panel.selectedIndex, panel.selectedIndex + 1)}Action {text: "Copy link"- onTriggered: jellyfin.copyLink(panel.selected)+ onTriggered: provider.copyLink(panel.selected)}}component LibraryDialog: Dialog {@@ -591,8 +599,8 @@ Rectangle {}LibraryDialog {id: connection- objectName: "jellyfinConnection"- title: server.connected ? "Jellyfin settings" : "Connect to Jellyfin"+ objectName: panel.prefix + "Connection"+ title: server.connected ? server.serviceName + " settings" : "Connect to Jellyfin".replace("Jellyfin", panel.serviceLabel)standardButtons: Dialog.CloseonAboutToShow: {address.text = server.address;@@ -605,7 +613,7 @@ Rectangle {}onClosed: password.text = ""contentItem: ScrollView {- implicitHeight: Math.min(connectionFields.implicitHeight, Math.max(180, panel.height - 190))+ implicitHeight: Math.min(connectionFields.implicitHeight, Math.max(180, panel.height - connection.header.implicitHeight - connection.footer.implicitHeight - connection.topPadding - connection.bottomPadding - 2 * connection.spacing - 32))contentWidth: availableWidthclip: trueColumn {@@ -614,12 +622,12 @@ Rectangle {spacing: 12SpunSearchField {id: address- objectName: "jellyfinAddress"+ objectName: panel.prefix + "Address"app: panel.appsearchIcon: falsewidth: parent.widthlabelText: "Server URL"- Accessible.name: "Jellyfin server URL"+ Accessible.name: "Jellyfin server URL".replace("Jellyfin", panel.serviceLabel)enabled: !server.connectingmaximumLength: 2048onActiveFocusChanged: if (!activeFocus)@@ -627,7 +635,7 @@ Rectangle {}SpunSearchField {id: username- objectName: "jellyfinUsername"+ objectName: panel.prefix + "Username"app: panel.appsearchIcon: falsewidth: parent.width@@ -637,7 +645,7 @@ Rectangle {}SpunSearchField {id: password- objectName: "jellyfinPassword"+ objectName: panel.prefix + "Password"app: panel.appsearchIcon: falsewidth: parent.width@@ -649,7 +657,7 @@ Rectangle {}CheckBox {id: remember- objectName: "jellyfinRemember"+ objectName: panel.prefix + "Remember"width: parent.widthimplicitHeight: Math.max(48, rememberLabel.implicitHeight + 16)text: "Remember connection"@@ -718,7 +726,7 @@ Rectangle {}SpunButton {id: signIn- objectName: "jellyfinSignIn"+ objectName: panel.prefix + "SignIn"text: server.connecting ? "Connecting…" : server.connected ? "Reconnect" : "Connect"tonal: trueenabled: !server.connecting && address.text.trim().length > 0 && username.text.trim().length > 0@@ -738,7 +746,7 @@ Rectangle {onClicked: panel.openMenu(folderMenu, this)}SpunButton {- objectName: "jellyfinQuality"+ objectName: panel.prefix + "Quality"visible: server.connectedwidth: parent.widthtext: server.bitrate ? server.bitrate + " kbps" : "Original quality"@@ -770,7 +778,7 @@ Rectangle {text: "All music libraries"onTriggered: {server.folder = "";- jellyfin.show("albums");+ provider.show("albums");}}Instantiator {@@ -780,7 +788,7 @@ Rectangle {text: modelData.nameonTriggered: {server.folder = modelData.id;- jellyfin.show("albums");+ provider.show("albums");}}onObjectAdded: (index, object) => folderMenu.insertItem(index + 1, object)@@ -793,7 +801,7 @@ Rectangle {model: [0, 128, 192, 320]delegate: Action {required property int modelData- objectName: "jellyfinQuality_" + modelData+ objectName: panel.prefix + "Quality_" + modelDatatext: modelData ? modelData + " kbps" : "Original quality"onTriggered: server.bitrate = modelData}@@ -803,7 +811,7 @@ Rectangle {}LibraryDialog {id: nameDialog- objectName: "jellyfinNameDialog"+ objectName: panel.prefix + "NameDialog"title: panel.renameId.length ? "Rename playlist" : "New playlist"standardButtons: Dialog.Save | Dialog.CancelonOpened: {@@ -814,13 +822,13 @@ Rectangle {}onAccepted: {if (panel.renameId.length)- jellyfin.renamePlaylist(panel.renameId, nameField.text);+ provider.renamePlaylist(panel.renameId, nameField.text);else- jellyfin.createPlaylist(nameField.text);+ provider.createPlaylist(nameField.text);}contentItem: SpunSearchField {id: nameField- objectName: "jellyfinPlaylistName"+ objectName: panel.prefix + "PlaylistName"app: panel.appsearchIcon: falselabelText: "Playlist name"@@ -844,7 +852,7 @@ Rectangle {width: playlistPicker.availableWidthtext: modelData.titleonClicked: {- jellyfin.addToPlaylist(modelData.remoteId, panel.selected);+ provider.addToPlaylist(modelData.remoteId, panel.selected);playlistPicker.close();}}@@ -855,9 +863,9 @@ Rectangle {title: "Delete playlist?"standardButtons: Dialog.Ok | Dialog.CancelonAboutToShow: standardButton(Dialog.Ok).text = "Delete"- onAccepted: jellyfin.deletePlaylist(jellyfin.collection.remoteId)+ onAccepted: provider.deletePlaylist(provider.collection.remoteId)contentItem: SpunText {- text: "This deletes the playlist from Jellyfin."+ text: "This deletes the playlist from Jellyfin.".replace("Jellyfin", panel.serviceLabel)wrapMode: Text.WordWrapcolor: panel.app.inkfont.pixelSize: SpunStyle.bodydiff --git a/scripts/test-subsonic-server.py b/scripts/test-subsonic-server.pynew file mode 100644index 0000000..e619a9e--- /dev/null+++ b/scripts/test-subsonic-server.py@@ -0,0 +1,96 @@+#!/usr/bin/env python3+"""Test Spun against a disposable Navidrome server and generated audio."""+import argparse+import concurrent.futures+import json+import hashlib+import os+from pathlib import Path+import secrets+import socket+import subprocess+import time+import urllib.error+import urllib.parse+import urllib.request+++def main():+ p=argparse.ArgumentParser(description=__doc__)+ p.add_argument('--server-binary',type=Path,required=True)+ p.add_argument('--test-binary',type=Path)+ p.add_argument('--output',type=Path,required=True)+ p.add_argument('--renderer',choices=['software','3d','native'],default='software',help='Use native only in a separate test desktop session')+ p.add_argument('--prepare-only',action='store_true',help='Leave the fixture server running for interactive development')+ args=p.parse_args()+ if not args.prepare_only and not args.test_binary:+ p.error("--test-binary is required unless --prepare-only is used")+ prepared=False+ root=args.output.resolve();root.mkdir(parents=True,exist_ok=False);root.chmod(0o700)+ for folder in ['music','data','config','cache','client-config','client-data','client-cache']:(root/folder).mkdir()+ def encode(i):+ album=root/'music'/f'Album {i//35:02}';album.mkdir(exist_ok=True)+ ext=['flac','mp3','opus'][i%3];song=album/f'{i:03}.{ext}'+ subprocess.run(['ffmpeg','-nostdin','-v','error','-f','lavfi','-i','sine=frequency=220:sample_rate=48000','-t','12','-af','volume=0.001','-metadata',f'title=Fixture {i:03}','-metadata','artist=Spun Test Artist','-metadata',f'album=Fixture Album {i//35:02}','-metadata','album_artist=Spun Test Artist','-metadata','genre=Test','-metadata',f'track={i%35+1}','-metadata','disc=1',str(song)],check=True)+ if i!=104:song.with_suffix('.lrc').write_text('[00:00.00]First test line\n[00:04.00]Second test line\n[00:08.00]Last test line\n')+ with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:list(pool.map(encode,range(105)))+ for album in (root/'music').iterdir():+ subprocess.run(['ffmpeg','-nostdin','-v','error','-f','lavfi','-i','color=c=0x88ccee:s=96x96','-frames:v','1',str(album/'cover.jpg')],check=True)+ with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]+ base=f'http://127.0.0.1:{port}/music'+ config=root/'navidrome.toml'+ config.write_text(f'Address = "127.0.0.1"\nPort = {port}\nBaseUrl = "/music"\nMusicFolder = {json.dumps(str(root/"music"))}\nDataFolder = {json.dumps(str(root/"data"))}\nCacheFolder = {json.dumps(str(root/"cache"))}\nScanSchedule = "0"\nEnableInsightsCollector = false\nLogLevel = "error"\n')+ username='spun-fixture';password=secrets.token_hex(24);token=''+ def request(path,body=None,method=None):+ headers={'Content-Type':'application/json'}+ if token: headers['X-ND-Authorization']='Bearer '+token+ req=urllib.request.Request(base+path,data=None if body is None else json.dumps(body).encode(),headers=headers,method=method)+ with urllib.request.urlopen(req,timeout=15) as res:+ data=res.read();return json.loads(data) if data else {}+ def api(method,**params):+ salt=secrets.token_hex(8)+ params.update(u=username,s=salt,t=hashlib.md5((password+salt).encode()).hexdigest(),v='1.16.1',c='SpunTest',f='json')+ result=request('/rest/'+method+'.view?'+urllib.parse.urlencode(params))['subsonic-response']+ if result['status']!='ok':raise RuntimeError('Fixture API failed: '+method)+ return result+ with (root/'server.log').open('w') as log:+ server=subprocess.Popen([str(args.server_binary.resolve()),'--configfile',str(config)],stdout=log,stderr=log)+ try:+ for _ in range(180):+ if server.poll() is not None:raise RuntimeError('Navidrome exited; see server.log')+ try:+ auth=request('/auth/createAdmin',{'username':username,'password':password});token=auth['token'];break+ except (OSError,ValueError):time.sleep(.25)+ else:raise RuntimeError('Navidrome did not start')+ request('/api/user',{'userName':'spun-reader','name':'Fixture reader','password':password,'isAdmin':False})+ api('startScan')+ for _ in range(240):+ result=api('search3',query='Fixture',songCount=200,albumCount=0,artistCount=0)+ if len(result.get('searchResult3',{}).get('song',[]))==105:break+ time.sleep(.25)+ else:raise RuntimeError('Navidrome music scan did not finish')+ fixture_env={'SPUN_TEST_SERVER':base,'SPUN_TEST_USER':username,'SPUN_TEST_PASSWORD':password,'SPUN_TEST_READER':'spun-reader','XDG_CONFIG_HOME':str(root/'client-config'),'XDG_DATA_HOME':str(root/'client-data'),'XDG_CACHE_HOME':str(root/'client-cache'),'QT_QPA_PLATFORM':'offscreen','QT_QUICK_BACKEND':'software','QT_QPA_PLATFORMTHEME':'','QT_FFMPEG_DECODING_HW_DEVICE_TYPES':',','QT_FFMPEG_ENCODING_HW_DEVICE_TYPES':','}+ env=os.environ|fixture_env+ if args.renderer=='3d':+ env.update(QT_QUICK_BACKEND='rhi',QSG_RHI_BACKEND='opengl',QSG_RENDER_LOOP='basic',LIBGL_ALWAYS_SOFTWARE='1',__GLX_VENDOR_LIBRARY_NAME='mesa',LP_NUM_THREADS='2')+ elif args.renderer=='native':+ env.update(QT_QPA_PLATFORM='wayland',QT_QUICK_BACKEND='rhi')+ # Fixture credentials remain only in this private test output directory.+ (root/'environment.json').write_text(json.dumps(fixture_env,indent=2));(root/'environment.json').chmod(0o600)+ (root/'server.pid').write_text(str(server.pid))+ print('Navidrome '+api('ping').get('serverVersion','unknown'),flush=True)+ if args.prepare_only:+ prepared=True+ print('Fixture server prepared at '+str(root),flush=True)+ return+ with (root/'test.log').open('w') as log:+ result=subprocess.run([str(args.test_binary.resolve()),'--test-subsonic','--capture-dir',str(root/'captures')],env=env,stdout=log,stderr=subprocess.STDOUT,timeout=360)+ print((root/'test.log').read_text())+ if result.returncode:raise SystemExit(result.returncode)+ finally:+ if not prepared:+ server.terminate()+ try: server.wait(timeout=15)+ except subprocess.TimeoutExpired: server.kill(); server.wait()++if __name__ == '__main__': main()diff --git a/src/jellyfin.h b/src/jellyfin.hindex 2f8394a..5f9f2a6 100644--- a/src/jellyfin.h+++ b/src/jellyfin.h@@ -1,116 +1,3 @@#pragma once-#include "jellyfinapi.h"-#include "lyrics.h"-#include "player.h"-#include <QTemporaryDir>-#include <QTimer>--class Jellyfin : public QObject {- Q_OBJECT- Q_PROPERTY(JellyfinApi *server READ server CONSTANT)- Q_PROPERTY(Player *transport READ transport CONSTANT)- Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY changed)- Q_PROPERTY(bool busy READ busy NOTIFY changed)- Q_PROPERTY(bool more READ more NOTIFY changed)- Q_PROPERTY(bool actionBusy READ actionBusy NOTIFY changed)- Q_PROPERTY(QString error READ error NOTIFY changed)- Q_PROPERTY(QString page READ page NOTIFY changed)- Q_PROPERTY(QString heading READ heading NOTIFY changed)- Q_PROPERTY(QVariantList items READ items NOTIFY changed)- Q_PROPERTY(QVariantMap collection READ collection NOTIFY changed)- Q_PROPERTY(QVariantMap current READ current NOTIFY changed)- Q_PROPERTY(bool canBack READ canBack NOTIFY changed)- Q_PROPERTY(bool active READ active WRITE setActive NOTIFY changed)- Q_PROPERTY(QVariantList lines READ lines NOTIFY changed)- Q_PROPERTY(bool loading READ loading NOTIFY changed)- Q_PROPERTY(QString message READ message NOTIFY changed)- Q_PROPERTY(bool timed READ timed NOTIFY changed)- Q_PROPERTY(int currentIndex READ currentIndex NOTIFY currentIndexChanged)-public:- explicit Jellyfin(const QString &directory, bool restore = true,- QObject *parent = nullptr);- ~Jellyfin() override;- JellyfinApi *server() { return &m_api; }- Player *transport() { return &m_player; }- bool enabled() const { return m_enabled; }- void setEnabled(bool);- bool busy() const { return m_busy; }- bool more() const { return m_more; }- bool actionBusy() const { return m_actionBusy; }- QString error() const { return m_error; }- QString page() const { return m_request.value("mode", "albums").toString(); }- QString heading() const { return m_heading; }- QVariantList items() const { return m_items; }- QVariantMap collection() const { return m_collection; }- QVariantMap current() const;- bool canBack() const { return !m_back.isEmpty(); }- Q_INVOKABLE QString artwork(const QString &id);- Q_INVOKABLE void show(const QString &page);- Q_INVOKABLE void search(const QString &query,- const QString &filter = "songs");- Q_INVOKABLE void open(const QVariantMap &item);- Q_INVOKABLE void back();- Q_INVOKABLE void reload();- Q_INVOKABLE void loadMore();- Q_INVOKABLE void playItems(const QVariantList &, int index = 0);- Q_INVOKABLE void playItem(const QVariantMap &);- Q_INVOKABLE void enqueue(const QVariantMap &);- Q_INVOKABLE bool favorite(const QString &id) const {- return m_api.isStarred(id);- }- Q_INVOKABLE void toggleFavorite(const QVariantMap &);- Q_INVOKABLE void createPlaylist(const QString &name);- Q_INVOKABLE void renamePlaylist(const QString &id, const QString &name);- Q_INVOKABLE void addToPlaylist(const QString &id, const QVariantMap &);- Q_INVOKABLE void removeFromPlaylist(const QVariantMap &);- Q_INVOKABLE void movePlaylistItem(int from, int to);- Q_INVOKABLE void deletePlaylist(const QString &id);- Q_INVOKABLE void copyLink(const QVariantMap &);- bool active() const { return m_active; }- void setActive(bool);- QVariantList lines() const { return m_lines; }- bool loading() const { return m_loading; }- QString message() const { return m_message; }- bool timed() const { return m_timed; }- int currentIndex() const { return m_lyricIndex; }- Q_INVOKABLE void refresh();- Q_INVOKABLE bool seekToLine(int);-signals:- void changed();- void currentIndexChanged();- void feedback(const QString &message, bool error);- void artworkChanged();--private:- void browse(const QVariantMap &, bool append = false);- void loadCurrent();- void loadArt();- void loadThumbs();- void persist();- void restoreQueue();- void report(bool stopped = false);- void updateLyrics();- void finishAction(const QString &, bool refreshPage = false);- QList<Track> tracks(const QVariantList &);- QVariantMap original(const QVariantMap &) const;- JellyfinApi m_api;- Player m_player;- QString m_directory, m_identity, m_error, m_heading = "Albums",- m_message = "No lyrics available";- bool m_enabled = false, m_busy = false, m_more = false, m_actionBusy = false,- m_active = false, m_loading = false, m_timed = false,- m_thumbBusy = false, m_storageValid = true;- int m_lyricIndex = -1;- quint64 m_generation = 0;- QVariantMap m_request{{"mode", "albums"}}, m_collection, m_reported;- qint64 m_reportedPosition = 0;- QVariantList m_items, m_back, m_lines;- QHash<QString, QVariantMap> m_catalog;- QHash<QString, QString> m_thumbs;- QStringList m_thumbOrder, m_thumbPending;- QString m_thumbActive;- std::shared_ptr<QTemporaryDir> m_audio, m_art;- QTemporaryDir m_thumbnailDirectory;- QTimer m_save, m_reportTimer;- LyricTimeline m_timeline;-};+#include "remotelibrary.h"+using Jellyfin = RemoteLibrary;diff --git a/src/jellyfinapi.cpp b/src/jellyfinapi.cppindex 66c3fdc..d2e47fb 100644--- a/src/jellyfinapi.cpp+++ b/src/jellyfinapi.cpp@@ -1092,3 +1092,10 @@ void JellyfinApi::movePlaylistItem(const QString &playlist,QString::number(index),{}, "POST", {}, cb);}++QUrl JellyfinApi::shareUrl(const QVariantMap &row) const {+ if (!owns(row)) return {};+ QUrl u(address() + "/web/index.html");+ u.setFragment("/details?id=" + QString::fromLatin1(QUrl::toPercentEncoding(row.value("remoteId").toString())));+ return u;+}diff --git a/src/jellyfinapi.h b/src/jellyfinapi.hindex 15f4511..919e5fa 100644--- a/src/jellyfinapi.h+++ b/src/jellyfinapi.h@@ -1,4 +1,5 @@#pragma once+#include "remotemusicapi.h"#include <QJsonObject>#include <QNetworkAccessManager>#include <QNetworkReply>@@ -9,20 +10,12 @@#include <functional>// Jellyfin credentials stay in request headers; persisted rows contain only// opaque identities.-class JellyfinApi : public QObject {+class JellyfinApi : public RemoteMusicApi {Q_OBJECT- Q_PROPERTY(bool connected READ connected NOTIFY changed)- Q_PROPERTY(bool connecting READ connecting NOTIFY changed)- Q_PROPERTY(QString address READ address NOTIFY changed)- Q_PROPERTY(QString username READ username NOTIFY changed)- Q_PROPERTY(QString error READ error NOTIFY changed)- Q_PROPERTY(QVariantList playlists READ playlists NOTIFY changed)- Q_PROPERTY(QVariantList folders READ folders NOTIFY changed)- Q_PROPERTY(QString folder READ folder WRITE setFolder NOTIFY changed)- Q_PROPERTY(bool scrobbling READ scrobbling WRITE setScrobbling NOTIFY changed)- Q_PROPERTY(int bitrate READ bitrate WRITE setBitrate NOTIFY changed)- Q_PROPERTY(bool keyringAvailable READ keyringAvailable CONSTANT)public:+ QString serviceName() const override { return "Jellyfin"; }+ QString scheme() const override { return "jellyfin"; }+ QUrl shareUrl(const QVariantMap &) const override;using Reply = std::function<void(const QVariantMap &, const QString &)>;using Params = QList<QPair<QString, QString>>;explicit JellyfinApi(bool restore = true, const QString &settingsPath = {});@@ -71,10 +64,6 @@ public:QNetworkRequest artworkRequest(const QUrl &) const;void reportPlayback(const QVariantMap &, qint64, bool, bool);-signals:- void changed();- void accountChanged();- void message(const QString &text);private:void secret(const QStringList &, const QByteArray &,diff --git a/src/main.cpp b/src/main.cppindex ee414c8..29814d0 100644--- a/src/main.cpp+++ b/src/main.cpp@@ -7,8 +7,10 @@#include "player.h"#include "youtube.h"#include "jellyfin.h"+#include "subsonicapi.h"#ifdef SPUN_DIAGNOSTICS#include "jellyfintest.h"+#include "subsonictest.h"#endif#include "tx6.h"#include "tapesound.h"@@ -1562,7 +1564,7 @@ int main(int argc, char **argv) {for (int i=1; i<argc; ++i) {const QByteArray option = QByteArray(argv[i]).split('=').first();if (option == "--") break;- if (option == "--test-jellyfin" || option == "--test-youtube-live" || option == "--test-youtube" || option == "--test-performance" || option == "--self-test" || option == "--test-tx6" || option == "--test-cd-deck" || option == "--test-cassette-deck" || option == "--test-turntable" || option == "--test-recorder" || option == "--test-media-ui" || option == "--test-artwork" || option == "--test-3d-lighting" || option == "--test-3d-ui" || option == "--test-3d-library" || option == "--test-import-ui" || option == "--test-library" || option == "--smoke-live"+ if (option == "--test-subsonic" || option == "--test-jellyfin" || option == "--test-youtube-live" || option == "--test-youtube" || option == "--test-performance" || option == "--self-test" || option == "--test-tx6" || option == "--test-cd-deck" || option == "--test-cassette-deck" || option == "--test-turntable" || option == "--test-recorder" || option == "--test-media-ui" || option == "--test-artwork" || option == "--test-3d-lighting" || option == "--test-3d-ui" || option == "--test-3d-library" || option == "--test-import-ui" || option == "--test-library" || option == "--smoke-live"|| option == "--verify-cider" || option == "--verify-cider-writes" || option == "--inspect-cider" || option == "--inspect-library") {const auto executable = QFileInfo(QStringLiteral("/proc/self/exe")).symLinkTarget();const auto diagnostics = QFile::encodeName(QFileInfo(executable).absolutePath() + "/spun-diagnostics");@@ -1603,6 +1605,7 @@ int main(int argc, char **argv) {parser.addOption({"benchmark", "Measure an isolated startup, idle, playing, mini, or cycle scene", "scene"});parser.addOption({"benchmark-medium", "Appearance for isolated measurements", "medium", "cd"});parser.addOption({"benchmark-3d", "Measure the native 3D asset rather than its 2D face"});+ parser.addOption({"test-subsonic", "Verify Navidrome/Subsonic against a disposable server"});parser.addOption({"test-jellyfin", "Verify Jellyfin against a disposable server"});parser.addOption({"test-youtube-live", "Verify anonymous live YouTube playback with isolated state"});parser.addOption({"test-youtube", "Verify anonymous YouTube browsing, local library and playback"});@@ -1633,7 +1636,7 @@ int main(int argc, char **argv) {parser.addPositionalArgument("files", "Music files or album folders to play", "[files…]");parser.process(app);if (parser.isSet("export-cover")) return Disc::fallbackArt().save(parser.value("export-cover")) ? 0 : 1;- const bool test = parser.isSet("test-jellyfin") || parser.isSet("test-youtube-live") || parser.isSet("test-youtube") || parser.isSet("test-performance") || parser.isSet("test-tx6") || parser.isSet("test-cd-deck") || parser.isSet("test-cassette-deck") || parser.isSet("test-turntable") || parser.isSet("test-recorder") || parser.isSet("test-artwork") || parser.isSet("test-3d-lighting") || parser.isSet("test-3d-ui") || parser.isSet("test-3d-library") || parser.isSet("test-media-ui") || parser.isSet("benchmark") || parser.isSet("test-import-ui") || parser.isSet("self-test") || parser.isSet("smoke-live") || parser.isSet("test-library");+ const bool test = parser.isSet("test-subsonic") || parser.isSet("test-jellyfin") || parser.isSet("test-youtube-live") || parser.isSet("test-youtube") || parser.isSet("test-performance") || parser.isSet("test-tx6") || parser.isSet("test-cd-deck") || parser.isSet("test-cassette-deck") || parser.isSet("test-turntable") || parser.isSet("test-recorder") || parser.isSet("test-artwork") || parser.isSet("test-3d-lighting") || parser.isSet("test-3d-ui") || parser.isSet("test-3d-library") || parser.isSet("test-media-ui") || parser.isSet("benchmark") || parser.isSet("test-import-ui") || parser.isSet("self-test") || parser.isSet("smoke-live") || parser.isSet("test-library");if(test && qEnvironmentVariableIsSet("SPUN_TEST_SCREEN"))app.setDesktopFileName("spun-diagnostics");if (!test && !parser.isSet("config") && !parser.isSet("isolated")) {auto bus = QDBusConnection::sessionBus();@@ -1669,6 +1672,11 @@ int main(int argc, char **argv) {Player player(settings);Youtube youtube(QFileInfo(settings).absolutePath() + "/youtube");Jellyfin jellyfin(QFileInfo(settings).absolutePath() + "/jellyfin", !test);+ RemoteLibrary subsonic(QFileInfo(settings).absolutePath() + "/subsonic", !test, nullptr,+ new SubsonicApi(!test, QFileInfo(settings).absolutePath() + "/subsonic/connection.ini"));+ QObject::connect(&player, &Player::mediumChanged, &subsonic, [&]{subsonic.transport()->setMedium(player.medium());});+ QObject::connect(&player, &Player::settingsChanged, &subsonic, [&]{subsonic.transport()->setVinylAlbumMode(player.vinylAlbumMode());});+ subsonic.transport()->setMedium(player.medium());QObject::connect(&player, &Player::mediumChanged, &jellyfin, [&]{jellyfin.transport()->setMedium(player.medium());});QObject::connect(&player, &Player::settingsChanged, &jellyfin, [&]{jellyfin.transport()->setVinylAlbumMode(player.vinylAlbumMode());});jellyfin.transport()->setMedium(player.medium());@@ -1721,6 +1729,7 @@ int main(int argc, char **argv) {engine.rootContext()->setContextProperty("player", &player);engine.rootContext()->setContextProperty("youtube", &youtube);engine.rootContext()->setContextProperty("jellyfin", &jellyfin);+ engine.rootContext()->setContextProperty("subsonic", &subsonic);engine.rootContext()->setContextProperty("tx6", &tx6);engine.rootContext()->setContextProperty("theme", &theme);engine.rootContext()->setContextProperty("typography", &typography);@@ -1779,7 +1788,7 @@ int main(int argc, char **argv) {window->setPosition(screen->availableGeometry().topLeft()+QPoint(60,60));}if (parser.isSet("youtube")) { window->setProperty("useYoutube",true);window->setProperty("libraryOpen",true); }- if (!test && !parser.isSet("isolated")) { if (auto *mediaControls = registerMpris(&player, &cider, youtube.transport(), jellyfin.transport())) mediaControls->setSourceWindow(window); }+ if (!test && !parser.isSet("isolated")) { if (auto *mediaControls = registerMpris(&player, &cider, youtube.transport(), jellyfin.transport(), subsonic.transport())) mediaControls->setSourceWindow(window); }QObject::connect(&app, &QCoreApplication::aboutToQuit, &player, &Player::save);if (parser.isSet("benchmark")) {window->setProperty("benchmarkPinned", true);@@ -2199,6 +2208,7 @@ int main(int argc, char **argv) {else if (parser.isSet("test-3d-lighting")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseThreeDLighting(player,window,temp.path(),parser.value("capture-dir"))); });else if (parser.isSet("test-3d-ui")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseThreeD(player,window,temp.path(),parser.value("capture-dir"))); });else if (parser.isSet("test-3d-library")) QTimer::singleShot(650, &app, [&] { player.setThreeD(true); if(!waitFor([&]{return window->property("threeDActive").toBool();})) { std::cerr << "FAIL 3D scene must be active for Cider integration tests" << std::endl;app.exit(2);return; } app.exit(exerciseLibrary(window,temp.path(),parser.value("capture-dir")) ? 1 : 0); });+ else if (parser.isSet("test-subsonic")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseSubsonic(player,subsonic,window,temp.path(),parser.value("capture-dir"))); });else if (parser.isSet("test-jellyfin")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseJellyfin(player,jellyfin,window,temp.path(),parser.value("capture-dir"))); });else if (parser.isSet("test-youtube-live")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseYoutubeLive(player,youtube,window,parser.value("capture-dir"))); });else if (parser.isSet("test-youtube")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseYoutube(player,youtube,window,temp.path(),parser.value("capture-dir"))); });diff --git a/src/mpris.cpp b/src/mpris.cppindex 1f27f9e..40e90a2 100644--- a/src/mpris.cpp+++ b/src/mpris.cpp@@ -18,8 +18,8 @@ void RootAdaptor::Raise() {for (auto *window : QGuiApplication::topLevelWindows())if (window->title() == "Spun") { window->showNormal(); window->raise(); window->requestActivate(); }}-PlayerAdaptor::PlayerAdaptor(Player *p, Cider *cider, Player *youtube, Player *jellyfin) : QDBusAbstractAdaptor(p), m_player(p), m_local(p), m_youtube(youtube), m_jellyfin(jellyfin), m_cider(cider) {- for (auto *p : {m_local,m_youtube,m_jellyfin}) { if (!p) continue;+PlayerAdaptor::PlayerAdaptor(Player *p, Cider *cider, Player *youtube, Player *jellyfin, Player *subsonic) : QDBusAbstractAdaptor(p), m_player(p), m_local(p), m_youtube(youtube), m_jellyfin(jellyfin), m_subsonic(subsonic), m_cider(cider) {+ for (auto *p : {m_local,m_youtube,m_jellyfin,m_subsonic}) { if (!p) continue;connect(p, &Player::trackChanged, this, &PlayerAdaptor::changed);connect(p, &Player::playingChanged, this, &PlayerAdaptor::changed);connect(p, &Player::durationChanged, this, &PlayerAdaptor::changed);@@ -55,11 +55,12 @@ void PlayerAdaptor::setSourceWindow(QObject *window) {m_sourceWindow = window;QQmlProperty(window, "useCider").connectNotifySignal(this, SLOT(syncSource()));QQmlProperty(window, "useYoutube").connectNotifySignal(this, SLOT(syncSource()));+ if(window->metaObject()->indexOfProperty("useSubsonic")>=0)QQmlProperty(window, "useSubsonic").connectNotifySignal(this, SLOT(syncSource()));if(window->metaObject()->indexOfProperty("useJellyfin")>=0)QQmlProperty(window, "useJellyfin").connectNotifySignal(this, SLOT(syncSource()));syncSource();}void PlayerAdaptor::syncSource() {- m_player = m_jellyfin && m_sourceWindow && m_sourceWindow->property("useJellyfin").toBool() ? m_jellyfin : m_youtube && m_sourceWindow && m_sourceWindow->property("useYoutube").toBool() ? m_youtube : m_local;+ m_player = m_subsonic && m_sourceWindow && m_sourceWindow->property("useSubsonic").toBool() ? m_subsonic : m_jellyfin && m_sourceWindow && m_sourceWindow->property("useJellyfin").toBool() ? m_jellyfin : m_youtube && m_sourceWindow && m_sourceWindow->property("useYoutube").toBool() ? m_youtube : m_local;setRemote(m_sourceWindow && m_sourceWindow->property("useCider").toBool());changed(); emit Seeked(position());}@@ -132,11 +133,11 @@ void PlayerAdaptor::changed() {QDBusConnection::sessionBus().send(message);});}-PlayerAdaptor *registerMpris(Player *player, Cider *cider, Player *youtube, Player *jellyfin) {+PlayerAdaptor *registerMpris(Player *player, Cider *cider, Player *youtube, Player *jellyfin, Player *subsonic) {auto bus = QDBusConnection::sessionBus();if (!bus.registerService("org.mpris.MediaPlayer2.spun")) return nullptr;new RootAdaptor(player);- auto *adaptor = new PlayerAdaptor(player, cider, youtube, jellyfin);+ auto *adaptor = new PlayerAdaptor(player, cider, youtube, jellyfin, subsonic);if (!bus.registerObject("/org/mpris/MediaPlayer2", player, QDBusConnection::ExportAdaptors)) {bus.unregisterService("org.mpris.MediaPlayer2.spun"); return nullptr;}diff --git a/src/mpris.h b/src/mpris.hindex f5fef75..a8b1ed0 100644--- a/src/mpris.h+++ b/src/mpris.h@@ -50,7 +50,7 @@ class PlayerAdaptor : public QDBusAbstractAdaptor {Q_PROPERTY(bool CanSeek READ canSeek)Q_PROPERTY(bool CanControl READ always CONSTANT)public:- explicit PlayerAdaptor(Player *p, Cider *cider = nullptr, Player *youtube = nullptr, Player *jellyfin = nullptr);+ explicit PlayerAdaptor(Player *p, Cider *cider = nullptr, Player *youtube = nullptr, Player *jellyfin = nullptr, Player *subsonic = nullptr);void setRemote(bool remote);void setSourceWindow(QObject *window);QString trackId() const;@@ -92,10 +92,11 @@ private:Player *m_local;Player *m_youtube;Player *m_jellyfin;+ Player *m_subsonic;Cider *m_cider;QPointer<QObject> m_sourceWindow;bool m_remote = false, m_changePending = false;QVariantMap m_lastProperties;};-PlayerAdaptor *registerMpris(Player *player, Cider *cider, Player *youtube = nullptr, Player *jellyfin = nullptr);+PlayerAdaptor *registerMpris(Player *player, Cider *cider, Player *youtube = nullptr, Player *jellyfin = nullptr, Player *subsonic = nullptr);diff --git a/src/jellyfin.cpp b/src/remotelibrary.cppsimilarity index 83%rename from src/jellyfin.cpprename to src/remotelibrary.cppindex 0d39993..1659537 100644--- a/src/jellyfin.cpp+++ b/src/remotelibrary.cpp@@ -1,4 +1,4 @@-#include "jellyfin.h"+#include "remotelibrary.h"#include <QClipboard>#include <QDir>#include <QFile>@@ -9,17 +9,21 @@#include <QJsonObject>#include <QSaveFile>-Jellyfin::Jellyfin(const QString &directory, bool restore, QObject *parent)- : QObject(parent), m_api(restore, directory + "/connection.ini"),- m_player(directory + "/player.ini", this, true), m_directory(directory) {- m_player.setExternalName("Jellyfin");+RemoteLibrary::RemoteLibrary(const QString &directory, bool restore,+ QObject *parent, RemoteMusicApi *api)+ : QObject(parent),+ m_apiOwner(api ? api+ : new JellyfinApi(restore, directory + "/connection.ini")),+ m_api(*m_apiOwner), m_player(directory + "/player.ini", this, true),+ m_directory(directory) {+ m_player.setExternalName(m_api.serviceName());m_save.setSingleShot(true);m_save.setInterval(200);- connect(&m_save, &QTimer::timeout, this, &Jellyfin::persist);- connect(&m_api, &JellyfinApi::message, this, [this](const QString &s) {+ connect(&m_save, &QTimer::timeout, this, &RemoteLibrary::persist);+ connect(&m_api, &RemoteMusicApi::message, this, [this](const QString &s) {emit feedback(s, !m_api.error().isEmpty());});- connect(&m_api, &JellyfinApi::accountChanged, this, [this] {+ connect(&m_api, &RemoteMusicApi::accountChanged, this, [this] {persist();++m_generation;m_player.stop();@@ -44,7 +48,8 @@ Jellyfin::Jellyfin(const QString &directory, bool restore, QObject *parent)m_error.clear();emit changed();});- connect(&m_api, &JellyfinApi::changed, this, [this] {+ connect(&m_api, &RemoteMusicApi::changed, this, [this] {+ m_player.setExternalName(m_api.serviceName());if (m_api.connected() && m_identity != m_api.identity()) {m_identity = m_api.identity();restoreQueue();@@ -53,7 +58,8 @@ Jellyfin::Jellyfin(const QString &directory, bool restore, QObject *parent)}emit changed();});- connect(&m_player, &Player::externalRequested, this, &Jellyfin::loadCurrent);+ connect(&m_player, &Player::externalRequested, this,+ &RemoteLibrary::loadCurrent);connect(&m_player, &Player::externalCancelled, this,[this] { m_api.cancel("audio"); });connect(&m_player, &Player::trackChanged, this, [this] {@@ -88,12 +94,12 @@ Jellyfin::Jellyfin(const QString &directory, bool restore, QObject *parent)connect(&m_reportTimer, &QTimer::timeout, this, [this] { report(); });m_reportTimer.start();}-Jellyfin::~Jellyfin() {+RemoteLibrary::~RemoteLibrary() {persist();report(true);m_player.stop();}-void Jellyfin::setEnabled(bool value) {+void RemoteLibrary::setEnabled(bool value) {if (m_enabled == value)return;m_enabled = value;@@ -112,25 +118,25 @@ void Jellyfin::setEnabled(bool value) {}emit changed();}-QVariantMap Jellyfin::original(const QVariantMap &row) const {+QVariantMap RemoteLibrary::original(const QVariantMap &row) const {return m_catalog.value(row.value("id").toString(), row);}-QVariantMap Jellyfin::current() const {+QVariantMap RemoteLibrary::current() const {return m_catalog.value(m_player.currentUrl().path().mid(1));}-void Jellyfin::show(const QString &mode) {+void RemoteLibrary::show(const QString &mode) {m_back.clear();m_collection.clear();browse({{"mode", mode}});}-void Jellyfin::search(const QString &query, const QString &filter) {+void RemoteLibrary::search(const QString &query, const QString &filter) {m_back.clear();m_collection.clear();browse({{"mode", "search"},{"query", query.trimmed().left(512)},{"filter", filter}});}-void Jellyfin::open(const QVariantMap &row) {+void RemoteLibrary::open(const QVariantMap &row) {if (!m_api.owns(row))return;if (row.value("kind") == "song") {@@ -144,19 +150,19 @@ void Jellyfin::open(const QVariantMap &row) {m_collection = row;browse({{"mode", row.value("kind")}, {"remoteId", row.value("remoteId")}});}-void Jellyfin::back() {+void RemoteLibrary::back() {if (m_back.isEmpty())return;auto state = m_back.takeLast().toMap();m_collection = state.value("collection").toMap();browse(state.value("request").toMap());}-void Jellyfin::reload() { browse(m_request); }-void Jellyfin::loadMore() {+void RemoteLibrary::reload() { browse(m_request); }+void RemoteLibrary::loadMore() {if (m_more && !m_busy)browse(m_request, true);}-void Jellyfin::browse(const QVariantMap &request, bool append) {+void RemoteLibrary::browse(const QVariantMap &request, bool append) {if (!m_api.connected())return;++m_generation;@@ -216,7 +222,7 @@ void Jellyfin::browse(const QVariantMap &request, bool append) {emit changed();});}-QList<Track> Jellyfin::tracks(const QVariantList &rows) {+QList<Track> RemoteLibrary::tracks(const QVariantList &rows) {QList<Track> out;for (const auto &v : rows) {auto row = original(v.toMap());@@ -225,7 +231,7 @@ QList<Track> Jellyfin::tracks(const QVariantList &rows) {const auto id = row.value("id").toString();m_catalog[id] = row;Track t;- t.path = "jellyfin://" + m_api.identity() + "/" + id;+ t.path = m_api.scheme() + "://" + m_api.identity() + "/" + id;t.title = row.value("title").toString();t.artist = row.value("artist").toString();t.album = row.value("album").toString();@@ -240,25 +246,25 @@ QList<Track> Jellyfin::tracks(const QVariantList &rows) {}return out;}-void Jellyfin::playItems(const QVariantList &rows, int index) {+void RemoteLibrary::playItems(const QVariantList &rows, int index) {auto queue = tracks(rows);if (!queue.isEmpty())m_player.setExternalTracks(queue, qBound(0, index, int(queue.size() - 1)),true);}-void Jellyfin::playItem(const QVariantMap &row) { playItems({row}); }-void Jellyfin::enqueue(const QVariantMap &row) {+void RemoteLibrary::playItem(const QVariantMap &row) { playItems({row}); }+void RemoteLibrary::enqueue(const QVariantMap &row) {auto queue = tracks({row});if (!queue.isEmpty()) {m_player.appendExternalTracks(queue);emit feedback("Added to queue", false);}}-void Jellyfin::loadCurrent() {+void RemoteLibrary::loadCurrent() {const auto row = current();const auto key = m_player.trackKey();if (!m_api.owns(row)) {- m_player.failExternal(key, "Connect to this song's Jellyfin server first.");+ m_player.failExternal(key, "Connect to this song's music server first.");return;}auto buffer = std::make_shared<QTemporaryDir>();@@ -277,7 +283,7 @@ void Jellyfin::loadCurrent() {key, QUrl::fromLocalFile(buffer->filePath("audio")));});}-void Jellyfin::loadArt() {+void RemoteLibrary::loadArt() {m_api.cancel("cover");const auto row = current();const auto key = m_player.trackKey();@@ -295,7 +301,7 @@ void Jellyfin::loadArt() {}});}-QString Jellyfin::artwork(const QString &id) {+QString RemoteLibrary::artwork(const QString &id) {if (m_thumbs.contains(id)) {m_thumbOrder.removeAll(id);m_thumbOrder.append(id);@@ -306,11 +312,11 @@ QString Jellyfin::artwork(const QString &id) {id != m_thumbActive && !m_thumbPending.contains(id) &&m_thumbPending.size() < 64) {m_thumbPending.append(id);- QTimer::singleShot(0, this, &Jellyfin::loadThumbs);+ QTimer::singleShot(0, this, &RemoteLibrary::loadThumbs);}return {};}-void Jellyfin::loadThumbs() {+void RemoteLibrary::loadThumbs() {if (m_thumbBusy || !m_enabled || !m_thumbnailDirectory.isValid())return;while (!m_thumbPending.isEmpty()) {@@ -336,13 +342,13 @@ void Jellyfin::loadThumbs() {file.isEmpty() ? QString() : QUrl::fromLocalFile(file).toString();m_thumbOrder.append(id);emit artworkChanged();- QTimer::singleShot(0, this, &Jellyfin::loadThumbs);+ QTimer::singleShot(0, this, &RemoteLibrary::loadThumbs);},"thumb");return;}}-void Jellyfin::finishAction(const QString &error, bool refreshPage) {+void RemoteLibrary::finishAction(const QString &error, bool refreshPage) {m_actionBusy = false;if (!error.isEmpty())emit feedback(error, true);@@ -350,7 +356,7 @@ void Jellyfin::finishAction(const QString &error, bool refreshPage) {reload();emit changed();}-void Jellyfin::toggleFavorite(const QVariantMap &row) {+void RemoteLibrary::toggleFavorite(const QVariantMap &row) {if (m_actionBusy)return;m_actionBusy = true;@@ -360,7 +366,7 @@ void Jellyfin::toggleFavorite(const QVariantMap &row) {finishAction(e, page() == "favorites");});}-void Jellyfin::createPlaylist(const QString &name) {+void RemoteLibrary::createPlaylist(const QString &name) {if (m_actionBusy || name.trimmed().isEmpty())return;m_actionBusy = true;@@ -371,7 +377,7 @@ void Jellyfin::createPlaylist(const QString &name) {show("playlists");});}-void Jellyfin::renamePlaylist(const QString &id, const QString &name) {+void RemoteLibrary::renamePlaylist(const QString &id, const QString &name) {if (m_actionBusy || name.trimmed().isEmpty())return;m_actionBusy = true;@@ -380,7 +386,7 @@ void Jellyfin::renamePlaylist(const QString &id, const QString &name) {id, {{"name", name.trimmed().left(120)}},[this](const QVariantMap &, const QString &e) { finishAction(e, true); });}-void Jellyfin::addToPlaylist(const QString &id, const QVariantMap &row) {+void RemoteLibrary::addToPlaylist(const QString &id, const QVariantMap &row) {if (m_actionBusy || !m_api.owns(row))return;m_actionBusy = true;@@ -390,7 +396,7 @@ void Jellyfin::addToPlaylist(const QString &id, const QVariantMap &row) {finishAction(e, page() == "playlist");});}-void Jellyfin::removeFromPlaylist(const QVariantMap &row) {+void RemoteLibrary::removeFromPlaylist(const QVariantMap &row) {if (m_actionBusy || page() != "playlist" ||!m_collection.value("editable").toBool())return;@@ -401,7 +407,7 @@ void Jellyfin::removeFromPlaylist(const QVariantMap &row) {{{"entryIdToRemove", row.value("entryId").toString()}},[this](const QVariantMap &, const QString &e) { finishAction(e, true); });}-void Jellyfin::movePlaylistItem(int from, int to) {+void RemoteLibrary::movePlaylistItem(int from, int to) {if (m_actionBusy || page() != "playlist" ||!m_collection.value("editable").toBool() || from < 0 || to < 0 ||from >= m_items.size() || to >= m_items.size() || from == to)@@ -415,7 +421,7 @@ void Jellyfin::movePlaylistItem(int from, int to) {m_collection.value("remoteId").toString(), entry, to,[this](const QVariantMap &, const QString &e) { finishAction(e, true); });}-void Jellyfin::deletePlaylist(const QString &id) {+void RemoteLibrary::deletePlaylist(const QString &id) {if (m_actionBusy)return;m_actionBusy = true;@@ -426,16 +432,16 @@ void Jellyfin::deletePlaylist(const QString &id) {show("playlists");});}-void Jellyfin::copyLink(const QVariantMap &row) {+void RemoteLibrary::copyLink(const QVariantMap &row) {if (!m_api.owns(row))return;- QUrl u(m_api.address() + "/web/index.html");- u.setFragment("/details?id=" + QString::fromLatin1(QUrl::toPercentEncoding(- row.value("remoteId").toString())));+ const QUrl u = m_api.shareUrl(row);+ if (u.isEmpty())+ return;QGuiApplication::clipboard()->setText(u.toString());emit feedback("Link copied", false);}-void Jellyfin::setActive(bool active) {+void RemoteLibrary::setActive(bool active) {if (m_active == active)return;m_active = active;@@ -447,7 +453,7 @@ void Jellyfin::setActive(bool active) {}emit changed();}-void Jellyfin::refresh() {+void RemoteLibrary::refresh() {m_lines.clear();m_timeline.reset({});m_lyricIndex = -1;@@ -481,20 +487,20 @@ void Jellyfin::refresh() {emit changed();});}-void Jellyfin::updateLyrics() {+void RemoteLibrary::updateLyrics() {const auto i = m_timeline.indexAt(m_player.position());if (i != m_lyricIndex) {m_lyricIndex = i;emit currentIndexChanged();}}-bool Jellyfin::seekToLine(int index) {+bool RemoteLibrary::seekToLine(int index) {if (!m_timed || index < 0 || index >= m_lines.size())return false;m_player.seek(m_lines[index].toMap().value("start").toLongLong());return true;}-void Jellyfin::report(bool stopped) {+void RemoteLibrary::report(bool stopped) {if (stopped) {if (!m_reported.isEmpty())m_api.reportPlayback(m_reported, m_reportedPosition, true, true);@@ -512,7 +518,7 @@ void Jellyfin::report(bool stopped) {m_reportedPosition = m_player.position();m_api.reportPlayback(row, m_reportedPosition, !m_player.playing(), false);}-void Jellyfin::persist() {+void RemoteLibrary::persist() {if (m_identity.isEmpty() || !m_storageValid)return;QDir().mkpath(m_directory);@@ -533,7 +539,7 @@ void Jellyfin::persist() {.toJson(QJsonDocument::Compact));f.commit();}-void Jellyfin::restoreQueue() {+void RemoteLibrary::restoreQueue() {m_storageValid = true;QFile f(m_directory + "/queue-" + m_identity + ".json");if (!f.exists())@@ -548,7 +554,7 @@ void Jellyfin::restoreQueue() {doc.object().value("version").toInt() != 1) {m_storageValid = false;emit feedback(- "Saved Jellyfin queue could not be read. It has been left untouched.",+ "Saved server queue could not be read. It has been left untouched.",true);return;}diff --git a/src/remotelibrary.h b/src/remotelibrary.hnew file mode 100644index 0000000..3012a16--- /dev/null+++ b/src/remotelibrary.h@@ -0,0 +1,118 @@+#pragma once+#include "jellyfinapi.h"+#include "lyrics.h"+#include "player.h"+#include <QTemporaryDir>+#include <QTimer>++class RemoteLibrary : public QObject {+ Q_OBJECT+ Q_PROPERTY(RemoteMusicApi *server READ server CONSTANT)+ Q_PROPERTY(Player *transport READ transport CONSTANT)+ Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY changed)+ Q_PROPERTY(bool busy READ busy NOTIFY changed)+ Q_PROPERTY(bool more READ more NOTIFY changed)+ Q_PROPERTY(bool actionBusy READ actionBusy NOTIFY changed)+ Q_PROPERTY(QString error READ error NOTIFY changed)+ Q_PROPERTY(QString page READ page NOTIFY changed)+ Q_PROPERTY(QString heading READ heading NOTIFY changed)+ Q_PROPERTY(QVariantList items READ items NOTIFY changed)+ Q_PROPERTY(QVariantMap collection READ collection NOTIFY changed)+ Q_PROPERTY(QVariantMap current READ current NOTIFY changed)+ Q_PROPERTY(bool canBack READ canBack NOTIFY changed)+ Q_PROPERTY(bool active READ active WRITE setActive NOTIFY changed)+ Q_PROPERTY(QVariantList lines READ lines NOTIFY changed)+ Q_PROPERTY(bool loading READ loading NOTIFY changed)+ Q_PROPERTY(QString message READ message NOTIFY changed)+ Q_PROPERTY(bool timed READ timed NOTIFY changed)+ Q_PROPERTY(int currentIndex READ currentIndex NOTIFY currentIndexChanged)+public:+ explicit RemoteLibrary(const QString &directory, bool restore = true,+ QObject *parent = nullptr,+ RemoteMusicApi *api = nullptr);+ ~RemoteLibrary() override;+ RemoteMusicApi *server() { return &m_api; }+ Player *transport() { return &m_player; }+ bool enabled() const { return m_enabled; }+ void setEnabled(bool);+ bool busy() const { return m_busy; }+ bool more() const { return m_more; }+ bool actionBusy() const { return m_actionBusy; }+ QString error() const { return m_error; }+ QString page() const { return m_request.value("mode", "albums").toString(); }+ QString heading() const { return m_heading; }+ QVariantList items() const { return m_items; }+ QVariantMap collection() const { return m_collection; }+ QVariantMap current() const;+ bool canBack() const { return !m_back.isEmpty(); }+ Q_INVOKABLE QString artwork(const QString &id);+ Q_INVOKABLE void show(const QString &page);+ Q_INVOKABLE void search(const QString &query,+ const QString &filter = "songs");+ Q_INVOKABLE void open(const QVariantMap &item);+ Q_INVOKABLE void back();+ Q_INVOKABLE void reload();+ Q_INVOKABLE void loadMore();+ Q_INVOKABLE void playItems(const QVariantList &, int index = 0);+ Q_INVOKABLE void playItem(const QVariantMap &);+ Q_INVOKABLE void enqueue(const QVariantMap &);+ Q_INVOKABLE bool favorite(const QString &id) const {+ return m_api.isStarred(id);+ }+ Q_INVOKABLE void toggleFavorite(const QVariantMap &);+ Q_INVOKABLE void createPlaylist(const QString &name);+ Q_INVOKABLE void renamePlaylist(const QString &id, const QString &name);+ Q_INVOKABLE void addToPlaylist(const QString &id, const QVariantMap &);+ Q_INVOKABLE void removeFromPlaylist(const QVariantMap &);+ Q_INVOKABLE void movePlaylistItem(int from, int to);+ Q_INVOKABLE void deletePlaylist(const QString &id);+ Q_INVOKABLE void copyLink(const QVariantMap &);+ bool active() const { return m_active; }+ void setActive(bool);+ QVariantList lines() const { return m_lines; }+ bool loading() const { return m_loading; }+ QString message() const { return m_message; }+ bool timed() const { return m_timed; }+ int currentIndex() const { return m_lyricIndex; }+ Q_INVOKABLE void refresh();+ Q_INVOKABLE bool seekToLine(int);+signals:+ void changed();+ void currentIndexChanged();+ void feedback(const QString &message, bool error);+ void artworkChanged();++private:+ void browse(const QVariantMap &, bool append = false);+ void loadCurrent();+ void loadArt();+ void loadThumbs();+ void persist();+ void restoreQueue();+ void report(bool stopped = false);+ void updateLyrics();+ void finishAction(const QString &, bool refreshPage = false);+ QList<Track> tracks(const QVariantList &);+ QVariantMap original(const QVariantMap &) const;+ std::unique_ptr<RemoteMusicApi> m_apiOwner;+ RemoteMusicApi &m_api;+ Player m_player;+ QString m_directory, m_identity, m_error, m_heading = "Albums",+ m_message = "No lyrics available";+ bool m_enabled = false, m_busy = false, m_more = false, m_actionBusy = false,+ m_active = false, m_loading = false, m_timed = false,+ m_thumbBusy = false, m_storageValid = true;+ int m_lyricIndex = -1;+ quint64 m_generation = 0;+ QVariantMap m_request{{"mode", "albums"}}, m_collection, m_reported;+ qint64 m_reportedPosition = 0;+ QVariantList m_items, m_back, m_lines;+ QHash<QString, QVariantMap> m_catalog;+ QHash<QString, QString> m_thumbs;+ QStringList m_thumbOrder, m_thumbPending;+ QString m_thumbActive;+ std::shared_ptr<QTemporaryDir> m_audio, m_art;+ QTemporaryDir m_thumbnailDirectory;+ QTimer m_save, m_reportTimer;+ LyricTimeline m_timeline;+};diff --git a/src/remotemusicapi.h b/src/remotemusicapi.hnew file mode 100644index 0000000..9f00342--- /dev/null+++ b/src/remotemusicapi.h@@ -0,0 +1,75 @@+#pragma once+#include <QNetworkRequest>+#include <QObject>+#include <QVariantMap>+#include <functional>++// Shared music-library contract. Protocol and authentication stay in each+// adapter.+class RemoteMusicApi : public QObject {+ Q_OBJECT+ Q_PROPERTY(bool connected READ connected NOTIFY changed)+ Q_PROPERTY(bool connecting READ connecting NOTIFY changed)+ Q_PROPERTY(QString address READ address NOTIFY changed)+ Q_PROPERTY(QString username READ username NOTIFY changed)+ Q_PROPERTY(QString error READ error NOTIFY changed)+ Q_PROPERTY(QVariantList playlists READ playlists NOTIFY changed)+ Q_PROPERTY(QVariantList folders READ folders NOTIFY changed)+ Q_PROPERTY(QString folder READ folder WRITE setFolder NOTIFY changed)+ Q_PROPERTY(bool scrobbling READ scrobbling WRITE setScrobbling NOTIFY changed)+ Q_PROPERTY(int bitrate READ bitrate WRITE setBitrate NOTIFY changed)+ Q_PROPERTY(bool keyringAvailable READ keyringAvailable CONSTANT)+ Q_PROPERTY(QString serviceName READ serviceName NOTIFY changed)+ Q_PROPERTY(QString scheme READ scheme CONSTANT)+public:+ using QObject::QObject;+ using Reply = std::function<void(const QVariantMap &, const QString &)>;+ using Params = QList<QPair<QString, QString>>;+ virtual QString serviceName() const = 0;+ virtual QString scheme() const = 0;+ virtual bool connected() const = 0;+ virtual bool connecting() const = 0;+ virtual QString address() const = 0;+ virtual QString username() const = 0;+ virtual QString identity() const = 0;+ virtual QString error() const = 0;+ virtual QVariantList playlists() const = 0;+ virtual QVariantList folders() const = 0;+ virtual QString folder() const = 0;+ virtual bool scrobbling() const = 0;+ virtual int bitrate() const = 0;+ virtual bool keyringAvailable() const = 0;+ virtual void setFolder(const QString &) = 0;+ virtual void setScrobbling(bool) = 0;+ virtual void setBitrate(int) = 0;+ Q_INVOKABLE virtual void connectServer(const QString &, const QString &,+ const QString &,+ bool remember = true) = 0;+ Q_INVOKABLE virtual void disconnectServer() = 0;+ Q_INVOKABLE virtual void reloadPlaylists() = 0;+ virtual void createPlaylist(const QString &, Reply = {}) = 0;+ virtual void cancel(const QString &) = 0;+ virtual void browse(const QVariantMap &, Reply,+ const QString &channel = "catalog") = 0;+ virtual void cover(const QVariantMap &, const QString &, Reply,+ const QString &channel = "cover") = 0;+ virtual void lyrics(const QVariantMap &, Reply) = 0;+ virtual void download(const QVariantMap &, const QString &, Reply,+ const QString &channel = "audio") = 0;+ virtual void star(const QVariantMap &, bool, Reply) = 0;+ virtual void editPlaylist(const QString &, const Params &, Reply) = 0;+ virtual void movePlaylistItem(const QString &, const QString &, int,+ Reply) = 0;+ virtual void removePlaylist(const QString &, Reply) = 0;+ virtual bool owns(const QVariantMap &) const = 0;+ virtual bool isStarred(const QString &) const = 0;+ virtual QVariantMap item(const QVariantMap &, const QString &) const = 0;+ virtual QUrl artworkUrl(const QUrl &) const = 0;+ virtual QNetworkRequest artworkRequest(const QUrl &) const = 0;+ virtual QUrl shareUrl(const QVariantMap &) const = 0;+ virtual void reportPlayback(const QVariantMap &, qint64, bool, bool) = 0;+signals:+ void changed();+ void accountChanged();+ void message(const QString &text);+};diff --git a/src/subsonicapi.cpp b/src/subsonicapi.cppnew file mode 100644index 0000000..5190f0d--- /dev/null+++ b/src/subsonicapi.cpp@@ -0,0 +1,1057 @@+#include "subsonicapi.h"+#include "jellyfinlrc.h"+#include <QBuffer>+#include <QDateTime>+static QString playlistRevision(const QVariantList &);+#include <QCryptographicHash>+#include <QFile>+#include <QImageReader>+#include <QJsonDocument>+#include <QJsonObject>+#include <QProcess>+#include <QSaveFile>+#include <QStandardPaths>+#include <QTimer>+#include <QUuid>+#include <algorithm>+#include <memory>++static QString hash(const QString &text) {+ return QString::fromLatin1(+ QCryptographicHash::hash(text.toUtf8(), QCryptographicHash::Sha256)+ .toHex());+}+static QString apiError(const QVariantMap &data) {+ switch (data.value("error").toMap().value("code").toInt()) {+ case 40:+ return "Incorrect server username or password.";+ case 41:+ return "This account does not support token authentication.";+ case 50:+ return "Your server account does not allow this action.";+ case 60:+ return "This Subsonic server requires an active Premium license.";+ case 70:+ return "This item no longer exists on the server.";+ case 20:+ case 30:+ return "The server API version is incompatible.";+ default:+ return "The server could not complete this action.";+ }+}+SubsonicApi::SubsonicApi(bool restore, const QString &settingsPath)+ : m_settings(settingsPath.isEmpty() ? QSettings().fileName() : settingsPath,+ QSettings::IniFormat) {+ if (!restore)+ return;+ m_address = m_settings.value("subsonic/address").toString();+ m_username = m_settings.value("subsonic/username").toString();+ if (!m_address.isEmpty() && !m_username.isEmpty()) {+ m_identity = hash("subsonic\n" + m_address + "\n" + m_username);+ if (m_settings.value("subsonic/remember", false).toBool())+ QTimer::singleShot(0, this, [this] {+ const auto generation = m_generation;+ secret({"lookup", "application", "spun", "account", m_identity}, {},+ [this, generation](bool ok, QByteArray password) {+ if (generation != m_generation)+ return;+ if (ok && !password.trimmed().isEmpty()) {+ if (password.endsWith('\n'))+ password.chop(1);+ m_restoring = true;+ connectServer(m_address, m_username,+ QString::fromUtf8(password), false);+ m_restoring = false;+ } else {+ m_error = "Sign in to reconnect to your music server.";+ emit changed();+ }+ });+ });+ }+}+SubsonicApi::~SubsonicApi() { stopRequests(); }+bool SubsonicApi::keyringAvailable() const {+ return !QStandardPaths::findExecutable("secret-tool").isEmpty();+}+void SubsonicApi::secret(const QStringList &args, const QByteArray &input,+ std::function<void(bool, QByteArray)> callback) {+ if (!keyringAvailable()) {+ callback(false, {});+ return;+ }+ auto p = new QProcess(this);+ auto timer = new QTimer(p);+ timer->setSingleShot(true);+ auto done = std::make_shared<bool>(false);+ auto finish = [p, done, callback](bool ok) {+ if (*done)+ return;+ *done = true;+ callback(ok, p->readAllStandardOutput());+ p->deleteLater();+ };+ connect(p, &QProcess::errorOccurred, this,+ [finish](QProcess::ProcessError e) {+ if (e == QProcess::FailedToStart)+ finish(false);+ });+ connect(p, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this,+ [finish](int code, QProcess::ExitStatus s) {+ finish(code == 0 && s == QProcess::NormalExit);+ });+ connect(timer, &QTimer::timeout, p, [p] { p->kill(); });+ p->start("secret-tool", args);+ p->write(input);+ p->closeWriteChannel();+ timer->start(15000);+}+void SubsonicApi::stopRequests() {+ ++m_generation;+ for (auto r : m_network.findChildren<QNetworkReply *>()) {+ r->disconnect(this);+ r->abort();+ r->deleteLater();+ }+ m_channels.clear();+}+void SubsonicApi::cancel(const QString &channel) {+ auto r = m_channels.take(channel);+ if (r) {+ r->disconnect(this);+ r->abort();+ r->deleteLater();+ }+}+void SubsonicApi::connectServer(const QString &address, const QString &user,+ const QString &password, bool remember) {+ QUrl base(address.trimmed());+ if (!base.isValid() ||+ !QStringList{"http", "https"}.contains(base.scheme()) ||+ base.host().isEmpty() || !base.userInfo().isEmpty() || base.hasQuery() ||+ base.hasFragment() || user.trimmed().isEmpty() || password.isEmpty()) {+ m_error = "Enter an HTTP(S) server address, username and password. Use the "+ "server root, without /rest.";+ emit changed();+ return;+ }+ QString path = base.path();+ while (path.endsWith('/'))+ path.chop(1);+ if (path.endsWith("/rest")) {+ m_error = "Use the server address without /rest.";+ emit changed();+ return;+ }+ base.setPath(path);+ const bool restoring = m_restoring;+ const auto oldIdentity = m_identity;+ stopRequests();+ m_connected = false;+ m_connecting = true;+ m_error.clear();+ m_stars.clear();+ m_playlists.clear();+ m_folders.clear();+ m_address = base.toString();+ m_username = user.trimmed();+ m_password = password;+ m_identity = hash("subsonic\n" + m_address + "\n" + m_username);+ m_lyricsExtension = false;+ m_formPost = false;+ emit accountChanged();+ emit changed();+ call(+ "ping", {},+ [this, remember, restoring, oldIdentity](const QVariantMap &info,+ const QString &error) {+ m_connecting = false;+ m_error = error;+ m_connected = error.isEmpty();+ if (m_connected) {+ m_serviceName = info.value("type").toString().compare(+ "navidrome", Qt::CaseInsensitive) == 0+ ? "Navidrome"+ : "Subsonic";+ if (m_settings.value("subsonic/remember", false).toBool() &&+ !oldIdentity.isEmpty() && oldIdentity != m_identity)+ secret({"clear", "application", "spun", "account", oldIdentity}, {},+ [](bool, QByteArray) {});+ const bool same = m_settings.value("subsonic/address") == m_address &&+ m_settings.value("subsonic/username") == m_username;+ if (!same)+ m_settings.remove("subsonic/folder");+ m_settings.setValue("subsonic/address", m_address);+ m_settings.setValue("subsonic/username", m_username);+ if (!remember && !restoring &&+ m_settings.value("subsonic/remember", false).toBool()) {+ m_settings.setValue("subsonic/remember", false);+ secret({"clear", "application", "spun", "account", m_identity}, {},+ [](bool, QByteArray) {});+ }+ if (remember) {+ const auto generation = m_generation;+ secret({"store", "--label=Spun Subsonic account", "application",+ "spun", "account", m_identity},+ m_password.toUtf8(),+ [this, generation](bool ok, QByteArray) {+ if (generation != m_generation)+ return;+ m_settings.setValue("subsonic/remember", ok);+ if (!ok)+ emit message("Connected for this session. The desktop "+ "keyring could not save the password.");+ });+ }+ discover();+ } else+ m_password.clear();+ emit changed();+ },+ "login");+}+void SubsonicApi::disconnectServer() {+ const auto old = m_identity;+ const bool remembered = m_settings.value("subsonic/remember", false).toBool();+ stopRequests();+ m_password.clear();+ m_connected = false;+ m_connecting = false;+ m_error.clear();+ m_stars.clear();+ m_playlists.clear();+ m_folders.clear();+ m_settings.remove("subsonic/remember");+ m_settings.remove("subsonic/address");+ m_settings.remove("subsonic/username");+ m_settings.remove("subsonic/folder");+ if (remembered && !old.isEmpty())+ secret({"clear", "application", "spun", "account", old}, {},+ [](bool, QByteArray) {});+ m_address.clear();+ m_username.clear();+ m_identity.clear();+ emit accountChanged();+ emit changed();+}+QUrl SubsonicApi::url(const QString &method, const Params ¶ms) const {+ if (m_password.isEmpty())+ return {};+ QUrl result(m_address);+ result.setPath(result.path() + "/rest/" + method + ".view");+ const auto salt = QUuid::createUuid().toString(QUuid::Id128);+ Params all{{"u", m_username},+ {"t", QString::fromLatin1(+ QCryptographicHash::hash((m_password + salt).toUtf8(),+ QCryptographicHash::Md5)+ .toHex())},+ {"s", salt},+ {"v", "1.16.1"},+ {"c", "Spun"},+ {"f", "json"}};+ all.append(params);+ QStringList encoded;+ for (const auto &p : all)+ encoded.append(QString::fromLatin1(QUrl::toPercentEncoding(p.first)) + "=" ++ QString::fromLatin1(QUrl::toPercentEncoding(p.second)));+ result.setQuery(encoded.join('&'), QUrl::StrictMode);+ return result;+}+void SubsonicApi::call(const QString &method, const Params ¶ms,+ Reply callback, const QString &channel) {+ if (!channel.isEmpty())+ cancel(channel);+ const auto target = url(method, params);+ if (target.isEmpty()) {+ QTimer::singleShot(0, this, [callback] {+ callback({}, "Connect to your music server in Settings.");+ });+ return;+ }+ const auto body = target.query(QUrl::FullyEncoded).toUtf8();+ if (body.size() > 2 * 1024 * 1024 || (!m_formPost && body.size() > 7500)) {+ QTimer::singleShot(0, this, [callback] {+ callback({},+ "This request is too large for the server. Select fewer songs.");+ });+ return;+ }+ QUrl endpoint = target;+ if (m_formPost)+ endpoint.setQuery(QString());+ QNetworkRequest request(endpoint);+ request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);+ request.setTransferTimeout(20000);+ request.setHeader(QNetworkRequest::ContentTypeHeader,+ "application/x-www-form-urlencoded");+ request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::ManualRedirectPolicy);+ auto r = m_formPost ? m_network.post(request, body) : m_network.get(request);+ if (!channel.isEmpty())+ m_channels[channel] = r;+ const auto generation = m_generation;+ connect(r, &QNetworkReply::readyRead, this, [r] {+ if (r->bytesAvailable() > 16 * 1024 * 1024)+ r->abort();+ });+ auto timer = new QTimer(r);+ timer->setSingleShot(true);+ connect(timer, &QTimer::timeout, r, &QNetworkReply::abort);+ timer->start(30000);+ connect(r, &QNetworkReply::finished, this,+ [this, r, generation, channel, callback] {+ if (!channel.isEmpty() && m_channels.value(channel) == r)+ m_channels.remove(channel);+ r->deleteLater();+ if (generation != m_generation)+ return;+ const int status =+ r->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ if (status >= 300 && status < 400) {+ callback({}, "The server redirected the request. Enter its final "+ "address in Settings.");+ return;+ }+ if (r->error() != QNetworkReply::NoError) {+ callback({}, status == 401 || status == 403+ ? "The server refused access. Check your "+ "account and server address."+ : "Could not reach the music server. Check the "+ "connection and retry.");+ return;+ }+ auto bytes = r->readAll();+ if (bytes.size() > 16 * 1024 * 1024) {+ callback({}, "The server response exceeds the 16 MiB limit.");+ return;+ }+ const auto data = QJsonDocument::fromJson(bytes)+ .object()+ .value("subsonic-response")+ .toObject()+ .toVariantMap();+ if (data.value("status") != "ok") {+ callback(+ data,+ data.isEmpty()+ ? "This address did not return a Subsonic API response."+ : apiError(data));+ return;+ }+ callback(data, {});+ });+}+void SubsonicApi::discover() {+ call("getOpenSubsonicExtensions", {},+ [this](const QVariantMap &d, const QString &) {+ for (const auto &v : d.value("openSubsonicExtensions").toList()) {+ if (v.toMap().value("name") == "songLyrics")+ m_lyricsExtension = true;+ if (v.toMap().value("name") == "formPost")+ m_formPost = true;+ }+ });+ call("getMusicFolders", {}, [this](const QVariantMap &d, const QString &) {+ m_folders = d.value("musicFolders").toMap().value("musicFolder").toList();+ emit changed();+ });+ call("getStarred2", {}, [this](const QVariantMap &d, const QString &e) {+ if (!e.isEmpty())+ return;+ for (const auto &kind :+ {QString("song"), QString("album"), QString("artist")})+ for (const auto &v : items(d.value("starred2").toMap().value(kind), kind))+ m_stars.insert(v.toMap().value("id").toString());+ emit changed();+ });+ reloadPlaylists();+}+void SubsonicApi::setFolder(const QString &id) {+ m_settings.setValue("subsonic/folder", id);+ emit changed();+}+void SubsonicApi::setScrobbling(bool value) {+ m_settings.setValue("subsonic/scrobble", value);+ if (!value) {+ m_playing.clear();+ m_lastReport = 0;+ m_listened = 0;+ m_wasPlaying = false;+ }+ emit changed();+}+void SubsonicApi::setBitrate(int value) {+ if (value != 0 && value != 128 && value != 192 && value != 320)+ return;+ m_settings.setValue("subsonic/bitrate", value);+ emit changed();+}+bool SubsonicApi::owns(const QVariantMap &track) const {+ return connected() && track.value("source") == "subsonic" &&+ track.value("server") == m_identity &&+ !track.value("remoteId").toString().isEmpty();+}+QVariantMap SubsonicApi::item(const QVariantMap &raw,+ const QString &kind) const {+ const auto remote = raw.value("id").toString();+ if (remote.isEmpty())+ return {};+ QVariantMap out{+ {"id", "sub_" + hash(m_identity + "\n" + kind + "\n" + remote)},+ {"source", "subsonic"},+ {"server", m_identity},+ {"remoteId", remote},+ {"kind", kind},+ {"title", raw.value("title", raw.value("name"))},+ {"artist", raw.value("artist", raw.value("owner"))},+ {"album", raw.value("album")},+ {"seconds", raw.value("duration", 0)},+ {"discNumber", raw.value("discNumber", 1)},+ {"year", raw.value("year")},+ {"trackNumber", raw.value("track")},+ {"count", raw.value("songCount", raw.value("albumCount", 0))},+ {"rating", raw.value("userRating", 0)},+ {"available", true}};+ if (kind == "song") {+ out["serverSong"] = true;+ out["artistId"] = raw.value("artistId");+ out["albumId"] = raw.value("albumId");+ }+ if (raw.contains("coverArt")) {+ QUrl cover;+ cover.setScheme("spunsubcover");+ cover.setHost("account");+ cover.setPath("/" + m_identity + "/" + raw.value("coverArt").toString());+ out["art"] = cover.toString();+ }+ if (kind == "playlist")+ out["editable"] = raw.value("owner").toString() == m_username;+ return out;+}+QVariantList SubsonicApi::items(const QVariant &rows,+ const QString &kind) const {+ QVariantList result;+ for (const auto &v : rows.toList()) {+ auto t = item(v.toMap(), kind);+ if (!t.isEmpty())+ result.append(t);+ }+ return result;+}+QUrl SubsonicApi::artworkUrl(const QUrl &reference) const {+ if (!connected() || reference.scheme() != "spunsubcover" ||+ reference.host() != "account" ||+ !reference.path().startsWith("/" + m_identity + "/"))+ return {};+ return url(+ "getCoverArt",+ {{"id", reference.path().mid(m_identity.size() + 2)}, {"size", "600"}});+}+void SubsonicApi::reloadPlaylists() {+ if (!connected())+ return;+ call(+ "getPlaylists", {},+ [this](const QVariantMap &d, const QString &e) {+ if (e.isEmpty()) {+ m_playlists =+ items(d.value("playlists").toMap().value("playlist"), "playlist");+ emit changed();+ } else+ emit message(e);+ },+ "playlists");+}+void SubsonicApi::createPlaylist(const QString &name, Reply callback) {+ if (name.trimmed().isEmpty()) {+ if (callback)+ callback({}, "Enter a playlist name.");+ return;+ }+ call("createPlaylist", {{"name", name.trimmed().left(120)}},+ [this, callback](const QVariantMap &d, const QString &e) {+ if (e.isEmpty())+ reloadPlaylists();+ if (callback)+ callback(d, e);+ });+}+void SubsonicApi::editPlaylist(const QString &id, const Params ¶ms,+ Reply callback) {+ playlistAccess(id, [this, id, params, callback](const QVariantMap &playlist,+ const QString &error) {+ if (!error.isEmpty()) {+ callback({}, error);+ return;+ }+ Params p{{"playlistId", id}};+ for (const auto ¶m : params) {+ if (param.first == "entryIdToRemove") {+ const auto rows = playlist.value("entry").toList();+ bool ok = false;+ const int index = param.second.section(':', 1).toInt(&ok);+ if (!ok || index < 0 || index >= rows.size() ||+ param.second.section(':', 0, 0) != playlistRevision(rows)) {+ callback({},+ "The playlist changed. Refresh it before removing songs.");+ return;+ }+ p.append({"songIndexToRemove", QString::number(index)});+ } else+ p.append(param);+ }+ call("updatePlaylist", p,+ [this, callback](const QVariantMap &d, const QString &e) {+ if (e.isEmpty())+ reloadPlaylists();+ callback(d, e);+ });+ });+}+void SubsonicApi::removePlaylist(const QString &id, Reply callback) {+ playlistAccess(+ id, [this, id, callback](const QVariantMap &, const QString &e) {+ if (!e.isEmpty()) {+ callback({}, e);+ return;+ }+ call("deletePlaylist", {{"id", id}},+ [this, callback](const QVariantMap &d, const QString &e) {+ if (e.isEmpty())+ reloadPlaylists();+ callback(d, e);+ });+ });+}+void SubsonicApi::star(const QVariantMap &track, bool starred, Reply callback) {+ if (!owns(track)) {+ callback({}, "Reconnect to this song’s server first.");+ return;+ }+ const auto id = track.value("id").toString();+ call(starred ? "star" : "unstar",+ {{track.value("kind") == "album" ? QString("albumId")+ : track.value("kind") == "artist" ? QString("artistId")+ : QString("id"),+ track.value("remoteId").toString()}},+ [this, id, starred, callback](const QVariantMap &d, const QString &e) {+ if (e.isEmpty()) {+ if (starred)+ m_stars.insert(id);+ else+ m_stars.remove(id);+ emit changed();+ }+ callback(d, e);+ });+}+void SubsonicApi::rate(const QVariantMap &track, int rating, Reply callback) {+ if (!owns(track) || rating < 0 || rating > 5) {+ callback({}, "Reconnect to this song’s server first.");+ return;+ }+ call("setRating",+ {{"id", track.value("remoteId").toString()},+ {"rating", QString::number(rating)}},+ callback);+}+void SubsonicApi::scrobble(const QVariantMap &track, bool submission,+ qint64 timestamp, Reply callback) {+ if (!scrobbling() || !owns(track))+ return;+ call("scrobble",+ {{"id", track.value("remoteId").toString()},+ {"submission", submission ? "true" : "false"},+ {"time", QString::number(timestamp)}},+ callback);+}+void SubsonicApi::browse(const QVariantMap &req, Reply callback,+ const QString &channel) {+ if (!connected()) {+ callback({}, "Connect to your music server in Settings.");+ return;+ }+ const auto mode = req.value("mode", "albums").toString();+ const int offset = qMax(0, req.value("offset").toInt());+ Params p;+ QString method, root, key, kind = "song";+ if (!folder().isEmpty())+ p.append(QPair<QString, QString>{"musicFolderId", folder()});+ if (mode == "albums" || mode == "recent") {+ method = "getAlbumList2";+ root = "albumList2";+ key = "album";+ kind = "album";+ p.append(QPair<QString, QString>{+ "type", mode == "recent"+ ? QString("recent")+ : req.value("sort", "alphabeticalByName").toString()});+ p.append(QPair<QString, QString>{"size", "100"});+ p.append(QPair<QString, QString>{"offset", QString::number(offset)});+ } else if (mode == "artists") {+ method = "getArtists";+ root = "artists";+ kind = "artist";+ } else if (mode == "genres") {+ method = "getGenres";+ root = "genres";+ key = "genre";+ kind = "genre";+ } else if (mode == "genre") {+ method = "getSongsByGenre";+ root = "songsByGenre";+ key = "song";+ p.append(QPair<QString, QString>{+ "genre", req.value("genre", req.value("remoteId")).toString()});+ p.append(QPair<QString, QString>{"count", "100"});+ p.append(QPair<QString, QString>{"offset", QString::number(offset)});+ } else if (mode == "favorites") {+ method = "getStarred2";+ root = "starred2";+ key = "song";+ } else if (mode == "random") {+ method = "getRandomSongs";+ root = "randomSongs";+ key = "song";+ p.append(QPair<QString, QString>{"size", "100"});+ } else if (mode == "playlists" ||+ (mode == "search" && req.value("filter") == "playlists")) {+ method = "getPlaylists";+ root = "playlists";+ key = "playlist";+ kind = "playlist";+ } else if (mode == "album") {+ method = "getAlbum";+ root = "album";+ key = "song";+ p = {{"id", req.value("remoteId").toString()}};+ } else if (mode == "artist") {+ method = "getArtist";+ root = "artist";+ key = "album";+ kind = "album";+ p = {{"id", req.value("remoteId").toString()}};+ } else if (mode == "playlist") {+ method = "getPlaylist";+ root = "playlist";+ key = "entry";+ p = {{"id", req.value("remoteId").toString()}};+ } else if (mode == "search" || mode == "songs") {+ method = "search3";+ root = "searchResult3";+ const auto filter = req.value("filter", "songs").toString();+ kind = filter == "albums" ? "album"+ : filter == "artists" ? "artist"+ : "song";+ key = kind;+ p.append(QPair<QString, QString>{+ "query", mode == "songs"+ ? (m_serviceName == "Navidrome" ? QString() : QString("*"))+ : req.value("query").toString()});+ for (const auto &type :+ {QString("song"), QString("album"), QString("artist")}) {+ p.append(+ QPair<QString, QString>{type + "Count", type == kind ? "100" : "0"});+ p.append(+ QPair<QString, QString>{type + "Offset", QString::number(offset)});+ }+ } else {+ callback({}, "This server view is not supported.");+ return;+ }+ call(+ method, p,+ [this, callback, root, key, kind, mode, offset,+ req](const QVariantMap &data, const QString &error) {+ if (!error.isEmpty()) {+ callback({}, error);+ return;+ }+ const auto container = data.value(root).toMap();+ QVariantList raw = container.value(key).toList();+ if (mode == "artists")+ for (const auto &index : container.value("index").toList())+ raw.append(index.toMap().value("artist").toList());+ if (mode == "genres")+ for (auto &v : raw) {+ auto m = v.toMap();+ m["id"] = m.value("value");+ m["name"] = m.value("value");+ v = m;+ }+ if (mode == "search" && kind == "playlist") {+ const auto query = req.value("query").toString().trimmed();+ raw.erase(std::remove_if(+ raw.begin(), raw.end(),+ [&query](const QVariant &v) {+ return !v.toMap().value("name").toString().contains(+ query, Qt::CaseInsensitive);+ }),+ raw.end());+ }+ const auto revision = playlistRevision(raw);+ const bool paged = mode == "albums" || mode == "recent" ||+ (mode == "search" && kind != "playlist") ||+ mode == "songs" || mode == "genre";+ const bool more = paged ? raw.size() == 100 : raw.size() > offset + 100;+ if (!paged)+ raw = raw.mid(offset, 100);+ auto rows = items(raw, kind);+ if (mode == "playlist")+ for (int i = 0; i < rows.size(); ++i) {+ auto row = rows[i].toMap();+ row["entryId"] = revision + ":" + QString::number(offset + i);+ rows[i] = row;+ }++ for (const auto &v : raw) {+ const auto t = v.toMap();+ if (t.contains("starred"))+ m_stars.insert(item(t, kind).value("id").toString());+ }+ if (mode == "favorites") {+ m_stars.clear();+ for (const auto &starKind :+ {QString("song"), QString("album"), QString("artist")})+ for (const auto &v : items(container.value(starKind), starKind))+ m_stars.insert(v.toMap().value("id").toString());+ emit changed();+ }+ QVariantMap result{{"items", rows},+ {"more", more && offset + rows.size() < 20000}};+ if (container.contains("name"))+ result["title"] = container.value("name");+ if (mode == "album") {+ result["artist"] = container.value("artist");+ result["year"] = container.value("year");+ }+ if (mode == "playlist")+ result["editable"] =+ container.value("owner").toString() == m_username;+ callback(result, {});+ },+ channel);+}+void SubsonicApi::lyrics(const QVariantMap &track, Reply callback) {+ if (!owns(track)) {+ callback({}, "Reconnect to this song’s server first.");+ return;+ }+ auto plain = [this, track, callback] {+ call(+ "getLyrics",+ {{"artist", track.value("artist").toString()},+ {"title", track.value("title").toString()}},+ [callback](const QVariantMap &d, const QString &e) {+ callback({{"ok", e.isEmpty()},+ {"lyrics", d.value("lyrics").toMap().value("value")},+ {"source", "Music server"}},+ e);+ },+ "lyrics");+ };+ if (!m_lyricsExtension) {+ plain();+ return;+ }+ call(+ "getLyricsBySongId", {{"id", track.value("remoteId").toString()}},+ [plain, callback](const QVariantMap &d, const QString &e) {+ const auto variants =+ d.value("lyricsList").toMap().value("structuredLyrics").toList();+ if (!e.isEmpty() || variants.isEmpty()) {+ plain();+ return;+ }+ QVariantMap chosen = variants.first().toMap();+ for (const auto &v : variants)+ if (v.toMap().value("synced").toBool()) {+ chosen = v.toMap();+ break;+ }+ QVariantList lines;+ QStringList text;+ QString lrc;+ const auto offset = chosen.value("offset").toLongLong();+ for (const auto &v : chosen.value("line").toList()) {+ const auto line = v.toMap();+ text.append(line.value("value").toString());+ if (chosen.value("synced").toBool()) {+ const qint64 ms =+ qMax<qint64>(0, line.value("start").toLongLong() - offset);+ lrc += QString("[%1:%2.%3]%4\n")+ .arg(ms / 60000)+ .arg(ms / 1000 % 60, 2, 10, QChar('0'))+ .arg(ms % 1000, 3, 10, QChar('0'))+ .arg(line.value("value").toString());+ }+ }+ lines = Lrc::parse(lrc);+ callback({{"ok", true},+ {"lines", lines},+ {"lyrics", text.join('\n')},+ {"source", "Music server"}},+ {});+ },+ "lyrics");+}+void SubsonicApi::download(const QVariantMap &track, const QString &path,+ Reply callback, const QString &channel) {+ cancel(channel);+ if (!owns(track)) {+ callback({}, "Connect to this song’s server in Settings.");+ return;+ }+ auto file = std::make_shared<QFile>(path);+ if (!file->open(QIODevice::WriteOnly)) {+ callback({}, "Could not create the audio buffer.");+ return;+ }+ file->setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);+ Params p{{"id", track.value("remoteId").toString()},+ {"format", bitrate() ? "mp3" : "raw"}};+ if (bitrate())+ p.append(QPair<QString, QString>{"maxBitRate", QString::number(bitrate())});+ QNetworkRequest request(url("stream", p));+ request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);+ request.setTransferTimeout(30000);+ request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::ManualRedirectPolicy);+ auto r = m_network.get(request);+ m_channels[channel] = r;+ r->setReadBufferSize(256 * 1024);+ const auto generation = m_generation;+ auto failed = std::make_shared<bool>(false);+ auto drain = [r, file, failed] {+ auto bytes = r->readAll();+ if (file->size() + bytes.size() > 512LL * 1024 * 1024 ||+ file->write(bytes) != bytes.size()) {+ *failed = true;+ r->abort();+ }+ };+ connect(r, &QNetworkReply::readyRead, this, drain);+ auto timer = new QTimer(r);+ timer->setSingleShot(true);+ connect(timer, &QTimer::timeout, r, &QNetworkReply::abort);+ timer->start(180000);+ connect(+ r, &QNetworkReply::finished, this,+ [this, r, file, failed, drain, generation, callback, path, channel] {+ if (m_channels.value(channel) == r) {+ m_channels.remove(channel);+ }+ drain();+ file->close();+ r->deleteLater();+ if (generation != m_generation)+ return;+ const auto type =+ r->header(QNetworkRequest::ContentTypeHeader).toString();+ const int status =+ r->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ if (*failed || r->error() != QNetworkReply::NoError || status != 200 ||+ type.contains("json") || type.contains("xml") ||+ type.contains("html") || file->size() == 0) {+ file->remove();+ callback({}, *failed+ ? "Audio exceeds the 512 MiB buffer limit, or the "+ "disk is full. Choose a lower server bitrate."+ : "Could not load this song from the server. Check "+ "the connection and retry.");+ return;+ }+ callback({{"ok", true}, {"file", path}}, {});+ });+}++QNetworkRequest SubsonicApi::artworkRequest(const QUrl &u) const {+ QNetworkRequest request(u);+ request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,+ QNetworkRequest::ManualRedirectPolicy);+ request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);+ request.setTransferTimeout(15000);+ return request;+}+void SubsonicApi::cover(const QVariantMap &track, const QString &path,+ Reply callback, const QString &channel) {+ cancel(channel);+ auto target = artworkUrl(QUrl(track.value("art").toString()));+ if (target.isEmpty()) {+ callback({}, {});+ return;+ }+ const int pixels = channel == "thumb" ? 256 : 1024;+ QUrlQuery query(target);+ query.removeAllQueryItems("size");+ query.addQueryItem("size", QString::number(pixels));+ target.setQuery(query);+ auto *r = m_network.get(artworkRequest(target));+ m_channels[channel] = r;+ const auto generation = m_generation;+ connect(r, &QNetworkReply::readyRead, this, [r] {+ if (r->bytesAvailable() > 4 * 1024 * 1024)+ r->abort();+ });+ auto *timer = new QTimer(r);+ timer->setSingleShot(true);+ connect(timer, &QTimer::timeout, r, &QNetworkReply::abort);+ timer->start(20000);+ connect(+ r, &QNetworkReply::finished, this,+ [this, r, generation, path, callback, channel, pixels] {+ if (m_channels.value(channel) == r)+ m_channels.remove(channel);+ r->deleteLater();+ if (generation != m_generation)+ return;+ if (r->error() != QNetworkReply::NoError ||+ r->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() !=+ 200) {+ callback({}, "Artwork is unavailable.");+ return;+ }+ auto bytes = r->readAll();+ if (bytes.size() > 4 * 1024 * 1024) {+ callback({}, "Artwork exceeds the size limit.");+ return;+ }+ QBuffer buffer(&bytes);+ buffer.open(QIODevice::ReadOnly);+ QImageReader reader(&buffer);+ const auto size = reader.size();+ if (!size.isValid() || size.width() > 10000 || size.height() > 10000) {+ callback({}, "Artwork could not be decoded.");+ return;+ }+ reader.setScaledSize(size.scaled(pixels, pixels, Qt::KeepAspectRatio));+ const auto image = reader.read();+ QSaveFile file(path);+ if (image.isNull() || !file.open(QIODevice::WriteOnly)) {+ callback({}, "Artwork could not be saved.");+ return;+ }+ file.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);+ if (!image.save(&file, "PNG") || !file.commit()) {+ callback({}, "Artwork could not be saved.");+ return;+ }+ callback({{"file", path}}, {});+ });+}+QUrl SubsonicApi::shareUrl(const QVariantMap &row) const {+ if (!owns(row))+ return {};+ // Server-specific web routes are not part of Subsonic. Share the clean server+ // address on other implementations, never a signed stream or artwork URL.+ QUrl u(address());+ if (m_serviceName == "Navidrome") {+ const auto kind = row.value("kind").toString();+ const auto id = kind == "song" ? row.value("albumId").toString()+ : row.value("remoteId").toString();+ if (!id.isEmpty() &&+ QStringList{"song", "album", "artist", "playlist"}.contains(kind))+ u.setFragment("/" + (kind == "song" ? QString("album") : kind) + "/" ++ QString::fromLatin1(QUrl::toPercentEncoding(id)) + "/show");+ }+ return u;+}+static QString playlistRevision(const QVariantList &rows) {+ QStringList ids;+ for (const auto &v : rows)+ ids.append(v.toMap().value("id").toString());+ return hash(ids.join('\n'));+}+void SubsonicApi::playlistAccess(const QString &id, Reply callback) {+ if (!connected() || id.isEmpty()) {+ callback({}, "Reconnect and refresh the playlist.");+ return;+ }+ call("getPlaylist", {{"id", id}},+ [this, callback](const QVariantMap &d, const QString &e) {+ if (!e.isEmpty()) {+ callback({}, e);+ return;+ }+ const auto p = d.value("playlist").toMap();+ if (p.value("owner").toString() != m_username) {+ callback({}, "Only the playlist owner can edit this playlist.");+ return;+ }+ if (p.value("entry").toList().size() > 20000) {+ callback({}, "This playlist exceeds the 20,000-song limit.");+ return;+ }+ callback(p, {});+ });+}+void SubsonicApi::movePlaylistItem(const QString &id, const QString &entry,+ int to, Reply callback) {+ playlistAccess(id, [this, id, entry, to, callback](const QVariantMap &p,+ const QString &e) {+ if (!e.isEmpty()) {+ callback({}, e);+ return;+ }+ auto rows = p.value("entry").toList();+ bool ok = false;+ const int from = entry.section(':', 1).toInt(&ok);+ if (!ok || entry.section(':', 0, 0) != playlistRevision(rows) || from < 0 ||+ to < 0 || from >= rows.size() || to >= rows.size()) {+ callback({}, "The playlist changed. Refresh it before reordering.");+ return;+ }+ rows.move(from, to);+ Params params{{"playlistId", id}};+ for (const auto &v : rows)+ params.append({"songId", v.toMap().value("id").toString()});+ call("createPlaylist", params,+ [this, callback](const QVariantMap &d, const QString &e) {+ if (e.isEmpty())+ reloadPlaylists();+ callback(d, e);+ });+ });+}+void SubsonicApi::reportPlayback(const QVariantMap &track, qint64 position,+ bool paused, bool stopped) {+ const auto now = QDateTime::currentMSecsSinceEpoch();+ const auto id = track.value("id").toString();+ if (!scrobbling() || !owns(track)) {+ m_playing.clear();+ m_lastReport = 0;+ m_listened = 0;+ m_wasPlaying = false;+ return;+ }+ if (m_playing != id) {+ m_playing = id;+ m_playStarted = now;+ m_listened = 0;+ m_submitted = false;+ m_wasPlaying = false;+ m_lastReport = 0;+ }+ if (m_lastReport && m_wasPlaying)+ m_listened += qBound<qint64>(0LL, now - m_lastReport, 15000LL);+ m_lastReport = now;+ m_wasPlaying = !paused && !stopped;+ const auto duration = track.value("seconds").toLongLong() * 1000;+ const auto threshold =+ duration > 0 ? qMin<qint64>(duration / 2, 240000) : 240000;+ auto done = [this](const QVariantMap &, const QString &error) {+ if (!error.isEmpty())+ emit message(error);+ };+ if (!m_submitted && m_listened >= threshold && threshold > 0) {+ m_submitted = true;+ scrobble(track, true, m_playStarted, done);+ } else if (!paused && !stopped && position >= 0)+ scrobble(track, false, now, done);+ if (stopped) {+ m_playing.clear();+ m_lastReport = 0;+ m_wasPlaying = false;+ }+}diff --git a/src/subsonicapi.h b/src/subsonicapi.hnew file mode 100644index 0000000..da3de22--- /dev/null+++ b/src/subsonicapi.h@@ -0,0 +1,98 @@+#pragma once+#include "remotemusicapi.h"+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QObject>+#include <QPointer>+#include <QSet>+#include <QSettings>+#include <QUrlQuery>+#include <functional>++// One configured account. Track identity includes server and user, never+// credentials.+class SubsonicApi : public RemoteMusicApi {+ Q_OBJECT+public:+ using Reply = std::function<void(const QVariantMap &, const QString &)>;+ using Params = QList<QPair<QString, QString>>;+ explicit SubsonicApi(bool restore = true, const QString &settingsPath = {});+ QString serviceName() const override { return m_serviceName; }+ QString scheme() const override { return "subsonic"; }+ QUrl shareUrl(const QVariantMap &) const override;+ QNetworkRequest artworkRequest(const QUrl &u) const override;+ void reportPlayback(const QVariantMap &, qint64, bool, bool) override;+ void movePlaylistItem(const QString &, const QString &, int, Reply) override;+ ~SubsonicApi() override;+ bool connected() const { return m_connected; }+ bool connecting() const { return m_connecting; }+ QString address() const { return m_address; }+ QString username() const { return m_username; }+ QString identity() const { return m_identity; }+ QString error() const { return m_error; }+ QVariantList playlists() const { return m_playlists; }+ QVariantList folders() const { return m_folders; }+ QString folder() const {+ return m_settings.value("subsonic/folder").toString();+ }+ void setFolder(const QString &id);+ bool scrobbling() const {+ return m_settings.value("subsonic/scrobble", true).toBool();+ }+ void setScrobbling(bool value);+ int bitrate() const {+ return m_settings.value("subsonic/bitrate", 0).toInt();+ }+ void setBitrate(int value);+ bool keyringAvailable() const;+ Q_INVOKABLE void connectServer(const QString &address, const QString &user,+ const QString &password, bool remember = true);+ Q_INVOKABLE void disconnectServer();+ Q_INVOKABLE void reloadPlaylists();+ void createPlaylist(const QString &name, Reply callback = {});+ void call(const QString &method, const Params ¶ms, Reply callback,+ const QString &channel = {});+ void cancel(const QString &channel);+ void browse(const QVariantMap &request, Reply callback,+ const QString &channel = "catalog");+ void cover(const QVariantMap &track, const QString &path, Reply callback,+ const QString &channel = "cover");+ void lyrics(const QVariantMap &track, Reply callback);+ void download(const QVariantMap &track, const QString &path, Reply callback,+ const QString &channel = "audio");+ void star(const QVariantMap &track, bool starred, Reply callback);+ void rate(const QVariantMap &track, int rating, Reply callback);+ void editPlaylist(const QString &id, const Params ¶ms, Reply callback);+ void removePlaylist(const QString &id, Reply callback);+ bool owns(const QVariantMap &track) const;+ bool isStarred(const QString &id) const { return m_stars.contains(id); }+ QVariantMap item(const QVariantMap &raw, const QString &kind) const;+ QUrl artworkUrl(const QUrl &reference) const;+ void scrobble(const QVariantMap &track, bool submission, qint64 timestamp,+ Reply callback);++private:+ QUrl url(const QString &method, const Params ¶ms) const;++protected:+ void secret(const QStringList &arguments, const QByteArray &input,+ std::function<void(bool, QByteArray)> callback);++private:+ void discover();+ void playlistAccess(const QString &, Reply);+ QString m_serviceName = "Subsonic", m_playing;+ qint64 m_playStarted = 0, m_listened = 0, m_lastReport = 0;+ bool m_submitted = false, m_wasPlaying = false;+ QVariantList items(const QVariant &rows, const QString &kind) const;+ void stopRequests();+ QNetworkAccessManager m_network;+ QSettings m_settings;+ QString m_address, m_username, m_password, m_identity, m_error;+ bool m_connected = false, m_connecting = false, m_lyricsExtension = false,+ m_formPost = false, m_restoring = false;+ quint64 m_generation = 0;+ QHash<QString, QPointer<QNetworkReply>> m_channels;+ QSet<QString> m_stars;+ QVariantList m_playlists, m_folders;+};diff --git a/src/subsonicprotocoltest.cpp b/src/subsonicprotocoltest.cppnew file mode 100644index 0000000..4bd7a8f--- /dev/null+++ b/src/subsonicprotocoltest.cpp@@ -0,0 +1,585 @@+#include "remotelibrary.h"+#include "subsonicapi.h"+#include <QBuffer>+#include <QDir>+#include <QFile>+#include <QJsonArray>+#include <QJsonDocument>+#include <QTcpServer>+#include <QTcpSocket>+#include <QTemporaryDir>+#include <QtTest>++class ProtocolTest : public QObject {+ Q_OBJECT+ QTemporaryDir storage;+ QTcpServer http;+ QString mode, received;+ QString base;+ QStringList requests;+ std::function<QVariantMap(const QString &, const QUrlQuery &)> responder;++private slots:+ void initTestCase() {+ qputenv("XDG_CONFIG_HOME", storage.path().toUtf8());+ QCoreApplication::setOrganizationName("SpunTests");+ QCoreApplication::setApplicationName("protocol");+ QVERIFY(http.listen(QHostAddress::LocalHost));+ base = "http://127.0.0.1:" + QString::number(http.serverPort());+ connect(&http, &QTcpServer::newConnection, this, [this] {+ while (http.hasPendingConnections()) {+ auto socket = http.nextPendingConnection();+ connect(socket, &QTcpSocket::disconnected, socket,+ &QObject::deleteLater);+ connect(socket, &QTcpSocket::readyRead, this, [this, socket] {+ auto buffer =+ socket->property("request").toByteArray() + socket->readAll();+ socket->setProperty("request", buffer);+ if (!buffer.contains("\r\n\r\n") || socket->property("sent").toBool())+ return;+ const int end = buffer.indexOf("\r\n\r\n");+ int length = 0;+ for (const auto &line : buffer.left(end).split('\n'))+ if (line.toLower().startsWith("content-length:"))+ length = line.mid(15).trimmed().toInt();+ if (buffer.size() < end + 4 + length)+ return;+ socket->setProperty("sent", true);+ received = QString::fromUtf8(buffer);+ requests.append(received);+ if (mode == "hold")+ return;+ QByteArray status = "200 OK",+ body = "{\"subsonic-response\":{\"status\":\"ok\","+ "\"version\":\"1.16.1\"}}",+ extra;+ if (responder) {+ const QUrl target("http://fixture" ++ QString::fromUtf8(buffer.split(' ').value(1)));+ QUrlQuery params(target);+ if (buffer.startsWith("POST "))+ params = QUrlQuery(QString::fromUtf8(buffer.mid(end + 4)));+ auto payload = responder(+ target.path().section('/', -1).section('.', 0, 0), params);+ if (!payload.contains("status"))+ payload["status"] = "ok";+ body = QJsonDocument(+ QJsonObject{{"subsonic-response",+ QJsonObject::fromVariantMap(payload)}})+ .toJson();+ }+ if (mode == "image" && received.contains("/getCoverArt.view")) {+ QImage image(1000, 500, QImage::Format_RGB32);+ image.fill(Qt::blue);+ QBuffer output(&body);+ output.open(QIODevice::WriteOnly | QIODevice::Truncate);+ image.save(&output, "PNG");+ }+ if (mode == "redirect") {+ status = "302 Found";+ extra = "Location: http://127.0.0.1:1/credential-leak\r\n";+ }+ if (mode == "malformed")+ body = "<html>Not a music server</html>";+ if (mode == "denied")+ body = "{\"subsonic-response\":{\"status\":\"failed\",\"error\":{"+ "\"code\":50}}}";+ if (mode == "disconnect") {+ socket->abort();+ return;+ }+ if (mode == "oversized")+ body = QByteArray(17 * 1024 * 1024, 'x');+ socket->write("HTTP/1.1 " + status + "\r\n" + extra ++ "Content-Type: application/json\r\nContent-Length: " ++ QByteArray::number(body.size()) ++ "\r\nConnection: close\r\n\r\n" + body);+ socket->disconnectFromHost();+ });+ }+ });+ }+ void init() {+ mode = "ok";+ received.clear();+ requests.clear();+ responder = {};+ }+ void validatesAddress() {+ SubsonicApi client;+ client.connectServer("https://user:[email protected]", "user", "password",+ false);+ QVERIFY(!client.connecting());+ QVERIFY(!client.error().isEmpty());+ client.connectServer(base + "/rest", "user", "password", false);+ QVERIFY(!client.connecting());+ QVERIFY(!client.error().isEmpty());+ }+ void rejectsUnsafeAndInvalidResponses_data() {+ QTest::addColumn<QString>("behavior");+ for (const auto &v :+ {"redirect", "malformed", "denied", "disconnect", "oversized"})+ QTest::newRow(v) << QString(v);+ }+ void rejectsUnsafeAndInvalidResponses() {+ QFETCH(QString, behavior);+ mode = behavior;+ SubsonicApi client;+ client.connectServer(base, "fixture", "test-secret", false);+ QTRY_VERIFY_WITH_TIMEOUT(!client.connecting(), 5000);+ QVERIFY(!client.connected());+ QVERIFY(!client.error().isEmpty());+ QVERIFY(!client.error().contains("test-secret"));+ }+ void encodesSpecialCharactersAndFreshSalt() {+ mode = "hold";+ SubsonicApi client;+ client.connectServer(base + "/music", "a+b & café", "never-in-url", false);+ QTRY_VERIFY(received.contains("/music/rest/ping.view"));+ QVERIFY(received.contains("a%2Bb%20%26%20caf%C3%A9"));+ QVERIFY(!received.contains("never-in-url"));+ const auto first = received;+ received.clear();+ client.connectServer(base + "/music", "a+b & café", "never-in-url", false);+ QTRY_VERIFY(!received.isEmpty());+ QVERIFY(received != first);+ client.disconnectServer();+ QVERIFY(!client.connecting());+ }+ void keyringSaveRestoreAndForget() {+ mode = "ok";+ const auto oldPath = qgetenv("PATH");+ const auto bin = storage.filePath("bin");+ QDir().mkpath(bin);+ const auto secretFile = storage.filePath("keyring-value");+ QFile tool(bin + "/secret-tool");+ QVERIFY(tool.open(QIODevice::WriteOnly));+ tool.write(R"PY(#!/usr/bin/python3+import os, pathlib, sys+p=pathlib.Path(os.environ['SPUN_TEST_KEYRING'])+if sys.argv[1]=='store':+ p.write_bytes(sys.stdin.buffer.read())+ p.chmod(0o600)+elif sys.argv[1]=='lookup':+ if not p.exists(): sys.exit(1)+ sys.stdout.buffer.write(p.read_bytes()+b'\n')+elif sys.argv[1]=='clear':+ p.unlink(missing_ok=True)+else:+ sys.exit(2)+)PY");+ tool.close();+ QVERIFY(tool.setPermissions(QFileDevice::ReadOwner |+ QFileDevice::WriteOwner |+ QFileDevice::ExeOwner));+ qputenv("PATH", bin.toUtf8() + ":" + oldPath);+ qputenv("SPUN_TEST_KEYRING", secretFile.toUtf8());+ const auto restore = qScopeGuard([&] {+ qputenv("PATH", oldPath);+ qunsetenv("SPUN_TEST_KEYRING");+ });+ {+ SubsonicApi client;+ client.connectServer(base, "fixture", "keyring fixture + café", true);+ QTRY_VERIFY(client.connected());+ QTRY_VERIFY(QSettings().value("subsonic/remember").toBool());+ QVERIFY(QFile::exists(secretFile));+ QFile config(QSettings().fileName());+ QSettings().sync();+ QVERIFY(config.open(QIODevice::ReadOnly));+ QVERIFY(!config.readAll().contains("keyring fixture"));+ }+ {+ SubsonicApi client;+ QTRY_VERIFY(client.connected());+ QCOMPARE(client.username(), QString("fixture"));+ client.disconnectServer();+ QTRY_VERIFY(!QFile::exists(secretFile));+ QVERIFY(!QSettings().contains("subsonic/remember"));+ }+ }+ void cancelAndReconnect() {+ mode = "hold";+ SubsonicApi client;+ client.connectServer(base, "fixture", "secret", false);+ QTest::qWait(50);+ client.disconnectServer();+ mode = "ok";+ QTest::qWait(50);+ QVERIFY(!client.connected());+ client.connectServer(base, "fixture", "secret", false);+ QTRY_VERIFY(client.connected());+ bool callback = false;+ mode = "hold";+ client.call(+ "search3", {},+ [&](const QVariantMap &, const QString &) { callback = true; },+ "catalog");+ QTest::qWait(50);+ client.cancel("catalog");+ QTest::qWait(50);+ QVERIFY(!callback);+ mode = "ok";+ client.call(+ "search3", {},+ [&](const QVariantMap &, const QString &e) { callback = e.isEmpty(); },+ "catalog");+ QTRY_VERIFY(callback);+ }+ void formPostAndLegacyFallback() {+ responder = [](const QString &method, const QUrlQuery &) -> QVariantMap {+ if (method == "getOpenSubsonicExtensions")+ return {{"openSubsonicExtensions",+ QVariantList{QVariantMap{{"name", "formPost"},+ {"versions", QVariantList{1}}}}}};+ return {};+ };+ SubsonicApi client(false);+ client.connectServer(base + "/music", "fixture", "private", false);+ QTRY_VERIFY(client.connected());+ QTest::qWait(150);+ requests.clear();+ bool done = false;+ client.call(+ "createPlaylist", {{"name", "a+b & café"}},+ [&](const QVariantMap &, const QString &e) { done = e.isEmpty(); });+ QTRY_VERIFY(done);+ QVERIFY(received.startsWith("POST /music/rest/createPlaylist.view HTTP"));+ QVERIFY(received.contains("a%2Bb%20%26%20caf%C3%A9"));+ QVERIFY(!received.contains("private"));+ QVERIFY(!received.section("\r\n", 0, 0).contains("t="));+ client.disconnectServer();+ responder = {};+ client.connectServer(base, "fixture", "private", false);+ QTRY_VERIFY(client.connected());+ QTest::qWait(100);+ done = false;+ client.call(+ "search3", {{"query", "*"}},+ [&](const QVariantMap &, const QString &e) { done = e.isEmpty(); });+ QTRY_VERIFY(done);+ QVERIFY(received.startsWith("GET /rest/search3.view?"));+ }+ void preciseApiErrors_data() {+ QTest::addColumn<int>("code");+ QTest::addColumn<QString>("text");+ QTest::newRow("credentials") << 40 << QString("password");+ QTest::newRow("token-auth") << 41 << QString("token authentication");+ QTest::newRow("permission") << 50 << QString("allow");+ QTest::newRow("premium") << 60 << QString("Premium");+ QTest::newRow("missing") << 70 << QString("no longer exists");+ QTest::newRow("version") << 20 << QString("incompatible");+ }+ void preciseApiErrors() {+ QFETCH(int, code);+ QFETCH(QString, text);+ responder = [code](const QString &, const QUrlQuery &) -> QVariantMap {+ return {{"status", "failed"},+ {"error",+ QVariantMap{{"code", code},+ {"message", "DO NOT DISPLAY signed-url-token"}}}};+ };+ SubsonicApi client(false);+ client.connectServer(base, "fixture", "private", false);+ QTRY_VERIFY(!client.connecting());+ QVERIFY(!client.connected());+ QVERIFY(client.error().contains(text));+ QVERIFY(!client.error().contains("signed-url"));+ }+ void lyricsExtensionAndFallback() {+ bool legacy = false;+ responder = [&](const QString &method, const QUrlQuery &) -> QVariantMap {+ if (method == "getOpenSubsonicExtensions")+ return {{"openSubsonicExtensions",+ QVariantList{QVariantMap{{"name", "songLyrics"},+ {"versions", QVariantList{1}}}}}};+ if (method == "getLyricsBySongId" && !legacy)+ return {{"lyricsList",+ QVariantMap{+ {"structuredLyrics",+ QVariantList{QVariantMap{+ {"synced", true},+ {"offset", 1000},+ {"line",+ QVariantList{+ QVariantMap{{"start", 2000}, {"value", "One"}},+ QVariantMap{{"start", 5000},+ {"value", "Two"}}}}}}}}}};+ if (method == "getLyrics")+ return {{"lyrics", QVariantMap{{"value", "Legacy lyrics"}}}};+ return {};+ };+ SubsonicApi client(false);+ client.connectServer(base, "fixture", "private", false);+ QTRY_VERIFY(client.connected());+ QTest::qWait(150);+ auto song = client.item(+ {{"id", "song"}, {"title", "Title"}, {"artist", "Artist"}}, "song");+ QVariantMap result;+ bool done = false;+ client.lyrics(song, [&](const QVariantMap &d, const QString &e) {+ result = d;+ done = e.isEmpty();+ });+ QTRY_VERIFY(done);+ auto lines = result.value("lines").toList();+ QCOMPARE(lines.size(), 2);+ QCOMPARE(lines.first().toMap().value("start").toLongLong(), 1000LL);+ legacy = true;+ done = false;+ client.lyrics(song, [&](const QVariantMap &d, const QString &e) {+ result = d;+ done = e.isEmpty();+ });+ QTRY_VERIFY(done);+ QCOMPARE(result.value("lyrics").toString(), QString("Legacy lyrics"));+ }+ void staleAndDuplicatePlaylistEntries() {+ QVariantList entries{QVariantMap{{"id", "a"}}, QVariantMap{{"id", "b"}},+ QVariantMap{{"id", "a"}}};+ QString owner = "fixture";+ QUrlQuery mutation;+ int mutations = 0;+ responder = [&](const QString &method, const QUrlQuery &p) -> QVariantMap {+ if (method == "getPlaylist")+ return {+ {"playlist",+ QVariantMap{{"id", "p"}, {"owner", owner}, {"entry", entries}}}};+ if (method == "createPlaylist" || method == "updatePlaylist" ||+ method == "deletePlaylist") {+ mutation = p;+ ++mutations;+ }+ return {};+ };+ SubsonicApi client(false);+ client.connectServer(base, "fixture", "private", false);+ QTRY_VERIFY(client.connected());+ QTest::qWait(100);+ QVariantMap result;+ bool done = false;+ QString error;+ auto callback = [&](const QVariantMap &d, const QString &e) {+ result = d;+ error = e;+ done = true;+ };+ client.browse({{"mode", "playlist"}, {"remoteId", "p"}}, callback);+ QTRY_VERIFY(done);+ auto rows = result.value("items").toList();+ QCOMPARE(rows.size(), 3);+ auto first = rows[0].toMap().value("entryId").toString(),+ last = rows[2].toMap().value("entryId").toString();+ QVERIFY(first != last);+ done = false;+ client.editPlaylist("p", {{"entryIdToRemove", last}}, callback);+ QTRY_VERIFY(done);+ QVERIFY(error.isEmpty());+ QCOMPARE(mutation.queryItemValue("songIndexToRemove"), QString("2"));+ done = false;+ client.movePlaylistItem("p", first, 1, callback);+ QTRY_VERIFY(done);+ QVERIFY(error.isEmpty());+ QCOMPARE(mutation.allQueryItemValues("songId"),+ QStringList({"b", "a", "a"}));+ entries.prepend(QVariantMap{{"id", "new"}});+ const int count = mutations;+ done = false;+ client.movePlaylistItem("p", first, 1, callback);+ QTRY_VERIFY(done);+ QVERIFY(error.contains("changed"));+ QCOMPARE(mutations, count);+ done = false;+ client.editPlaylist("p", {{"entryIdToRemove", last}}, callback);+ QTRY_VERIFY(done);+ QVERIFY(error.contains("changed"));+ QCOMPARE(mutations, count);+ owner = "someone-else";+ done = false;+ client.removePlaylist("p", callback);+ QTRY_VERIFY(done);+ QVERIFY(error.contains("owner"));+ QCOMPARE(mutations, count);+ }+ void listeningTimeIgnoresSeeksAndPauses() {+ int submissions = 0, nowPlaying = 0;+ responder = [&](const QString &method, const QUrlQuery &p) -> QVariantMap {+ if (method == "scrobble") {+ if (p.queryItemValue("submission") == "true")+ ++submissions;+ else+ ++nowPlaying;+ }+ return {};+ };+ SubsonicApi client(false);+ client.connectServer(base, "fixture", "private", false);+ QTRY_VERIFY(client.connected());+ QTest::qWait(100);+ client.setScrobbling(true);+ auto song = client.item({{"id", "song"}, {"duration", 2}}, "song");+ client.reportPlayback(song, 0, false, false);+ QTRY_COMPARE(nowPlaying, 1);+ client.reportPlayback(song, 1900, true, false);+ QTest::qWait(1100);+ client.reportPlayback(song, 1900, true, false);+ QCOMPARE(submissions, 0);+ client.reportPlayback(song, 0, false, false);+ QTest::qWait(1100);+ client.reportPlayback(song, 1100, false, false);+ QTRY_COMPARE(submissions, 1);+ client.reportPlayback(song, 1500, false, false);+ QTest::qWait(100);+ QCOMPARE(submissions, 1);+ client.setScrobbling(false);+ const int reports = nowPlaying;+ client.reportPlayback(song, 0, false, false);+ QTest::qWait(1100);+ client.reportPlayback(song, 1500, false, false);+ QTest::qWait(100);+ QCOMPARE(submissions, 1);+ QCOMPARE(nowPlaying, reports);+ }+ void accountScopedReferencesAndMissingArt() {+ SubsonicApi client(false);+ client.connectServer(base, "fixture", "private", false);+ QTRY_VERIFY(client.connected());+ QTest::qWait(100);+ auto song = client.item(+ {{"id", "1"}, {"title", "Song"}, {"coverArt", "art"}}, "song");+ const auto serialized = QJsonDocument::fromVariant(song).toJson();+ QVERIFY(!serialized.contains("private"));+ QVERIFY(!serialized.contains("t="));+ QVERIFY(!serialized.contains("127.0.0.1"));+ QVERIFY(!client.artworkUrl(QUrl(song.value("art").toString())).isEmpty());+ bool done = false;+ client.cover(+ client.item({{"id", "2"}}, "song"), storage.filePath("missing.png"),+ [&](const QVariantMap &, const QString &) { done = true; }, "thumb");+ QVERIFY(done);+ auto old = client.identity();+ client.connectServer(base, "reader", "private", false);+ QTRY_VERIFY(client.connected());+ QVERIFY(client.identity() != old);+ QVERIFY(!client.owns(song));+ QVERIFY(client.artworkUrl(QUrl(song.value("art").toString())).isEmpty());+ done = false;+ client.download(+ song, storage.filePath("bad.audio"),+ [&](const QVariantMap &, const QString &e) { done = !e.isEmpty(); });+ QVERIFY(done);+ QVERIFY(!QFile::exists(storage.filePath("bad.audio")));+ }++ void coversRecoverAndUseIndependentChannels() {+ SubsonicApi client(false);+ client.connectServer(base, "fixture", "private", false);+ QTRY_VERIFY(client.connected());+ QTest::qWait(100);+ auto song = client.item({{"id", "1"}, {"coverArt", "art"}}, "song");+ bool done = false;+ QString error;+ mode = "malformed";+ client.cover(+ song, storage.filePath("cover-error.png"),+ [&](const QVariantMap &, const QString &e) {+ done = true;+ error = e;+ },+ "thumb");+ QTRY_VERIFY(done);+ QVERIFY(!error.isEmpty());+ mode = "image";+ int completed = 0;+ for (const auto &channel : {QString("cover"), QString("thumb")})+ client.cover(+ song, storage.filePath(channel + ".png"),+ [&](const QVariantMap &, const QString &e) {+ if (e.isEmpty())+ ++completed;+ },+ channel);+ QTRY_COMPARE(completed, 2);+ QCOMPARE(QImage(storage.filePath("thumb.png")).size(), QSize(256, 128));+ QCOMPARE(QImage(storage.filePath("cover.png")).size(), QSize(1024, 512));+ mode = "hold";+ done = false;+ client.cover(+ song, storage.filePath("stale.png"),+ [&](const QVariantMap &, const QString &) { done = true; }, "thumb");+ QTest::qWait(50);+ client.cancel("thumb");+ QTest::qWait(50);+ QVERIFY(!done);+ QVERIFY(!QFile::exists(storage.filePath("stale.png")));+ }+ void classicPagingPlaylistSearchAndFavorites() {+ responder = [](const QString &method, const QUrlQuery &p) -> QVariantMap {+ if (method == "getPlaylists")+ return {{"playlists",+ QVariantMap{{"playlist",+ QVariantList{QVariantMap{{"id", "p"},+ {"name", "Evening Mix"},+ {"owner", "fixture"}},+ QVariantMap{{"id", "q"},+ {"name", "Morning Mix"},+ {"owner", "other"}}}}}}};+ if (method == "search3") {+ QVariantList songs;+ const int start = p.queryItemValue("songOffset").toInt();+ for (int i = start; i < qMin(start + 100, 105); ++i)+ songs.append(QVariantMap{{"id", QString::number(i)},+ {"title", QString::number(i)}});+ return {{"searchResult3", QVariantMap{{"song", songs}}}};+ }+ if (method == "getStarred2") {+ QVariantList songs;+ for (int i = 0; i < 105; ++i)+ songs.append(QVariantMap{{"id", QString::number(i)}});+ return {{"starred2", QVariantMap{{"song", songs},+ {"album", QVariantList{QVariantMap{+ {"id", "album"}}}}}}};+ }+ return {};+ };+ SubsonicApi client(false);+ client.connectServer(base, "fixture", "private", false);+ QTRY_VERIFY(client.connected());+ QTest::qWait(100);+ QVariantMap result;+ bool done = false;+ auto cb = [&](const QVariantMap &d, const QString &e) {+ result = d;+ done = e.isEmpty();+ };+ client.browse({{"mode", "songs"}}, cb);+ QTRY_VERIFY(done);+ QCOMPARE(result.value("items").toList().size(), 100);+ QVERIFY(result.value("more").toBool());+ QVERIFY(received.contains("query=%2A"));+ done = false;+ client.browse({{"mode", "songs"}, {"offset", 100}}, cb);+ QTRY_VERIFY(done);+ QCOMPARE(result.value("items").toList().size(), 5);+ QVERIFY(!result.value("more").toBool());+ done = false;+ client.browse(+ {{"mode", "search"}, {"filter", "playlists"}, {"query", "evening"}},+ cb);+ QTRY_VERIFY(done);+ QCOMPARE(result.value("items").toList().size(), 1);+ QCOMPARE(+ result.value("items").toList().first().toMap().value("kind").toString(),+ QString("playlist"));+ done = false;+ client.browse({{"mode", "favorites"}, {"offset", 100}}, cb);+ QTRY_VERIFY(done);+ QCOMPARE(result.value("items").toList().size(), 5);+ QVERIFY(client.isStarred(+ client.item({{"id", "0"}}, "song").value("id").toString()));+ QVERIFY(client.isStarred(+ client.item({{"id", "album"}}, "album").value("id").toString()));+ }+};+QTEST_GUILESS_MAIN(ProtocolTest)+#include "subsonicprotocoltest.moc"diff --git a/src/subsonictest.cpp b/src/subsonictest.cppnew file mode 100644index 0000000..6e2b057--- /dev/null+++ b/src/subsonictest.cpp@@ -0,0 +1,528 @@+#include "subsonictest.h"+#include "mpris.h"+#include "subsonicapi.h"+#include "testcapture.h"+#include "testinput.h"+#include "tx6.h"+#include <QDir>+#include <QFile>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QNetworkAccessManager>+#include <QQmlContext>+#include <QSignalSpy>+#include <QTest>+#include <iostream>++namespace {+bool until(const std::function<bool()> &fn, int timeout = 15000) {+ QElapsedTimer t;+ t.start();+ while (!fn() && t.elapsed() < timeout)+ QTest::qWait(20);+ return fn();+}+QQuickItem *find(QQuickItem *item, const QString &name) {+ if (item->objectName() == name)+ return item;+ for (auto *child : item->childItems())+ if (auto *found = find(child, name))+ return found;+ return nullptr;+}+} // namespace+int exerciseSubsonic(Player &local, RemoteLibrary &jf, QQuickWindow *window,+ const QString &temp, const QString &captures) {+ int checks = 0, failures = 0;+ auto check = [&](bool ok, const char *text) {+ ++checks;+ if (!ok)+ ++failures;+ std::cout << (ok ? "PASS " : "FAIL ") << text << std::endl;+ return ok;+ };+ auto capture = [&](const QString &name) {+ if (captures.isEmpty())+ return;+ QTest::qWait(250);+ QDir().mkpath(captures);+ check(until([&] {+ return qAbs(window->width() -+ qRound(window->property("layoutWidth").toDouble() *+ window->property("uiScale").toDouble())) < 2;+ }),+ "native window fits complete layout");+ QImage image;+ check(+ until(+ [&] {+ window->requestUpdate();+ image = captureTestWindow(window);+ return image.size() ==+ QSize(+ qRound(window->width() * window->devicePixelRatio()),+ qRound(window->height() * window->devicePixelRatio()));+ },+ 5000),+ "capture matches current window dimensions");+ check(!image.isNull() && image.save(captures + "/" + name + ".png"),+ "rendered capture saved");+ };+ auto click = [&](const QString &name) {+ auto *item = find(window->contentItem(), name);+ if (!check(item != nullptr, qPrintable("control exists: " + name)))+ return;+ QTest::mouseClick(+ window, Qt::LeftButton, Qt::NoModifier,+ item->mapToScene(QPointF(item->width() / 2, item->height() / 2))+ .toPoint());+ QTest::qWait(100);+ };+ window->setColor(QColor("#242a30"));+ auto *api = static_cast<SubsonicApi *>(jf.server());+ auto *player = jf.transport();+ player->setVolume(0);+ local.setVolume(0);+ const auto base = qEnvironmentVariable("SPUN_TEST_SERVER"),+ user = qEnvironmentVariable("SPUN_TEST_USER"),+ password = qEnvironmentVariable("SPUN_TEST_PASSWORD");+ if (!check(!base.isEmpty() && !password.isEmpty(),+ "disposable server environment configured"))+ return 1;+ auto fixtureCall = [&](const QString &method,+ const SubsonicApi::Params ¶ms =+ SubsonicApi::Params{}) {+ bool done = false;+ QVariantMap result;+ QString error;+ api->call(method, params, [&](const QVariantMap &d, const QString &e) {+ result = d;+ error = e;+ done = true;+ });+ check(until([&] { return done; }) && error.isEmpty(),+ qPrintable("fixture API: " + method));+ return result;+ };+ local.demo();+ check(until([&] { return local.count() > 0 && !local.busy(); }),+ "local queue fixture loaded");+ local.pause();+ auto localKey = local.trackKey();+ click("subsonicSourceButton");+ check(window->property("useSubsonic").toBool() && jf.enabled(),+ "Subsonic source selected");+ capture("subsonic-disconnected");+ click("subsonicConnect");+ check(until([&] {+ auto *f = find(window->contentItem(), "subsonicAddress");+ return f && f->isVisible();+ }),+ "connection dialog opens");+ check(+ until([&] {+ return find(window->contentItem(), "subsonicAddress")->hasActiveFocus();+ }),+ "connection starts with first input focused");+ QTest::keyClick(window, Qt::Key_Tab);+ check(find(window->contentItem(), "subsonicUsername")->hasActiveFocus(),+ "Tab moves to username");+ QTest::keyClick(window, Qt::Key_Tab, Qt::ShiftModifier);+ check(+ until([&] {+ return find(window->contentItem(), "subsonicAddress")->hasActiveFocus();+ }),+ "Shift Tab returns to server field");+ capture("subsonic-connect-dialog");+ for (const auto &entry :+ QList<QPair<QString, QString>>{{"subsonicAddress", base},+ {"subsonicUsername", user},+ {"subsonicPassword", password}}) {+ auto *field = find(window->contentItem(), entry.first);+ if (field)+ field->setProperty("text", entry.second);+ }+ if (auto *remember = find(window->contentItem(), "subsonicRemember"))+ remember->setProperty("checked", false);+ click("subsonicSignIn");+ if (!check(until([&] { return api->connected(); }),+ "real server sign-in from UI"))+ return 1;+ check(api->serviceName() == "Navidrome",+ "Navidrome capability identification");+ check(until([&] { return !api->folders().isEmpty(); }),+ "music libraries discovered");+ check(find(window->contentItem(), "subsonicPassword")+ ->property("text")+ .toString()+ .isEmpty(),+ "password field cleared after sign-in");+ QMetaObject::invokeMethod(find(window->contentItem(), "subsonicPanel"),+ "closeActions");+ QTest::qWait(250);+ check(until([&] { return !jf.busy() && !jf.items().isEmpty(); }),+ "albums load after connection");+ capture("subsonic-albums");+ click("subsonicPageActions");+ click("subsonicSettings");+ capture("subsonic-settings");+ click("subsonicQuality");+ click("subsonicQuality_192");+ check(api->bitrate() == 192, "quality menu applies selected bitrate");+ api->setBitrate(0);+ QMetaObject::invokeMethod(find(window->contentItem(), "subsonicPanel"),+ "closeActions");+ const auto folder = api->folders().first().toMap().value("id").toString();+ api->setFolder(folder);+ jf.show("songs");+ check(!folder.isEmpty() && until([&] { return !jf.busy(); }) &&+ jf.items().size() == 100,+ "music folder selection scopes catalog");+ api->setFolder("");+ jf.search("Fixture");+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 100 &&+ jf.more(),+ "search first page and continuation");+ jf.loadMore();+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 105 &&+ !jf.more(),+ "search pagination returns all 105 songs");+ QSet<QString> ids;+ for (const auto &v : jf.items())+ ids.insert(v.toMap().value("id").toString());+ check(ids.size() == 105, "pagination preserves unique identities");+ if (jf.items().size() < 3)+ return 1;+ const auto songs = jf.items();+ auto first = songs[0].toMap(), second = songs[1].toMap(),+ third = songs[2].toMap();+ jf.search("Fixture 001");+ jf.search("Fixture 002");+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 1 &&+ jf.items()[0].toMap().value("title") == "Fixture 002",+ "latest search wins");+ jf.show("albums");+ check(until([&] { return !jf.busy(); }) && !jf.items().isEmpty(),+ "album browser");+ auto album = jf.items().first().toMap();+ jf.open(album);+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 35,+ "album opens complete ordered tracks");+ jf.back();+ check(until([&] { return !jf.busy(); }) && jf.page() == "albums",+ "back returns to albums");+ jf.show("artists");+ check(until([&] { return !jf.busy(); }) && !jf.items().isEmpty(),+ "artist browser");+ jf.open(jf.items().first().toMap());+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 3,+ "artist opens albums");+ jf.search("Fixture Album", "albums");+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 3,+ "album search");+ jf.search("Spun Test", "artists");+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 1,+ "artist search");+ jf.show("genres");+ check(until([&] { return !jf.busy(); }) && !jf.items().isEmpty(),+ "genre browser");+ jf.open(jf.items().first().toMap());+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 100 &&+ jf.more(),+ "genre opens paginated songs");+ jf.toggleFavorite(first);+ check(until([&] { return !jf.actionBusy(); }) &&+ jf.favorite(first.value("id").toString()),+ "server favorite saved");+ jf.show("favorites");+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 1,+ "favorites browser");+ jf.toggleFavorite(first);+ check(until([&] { return !jf.actionBusy() && !jf.busy(); }) &&+ jf.items().isEmpty(),+ "server favorite removed");+ click("subsonicPageActions");+ click("subsonicNewPlaylist");+ check(until([&] {+ auto *f = find(window->contentItem(), "subsonicPlaylistName");+ return f && f->hasActiveFocus();+ }),+ "playlist dialog receives keyboard focus");+ capture("subsonic-playlist-dialog");+ bool focusTrapped = true;+ auto *dialog = find(window->contentItem(), "subsonicNameDialog");+ for (int i = 0; i < 8; ++i) {+ QTest::keyClick(window, Qt::Key_Tab);+ QQuickItem *focus = window->activeFocusItem();+ while (focus && focus != dialog)+ focus = focus->parentItem();+ focusTrapped &= focus == dialog;+ }+ check(focusTrapped,+ "dialog retains keyboard focus through repeated Tab navigation");+ if (auto *f = find(window->contentItem(), "subsonicPlaylistName"))+ f->setProperty("text", "Spun fixture playlist");+ click("subsonicNameDialogAccept");+ check(until([&] { return api->playlists().size() == 1; }),+ "playlist created through UI");+ if (api->playlists().isEmpty())+ return 1;+ check(until([&] { return !jf.busy(); }) && jf.page() == "playlists" &&+ jf.items().size() == 1,+ "new playlist appears without manual refresh");+ check(find(window->contentItem(), "subsonicSearch")+ ->property("placeholderText")+ .toString() == "Search playlists",+ "playlist view keeps search filter in sync");+ jf.search("Spun fixture", "playlists");+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 1 &&+ jf.items()[0].toMap().value("kind") == "playlist",+ "playlist search returns playlists");+ auto playlist = api->playlists().first().toMap();+ const auto playlistId = playlist.value("remoteId").toString();+ check(playlist.value("editable").toBool(),+ "owner playlist editing available");+ jf.addToPlaylist(playlistId, first);+ check(until([&] { return !jf.actionBusy(); }), "first playlist song added");+ jf.addToPlaylist(playlistId, second);+ check(until([&] { return !jf.actionBusy(); }), "second playlist song added");+ jf.open(playlist);+ check(until([&] { return !jf.busy(); }) && jf.items().size() == 2,+ "playlist contains added songs");+ jf.movePlaylistItem(0, 1);+ check(until([&] { return !jf.actionBusy() && !jf.busy(); }) &&+ jf.items().last().toMap().value("remoteId") ==+ first.value("remoteId"),+ "playlist order updated on server");+ jf.removeFromPlaylist(jf.items().first().toMap());+ check(until([&] { return !jf.actionBusy() && !jf.busy(); }) &&+ jf.items().size() == 1,+ "playlist removal uses entry identity");+ jf.renamePlaylist(playlistId, "Renamed fixture");+ check(until([&] { return !jf.actionBusy() && !jf.busy(); }) &&+ jf.heading() == "Renamed fixture",+ "playlist renamed on server");+ capture("subsonic-playlist");+ for (const auto &song : QVariantList{first, second, third}) {+ jf.playItem(song.toMap());+ check(until([&] { return player->position() > 500; }),+ "native audio playback advances");+ check(player->duration() > 11000 &&+ player->title() == song.toMap().value("title"),+ "native duration and public metadata");+ player->pause();+ auto pos = player->position();+ QTest::qWait(100);+ check(!player->playing() && qAbs(player->position() - pos) < 100,+ "pause freezes transport");+ player->seek(5000);+ check(until([&] { return qAbs(player->position() - 5000) < 400; }),+ "buffered seek");+ }+ check(fixtureCall("getNowPlaying")+ .value("nowPlaying")+ .toMap()+ .value("entry")+ .toList()+ .size() > 0,+ "server receives now-playing reports");+ player->stop();+ jf.playItem(first);+ jf.playItem(second);+ jf.playItem(third);+ check(until([&] { return player->position() > 200; }) &&+ player->title() == third.value("title"),+ "rapid track changes discard obsolete audio downloads");+ player->pause();+ jf.playItems({first, second});+ check(until([&] { return player->position() > 200; }),+ "queue plays first song");+ player->pause();+ player->next(false, false);+ check(player->title() == second.value("title") && !player->playing(),+ "next preserves pause");+ player->play();+ check(until([&] { return player->position() > 200; }), "next song resolves");+ player->pause();+ jf.setActive(true);+ check(until([&] { return !jf.loading(); }) && jf.timed() &&+ jf.lines().size() == 3,+ "timed Subsonic lyrics");+ check(jf.seekToLine(1) &&+ until([&] { return qAbs(player->position() - 4000) < 400; }),+ "lyric seek uses player timeline");+ check(until([&] {+ const auto art = player->artwork();+ if (art.isNull())+ return false;+ const auto pixel = art.pixelColor(art.width() / 2, art.height() / 2);+ return qAbs(pixel.red() - 136) < 12 &&+ qAbs(pixel.green() - 204) < 12 &&+ qAbs(pixel.blue() - 238) < 12;+ }),+ "authenticated current artwork decoded");+ PlayerAdaptor media(&local, nullptr, nullptr, nullptr, player);+ media.setSourceWindow(window);+ check(media.metadata().value("xesam:title") == player->title(),+ "MPRIS uses Subsonic metadata");+ media.Play();+ check(until([&] { return player->playing(); }), "MPRIS plays Subsonic");+ media.Pause();+ check(!player->playing(), "MPRIS pauses Subsonic");+ click("localSourceButton");+ check(!jf.enabled() && !player->playing() && local.trackKey() == localKey,+ "source switch preserves local queue and pauses Subsonic");+ click("jellyfinSourceButton");+ check(window->property("useJellyfin").toBool() && !jf.enabled() &&+ !player->playing(),+ "Jellyfin and Subsonic remain separate sources");+ click("subsonicSourceButton");+ check(player->count() == 2, "Subsonic queue survives source switching");+ window->setProperty("libraryOpen", false);+ local.setShowPlayerBody(true);+ for (const auto &medium : QStringList{"cd", "vinyl", "cassette", "tp7"}) {+ local.setMedium(medium);+ local.setThreeD(false);+ QTest::qWait(180);+ check(window->property("deckPlayer").value<QObject *>() == player,+ "2D medium uses Subsonic transport");+ capture("subsonic-" + medium + "-2d");+ if (qEnvironmentVariable("QT_QUICK_BACKEND") != "software") {+ local.setThreeD(true);+ check(until([&] { return window->property("threeDActive").toBool(); }),+ "3D medium activates");+ QTest::qWait(500);+ capture("subsonic-" + medium + "-3d");+ player->seek(2000);+ click("playButton");+ check(until([&] { return player->position() > 2200; }) &&+ player->playing(),+ "3D transport starts Subsonic audio");+ click("playButton");+ check(!player->playing(), "3D transport pauses Subsonic audio");+ }+ }+ auto *mixer = qobject_cast<Tx6 *>(+ qmlContext(window)->contextProperty("tx6").value<QObject *>());+ if (check(mixer != nullptr, "TX-6 integration is available")) {+ mixer->setVisible(true);+ mixer->setPowered(true);+ mixer->reset();+ check(mixer->active(), "TX-6 routes Subsonic in TP-7 view");+ player->play();+ check(until([&] { return mixer->meters()[0].toDouble() > 0.00001; }),+ "decoded Subsonic audio reaches TX-6 mixer");+ player->pause();+ capture("subsonic-tx6");+ mixer->setVisible(false);+ }+ local.setMotion(false);+ QTest::qWait(100);+ check(find(window->contentItem(), "subsonicPanel")->opacity() == 1,+ "reduced motion leaves browser fully visible");+ local.setThreeD(false);+ fixtureCall("updatePlaylist",+ {{"playlistId", playlistId}, {"public", "true"}});+ api->connectServer(base, qEnvironmentVariable("SPUN_TEST_READER"), password,+ false);+ check(until([&] { return api->connected() && !api->playlists().isEmpty(); }),+ "shared playlist available to reader account");+ if (!api->playlists().isEmpty()) {+ jf.open(api->playlists().first().toMap());+ check(until([&] { return !jf.busy(); }) &&+ !jf.collection().value("editable").toBool() &&+ jf.items().size() == 1,+ "read-only playlist displays tracks without edit permission");+ jf.removeFromPlaylist(jf.items().value(0).toMap());+ check(!jf.actionBusy() && jf.items().size() == 1,+ "read-only playlist removal blocked locally");+ bool finished = false;+ QString permissionError;+ api->editPlaylist(playlistId, {{"name", "Not allowed"}},+ [&](const QVariantMap &, const QString &error) {+ permissionError = error;+ finished = true;+ });+ check(until([&] { return finished; }) && !permissionError.isEmpty(),+ "server rejects unauthorized playlist mutation");+ }+ api->connectServer(base, user, password, false);+ check(until([&] { return api->connected() && !api->playlists().isEmpty(); }),+ "owner account reconnects after permission checks");+ jf.deletePlaylist(playlistId);+ check(until([&] { return !jf.actionBusy() && api->playlists().isEmpty(); }),+ "playlist deleted on server");+ api->setBitrate(128);+ jf.playItem(first);+ check(until([&] { return player->position() > 300; }, 30000),+ "server transcoding plays at 128 kbps");+ const auto playedBefore =+ fixtureCall("getSong", {{"id", first.value("remoteId").toString()}})+ .value("song")+ .toMap()+ .value("playCount")+ .toInt();+ QTest::qWait(6500);+ player->pause();+ check(until(+ [&] {+ return fixtureCall("getSong",+ {{"id", first.value("remoteId").toString()}})+ .value("song")+ .toMap()+ .value("playCount")+ .toInt() > playedBefore;+ },+ 4000),+ "actual listening submits play count to server");+ jf.show("recent");+ check(until([&] { return !jf.busy(); }) && !jf.items().isEmpty(),+ "recently played albums");+ api->setScrobbling(false);+ player->play();+ const auto before =+ fixtureCall("getSong", {{"id", first.value("remoteId").toString()}})+ .value("song")+ .toMap()+ .value("playCount")+ .toInt();+ player->seek(3000);+ QTest::qWait(6500);+ const auto after =+ fixtureCall("getSong", {{"id", first.value("remoteId").toString()}})+ .value("song")+ .toMap()+ .value("playCount")+ .toInt();+ check(before == after, "disabled reporting does not submit listens");+ player->pause();+ api->setScrobbling(true);+ api->setBitrate(0);+ const auto identity = api->identity();+ api->disconnectServer();+ check(!api->connected() && player->count() == 0 && jf.items().isEmpty(),+ "disconnect clears private playback and browsing state");+ api->connectServer(base, user, password, false);+ check(until([&] { return api->connected(); }) &&+ api->identity() == identity && player->count() == 1 &&+ !player->playing(),+ "same account restores queue without autoplay");+ QFile config(temp + "/subsonic/connection.ini");+ if (config.open(QIODevice::ReadOnly)) {+ const auto bytes = config.readAll();+ check(!bytes.contains(password.toUtf8()) && !bytes.contains("AccessToken"),+ "settings contain no password or token");+ }+ api->connectServer(base, qEnvironmentVariable("SPUN_TEST_READER"), password,+ false);+ check(until([&] { return api->connected(); }) && player->count() == 0,+ "different account cannot inherit private queue");+ api->connectServer(base, user, "wrong-password", false);+ check(until([&] { return !api->connecting(); }) && !api->connected() &&+ !api->error().isEmpty(),+ "wrong password rejected with recoverable error");+ std::cout << "SUBSONIC_RESULT " << checks << " checks, " << failures+ << " failures" << std::endl;+ return failures ? 1 : 0;+}diff --git a/src/subsonictest.h b/src/subsonictest.hnew file mode 100644index 0000000..786a8e0--- /dev/null+++ b/src/subsonictest.h@@ -0,0 +1,5 @@+#pragma once+#include "remotelibrary.h"+#include <QQuickWindow>+int exerciseSubsonic(Player &, RemoteLibrary &, QQuickWindow *, const QString &,+ const QString &);