Skip to content

armgit / Spun

Public Imported from GitHub
0

A CD-shaped music player for Linux, with local playback and Cider integration.

Add native Jellyfin and anonymous YouTube Music support

yappologistic017584687baa
diff --git a/.gitignore b/.gitignore
index 7234b06..167e46c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,3 +51,12 @@
__pycache__/
cider-connection.json
listening.json
+
+!/helper/
+/helper/*
+!/helper/youtube.py
+!/helper/requirements.txt
+!/tests/
+/tests/*
+!/tests/youtube_fixture.py
+!/tests/test_youtube.py
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 42f39df..3aa2de9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -46,7 +46,7 @@ qt_add_library(spun_core STATIC
src/listening.cpp src/listening.h src/tapesound.cpp src/tapesound.h src/vinylnoise.cpp src/vinylnoise.h
src/musicactions.cpp src/musicactions.h
src/library.cpp src/library.h src/lyrics.cpp src/lyrics.h src/artwork.cpp src/artwork.h
- src/tx6.cpp src/tx6.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/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.h
src/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_PLUGIN
NO_RESOURCE_TARGET_PATH RESOURCE_PREFIX "/" OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${target}-qml"
- QML_FILES ${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/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)
# 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/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/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)
@@ -129,6 +129,15 @@ if(BUILD_TESTING)
set_tests_properties(spun-folder-import PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QPA_PLATFORMTHEME=")
add_test(NAME spun-refresh-independent-motion COMMAND spun-diagnostics --test-performance)
set_tests_properties(spun-refresh-independent-motion PROPERTIES ENVIRONMENT "SPUN_PERF_TIMING_ONLY=1;QT_QPA_PLATFORM=offscreen;QT_QUICK_BACKEND=software;QSG_RENDER_LOOP=basic;QT_QPA_PLATFORMTHEME=")
+ add_test(NAME spun-youtube COMMAND spun --test-youtube)
+ set_tests_properties(spun-youtube PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QUICK_BACKEND=software;QSG_RENDER_LOOP=basic;QT_QPA_PLATFORMTHEME=")
add_test(NAME spun-playback-and-ui COMMAND spun --self-test)
set_tests_properties(spun-playback-and-ui PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QUICK_BACKEND=software;QSG_RENDER_LOOP=basic;QT_QPA_PLATFORMTHEME=")
endif()
+
+if(BUILD_TESTING)
+ qt_add_executable(spun-jellyfin-protocol-test src/jellyfinprotocoltest.cpp)
+ target_link_libraries(spun-jellyfin-protocol-test PRIVATE spun_core Qt6::Test)
+ 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()
diff --git a/NOTICE b/NOTICE
index 4e902ca..884118c 100644
--- a/NOTICE
+++ b/NOTICE
@@ -41,3 +41,15 @@ The approved screenshot in assets/screenshots/spun-vinyl.png illustrates
Spun in use. Third-party album artwork and other third-party imagery shown
in it retain their respective rights and are not relicensed under Spun's
PolyForm Noncommercial license.
+
+Anonymous YouTube Music provider
+-------------------------------
+The normalization and catalog helper in helper/youtube.py is adapted from Sung,
+Copyright (c) 2026 Sung contributors, under the MIT license.
+See licenses/Sung-MIT.txt. Optional runtime dependencies are installed separately:
+ytmusicapi and yt-dlp. Spun is not affiliated with Google or YouTube.
+
+The Jellyfin client, LRC parser, protocol tests and disposable-server fixture in
+src/jellyfinapi.*, src/jellyfinlrc.h, src/jellyfinprotocoltest.cpp and
+scripts/test-jellyfin-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.md
index c71dabf..0078231 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,7 @@
<a href="#license">License</a>
</p>
-Play local music 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, 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,13 +136,63 @@ Choose a medium in **More → Preferences**. All four share playback controls, a
In 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 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 or Jellyfin 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.
Mixing happens inside Spun. External USB hardware, recording, MIDI, synth mode and separate aux/cue outputs are not supported. With Cider, only master volume works because Cider plays its own audio. Additional tracks use private temporary audio caches, removed on unload or normal exit, with a 512 MiB limit per track (about 23 minutes).
+### YouTube Music
+
+Choose **YouTube** in the source bar. Search songs, albums, artists and playlists,
+paste a YouTube or YouTube Music link, or use **Discover music**. Open an album or
+playlist to browse its songs; its menu offers **Play all**. Song menus provide
+queueing, radio, favorites, local playlists, album/artist navigation and link copying.
+Radio opens a suggested queue that you can play or edit.
+
+No Google login, account synchronization or browser cookies are used. Favorites,
+playlists, listening history and queue references stay on this device, separately
+from the Local queue. Playlist names and contents can be edited in the browser;
+history can be cleared from its menu. All four 2D/3D players, Mini, media keys,
+seeking, lyrics (when available) and the TX-6 audio route use the same native
+transport. Starting a song does not change the Local or Cider queue.
+
+YouTube support is optional. Install Python 3 with venv/pip support and Node.js,
+then run this from the source checkout:
+
+```sh
+./scripts/setup-youtube.sh
+```
+
+The helper runtime is isolated in `runtime/youtube`; it adds no browser engine
+and starts no background server. Local and Cider playback do not need it. After
+setup, use **Retry** if the YouTube panel was already open. The Nix package does
+not currently bundle the optional Python runtime; use the environment overrides
+below with a separately managed runtime.
+
+Audio is temporarily buffered before playback, with a 64 MiB limit per song and
+at most one next-song buffer. Buffers are removed when replaced or on normal exit;
+they are not an offline music library. Track starts depend on the network and may
+pause briefly. This unofficial integration depends on `ytmusicapi` and `yt-dlp`;
+YouTube changes can require dependency updates. Account-only or otherwise
+restricted songs may not play anonymously. There is no guarantee of gapless
+playback or parity with the official service.
+
+Local YouTube data is in `youtube/library.json` beside Spun's settings file.
+`--config /path/to/settings.ini` also isolates that library. `SPUN_YOUTUBE_PYTHON`
+and `SPUN_YOUTUBE_HELPER` can point to a separately managed runtime and helper.
+
+### Connect to Jellyfin
+
+Choose **Jellyfin**, then **Connect**. Enter your server URL (including its base path, if configured), username and password. Use HTTPS for remote servers. **Remember connection** stores the access token in the desktop keyring through `secret-tool`; passwords are never saved. Without a working keyring, sign in each time.
+
+Browse and search albums, artists, songs and playlists. Item menus provide favorites, queueing and playlist editing, including reordering and removal. Playlist permissions come from the server. Library actions include recently played songs, genres, refresh and server settings. Settings let you select a music library, choose original quality or 128/192/320 kbps, and turn playback reporting off.
+
+Jellyfin uses the same transport, queue, desktop media controls, timed lyrics and 2D/3D players as local music, including TX-6. Queues are saved separately for each server account and restore paused. Artwork and audio are fetched with authenticated requests; tokens are not embedded in shared links or saved queue entries.
+
+Playback 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.
+
### Browse through Cider
Use the top-left search button to browse songs, albums, playlists and artists without leaving Spun.
@@ -173,7 +223,7 @@ Cider changes refresh the visible queue and relevant details. Temporary connecti
Choose 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 or Cider 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 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.
**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.
@@ -249,6 +299,8 @@ ctest --test-dir build --output-on-failure
Tests use temporary preferences and synthetic local API fixtures. Audio checks need a working user audio session, and API fixtures need permission to listen on loopback. Desktop-control tests use a private D-Bus session. Diagnostics are separate from the normal player.
+The registered YouTube test uses local fixtures and needs no network or provider runtime. Run `python3 tests/test_youtube.py` for helper parsing checks. After setting up the optional runtime, `./build/spun --test-youtube-live` checks anonymous browsing, playback, seeking and artwork against the live service with temporary settings. `./scripts/preview-youtube.sh` opens a separate local preview profile with Cider and desktop media registration disabled.
+
For focused player, artwork, lighting, geometry and media checks:
```bash
@@ -257,6 +309,15 @@ For focused player, artwork, lighting, geometry and media checks:
The default uses offscreen CPU rendering through Mesa and requires an available X display for its OpenGL context. It does not create visible windows. It checks CD, cassette, recorder, turntable and TX-6 controls, mixer audio processing, physical rotation, seeking, rendered artwork and palette changes without exercising the full native window lifecycle.
+Jellyfin protocol tests run with CTest. For real-server integration checks, install a Jellyfin server binary and FFmpeg, then run:
+
+```bash
+python3 scripts/test-jellyfin-server.py --server-binary /path/to/jellyfin \
+ --test-binary build/spun-diagnostics --output /tmp/spun-jellyfin-test
+```
+
+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 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/flake.nix b/flake.nix
index ef369ce..73a68b5 100644
--- a/flake.nix
+++ b/flake.nix
@@ -57,6 +57,8 @@
install -Dm644 ../assets/First-Light.flac "$out/share/spun/First-Light.flac"
install -Dm644 ../assets/spun-icon.png "$out/share/icons/hicolor/512x512/apps/spun.png"
install -Dm644 ../LICENSE "$out/share/licenses/spun/LICENSE"
+ install -Dm644 ../helper/youtube.py "$out/share/spun/youtube.py"
+ install -Dm644 ../licenses/Sung-MIT.txt "$out/share/licenses/spun/Sung-MIT.txt"
install -Dm644 ../NOTICE "$out/share/licenses/spun/NOTICE"
runHook postInstall
'';
diff --git a/helper/requirements.txt b/helper/requirements.txt
new file mode 100644
index 0000000..1dc3213
--- /dev/null
+++ b/helper/requirements.txt
@@ -0,0 +1,2 @@
+ytmusicapi==1.12.2
+yt-dlp[default]==2026.8.19
diff --git a/helper/youtube.py b/helper/youtube.py
new file mode 100644
index 0000000..adf93d1
--- /dev/null
+++ b/helper/youtube.py
@@ -0,0 +1,168 @@
+#!/usr/bin/env python3
+"""One request per process. No server, browser, telemetry, or idle worker."""
+import json
+import re
+import sys
+from urllib.parse import urlparse, parse_qs
+
+
+def artwork(item):
+ thumbs = item.get('thumbnails') or []
+ if not thumbs:
+ return ''
+ src = thumbs[-1].get('url', '')
+ # Google returns tiny search thumbnails; ask the same image service for 544px.
+ if 'googleusercontent.com/' in src or 'ggpht.com/' in src:
+ src = re.sub(r'=w\d+-h\d+[^?]*$', '=w544-h544-l90-rj', src)
+ return src
+
+
+def normalize(item, kind='', parent=None):
+ parent = parent or {}
+ video = item.get('videoId') or ''
+ browse = item.get('browseId') or item.get('playlistId') or ''
+ kind = item.get('resultType') or kind or ('song' if video else 'playlist' if item.get('playlistId') else 'album')
+ artists = item.get('artists') or parent.get('artists') or []
+ if isinstance(artists, str):
+ artists = [{'name': artists}]
+ album = item.get('album') or {}
+ if isinstance(album, str):
+ album = {'name': album}
+ if parent.get('type') == 'album':
+ album = {'name': parent.get('title', ''), 'id': parent.get('browseId', '')}
+ author = item.get('author') or {}
+ artist_name = ', '.join(x.get('name', '') for x in artists)
+ if not artist_name and isinstance(author, dict):
+ artist_name = author.get('name', '')
+ return {'id': video or browse, 'videoId': video, 'browseId': browse,
+ 'kind': kind, 'title': item.get('title') or item.get('name') or (item.get('artist') if isinstance(item.get('artist'), str) else '') or 'Untitled',
+ 'artist': artist_name,
+ 'artistId': next((a.get('id') for a in artists if a.get('id')), browse if kind == 'artist' else ''),
+ 'album': album.get('name', ''), 'albumId': album.get('id', ''),
+ 'art': artwork(item) or artwork(parent), 'duration': item.get('duration') or item.get('length') or '',
+ 'seconds': item.get('duration_seconds') or 0,
+ 'discNumber': item.get('discNumber') or item.get('disc_number') or 1,
+ 'explicit': bool(item.get('isExplicit')), 'available': item.get('isAvailable', True)}
+
+
+def clean(items, kind='', parent=None):
+ return [t for i in items if isinstance(i, dict) and (t := normalize(i, kind, parent))['id']]
+
+
+def normalize_lyrics(data):
+ from dataclasses import asdict, is_dataclass
+ if is_dataclass(data): data=asdict(data)
+ data=data or {}
+ raw=data.get('lyrics') or ''
+ if isinstance(raw,str):return {'lyrics':raw,'lines':[]}
+ lines=[]
+ for line in raw:
+ if is_dataclass(line):line=asdict(line)
+ if not isinstance(line,dict):continue
+ start=line.get('start_time');end=line.get('end_time');text=line.get('text','')
+ if not isinstance(start,(int,float)) or start<0 or not isinstance(text,str):continue
+ lines.append({'start':int(start),'end':int(end) if isinstance(end,(int,float)) and end>=start else 0,'text':text})
+ lines.sort(key=lambda line:line['start'])
+ return {'lyrics':'\n'.join(line['text'] for line in lines),'lines':lines}
+
+
+
+def run(req):
+ op = req.get('op', '')
+ if op == 'check':
+ import ytmusicapi, yt_dlp, shutil
+ if not shutil.which('node'):
+ raise RuntimeError('Node.js is required for YouTube playback.')
+ return {'ready': True}
+ if op == 'buffer':
+ import yt_dlp
+ from pathlib import Path
+ vid = req.get('id', '')
+ if not re.fullmatch(r'[A-Za-z0-9_-]{11}', vid):
+ raise ValueError('Invalid YouTube song')
+ directory = Path(req['directory']).resolve(strict=True)
+ def bound_size(progress):
+ if progress.get('downloaded_bytes', 0) > 64*1024*1024:
+ raise RuntimeError('This song exceeds the 64 MiB playback buffer.')
+ opts = dict(quiet=True, noprogress=True, no_warnings=True, noplaylist=True,
+ format='bestaudio[ext=m4a]/bestaudio', socket_timeout=15,
+ retries=1, extractor_retries=1, cachedir=False,
+ js_runtimes={'node': {}}, max_filesize=64*1024*1024,
+ outtmpl=str(directory / (vid + '.%(ext)s')),
+ progress_hooks=[bound_size])
+ with yt_dlp.YoutubeDL(opts) as dl:
+ info = dl.extract_info('https://music.youtube.com/watch?v=' + vid, download=True)
+ path = Path(dl.prepare_filename(info))
+ if not path.is_file() or path.stat().st_size > 64*1024*1024:
+ raise RuntimeError('Could not buffer this song within the playback limit.')
+ return {'file': str(path), 'seconds': info.get('duration', 0)}
+ from ytmusicapi import YTMusic
+ api = YTMusic(requests_session=True)
+ original = api._session.request
+ def bounded(*args, **kwargs):
+ kwargs.setdefault('timeout', 15)
+ return original(*args, **kwargs)
+ api._session.request = bounded
+ if op == 'home':
+ return {'sections': [{'title': s.get('title', ''), 'items': clean(s.get('contents', []))}
+ for s in api.get_home(limit=5) if s.get('contents')]}
+ if op == 'search':
+ limit = min(max(int(req.get('limit', 30)), 1), 200)
+ return {'items': clean(api.search(req['query'], filter=req.get('filter') or None, limit=limit))}
+ if op == 'album':
+ data = api.get_album(req['id'])
+ data.update(type='album', browseId=req['id'])
+ return {'title': data.get('title', ''), 'artist': ', '.join(a.get('name','') for a in data.get('artists',[]) if isinstance(a,dict)), 'year': data.get('year',''), 'art': artwork(data), 'items': clean(data.get('tracks', []), 'song', data)}
+ if op == 'playlist':
+ data = api.get_playlist(req['id'], limit=min(int(req.get('limit', 100)), 5000))
+ return {'title': data.get('title', ''), 'art': artwork(data), 'items': clean(data.get('tracks', []), 'song', data), 'total': data.get('trackCount', 0)}
+ if op == 'artist':
+ data = api.get_artist(req['id'])
+ sections = []
+ for key, title, kind in [('songs','Songs','song'),('albums','Albums','album'),('singles','Singles','album'),('videos','Videos','video'),('related','Related artists','artist')]:
+ section = data.get(key) or {}
+ items = section.get('results', []) if isinstance(section, dict) else section
+ if items:
+ sections.append({'title':title,'items':clean(items,kind)})
+ return {'title':data.get('name',''), 'art':artwork(data), 'sections':sections}
+ if op == 'radio':
+ data = api.get_watch_playlist(videoId=req['id'], radio=True, limit=30)
+ return {'items': clean(data.get('tracks', []), 'song')}
+ if op == 'lyrics':
+ data = api.get_watch_playlist(videoId=req['id'], limit=1)
+ if not data.get('lyrics'): return {'lyrics': '', 'lines': []}
+ try: result = api.get_lyrics(data['lyrics'], timestamps=True)
+ except Exception: result = api.get_lyrics(data['lyrics'])
+ return normalize_lyrics(result)
+ if op == 'link':
+ parsed = urlparse(req['url'])
+ if parsed.hostname not in ('youtube.com','www.youtube.com','music.youtube.com','m.youtube.com','youtu.be'):
+ raise ValueError('Paste a YouTube or YouTube Music link')
+ query = parse_qs(parsed.query)
+ video = (query.get('v') or [''])[0]
+ if parsed.hostname == 'youtu.be':
+ video = parsed.path.strip('/')
+ if video:
+ data = api.get_song(video).get('videoDetails', {})
+ if not data:
+ raise ValueError('This song is unavailable')
+ t = normalize({'videoId':video,'title':data.get('title'), 'artists':[{'name':data.get('author',''),'id':data.get('channelId','')}], 'thumbnails':data.get('thumbnail',{}).get('thumbnails',[]), 'duration_seconds':int(data.get('lengthSeconds') or 0)}, 'song')
+ return {'title':t['title'],'items':[t]}
+ playlist = (query.get('list') or [''])[0]
+ if playlist:
+ return run({'op':'playlist','id':playlist,'limit':100})
+ raise ValueError('This link has no song or playlist')
+ raise ValueError('Unknown request')
+
+
+if __name__ == '__main__':
+ try:
+ payload = sys.stdin.read(65537)
+ if len(payload) > 65536: raise ValueError('Request is too large')
+ print(json.dumps({'ok': True, **run(json.loads(payload))}, ensure_ascii=False))
+ except Exception as exc:
+ # Keep provider diagnostics on stderr; the application displays a short,
+ # actionable message without stream URLs or server response bodies.
+ print(str(exc)[-1800:], file=sys.stderr)
+ print(json.dumps({'ok': False, 'error': 'YouTube could not complete this request.'}))
+ sys.exit(1)
diff --git a/licenses/Sung-MIT.txt b/licenses/Sung-MIT.txt
new file mode 100644
index 0000000..4ac4058
--- /dev/null
+++ b/licenses/Sung-MIT.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Sung contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/qml/JellyfinPanel.qml b/qml/JellyfinPanel.qml
new file mode 100644
index 0000000..f9b8025
--- /dev/null
+++ b/qml/JellyfinPanel.qml
@@ -0,0 +1,866 @@
+import QtQuick
+import QtQuick.Controls
+import QtQml.Models
+
+Rectangle {
+ id: panel
+ objectName: "jellyfinPanel"
+ required property var app
+ readonly property var server: jellyfin.server
+ property string searchFilter: "albums"
+ property var selected: ({})
+ property int selectedIndex: -1
+ property string renameId: ""
+ property int revision: 0
+ property int artworkRevision: 0
+ readonly 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
+ color: app.surface
+ radius: SpunStyle.panelRadius
+ function closeActions() {
+ actions.close();
+ pageActions.close();
+ connection.close();
+ nameDialog.close();
+ playlistPicker.close();
+ deleteDialog.close();
+ folderMenu.close();
+ qualityMenu.close();
+ }
+ function focusSearch() {
+ if (server.connected) {
+ search.forceActiveFocus();
+ search.selectAll();
+ } else
+ connectButton.forceActiveFocus();
+ }
+ function openMenu(menu, anchor) {
+ const point = anchor ? anchor.mapToItem(panel, anchor.width, anchor.height) : Qt.point(panel.width - 16, 156);
+ menu.x = Math.max(8, Math.min(panel.width - menu.width - 8, point.x - menu.width));
+ menu.y = Math.max(8, Math.min(panel.height - menu.height - 8, point.y));
+ menu.open();
+ }
+ function menuFor(row, index, anchor) {
+ selected = row;
+ selectedIndex = index;
+ openMenu(actions, anchor);
+ }
+ function settle() {
+ entrance.stop();
+ opacity = 1;
+ offset.x = 0;
+ }
+ transform: Translate {
+ id: offset
+ }
+ onVisibleChanged: {
+ if (!visible)
+ closeActions();
+ settle();
+ if (visible && SpunStyle.motion)
+ entrance.start();
+ }
+ Connections {
+ target: SpunStyle
+ function onMotionChanged() {
+ if (!SpunStyle.motion)
+ panel.settle();
+ }
+ }
+ Connections {
+ target: jellyfin
+ function onChanged() {
+ panel.revision++;
+ }
+ function onArtworkChanged() {
+ panel.artworkRevision++;
+ }
+ }
+ ParallelAnimation {
+ id: entrance
+ NumberAnimation {
+ target: panel
+ property: "opacity"
+ from: 0
+ to: 1
+ duration: SpunStyle.feedback
+ easing.type: Easing.BezierSpline
+ easing.bezierCurve: SpunStyle.effectsCurve
+ }
+ NumberAnimation {
+ target: offset
+ property: "x"
+ from: 12
+ to: 0
+ duration: SpunStyle.enter
+ easing.type: Easing.BezierSpline
+ easing.bezierCurve: SpunStyle.enterCurve
+ }
+ }
+ Row {
+ id: tabs
+ x: 12
+ y: 12
+ visible: server.connected
+ function focusTab(i) {
+ tabItems.itemAt(Math.max(0, Math.min(tabItems.count - 1, i))).forceActiveFocus(Qt.TabFocusReason);
+ }
+ Accessible.role: Accessible.PageTabList
+ Accessible.name: "Jellyfin library"
+ Repeater {
+ id: tabItems
+ model: ["albums", "artists", "songs", "playlists"]
+ SpunChoiceButton {
+ required property string modelData
+ required property int index
+ objectName: "jellyfinTab_" + modelData
+ width: (panel.width - 24) / 4
+ text: modelData.charAt(0).toUpperCase() + modelData.slice(1)
+ ink: panel.app.ink
+ mutedInk: panel.app.mutedInk
+ accent: panel.app.accent
+ selected: panel.selectedPage === modelData
+ Accessible.role: Accessible.PageTab
+ Accessible.selectable: true
+ Accessible.selected: selected
+ Keys.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;
+ }
+ Keys.onLeftPressed: tabs.focusTab(index - 1)
+ Keys.onRightPressed: tabs.focusTab(index + 1)
+ Keys.onPressed: event => {
+ if (event.key === Qt.Key_Home) {
+ tabs.focusTab(0);
+ event.accepted = true;
+ } else if (event.key === Qt.Key_End) {
+ tabs.focusTab(3);
+ event.accepted = true;
+ } else
+ event.accepted = false;
+ }
+ Keys.onReturnPressed: clicked()
+ Keys.onEnterPressed: clicked()
+ onClicked: {
+ panel.searchFilter = modelData;
+ search.text = "";
+ jellyfin.show(modelData);
+ }
+ }
+ }
+ }
+ SpunText {
+ visible: !server.connected
+ x: 24
+ y: 24
+ text: "Jellyfin"
+ font.pixelSize: SpunStyle.title
+ color: panel.app.ink
+ }
+ SpunSearchField {
+ id: search
+ objectName: "jellyfinSearch"
+ app: panel.app
+ visible: server.connected
+ x: 16
+ y: 60
+ width: parent.width - 32
+ height: 44
+ maximumLength: 512
+ placeholderText: "Search " + panel.searchFilter
+ onAccepted: jellyfin.search(text, panel.searchFilter)
+ Keys.onDownPressed: {
+ list.forceActiveFocus();
+ if (list.count)
+ list.currentIndex = 0;
+ }
+ }
+ IconButton {
+ visible: server.connected
+ x: 8
+ y: 114
+ glyphName: "back"
+ tip: "Back"
+ ink: panel.app.ink
+ enabled: jellyfin.canBack
+ onClicked: jellyfin.back()
+ }
+ SpunText {
+ visible: server.connected
+ x: 52
+ y: 120
+ width: parent.width - 104
+ height: 28
+ verticalAlignment: Text.AlignVCenter
+ text: jellyfin.heading
+ font.pixelSize: SpunStyle.body
+ font.weight: Font.Medium
+ color: panel.app.ink
+ elide: Text.ElideRight
+ }
+ IconButton {
+ objectName: "jellyfinPageActions"
+ x: parent.width - 48
+ y: server.connected ? 114 : 16
+ glyphName: "more"
+ tip: "Library actions"
+ ink: panel.app.ink
+ onClicked: server.connected ? pageActions.open() : connection.open()
+ }
+ Column {
+ x: 24
+ y: 88
+ width: parent.width - 48
+ spacing: 16
+ visible: !server.connected
+ SpunText {
+ width: parent.width
+ text: server.error || "Connect your music library."
+ wrapMode: Text.WordWrap
+ color: server.error.length ? theme.colors.error : panel.app.mutedInk
+ font.pixelSize: SpunStyle.body
+ }
+ SpunButton {
+ id: connectButton
+ objectName: "jellyfinConnect"
+ text: server.connecting ? "Connecting…" : "Connect"
+ enabled: !server.connecting
+ tonal: true
+ onClicked: connection.open()
+ }
+ SpunLoading {
+ width: parent.width
+ visible: server.connecting
+ label: "Connecting to Jellyfin"
+ }
+ }
+ SpunLoading {
+ objectName: "jellyfinLoading"
+ x: 24
+ y: 160
+ width: parent.width - 48
+ visible: server.connected && jellyfin.busy
+ label: "Loading music"
+ }
+ ListView {
+ id: list
+ objectName: "jellyfinResults"
+ x: 8
+ y: 164
+ width: parent.width - 16
+ height: parent.height - y - 56
+ visible: server.connected && !jellyfin.error.length
+ model: jellyfin.items
+ clip: true
+ spacing: 2
+ boundsBehavior: Flickable.StopAtBounds
+ ScrollBar.vertical: ScrollBar {}
+ Keys.onReturnPressed: if (currentIndex >= 0)
+ jellyfin.open(jellyfin.items[currentIndex])
+ Keys.onEnterPressed: if (currentIndex >= 0)
+ jellyfin.open(jellyfin.items[currentIndex])
+ delegate: ItemDelegate {
+ id: row
+ required property var modelData
+ required property int index
+ objectName: "jellyfinResult_" + index
+ width: list.width
+ height: 68
+ focusPolicy: Qt.StrongFocus
+ Accessible.name: modelData.title + ", " + modelData.artist
+ highlighted: ListView.isCurrentItem
+ background: Rectangle {
+ radius: SpunStyle.rowRadius
+ color: row.highlighted ? panel.app.inset : "transparent"
+ border.width: row.visualFocus ? 2 : 0
+ border.color: panel.app.accent
+ SpunStateLayer {
+ anchors.fill: parent
+ radius: parent.radius
+ pressed: row.down
+ hovered: row.hovered
+ focused: row.visualFocus
+ color: panel.app.ink
+ }
+ }
+ onClicked: {
+ list.currentIndex = index;
+ jellyfin.open(modelData);
+ }
+ Image {
+ x: 8
+ y: 12
+ width: 44
+ height: 44
+ source: {
+ panel.artworkRevision;
+ return jellyfin.artwork(row.modelData.id || "");
+ }
+ sourceSize: Qt.size(88, 88)
+ asynchronous: true
+ fillMode: Image.PreserveAspectCrop
+ Rectangle {
+ anchors.fill: parent
+ visible: parent.status !== Image.Ready
+ radius: 6
+ color: panel.app.inset
+ Glyph {
+ anchors.centerIn: parent
+ name: "disc"
+ ink: panel.app.mutedInk
+ width: 24
+ height: 24
+ }
+ }
+ }
+ SpunText {
+ x: 62
+ y: 12
+ width: parent.width - 108
+ text: row.modelData.title
+ color: panel.app.ink
+ font.pixelSize: SpunStyle.body
+ elide: Text.ElideRight
+ }
+ SpunText {
+ x: 62
+ y: 37
+ width: parent.width - 108
+ text: row.modelData.artist || row.modelData.kind
+ color: panel.app.mutedInk
+ font.pixelSize: SpunStyle.caption
+ elide: Text.ElideRight
+ }
+ IconButton {
+ objectName: "jellyfinRowMenu_" + row.index
+ x: parent.width - 44
+ y: 12
+ glyphName: "more"
+ tip: "Item actions"
+ ink: panel.app.mutedInk
+ onClicked: panel.menuFor(row.modelData, row.index, this)
+ }
+ }
+ }
+ Column {
+ x: 24
+ y: 210
+ width: parent.width - 48
+ spacing: 12
+ visible: server.connected && !jellyfin.busy && (!!jellyfin.error.length || !jellyfin.items.length)
+ SpunText {
+ width: parent.width
+ text: jellyfin.error || "No results"
+ wrapMode: Text.WordWrap
+ color: jellyfin.error.length ? theme.colors.error : panel.app.mutedInk
+ font.pixelSize: SpunStyle.body
+ }
+ SpunButton {
+ text: "Retry"
+ visible: !!jellyfin.error.length
+ onClicked: jellyfin.reload()
+ }
+ }
+ SpunButton {
+ objectName: "jellyfinMore"
+ visible: server.connected && jellyfin.more
+ enabled: !jellyfin.busy
+ anchors.horizontalCenter: parent.horizontalCenter
+ y: parent.height - 48
+ text: jellyfin.busy ? "Loading…" : "Load more"
+ onClicked: jellyfin.loadMore()
+ }
+ component Action: MenuItem {
+ id: action
+ implicitHeight: 40
+ font.family: SpunStyle.family
+ contentItem: SpunText {
+ text: action.text
+ color: panel.app.ink
+ opacity: action.enabled ? 1 : SpunStyle.disabledOpacity
+ font.pixelSize: SpunStyle.body
+ verticalAlignment: Text.AlignVCenter
+ elide: Text.ElideRight
+ }
+ background: Rectangle {
+ radius: 12
+ color: "transparent"
+ SpunStateLayer {
+ anchors.fill: parent
+ radius: 12
+ color: panel.app.ink
+ enabled: action.enabled
+ pressed: action.down
+ hovered: action.highlighted
+ focused: action.visualFocus
+ }
+ }
+ }
+ component PopupMenu: Menu {
+ width: Math.min(270, panel.width - 32)
+ x: panel.width - width - 16
+ y: 156
+ enter: SpunPopupEnter {}
+ exit: Transition {
+ NumberAnimation {
+ property: "opacity"
+ to: 0
+ duration: SpunStyle.exit
+ }
+ }
+ background: Rectangle {
+ color: SpunStyle.popup
+ radius: SpunStyle.popupRadius
+ }
+ }
+ PopupMenu {
+ id: pageActions
+ Action {
+ text: jellyfin.more ? "Play listed songs" : "Play songs"
+ enabled: !jellyfin.busy && jellyfin.items.some(row => row.kind === "song")
+ onTriggered: jellyfin.playItems(jellyfin.items)
+ }
+ Action {
+ text: "Favorites"
+ onTriggered: jellyfin.show("favorites")
+ }
+ Action {
+ text: "Genres"
+ onTriggered: jellyfin.show("genres")
+ }
+ Action {
+ text: "Recently played"
+ onTriggered: jellyfin.show("recent")
+ }
+ Action {
+ objectName: "jellyfinNewPlaylist"
+ text: "New playlist…"
+ onTriggered: {
+ panel.renameId = "";
+ nameField.text = "";
+ nameDialog.open();
+ }
+ }
+ Action {
+ text: "Rename playlist…"
+ visible: panel.playlistPage && !!jellyfin.collection.editable
+ height: visible ? 40 : 0
+ enabled: !jellyfin.actionBusy
+ onTriggered: {
+ panel.renameId = jellyfin.collection.remoteId;
+ nameField.text = jellyfin.heading;
+ nameDialog.open();
+ }
+ }
+ Action {
+ text: "Delete playlist…"
+ visible: panel.playlistPage && !!jellyfin.collection.deletable
+ height: visible ? 40 : 0
+ enabled: !jellyfin.actionBusy
+ onTriggered: deleteDialog.open()
+ }
+ Action {
+ text: "Refresh"
+ enabled: !jellyfin.busy
+ onTriggered: jellyfin.reload()
+ }
+ Action {
+ objectName: "jellyfinSettings"
+ text: "Server settings…"
+ onTriggered: connection.open()
+ }
+ }
+ PopupMenu {
+ id: actions
+ Action {
+ text: panel.selected.kind === "song" ? "Play" : "Open"
+ onTriggered: jellyfin.open(panel.selected)
+ }
+ Action {
+ text: "Add to queue"
+ enabled: panel.selected.kind === "song"
+ onTriggered: jellyfin.enqueue(panel.selected)
+ }
+ Action {
+ text: {
+ panel.revision;
+ return jellyfin.favorite(panel.selected.id || "") ? "Remove from favorites" : "Add to favorites";
+ }
+ enabled: !jellyfin.actionBusy
+ onTriggered: jellyfin.toggleFavorite(panel.selected)
+ }
+ Action {
+ text: "Add to playlist…"
+ enabled: panel.selected.kind === "song"
+ onTriggered: playlistPicker.open()
+ }
+ Action {
+ text: "Open album"
+ enabled: !!panel.selected.albumId
+ onTriggered: jellyfin.open({
+ source: "jellyfin",
+ server: panel.selected.server,
+ kind: "album",
+ remoteId: panel.selected.albumId,
+ title: panel.selected.album
+ })
+ }
+ Action {
+ text: "Open artist"
+ enabled: !!panel.selected.artistId
+ onTriggered: jellyfin.open({
+ source: "jellyfin",
+ server: panel.selected.server,
+ kind: "artist",
+ remoteId: panel.selected.artistId,
+ title: panel.selected.artist
+ })
+ }
+ Action {
+ text: "Remove from playlist"
+ visible: panel.playlistPage && !!jellyfin.collection.editable
+ height: visible ? 40 : 0
+ enabled: !jellyfin.actionBusy
+ onTriggered: jellyfin.removeFromPlaylist(panel.selected)
+ }
+ Action {
+ text: "Move up"
+ visible: panel.playlistPage && !!jellyfin.collection.editable
+ height: visible ? 40 : 0
+ enabled: !jellyfin.actionBusy && panel.selectedIndex > 0
+ onTriggered: jellyfin.movePlaylistItem(panel.selectedIndex, panel.selectedIndex - 1)
+ }
+ Action {
+ text: "Move down"
+ visible: panel.playlistPage && !!jellyfin.collection.editable
+ height: visible ? 40 : 0
+ enabled: !jellyfin.actionBusy && panel.selectedIndex >= 0 && panel.selectedIndex < jellyfin.items.length - 1
+ onTriggered: jellyfin.movePlaylistItem(panel.selectedIndex, panel.selectedIndex + 1)
+ }
+ Action {
+ text: "Copy link"
+ onTriggered: jellyfin.copyLink(panel.selected)
+ }
+ }
+ component LibraryDialog: Dialog {
+ id: dialog
+ modal: true
+ focus: true
+ width: Math.min(360, Math.max(280, panel.width - 32))
+ x: (panel.width - width) / 2
+ y: Math.max(16, Math.min(150, panel.height - height - 16))
+ padding: 24
+ spacing: 16
+ enter: SpunPopupEnter {}
+ exit: Transition {
+ NumberAnimation {
+ property: "opacity"
+ to: 0
+ duration: SpunStyle.exit
+ }
+ }
+ background: Rectangle {
+ color: SpunStyle.popup
+ radius: SpunStyle.dialogRadius
+ }
+ header: SpunText {
+ text: dialog.title
+ color: panel.app.ink
+ font.pixelSize: SpunStyle.title
+ font.weight: Font.Medium
+ leftPadding: 24
+ rightPadding: 24
+ topPadding: 24
+ wrapMode: Text.WordWrap
+ }
+ footer: DialogButtonBox {
+ buttonLayout: DialogButtonBox.AndroidLayout
+ standardButtons: dialog.standardButtons
+ alignment: Qt.AlignRight
+ spacing: 8
+ leftPadding: 24
+ rightPadding: 24
+ bottomPadding: 24
+ background: Item {}
+ delegate: SpunButton {
+ objectName: dialog.objectName + (DialogButtonBox.buttonRole === DialogButtonBox.AcceptRole ? "Accept" : "Cancel")
+ horizontalPadding: 16
+ }
+ }
+ }
+ LibraryDialog {
+ id: connection
+ objectName: "jellyfinConnection"
+ title: server.connected ? "Jellyfin settings" : "Connect to Jellyfin"
+ standardButtons: Dialog.Close
+ onAboutToShow: {
+ address.text = server.address;
+ username.text = server.username;
+ password.text = "";
+ }
+ onOpened: {
+ address.forceActiveFocus();
+ address.cursorPosition = 0;
+ }
+ onClosed: password.text = ""
+ contentItem: ScrollView {
+ implicitHeight: Math.min(connectionFields.implicitHeight, Math.max(180, panel.height - 190))
+ contentWidth: availableWidth
+ clip: true
+ Column {
+ id: connectionFields
+ width: connection.availableWidth
+ spacing: 12
+ SpunSearchField {
+ id: address
+ objectName: "jellyfinAddress"
+ app: panel.app
+ searchIcon: false
+ width: parent.width
+ labelText: "Server URL"
+ Accessible.name: "Jellyfin server URL"
+ enabled: !server.connecting
+ maximumLength: 2048
+ onActiveFocusChanged: if (!activeFocus)
+ cursorPosition = 0
+ }
+ SpunSearchField {
+ id: username
+ objectName: "jellyfinUsername"
+ app: panel.app
+ searchIcon: false
+ width: parent.width
+ labelText: "Username"
+ enabled: !server.connecting
+ maximumLength: 256
+ }
+ SpunSearchField {
+ id: password
+ objectName: "jellyfinPassword"
+ app: panel.app
+ searchIcon: false
+ width: parent.width
+ labelText: "Password"
+ echoMode: TextInput.Password
+ enabled: !server.connecting
+ maximumLength: 1024
+ onAccepted: signIn.clicked()
+ }
+ CheckBox {
+ id: remember
+ objectName: "jellyfinRemember"
+ width: parent.width
+ implicitHeight: Math.max(48, rememberLabel.implicitHeight + 16)
+ text: "Remember connection"
+ enabled: server.keyringAvailable && !server.connecting
+ checked: server.keyringAvailable
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.name: text
+ padding: 0
+ background: Rectangle {
+ radius: SpunStyle.rowRadius
+ color: "transparent"
+ border.width: remember.visualFocus ? 2 : 0
+ border.color: panel.app.accent
+ SpunStateLayer {
+ anchors.fill: parent
+ radius: parent.radius
+ color: panel.app.ink
+ enabled: remember.enabled
+ pressed: remember.down
+ focused: remember.visualFocus
+ hovered: remember.hovered
+ }
+ }
+ indicator: Rectangle {
+ x: 14
+ anchors.verticalCenter: parent.verticalCenter
+ width: 18
+ height: 18
+ radius: 2
+ color: remember.checked ? panel.app.accent : "transparent"
+ border.width: remember.checked ? 0 : 2
+ border.color: panel.app.mutedInk
+ opacity: remember.enabled ? 1 : SpunStyle.disabledOpacity
+ Behavior on color {
+ ColorAnimation { duration: SpunStyle.feedback }
+ }
+ Glyph {
+ anchors.centerIn: parent
+ width: 16
+ height: 16
+ name: "check"
+ ink: theme.colors.onAccent
+ visible: remember.checked
+ }
+ }
+ contentItem: SpunText {
+ id: rememberLabel
+ leftPadding: 44
+ rightPadding: 12
+ text: remember.text
+ font.pixelSize: SpunStyle.body
+ verticalAlignment: Text.AlignVCenter
+ wrapMode: Text.WordWrap
+ color: panel.app.ink
+ opacity: remember.enabled ? 1 : SpunStyle.disabledOpacity
+ }
+ }
+ SpunText {
+ visible: server.error.length > 0
+ width: parent.width
+ text: server.error
+ wrapMode: Text.WordWrap
+ color: theme.colors.error
+ font.pixelSize: SpunStyle.body
+ }
+ SpunButton {
+ id: signIn
+ objectName: "jellyfinSignIn"
+ text: server.connecting ? "Connecting…" : server.connected ? "Reconnect" : "Connect"
+ tonal: true
+ enabled: !server.connecting && address.text.trim().length > 0 && username.text.trim().length > 0
+ onClicked: {
+ server.connectServer(address.text, username.text, password.text, remember.checked);
+ password.text = "";
+ }
+ }
+ SpunButton {
+ visible: server.connected
+ width: parent.width
+ text: {
+ panel.revision;
+ const f = server.folders.find(row => row.id === server.folder);
+ return f ? f.name : "All music libraries";
+ }
+ onClicked: panel.openMenu(folderMenu, this)
+ }
+ SpunButton {
+ objectName: "jellyfinQuality"
+ visible: server.connected
+ width: parent.width
+ text: server.bitrate ? server.bitrate + " kbps" : "Original quality"
+ onClicked: panel.openMenu(qualityMenu, this)
+ }
+ PreferenceSwitch {
+ app: panel.app
+ width: parent.width
+ glyphName: "repeat"
+ visible: server.connected
+ text: "Report playback"
+ checked: server.scrobbling
+ onToggled: server.scrobbling = checked
+ }
+ SpunButton {
+ visible: server.connected
+ text: "Disconnect"
+ onClicked: {
+ server.disconnectServer();
+ connection.close();
+ }
+ }
+ }
+ }
+ }
+ PopupMenu {
+ id: folderMenu
+ Action {
+ text: "All music libraries"
+ onTriggered: {
+ server.folder = "";
+ jellyfin.show("albums");
+ }
+ }
+ Instantiator {
+ model: server.folders
+ delegate: Action {
+ required property var modelData
+ text: modelData.name
+ onTriggered: {
+ server.folder = modelData.id;
+ jellyfin.show("albums");
+ }
+ }
+ onObjectAdded: (index, object) => folderMenu.insertItem(index + 1, object)
+ onObjectRemoved: (index, object) => folderMenu.removeItem(object)
+ }
+ }
+ PopupMenu {
+ id: qualityMenu
+ Instantiator {
+ model: [0, 128, 192, 320]
+ delegate: Action {
+ required property int modelData
+ objectName: "jellyfinQuality_" + modelData
+ text: modelData ? modelData + " kbps" : "Original quality"
+ onTriggered: server.bitrate = modelData
+ }
+ onObjectAdded: (index, object) => qualityMenu.insertItem(index, object)
+ onObjectRemoved: (index, object) => qualityMenu.removeItem(object)
+ }
+ }
+ LibraryDialog {
+ id: nameDialog
+ objectName: "jellyfinNameDialog"
+ title: panel.renameId.length ? "Rename playlist" : "New playlist"
+ standardButtons: Dialog.Save | Dialog.Cancel
+ onOpened: {
+ nameField.forceActiveFocus();
+ nameField.selectAll();
+ standardButton(Dialog.Save).text = panel.renameId.length ? "Save" : "Create";
+ standardButton(Dialog.Save).enabled = nameField.text.trim().length > 0;
+ }
+ onAccepted: {
+ if (panel.renameId.length)
+ jellyfin.renamePlaylist(panel.renameId, nameField.text);
+ else
+ jellyfin.createPlaylist(nameField.text);
+ }
+ contentItem: SpunSearchField {
+ id: nameField
+ objectName: "jellyfinPlaylistName"
+ app: panel.app
+ searchIcon: false
+ labelText: "Playlist name"
+ maximumLength: 120
+ onTextChanged: if (nameDialog.visible)
+ nameDialog.standardButton(Dialog.Save).enabled = text.trim().length > 0
+ }
+ }
+ LibraryDialog {
+ id: playlistPicker
+ title: "Add to playlist"
+ standardButtons: Dialog.Cancel
+ contentItem: ListView {
+ implicitHeight: Math.min(contentHeight, 220)
+ model: server.playlists.filter(row => row.editable)
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+ ScrollBar.vertical: ScrollBar {}
+ delegate: SpunButton {
+ required property var modelData
+ width: playlistPicker.availableWidth
+ text: modelData.title
+ onClicked: {
+ jellyfin.addToPlaylist(modelData.remoteId, panel.selected);
+ playlistPicker.close();
+ }
+ }
+ }
+ }
+ LibraryDialog {
+ id: deleteDialog
+ title: "Delete playlist?"
+ standardButtons: Dialog.Ok | Dialog.Cancel
+ onAboutToShow: standardButton(Dialog.Ok).text = "Delete"
+ onAccepted: jellyfin.deletePlaylist(jellyfin.collection.remoteId)
+ contentItem: SpunText {
+ text: "This deletes the playlist from Jellyfin."
+ wrapMode: Text.WordWrap
+ color: panel.app.ink
+ font.pixelSize: SpunStyle.body
+ }
+ }
+}
diff --git a/qml/LibraryPanel.qml b/qml/LibraryPanel.qml
index 2d5de15..76ac30d 100644
--- a/qml/LibraryPanel.qml
+++ b/qml/LibraryPanel.qml
@@ -136,33 +136,8 @@ Rectangle {
function onItemsChanged() { const keys = new Set(panel.browser.items.map((item, index) => panel.rowKey(index, item))); panel.selectionKeys = panel.selectionKeys.filter(key => keys.has(key)); Qt.callLater(function() { list.contentY = panel.pageY; list.currentIndex = panel.pageIndex; if (!panel.appending && panel.visible && list.count) { if (panel.app.animate) { listEntrance.startOffset = panel.navigationDirection * 12; listEntrance.restart() }; panel.navigationDirection = 0 } }) }
function onReturned() { const positions = panel.savedPositions.slice(); const previous = positions.pop() || { y: 0, index: -1 }; panel.savedPositions = positions; panel.navigationDirection = -1; Qt.callLater(function() { list.currentIndex = Math.min(list.count - 1, previous.index); list.contentY = previous.y; list.forceActiveFocus(Qt.BacktabFocusReason) }) }
}
- component SmallButton: AbstractButton {
- id: control
- property bool selected: false
- property bool pill: true
- implicitHeight: 36
- focusPolicy: Qt.StrongFocus
- hoverEnabled: true
- Accessible.name: text
- background: Rectangle {
- radius: 18 * theme.radius
- color: "transparent"
- Rectangle {
- anchors.fill: parent; radius: parent.radius; color: SpunStyle.selected; opacity: control.selected && control.pill ? 1 : 0
- Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
- }
- SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: panel.app.ink; enabled: control.enabled; pressed: control.down; focused: control.visualFocus; hovered: control.hovered }
- border.width: control.visualFocus ? 2 : 0
- border.color: panel.app.accent
- }
- contentItem: SpunText {
- text: control.text; color: control.selected ? panel.app.accent : panel.app.mutedInk
- font.family: SpunStyle.family; font.pixelSize: SpunStyle.body; font.weight: Font.Medium
- horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter
- opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
- Behavior on color { ColorAnimation { duration: panel.feedbackTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
- Behavior on opacity { NumberAnimation { duration: panel.feedbackTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
- }
+ component SmallButton: SpunChoiceButton {
+ ink: panel.app.ink; mutedInk: panel.app.mutedInk; accent: panel.app.accent
}
Rectangle {
visible: !panel.detail && !panel.sessions && !panel.releases && !panel.forYou && panel.selectionCount === 0
@@ -548,6 +523,11 @@ Rectangle {
Keys.onPressed: event => { if (event.key === Qt.Key_Menu || (event.key === Qt.Key_F10 && (event.modifiers & Qt.ShiftModifier))) { panel.showActions(row.modelData, rowActions); event.accepted = true } }
SpunToolTip { visible: row.hovered && !rowActions.hovered && !trackMenu.visible && row.visible && !row.down; text: row.modelData.title + (row.modelData.artist ? "\n" + row.modelData.artist : "") + (row.song && !row.modelData.playable ? "\nUnavailable" : "") }
}
+ SpunLoading {
+ anchors.horizontalCenter: parent.horizontalCenter; y: parent.height / 2 - 38; width: 180
+ visible: panel.browser.busy && list.count === 0
+ label: "Loading library"
+ }
SpunText {
anchors.centerIn: parent; width: 222
visible: list.count === 0
diff --git a/qml/Main.qml b/qml/Main.qml
index 9728da9..1006f2e 100644
--- a/qml/Main.qml
+++ b/qml/Main.qml
@@ -86,6 +86,23 @@ ApplicationWindow {
onCassetteChanged: Qt.callLater(function() { stopSwap(); scrubber.cancelScrub(); updateMask() })
readonly property bool vinyl: player.vinyl
onVinylChanged: Qt.callLater(updateMask)
+ property bool useJellyfin: false
+ onUseJellyfinChanged: {
+ if (useJellyfin) { useYoutube=false; useCider=false; player.pause(); if(ciderService.playing)ciderService.pause() }
+ jellyfin.enabled=useJellyfin
+ stopSwap(); presentation.clear(); cancel3DPointer(); cancelSeekPreview(); discFlipped=false; libraryOpen=false
+ clearQueueSelection(); cancelQueueDrag(); queueMenu.close(); songMenu.close(); musicBrowser.closeActions()
+ Qt.callLater(function(){presentDisc();syncLyrics();updateMask()})
+ }
+ property bool useYoutube: false
+ readonly property var lyricService: useJellyfin ? jellyfin : useYoutube ? youtube : lyrics
+ onUseYoutubeChanged: {
+ if (useYoutube) { useJellyfin=false; if (ciderService.playing) ciderService.pause(); useCider=false; player.pause() }
+ youtube.enabled=useYoutube
+ stopSwap(); presentation.clear(); cancel3DPointer(); cancelSeekPreview(); discFlipped=false; libraryOpen=false
+ clearQueueSelection(); cancelQueueDrag(); queueMenu.close(); songMenu.close(); musicBrowser.closeActions()
+ Qt.callLater(function(){presentDisc();syncLyrics();updateMask()})
+ }
property bool useCider: !testMode && root.ciderService.available
property var ciderService: cider
property var listeningService: listening
@@ -105,10 +122,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 : player
- readonly property string cassetteTrackIdentity: (useCider ? "cider:" : "local:") + (deckPlayer.trackKey || "")
+ 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 || "")
onCassetteTrackIdentityChanged: { cancel3DPointer(); Qt.callLater(syncTapeSound) }
- function syncTapeSound() { tapeSound.observe(useCider ? "cider" : "local", deckPlayer.trackKey || "") }
+ function syncTapeSound() { tapeSound.observe(useCider ? "cider" : useJellyfin ? "jellyfin" : 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 }
@@ -129,7 +147,7 @@ ApplicationWindow {
running: root.vinyl && player.vinylSkips && root.deckPlayer.playing && !root.needleDragging
onTriggered: { root.skipGroove(); interval = 45000 + Math.floor(Math.random()*35000) }
}
- onUseCiderChanged: { 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;} 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: false
property real swapOffset: 0
property real outgoingOffset: 0
@@ -141,11 +159,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:" : "local:") + (deckPlayer.albumKey || deckPlayer.title) : ""
+ const albumKey = deckPlayer.count ? (useCider ? "cider:" : useJellyfin ? "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() { lyrics.remote = useCider; lyrics.active = discFlipped && lyricsView && 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 }
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() } }
@@ -166,7 +184,7 @@ ApplicationWindow {
if (current < 0 || (useCider && (!discDetails.albumId || ciderService.discLoading || ciderService.discError.length))) return null
return {rows: rows, total: total, current: current}
}
- readonly property string recordKey: recordMap ? (useCider ? "cider:" : "local:") + recordMap.rows.map(row => (row.track.id || row.track.path) + ":" + row.duration).join("|") : ""
+ 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("|") : ""
onRecordKeyChanged: { cancelSeekPreview(); scrubber.cancelScrub() }
readonly property real recordProgress: recordMap ? Math.max(0, Math.min(1, (recordMap.rows[recordMap.current].start + deckPlayer.position) / recordMap.total)) : progress
readonly property bool seekPreviewActive: !!activeSeekControl || scrubber.scrubbing || !!(tonearm && tonearm.dragging)
@@ -201,7 +219,7 @@ ApplicationWindow {
const target = recordTarget(fraction)
if (!target) return false
const accepted = useCider ? listeningService.playAlbumPosition(discDetails.albumId, albumTracks, target.index, target.position)
- : player.playAlbumPosition(target.track.path, target.position)
+ : deckPlayer.playAlbumPosition(target.track.path, target.position)
if (!accepted) notifyAction("This album position is not available. Try again when playback is ready.", true)
return accepted
}
@@ -305,12 +323,13 @@ ApplicationWindow {
Qt.callLater(updateMask)
}
function openMusicLink(text, clipboard) {
+ if(useYoutube){if(clipboard)youtube.openClipboardLink();else youtube.search(text);libraryOpen=true;return true}
const accepted = clipboard ? musicBrowser.browser.openClipboardLink() : musicBrowser.browser.openLink(text)
if (!accepted) { notifyAction("Use an Apple Music song, album or playlist link.", true); return false }
useCider = true; libraryOpen = true
return true
}
- function openArtistName(name) { useCider = true; libraryOpen = true; library.showArtist(name) }
+ 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 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
@@ -399,7 +418,7 @@ ApplicationWindow {
}
function moveQueueRow(from, to, revision) {
if (useCider) root.ciderService.moveQueue(from,to,revision)
- else player.move(from,to)
+ else deckPlayer.move(from,to)
}
function showQueueActions(index, anchor) {
if (queueSelectionCount && queueSelection.indexOf(index) < 0) clearQueueSelection()
@@ -427,7 +446,7 @@ ApplicationWindow {
}
property bool queueOpen: false
property bool helpOpen: false
- readonly property bool menuOpen: !!(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: !!(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
property bool backgroundBlur: player.backgroundBlur && platformNative.supportsBlur
onBackgroundBlurChanged: { platformNative.effects(root, backgroundBlur); Qt.callLater(updateMask) }
property bool muted: false
@@ -460,7 +479,8 @@ ApplicationWindow {
readonly property int feedbackTime: SpunStyle.feedback
readonly property int transitionTime: SpunStyle.navigate
property int tick: 0
- function useLocal() {
+ function useLocal() { useJellyfin=false;
+ useYoutube=false
if (useCider && root.ciderService.playing) root.ciderService.pause()
useCider = false
}
@@ -516,13 +536,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.useCider ? root.ciderService.toggle() : player.count ? player.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.useJellyfin) ? 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 ? musicBrowser.focusSearch() : root.openQueueSearch() }
- Shortcut { sequence: "Ctrl+B"; enabled: root.useCider && !root.menuOpen; onActivated: root.openLibrary() }
+ 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+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) }
@@ -532,7 +552,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 (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 (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 (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: "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 }
@@ -588,37 +608,37 @@ ApplicationWindow {
id: badge
objectName: "sourceBar"
visible: !root.miniMode
- x: (root.playerWidth - width) / 2; y: 13; width: platformNative.hyprland ? 256 : 344; height: 48; radius: 24
+ x: (root.playerWidth - width) / 2; y: 13; width: platformNative.hyprland ? 424 : 512; height: 48; radius: 24
color: root.surface
border.width: 0
MouseArea { anchors.fill: parent; onPressed: root.startSystemMove() }
Rectangle {
objectName: "sourceIndicator"
- SpunSpring { id: sourceMotion; targetValue: root.useCider ? 128 : 56 }
- x: sourceMotion.value; y: 6; width: 72; height: 36; radius: 18
+ 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
color: root.inset
}
Row {
id: sourceTabs
function focusTab(index) {
- const button = sourceTabItems.itemAt(Math.max(0, Math.min(1, index)))
+ const button = sourceTabItems.itemAt(Math.max(0, Math.min(3, index)))
if (button) button.forceActiveFocus(Qt.TabFocusReason)
}
x: 56; y: 6; spacing: 0
Repeater {
id: sourceTabItems
- model: ["Local", "Cider"]
+ model: ["Local", "Cider", "YouTube", "Jellyfin"]
AbstractButton {
id: sourceTab
- objectName: index === 0 ? "localSourceButton" : "ciderSourceButton"
+ objectName: index === 0 ? "localSourceButton" : index === 1 ? "ciderSourceButton" : index === 2 ? "youtubeSourceButton" : "jellyfinSourceButton"
required property string modelData
required property int index
- width: 72; height: 36
+ width: 80; height: 36
focusPolicy: Qt.StrongFocus
hoverEnabled: true
Accessible.name: modelData
Accessible.role: Accessible.PageTab
- Accessible.selectable: true; Accessible.selected: root.useCider === (index === 1)
+ Accessible.selectable: true; Accessible.selected: (root.useJellyfin ? 3 : root.useYoutube ? 2 : root.useCider ? 1 : 0) === index
Keys.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
}
@@ -626,7 +646,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(1); event.accepted = true }
+ else if (event.key === Qt.Key_End) { sourceTabs.focusTab(3); event.accepted = true }
else event.accepted = false
}
@@ -638,26 +658,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.useCider === (parent.index === 1)) ? root.accent : root.mutedInk; font.pixelSize: SpunStyle.body; font.weight: Font.Medium }
- onClicked: { if (index === 0 && root.useCider && root.ciderService.playing) root.ciderService.pause(); root.useCider = index === 1; if (index === 1 && player.ciderAutoStart) root.ciderService.ensureRunning() }
+ 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} }
}
}
}
IconButton {
objectName: "addMusicButton"
- x: 4; y: 4; glyphName: root.useCider ? "search" : "plus"; tip: root.useCider ? "Browse music · Ctrl+B" : "Add music · Ctrl+O"
+ 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"
selected: root.libraryOpen; fill: root.libraryOpen ? root.inset : "transparent"
- ink: root.libraryOpen ? root.accent : root.ink; hoverFill: root.hoverFill; onClicked: root.useCider ? root.openLibrary() : files.open()
+ ink: root.libraryOpen ? root.accent : root.ink; hoverFill: root.hoverFill; onClicked: root.useCider || root.useYoutube || root.useJellyfin ? root.openLibrary() : files.open()
}
IconButton {
objectName: "queueButton"
- x: 212; y: 4; glyphName: "queue"; tip: "Queue · Ctrl+L"
+ x: 380; 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.hoverFill
onClicked: root.queueOpen = !root.queueOpen
}
- IconButton { visible: !platformNative.hyprland; x: 256; y: 4; glyphName: "minus"; tip: "Minimize"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: root.showMinimized() }
- IconButton { visible: !platformNative.hyprland; x: 300; y: 4; glyphName: "close"; tip: "Close Spun"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: Qt.quit() }
+ 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() }
}
Item {
@@ -898,8 +918,8 @@ ApplicationWindow {
id: lyricList
objectName: "lyricList"
x: root.cassette ? 42 : 76; y: root.cassette ? 176 : root.bodyVisible ? 166 : 260; width: root.cassette ? 326 : 258; height: root.bodyVisible ? (root.cassette ? 162 : 172) : root.cassette ? 116 : 84
- visible: root.lyricsView && lyrics.lines.length > 0
- model: lyrics.lines; clip: true; spacing: 8
+ visible: root.lyricsView && root.lyricService.lines.length > 0
+ model: root.lyricService.lines; clip: true; spacing: 8
boundsBehavior: Flickable.StopAtBounds
activeFocusOnTab: root.discFlipped && root.lyricsView
Accessible.name: "Lyrics"
@@ -948,7 +968,7 @@ ApplicationWindow {
y: lyricList.tipOffset - height - 8
}
function followLine() {
- if (following && lyrics.currentIndex >= 0) positionViewAtIndex(lyrics.currentIndex, ListView.Beginning)
+ if (following && root.lyricService.currentIndex >= 0) positionViewAtIndex(root.lyricService.currentIndex, ListView.Beginning)
}
onModelChanged: { dismissSeekTip(); following = true; Qt.callLater(function() { positionViewAtBeginning(); followLine() }) }
onMovementStarted: { following = false; dismissSeekTip() }
@@ -958,7 +978,7 @@ ApplicationWindow {
} else event.accepted = false
}
TapHandler { onTapped: lyricList.forceActiveFocus() }
- Connections { target: lyrics; function onCurrentIndexChanged() { lyricList.followLine() } }
+ Connections { target: root.lyricService; function onCurrentIndexChanged() { lyricList.followLine() } }
ScrollBar.vertical: ScrollBar {
width: 3; padding: 0; minimumSize: .12
contentItem: Rectangle { implicitWidth: 3; implicitHeight: 20; radius: 1.5; color: root.accent; opacity: .5 }
@@ -970,10 +990,10 @@ ApplicationWindow {
required property var modelData
required property int index
property bool hintDismissed: false
- readonly property bool seekable: lyrics.timed && !lyrics.loading && modelData.start >= 0 && modelData.start < root.deckPlayer.duration && (!root.useCider || root.ciderService.canSeek)
+ readonly property bool seekable: root.lyricService.timed && !root.lyricService.loading && modelData.start >= 0 && modelData.start < root.deckPlayer.duration && (!root.useCider || root.ciderService.canSeek)
function seekHere() {
lyricList.dismissSeekTip()
- if (seekable && lyrics.seekToLine(index)) {
+ if (seekable && root.lyricService.seekToLine(index)) {
lyricList.following = true
lyricList.forceActiveFocus()
Qt.callLater(lyricList.followLine)
@@ -983,8 +1003,8 @@ ApplicationWindow {
text: modelData.text; textFormat: Text.PlainText
wrapMode: Text.WordWrap; horizontalAlignment: Text.AlignHCenter
font.pixelSize: root.miniMode ? 19 : 15
- color: (seekable && lyricList.hoveredLine === lyricLine) || (lyrics.timed && index === lyrics.currentIndex) ? root.accent : root.ink
- opacity: lyrics.timed && index !== lyrics.currentIndex && !(seekable && lyricList.hoveredLine === lyricLine) ? .62 : 1
+ color: (seekable && lyricList.hoveredLine === lyricLine) || (root.lyricService.timed && index === root.lyricService.currentIndex) ? root.accent : root.ink
+ opacity: root.lyricService.timed && index !== root.lyricService.currentIndex && !(seekable && lyricList.hoveredLine === lyricLine) ? .62 : 1
Behavior on color { ColorAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
Accessible.role: seekable ? Accessible.Button : Accessible.StaticText
@@ -1018,18 +1038,18 @@ ApplicationWindow {
}
Column {
x: 80; y: root.cassette || root.bodyVisible ? 182 : 262; width: 250; spacing: 4
- visible: root.lyricsView && !lyrics.lines.length
+ visible: root.lyricsView && !root.lyricService.lines.length
SpunText {
- width: parent.width; text: lyrics.loading ? "Loading lyrics…" : lyrics.message
+ width: parent.width; text: root.lyricService.loading ? "Loading lyrics…" : root.lyricService.message
color: root.mutedInk; font.pixelSize: root.miniMode ? 18 : SpunStyle.body
wrapMode: Text.WordWrap; horizontalAlignment: Text.AlignHCenter
}
IconButton {
objectName: "lyricsRetry"
anchors.horizontalCenter: parent.horizontalCenter
- visible: !lyrics.loading && lyrics.message !== "No lyrics available"
+ visible: !root.lyricService.loading && root.lyricService.message !== "No lyrics available"
glyphName: "repeat"; tip: "Retry lyrics"; ink: root.accent; hoverFill: root.hoverFill
- onClicked: lyrics.refresh()
+ onClicked: root.lyricService.refresh()
}
}
Row {
@@ -1043,7 +1063,7 @@ ApplicationWindow {
font.pixelSize: root.miniMode ? 16 : SpunStyle.caption; color: root.mutedInk
}
IconButton {
- visible: root.lyricsView && lyrics.timed && !lyricList.following
+ visible: root.lyricsView && root.lyricService.timed && !lyricList.following
objectName: "followLyricsButton"
width: 36; height: 36; glyphName: "follow"; tip: "Follow current line"
ink: root.accent; hoverFill: root.hoverFill
@@ -1354,9 +1374,9 @@ ApplicationWindow {
HoverHandler { id: miniControlsHover }
Row {
x: 8; y: 4; spacing: 0
- IconButton { id: miniPrevious; objectName: "miniPrevious"; glyphName: "previous"; tip: "Previous track"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canPrevious : player.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.useCider ? root.ciderService.toggle() : player.count ? player.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 : player.count > 0; onClicked: root.deckPlayer.next()
+ IconButton { 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: 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 }
}
IconButton { id: miniRestore; objectName: "miniRestore"; glyphName: "external"; tip: "Full player · Ctrl+M"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: player.miniMode = false }
@@ -1372,22 +1392,22 @@ ApplicationWindow {
MouseArea { anchors.fill: parent; onPressed: root.startSystemMove() }
SpunText {
id: playerSongTitle; objectName: "songTitle"
- x: 24; y: 16; width: root.useCider ? 238 : 272
+ x: 24; y: 16; width: root.useCider || root.useYoutube || root.useJellyfin ? 238 : 272
text: root.deckPlayer.title; color: root.ink; elide: Text.ElideRight
font.pixelSize: SpunStyle.title; font.weight: Font.Normal
}
IconButton {
objectName: "currentSongActions"
- visible: root.useCider; enabled: root.ciderService.count > 0
+ visible: root.useCider || root.useYoutube || root.useJellyfin; enabled: root.deckPlayer.count > 0
x: 264; y: 12; width: 40; height: 40
glyphName: "more"; tip: "Song actions"; ink: root.mutedInk; hoverFill: root.hoverFill
- onClicked: { 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.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() }
}
AbstractButton {
id: playerArtist
objectName: "playerArtistLink"
x: 24; y: 44; width: 284; height: 28
- enabled: root.useCider && root.deckPlayer.artist.length > 0; hoverEnabled: true
+ enabled: (root.useCider || root.useYoutube || root.useJellyfin) && root.deckPlayer.artist.length > 0; hoverEnabled: true
Accessible.name: "View artist " + root.deckPlayer.artist
background: null
onClicked: root.openArtistName(root.deckPlayer.artist)
@@ -1408,7 +1428,7 @@ ApplicationWindow {
Row {
x: 16; y: 80 + (root.showHorizontalSeek ? 28 : 0); spacing: 4
IconButton { objectName: "shuffleButton"; y: 4; selected: root.deckPlayer.shuffle; glyphName: "shuffle"; tip: root.deckPlayer.shuffle ? "Shuffle on" : "Shuffle off"; enabled: !root.recordMap && (!root.useCider || !root.ciderService.controlBusy); ink: root.deckPlayer.shuffle ? root.accent : root.mutedInk; hoverFill: root.hoverFill; onClicked: root.deckPlayer.shuffle = !root.deckPlayer.shuffle }
- IconButton { objectName: "previousButton"; y: 4; glyphName: "previous"; tip: "Previous track · Ctrl+←"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canPrevious : player.count > 0; onClicked: root.deckPlayer.previous() }
+ IconButton { objectName: "previousButton"; y: 4; glyphName: "previous"; tip: "Previous track · Ctrl+←"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canPrevious : root.deckPlayer.count > 0; onClicked: root.deckPlayer.previous() }
IconButton {
objectName: "playButton"
glyphSize: 26
@@ -1416,9 +1436,9 @@ 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.useCider ? root.ciderService.toggle() : player.count ? player.toggle() : files.open()
+ onClicked: root.deckPlayer.count ? root.deckPlayer.toggle() : (root.useYoutube || root.useJellyfin) ? 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 : player.count > 0; onClicked: root.deckPlayer.next() }
+ 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 {
objectName: "repeatButton"
y: 4
@@ -1446,7 +1466,7 @@ ApplicationWindow {
objectName: "demoHint"
x: deck.x + 3; y: 705 + root.mixerHeightExtra; width: 400; horizontalAlignment: Text.AlignHCenter
visible: !root.miniMode
- text: root.useCider || player.count ? "" : "Play demo"
+ text: root.useCider || root.useYoutube || root.useJellyfin || player.count ? "" : "Play demo"
color: root.mutedInk; font.pixelSize: SpunStyle.caption
MouseArea { anchors.fill: parent; cursorShape: Qt.PointingHandCursor; onClicked: { root.useLocal(); player.demo() } }
}
@@ -1747,12 +1767,12 @@ ApplicationWindow {
}
onClicked: root.ciderService.raise()
}
- IconButton { visible: !root.useCider; x: 0; anchors.verticalCenter: parent.verticalCenter; glyphName: "plus"; tip: "Add tracks"; ink: root.ink; hoverFill: root.hoverFill; onClicked: files.open() }
- IconButton { visible: !root.useCider; 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.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() }
Button {
id: clearQueueButton
visible: !root.useCider; anchors.right: parent.right; anchors.verticalCenter: parent.verticalCenter; width: 76; height: SpunStyle.target
- text: "Clear"; enabled: player.count > 0
+ text: "Clear"; enabled: root.deckPlayer.count > 0
font.family: SpunStyle.family; font.pixelSize: SpunStyle.body; font.weight: Font.Medium
background: Rectangle {
radius: height / 2 * theme.radius
@@ -1770,7 +1790,7 @@ ApplicationWindow {
Loader {
id: musicBrowser
x: jewelCase.x; anchors.top: jewelCase.top; width: jewelCase.width; anchors.bottom: deck.bottom
- visible: root.libraryOpen
+ visible: root.libraryOpen && !root.useYoutube && !root.useJellyfin
active: false
// Build the browser on its first opening, then retain its scroll, search,
// focus and transition state for every subsequent visit.
@@ -1784,6 +1804,21 @@ ApplicationWindow {
sourceComponent: LibraryPanel { app: root }
}
+ Loader {
+ id: youtubeBrowser
+ x: jewelCase.x; anchors.top: jewelCase.top; width: jewelCase.width; anchors.bottom: deck.bottom
+ active: root.useYoutube; visible: root.useYoutube && root.libraryOpen
+ sourceComponent: YoutubePanel { app: root }
+ }
+ Loader {
+ id: jellyfinBrowser
+ x: youtubeBrowser.x; y: youtubeBrowser.y; width: youtubeBrowser.width; height: youtubeBrowser.height
+ active: root.useJellyfin; visible: root.useJellyfin && root.libraryOpen
+ sourceComponent: JellyfinPanel { app: root }
+ }
+ Connections { target: jellyfin; function onFeedback(message,error){root.notifyAction(message,error)} }
+ Connections { target: youtube; function onFeedback(message,error){root.notifyAction(message,error)} }
+
function previewQueueCleanup(mode) {
const preview = root.ciderService.previewCleanup(mode)
if (!preview.rows) return
@@ -1900,7 +1935,7 @@ ApplicationWindow {
SettingsAction { objectName: "queueBatchRemove"; visible: queueMenu.batch; text: "Remove selected…"; glyphName: "close"; enabled: root.queueControlsReady; onTriggered: root.editQueueSelection("remove") }
SettingsAction { objectName: "queueMoveUp"; visible: !queueMenu.batch; text: "Move up"; glyphName: "up"; enabled: root.queueReorderAllowed && queueMenu.rowIndex > 0; onTriggered: root.moveQueueRow(queueMenu.rowIndex,queueMenu.rowIndex - 1,queueMenu.revision) }
SettingsAction { objectName: "queueMoveDown"; visible: !queueMenu.batch; text: "Move down"; glyphName: "down"; enabled: root.queueReorderAllowed && queueMenu.rowIndex < root.queueRows.length - 1; onTriggered: root.moveQueueRow(queueMenu.rowIndex,queueMenu.rowIndex + 1,queueMenu.revision) }
- SettingsAction { objectName: "queueRemove"; visible: !queueMenu.batch; text: "Remove from queue"; glyphName: "close"; enabled: root.queueControlsReady; onTriggered: root.useCider ? root.ciderService.removeQueue(queueMenu.rowIndex,queueMenu.revision) : player.remove(queueMenu.rowIndex) }
+ SettingsAction { objectName: "queueRemove"; visible: !queueMenu.batch; text: "Remove from queue"; glyphName: "close"; enabled: root.queueControlsReady; onTriggered: root.useCider ? root.ciderService.removeQueue(queueMenu.rowIndex,queueMenu.revision) : root.deckPlayer.remove(queueMenu.rowIndex) }
SettingsAction {
objectName: "queueRadioAction"; visible: root.useCider && !queueMenu.batch
text: library.radioBusy ? "Finding station…" : library.radioAvailable ? "Start radio" : "Radio unavailable"
@@ -2095,7 +2130,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 && player.count > 0; onTriggered: cover.open() }
+ SettingsAction { text: "Change artwork"; glyphName: "artwork"; enabled: !root.useCider && !root.useYoutube && !root.useJellyfin && 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/SpunChoiceButton.qml b/qml/SpunChoiceButton.qml
new file mode 100644
index 0000000..5af83ec
--- /dev/null
+++ b/qml/SpunChoiceButton.qml
@@ -0,0 +1,34 @@
+import QtQuick
+import QtQuick.Controls
+
+AbstractButton {
+ id: control
+ property color ink: theme.colors.text
+ property color mutedInk: theme.colors.muted
+ property color accent: theme.colors.accent
+ property bool selected: false
+ property bool pill: true
+ implicitHeight: 36
+ focusPolicy: Qt.StrongFocus
+ hoverEnabled: true
+ Accessible.name: text
+ background: Rectangle {
+ radius: 18 * theme.radius
+ color: "transparent"
+ Rectangle {
+ anchors.fill: parent; radius: parent.radius; color: SpunStyle.selected; opacity: control.selected && control.pill ? 1 : 0
+ Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ }
+ SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: control.ink; enabled: control.enabled; pressed: control.down; focused: control.visualFocus; hovered: control.hovered }
+ border.width: control.visualFocus ? 2 : 0
+ border.color: control.accent
+ }
+ contentItem: SpunText {
+ text: control.text; color: control.selected ? control.accent : control.mutedInk
+ font.family: SpunStyle.family; font.pixelSize: SpunStyle.body; font.weight: Font.Medium
+ horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter
+ opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
+ Behavior on color { ColorAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ }
+}
diff --git a/qml/SpunLoading.qml b/qml/SpunLoading.qml
new file mode 100644
index 0000000..e0be6d2
--- /dev/null
+++ b/qml/SpunLoading.qml
@@ -0,0 +1,34 @@
+import QtQuick
+
+Item {
+ id: control
+ property string label: "Loading"
+ readonly property bool animating: visible && SpunStyle.motion
+ implicitHeight: 32
+ Accessible.role: Accessible.Indicator
+ Accessible.name: label
+ Accessible.description: "In progress"
+ Accessible.ignored: !visible
+ Rectangle {
+ id: track
+ width: parent.width; height: 4; radius: 2
+ anchors.verticalCenter: parent.verticalCenter
+ color: theme.colors.outline
+ clip: true
+ Rectangle {
+ id: indicator
+ width: track.width * .35; height: 4; radius: 2
+ color: theme.colors.accent
+ x: (track.width - width) / 2
+ }
+ }
+ NumberAnimation {
+ id: travel
+ target: indicator; property: "x"
+ from: -indicator.width; to: track.width
+ duration: 1400; loops: Animation.Infinite
+ running: control.animating
+ easing.type: Easing.InOutSine
+ }
+ onAnimatingChanged: if (!animating) indicator.x = (track.width - indicator.width) / 2
+}
diff --git a/qml/SpunSearchField.qml b/qml/SpunSearchField.qml
index a7a5cad..1c4e3e5 100644
--- a/qml/SpunSearchField.qml
+++ b/qml/SpunSearchField.qml
@@ -1,20 +1,76 @@
import QtQuick
import QtQuick.Controls
+
TextField {
id: field
required property var app
property bool searchIcon: true
- Accessible.name: placeholderText
- implicitHeight: SpunStyle.target
- font.family: SpunStyle.family; font.pixelSize: SpunStyle.body
- color: app.ink; placeholderTextColor: app.mutedInk
- selectionColor: app.accent; selectedTextColor: theme.colors.onAccent
- leftPadding: searchIcon ? 40 : 16; rightPadding: 40
+ property string labelText: ""
+ readonly property bool formField: labelText.length > 0
+ readonly property bool raisedLabel: activeFocus || text.length > 0
+ Accessible.name: formField ? labelText : placeholderText
+ implicitHeight: formField ? 56 : SpunStyle.target
+ font.family: SpunStyle.family
+ font.pixelSize: SpunStyle.body
+ color: app.ink
+ placeholderTextColor: app.mutedInk
+ selectionColor: app.accent
+ selectedTextColor: theme.colors.onAccent
+ leftPadding: searchIcon ? 40 : 16
+ rightPadding: formField ? 16 : 40
+ topPadding: formField ? 24 : 0
+ bottomPadding: formField ? 8 : 0
background: Rectangle {
color: field.app.inset
- SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: field.app.ink; focused: field.activeFocus; hovered: field.hovered }
- radius: height / 2 * theme.radius
- border.width: field.activeFocus ? 2 : 0; border.color: field.app.accent
+ SpunStateLayer {
+ anchors.fill: parent
+ radius: parent.radius
+ color: field.app.ink
+ focused: field.activeFocus
+ hovered: field.hovered
+ }
+ radius: field.formField ? 4 * theme.radius : height / 2 * theme.radius
+ bottomLeftRadius: field.formField ? 0 : radius
+ bottomRightRadius: field.formField ? 0 : radius
+ border.width: !field.formField && field.activeFocus ? 2 : 0
+ border.color: field.app.accent
+ }
+ Rectangle {
+ visible: field.formField
+ anchors.bottom: parent.bottom
+ width: parent.width
+ height: field.activeFocus ? 2 : 1
+ color: field.activeFocus ? field.app.accent : field.app.mutedInk
+ }
+ SpunText {
+ visible: field.formField
+ x: field.leftPadding
+ y: field.raisedLabel ? 7 : (field.height - implicitHeight) / 2
+ text: field.labelText
+ font.pixelSize: field.raisedLabel ? SpunStyle.caption : SpunStyle.body
+ color: field.activeFocus ? field.app.accent : field.app.mutedInk
+ Behavior on y {
+ NumberAnimation {
+ duration: SpunStyle.feedback
+ easing.type: Easing.BezierSpline
+ easing.bezierCurve: SpunStyle.effectsCurve
+ }
+ }
+ Behavior on font.pixelSize {
+ NumberAnimation {
+ duration: SpunStyle.feedback
+ easing.type: Easing.BezierSpline
+ easing.bezierCurve: SpunStyle.effectsCurve
+ }
+ }
+ }
+ Glyph {
+ visible: field.searchIcon
+ x: SpunStyle.textGap
+ anchors.verticalCenter: parent.verticalCenter
+ width: SpunStyle.smallIcon
+ height: width
+ name: "search"
+ ink: field.app.mutedInk
}
- Glyph { visible: field.searchIcon; x: SpunStyle.textGap; anchors.verticalCenter: parent.verticalCenter; width: SpunStyle.smallIcon; height: width; name: "search"; ink: field.app.mutedInk }
}
diff --git a/qml/SpunSlider.qml b/qml/SpunSlider.qml
index ac381c8..bb4c008 100644
--- a/qml/SpunSlider.qml
+++ b/qml/SpunSlider.qml
@@ -51,6 +51,11 @@ Slider {
width: 4; height: (control.pressed || control.previewing) ? 20 : 16; radius: 2
color: theme.colors.accent; opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
Behavior on height { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ SpunStateLayer {
+ anchors.centerIn: parent; width: 24; height: 32; radius: 12
+ color: theme.colors.accent; hovered: control.hovered; pressed: control.pressed
+ enabled: control.enabled
+ }
Rectangle {
anchors.centerIn: parent; width: 16; height: 28; radius: 8
color: "transparent"; border.width: control.visualFocus ? 2 : 0; border.color: theme.colors.accent
diff --git a/qml/YoutubePanel.qml b/qml/YoutubePanel.qml
new file mode 100644
index 0000000..19eb5c2
--- /dev/null
+++ b/qml/YoutubePanel.qml
@@ -0,0 +1,226 @@
+import QtQuick
+import QtQuick.Controls
+
+Rectangle {
+ id: panel
+ objectName: "youtubePanel"
+ required property var app
+ color: app.surface
+ radius: SpunStyle.panelRadius
+ readonly property bool playlistPage: youtube.page.startsWith("playlist:")
+ property var selected: ({})
+ property int selectedIndex: -1
+ property string renameId: ""
+ property string searchFilter: "songs"
+ property int revision: 0
+ readonly property bool actionsOpen: actions.visible || pageActions.visible || nameDialog.visible || playlistPicker.visible || deleteDialog.visible || historyDialog.visible
+ function closeActions(){actions.close();pageActions.close();nameDialog.close();playlistPicker.close();deleteDialog.close();historyDialog.close()}
+ function settle() { entrance.stop(); opacity = 1; entranceOffset.x = 0 }
+ onVisibleChanged: {
+ if (!visible) closeActions()
+ settle()
+ if (visible && SpunStyle.motion) entrance.start()
+ }
+ transform: Translate { id: entranceOffset }
+ Connections { target: SpunStyle; function onMotionChanged() { if (!SpunStyle.motion) panel.settle() } }
+ ParallelAnimation {
+ id: entrance
+ NumberAnimation { target: panel; property: "opacity"; from: 0; to: 1; duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve }
+ NumberAnimation { target: entranceOffset; property: "x"; from: 12; to: 0; duration: SpunStyle.enter; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.enterCurve }
+ }
+ readonly property string selectedPage: playlistPage ? "playlists" : ["favorites", "playlists", "history"].includes(youtube.page) ? youtube.page : "search"
+ Connections { target: youtube; function onChanged(){ panel.revision++; list.currentIndex=-1 } }
+ function menuFor(row,index) { selected=row; selectedIndex=index; actions.open() }
+ function focusSearch() { search.forceActiveFocus(); search.selectAll() }
+ function playAll() { youtube.playItems(youtube.items) }
+
+ Rectangle {
+ SpunSpring { id: tabMotion; targetValue: 12 + ["search", "favorites", "playlists", "history"].indexOf(panel.selectedPage) * ((panel.width - 24) / 4) }
+ x: tabMotion.value; y: 12; width: (panel.width - 24) / 4; height: 36
+ radius: 18 * theme.radius; color: SpunStyle.selected
+ }
+ Row {
+ id: tabs
+ x: 12; y: 12
+ Accessible.role: Accessible.PageTabList
+ Accessible.name: "YouTube library"
+ function focusTab(index) { tabItems.itemAt(Math.max(0, Math.min(tabItems.count - 1, index))).forceActiveFocus(Qt.TabFocusReason) }
+ Repeater {
+ id: tabItems
+ model: [{name:"Search",page:"search"},{name:"Favorites",page:"favorites"},{name:"Playlists",page:"playlists"},{name:"History",page:"history"}]
+ SpunChoiceButton {
+ required property var modelData
+ required property int index
+ objectName: "youtubeTab_" + modelData.page
+ width: (panel.width - 24) / 4; text: modelData.name; pill: false
+ ink: panel.app.ink; mutedInk: panel.app.mutedInk; accent: panel.app.accent
+ selected: panel.selectedPage === modelData.page
+ Accessible.role: Accessible.PageTab
+ Accessible.selectable: true; Accessible.selected: selected
+ Keys.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
+ }
+ Keys.onLeftPressed: tabs.focusTab(index - 1)
+ Keys.onRightPressed: tabs.focusTab(index + 1)
+ Keys.onPressed: event => {
+ if (event.key === Qt.Key_Home) { tabs.focusTab(0); event.accepted = true }
+ else if (event.key === Qt.Key_End) { tabs.focusTab(tabItems.count - 1); event.accepted = true }
+ else event.accepted = false
+ }
+ Keys.onReturnPressed: clicked()
+ Keys.onEnterPressed: clicked()
+ onClicked: youtube.show(modelData.page)
+ }
+ }
+ }
+ SpunSearchField {
+ id: search; objectName: "youtubeSearch"
+ app: panel.app; x: 16; y: 60; width: parent.width-32; height: 44
+ maximumLength: 2048; placeholderText: "Search or paste a YouTube link"
+ onAccepted: youtube.search(text,panel.searchFilter)
+ }
+ Row {
+ x: 16; y: 108; spacing: 2
+ Repeater {
+ model: [{name:"Songs",filter:"songs"},{name:"Albums",filter:"albums"},{name:"Artists",filter:"artists"},{name:"Playlists",filter:"playlists"}]
+ SpunChoiceButton {
+ required property var modelData
+ width: (panel.width - 38) / 4; height: 36; text: modelData.name; selected: panel.searchFilter===modelData.filter
+ ink: panel.app.ink; mutedInk: panel.app.mutedInk; accent: panel.app.accent
+ Accessible.role: Accessible.RadioButton; Accessible.checkable: true; Accessible.checked: selected
+ onClicked: {panel.searchFilter=modelData.filter;if(search.text.trim().length)youtube.search(search.text,panel.searchFilter)}
+ }
+ }
+ }
+ IconButton { x: 8; y: 151; glyphName: "back"; tip: "Back"; ink: panel.app.ink; enabled: youtube.canBack; onClicked: youtube.back() }
+ SpunText { x: 52; y: 156; width: parent.width-104; height: 36; text: youtube.heading; color: panel.app.ink; font.pixelSize: SpunStyle.body; font.weight: Font.Medium; elide: Text.ElideRight; verticalAlignment: Text.AlignVCenter }
+ IconButton { objectName:"youtubePageActions"; x: parent.width-48; y:151; glyphName:"more"; tip:"Library actions"; ink:panel.app.ink; onClicked:pageActions.open() }
+ SpunLoading { objectName: "youtubeLoading"; x: SpunStyle.outerInset; y: 214; width: parent.width - 2 * x; visible: youtube.busy; label: "Loading music" }
+ ListView {
+ id: list; objectName: "youtubeResults"
+ x: 8; y: 200; width: parent.width-16; height: parent.height-y-SpunStyle.inset
+ clip: true; spacing: 2; model: youtube.items; visible: !youtube.busy && !youtube.error.length
+ boundsBehavior: Flickable.StopAtBounds
+ ScrollBar.vertical: ScrollBar {}
+ Keys.onReturnPressed: {if(currentIndex>=0)youtube.open(youtube.items[currentIndex])}
+ Keys.onEnterPressed: {if(currentIndex>=0)youtube.open(youtube.items[currentIndex])}
+ delegate: ItemDelegate {
+ id: row
+ required property var modelData
+ required property int index
+ objectName: "youtubeResult_"+index
+ width: list.width; height: 68
+ Accessible.name: modelData.title + ", " + modelData.artist
+ focusPolicy: Qt.StrongFocus
+ highlighted: ListView.isCurrentItem
+ background: Rectangle {
+ border.width: row.visualFocus ? 2 : 0; border.color: panel.app.accent
+ radius: SpunStyle.rowRadius; color: row.highlighted ? panel.app.inset : "transparent"
+ SpunStateLayer {anchors.fill:parent;radius:12;color:panel.app.ink;pressed:row.down;hovered:row.hovered;focused:row.visualFocus}
+ }
+ onClicked: {list.currentIndex=index;youtube.open(modelData)}
+ Image {
+ x: 8; y: 12; width: 44; height: 44
+ source: row.modelData.art || ""; asynchronous: true; sourceSize: Qt.size(88,88); fillMode: Image.PreserveAspectCrop
+ Rectangle {anchors.fill:parent;visible:parent.status!==Image.Ready;color:panel.app.inset;radius:6;Glyph {anchors.centerIn:parent;name: "disc";ink:panel.app.mutedInk;width:24;height:24}}
+ }
+ SpunText {x:62;y:12;width:parent.width-108;text:row.modelData.title;color:panel.app.ink;font.pixelSize:SpunStyle.body;elide:Text.ElideRight}
+ SpunText {x:62;y:37;width:parent.width-108;text:row.modelData.artist || row.modelData.kind;color:panel.app.mutedInk;font.pixelSize:SpunStyle.caption;elide:Text.ElideRight}
+ IconButton {objectName:"youtubeRowMenu_"+row.index;x:parent.width-44;y:12;glyphName:"more";tip:"Song actions";ink:panel.app.mutedInk;onClicked:panel.menuFor(row.modelData,row.index)}
+ }
+ }
+ Column {
+ x: 24; y: 230; width: parent.width-48; spacing: 16
+ visible: !youtube.busy && (youtube.error.length>0 || youtube.items.length===0)
+ SpunText {width:parent.width;text:youtube.error || (youtube.page==="search"?"Find a song, album, artist or playlist. No account needed.":"Nothing here yet.");wrapMode:Text.WordWrap;color:youtube.error.length?theme.colors.error:panel.app.mutedInk;font.pixelSize:SpunStyle.body}
+ SpunButton {objectName:"youtubeRetry";text:"Retry";visible:youtube.error.length>0;onClicked:{if(!youtube.ready)youtube.check();else if(search.text.trim().length)youtube.search(search.text,panel.searchFilter);else youtube.show("home")}}
+ SpunButton {objectName:"youtubeDiscover";text:"Discover music";visible:!youtube.error.length && youtube.page==="search";onClicked:youtube.show("home")}
+ }
+
+ component Action: MenuItem {
+ id: action
+ implicitHeight: 40
+ font.family: SpunStyle.family
+ contentItem: SpunText {text:action.text;color:panel.app.ink;opacity:action.enabled?1:SpunStyle.disabledOpacity;font.pixelSize:SpunStyle.body;verticalAlignment:Text.AlignVCenter;elide:Text.ElideRight}
+ background:Rectangle {color:"transparent";radius:12;SpunStateLayer {anchors.fill:parent;radius:12;color:panel.app.ink;pressed:action.down;hovered:action.highlighted;focused:action.visualFocus;enabled:action.enabled}}
+ }
+ Menu {
+ id: actions; width: 270
+ enter: SpunPopupEnter {}
+ exit: Transition { NumberAnimation { property: "opacity"; to: 0; duration: SpunStyle.exit } }
+ x: 30; y: Math.min(panel.height-height-16,230)
+ background: Rectangle {color:SpunStyle.popup;radius:SpunStyle.popupRadius}
+ Action {text:"Play";enabled:panel.selected.kind==="song"||panel.selected.kind==="video";onTriggered:youtube.playItem(panel.selected)}
+ Action {text:"Add to queue";enabled:panel.selected.kind==="song"||panel.selected.kind==="video";onTriggered:youtube.enqueue(panel.selected)}
+ Action {text:{panel.revision;return youtube.favorite(panel.selected.id||"")?"Remove from favorites":"Save to favorites"} visible:panel.selected.kind!=="local-playlist";height:visible?implicitHeight:0;onTriggered:youtube.toggleFavorite(panel.selected)}
+ Action {text:"Add to playlist…";enabled:panel.selected.kind==="song"||panel.selected.kind==="video";onTriggered:playlistPicker.open()}
+ Action {text:"Song radio";enabled:panel.selected.kind==="song"||panel.selected.kind==="video";onTriggered:youtube.radio(panel.selected)}
+ Action {text:"Open album";enabled:!!panel.selected.albumId;onTriggered:youtube.open({id:panel.selected.albumId,kind:"album",title:panel.selected.album})}
+ Action {text:"Open artist";enabled:!!panel.selected.artistId;onTriggered:youtube.open({id:panel.selected.artistId,kind:"artist",title:panel.selected.artist})}
+ Action {text:"Copy link";visible:panel.selected.kind!=="local-playlist";height:visible?implicitHeight:0;onTriggered:youtube.copyLink(panel.selected)}
+ Action {text:"Remove from this playlist";visible:panel.playlistPage && panel.selectedIndex>=0;height:visible?implicitHeight:0;onTriggered:youtube.removeFromPlaylist(youtube.page.slice(9),panel.selectedIndex)}
+ Action {text:"Rename playlist…";visible:panel.selected.kind==="local-playlist";height:visible?implicitHeight:0;onTriggered:{panel.renameId=panel.selected.id;nameField.text=panel.selected.title;nameDialog.open()}}
+ }
+ Menu {
+ enter: SpunPopupEnter {}
+ exit: Transition { NumberAnimation { property: "opacity"; to: 0; duration: SpunStyle.exit } }
+ id: pageActions; width: 240; x:panel.width-width-8;y:196
+ background:Rectangle {color:SpunStyle.popup;radius:SpunStyle.popupRadius}
+ Action {text:"Play all";enabled:youtube.items.some(row=>row.kind==="song"||row.kind==="video");onTriggered:panel.playAll()}
+ Action {objectName:"youtubeNewPlaylist";text:"New playlist…";onTriggered:{panel.renameId="";nameField.text="";nameDialog.open()}}
+ Action {text:"Rename playlist…";visible:panel.playlistPage;height:visible?implicitHeight:0;onTriggered:{panel.renameId=youtube.page.slice(9);nameField.text=youtube.heading;nameDialog.open()}}
+ Action {text:"Delete playlist…";visible:panel.playlistPage;height:visible?implicitHeight:0;onTriggered:deleteDialog.open()}
+ Action {text:"Clear history…";visible:youtube.page==="history";height:visible?implicitHeight:0;onTriggered:historyDialog.open()}
+ }
+ component LibraryDialog: Dialog {
+ id: libraryDialog
+ padding: SpunStyle.outerInset
+ spacing: SpunStyle.inset
+ property string acceptText: ""
+ enter: SpunPopupEnter {}
+ exit: Transition { NumberAnimation { property: "opacity"; to: 0; duration: SpunStyle.exit } }
+ onAboutToShow: { if (acceptText.length && standardButton(Dialog.Ok)) standardButton(Dialog.Ok).text = acceptText }
+ background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.dialogRadius }
+ header: SpunText {
+ text: libraryDialog.title
+ color: panel.app.ink; font.pixelSize: SpunStyle.title; font.weight: Font.Medium
+ leftPadding: SpunStyle.outerInset; rightPadding: SpunStyle.outerInset; topPadding: SpunStyle.outerInset; bottomPadding: 0
+ wrapMode: Text.WordWrap
+ }
+ footer: DialogButtonBox {
+ buttonLayout: DialogButtonBox.AndroidLayout
+ standardButtons: libraryDialog.standardButtons
+ alignment: Qt.AlignRight
+ spacing: SpunStyle.gap; leftPadding: SpunStyle.outerInset; rightPadding: SpunStyle.outerInset; topPadding: 0; bottomPadding: SpunStyle.outerInset
+ background: Item {}
+ delegate: SpunButton { objectName: libraryDialog.objectName + (DialogButtonBox.buttonRole === DialogButtonBox.AcceptRole ? "Accept" : "Cancel"); horizontalPadding: 16 }
+ }
+ }
+ LibraryDialog {
+ id:nameDialog; objectName:"youtubeNameDialog"; palette.window:panel.app.surface;palette.windowText:panel.app.ink;palette.text:panel.app.ink;palette.base:panel.app.inset;palette.buttonText:panel.app.accent; title: panel.renameId.length?"Rename playlist":"New playlist";modal:true;focus:true;width:Math.min(320,panel.width-32);x:(panel.width-width)/2;y:Math.max(16,Math.min(180,panel.height-height-16))
+ standardButtons:Dialog.Save|Dialog.Cancel
+ onOpened:{nameField.forceActiveFocus();nameField.selectAll();standardButton(Dialog.Save).enabled=nameField.text.trim().length>0}
+ onAccepted:{if(panel.renameId.length)youtube.renamePlaylist(panel.renameId,nameField.text);else {const id=youtube.createPlaylist(nameField.text);if(playlistPicker.visible){youtube.addToPlaylist(id,panel.selected);playlistPicker.close()}}}
+ contentItem:SpunSearchField {app:panel.app;searchIcon:false;id:nameField;objectName:"youtubePlaylistName";color:panel.app.ink;placeholderTextColor:panel.app.mutedInk;maximumLength:100;labelText:"Playlist name";onTextChanged:if(nameDialog.visible)nameDialog.standardButton(Dialog.Save).enabled=text.trim().length>0}
+ }
+ LibraryDialog {
+ id:playlistPicker; palette.window:panel.app.surface;palette.windowText:panel.app.ink;palette.text:panel.app.ink;palette.buttonText:panel.app.accent;title:"Add to playlist";modal:true;focus:true;width:Math.min(320,panel.width-32);x:(panel.width-width)/2;y:Math.max(16,Math.min(180,panel.height-height-16));standardButtons:Dialog.Cancel
+ contentItem: Column {
+ spacing: 6
+ ListView {
+ width: playlistPicker.availableWidth; implicitHeight: Math.min(contentHeight, Math.max(80, panel.height-360))
+ model: youtube.playlists; clip: true; spacing: 4
+ boundsBehavior: Flickable.StopAtBounds
+ ScrollBar.vertical: ScrollBar {}
+ delegate: SpunButton {
+ required property var modelData
+ width: playlistPicker.availableWidth; text: modelData.name
+ onClicked: {youtube.addToPlaylist(modelData.id,panel.selected);playlistPicker.close()}
+ }
+ }
+ SpunButton {text:"New playlist…";onClicked:{panel.renameId="";nameField.text="";nameDialog.open()}}
+ }
+ }
+ LibraryDialog {id:deleteDialog; acceptText:"Delete"; palette.window:panel.app.surface;palette.windowText:panel.app.ink;palette.buttonText:panel.app.accent;title:"Delete this playlist?";modal:true;focus:true;width:Math.min(320,panel.width-32);x:(panel.width-width)/2;y:Math.max(16,Math.min(180,panel.height-height-16));standardButtons:Dialog.Ok|Dialog.Cancel;onAccepted:youtube.deletePlaylist(youtube.page.slice(9));contentItem:SpunText {text:"This removes the saved list from this device.";wrapMode:Text.WordWrap;color:panel.app.ink}}
+ LibraryDialog {id:historyDialog; acceptText:"Clear"; palette.window:panel.app.surface;palette.windowText:panel.app.ink;palette.buttonText:panel.app.accent;title:"Clear listening history?";modal:true;focus:true;width:Math.min(320,panel.width-32);x:(panel.width-width)/2;y:Math.max(16,Math.min(180,panel.height-height-16));standardButtons:Dialog.Ok|Dialog.Cancel;onAccepted:youtube.clearHistory();contentItem:SpunText {text:"This clears YouTube listening history stored on this device.";wrapMode:Text.WordWrap;color:panel.app.ink}}
+}
diff --git a/scripts/install-launcher.sh b/scripts/install-launcher.sh
index 8c1640e..0f6c9fd 100755
--- a/scripts/install-launcher.sh
+++ b/scripts/install-launcher.sh
@@ -11,7 +11,7 @@ def escape(value):
content = f'''[Desktop Entry]
Type=Application
Name=Spun
-Comment=CD-shaped music player for local files and Cider.
+Comment=Music player for local files, Cider, YouTube Music and Jellyfin.
Exec="{escape(root / 'scripts/run.sh')}" %F
Icon={root / 'assets/spun-icon.png'}
Terminal=false
diff --git a/scripts/preview-youtube.sh b/scripts/preview-youtube.sh
new file mode 100755
index 0000000..513f10c
--- /dev/null
+++ b/scripts/preview-youtube.sh
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+set -euo pipefail
+spun_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
+mkdir -p "$spun_root/work/youtube-preview"
+exec "$spun_root/build/spun" --isolated --youtube --config "$spun_root/work/youtube-preview/settings.ini"
diff --git a/scripts/setup-youtube.sh b/scripts/setup-youtube.sh
new file mode 100755
index 0000000..2708d93
--- /dev/null
+++ b/scripts/setup-youtube.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+set -euo pipefail
+root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
+command -v node >/dev/null || { echo 'Install Node.js before setting up YouTube Music.' >&2; exit 1; }
+python3 -m venv "$root/runtime/youtube"
+"$root/runtime/youtube/bin/python" -m pip install -r "$root/helper/requirements.txt"
+echo 'YouTube Music is ready. No Google account is needed.'
diff --git a/scripts/test-jellyfin-server.py b/scripts/test-jellyfin-server.py
new file mode 100644
index 0000000..7631711
--- /dev/null
+++ b/scripts/test-jellyfin-server.py
@@ -0,0 +1,98 @@
+#!/usr/bin/env python3
+"""Test Spun against a disposable Jellyfin server and generated audio."""
+import argparse
+import concurrent.futures
+import json
+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','other-music','data','config','cache','logs','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)
+ (root/'other-music/Other Album').mkdir()
+ subprocess.run(['ffmpeg','-nostdin','-v','error','-f','lavfi','-i','anullsrc','-t','2','-metadata','title=Other library song','-metadata','album=Other album',str(root/'other-music/Other Album/other.flac')],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}/jellyfin'
+ (root/'config/network.xml').write_text(f'''<?xml version="1.0"?><NetworkConfiguration><BaseUrl>/jellyfin</BaseUrl><InternalHttpPort>{port}</InternalHttpPort><EnableIPv4>true</EnableIPv4><EnableIPv6>false</EnableIPv6><EnableHttps>false</EnableHttps><RequireHttps>false</RequireHttps><EnableRemoteAccess>false</EnableRemoteAccess><EnableUPnP>false</EnableUPnP><EnablePublishedServerUriByRequest>false</EnablePublishedServerUriByRequest><LocalNetworkAddresses><string>127.0.0.1</string></LocalNetworkAddresses></NetworkConfiguration>''')
+ username='spun-fixture';password=secrets.token_hex(24);token=''
+ def api(path,body=None,method=None):
+ headers={'Content-Type':'application/json','Authorization':'MediaBrowser Client="SpunTest", Device="Fixture", DeviceId="spun-fixture", Version="1"'+(f', Token="{token}"' if token else '')}
+ 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 {}
+ with (root/'server.log').open('w') as log:
+ server=subprocess.Popen([str(args.server_binary.resolve()),'--nowebclient','--nonetchange','--datadir',str(root/'data'),'--configdir',str(root/'config'),'--cachedir',str(root/'cache'),'--logdir',str(root/'logs'),'--ffmpeg','/usr/bin/ffmpeg'],stdout=log,stderr=log)
+ try:
+ for _ in range(180):
+ if server.poll() is not None:raise RuntimeError('Jellyfin exited; see server.log')
+ try:api('/Startup/Configuration');break
+ except (OSError,ValueError):time.sleep(.5)
+ else:raise RuntimeError('Jellyfin did not start')
+ api('/Startup/Configuration',{'UICulture':'en-US','MetadataCountryCode':'US','PreferredMetadataLanguage':'en'})
+ api('/Startup/User')
+ api('/Startup/User',{'Name':username,'Password':password})
+ api('/Startup/RemoteAccess',{'EnableRemoteAccess':False,'EnableAutomaticPortMapping':False})
+ api('/Startup/Complete',{})
+ auth=api('/Users/AuthenticateByName',{'Username':username,'Pw':password});token=auth['AccessToken'];uid=auth['User']['Id']
+ for name,folder in [('Fixture Music','music'),('Other Music','other-music')]:
+ api('/Library/VirtualFolders?'+urllib.parse.urlencode({'name':name,'collectionType':'music','refreshLibrary':'false'}),{'LibraryOptions':{'PathInfos':[{'Path':str(root/folder)}],'EnableRealtimeMonitor':False,'EnableInternetProviders':False,'EnableAutomaticSeriesGrouping':False,'MetadataSavers':[],'TypeOptions':[{'Type':kind,'MetadataFetchers':[],'MetadataFetcherOrder':[],'ImageFetchers':[],'ImageFetcherOrder':[]} for kind in ['MusicAlbum','MusicArtist','Audio']]}})
+ api('/Library/Refresh',{})
+ for _ in range(240):
+ result=api('/Items?'+urllib.parse.urlencode({'UserId':uid,'Recursive':'true','IncludeItemTypes':'Audio','SearchTerm':'Fixture','Limit':200}))
+ if len(result.get('Items',[]))==105:break
+ time.sleep(.5)
+ else:raise RuntimeError('Jellyfin music scan did not finish')
+ guest=api('/Users/New',{'Name':'spun-reader','Password':password})
+ policy=guest['Policy'];policy.update(IsAdministrator=False,EnableAllFolders=True,EnableMediaPlayback=True,EnableAudioPlaybackTranscoding=True,EnableContentDeletion=False,EnableSharedDeviceControl=False)
+ api('/Users/'+guest['Id']+'/Policy',policy)
+ fixture_env={'SPUN_TEST_SERVER':base,'SPUN_TEST_USER':username,'SPUN_TEST_PASSWORD':password,'SPUN_TEST_READER':'spun-reader','SPUN_TEST_READER_ID':guest['Id'],'SPUN_TEST_ADMIN_ID':uid,'SPUN_TEST_ADMIN_TOKEN':token,'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('Jellyfin '+api('/System/Info/Public').get('Version','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-jellyfin','--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()
+
+if __name__ == '__main__': main()
diff --git a/src/jellyfin.cpp b/src/jellyfin.cpp
new file mode 100644
index 0000000..0d39993
--- /dev/null
+++ b/src/jellyfin.cpp
@@ -0,0 +1,558 @@
+#include "jellyfin.h"
+#include <QClipboard>
+#include <QDir>
+#include <QFile>
+#include <QGuiApplication>
+#include <QImage>
+#include <QJsonArray>
+#include <QJsonDocument>
+#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");
+ 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) {
+ emit feedback(s, !m_api.error().isEmpty());
+ });
+ connect(&m_api, &JellyfinApi::accountChanged, this, [this] {
+ persist();
+ ++m_generation;
+ m_player.stop();
+ m_player.setExternalTracks({}, 0, false);
+ m_audio.reset();
+ m_art.reset();
+ m_items.clear();
+ m_back.clear();
+ m_catalog.clear();
+ for (const auto &path : m_thumbs)
+ QFile::remove(QUrl(path).toLocalFile());
+ m_thumbs.clear();
+ m_thumbOrder.clear();
+ m_thumbPending.clear();
+ m_thumbActive.clear();
+ m_identity.clear();
+ m_reported.clear();
+ m_lines.clear();
+ m_timeline.reset({});
+ m_busy = m_more = m_actionBusy = m_thumbBusy = m_loading = false;
+ m_collection.clear();
+ m_error.clear();
+ emit changed();
+ });
+ connect(&m_api, &JellyfinApi::changed, this, [this] {
+ if (m_api.connected() && m_identity != m_api.identity()) {
+ m_identity = m_api.identity();
+ restoreQueue();
+ if (m_enabled)
+ show("albums");
+ }
+ emit changed();
+ });
+ connect(&m_player, &Player::externalRequested, this, &Jellyfin::loadCurrent);
+ connect(&m_player, &Player::externalCancelled, this,
+ [this] { m_api.cancel("audio"); });
+ connect(&m_player, &Player::trackChanged, this, [this] {
+ report(true);
+ m_audio.reset();
+ m_api.cancel("audio");
+ loadArt();
+ refresh();
+ m_save.start();
+ emit changed();
+ });
+ connect(&m_player, &Player::queueChanged, this, [this] { m_save.start(); });
+ connect(&m_player, &Player::playingChanged, this, [this] {
+ report(m_player.playbackState() == QMediaPlayer::StoppedState &&
+ !m_player.busy());
+ });
+ connect(&m_player, &Player::positionChanged, this, [this] {
+ updateLyrics();
+ if (m_reported.isEmpty() && m_player.playing())
+ report();
+ else if (!m_reported.isEmpty() && m_player.position() > 0)
+ m_reportedPosition = m_player.position();
+ });
+ connect(&m_player, &Player::seeked, this, [this] { report(); });
+ connect(&m_player, &Player::errorChanged, this, [this] {
+ if (!m_player.error().isEmpty()) {
+ report(true);
+ emit feedback(m_player.error(), true);
+ }
+ });
+ m_reportTimer.setInterval(10000);
+ connect(&m_reportTimer, &QTimer::timeout, this, [this] { report(); });
+ m_reportTimer.start();
+}
+Jellyfin::~Jellyfin() {
+ persist();
+ report(true);
+ m_player.stop();
+}
+void Jellyfin::setEnabled(bool value) {
+ if (m_enabled == value)
+ return;
+ m_enabled = value;
+ if (!value) {
+ m_player.pause();
+ report(true);
+ m_api.cancel("catalog");
+ m_api.cancel("thumb");
+ m_busy = m_thumbBusy = false;
+ m_thumbActive.clear();
+ } else if (m_api.connected()) {
+ if (m_items.isEmpty())
+ reload();
+ else
+ loadThumbs();
+ }
+ emit changed();
+}
+QVariantMap Jellyfin::original(const QVariantMap &row) const {
+ return m_catalog.value(row.value("id").toString(), row);
+}
+QVariantMap Jellyfin::current() const {
+ return m_catalog.value(m_player.currentUrl().path().mid(1));
+}
+void Jellyfin::show(const QString &mode) {
+ m_back.clear();
+ m_collection.clear();
+ browse({{"mode", mode}});
+}
+void Jellyfin::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) {
+ if (!m_api.owns(row))
+ return;
+ if (row.value("kind") == "song") {
+ playItem(row);
+ return;
+ }
+ m_back.append(
+ QVariantMap{{"request", m_request}, {"collection", m_collection}});
+ if (m_back.size() > 30)
+ m_back.removeFirst();
+ m_collection = row;
+ browse({{"mode", row.value("kind")}, {"remoteId", row.value("remoteId")}});
+}
+void Jellyfin::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() {
+ if (m_more && !m_busy)
+ browse(m_request, true);
+}
+void Jellyfin::browse(const QVariantMap &request, bool append) {
+ if (!m_api.connected())
+ return;
+ ++m_generation;
+ const auto generation = m_generation;
+ m_api.cancel("thumb");
+ m_thumbBusy = false;
+ m_thumbPending.clear();
+ m_thumbActive.clear();
+ m_request = request;
+ m_busy = true;
+ m_error.clear();
+ if (!append)
+ m_items.clear();
+ auto req = request;
+ req["offset"] = append ? m_items.size() : 0;
+ const auto mode = page();
+ m_heading = m_collection.value("title").toString();
+ if (m_heading.isEmpty())
+ m_heading = mode == "search" ? request.value("query").toString()
+ : mode.left(1).toUpper() + mode.mid(1);
+ emit changed();
+ m_api.browse(req, [this, generation, append](const QVariantMap &data,
+ const QString &error) {
+ if (generation != m_generation)
+ return;
+ m_busy = false;
+ m_error = error;
+ if (error.isEmpty()) {
+ const auto rows = data.value("items").toList();
+ for (const auto &v : rows) {
+ auto row = v.toMap();
+ if (m_api.owns(row))
+ m_catalog[row.value("id").toString()] = row;
+ }
+ if (!append)
+ m_items = rows;
+ else
+ m_items.append(rows);
+ m_more = data.value("more").toBool();
+ if (data.contains("editable"))
+ m_collection["editable"] = data.value("editable");
+ if (data.contains("title"))
+ m_heading = data.value("title").toString();
+ // Retain only displayed rows and queued tracks, not every visited page.
+ QSet<QString> keep;
+ for (const auto &v : m_items)
+ keep.insert(v.toMap().value("id").toString());
+ for (const auto &v : m_player.queue())
+ keep.insert(QUrl(v.toMap().value("path").toString()).path().mid(1));
+ for (auto it = m_catalog.begin(); it != m_catalog.end();)
+ if (!keep.contains(it.key()))
+ it = m_catalog.erase(it);
+ else
+ ++it;
+ loadThumbs();
+ }
+ emit changed();
+ });
+}
+QList<Track> Jellyfin::tracks(const QVariantList &rows) {
+ QList<Track> out;
+ for (const auto &v : rows) {
+ auto row = original(v.toMap());
+ if (!m_api.owns(row) || row.value("kind") != "song")
+ continue;
+ const auto id = row.value("id").toString();
+ m_catalog[id] = row;
+ Track t;
+ t.path = "jellyfin://" + m_api.identity() + "/" + id;
+ t.title = row.value("title").toString();
+ t.artist = row.value("artist").toString();
+ t.album = row.value("album").toString();
+ t.duration = row.value("seconds").toLongLong() * 1000;
+ t.number = row.value("trackNumber").toInt();
+ t.discNumber = row.value("discNumber", 1).toInt();
+ t.year = row.value("year").toInt();
+ t.cover = m_thumbs.value(id);
+ out.append(t);
+ if (out.size() >= 20000)
+ break;
+ }
+ return out;
+}
+void Jellyfin::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) {
+ auto queue = tracks({row});
+ if (!queue.isEmpty()) {
+ m_player.appendExternalTracks(queue);
+ emit feedback("Added to queue", false);
+ }
+}
+void Jellyfin::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.");
+ return;
+ }
+ auto buffer = std::make_shared<QTemporaryDir>();
+ const auto path = buffer->filePath("audio");
+ m_api.download(
+ row, path,
+ [this, buffer, key](const QVariantMap &, const QString &error) {
+ if (key != m_player.trackKey())
+ return;
+ if (!error.isEmpty()) {
+ m_player.failExternal(key, error);
+ return;
+ }
+ m_audio = buffer;
+ m_player.resolveExternal(
+ key, QUrl::fromLocalFile(buffer->filePath("audio")));
+ });
+}
+void Jellyfin::loadArt() {
+ m_api.cancel("cover");
+ const auto row = current();
+ const auto key = m_player.trackKey();
+ if (!m_api.owns(row))
+ return;
+ auto dir = std::make_shared<QTemporaryDir>();
+ m_api.cover(row, dir->filePath("cover.png"),
+ [this, dir, key](const QVariantMap &d, const QString &) {
+ if (key != m_player.trackKey())
+ return;
+ QImage image(d.value("file").toString());
+ if (!image.isNull()) {
+ m_art = dir;
+ m_player.setExternalArtwork(key, image);
+ }
+ });
+}
+QString Jellyfin::artwork(const QString &id) {
+ if (m_thumbs.contains(id)) {
+ m_thumbOrder.removeAll(id);
+ m_thumbOrder.append(id);
+ return m_thumbs.value(id);
+ }
+ if (m_enabled && m_catalog.contains(id) &&
+ !m_catalog.value(id).value("art").toString().isEmpty() &&
+ id != m_thumbActive && !m_thumbPending.contains(id) &&
+ m_thumbPending.size() < 64) {
+ m_thumbPending.append(id);
+ QTimer::singleShot(0, this, &Jellyfin::loadThumbs);
+ }
+ return {};
+}
+void Jellyfin::loadThumbs() {
+ if (m_thumbBusy || !m_enabled || !m_thumbnailDirectory.isValid())
+ return;
+ while (!m_thumbPending.isEmpty()) {
+ const auto id = m_thumbPending.takeFirst();
+ if (!m_catalog.contains(id) || m_thumbs.contains(id))
+ continue;
+ m_thumbBusy = true;
+ m_thumbActive = id;
+ const auto generation = m_generation;
+ m_api.cover(
+ m_catalog.value(id), m_thumbnailDirectory.filePath(id + ".png"),
+ [this, generation, id](const QVariantMap &d, const QString &) {
+ if (generation != m_generation)
+ return;
+ m_thumbBusy = false;
+ m_thumbActive.clear();
+ while (m_thumbs.size() >= 256 && !m_thumbOrder.isEmpty()) {
+ const auto evicted = m_thumbOrder.takeFirst();
+ QFile::remove(QUrl(m_thumbs.take(evicted)).toLocalFile());
+ }
+ const auto file = d.value("file").toString();
+ m_thumbs[id] =
+ file.isEmpty() ? QString() : QUrl::fromLocalFile(file).toString();
+ m_thumbOrder.append(id);
+ emit artworkChanged();
+ QTimer::singleShot(0, this, &Jellyfin::loadThumbs);
+ },
+ "thumb");
+ return;
+ }
+}
+void Jellyfin::finishAction(const QString &error, bool refreshPage) {
+ m_actionBusy = false;
+ if (!error.isEmpty())
+ emit feedback(error, true);
+ else if (refreshPage)
+ reload();
+ emit changed();
+}
+void Jellyfin::toggleFavorite(const QVariantMap &row) {
+ if (m_actionBusy)
+ return;
+ m_actionBusy = true;
+ emit changed();
+ m_api.star(original(row), !favorite(row.value("id").toString()),
+ [this](const QVariantMap &, const QString &e) {
+ finishAction(e, page() == "favorites");
+ });
+}
+void Jellyfin::createPlaylist(const QString &name) {
+ if (m_actionBusy || name.trimmed().isEmpty())
+ return;
+ m_actionBusy = true;
+ emit changed();
+ m_api.createPlaylist(name, [this](const QVariantMap &, const QString &error) {
+ finishAction(error);
+ if (error.isEmpty())
+ show("playlists");
+ });
+}
+void Jellyfin::renamePlaylist(const QString &id, const QString &name) {
+ if (m_actionBusy || name.trimmed().isEmpty())
+ return;
+ m_actionBusy = true;
+ emit changed();
+ m_api.editPlaylist(
+ id, {{"name", name.trimmed().left(120)}},
+ [this](const QVariantMap &, const QString &e) { finishAction(e, true); });
+}
+void Jellyfin::addToPlaylist(const QString &id, const QVariantMap &row) {
+ if (m_actionBusy || !m_api.owns(row))
+ return;
+ m_actionBusy = true;
+ emit changed();
+ m_api.editPlaylist(id, {{"songIdToAdd", row.value("remoteId").toString()}},
+ [this](const QVariantMap &, const QString &e) {
+ finishAction(e, page() == "playlist");
+ });
+}
+void Jellyfin::removeFromPlaylist(const QVariantMap &row) {
+ if (m_actionBusy || page() != "playlist" ||
+ !m_collection.value("editable").toBool())
+ return;
+ m_actionBusy = true;
+ emit changed();
+ m_api.editPlaylist(
+ m_collection.value("remoteId").toString(),
+ {{"entryIdToRemove", row.value("entryId").toString()}},
+ [this](const QVariantMap &, const QString &e) { finishAction(e, true); });
+}
+void Jellyfin::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)
+ return;
+ const auto entry = m_items[from].toMap().value("entryId").toString();
+ if (entry.isEmpty())
+ return;
+ m_actionBusy = true;
+ emit changed();
+ m_api.movePlaylistItem(
+ m_collection.value("remoteId").toString(), entry, to,
+ [this](const QVariantMap &, const QString &e) { finishAction(e, true); });
+}
+void Jellyfin::deletePlaylist(const QString &id) {
+ if (m_actionBusy)
+ return;
+ m_actionBusy = true;
+ emit changed();
+ m_api.removePlaylist(id, [this](const QVariantMap &, const QString &e) {
+ finishAction(e);
+ if (e.isEmpty())
+ show("playlists");
+ });
+}
+void Jellyfin::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())));
+ QGuiApplication::clipboard()->setText(u.toString());
+ emit feedback("Link copied", false);
+}
+void Jellyfin::setActive(bool active) {
+ if (m_active == active)
+ return;
+ m_active = active;
+ if (active)
+ refresh();
+ else {
+ m_api.cancel("lyrics");
+ m_loading = false;
+ }
+ emit changed();
+}
+void Jellyfin::refresh() {
+ m_lines.clear();
+ m_timeline.reset({});
+ m_lyricIndex = -1;
+ m_timed = false;
+ m_loading = false;
+ m_message = "No lyrics available";
+ emit currentIndexChanged();
+ const auto row = current();
+ const auto key = m_player.trackKey();
+ if (!m_active || !m_api.owns(row)) {
+ emit changed();
+ return;
+ }
+ m_loading = true;
+ emit changed();
+ m_api.lyrics(row, [this, key](const QVariantMap &d, const QString &error) {
+ if (key != m_player.trackKey())
+ return;
+ m_loading = false;
+ m_lines = d.value("lines").toList();
+ m_timed = !m_lines.isEmpty();
+ if (!m_timed)
+ for (const auto &line :
+ d.value("lyrics").toString().split('\n', Qt::SkipEmptyParts))
+ m_lines.append(QVariantMap{{"text", line}, {"start", -1}, {"end", -1}});
+ m_message = error.isEmpty()
+ ? (m_lines.isEmpty() ? "No lyrics available" : "")
+ : error;
+ m_timeline.reset(m_timed ? m_lines : QVariantList{});
+ updateLyrics();
+ emit changed();
+ });
+}
+void Jellyfin::updateLyrics() {
+ const auto i = m_timeline.indexAt(m_player.position());
+ if (i != m_lyricIndex) {
+ m_lyricIndex = i;
+ emit currentIndexChanged();
+ }
+}
+bool Jellyfin::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) {
+ if (stopped) {
+ if (!m_reported.isEmpty())
+ m_api.reportPlayback(m_reported, m_reportedPosition, true, true);
+ m_reported.clear();
+ return;
+ }
+ if (!m_enabled || m_player.busy() ||
+ m_player.playbackState() == QMediaPlayer::StoppedState ||
+ (m_reported.isEmpty() && !m_player.playing()))
+ return;
+ const auto row = current();
+ if (!m_api.owns(row))
+ return;
+ m_reported = row;
+ m_reportedPosition = m_player.position();
+ m_api.reportPlayback(row, m_reportedPosition, !m_player.playing(), false);
+}
+void Jellyfin::persist() {
+ if (m_identity.isEmpty() || !m_storageValid)
+ return;
+ QDir().mkpath(m_directory);
+ QVariantList rows;
+ for (const auto &v : m_player.queue()) {
+ auto id = QUrl(v.toMap().value("path").toString()).path().mid(1);
+ if (m_catalog.contains(id))
+ rows.append(m_catalog[id]);
+ }
+ QSaveFile f(m_directory + "/queue-" + m_identity + ".json");
+ if (!f.open(QIODevice::WriteOnly))
+ return;
+ f.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);
+ f.write(
+ QJsonDocument(QJsonObject{{"version", 1},
+ {"queue", QJsonArray::fromVariantList(rows)},
+ {"index", m_player.currentIndex()}})
+ .toJson(QJsonDocument::Compact));
+ f.commit();
+}
+void Jellyfin::restoreQueue() {
+ m_storageValid = true;
+ QFile f(m_directory + "/queue-" + m_identity + ".json");
+ if (!f.exists())
+ return;
+ if (!f.open(QIODevice::ReadOnly) || f.size() > 16 * 1024 * 1024) {
+ m_storageValid = false;
+ return;
+ }
+ QJsonParseError error;
+ auto doc = QJsonDocument::fromJson(f.readAll(), &error);
+ if (error.error != QJsonParseError::NoError || !doc.isObject() ||
+ doc.object().value("version").toInt() != 1) {
+ m_storageValid = false;
+ emit feedback(
+ "Saved Jellyfin queue could not be read. It has been left untouched.",
+ true);
+ return;
+ }
+ auto rows = doc.object().value("queue").toArray().toVariantList();
+ m_player.setExternalTracks(tracks(rows), doc.object().value("index").toInt(),
+ false);
+}
diff --git a/src/jellyfin.h b/src/jellyfin.h
new file mode 100644
index 0000000..2f8394a
--- /dev/null
+++ b/src/jellyfin.h
@@ -0,0 +1,116 @@
+#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;
+};
diff --git a/src/jellyfinapi.cpp b/src/jellyfinapi.cpp
new file mode 100644
index 0000000..66c3fdc
--- /dev/null
+++ b/src/jellyfinapi.cpp
@@ -0,0 +1,1094 @@
+#include "jellyfinapi.h"
+#include "jellyfinlrc.h"
+#include <QBuffer>
+#include <QCryptographicHash>
+#include <QFile>
+#include <QImageReader>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QProcess>
+#include <QSaveFile>
+#include <QStandardPaths>
+#include <QTimer>
+#include <QUuid>
+#include <algorithm>
+#include <memory>
+
+namespace {
+QString digest(const QString &s) {
+ return QString::fromLatin1(
+ QCryptographicHash::hash(s.toUtf8(), QCryptographicHash::Sha256).toHex());
+}
+QString part(const QString &s) {
+ return QString::fromLatin1(QUrl::toPercentEncoding(s));
+}
+QString credentialKey(const QString &address, const QString &user) {
+ return "jellyfin_" + digest(address + "\n" + user);
+}
+QStringList values(const JellyfinApi::Params &params, const QString &key) {
+ QStringList out;
+ for (const auto &p : params)
+ if (p.first == key)
+ out << p.second;
+ return out;
+}
+QString value(const JellyfinApi::Params &params, const QString &key) {
+ return values(params, key).value(0);
+}
+QString networkError(QNetworkReply *r) {
+ const int status =
+ r->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ if (status == 401)
+ return "Jellyfin sign-in failed or the session expired. Reconnect in "
+ "Settings.";
+ if (status == 403)
+ return "Your Jellyfin account does not allow this action.";
+ if (status == 404)
+ return "This item or endpoint is no longer available on Jellyfin.";
+ if (status >= 300 && status < 400)
+ return "Jellyfin redirected the request. Use the final server address in "
+ "Settings.";
+ if (r->error() == QNetworkReply::SslHandshakeFailedError)
+ return "Jellyfin's TLS certificate could not be verified.";
+ return "Could not reach Jellyfin or complete the request. Check the "
+ "connection and retry.";
+}
+} // namespace
+JellyfinApi::JellyfinApi(bool restore, const QString &settingsPath)
+ : m_settings(settingsPath.isEmpty() ? QSettings().fileName() : settingsPath,
+ QSettings::IniFormat) {
+ m_device = m_settings.value("jellyfin/device").toString();
+ if (m_device.isEmpty()) {
+ m_device = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ m_settings.setValue("jellyfin/device", m_device);
+ }
+ if (!restore)
+ return;
+ m_address = m_settings.value("jellyfin/address").toString();
+ m_username = m_settings.value("jellyfin/username").toString();
+ if (m_address.isEmpty() || !m_settings.value("jellyfin/remember").toBool())
+ return;
+ QTimer::singleShot(0, this, [this] {
+ const auto generation = m_generation;
+ secret({"lookup", "application", "spun", "account",
+ credentialKey(m_address, m_username)},
+ {}, [this, generation](bool ok, QByteArray token) {
+ if (generation != m_generation)
+ return;
+ if (!ok || token.trimmed().isEmpty()) {
+ m_error = "Sign in to reconnect to Jellyfin.";
+ emit changed();
+ return;
+ }
+ m_token = QString::fromUtf8(token.trimmed());
+ m_connecting = true;
+ emit changed();
+ json(
+ "Users/Me", {}, "GET", {},
+ [this](const QVariantMap &d, const QString &e) {
+ m_connecting = false;
+ if (!e.isEmpty()) {
+ m_error = e;
+ m_token.clear();
+ emit changed();
+ return;
+ }
+ acceptLogin({{"User", d}, {"AccessToken", m_token}}, false);
+ },
+ "login");
+ });
+ });
+}
+JellyfinApi::~JellyfinApi() { stopRequests(); }
+void JellyfinApi::stopRequests() {
+ m_reports.clear();
+ ++m_generation;
+ for (auto *r : m_network.findChildren<QNetworkReply *>()) {
+ r->disconnect(this);
+ r->abort();
+ r->deleteLater();
+ }
+ m_channels.clear();
+}
+void JellyfinApi::cancel(const QString &channel) {
+ auto r = m_channels.take(channel);
+ if (r) {
+ r->disconnect(this);
+ r->abort();
+ r->deleteLater();
+ }
+}
+QUrl JellyfinApi::url(const QString &path, const Params &params) const {
+ QUrl u(m_address);
+ u.setPath(u.path() + "/" + path, QUrl::TolerantMode);
+ QUrlQuery q;
+ for (const auto &p : params)
+ q.addQueryItem(p.first, p.second);
+ u.setQuery(q);
+ return u;
+}
+QNetworkRequest JellyfinApi::request(const QUrl &u) const {
+ QNetworkRequest r(u);
+ r.setTransferTimeout(15000);
+ r.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
+ QNetworkRequest::ManualRedirectPolicy);
+ r.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);
+ QByteArray auth =
+ "MediaBrowser Client=\"Spun\", Device=\"Spun Linux\", DeviceId=\"" +
+ m_device.toUtf8() + "\", Version=\"1.0\"";
+ if (!m_token.isEmpty())
+ auth += ", Token=\"" + m_token.toUtf8() + "\"";
+ r.setRawHeader("Authorization", auth);
+ r.setRawHeader("Accept", "application/json");
+ return r;
+}
+void JellyfinApi::json(const QString &path, const Params &params,
+ const QByteArray &method, const QJsonObject &body,
+ Reply callback, const QString &channel) {
+ if (!channel.isEmpty())
+ cancel(channel);
+ auto req = request(url(path, params));
+ req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
+ auto *r = m_network.sendCustomRequest(
+ req, method,
+ method == "GET" ? QByteArray()
+ : QJsonDocument(body).toJson(QJsonDocument::Compact));
+ if (!channel.isEmpty())
+ m_channels[channel] = r;
+ const auto generation = m_generation;
+ auto oversized = std::make_shared<bool>(false);
+ connect(r, &QNetworkReply::readyRead, this, [r, oversized] {
+ if (r->bytesAvailable() > 16 * 1024 * 1024) {
+ *oversized = true;
+ 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, callback, channel, oversized] {
+ if (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 (*oversized) {
+ callback({}, "Jellyfin response exceeds the 16 MiB limit.");
+ return;
+ }
+ if (r->error() != QNetworkReply::NoError || status < 200 ||
+ status >= 300) {
+ callback({{"httpStatus", status}}, networkError(r));
+ return;
+ }
+ const auto bytes = r->readAll();
+ if (bytes.isEmpty()) {
+ callback({}, {});
+ return;
+ }
+ QJsonParseError error;
+ const auto doc = QJsonDocument::fromJson(bytes, &error);
+ if (error.error != QJsonParseError::NoError ||
+ (!doc.isObject() && !doc.isArray())) {
+ callback({},
+ "This address did not return a Jellyfin API response.");
+ return;
+ }
+ callback(doc.isObject()
+ ? doc.object().toVariantMap()
+ : QVariantMap{{"Items", doc.array().toVariantList()}},
+ {});
+ });
+}
+void JellyfinApi::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()) {
+ m_error = "Enter an HTTP(S) Jellyfin server address and username.";
+ emit changed();
+ return;
+ }
+ auto path = base.path();
+ while (path.endsWith('/'))
+ path.chop(1);
+ base.setPath(path);
+ if (!remember && m_settings.value("jellyfin/remember").toBool()) {
+ secret({"clear", "application", "spun", "account",
+ credentialKey(m_settings.value("jellyfin/address").toString(),
+ m_settings.value("jellyfin/username").toString())},
+ {}, [](bool, QByteArray) {});
+ m_settings.setValue("jellyfin/remember", false);
+ }
+ stopRequests();
+ m_connected = false;
+ m_connecting = true;
+ m_error.clear();
+ m_token.clear();
+ m_user.clear();
+ m_identity.clear();
+ m_stars.clear();
+ m_playlists.clear();
+ m_folders.clear();
+ m_playing.clear();
+ m_address = base.toString();
+ m_username = user.trimmed();
+ emit accountChanged();
+ emit changed();
+ json(
+ "Users/AuthenticateByName", {}, "POST",
+ {{"Username", m_username}, {"Pw", password}},
+ [this, remember](const QVariantMap &d, const QString &e) {
+ m_connecting = false;
+ if (!e.isEmpty()) {
+ m_error = e;
+ emit changed();
+ return;
+ }
+ acceptLogin(d, remember);
+ },
+ "login");
+}
+void JellyfinApi::acceptLogin(const QVariantMap &d, bool remember) {
+ const auto user = d.value("User").toMap();
+ const auto token = d.value("AccessToken").toString();
+ if (user.value("Id").toString().isEmpty() || token.isEmpty() ||
+ token.contains('"') || token.contains('\n') || token.contains('\r')) {
+ m_error = "Jellyfin returned an invalid sign-in response.";
+ m_token.clear();
+ emit changed();
+ return;
+ }
+ m_user = user.value("Id").toString();
+ m_token = token;
+ m_identity = digest(m_address + "\n" + m_user);
+ m_connected = true;
+ m_error.clear();
+ const auto oldAddress = m_settings.value("jellyfin/address").toString(),
+ oldUser = m_settings.value("jellyfin/username").toString();
+ if (oldAddress != m_address || oldUser != m_username) {
+ m_settings.remove("jellyfin/folder");
+ if (!oldAddress.isEmpty())
+ secret({"clear", "application", "spun", "account",
+ credentialKey(oldAddress, oldUser)},
+ {}, [](bool, QByteArray) {});
+ m_settings.setValue("jellyfin/remember", false);
+ }
+ m_settings.setValue("jellyfin/address", m_address);
+ m_settings.setValue("jellyfin/username", m_username);
+ if (remember) {
+ const auto generation = m_generation;
+ secret({"store", "--label=Spun Jellyfin", "application", "spun", "account",
+ credentialKey(m_address, m_username)},
+ m_token.toUtf8(), [this, generation](bool ok, QByteArray) {
+ if (generation != m_generation)
+ return;
+ m_settings.setValue("jellyfin/remember", ok);
+ if (!ok)
+ emit message("Connected for this session. The keyring could not "
+ "save the Jellyfin session.");
+ });
+ }
+ emit changed();
+ discover();
+}
+void JellyfinApi::disconnectServer() {
+ const auto old = credentialKey(m_address, m_username);
+ const bool remembered = m_settings.value("jellyfin/remember").toBool();
+ stopRequests();
+ m_token.clear();
+ m_user.clear();
+ m_identity.clear();
+ m_connected = false;
+ m_connecting = false;
+ m_error.clear();
+ m_stars.clear();
+ m_playlists.clear();
+ m_folders.clear();
+ m_playing.clear();
+ m_address.clear();
+ m_username.clear();
+ for (const auto &key : {"address", "username", "remember", "folder"})
+ m_settings.remove(QString("jellyfin/") + key);
+ if (remembered)
+ secret({"clear", "application", "spun", "account", old}, {},
+ [](bool, QByteArray) {});
+ emit accountChanged();
+ emit changed();
+}
+void JellyfinApi::setFolder(const QString &id) {
+ m_settings.setValue("jellyfin/folder", id);
+ emit changed();
+}
+void JellyfinApi::setScrobbling(bool value) {
+ if (!value && !m_playing.isEmpty()) {
+ const bool idle = m_reports.isEmpty();
+ m_reports.append(
+ {"Sessions/Playing/Stopped", QJsonObject{{"ItemId", m_playing}}});
+ m_playing.clear();
+ if (idle)
+ sendPlaybackReport();
+ }
+ m_settings.setValue("jellyfin/scrobble", value);
+ emit changed();
+}
+void JellyfinApi::setBitrate(int value) {
+ if (!QList<int>{0, 128, 192, 320}.contains(value))
+ return;
+ m_settings.setValue("jellyfin/bitrate", value);
+ emit changed();
+}
+bool JellyfinApi::owns(const QVariantMap &t) const {
+ return connected() && t.value("source") == "jellyfin" &&
+ t.value("server") == m_identity &&
+ !t.value("remoteId").toString().isEmpty();
+}
+QVariantMap JellyfinApi::item(const QVariantMap &raw,
+ const QString &kind) const {
+ const auto id = raw.value("Id", raw.value("id")).toString();
+ if (id.isEmpty())
+ return {};
+ QStringList artists = raw.value("Artists").toStringList();
+ if (artists.isEmpty())
+ artists = raw.value("AlbumArtists").toStringList();
+ QVariantMap out{
+ {"id", "jf_" + digest(m_identity + "\n" + kind + "\n" + id)},
+ {"source", "jellyfin"},
+ {"server", m_identity},
+ {"remoteId", id},
+ {"kind", kind},
+ {"title", raw.value("Name", raw.value("name"))},
+ {"artist", artists.join(", ")},
+ {"album", raw.value("Album")},
+ {"seconds", raw.value("RunTimeTicks").toLongLong() / 10000000},
+ {"discNumber", raw.value("ParentIndexNumber", 1)},
+ {"trackNumber", raw.value("IndexNumber")},
+ {"year", raw.value("ProductionYear")},
+ {"count", raw.value("ChildCount", raw.value("SongCount", 0))},
+ {"available", true}};
+ if (kind == "song") {
+ out["serverSong"] = true;
+ out["albumId"] = raw.value("AlbumId");
+ const auto artistItems = raw.value("ArtistItems").toList();
+ if (!artistItems.isEmpty())
+ out["artistId"] = artistItems.first().toMap().value("Id");
+ }
+ if (raw.contains("PlaylistItemId"))
+ out["entryId"] = raw.value("PlaylistItemId");
+ if (kind == "playlist")
+ out["editable"] = raw.value("CanDelete", false);
+ if (kind == "playlist")
+ out["deletable"] = raw.value("CanDelete", false);
+ auto imageId = id;
+ if (!raw.value("ImageTags").toMap().contains("Primary"))
+ imageId = raw.value("AlbumPrimaryImageTag").toString().isEmpty()
+ ? QString()
+ : raw.value("AlbumId").toString();
+ if (!imageId.isEmpty()) {
+ QUrl art;
+ art.setScheme("spuncover");
+ art.setHost("jellyfin");
+ art.setPath("/" + m_identity + "/" + imageId);
+ out["art"] = art.toString();
+ }
+ return out;
+}
+QUrl JellyfinApi::artworkUrl(const QUrl &ref) const {
+ if (!connected() || ref.scheme() != "spuncover" || ref.host() != "jellyfin" ||
+ !ref.path().startsWith("/" + m_identity + "/"))
+ return {};
+ return url("Items/" + part(ref.path().mid(m_identity.size() + 2)) +
+ "/Images/Primary",
+ {{"MaxWidth", "600"}, {"Quality", "90"}});
+}
+QNetworkRequest JellyfinApi::artworkRequest(const QUrl &ref) const {
+ return request(artworkUrl(ref));
+}
+void JellyfinApi::fetchRows(const QString &path, Params params, bool all,
+ Reply callback, const QString &channel) {
+ auto rows = std::make_shared<QVariantList>();
+ auto step = std::make_shared<std::function<void(int)>>();
+ std::weak_ptr<std::function<void(int)>> weak = step;
+ const int start = value(params, "StartIndex").toInt();
+ *step = [this, path, params, all, callback, channel, rows, weak](int offset) {
+ auto next = weak.lock();
+ if (!next)
+ return;
+ auto p = params;
+ for (auto it = p.begin(); it != p.end();)
+ if (it->first == "StartIndex" || it->first == "Limit")
+ it = p.erase(it);
+ else
+ ++it;
+ p.append(QPair<QString, QString>{"StartIndex", QString::number(offset)});
+ p.append(QPair<QString, QString>{"Limit", "100"});
+ json(
+ path, p, "GET", {},
+ [this, all, callback, rows, next, offset](const QVariantMap &d,
+ const QString &e) {
+ if (!e.isEmpty()) {
+ callback({}, e);
+ return;
+ }
+ const auto page = d.value("Items").toList();
+ rows->append(page);
+ const int total =
+ d.value("TotalRecordCount", offset + page.size()).toInt();
+ const bool more = !page.isEmpty() && offset + page.size() < total;
+ if (all && more) {
+ if (rows->size() >= 20000) {
+ callback({}, "This collection exceeds the 20,000-item limit. "
+ "Open a smaller collection.");
+ return;
+ }
+ (*next)(offset + page.size());
+ return;
+ }
+ callback({{"Items", *rows}, {"more", more}}, {});
+ },
+ channel);
+ };
+ (*step)(start);
+}
+void JellyfinApi::discover() {
+ json(
+ "Users/" + part(m_user) + "/Views", {}, "GET", {},
+ [this](const QVariantMap &d, const QString &e) {
+ if (!e.isEmpty()) {
+ emit message(e);
+ return;
+ }
+ m_folders.clear();
+ for (const auto &v : d.value("Items").toList()) {
+ auto row = v.toMap();
+ if (row.value("CollectionType") == "music")
+ m_folders.append(QVariantMap{{"id", row.value("Id")},
+ {"name", row.value("Name")}});
+ }
+ bool found = folder().isEmpty();
+ for (const auto &v : m_folders)
+ if (v.toMap().value("id") == folder())
+ found = true;
+ if (!found)
+ m_settings.remove("jellyfin/folder");
+ emit changed();
+ },
+ "folders");
+ fetchRows(
+ "Items",
+ {{"UserId", m_user},
+ {"Recursive", "true"},
+ {"IncludeItemTypes", "Audio"},
+ {"Filters", "IsFavorite"},
+ {"Fields", "UserData"}},
+ true,
+ [this](const QVariantMap &d, const QString &e) {
+ if (!e.isEmpty())
+ return;
+ for (const auto &v : d.value("Items").toList())
+ m_stars.insert(item(v.toMap(), "song").value("id").toString());
+ emit changed();
+ },
+ "stars");
+ reloadPlaylists();
+}
+void JellyfinApi::playlistAccess(const QString &id, Reply cb,
+ const QString &channel) {
+ json(
+ "Playlists/" + part(id) + "/Users/" + part(m_user), {}, "GET", {},
+ [cb](const QVariantMap &d, const QString &e) {
+ cb({{"editable", e.isEmpty() && d.value("CanEdit").toBool()}}, {});
+ },
+ channel);
+}
+void JellyfinApi::browse(const QVariantMap &req, Reply cb,
+ const QString &channel) {
+ if (!connected()) {
+ cb({}, "Connect to Jellyfin in Settings.");
+ return;
+ }
+ const auto mode = req.value("mode", "albums").toString();
+ QString path = "Items", kind = "song";
+ bool all = false;
+ Params p{
+ {"UserId", m_user},
+ {"Recursive", "true"},
+ {"Fields", "PrimaryImageAspectRatio,Genres,CanDelete,ChildCount"},
+ {"EnableUserData", "true"},
+ {"SortBy", "SortName"},
+ {"SortOrder", "Ascending"},
+ {"StartIndex", QString::number(qMax(0, req.value("offset").toInt()))}};
+ auto set = [&p](const QString &k, const QString &v) {
+ for (auto it = p.begin(); it != p.end();)
+ if (it->first == k)
+ it = p.erase(it);
+ else
+ ++it;
+ p.append(QPair<QString, QString>{k, v});
+ };
+ if (!folder().isEmpty())
+ set("ParentId", folder());
+ if (mode == "albums") {
+ kind = "album";
+ set("IncludeItemTypes", "MusicAlbum");
+ set("SortBy", "DateCreated,SortName");
+ set("SortOrder", "Descending");
+ } else if (mode == "artists") {
+ kind = "artist";
+ path = "Artists";
+ } else if (mode == "genres") {
+ kind = "genre";
+ path = "MusicGenres";
+ set("IncludeItemTypes", "Audio");
+ } else if (mode == "genre") {
+ set("GenreIds", req.value("remoteId").toString());
+ set("IncludeItemTypes", "Audio");
+ } else if (mode == "favorites") {
+ set("Filters", "IsFavorite");
+ set("IncludeItemTypes", "Audio");
+ } else if (mode == "songs" || mode == "recent") {
+ set("IncludeItemTypes", "Audio");
+ if (mode == "recent") {
+ set("SortBy", "DatePlayed,SortName");
+ set("SortOrder", "Descending");
+ set("Filters", "IsPlayed");
+ }
+ } else if (mode == "random") {
+ set("SortBy", "Random");
+ set("IncludeItemTypes", "Audio");
+ } else if (mode == "playlists") {
+ kind = "playlist";
+ set("IncludeItemTypes", "Playlist");
+ set("MediaTypes", "Audio");
+ set("ParentId", "");
+ } else if (mode == "album") {
+ all = true;
+ set("ParentId", req.value("remoteId").toString());
+ set("IncludeItemTypes", "Audio");
+ set("SortBy", "ParentIndexNumber,IndexNumber,SortName");
+ } else if (mode == "artist") {
+ kind = "album";
+ set("ArtistIds", req.value("remoteId").toString());
+ set("IncludeItemTypes", "MusicAlbum");
+ } else if (mode == "playlist") {
+ all = true;
+ path = "Playlists/" + part(req.value("remoteId").toString()) + "/Items";
+ p = {{"UserId", m_user}, {"Fields", "Genres,CanDelete"}};
+ } else if (mode == "search") {
+ const auto filter = req.value("filter", "songs").toString();
+ kind = filter == "albums" ? "album"
+ : filter == "artists" ? "artist"
+ : filter == "playlists" ? "playlist"
+ : "song";
+ set("SearchTerm", req.value("query").toString());
+ if (kind == "artist")
+ path = "Artists";
+ else
+ set("IncludeItemTypes", kind == "album" ? "MusicAlbum"
+ : kind == "playlist" ? "Playlist"
+ : "Audio");
+ } else {
+ cb({}, "This Jellyfin view is not supported.");
+ return;
+ }
+ fetchRows(
+ path, p, all,
+ [this, cb, kind, mode, req, channel](const QVariantMap &d,
+ const QString &e) {
+ if (!e.isEmpty()) {
+ cb({}, e);
+ return;
+ }
+ QVariantList rows;
+ for (const auto &v : d.value("Items").toList()) {
+ const auto raw = v.toMap();
+ auto row = item(raw, kind);
+ if (row.isEmpty())
+ continue;
+ rows << row;
+ if (raw.value("UserData").toMap().value("IsFavorite").toBool())
+ m_stars.insert(row.value("id").toString());
+ else
+ m_stars.remove(row.value("id").toString());
+ }
+ QVariantMap result{
+ {"items", rows},
+ {"more", mode != "random" && d.value("more").toBool()}};
+ if (mode == "playlist" || mode == "album") {
+ const auto remote = req.value("remoteId").toString();
+ json(
+ "Users/" + part(m_user) + "/Items/" + part(remote), {}, "GET", {},
+ [this, cb, result, remote, mode,
+ channel](const QVariantMap &meta, const QString &error) mutable {
+ if (!error.isEmpty()) {
+ cb({}, error);
+ return;
+ }
+ result["title"] = meta.value("Name");
+ result["artist"] = meta.value(
+ "AlbumArtist",
+ meta.value("AlbumArtists").toStringList().join(", "));
+ result["year"] = meta.value("ProductionYear");
+ if (mode == "playlist")
+ playlistAccess(
+ remote,
+ [cb, result](const QVariantMap &access,
+ const QString &) mutable {
+ result["editable"] = access.value("editable");
+ cb(result, {});
+ },
+ channel);
+ else
+ cb(result, {});
+ },
+ channel);
+ } else if (kind == "playlist")
+ resolvePlaylistAccess(
+ rows,
+ [cb, result](const QVariantMap &d, const QString &e) mutable {
+ result["items"] = d.value("items");
+ cb(result, e);
+ },
+ channel);
+ else
+ cb(result, {});
+ },
+ channel);
+}
+void JellyfinApi::reloadPlaylists() {
+ if (!connected())
+ return;
+ fetchRows(
+ "Items",
+ {{"UserId", m_user},
+ {"Recursive", "true"},
+ {"IncludeItemTypes", "Playlist"},
+ {"MediaTypes", "Audio"},
+ {"Fields", "CanDelete"}},
+ true,
+ [this](const QVariantMap &d, const QString &e) {
+ if (!e.isEmpty()) {
+ emit message(e);
+ return;
+ }
+ QVariantList rows;
+ for (const auto &v : d.value("Items").toList())
+ rows << item(v.toMap(), "playlist");
+ resolvePlaylistAccess(
+ rows,
+ [this](const QVariantMap &result, const QString &) {
+ m_playlists = result.value("items").toList();
+ emit changed();
+ },
+ "playlists");
+ },
+ "playlists");
+}
+void JellyfinApi::resolvePlaylistAccess(QVariantList rows, Reply cb,
+ const QString &channel) {
+ auto data = std::make_shared<QVariantList>(std::move(rows));
+ auto index = std::make_shared<int>(0);
+ auto step = std::make_shared<std::function<void()>>();
+ std::weak_ptr<std::function<void()>> weak = step;
+ *step = [this, data, index, weak, cb, channel] {
+ while (*index < data->size() &&
+ data->at(*index).toMap().value("editable").toBool())
+ ++*index;
+ if (*index >= data->size()) {
+ cb({{"items", *data}}, {});
+ return;
+ }
+ auto keep = weak.lock();
+ playlistAccess(
+ data->at(*index).toMap().value("remoteId").toString(),
+ [data, index, keep](const QVariantMap &access, const QString &) {
+ auto row = data->at(*index).toMap();
+ row["editable"] = access.value("editable");
+ (*data)[(*index)++] = row;
+ (*keep)();
+ },
+ channel);
+ };
+ (*step)();
+}
+void JellyfinApi::createPlaylist(const QString &name, Reply cb) {
+ if (name.trimmed().isEmpty() || !connected()) {
+ if (cb)
+ cb({}, "Connect and enter a playlist name first.");
+ return;
+ }
+ json("Playlists", {}, "POST",
+ {{"Name", name.trimmed().left(120)},
+ {"UserId", m_user},
+ {"MediaType", "Audio"},
+ {"IsPublic", false}},
+ [this, cb](const QVariantMap &data, const QString &e) {
+ if (e.isEmpty())
+ reloadPlaylists();
+ if (cb)
+ cb(data, e);
+ else
+ emit message(e.isEmpty() ? "Server playlist created" : e);
+ });
+}
+void JellyfinApi::editPlaylist(const QString &id, const Params &params,
+ Reply cb) {
+ if (!connected()) {
+ cb({}, "Connect to Jellyfin first.");
+ return;
+ }
+ auto done = [this, cb](const QVariantMap &d, const QString &e) {
+ if (e.isEmpty())
+ reloadPlaylists();
+ cb(d, e);
+ };
+ if (!value(params, "name").isEmpty()) {
+ json("Playlists/" + part(id), {}, "POST", {{"Name", value(params, "name")}},
+ done);
+ return;
+ }
+ const auto additions = values(params, "songIdToAdd");
+ if (!additions.isEmpty()) {
+ json("Playlists/" + part(id) + "/Items",
+ {{"Ids", additions.join(',')}, {"UserId", m_user}}, "POST", {}, done);
+ return;
+ }
+ const auto entries = values(params, "entryIdToRemove");
+ if (!entries.isEmpty()) {
+ if (entries.contains(QString())) {
+ done({}, "Refresh the playlist before removing songs.");
+ return;
+ }
+ json("Playlists/" + part(id) + "/Items", {{"EntryIds", entries.join(',')}},
+ "DELETE", {}, done);
+ return;
+ }
+ const auto removals = values(params, "songIndexToRemove");
+ if (!removals.isEmpty()) {
+ browse(
+ {{"mode", "playlist"}, {"remoteId", id}},
+ [this, id, removals, done](const QVariantMap &d, const QString &e) {
+ if (!e.isEmpty()) {
+ done({}, e);
+ return;
+ }
+ QStringList ids;
+ const auto rows = d.value("items").toList();
+ for (const auto &s : removals) {
+ bool ok = false;
+ const int index = s.toInt(&ok);
+ if (!ok || index < 0 || index >= rows.size()) {
+ done({},
+ "The playlist changed. Refresh it before removing songs.");
+ return;
+ }
+ ids << rows[index].toMap().value("entryId").toString();
+ }
+ if (ids.contains(QString())) {
+ done({}, "Jellyfin did not provide playlist entry identities.");
+ return;
+ }
+ json("Playlists/" + part(id) + "/Items",
+ {{"EntryIds", ids.join(',')}}, "DELETE", {}, done);
+ },
+ "playlist-edit");
+ return;
+ }
+ done({}, "No playlist changes supplied.");
+}
+void JellyfinApi::removePlaylist(const QString &id, Reply cb) {
+ if (!connected()) {
+ cb({}, "Connect to Jellyfin first.");
+ return;
+ }
+ json("Items/" + part(id), {}, "DELETE", {},
+ [this, cb](const QVariantMap &d, const QString &e) {
+ if (e.isEmpty())
+ reloadPlaylists();
+ cb(d, e);
+ });
+}
+void JellyfinApi::star(const QVariantMap &track, bool starred, Reply cb) {
+ if (!owns(track)) {
+ cb({}, "Reconnect to this song's Jellyfin server first.");
+ return;
+ }
+ cancel("stars");
+ json("Users/" + part(m_user) + "/FavoriteItems/" +
+ part(track.value("remoteId").toString()),
+ {}, starred ? "POST" : "DELETE", {},
+ [this, track, starred, cb](const QVariantMap &d, const QString &e) {
+ if (e.isEmpty()) {
+ if (starred)
+ m_stars.insert(track.value("id").toString());
+ else
+ m_stars.remove(track.value("id").toString());
+ emit changed();
+ }
+ cb(d, e);
+ });
+}
+void JellyfinApi::reportPlayback(const QVariantMap &track, qint64 position,
+ bool paused, bool stopped) {
+ if (!owns(track) || !scrobbling())
+ return;
+ const auto id = track.value("remoteId").toString();
+ QString endpoint = stopped ? "Sessions/Playing/Stopped"
+ : m_playing == id ? "Sessions/Playing/Progress"
+ : "Sessions/Playing";
+ if ((stopped && m_playing != id) ||
+ (paused && !stopped && m_playing.isEmpty()))
+ return;
+ QJsonObject body{{"ItemId", id},
+ {"PositionTicks", double(qMax<qint64>(0, position) * 10000)},
+ {"IsPaused", paused},
+ {"CanSeek", true},
+ {"PlayMethod", bitrate() ? "Transcode" : "DirectPlay"}};
+ if (stopped)
+ m_playing.clear();
+ else
+ m_playing = id;
+ const bool idle = m_reports.isEmpty();
+ if (m_reports.size() > 1 && endpoint == "Sessions/Playing/Progress" &&
+ m_reports.last().first == endpoint)
+ m_reports.last().second = body;
+ else
+ m_reports.append({endpoint, body});
+ if (idle)
+ sendPlaybackReport();
+}
+void JellyfinApi::sendPlaybackReport() {
+ if (m_reports.isEmpty())
+ return;
+ const auto report = m_reports.first();
+ json(
+ report.first, {}, "POST", report.second,
+ [this](const QVariantMap &, const QString &error) {
+ if (!error.isEmpty()) {
+ m_reports.clear();
+ m_playing.clear();
+ return;
+ }
+ if (!m_reports.isEmpty())
+ m_reports.removeFirst();
+ sendPlaybackReport();
+ },
+ "session");
+}
+void JellyfinApi::lyrics(const QVariantMap &track, Reply cb) {
+ if (!owns(track)) {
+ cb({}, "Reconnect to this song's Jellyfin server first.");
+ return;
+ }
+ json(
+ "Audio/" + part(track.value("remoteId").toString()) + "/Lyrics", {},
+ "GET", {},
+ [cb](const QVariantMap &d, const QString &e) {
+ if (!e.isEmpty()) {
+ if (d.value("httpStatus").toInt() == 404)
+ cb({{"ok", true}, {"lyrics", ""}, {"lines", QVariantList{}}}, {});
+ else
+ cb({}, e);
+ return;
+ }
+ QStringList text;
+ QString lrc;
+ const auto offset =
+ d.value("Metadata").toMap().value("Offset").toLongLong();
+ for (const auto &v : d.value("Lyrics").toList()) {
+ const auto line = v.toMap();
+ const auto t = line.value("Text").toString();
+ text << t;
+ if (line.contains("Start") && !line.value("Start").isNull()) {
+ const auto ms = qMax<qint64>(
+ 0, (line.value("Start").toLongLong() - offset) / 10000);
+ 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(t);
+ }
+ }
+ cb({{"ok", true},
+ {"lyrics", text.join('\n')},
+ {"lines", Lrc::parse(lrc)},
+ {"source", "Jellyfin"}},
+ {});
+ },
+ "lyrics");
+}
+void JellyfinApi::file(const QUrl &u, const QString &path, qint64 limit,
+ Reply cb, const QString &channel) {
+ cancel(channel);
+ auto f = std::make_shared<QFile>(path);
+ if (!f->open(QIODevice::WriteOnly)) {
+ cb({}, "Could not create the server buffer.");
+ return;
+ }
+ f->setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);
+ auto req = request(u);
+ req.setTransferTimeout(30000);
+ auto *r = m_network.get(req);
+ m_channels[channel] = r;
+ r->setReadBufferSize(256 * 1024);
+ const auto generation = m_generation;
+ auto failed = std::make_shared<bool>(false);
+ auto drain = [r, f, limit, failed] {
+ const auto bytes = r->readAll();
+ if (f->size() + bytes.size() > limit || f->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, f, drain, failed, generation, path, cb, channel] {
+ drain();
+ f->close();
+ if (m_channels.value(channel) == r)
+ m_channels.remove(channel);
+ r->deleteLater();
+ if (generation != m_generation) {
+ f->remove();
+ 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 || f->size() == 0 || type.contains("json") ||
+ type.contains("html") || type.contains("xml")) {
+ f->remove();
+ cb({}, *failed ? "The server buffer limit was reached or the "
+ "disk is full. Choose a lower bitrate."
+ : networkError(r));
+ return;
+ }
+ cb({{"ok", true}, {"file", path}}, {});
+ });
+}
+void JellyfinApi::download(const QVariantMap &track, const QString &path,
+ Reply cb, const QString &channel) {
+ if (!owns(track)) {
+ cb({}, "Reconnect to this song's Jellyfin server first.");
+ return;
+ }
+ const auto id = part(track.value("remoteId").toString());
+ Params p{{"UserId", m_user}, {"DeviceId", m_device}};
+ if (bitrate()) {
+ p.append(QPair<QString, QString>{"AudioCodec", "mp3"});
+ p.append(QPair<QString, QString>{"AudioBitRate",
+ QString::number(bitrate() * 1000)});
+ p.append(QPair<QString, QString>{"Container", "mp3"});
+ } else
+ p.append(QPair<QString, QString>{"Static", "true"});
+ file(url("Audio/" + id + (bitrate() ? "/stream.mp3" : "/stream"), p), path,
+ 512LL * 1024 * 1024, cb, channel);
+}
+void JellyfinApi::cover(const QVariantMap &track, const QString &path, Reply cb,
+ const QString &channel) {
+ auto u = artworkUrl(QUrl(track.value("art").toString()));
+ if (u.isEmpty()) {
+ cb({}, {});
+ return;
+ }
+ const int pixels = channel == "thumb" ? 256 : 1024;
+ QUrlQuery query(u);
+ query.removeAllQueryItems("MaxWidth");
+ query.removeAllQueryItems("MaxHeight");
+ query.addQueryItem("MaxWidth", QString::number(pixels));
+ query.addQueryItem("MaxHeight", QString::number(pixels));
+ u.setQuery(query);
+ if (u.isEmpty()) {
+ cb({}, {});
+ return;
+ }
+ file(
+ u, path + ".source", 4 * 1024 * 1024,
+ [path, cb, pixels](const QVariantMap &d, const QString &e) {
+ if (!e.isEmpty()) {
+ cb({}, e);
+ return;
+ }
+ const auto source = d.value("file").toString();
+ QImageReader reader(source);
+ const auto size = reader.size();
+ QImage image;
+ if (size.isValid() && size.width() <= 10000 && size.height() <= 10000) {
+ reader.setScaledSize(
+ size.scaled(pixels, pixels, Qt::KeepAspectRatio));
+ image = reader.read();
+ }
+ QFile::remove(source);
+ QSaveFile f(path);
+ if (image.isNull() || !f.open(QIODevice::WriteOnly)) {
+ cb({}, "Jellyfin artwork could not be decoded.");
+ return;
+ }
+ f.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);
+ if (!image.save(&f, "PNG") || !f.commit()) {
+ cb({}, "Jellyfin artwork could not be saved.");
+ return;
+ }
+ cb({{"file", path}}, {});
+ },
+ channel);
+}
+
+bool JellyfinApi::keyringAvailable() const {
+ return !QStandardPaths::findExecutable("secret-tool").isEmpty();
+}
+void JellyfinApi::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 JellyfinApi::movePlaylistItem(const QString &playlist,
+ const QString &entry, int index, Reply cb) {
+ if (!connected() || playlist.isEmpty() || entry.isEmpty() || index < 0) {
+ cb({}, "Refresh the playlist before moving songs.");
+ return;
+ }
+ json("Playlists/" + part(playlist) + "/Items/" + part(entry) + "/Move/" +
+ QString::number(index),
+ {}, "POST", {}, cb);
+}
diff --git a/src/jellyfinapi.h b/src/jellyfinapi.h
new file mode 100644
index 0000000..15f4511
--- /dev/null
+++ b/src/jellyfinapi.h
@@ -0,0 +1,104 @@
+#pragma once
+#include <QJsonObject>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QPointer>
+#include <QSet>
+#include <QSettings>
+#include <QUrlQuery>
+#include <functional>
+// Jellyfin credentials stay in request headers; persisted rows contain only
+// opaque identities.
+class JellyfinApi : 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)
+public:
+ using Reply = std::function<void(const QVariantMap &, const QString &)>;
+ using Params = QList<QPair<QString, QString>>;
+ explicit JellyfinApi(bool restore = true, const QString &settingsPath = {});
+ bool keyringAvailable() const;
+ ~JellyfinApi() 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("jellyfin/folder").toString();
+ }
+ bool scrobbling() const {
+ return m_settings.value("jellyfin/scrobble", true).toBool();
+ }
+ int bitrate() const {
+ return m_settings.value("jellyfin/bitrate", 0).toInt();
+ }
+ void setFolder(const QString &id);
+ void setScrobbling(bool value);
+ void setBitrate(int value);
+ Q_INVOKABLE void connectServer(const QString &, const QString &,
+ const QString &, bool remember = true);
+ Q_INVOKABLE void disconnectServer();
+ Q_INVOKABLE void reloadPlaylists();
+ void createPlaylist(const QString &name, Reply cb = {});
+ void cancel(const QString &channel);
+ void browse(const QVariantMap &, Reply, const QString &channel = "catalog");
+ void cover(const QVariantMap &, const QString &, Reply,
+ const QString &channel = "cover");
+ void lyrics(const QVariantMap &, Reply);
+ void download(const QVariantMap &, const QString &, Reply,
+ const QString &channel = "audio");
+ void star(const QVariantMap &, bool, Reply);
+ void editPlaylist(const QString &, const Params &, Reply);
+ void movePlaylistItem(const QString &, const QString &, int, Reply);
+ void removePlaylist(const QString &, Reply);
+ bool owns(const QVariantMap &) const;
+ bool isStarred(const QString &id) const { return m_stars.contains(id); }
+ QVariantMap item(const QVariantMap &, const QString &) const;
+ QUrl artworkUrl(const QUrl &) const;
+ 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 &,
+ std::function<void(bool, QByteArray)>);
+ QUrl url(const QString &, const Params & = {}) const;
+ QNetworkRequest request(const QUrl &) const;
+ void json(const QString &, const Params &, const QByteArray &,
+ const QJsonObject &, Reply, const QString &channel = {});
+ void fetchRows(const QString &, Params, bool, Reply, const QString &);
+ void file(const QUrl &, const QString &, qint64, Reply, const QString &);
+ void stopRequests();
+ void resolvePlaylistAccess(QVariantList, Reply, const QString &);
+ void sendPlaybackReport();
+ QList<QPair<QString, QJsonObject>> m_reports;
+ void discover();
+ void acceptLogin(const QVariantMap &, bool);
+ void playlistAccess(const QString &, Reply, const QString &channel = {});
+ QNetworkAccessManager m_network;
+ QSettings m_settings;
+ QString m_address, m_username, m_identity, m_error, m_token, m_user, m_device;
+ bool m_connected = false, m_connecting = false;
+ quint64 m_generation = 0;
+ QHash<QString, QPointer<QNetworkReply>> m_channels;
+ QVariantList m_playlists, m_folders;
+ QSet<QString> m_stars;
+ QString m_playing;
+};
diff --git a/src/jellyfinlrc.h b/src/jellyfinlrc.h
new file mode 100644
index 0000000..ad80b32
--- /dev/null
+++ b/src/jellyfinlrc.h
@@ -0,0 +1,74 @@
+#pragma once
+#include <QRegularExpression>
+#include <QVariantList>
+#include <algorithm>
+namespace Lrc {
+inline QVariantList parse(QString text, qint64 duration = 0) {
+ if (text.size() > 262144)
+ return {};
+ static const QRegularExpression stamp(
+ R"(\[(\d{1,3}):([0-5]\d)(?:\.(\d{1,3}))?\])");
+ static const QRegularExpression offset(
+ R"(\[offset:([+-]?\d{1,7})\])",
+ QRegularExpression::CaseInsensitiveOption);
+ const auto adjustment = offset.match(text);
+ const qint64 shift =
+ adjustment.hasMatch() ? adjustment.captured(1).toLongLong() : 0;
+ QVariantList lines;
+ for (const auto &raw : text.split('\n')) {
+ auto matches = stamp.globalMatch(raw);
+ QList<qint64> starts;
+ int end = 0;
+ while (matches.hasNext()) {
+ auto m = matches.next();
+ starts.append((m.captured(1).toLongLong() * 60 + m.captured(2).toInt()) *
+ 1000 +
+ m.captured(3).leftJustified(3, '0').toInt() - shift);
+ end = m.capturedEnd();
+ }
+ const auto words = raw.mid(end).trimmed();
+ for (auto start : starts) {
+ if (start < 0)
+ start = 0;
+ lines.append(QVariantMap{{"start", start}, {"end", 0}, {"text", words}});
+ if (lines.size() > 4000)
+ return {};
+ }
+ }
+ std::stable_sort(lines.begin(), lines.end(),
+ [](const QVariant &a, const QVariant &b) {
+ return a.toMap().value("start").toLongLong() <
+ b.toMap().value("start").toLongLong();
+ });
+ // Equal timestamps represent one line (e.g. a translation), never zero-length
+ // rows.
+ QVariantList merged;
+ for (const auto &v : lines) {
+ auto line = v.toMap();
+ if (!merged.isEmpty() &&
+ merged.last().toMap().value("start") == line.value("start")) {
+ auto last = merged.last().toMap();
+ last["text"] =
+ last.value("text").toString() + "\n" + line.value("text").toString();
+ merged.last() = last;
+ } else
+ merged.append(line);
+ }
+ bool words = false;
+ for (int i = 0; i < merged.size(); ++i) {
+ auto line = merged[i].toMap();
+ line["end"] = i + 1 < merged.size()
+ ? merged[i + 1].toMap().value("start").toLongLong()
+ : qMax(duration, line.value("start").toLongLong() + 5000);
+ words |= !line.value("text").toString().isEmpty();
+ merged[i] = line;
+ }
+ return words ? merged : QVariantList{};
+}
+inline QString plain(const QVariantList &lines) {
+ QStringList result;
+ for (const auto &v : lines)
+ result.append(v.toMap().value("text").toString());
+ return result.join('\n');
+}
+} // namespace Lrc
diff --git a/src/jellyfinprotocoltest.cpp b/src/jellyfinprotocoltest.cpp
new file mode 100644
index 0000000..3dcb806
--- /dev/null
+++ b/src/jellyfinprotocoltest.cpp
@@ -0,0 +1,331 @@
+#include "jellyfin.h"
+#include "jellyfinapi.h"
+#include <QBuffer>
+#include <QDir>
+#include <QFile>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QTcpServer>
+#include <QTcpSocket>
+#include <QTemporaryDir>
+#include <QUrlQuery>
+#include <QtTest>
+class JellyfinProtocolTest : public QObject {
+ Q_OBJECT
+ QTemporaryDir storage;
+ QTcpServer http;
+ QString mode = "ok", base;
+ QByteArray received;
+ int requests = 0;
+private slots:
+ void initTestCase() {
+ qputenv("XDG_CONFIG_HOME", storage.path().toUtf8());
+ QCoreApplication::setOrganizationName("SpunTests");
+ QCoreApplication::setApplicationName("jellyfin-protocol");
+ QVERIFY(http.listen(QHostAddress::LocalHost));
+ base = "http://127.0.0.1:" + QString::number(http.serverPort()) + "/music";
+ 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 data =
+ socket->property("data").toByteArray() + socket->readAll();
+ socket->setProperty("data", data);
+ const int end = data.indexOf("\r\n\r\n");
+ if (end < 0 || socket->property("sent").toBool())
+ return;
+ int length = 0;
+ for (const auto &line : data.left(end).split('\n'))
+ if (line.toLower().startsWith("content-length:"))
+ length = line.mid(15).trimmed().toInt();
+ if (data.size() < end + 4 + length)
+ return;
+ socket->setProperty("sent", true);
+ received = data;
+ ++requests;
+ if (mode == "hold")
+ return;
+ QByteArray status = "200 OK",
+ body = "{\"Items\":[],\"TotalRecordCount\":0}", extra, contentType = "application/json";
+ if (data.startsWith("POST /music/Users/AuthenticateByName"))
+ body = "{\"User\":{\"Id\":\"fixture-user\"},\"AccessToken\":"
+ "\"fixture-token\"}";
+ if (data.startsWith("GET /music/Users/Me"))
+ body = "{\"Id\":\"fixture-user\"}";
+ if (mode == "redirect") {
+ status = "302 Found";
+ extra = "Location: http://127.0.0.1:1/leak\r\n";
+ }
+ if (mode == "malformed")
+ body = "<html>Wrong server</html>";
+ if (mode == "expired")
+ status = "401 Unauthorized";
+ if (mode == "forbidden")
+ status = "403 Forbidden";
+ if (mode == "missing")
+ status = "404 Not Found";
+ if (mode == "oversized")
+ body = QByteArray(17 * 1024 * 1024, 'x');
+ if (mode == "disconnect") {
+ socket->abort();
+ return;
+ }
+ if (mode == "lyrics")
+ body = "{\"Metadata\":{\"IsSynced\":true,\"Offset\":10000000},"
+ "\"Lyrics\":[{\"Text\":\"One\",\"Start\":20000000},{"
+ "\"Text\":\"Two\",\"Start\":50000000}]}";
+ if (mode == "thumbnails") {
+ const QUrl requestUrl(
+ base + QString::fromUtf8(data.split(' ').value(1)).mid(6));
+ if (requestUrl.path().contains("/Images/")) {
+ contentType = "image/png";
+ QImage image(8, 8, QImage::Format_RGB32);
+ image.fill(Qt::blue);
+ QBuffer buffer(&body);
+ buffer.open(QIODevice::WriteOnly | QIODevice::Truncate);
+ image.save(&buffer, "PNG");
+ } else if (requestUrl.path().endsWith("/Items")) {
+ const int start =
+ QUrlQuery(requestUrl).queryItemValue("StartIndex").toInt();
+ QJsonArray rows;
+ for (int i = start; i < qMin(start + 100, 300); ++i)
+ rows.append(QJsonObject{
+ {"Id", QString::number(i)},
+ {"Name", QString("Song %1").arg(i)},
+ {"Type", "Audio"},
+ {"ImageTags", QJsonObject{{"Primary", "fixture"}}}});
+ body = QJsonDocument(QJsonObject{{"Items", rows},
+ {"TotalRecordCount", 300}})
+ .toJson();
+ }
+ }
+ socket->write("HTTP/1.1 " + status + "\r\n" + extra +
+ "Content-Type: " + contentType + "\r\nContent-Length: " +
+ QByteArray::number(body.size()) +
+ "\r\nConnection: close\r\n\r\n" + body);
+ socket->disconnectFromHost();
+ });
+ }
+ });
+ }
+ void init() {
+ mode = "ok";
+ received.clear();
+ requests = 0;
+ }
+ void rejectsBadResponses_data() {
+ QTest::addColumn<QString>("behavior");
+ for (auto v : {"redirect", "malformed", "expired", "forbidden", "oversized",
+ "disconnect"})
+ QTest::newRow(v) << QString(v);
+ }
+ void rejectsBadResponses() {
+ QFETCH(QString, behavior);
+ mode = behavior;
+ JellyfinApi client(false);
+ 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 credentialsAndBasePath() {
+ mode = "hold";
+ JellyfinApi client(false);
+ client.connectServer(base, "café + &", "test-secret", false);
+ QTRY_VERIFY(!received.isEmpty());
+ const auto header = received.left(received.indexOf("\r\n\r\n"));
+ QVERIFY(header.startsWith("POST /music/Users/AuthenticateByName "));
+ QVERIFY(!header.contains("test-secret"));
+ QVERIFY(received.contains("test-secret"));
+ client.disconnectServer();
+ QVERIFY(!client.connecting());
+ }
+ void invalidAddresses() {
+ JellyfinApi client(false);
+ for (auto s : {"file:///tmp/server", "http://user:secret@localhost",
+ "http://localhost/?token=x", "http://localhost/#web"}) {
+ client.connectServer(s, "a", "", false);
+ QVERIFY(!client.connecting());
+ QVERIFY(!client.error().isEmpty());
+ }
+ }
+ 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");
+ });
+ {
+ JellyfinApi client;
+ client.connectServer(base, "fixture", "keyring fixture + café", true);
+ QTRY_VERIFY(client.connected());
+ QTRY_VERIFY(QSettings().value("jellyfin/remember").toBool());
+ QVERIFY(QFile::exists(secretFile));
+ QFile config(QSettings().fileName());
+ QSettings().sync();
+ QVERIFY(config.open(QIODevice::ReadOnly));
+ QVERIFY(!config.readAll().contains("keyring fixture"));
+ }
+ {
+ JellyfinApi client;
+ QTRY_VERIFY(client.connected());
+ QCOMPARE(client.username(), QString("fixture"));
+ client.disconnectServer();
+ QTRY_VERIFY(!QFile::exists(secretFile));
+ QVERIFY(!QSettings().contains("jellyfin/remember"));
+ }
+ }
+ void cancelledLogin() {
+ mode = "hold";
+ JellyfinApi client(false);
+ client.connectServer(base, "a", "b", false);
+ QTRY_VERIFY(!received.isEmpty());
+ client.disconnectServer();
+ QTest::qWait(100);
+ QVERIFY(!client.connected());
+ QVERIFY(client.error().isEmpty());
+ }
+ void artworkCredentialsAreEphemeral() {
+ JellyfinApi client(false);
+ client.connectServer(base, "a", "b", false);
+ QTRY_VERIFY(client.connected());
+ auto item = client.item(
+ {{"Id", "song"}, {"ImageTags", QVariantMap{{"Primary", "tag"}}}},
+ "song");
+ QVERIFY(!item.value("art").toString().contains("fixture-token"));
+ const auto req = client.artworkRequest(QUrl(item.value("art").toString()));
+ QVERIFY(!req.url().toString().contains("fixture-token"));
+ QVERIFY(req.rawHeader("Authorization").contains("fixture-token"));
+ client.disconnectServer();
+ QVERIFY(client.artworkUrl(QUrl(item.value("art").toString())).isEmpty());
+ }
+ void lyricOffsetAndMissing() {
+ JellyfinApi client(false);
+ client.connectServer(base, "a", "b", false);
+ QTRY_VERIFY(client.connected());
+ QTest::qWait(100);
+ auto song = client.item({{"Id", "song"}}, "song");
+ mode = "lyrics";
+ bool done = false;
+ QVariantMap result;
+ QString error;
+ client.lyrics(song, [&](const QVariantMap &d, const QString &e) {
+ done = true;
+ result = d;
+ error = e;
+ });
+ QTRY_VERIFY(done);
+ QVERIFY(error.isEmpty());
+ QCOMPARE(result.value("lines").toList().size(), 2);
+ QCOMPARE(result.value("lines")
+ .toList()
+ .first()
+ .toMap()
+ .value("start")
+ .toLongLong(),
+ 1000);
+ mode = "missing";
+ done = false;
+ client.lyrics(song, [&](const QVariantMap &d, const QString &e) {
+ done = true;
+ result = d;
+ error = e;
+ });
+ QTRY_VERIFY(done);
+ QVERIFY(error.isEmpty());
+ QVERIFY(result.value("lines").toList().isEmpty());
+ }
+ void failedAudioCleansBuffer() {
+ JellyfinApi client(false);
+ client.connectServer(base, "a", "b", false);
+ QTRY_VERIFY(client.connected());
+ QTest::qWait(100);
+ mode = "forbidden";
+ const auto path = storage.filePath("failed-audio");
+ bool done = false;
+ QString error;
+ client.download(client.item({{"Id", "song"}}, "song"), path,
+ [&](const QVariantMap &, const QString &e) {
+ done = true;
+ error = e;
+ });
+ QTRY_VERIFY(done);
+ QVERIFY(!error.isEmpty());
+ QVERIFY(!QFile::exists(path));
+ }
+ void boundedThumbnailCache() {
+ QTemporaryDir profile;
+ Jellyfin client(profile.path(), false);
+ client.setEnabled(true);
+ client.server()->connectServer(base, "a", "b", false);
+ QTRY_VERIFY(client.server()->connected());
+ QTRY_VERIFY(!client.busy());
+ mode = "thumbnails";
+ client.show("songs");
+ QTRY_VERIFY(!client.busy());
+ client.loadMore();
+ QTRY_VERIFY(!client.busy());
+ client.loadMore();
+ QTRY_VERIFY(!client.busy());
+ QCOMPARE(client.items().size(), 300);
+ QString lastFile;
+ for (const auto &v : client.items()) {
+ const auto id = v.toMap().value("id").toString();
+ QTRY_VERIFY(!client.artwork(id).isEmpty());
+ lastFile = QUrl(client.artwork(id)).toLocalFile();
+ }
+ const auto directory = QFileInfo(lastFile).absoluteDir();
+ QCOMPARE(directory.entryList({"*.png"}, QDir::Files).size(), 256);
+ const int completed = requests;
+ QTest::qWait(200);
+ QCOMPARE(requests, completed);
+ const auto first = client.items().first().toMap().value("id").toString();
+ QVERIFY(client.artwork(first).isEmpty());
+ QTRY_VERIFY(!client.artwork(first).isEmpty());
+ QCOMPARE(directory.entryList({"*.png"}, QDir::Files).size(), 256);
+ QVERIFY(requests > completed);
+ client.server()->disconnectServer();
+ QVERIFY(directory.entryList({"*.png"}, QDir::Files).isEmpty());
+ }
+ void accountIdentity() {
+ JellyfinApi a(false), b(false);
+ a.connectServer(base, "a", "b", false);
+ b.connectServer(base + "/other", "a", "b", false);
+ QTRY_VERIFY(a.connected());
+ const auto song = a.item({{"Id", "song"}}, "song");
+ QVERIFY(!b.owns(song));
+ a.disconnectServer();
+ QVERIFY(!a.owns(song));
+ }
+};
+QTEST_MAIN(JellyfinProtocolTest)
+#include "jellyfinprotocoltest.moc"
diff --git a/src/jellyfintest.cpp b/src/jellyfintest.cpp
new file mode 100644
index 0000000..998c74d
--- /dev/null
+++ b/src/jellyfintest.cpp
@@ -0,0 +1,490 @@
+#include "jellyfintest.h"
+#include "mpris.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 exerciseJellyfin(Player &local, Jellyfin &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);
+ auto image = captureTestWindow(window);
+ 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 = 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;
+ QNetworkAccessManager fixture;
+ auto fixtureGet = [&](const QString &path, const QByteArray &method = "GET",
+ const QJsonObject &body = QJsonObject{}) {
+ QNetworkRequest request(QUrl(base + path));
+ request.setRawHeader("Authorization", "MediaBrowser Token=\"" +
+ qgetenv("SPUN_TEST_ADMIN_TOKEN") +
+ "\"");
+ request.setTransferTimeout(3000);
+ request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
+ auto *reply = fixture.sendCustomRequest(
+ request, method,
+ method == "GET" ? QByteArray()
+ : QJsonDocument(body).toJson(QJsonDocument::Compact));
+ until([&] { return reply->isFinished(); }, 4000);
+ auto result = QJsonDocument::fromJson(reply->readAll());
+ reply->deleteLater();
+ return result;
+ };
+ auto session = [&]() {
+ for (const auto &value : fixtureGet("/Sessions").array()) {
+ const auto row = value.toObject().toVariantMap();
+ if (row.value("Client") == "Spun")
+ return row;
+ }
+ return QVariantMap{};
+ };
+ local.demo();
+ check(until([&] { return local.count() > 0 && !local.busy(); }),
+ "local queue fixture loaded");
+ local.pause();
+ auto localKey = local.trackKey();
+ click("jellyfinSourceButton");
+ check(window->property("useJellyfin").toBool() && jf.enabled(),
+ "Jellyfin source selected");
+ capture("jellyfin-disconnected");
+ click("jellyfinConnect");
+ check(until([&] {
+ auto *f = find(window->contentItem(), "jellyfinAddress");
+ return f && f->isVisible();
+ }),
+ "connection dialog opens");
+ check(until([&] { return find(window->contentItem(), "jellyfinAddress")->hasActiveFocus(); }),
+ "connection starts with first input focused");
+ QTest::keyClick(window, Qt::Key_Tab);
+ check(find(window->contentItem(), "jellyfinUsername")->hasActiveFocus(),
+ "Tab moves to username");
+ QTest::keyClick(window, Qt::Key_Tab, Qt::ShiftModifier);
+ check(until([&] { return find(window->contentItem(), "jellyfinAddress")->hasActiveFocus(); }),
+ "Shift Tab returns to server field");
+ for (const auto &entry :
+ QList<QPair<QString, QString>>{{"jellyfinAddress", base},
+ {"jellyfinUsername", user},
+ {"jellyfinPassword", password}}) {
+ auto *field = find(window->contentItem(), entry.first);
+ if (field)
+ field->setProperty("text", entry.second);
+ }
+ if (auto *remember = find(window->contentItem(), "jellyfinRemember"))
+ remember->setProperty("checked", false);
+ click("jellyfinSignIn");
+ if (!check(until([&] { return api->connected(); }),
+ "real server sign-in from UI"))
+ return 1;
+ check(until([&] { return api->folders().size() == 2; }),
+ "music libraries discovered");
+ check(find(window->contentItem(), "jellyfinPassword")
+ ->property("text")
+ .toString()
+ .isEmpty(),
+ "password field cleared after sign-in");
+ QMetaObject::invokeMethod(find(window->contentItem(), "jellyfinPanel"),
+ "closeActions");
+ QTest::qWait(250);
+ check(until([&] { return !jf.busy() && !jf.items().isEmpty(); }),
+ "albums load after connection");
+ capture("jellyfin-albums");
+ click("jellyfinPageActions");
+ click("jellyfinSettings");
+ capture("jellyfin-settings");
+ click("jellyfinQuality");
+ click("jellyfinQuality_192");
+ check(api->bitrate() == 192, "quality menu applies selected bitrate");
+ api->setBitrate(0);
+ QMetaObject::invokeMethod(find(window->contentItem(), "jellyfinPanel"),
+ "closeActions");
+ QString otherFolder;
+ for (const auto &v : api->folders())
+ if (v.toMap().value("name") == "Other Music")
+ otherFolder = v.toMap().value("id").toString();
+ api->setFolder(otherFolder);
+ jf.show("songs");
+ check(!otherFolder.isEmpty() && until([&] { return !jf.busy(); }) &&
+ jf.items().size() == 1 &&
+ jf.items()[0].toMap().value("title") == "Other library song",
+ "library 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.show("genres");
+ check(until([&] { return !jf.busy(); }) && !jf.items().isEmpty(),
+ "genre browser");
+ 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("jellyfinPageActions");
+ click("jellyfinNewPlaylist");
+ check(until([&] {
+ auto *f = find(window->contentItem(), "jellyfinPlaylistName");
+ return f && f->hasActiveFocus();
+ }),
+ "playlist dialog receives keyboard focus");
+ capture("jellyfin-playlist-dialog");
+ bool focusTrapped = true;
+ auto *dialog = find(window->contentItem(), "jellyfinNameDialog");
+ 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(), "jellyfinPlaylistName"))
+ f->setProperty("text", "Spun fixture playlist");
+ click("jellyfinNameDialogAccept");
+ 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");
+ 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("jellyfin-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(until(
+ [&] {
+ return session()
+ .value("PlayState")
+ .toMap()
+ .value("IsPaused")
+ .toBool();
+ },
+ 5000),
+ "server receives pause state");
+ check(qAbs(session()
+ .value("PlayState")
+ .toMap()
+ .value("PositionTicks")
+ .toLongLong() /
+ 10000 -
+ 5000) < 500,
+ "server receives seek position");
+ player->stop();
+ check(
+ until([&] { return session().value("NowPlayingItem").toMap().isEmpty(); },
+ 5000),
+ "stop ends server playback session");
+ 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 Jellyfin 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, player);
+ media.setSourceWindow(window);
+ check(media.metadata().value("xesam:title") == player->title(),
+ "MPRIS uses Jellyfin metadata");
+ media.Play();
+ check(until([&] { return player->playing(); }), "MPRIS plays Jellyfin");
+ media.Pause();
+ check(!player->playing(), "MPRIS pauses Jellyfin");
+ click("localSourceButton");
+ check(!jf.enabled() && !player->playing() && local.trackKey() == localKey,
+ "source switch preserves local queue and pauses Jellyfin");
+ click("jellyfinSourceButton");
+ check(player->count() == 2, "Jellyfin 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 Jellyfin transport");
+ capture("jellyfin-" + 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("jellyfin-" + medium + "-3d");
+ player->seek(2000);
+ click("playButton");
+ check(until([&] { return player->position() > 2200; }) &&
+ player->playing(),
+ "3D transport starts Jellyfin audio");
+ click("playButton");
+ check(!player->playing(), "3D transport pauses Jellyfin 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 Jellyfin in TP-7 view");
+ player->play();
+ check(until([&] { return mixer->meters()[0].toDouble() > 0.00001; }),
+ "decoded Jellyfin audio reaches TX-6 mixer");
+ player->pause();
+ capture("jellyfin-tx6");
+ mixer->setVisible(false);
+ }
+ local.setMotion(false);
+ QTest::qWait(100);
+ check(find(window->contentItem(), "jellyfinPanel")->opacity() == 1,
+ "reduced motion leaves browser fully visible");
+ local.setThreeD(false);
+ fixtureGet(
+ "/Playlists/" + playlistId, "POST",
+ {{"Users",
+ QJsonArray{
+ QJsonObject{{"UserId", qEnvironmentVariable("SPUN_TEST_ADMIN_ID")},
+ {"CanEdit", true}},
+ QJsonObject{{"UserId", qEnvironmentVariable("SPUN_TEST_READER_ID")},
+ {"CanEdit", false}}}}});
+ 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");
+ check(
+ until(
+ [&] { return !session().value("NowPlayingItem").toMap().isEmpty(); },
+ 5000),
+ "server receives playback start");
+ api->setScrobbling(false);
+ check(
+ until([&] { return session().value("NowPlayingItem").toMap().isEmpty(); },
+ 5000),
+ "disabling reporting clears session");
+ player->seek(3000);
+ QTest::qWait(100);
+ check(session().value("NowPlayingItem").toMap().isEmpty(),
+ "disabled reporting stays disabled during seek");
+ 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 + "/jellyfin/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 << "JELLYFIN_RESULT " << checks << " checks, " << failures
+ << " failures" << std::endl;
+ return failures ? 1 : 0;
+}
diff --git a/src/jellyfintest.h b/src/jellyfintest.h
new file mode 100644
index 0000000..954aea2
--- /dev/null
+++ b/src/jellyfintest.h
@@ -0,0 +1,5 @@
+#pragma once
+#include "jellyfin.h"
+#include <QQuickWindow>
+int exerciseJellyfin(Player &, Jellyfin &, QQuickWindow *, const QString &,
+ const QString &);
diff --git a/src/main.cpp b/src/main.cpp
index 485103a..ee414c8 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -5,6 +5,11 @@
#include <QtQuick3D/qquick3d.h>
#endif
#include "player.h"
+#include "youtube.h"
+#include "jellyfin.h"
+#ifdef SPUN_DIAGNOSTICS
+#include "jellyfintest.h"
+#endif
#include "tx6.h"
#include "tapesound.h"
#include "vinylnoise.h"
@@ -13,6 +18,7 @@
#include "musicactions.h"
#ifdef SPUN_DIAGNOSTICS
#include "librarytest.h"
+#include "youtubetest.h"
#include "mediauitest.h"
#include "artworktest.h"
#include "threedtest.h"
@@ -213,7 +219,7 @@ public:
// Error notices can overlap the otherwise click-through perimeter.
region |= QRegion(73, 419, 384, 80);
if (queue) {
- const auto *panelName = window->property("libraryOpen").toBool() ? "libraryPanel" : "queuePanel";
+ const auto *panelName = window->property("libraryOpen").toBool() ? (window->property("useYoutube").toBool() ? "youtubePanel" : "libraryPanel") : "queuePanel";
if (auto *panel = window->findChild<QQuickItem *>(panelName))
region |= itemRegion(panel);
}
@@ -782,7 +788,7 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
check(sourceIndicator && waitFor([&] { return qAbs(sourceIndicator->x() - 56) < .25; }),
"source selection spring settles after reversing direction");
window->setProperty("useCider", true); QTest::qWait(20); player.setMotion(false); QTest::qWait(20);
- check(sourceIndicator && qAbs(sourceIndicator->x() - 128) < .1,
+ check(sourceIndicator && ciderTab && qAbs(sourceIndicator->x() - ciderTab->mapToItem(sourceIndicator->parentItem(), QPointF()).x()) < .1,
"reduced motion settles an in-flight selection spring immediately");
window->setProperty("useCider", false); player.setMotion(true);
auto *hoverButton = findItem(window->contentItem(), "menuButton");
@@ -1486,8 +1492,10 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
player.addUrls({QUrl::fromLocalFile(nextAlbum)},false);waitFor([&]{return !player.busy();});
write(temp+"/state/noctalia/settings.toml", "[shell.animation]\nenabled = true\n");
waitFor([&]{return theme.motionScale()>0;});
- player.select(1,false);waitFor([&]{return !player.artworkLoading();});QTest::qWait(80);
- check(window->property("swapRunning").toBool(), "changing albums slides out the previous disc");
+ // Observe departure as it starts. Waiting for the incoming artwork and
+ // then sleeping can miss departure while the arrival phase still runs.
+ player.select(1,false);
+ check(waitFor([&]{return window->property("swapRunning").toBool();}), "changing albums slides out the previous disc");
auto *outgoingDisc = window->findChild<QObject *>("outgoingDiscLoader");
check(outgoingDisc && outgoingDisc->property("active").toBool()
&& outgoingDisc->property("item").value<QObject *>(), "outgoing disc remains rendered during its exit animation");
@@ -1554,7 +1562,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-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-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");
@@ -1595,6 +1603,9 @@ 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-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"});
parser.addOption({"test-library", "Run isolated music browser checks"});
parser.addOption({"self-test", "Run isolated playback and UI checks"});
parser.addOption({"test-artwork", "Verify artwork updates across playback sources and physical media"});
@@ -1615,14 +1626,16 @@ int main(int argc, char **argv) {
parser.addOption({"inspect-library", "Verify Cider music browsing without changing playback"});
parser.addOption({"inspect-cider", "Verify live Cider metadata and artwork without changing playback"});
parser.addOption({"capture-dir", "Save test captures", "directory"});
+ parser.addOption({"youtube", "Open the anonymous YouTube Music browser"});
+ parser.addOption({"isolated", "Do not connect to Cider or register desktop media controls"});
parser.addOption({"config", "Use a specific settings file", "path"});
parser.addOption({"export-cover", "Write the original fallback artwork", "path"});
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-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-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")) {
+ if (!test && !parser.isSet("config") && !parser.isSet("isolated")) {
auto bus = QDBusConnection::sessionBus();
if (bus.interface() && bus.interface()->isServiceRegistered("org.mpris.MediaPlayer2.spun")) {
QDBusInterface shell("org.mpris.MediaPlayer2.spun", "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2", bus);
@@ -1654,8 +1667,17 @@ int main(int argc, char **argv) {
const qint64 fontReady = startup.elapsed();
Theme theme(configRoot, stateRoot);
Player player(settings);
+ Youtube youtube(QFileInfo(settings).absolutePath() + "/youtube");
+ Jellyfin jellyfin(QFileInfo(settings).absolutePath() + "/jellyfin", !test);
+ 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());
+ QObject::connect(&player,&Player::mediumChanged,&youtube,[&]{youtube.transport()->setMedium(player.medium());});
+ QObject::connect(&player,&Player::settingsChanged,&youtube,[&]{youtube.transport()->setVinylAlbumMode(player.vinylAlbumMode());});
+ youtube.transport()->setMedium(player.medium());
+ youtube.transport()->setVinylAlbumMode(player.vinylAlbumMode());
Tx6 tx6(&player,settings,!test || qEnvironmentVariableIsSet("SPUN_TEST_MIXER_OUTPUT"));
- Cider cider(!test, QFileInfo(settings).absolutePath() + "/cider-connection.json");
+ Cider cider(!test && !parser.isSet("isolated"), QFileInfo(settings).absolutePath() + "/cider-connection.json");
Lyrics lyrics(&player, &cider);
Library library(&cider);
MusicActions musicActions(&cider);
@@ -1697,6 +1719,8 @@ int main(int argc, char **argv) {
#endif
engine.rootContext()->setContextProperty("player3DUrl", QUrl(QStringLiteral("qrc:/qml/Player3D.qml")));
engine.rootContext()->setContextProperty("player", &player);
+ engine.rootContext()->setContextProperty("youtube", &youtube);
+ engine.rootContext()->setContextProperty("jellyfin", &jellyfin);
engine.rootContext()->setContextProperty("tx6", &tx6);
engine.rootContext()->setContextProperty("theme", &theme);
engine.rootContext()->setContextProperty("typography", &typography);
@@ -1754,7 +1778,8 @@ int main(int argc, char **argv) {
window->setScreen(screen);
window->setPosition(screen->availableGeometry().topLeft()+QPoint(60,60));
}
- if (!test) { if (auto *mediaControls = registerMpris(&player, &cider)) mediaControls->setSourceWindow(window); }
+ 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); }
QObject::connect(&app, &QCoreApplication::aboutToQuit, &player, &Player::save);
if (parser.isSet("benchmark")) {
window->setProperty("benchmarkPinned", true);
@@ -2174,6 +2199,9 @@ 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-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"))); });
else if (parser.isSet("test-media-ui")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseMediaUi(player,window,temp.path(),parser.value("capture-dir"))); });
else if (parser.isSet("test-library")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseLibrary(window,temp.path(),parser.value("capture-dir")) ? 1 : 0); });
else if (test) QTimer::singleShot(650, &app, [&] {
diff --git a/src/mpris.cpp b/src/mpris.cpp
index 61aefe3..1f27f9e 100644
--- a/src/mpris.cpp
+++ b/src/mpris.cpp
@@ -18,7 +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) : QDBusAbstractAdaptor(p), m_player(p), m_cider(cider) {
+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;
connect(p, &Player::trackChanged, this, &PlayerAdaptor::changed);
connect(p, &Player::playingChanged, this, &PlayerAdaptor::changed);
connect(p, &Player::durationChanged, this, &PlayerAdaptor::changed);
@@ -26,7 +27,8 @@ PlayerAdaptor::PlayerAdaptor(Player *p, Cider *cider) : QDBusAbstractAdaptor(p),
connect(p, &Player::volumeChanged, this, &PlayerAdaptor::changed);
connect(p, &Player::queueChanged, this, &PlayerAdaptor::changed);
connect(p, &Player::artworkChanged, this, &PlayerAdaptor::changed);
- connect(p, &Player::seeked, this, [this](qint64 value) { if (!m_remote) emit Seeked(value * 1000); });
+ connect(p, &Player::seeked, this, [this,p](qint64 value) { if (!m_remote && m_player==p) emit Seeked(value * 1000); });
+ }
if (cider) {
connect(cider, &Cider::trackChanged, this, &PlayerAdaptor::changed);
connect(cider, &Cider::playingChanged, this, &PlayerAdaptor::changed);
@@ -52,9 +54,15 @@ void PlayerAdaptor::setLoop(const QString &value) {
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("useJellyfin")>=0)QQmlProperty(window, "useJellyfin").connectNotifySignal(this, SLOT(syncSource()));
syncSource();
}
-void PlayerAdaptor::syncSource() { setRemote(m_sourceWindow && m_sourceWindow->property("useCider").toBool()); }
+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;
+ setRemote(m_sourceWindow && m_sourceWindow->property("useCider").toBool());
+ changed(); emit Seeked(position());
+}
void PlayerAdaptor::setRemote(bool remote) {
remote = remote && m_cider;
if (remote == m_remote) return;
@@ -124,11 +132,11 @@ void PlayerAdaptor::changed() {
QDBusConnection::sessionBus().send(message);
});
}
-PlayerAdaptor *registerMpris(Player *player, Cider *cider) {
+PlayerAdaptor *registerMpris(Player *player, Cider *cider, Player *youtube, Player *jellyfin) {
auto bus = QDBusConnection::sessionBus();
if (!bus.registerService("org.mpris.MediaPlayer2.spun")) return nullptr;
new RootAdaptor(player);
- auto *adaptor = new PlayerAdaptor(player, cider);
+ auto *adaptor = new PlayerAdaptor(player, cider, youtube, jellyfin);
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.h
index ec08266..f5fef75 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);
+ explicit PlayerAdaptor(Player *p, Cider *cider = nullptr, Player *youtube = nullptr, Player *jellyfin = nullptr);
void setRemote(bool remote);
void setSourceWindow(QObject *window);
QString trackId() const;
@@ -80,7 +80,7 @@ public slots:
void Play() { if (canControl()) { if (m_remote) m_cider->play(); else m_player->play(); } }
void Seek(qlonglong offset);
void SetPosition(const QDBusObjectPath &trackId, qlonglong position);
- void OpenUri(const QString &uri) { m_player->addUrls({QUrl(uri)}); }
+ void OpenUri(const QString &uri) { m_local->addUrls({QUrl(uri)}); }
signals:
void Seeked(qlonglong position);
private slots:
@@ -89,10 +89,13 @@ private:
void changed();
void seekTo(qint64 position);
Player *m_player;
+ Player *m_local;
+ Player *m_youtube;
+ Player *m_jellyfin;
Cider *m_cider;
QPointer<QObject> m_sourceWindow;
bool m_remote = false, m_changePending = false;
QVariantMap m_lastProperties;
};
-PlayerAdaptor *registerMpris(Player *player, Cider *cider);
+PlayerAdaptor *registerMpris(Player *player, Cider *cider, Player *youtube = nullptr, Player *jellyfin = nullptr);
diff --git a/src/player.cpp b/src/player.cpp
index 004ae66..cdb7097 100644
--- a/src/player.cpp
+++ b/src/player.cpp
@@ -23,8 +23,8 @@
static QString text(const TagLib::String &s) { return QString::fromStdString(s.to8Bit(true)); }
-Player::Player(const QString &settingsPath, QObject *parent)
- : QObject(parent), m_settings(settingsPath, QSettings::IniFormat) {
+Player::Player(const QString &settingsPath, QObject *parent, bool external)
+ : QObject(parent), m_external(external), m_settings(settingsPath, QSettings::IniFormat) {
connect(this, &Player::queueChanged, this, [this] { m_tracksDirty = true; });
connect(this, &Player::trackChanged, this, &Player::discDetailsChanged);
connect(this, &Player::queueChanged, this, &Player::discDetailsChanged);
@@ -60,6 +60,7 @@ Player::Player(const QString &settingsPath, QObject *parent)
m_miniOnTop = m_settings.value("miniOnTop", false).toBool();
m_miniMode = m_settings.value("miniMode", false).toBool();
m_backgroundBlur = m_settings.value("backgroundBlur", false).toBool();
+ if (m_external) return;
const int size = m_settings.beginReadArray("tracks");
for (int i = 0; i < size; ++i) {
m_settings.setArrayIndex(i);
@@ -128,20 +129,20 @@ void Player::ensureMedia() {
}
if (status == QMediaPlayer::EndOfMedia) next(true);
});
- m_media->setSource(currentUrl());
+ m_media->setSource(mediaUrl());
}
-QString Player::title() const { return m_index >= 0 ? m_tracks[m_index].title : "Add music"; }
+QString Player::title() const { return m_index >= 0 ? m_tracks[m_index].title : m_external ? (m_externalName == "YouTube Music" ? "Search YouTube Music" : "Browse " + m_externalName) : "Add music"; }
QString Player::artist() const { return m_index >= 0 ? (m_tracks[m_index].artist.isEmpty() ? "Unknown artist" : m_tracks[m_index].artist) : QString(); }
QString Player::album() const { return m_index >= 0 ? m_tracks[m_index].album : QString(); }
-QString Player::format() const { return m_index >= 0 ? QFileInfo(m_tracks[m_index].path).suffix().toUpper() : "LOCAL MUSIC PLAYER"; }
-QUrl Player::currentUrl() const { return m_index >= 0 ? QUrl::fromLocalFile(m_tracks[m_index].path) : QUrl(); }
+QString Player::format() const { if (m_external) return m_externalName.toUpper(); return m_index >= 0 ? QFileInfo(m_tracks[m_index].path).suffix().toUpper() : "LOCAL MUSIC PLAYER"; }
+QUrl Player::currentUrl() const { return m_index >= 0 ? (m_external ? QUrl(m_tracks[m_index].path) : QUrl::fromLocalFile(m_tracks[m_index].path)) : QUrl(); }
QString Player::trackId() const {
return m_index < 0 ? "/org/mpris/MediaPlayer2/TrackList/NoTrack" : "/org/spun/track/t" +
QString::fromLatin1(QCryptographicHash::hash(currentUrl().toEncoded(), QCryptographicHash::Sha256).toHex().left(24));
}
QVariantList Player::queue() const {
QVariantList result;
- for (const auto &t : m_tracks) result.append(QVariantMap{{"path", t.path}, {"title", t.title}, {"artist", t.artist.isEmpty() ? "Unknown artist" : t.artist}, {"duration", t.duration}, {"artwork", queueArtworkUrl(t.path, t.cover)}});
+ for (const auto &t : m_tracks) result.append(QVariantMap{{"path", t.path}, {"title", t.title}, {"artist", t.artist.isEmpty() ? "Unknown artist" : t.artist}, {"duration", t.duration}, {"artwork", (m_external ? t.cover : queueArtworkUrl(t.path, t.cover))}});
return result;
}
bool Player::supported(const QString &path) {
@@ -274,12 +275,13 @@ void Player::addUrls(const QList<QUrl> &urls, bool autoplay) {
}
void Player::select(int index, bool autoplay) {
if (index < 0 || index >= count()) return;
+ if (m_external) { pause(); m_externalSource = QUrl(); emit externalCancelled(); }
if (m_playPending) pause();
m_restorePosition = -1;
dismissError();
m_index = index;
m_shuffleVisited.insert(m_tracks[index].path);
- if (m_media) m_media->setSource(currentUrl());
+ if (m_media) m_media->setSource(mediaUrl());
loadArt();
emit trackChanged(); emit durationChanged(); emit positionChanged();
if (autoplay) play();
@@ -294,7 +296,7 @@ void Player::loadArt() {
m_artFile.clear();
}
emit artworkChanged();
- if (!m_artJobActive && m_artLoading) startArtLoad();
+ if (!m_external && !m_artJobActive && m_artLoading) startArtLoad();
}
void Player::startArtLoad() {
m_artJobActive = true;
@@ -337,6 +339,10 @@ void Player::toggle() { playing() ? pause() : play(); }
void Player::play() {
if (m_index < 0) return;
dismissError();
+ if (m_external && m_externalSource.isEmpty()) {
+ if (!m_externalWantPlay) { m_externalWantPlay = true; emit playingChanged(); emit externalRequested(trackKey()); }
+ return;
+ }
if (m_media) { m_media->play(); return; }
if (!m_playPending) { m_playPending = true; emit playingChanged(); }
if (m_preparingAudio) return;
@@ -347,11 +353,14 @@ void Player::play() {
m_audioPreparation.setFuture(QtConcurrent::run([] { (void)QMediaDevices::defaultAudioOutput(); }));
}
void Player::pause() {
+ const bool externalPending = std::exchange(m_externalWantPlay, false);
+ if (externalPending) { emit externalCancelled(); emit playingChanged(); }
const bool pending = std::exchange(m_playPending, false);
if (m_media) m_media->pause();
if (pending) emit playingChanged();
}
void Player::stop() {
+ if (m_external) pause();
const bool pending = std::exchange(m_playPending, false);
m_restorePosition = -1;
if (m_media) m_media->stop();
@@ -414,7 +423,7 @@ void Player::previous(bool autoplay) {
}
void Player::seek(qint64 milliseconds) {
const auto pos = qBound<qint64>(0, milliseconds, duration());
- if (!m_media || m_media->mediaStatus() == QMediaPlayer::LoadingMedia) {
+ if (!m_media || (m_external && m_externalSource.isEmpty()) || m_media->mediaStatus() == QMediaPlayer::LoadingMedia) {
m_restorePosition = pos;
emit positionChanged();
if (!m_media) emit seeked(pos);
@@ -518,6 +527,7 @@ void Player::save() {
m_settings.setValue("miniMode", m_miniMode);
m_settings.setValue("miniOnTop", m_miniOnTop);
m_settings.setValue("ciderAutoStart", m_ciderAutoStart);
+ if (m_external) { m_settings.sync(); return; }
m_settings.setValue("currentPath", currentUrl().toLocalFile());
m_settings.setValue("position", position());
if (m_tracksDirty) {
@@ -547,7 +557,7 @@ QVariantMap Player::discDetails() const {
if (i==m_index) { indices.append(i); continue; }
if (current.album.isEmpty() || t.album!=current.album) continue;
const bool sameArtist=(!current.albumArtist.isEmpty() ? current.albumArtist==t.albumArtist : current.artist==t.artist);
- if (sameArtist || QFileInfo(t.path).absolutePath()==currentFolder) indices.append(i);
+ if (sameArtist || (!m_external && QFileInfo(t.path).absolutePath()==currentFolder)) indices.append(i);
}
std::stable_sort(indices.begin(), indices.end(), [&](int a,int b) {
const auto &left=m_tracks[a], &right=m_tracks[b];
@@ -584,3 +594,44 @@ void Player::refreshMixerRoute() {
m_media->setAudioBufferOutput(active?m_mixOutput.get():nullptr);
m_audio->setMuted(active);
}
+
+// External catalogs keep stable public identities separate from expiring media URLs.
+// A separate Player instance shares transport behavior without altering the local queue.
+void Player::setExternalTracks(const QList<Track> &tracks, int index, bool autoplay) {
+ if (!m_external) return;
+ clear(); m_tracks = tracks; emit queueChanged();
+ if (!m_tracks.isEmpty()) select(qBound(0, index, count()-1), autoplay);
+}
+void Player::appendExternalTracks(const QList<Track> &tracks) {
+ if (!m_external || tracks.isEmpty()) return;
+ const bool empty = m_tracks.isEmpty(); m_tracks.append(tracks); emit queueChanged();
+ if (empty) select(0, false);
+}
+void Player::resolveExternal(const QString &key, const QUrl &source) {
+ if (!m_external || key != trackKey() || !source.isLocalFile() || !QFileInfo::exists(source.toLocalFile())) return;
+ const bool autoplay = std::exchange(m_externalWantPlay, false);
+ const auto pendingPosition = m_restorePosition;
+ m_externalSource = source;
+ ensureMedia();
+ if (m_media->source() != source) m_media->setSource(source);
+ m_restorePosition = pendingPosition;
+ if (autoplay) m_media->play();
+ emit playingChanged();
+}
+void Player::setExternalArtwork(const QString &key, const QImage &image) {
+ if (!m_external || key != trackKey()) return;
+ m_art = image.scaled(1200,1200,Qt::KeepAspectRatio,Qt::SmoothTransformation);
+ m_artLoading = false;
+ if (!m_artFile.isEmpty()) QFile::remove(m_artFile);
+ m_artFile.clear();
+ if (!m_art.isNull()) {
+ m_artFile = QFileInfo(m_settings.fileName()).absolutePath()+"/youtube-current-art.png";
+ QSaveFile file(m_artFile);
+ if (!file.open(QIODevice::WriteOnly) || !m_art.save(&file,"PNG") || !file.commit()) m_artFile.clear();
+ }
+ emit artworkChanged();
+}
+void Player::failExternal(const QString &key, const QString &message) {
+ if (!m_external || key != trackKey()) return;
+ pause(); fail(message);
+}
diff --git a/src/player.h b/src/player.h
index f3f69da..ecfe937 100644
--- a/src/player.h
+++ b/src/player.h
@@ -66,7 +66,14 @@ class Player : public QObject {
Q_PROPERTY(QString importStatus READ importStatus NOTIFY importProgressChanged)
Q_PROPERTY(QString error READ error NOTIFY errorChanged)
public:
- explicit Player(const QString &settingsPath, QObject *parent = nullptr);
+ explicit Player(const QString &settingsPath, QObject *parent = nullptr, bool external = false);
+ void setExternalName(const QString &name) { m_externalName = name; }
+ bool external() const { return m_external; }
+ void setExternalTracks(const QList<Track> &tracks, int index = 0, bool autoplay = true);
+ void appendExternalTracks(const QList<Track> &tracks);
+ void resolveExternal(const QString &key, const QUrl &source);
+ void setExternalArtwork(const QString &key, const QImage &image);
+ void failExternal(const QString &key, const QString &message);
~Player() override;
QString trackKey() const { return currentUrl().toString(); }
bool threeD() const { return m_threeD; }
@@ -100,8 +107,8 @@ public:
QVariantList queue() const;
int count() const { return m_tracks.size(); }
int currentIndex() const { return m_index; }
- bool playing() const { return m_playPending || (m_media && m_media->playbackState() == QMediaPlayer::PlayingState); }
- QMediaPlayer::PlaybackState playbackState() const { return m_playPending ? QMediaPlayer::PlayingState : m_media ? m_media->playbackState() : QMediaPlayer::StoppedState; }
+ bool playing() const { return m_externalWantPlay || m_playPending || (m_media && m_media->playbackState() == QMediaPlayer::PlayingState); }
+ QMediaPlayer::PlaybackState playbackState() const { return (m_externalWantPlay || m_playPending) ? QMediaPlayer::PlayingState : m_media ? m_media->playbackState() : QMediaPlayer::StoppedState; }
qint64 position() const { return m_restorePosition >= 0 ? m_restorePosition : m_media ? m_media->position() : 0; }
qint64 duration() const { return m_media && m_media->duration() > 0 ? m_media->duration() : m_index >= 0 ? m_tracks[m_index].duration : 0; }
double volume() const { return m_volume; }
@@ -157,6 +164,8 @@ public:
static bool supported(const QString &path);
static Track readTrack(const QString &path);
signals:
+ void externalRequested(const QString &key);
+ void externalCancelled();
void vinylChanged();
void mediumChanged();
void discDetailsChanged();
@@ -177,6 +186,10 @@ signals:
void errorChanged();
void imported();
private:
+ QString m_externalName = "YouTube Music";
+ bool m_external = false, m_externalWantPlay = false;
+ QUrl m_externalSource;
+ QUrl mediaUrl() const { return m_external ? m_externalSource : currentUrl(); }
void ensureMedia();
void loadArt();
void startArtLoad();
diff --git a/src/tx6.cpp b/src/tx6.cpp
index ad32470..ff6d9be 100644
--- a/src/tx6.cpp
+++ b/src/tx6.cpp
@@ -12,11 +12,7 @@ Tx6::Tx6(Player *player,const QString &settings,bool outputEnabled):QObject(play
m_visible=m_settings.value("tx6Visible",false).toBool();
m_channels[0].name="TP-7 · USB 1/2";
for(int c=0;c<6;++c)for(int b=0;b<3;++b)coefficients(c,b);
- player->attachMixer(this);
- connect(player,&Player::mediumChanged,this,&Tx6::updateRoute);
- connect(player,&Player::trackChanged,this,&Tx6::flush);
- connect(player,&Player::seeked,this,&Tx6::flush);
- connect(player,&Player::playingChanged,this,[this]{if(!m_player->playing())flush();});
+ m_player=nullptr; setPlayer(player);
m_pump.setInterval(8);
connect(&m_pump,&QTimer::timeout,this,[this]{
if(!m_output || m_pending.isEmpty())return;
@@ -121,3 +117,14 @@ void Tx6::consume(const QAudioBuffer &buffer){
m_pending.append(pcm);
}
void Tx6::flush(){m_pump.stop();m_output=nullptr;if(m_sink)m_sink->stop();m_sink.reset();m_pending.clear();m_echo.fill(0);m_echoCursor=0;m_envelope=0;m_outputPeak[0]=m_outputPeak[1]=0;m_master=m_player->volume();for(auto &c:m_channels){c.peak=0;for(auto &f:c.filters){std::fill_n(f.z1,2,0);std::fill_n(f.z2,2,0);}}emit metersChanged();}
+
+void Tx6::setPlayer(Player *player) {
+ if (!player || player==m_player) return;
+ if (m_player) { flush(); disconnect(m_player,nullptr,this,nullptr); m_player->attachMixer(nullptr); }
+ m_player=player;player->attachMixer(this);
+ connect(player,&Player::mediumChanged,this,&Tx6::updateRoute);
+ connect(player,&Player::trackChanged,this,&Tx6::flush);
+ connect(player,&Player::seeked,this,&Tx6::flush);
+ connect(player,&Player::playingChanged,this,[this]{if(!m_player->playing())flush();});
+ updateRoute();
+}
diff --git a/src/tx6.h b/src/tx6.h
index 2cfe86c..790d1f9 100644
--- a/src/tx6.h
+++ b/src/tx6.h
@@ -51,6 +51,7 @@ public:
Q_INVOKABLE void load(int channel, const QUrl &file);
Q_INVOKABLE void unload(int channel);
Q_INVOKABLE void reset();
+ Q_INVOKABLE void setPlayer(Player *player);
void consume(const QAudioBuffer &buffer);
void flush();
static QAudioFormat format();
diff --git a/src/youtube.cpp b/src/youtube.cpp
new file mode 100644
index 0000000..ec895b8
--- /dev/null
+++ b/src/youtube.cpp
@@ -0,0 +1,816 @@
+#include "youtube.h"
+#include <QBuffer>
+#include <QClipboard>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QGuiApplication>
+#include <QImageReader>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QNetworkReply>
+#include <QRegularExpression>
+#include <QSaveFile>
+#include <QStandardPaths>
+#include <QUuid>
+#include <signal.h>
+#include <unistd.h>
+
+static QString keyFor(const QString &id) {
+ return "https://music.youtube.com/watch?v=" + id;
+}
+static bool videoId(const QString &id) {
+ static const QRegularExpression pattern("^[A-Za-z0-9_-]{11}$");
+ return pattern.match(id).hasMatch();
+}
+static bool artUrl(const QUrl &url) {
+ const auto host = url.host().toLower();
+ return url.scheme() == "https" &&
+ (host == "i.ytimg.com" || host.endsWith(".googleusercontent.com") ||
+ host.endsWith(".ggpht.com"));
+}
+QVariantMap Youtube::cleanItem(const QVariantMap &row) {
+ const auto id = row.value("id", row.value("videoId")).toString();
+ const auto kind = row.value("kind", "song").toString();
+ if (id.isEmpty() || id.size() > 256 ||
+ !QRegularExpression("^[A-Za-z0-9_-]+$").match(id).hasMatch())
+ return {};
+ if (!QStringList{"song", "video", "album", "artist", "playlist"}.contains(
+ kind))
+ return {};
+ if ((kind == "song" || kind == "video") && !videoId(id))
+ return {};
+ QVariantMap result{
+ {"id", id},
+ {"kind", kind},
+ {"title", row.value("title", "Untitled").toString().left(512)},
+ {"artist", row.value("artist").toString().left(512)},
+ {"album", row.value("album").toString().left(512)},
+ {"albumId", row.value("albumId").toString().left(256)},
+ {"artistId", row.value("artistId").toString().left(256)},
+ {"available", row.value("available", true).toBool()}};
+ if (artUrl(QUrl(row.value("art").toString())))
+ result["art"] = row.value("art").toString().left(2048);
+ qint64 seconds = row.value("seconds").toLongLong();
+ if (seconds <= 0) {
+ const auto parts = row.value("duration").toString().split(':');
+ for (const auto &part : parts)
+ seconds = seconds * 60 + part.toInt();
+ }
+ result["seconds"] = qBound(qint64(0), seconds, qint64(86400));
+ return result;
+}
+Youtube::Youtube(const QString &directory, QObject *parent)
+ : QObject(parent), m_player(directory + "/transport.ini", nullptr, true),
+ m_directory(directory), m_path(directory + "/library.json") {
+ QDir().mkpath(directory);
+ m_save.setSingleShot(true);
+ m_save.setInterval(250);
+ connect(&m_save, &QTimer::timeout, this, &Youtube::persist);
+ QFile file(m_path);
+ if (file.exists()) {
+ if (!file.open(QIODevice::ReadOnly) || file.size() > 8 * 1024 * 1024)
+ m_storageValid = false;
+ else {
+ QJsonParseError error;
+ auto doc = QJsonDocument::fromJson(file.readAll(), &error);
+ m_storageValid = error.error == QJsonParseError::NoError &&
+ doc.isObject() &&
+ doc.object().value("version").toInt() == 1;
+ if (m_storageValid) {
+ const auto root = doc.object();
+ const auto clean = [](const QJsonArray &array) {
+ QVariantList rows;
+ for (const auto &v : array) {
+ auto row = Youtube::cleanItem(v.toObject().toVariantMap());
+ if (!row.isEmpty() && rows.size() < 5000)
+ rows.append(row);
+ }
+ return rows;
+ };
+ m_favorites = clean(root.value("favorites").toArray());
+ m_history = clean(root.value("history").toArray());
+ for (const auto &v : root.value("playlists").toArray()) {
+ auto p = v.toObject();
+ const auto id = p.value("id").toString();
+ if (QUuid(id).isNull() || m_playlists.size() >= 100)
+ continue;
+ m_playlists.append(
+ QVariantMap{{"id", id},
+ {"name", p.value("name").toString().left(100)},
+ {"items", clean(p.value("items").toArray())}});
+ }
+ auto rows = clean(root.value("queue").toArray());
+ m_player.setExternalTracks(tracks(rows), root.value("index").toInt(),
+ false);
+ }
+ }
+ if (!m_storageValid)
+ m_error =
+ "Your YouTube library could not be read. It has been left untouched.";
+ }
+ connect(&m_player, &Player::externalRequested, this,
+ [this] { loadCurrent(); });
+ connect(&m_player, &Player::externalCancelled, this,
+ [this] { cancel("play"); });
+ connect(&m_player, &Player::trackChanged, this, [this] {
+ m_recordedKey.clear();
+ m_audio.reset();
+ cancel("prepare");
+ m_save.start();
+ loadArt();
+ refresh();
+ emit changed();
+ });
+ connect(&m_player, &Player::queueChanged, this, [this] {
+ m_save.start();
+ cancel("prepare");
+ m_prepared.reset();
+ m_preparedKey.clear();
+ });
+ connect(&m_player, &Player::positionChanged, this, [this] {
+ updateLyricIndex();
+ if (m_player.playing() && m_player.position() > 1000 &&
+ m_recordedKey != m_player.trackKey()) {
+ auto row = current();
+ if (row.isEmpty())
+ return;
+ m_recordedKey = m_player.trackKey();
+ for (int i = m_history.size() - 1; i >= 0; --i)
+ if (m_history[i].toMap().value("id") == row.value("id"))
+ m_history.removeAt(i);
+ m_history.prepend(row);
+ while (m_history.size() > 200)
+ m_history.removeLast();
+ m_save.start();
+ if (m_page == "history")
+ localPage();
+ prepareNext();
+ }
+ });
+}
+Youtube::~Youtube() {
+ m_save.stop();
+ persist();
+ for (const auto &key : m_jobs.keys())
+ cancel(key);
+ m_player.stop();
+}
+void Youtube::fail(const QString &message) {
+ m_error = message;
+ emit changed();
+ emit feedback(message, true);
+}
+void Youtube::cancel(const QString &channel) {
+ const auto p = m_jobs.take(channel);
+ if (!p)
+ return;
+ p->disconnect(this);
+ if (p->processId() > 0)
+ ::kill(-p->processId(), SIGKILL);
+ if (p->state() == QProcess::Starting)
+ connect(p, &QProcess::started, p, [p] {
+ if (p->processId() > 0)
+ ::kill(-p->processId(), SIGKILL);
+ p->kill();
+ });
+ p->kill();
+ connect(p, &QProcess::finished, p, &QObject::deleteLater);
+ if (p->state() == QProcess::NotRunning)
+ p->deleteLater();
+}
+void Youtube::request(const QString &channel, const QVariantMap &args,
+ Callback done, std::shared_ptr<QTemporaryDir> directory) {
+ cancel(channel);
+ auto *p = new QProcess(this);
+ m_jobs.insert(channel, p);
+ p->setChildProcessModifier([] { ::setsid(); });
+ if (directory)
+ connect(p, &QObject::destroyed, [directory] {});
+ auto *timer = new QTimer(p);
+ timer->setSingleShot(true);
+ timer->setInterval(channel == "play" || channel == "prepare" ? 90000 : 45000);
+ auto output = std::make_shared<QByteArray>();
+ connect(p, &QProcess::readyReadStandardOutput, this,
+ [this, p, channel, output] {
+ output->append(p->readAllStandardOutput());
+ if (output->size() > 8 * 1024 * 1024) {
+ p->kill();
+ }
+ });
+ connect(p, &QProcess::readyReadStandardError, this,
+ [p] { p->readAllStandardError(); });
+ connect(timer, &QTimer::timeout, this, [this, channel, done] {
+ cancel(channel);
+ done({{"ok", false},
+ {"error", "YouTube timed out. Check your connection and retry."}});
+ });
+ connect(p, &QProcess::errorOccurred, this,
+ [this, p, channel, done](QProcess::ProcessError error) {
+ if (error != QProcess::FailedToStart)
+ return;
+ m_jobs.remove(channel);
+ done({{"ok", false},
+ {"error", "YouTube support is not installed. Run "
+ "scripts/setup-youtube.sh in the Spun folder."}});
+ p->deleteLater();
+ });
+ connect(p, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this,
+ [this, p, channel, done, output](int, QProcess::ExitStatus) {
+ if (m_jobs.value(channel) != p)
+ return;
+ m_jobs.remove(channel);
+ output->append(p->readAllStandardOutput());
+ auto data =
+ QJsonDocument::fromJson(*output).object().toVariantMap();
+ if (data.isEmpty() || output->size() > 8 * 1024 * 1024)
+ data = {{"ok", false},
+ {"error", "YouTube returned an unreadable response. "
+ "Retry or update YouTube support."}};
+ p->deleteLater();
+ done(data);
+ });
+ QString python = qEnvironmentVariable("SPUN_YOUTUBE_PYTHON");
+ if (python.isEmpty())
+ python = QStringLiteral(SPUN_SOURCE_DIR) + "/runtime/youtube/bin/python";
+ QString helper = qEnvironmentVariable("SPUN_YOUTUBE_HELPER",
+ QStringLiteral(SPUN_SOURCE_DIR) +
+ "/helper/youtube.py");
+ p->start(python, {helper});
+ p->write(QJsonDocument::fromVariant(args).toJson(QJsonDocument::Compact));
+ p->closeWriteChannel();
+ timer->start();
+}
+void Youtube::setEnabled(bool enabled) {
+ if (m_enabled == enabled)
+ return;
+ m_enabled = enabled;
+ if (!enabled) {
+ m_player.pause();
+ cancel("prepare");
+ m_prepared.reset();
+ m_preparedKey.clear();
+ } else {
+ if (!m_checked)
+ check();
+ if (!m_player.trackKey().isEmpty() && m_player.artwork().isNull())
+ loadArt();
+ }
+ emit changed();
+}
+void Youtube::check() {
+ m_checked = true;
+ m_busy = true;
+ emit changed();
+ request("browse", {{"op", "check"}}, [this](const auto &r) {
+ m_busy = false;
+ m_ready = r.value("ok").toBool();
+ m_error = m_ready
+ ? QString()
+ : "YouTube support needs setup. Run scripts/setup-youtube.sh "
+ "in the Spun folder, then Retry.";
+ emit changed();
+ });
+}
+void Youtube::browse(const QVariantMap &requestData, const QString &title,
+ bool remember) {
+ if (remember)
+ m_back.append(QVariantMap{
+ {"items", m_items}, {"heading", m_heading}, {"page", m_page}});
+ while (m_back.size() > 20)
+ m_back.removeFirst();
+ m_page = "browse";
+ m_heading = title;
+ m_busy = true;
+ m_error.clear();
+ m_items.clear();
+ emit changed();
+ request("browse", requestData, [this](const auto &r) {
+ m_busy = false;
+ if (!r.value("ok").toBool()) {
+ fail(r.value("error").toString());
+ return;
+ }
+ m_ready = true;
+ auto rows = r.value("items").toList();
+ if (rows.isEmpty())
+ for (const auto &s : r.value("sections").toList())
+ rows.append(s.toMap().value("items").toList());
+ for (const auto &v : rows) {
+ auto row = cleanItem(v.toMap());
+ if (!row.isEmpty() && m_items.size() < 5000)
+ m_items.append(row);
+ }
+ if (!r.value("title").toString().isEmpty())
+ m_heading = r.value("title").toString();
+ emit changed();
+ });
+}
+void Youtube::search(const QString &query, const QString &filter) {
+ auto q = query.trimmed().left(2048);
+ if (q.isEmpty())
+ return;
+ if (q.startsWith("https://")) {
+ browse({{"op", "link"}, {"url", q}}, "YouTube link");
+ return;
+ }
+ if (!QStringList{"songs", "albums", "artists", "playlists", "videos"}
+ .contains(filter))
+ return;
+ browse({{"op", "search"}, {"query", q}, {"filter", filter}, {"limit", 50}},
+ q);
+}
+void Youtube::show(const QString &page) {
+ cancel("browse");
+ m_busy = false;
+ m_error.clear();
+ m_back.clear();
+ m_page = page;
+ if (page == "home") {
+ browse({{"op", "home"}}, "Discover", false);
+ return;
+ }
+ if (page == "search") {
+ m_heading = "Search YouTube Music";
+ m_items.clear();
+ emit changed();
+ return;
+ }
+ localPage();
+}
+void Youtube::localPage() {
+ if (m_page == "favorites") {
+ m_heading = "Favorites · on this device";
+ m_items = m_favorites;
+ } else if (m_page == "history") {
+ m_heading = "Recently played";
+ m_items = m_history;
+ } else if (m_page == "playlists") {
+ m_heading = "Your playlists";
+ m_items.clear();
+ for (const auto &v : m_playlists) {
+ auto p = v.toMap();
+ m_items.append(QVariantMap{
+ {"id", p["id"]},
+ {"kind", "local-playlist"},
+ {"title", p["name"]},
+ {"artist", QString::number(p["items"].toList().size()) + " songs"}});
+ }
+ } else if (m_page.startsWith("playlist:")) {
+ m_items.clear();
+ for (const auto &v : m_playlists) {
+ auto p = v.toMap();
+ if (p["id"].toString() == m_page.mid(9)) {
+ m_heading = p["name"].toString();
+ m_items = p["items"].toList();
+ }
+ }
+ }
+ emit changed();
+}
+void Youtube::open(const QVariantMap &row) {
+ auto kind = row.value("kind").toString();
+ if (kind == "local-playlist") {
+ m_back.append(QVariantMap{
+ {"items", m_items}, {"heading", m_heading}, {"page", m_page}});
+ m_page = "playlist:" + row.value("id").toString();
+ localPage();
+ return;
+ }
+ const auto item = cleanItem(row);
+ if (item.isEmpty())
+ return;
+ if (kind == "song" || kind == "video") {
+ playItem(item);
+ return;
+ }
+ if (QStringList{"album", "artist", "playlist"}.contains(kind))
+ browse({{"op", kind}, {"id", item["id"]}, {"limit", 5000}},
+ item["title"].toString());
+}
+void Youtube::back() {
+ if (m_back.isEmpty())
+ return;
+ cancel("browse");
+ m_busy = false;
+ m_error.clear();
+ const auto state = m_back.takeLast().toMap();
+ m_items = state["items"].toList();
+ m_page = state["page"].toString();
+ m_heading = state["heading"].toString();
+ if (m_page == "favorites" || m_page == "history" || m_page == "playlists" ||
+ m_page.startsWith("playlist:"))
+ localPage();
+ else
+ emit changed();
+}
+QList<Track> Youtube::tracks(const QVariantList &rows) {
+ QList<Track> result;
+ for (const auto &v : rows) {
+ auto r = cleanItem(v.toMap());
+ if (r.isEmpty() || !videoId(r["id"].toString()) ||
+ !r["available"].toBool() || result.size() >= 5000)
+ continue;
+ const auto key = keyFor(r["id"].toString());
+ m_catalog[key] = r;
+ Track t;
+ t.path = key;
+ t.title = r["title"].toString();
+ t.artist = r["artist"].toString();
+ t.album = r["album"].toString();
+ t.albumArtist = r["albumId"].toString();
+ t.cover = r["art"].toString();
+ t.duration = r["seconds"].toLongLong() * 1000;
+ t.number = result.size() + 1;
+ result.append(t);
+ }
+ return result;
+}
+QVariantList Youtube::queueItems() const {
+ QVariantList rows;
+ for (const auto &v : m_player.queue())
+ rows.append(m_catalog.value(v.toMap().value("path").toString()));
+ return rows;
+}
+QVariantMap Youtube::current() const {
+ return m_catalog.value(m_player.trackKey());
+}
+void Youtube::playItems(const QVariantList &rows, int index) {
+ auto list = tracks(rows);
+ if (list.isEmpty()) {
+ fail("No playable songs in this selection.");
+ return;
+ }
+ setEnabled(true);
+ m_player.setExternalTracks(list, index, true);
+}
+void Youtube::playItem(const QVariantMap &row) { playItems({row}); }
+void Youtube::enqueue(const QVariantMap &row) {
+ auto list = tracks({row});
+ if (list.isEmpty())
+ return;
+ if (m_player.count() >= 5000) {
+ fail("The queue is full.");
+ return;
+ }
+ m_player.appendExternalTracks(list);
+ emit feedback("Added to YouTube queue", false);
+}
+void Youtube::radio(const QVariantMap &row) {
+ const auto item = cleanItem(row);
+ if (!videoId(item.value("id").toString()))
+ return;
+ browse({{"op", "radio"}, {"id", item["id"]}}, "Song radio");
+}
+void Youtube::loadCurrent() {
+ if (!m_enabled) {
+ m_player.pause();
+ return;
+ }
+ const auto key = m_player.trackKey();
+ const auto row = current();
+ if (row.isEmpty())
+ return;
+ if (key == m_preparedKey && m_prepared) {
+ auto directory = std::move(m_prepared);
+ m_preparedKey.clear();
+ const auto files = QDir(directory->path()).entryList(QDir::Files);
+ if (!files.isEmpty()) {
+ m_player.resolveExternal(
+ key, QUrl::fromLocalFile(directory->path() + "/" + files.first()));
+ m_audio = directory;
+ return;
+ }
+ }
+ auto directory = std::make_shared<QTemporaryDir>(QDir::tempPath() +
+ "/spun-youtube-XXXXXX");
+ if (!directory->isValid()) {
+ m_player.failExternal(key, "Could not create the YouTube playback buffer.");
+ return;
+ }
+ request(
+ "play",
+ {{"op", "buffer"}, {"id", row["id"]}, {"directory", directory->path()}},
+ [this, key, directory](const auto &r) {
+ if (key != m_player.trackKey() || !m_enabled)
+ return;
+ const auto file =
+ QFileInfo(r.value("file").toString()).canonicalFilePath();
+ if (!r.value("ok").toBool() || file.isEmpty() ||
+ !file.startsWith(directory->path() + "/")) {
+ m_player.failExternal(
+ key, "Could not play this song anonymously. It may be "
+ "unavailable, restricted, or YouTube may need a resolver "
+ "update. Try another song or retry.");
+ return;
+ }
+ m_player.resolveExternal(key, QUrl::fromLocalFile(file));
+ m_audio = directory;
+ },
+ directory);
+}
+void Youtube::prepareNext() {
+ if (!m_enabled || m_player.shuffle() || m_player.repeatMode() == 2)
+ return;
+ const auto rows = queueItems();
+ const auto next = m_player.currentIndex() + 1;
+ if (next >= rows.size())
+ return;
+ const auto row = rows[next].toMap();
+ const auto key = keyFor(row.value("id").toString());
+ if (key == m_preparedKey)
+ return;
+ auto directory = std::make_shared<QTemporaryDir>(QDir::tempPath() +
+ "/spun-youtube-XXXXXX");
+ if (!directory->isValid())
+ return;
+ const auto currentKey = m_player.trackKey();
+ request(
+ "prepare",
+ {{"op", "buffer"}, {"id", row["id"]}, {"directory", directory->path()}},
+ [this, key, currentKey, directory](const auto &r) {
+ if (!m_enabled || m_player.trackKey() != currentKey ||
+ !r.value("ok").toBool())
+ return;
+ auto file = QFileInfo(r.value("file").toString()).canonicalFilePath();
+ if (!file.startsWith(directory->path() + "/"))
+ return;
+ m_preparedKey = key;
+ m_prepared = directory;
+ },
+ directory);
+}
+void Youtube::loadArt() {
+ if (m_artReply) {
+ m_artReply->abort();
+ m_artReply->deleteLater();
+ m_artReply = nullptr;
+ }
+ const auto key = m_player.trackKey();
+ const QUrl url(current().value("art").toString());
+ if (!artUrl(url)) {
+ m_player.setExternalArtwork(key, {});
+ return;
+ }
+ QNetworkRequest request(url);
+ request.setTransferTimeout(15000);
+ request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
+ QNetworkRequest::ManualRedirectPolicy);
+ auto *reply = m_network.get(request);
+ m_artReply = reply;
+ reply->setReadBufferSize(8 * 1024 * 1024 + 1);
+ auto data = std::make_shared<QByteArray>();
+ connect(reply, &QNetworkReply::readyRead, this, [reply, data] {
+ data->append(reply->readAll());
+ if (data->size() > 8 * 1024 * 1024)
+ reply->abort();
+ });
+ connect(reply, &QNetworkReply::finished, this, [this, key, reply, data] {
+ data->append(reply->readAll());
+ QImage image;
+ if (reply->error() == QNetworkReply::NoError &&
+ data->size() <= 8 * 1024 * 1024) {
+ QBuffer buffer(data.get());
+ buffer.open(QIODevice::ReadOnly);
+ QImageReader reader(&buffer);
+ if (reader.size().isValid() && reader.size().width() <= 8192 &&
+ reader.size().height() <= 8192) {
+ reader.setScaledSize(
+ reader.size().scaled(1200, 1200, Qt::KeepAspectRatio));
+ image = reader.read();
+ }
+ }
+ if (m_artReply == reply) {
+ m_artReply = nullptr;
+ m_player.setExternalArtwork(key, image);
+ }
+ reply->deleteLater();
+ });
+}
+bool Youtube::favorite(const QString &id) const {
+ for (const auto &v : m_favorites)
+ if (v.toMap().value("id").toString() == id)
+ return true;
+ return false;
+}
+void Youtube::toggleFavorite(const QVariantMap &item) {
+ auto row = cleanItem(item);
+ if (row.isEmpty())
+ return;
+ const auto id = row["id"].toString();
+ for (int i = 0; i < m_favorites.size(); ++i)
+ if (m_favorites[i].toMap().value("id").toString() == id) {
+ m_favorites.removeAt(i);
+ m_save.start();
+ if (m_page == "favorites")
+ localPage();
+ else
+ emit changed();
+ return;
+ }
+ if (m_favorites.size() >= 5000) {
+ fail("Your favorites list is full.");
+ return;
+ }
+ m_favorites.prepend(row);
+ m_save.start();
+ if (m_page == "favorites")
+ localPage();
+ else
+ emit changed();
+}
+QVariantList Youtube::playlists() const {
+ QVariantList rows;
+ for (const auto &v : m_playlists) {
+ auto p = v.toMap();
+ rows.append(QVariantMap{{"id", p["id"]}, {"name", p["name"]}});
+ }
+ return rows;
+}
+QString Youtube::createPlaylist(const QString &name) {
+ if (name.trimmed().isEmpty() || m_playlists.size() >= 100)
+ return {};
+ const auto id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ m_playlists.append(QVariantMap{{"id", id},
+ {"name", name.trimmed().left(100)},
+ {"items", QVariantList{}}});
+ m_save.start();
+ if (m_page == "playlists")
+ localPage();
+ else
+ emit changed();
+ return id;
+}
+void Youtube::renamePlaylist(const QString &id, const QString &name) {
+ if (name.trimmed().isEmpty())
+ return;
+ for (auto &v : m_playlists) {
+ auto p = v.toMap();
+ if (p["id"].toString() == id) {
+ p["name"] = name.trimmed().left(100);
+ v = p;
+ }
+ }
+ m_save.start();
+ localPage();
+}
+void Youtube::deletePlaylist(const QString &id) {
+ for (int i = 0; i < m_playlists.size(); ++i)
+ if (m_playlists[i].toMap().value("id").toString() == id) {
+ m_playlists.removeAt(i);
+ break;
+ }
+ m_save.start();
+ show("playlists");
+}
+void Youtube::addToPlaylist(const QString &id, const QVariantMap &item) {
+ auto row = cleanItem(item);
+ if (row.isEmpty() || !videoId(row["id"].toString()))
+ return;
+ for (auto &v : m_playlists) {
+ auto p = v.toMap();
+ if (p["id"].toString() != id)
+ continue;
+ auto rows = p["items"].toList();
+ if (rows.size() >= 5000) {
+ fail("This playlist is full.");
+ return;
+ }
+ rows.append(row);
+ p["items"] = rows;
+ v = p;
+ m_save.start();
+ localPage();
+ emit feedback("Added to " + p["name"].toString(), false);
+ return;
+ }
+}
+void Youtube::removeFromPlaylist(const QString &id, int index) {
+ for (auto &v : m_playlists) {
+ auto p = v.toMap();
+ if (p["id"].toString() != id)
+ continue;
+ auto rows = p["items"].toList();
+ if (index < 0 || index >= rows.size())
+ return;
+ rows.removeAt(index);
+ p["items"] = rows;
+ v = p;
+ }
+ m_save.start();
+ localPage();
+}
+void Youtube::clearHistory() {
+ m_history.clear();
+ m_save.start();
+ if (m_page == "history")
+ localPage();
+}
+void Youtube::copyLink(const QVariantMap &item) {
+ const auto r = cleanItem(item);
+ if (r.isEmpty())
+ return;
+ const auto kind = r["kind"].toString();
+ const auto link =
+ (kind == "song" || kind == "video")
+ ? keyFor(r["id"].toString())
+ : QStringLiteral("https://music.youtube.com/") +
+ (kind == "playlist" ? "playlist?list=" : "browse/") +
+ r["id"].toString();
+ QGuiApplication::clipboard()->setText(link);
+ emit feedback("Link copied", false);
+}
+void Youtube::openClipboardLink() {
+ search(QGuiApplication::clipboard()->text());
+}
+void Youtube::persist() {
+ QSet<QString> keys;
+ for (const auto &v : m_player.queue())
+ keys.insert(v.toMap().value("path").toString());
+ for (auto it = m_catalog.begin(); it != m_catalog.end();) {
+ if (!keys.contains(it.key()))
+ it = m_catalog.erase(it);
+ else
+ ++it;
+ }
+ if (!m_storageValid)
+ return;
+ QSaveFile file(m_path);
+ auto data = QJsonDocument::fromVariant(
+ QVariantMap{{"version", 1},
+ {"favorites", m_favorites},
+ {"history", m_history},
+ {"playlists", m_playlists},
+ {"queue", queueItems()},
+ {"index", m_player.currentIndex()}})
+ .toJson(QJsonDocument::Compact);
+ if (data.size() > 8 * 1024 * 1024) {
+ fail("The local YouTube library is too large to save.");
+ return;
+ }
+ if (!file.open(QIODevice::WriteOnly) || file.write(data) != data.size() ||
+ !file.commit())
+ fail("Could not save your local YouTube library.");
+}
+void Youtube::setActive(bool active) {
+ if (m_lyricsActive == active)
+ return;
+ m_lyricsActive = active;
+ if (active)
+ refresh();
+ else {
+ cancel("lyrics");
+ m_lyricsLoading = false;
+ }
+ emit changed();
+}
+void Youtube::refresh() {
+ cancel("lyrics");
+ m_lines.clear();
+ m_timed = false;
+ m_timeline.reset({});
+ m_lyricsMessage = "No lyrics available";
+ m_lyricsLoading = false;
+ updateLyricIndex();
+ if (!m_lyricsActive || current().isEmpty()) {
+ emit changed();
+ return;
+ }
+ m_lyricsLoading = true;
+ emit changed();
+ const auto key = m_player.trackKey();
+ request("lyrics", {{"op", "lyrics"}, {"id", current()["id"]}},
+ [this, key](const auto &r) {
+ if (key != m_player.trackKey() || !m_lyricsActive)
+ return;
+ m_lyricsLoading = false;
+ if (!r.value("ok").toBool())
+ m_lyricsMessage = "Could not load lyrics. Try again.";
+ else {
+ m_lines = r.value("lines").toList();
+ m_timed = !m_lines.isEmpty();
+ if (m_lines.isEmpty())
+ m_lines = Lyrics::parse(r.value("lyrics").toString());
+ }
+ m_timeline.reset(m_lines);
+ updateLyricIndex();
+ emit changed();
+ });
+}
+void Youtube::updateLyricIndex() {
+ const int index = m_timed ? m_timeline.indexAt(m_player.position()) : -1;
+ if (index != m_lyricIndex) {
+ m_lyricIndex = index;
+ emit currentIndexChanged();
+ }
+}
+bool Youtube::seekToLine(int index) {
+ if (!m_timed || index < 0 || index >= m_lines.size())
+ return false;
+ const auto pos = m_lines[index].toMap().value("start").toLongLong();
+ if (pos < 0 || pos >= m_player.duration())
+ return false;
+ m_player.seek(pos);
+ return true;
+}
diff --git a/src/youtube.h b/src/youtube.h
new file mode 100644
index 0000000..367ccf6
--- /dev/null
+++ b/src/youtube.h
@@ -0,0 +1,117 @@
+#pragma once
+#include "lyrics.h"
+#include "player.h"
+#include <QNetworkAccessManager>
+#include <QPointer>
+#include <QProcess>
+#include <QTemporaryDir>
+#include <QTimer>
+#include <functional>
+
+// Anonymous catalog plus a local-only library. No browser profile or account
+// state.
+class Youtube : public QObject {
+ Q_OBJECT
+ Q_PROPERTY(Player *transport READ transport CONSTANT)
+ Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY changed)
+ Q_PROPERTY(bool ready READ ready NOTIFY changed)
+ Q_PROPERTY(bool busy READ busy NOTIFY changed)
+ Q_PROPERTY(QString error READ error NOTIFY changed)
+ Q_PROPERTY(QString heading READ heading NOTIFY changed)
+ Q_PROPERTY(QString page READ page NOTIFY changed)
+ Q_PROPERTY(QVariantList items READ items NOTIFY changed)
+ Q_PROPERTY(QVariantList playlists READ playlists 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 Youtube(const QString &directory, QObject *parent = nullptr);
+ ~Youtube() override;
+ Player *transport() { return &m_player; }
+ bool enabled() const { return m_enabled; }
+ void setEnabled(bool enabled);
+ bool ready() const { return m_ready; }
+ bool busy() const { return m_busy; }
+ QString error() const { return m_error; }
+ QString heading() const { return m_heading; }
+ QString page() const { return m_page; }
+ QVariantList items() const { return m_items; }
+ QVariantList playlists() const;
+ QVariantMap current() const;
+ bool canBack() const { return !m_back.isEmpty(); }
+ Q_INVOKABLE void check();
+ Q_INVOKABLE void search(const QString &query,
+ const QString &filter = "songs");
+ Q_INVOKABLE void show(const QString &page);
+ Q_INVOKABLE void open(const QVariantMap &item);
+ Q_INVOKABLE void back();
+ Q_INVOKABLE void playItems(const QVariantList &items, int index = 0);
+ Q_INVOKABLE void playItem(const QVariantMap &item);
+ Q_INVOKABLE void enqueue(const QVariantMap &item);
+ Q_INVOKABLE void radio(const QVariantMap &item);
+ Q_INVOKABLE bool favorite(const QString &id) const;
+ Q_INVOKABLE void toggleFavorite(const QVariantMap &item);
+ Q_INVOKABLE QString createPlaylist(const QString &name);
+ Q_INVOKABLE void renamePlaylist(const QString &id, const QString &name);
+ Q_INVOKABLE void deletePlaylist(const QString &id);
+ Q_INVOKABLE void addToPlaylist(const QString &id, const QVariantMap &item);
+ Q_INVOKABLE void removeFromPlaylist(const QString &id, int index);
+ Q_INVOKABLE void clearHistory();
+ Q_INVOKABLE void copyLink(const QVariantMap &item);
+ Q_INVOKABLE void openClipboardLink();
+ bool active() const { return m_lyricsActive; }
+ void setActive(bool active);
+ QVariantList lines() const { return m_lines; }
+ bool loading() const { return m_lyricsLoading; }
+ QString message() const { return m_lyricsMessage; }
+ bool timed() const { return m_timed; }
+ int currentIndex() const { return m_lyricIndex; }
+ Q_INVOKABLE void refresh();
+ Q_INVOKABLE bool seekToLine(int index);
+ static QVariantMap cleanItem(const QVariantMap &item);
+signals:
+ void changed();
+ void currentIndexChanged();
+ void feedback(const QString &message, bool error);
+
+private:
+ using Callback = std::function<void(const QVariantMap &)>;
+ void request(const QString &channel, const QVariantMap &request,
+ Callback callback,
+ std::shared_ptr<QTemporaryDir> directory = {});
+ void cancel(const QString &channel);
+ void browse(const QVariantMap &request, const QString &title,
+ bool remember = true);
+ void loadCurrent();
+ void loadArt();
+ void prepareNext();
+ void updateLyricIndex();
+ void persist();
+ void localPage();
+ QList<Track> tracks(const QVariantList &items);
+ QVariantList queueItems() const;
+ void fail(const QString &message);
+ Player m_player;
+ QString m_directory, m_path, m_heading = "YouTube Music", m_page = "search",
+ m_error;
+ bool m_enabled = false, m_ready = false, m_busy = false, m_checked = false,
+ m_storageValid = true;
+ QVariantList m_items, m_favorites, m_history, m_playlists, m_back;
+ QHash<QString, QVariantMap> m_catalog;
+ QHash<QString, QPointer<QProcess>> m_jobs;
+ QNetworkAccessManager m_network;
+ QPointer<QNetworkReply> m_artReply;
+ std::shared_ptr<QTemporaryDir> m_audio, m_prepared;
+ QString m_preparedKey, m_recordedKey;
+ QTimer m_save;
+ bool m_lyricsActive = false, m_lyricsLoading = false, m_timed = false;
+ QVariantList m_lines;
+ QString m_lyricsMessage = "No lyrics available";
+ int m_lyricIndex = -1;
+ LyricTimeline m_timeline;
+};
diff --git a/src/youtubetest.cpp b/src/youtubetest.cpp
new file mode 100644
index 0000000..f09adc6
--- /dev/null
+++ b/src/youtubetest.cpp
@@ -0,0 +1,462 @@
+#include "youtubetest.h"
+#include "artwork.h"
+#include "mpris.h"
+#include "testcapture.h"
+#include "testinput.h"
+#include "tx6.h"
+#include "youtube.h"
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QQmlContext>
+#include <QSignalSpy>
+#include <QTest>
+#include <iostream>
+
+static bool until(const std::function<bool()> &predicate, int timeout = 4000) {
+ QElapsedTimer timer;
+ timer.start();
+ while (!predicate() && timer.elapsed() < timeout)
+ QTest::qWait(20);
+ return predicate();
+}
+static QQuickItem *find(QQuickItem *item, const QString &name) {
+ if (item->objectName() == name)
+ return item;
+ for (auto *child : item->childItems())
+ if (auto *result = find(child, name))
+ return result;
+ return nullptr;
+}
+int exerciseYoutube(Player &local, Youtube &yt, QQuickWindow *window,
+ const QString &temp, const QString &captures) {
+ int checks = 0, failures = 0;
+ auto check = [&](bool ok, const char *label) {
+ ++checks;
+ if (!ok)
+ ++failures;
+ std::cout << (ok ? "PASS " : "FAIL ") << label << std::endl;
+ return ok;
+ };
+ qputenv("SPUN_YOUTUBE_PYTHON", "/usr/bin/python3");
+ qputenv("SPUN_YOUTUBE_HELPER", SPUN_SOURCE_DIR "/tests/youtube_fixture.py");
+ qputenv("SPUN_YOUTUBE_FIXTURE_AUDIO", SPUN_DEMO_FILE);
+ auto *p = yt.transport();
+ p->setVolume(0);
+ local.setVolume(0);
+ 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(70);
+ };
+ auto capture = [&](const QString &name) {
+ if (captures.isEmpty())
+ return;
+ QTest::qWait(200);
+ QDir().mkpath(captures);
+ auto image = captureTestWindow(window);
+ check(!image.isNull() && image.save(captures + "/" + name + ".png"),
+ "render capture saved");
+ };
+ local.demo();
+ check(until([&] { return local.count() > 0 && !local.busy(); }),
+ "local fixture loaded");
+ local.pause();
+ const auto localKey = local.trackKey();
+ click("youtubeSourceButton");
+ check(window->property("useYoutube").toBool() && yt.enabled(),
+ "YouTube source selected by pointer");
+ check(until([&] { return !yt.busy() && yt.ready(); }),
+ "anonymous provider setup check");
+ auto *searchTab = find(window->contentItem(), "youtubeTab_search");
+ auto *favoritesTab = find(window->contentItem(), "youtubeTab_favorites");
+ if (check(searchTab && favoritesTab, "library tabs available")) {
+ searchTab->forceActiveFocus(Qt::TabFocusReason);
+ const auto previousPage = yt.page();
+ QTest::keyClick(window, Qt::Key_Right);
+ check(favoritesTab->hasActiveFocus() && yt.page() == previousPage,
+ "tab arrows move focus without changing the page");
+ QTest::keyClick(window, Qt::Key_Return);
+ check(yt.page() == "favorites" &&
+ favoritesTab->property("selected").toBool(),
+ "keyboard activation selects library tab");
+ QTest::keyClick(window, Qt::Key_Home);
+ check(searchTab->hasActiveFocus(), "Home focuses first library tab");
+ QTest::keyClick(window, Qt::Key_Return);
+ }
+ yt.search("slow");
+ auto *loading = find(window->contentItem(), "youtubeLoading");
+ check(loading && loading->isVisible(), "pending search shows progress");
+ const bool motion = local.motion();
+ local.setMotion(false);
+ QTest::qWait(30);
+ check(loading && !loading->property("animating").toBool(),
+ "reduced motion stops progress animation");
+ capture("youtube-loading-reduced-motion");
+ local.setMotion(motion);
+ yt.search("fixture");
+ check(until([&] { return !yt.busy() && yt.items().size() == 2; }),
+ "latest search replaces pending request");
+ QTest::qWait(2200);
+ check(yt.heading() == "fixture", "stale search does not replace results");
+ check(loading && !loading->isVisible() &&
+ !loading->property("animating").toBool(),
+ "completed search stops and hides progress");
+ capture("youtube-search");
+ QTest::keyClick(window, Qt::Key_F, Qt::ControlModifier);
+ check(find(window->contentItem(), "youtubeSearch")->hasActiveFocus(),
+ "Ctrl+F focuses YouTube search");
+ window->contentItem()->forceActiveFocus();
+ click("youtubeRowMenu_0");
+ check(window->property("menuOpen").toBool(),
+ "YouTube menu blocks underlying playback shortcuts");
+ capture("youtube-song-menu");
+ QTest::keyClick(window, Qt::Key_Escape);
+ QTest::qWait(60);
+
+ if (yt.items().size() != 2)
+ return 1;
+ auto first = yt.items()[0].toMap(), second = yt.items()[1].toMap();
+ for (const auto &filter : QStringList{"albums", "artists", "playlists"}) {
+ yt.search("fixture", filter);
+ check(until([&] { return !yt.busy() && !yt.items().isEmpty(); }),
+ qPrintable(filter + " search"));
+ yt.open(yt.items().first().toMap());
+ check(until([&] { return !yt.busy() && yt.items().size() == 2; }),
+ qPrintable(filter + " browsing"));
+ yt.back();
+ check(yt.items().size() == 1, "back restores previous collection");
+ }
+ yt.show("home");
+ check(until([&] { return !yt.busy() && yt.items().size() == 2; }),
+ "anonymous discovery");
+ yt.radio(first);
+ check(until([&] { return !yt.busy() && yt.items().size() == 2; }),
+ "song radio queue");
+ yt.search("https://music.youtube.com/watch?v=fixture0001");
+ check(until([&] { return !yt.busy() && yt.items().size() == 2; }),
+ "YouTube link lookup");
+ yt.toggleFavorite(first);
+ check(yt.favorite(first["id"].toString()), "local favorite saved");
+ yt.show("favorites");
+ check(yt.items().size() == 1, "favorites page");
+ yt.toggleFavorite(first);
+ check(!yt.favorite(first["id"].toString()) && yt.items().isEmpty(),
+ "favorite removed");
+ yt.toggleFavorite(first);
+ click("youtubePageActions");
+ click("youtubeNewPlaylist");
+ check(window->property("menuOpen").toBool(), "playlist dialog is modal");
+ check(until([&] {
+ auto *field = find(window->contentItem(), "youtubePlaylistName");
+ return field && field->hasActiveFocus();
+ }),
+ "playlist dialog focuses its field after entering");
+ capture("youtube-playlist-dialog");
+ for (char letter : QByteArray("UI playlist"))
+ QTest::keyClick(window, letter);
+ click("youtubeNameDialogAccept");
+ check(yt.playlists().size() == 1 &&
+ yt.playlists().first().toMap().value("name").toString() ==
+ "UI playlist",
+ "playlist saved through dialog keyboard input and button");
+ if (!yt.playlists().isEmpty())
+ yt.deletePlaylist(yt.playlists().first().toMap().value("id").toString());
+ QTest::keyClick(window, Qt::Key_Escape);
+ QTest::qWait(100);
+ auto playlist = yt.createPlaylist("A local playlist");
+ check(!playlist.isEmpty(), "local playlist created");
+ yt.addToPlaylist(playlist, first);
+ yt.addToPlaylist(playlist, second);
+ yt.show("playlists");
+ check(yt.items().size() == 1, "playlist listing");
+ yt.open(yt.items().first().toMap());
+ check(yt.items().size() == 2, "playlist songs");
+ yt.renamePlaylist(playlist, "Renamed playlist");
+ check(yt.heading() == "Renamed playlist", "playlist rename");
+ yt.removeFromPlaylist(playlist, 0);
+ check(yt.items().size() == 1, "playlist song removal");
+ capture("youtube-playlist");
+ yt.playItems({first, second});
+ check(until([&] { return p->position() > 1200; }),
+ "buffered audio plays with native transport");
+ check(p->title() == first["title"].toString() && p->count() == 2,
+ "public metadata and queue survive resolution");
+ p->pause();
+ click("playButton");
+ check(until([&] { return p->playing(); }),
+ "main play button controls YouTube");
+ click("playButton");
+ check(!p->playing(), "main pause button controls YouTube");
+ local.setMiniMode(true);
+ QTest::qWait(180);
+ click("miniPlay");
+ check(until([&] { return p->playing(); }), "Mini play controls YouTube");
+ click("miniPlay");
+ local.setMiniMode(false);
+ QTest::qWait(100);
+ QTest::keyClick(window, Qt::Key_Space);
+ check(until([&] { return p->playing(); }), "Space controls YouTube");
+ p->pause();
+ const auto position = p->position();
+ QTest::qWait(160);
+ check(!p->playing() && qAbs(p->position() - position) < 100,
+ "pause stops playback clock");
+ p->seek(9000);
+ check(until([&] { return qAbs(p->position() - 9000) < 300; }),
+ "seek uses same transport timeline");
+ yt.setActive(true);
+ check(until([&] { return !yt.loading() && yt.lines().size() == 2; }),
+ "timed lyrics load");
+ check(yt.seekToLine(1) &&
+ until([&] { return qAbs(p->position() - 5000) < 300; }),
+ "lyric seek");
+ p->next(false, false);
+ check(p->title() == second["title"].toString() && !p->playing(),
+ "next while paused preserves pause");
+ p->play();
+ check(until([&] { return p->position() > 100; }),
+ "next selected song resolves");
+ p->pause();
+ p->seek(0);
+ p->previous(false);
+ check(p->title() == first["title"].toString(), "previous selects first song");
+ p->move(0, 1);
+ check(p->currentIndex() == 1 && p->title() == first["title"].toString(),
+ "queue reorder retains current identity");
+ p->remove(0);
+ check(p->count() == 1 && p->currentIndex() == 0,
+ "queue removal keeps current song");
+ yt.enqueue(second);
+ check(p->count() == 2, "enqueue adds song");
+ p->setShuffle(true);
+ p->next(false, false);
+ check(p->currentIndex() == 1, "shuffle chooses another song");
+ p->setShuffle(false);
+ p->setRepeatMode(2);
+ p->next(true);
+ check(p->currentIndex() == 1, "repeat one retains song");
+ p->setRepeatMode(1);
+ p->next(true, false);
+ check(p->currentIndex() == 0, "repeat queue wraps");
+ p->setRepeatMode(0);
+ p->select(1, false);
+ p->next(true);
+ check(!p->playing(), "queue ends without repeat");
+ auto slow = first;
+ slow["id"] = "fixture0003";
+ yt.playItem(slow);
+ p->seek(10000);
+ p->pause();
+ QTest::qWait(2400);
+ check(!p->playing(), "pause cancels pending playback");
+ yt.playItem(slow);
+ yt.playItem(first);
+ check(until([&] { return p->position() > 100; }),
+ "new song replaces slow resolution");
+ QTest::qWait(2100);
+ check(p->trackKey().endsWith("fixture0001"),
+ "stale resolver cannot change song");
+ yt.playItem(slow);
+ window->setProperty("useYoutube", false);
+ QTest::qWait(2300);
+ check(!p->playing() && local.trackKey() == localKey,
+ "switch to Local cancels YouTube without changing local queue");
+ window->setProperty("useYoutube", true);
+ auto bad = first;
+ bad["id"] = "fixture0004";
+ yt.playItem(bad);
+ check(until([&] { return !p->error().isEmpty(); }),
+ "unavailable song displays error");
+ check(!p->playing(), "failed playback clears pending state");
+ yt.playItems({first, second});
+ check(until([&] { return p->position() > 100; }),
+ "playback recovers after error");
+ p->pause();
+ p->setVolume(.4);
+ check(qAbs(p->volume() - .4) < .001, "volume control");
+ p->setVolume(0);
+ PlayerAdaptor media(&local, nullptr, p);
+ media.setSourceWindow(window);
+ check(media.metadata()["xesam:title"].toString() == p->title(),
+ "media keys expose active YouTube metadata");
+ media.SetPosition(QDBusObjectPath(media.trackId()), 7000000);
+ check(until([&] { return qAbs(p->position() - 7000) < 300; }),
+ "MPRIS seek routed to YouTube");
+ media.PlayPause();
+ check(until([&] { return p->playing(); }),
+ "MPRIS playback routed to YouTube");
+ media.Pause();
+ auto *mixer = qmlContext(window)->contextProperty("tx6").value<Tx6 *>();
+ local.setMedium("tp7");
+ mixer->setVisible(true);
+ check(mixer->active(), "TX-6 routes YouTube through native mixer");
+ mixer->setEq(0, 1, 3);
+ mixer->setDelay(true);
+ mixer->setCompressor(true);
+ check(mixer->delay() && mixer->compressor(),
+ "TX-6 effects accept YouTube route");
+ mixer->reset();
+ yt.show("history");
+ check(!yt.items().isEmpty(), "listening history recorded locally");
+ yt.clearHistory();
+ check(yt.items().isEmpty(), "history cleared");
+ yt.search("error");
+ check(until([&] { return !yt.busy() && !yt.error().isEmpty(); }),
+ "network failure visible");
+ capture("youtube-error");
+ yt.search("empty");
+ check(until([&] { return !yt.busy() && yt.error().isEmpty(); }) &&
+ yt.items().isEmpty(),
+ "empty search clears old results");
+ yt.search("fixture");
+ check(until([&] { return !yt.busy() && yt.items().size() == 2; }),
+ "retry recovers search");
+ window->setProperty("libraryOpen", true);
+ p->setExternalArtwork(
+ p->trackKey(),
+ readTrackArtwork(QStringLiteral(SPUN_DEMO_FILE), {}, QSize(800, 800)));
+ for (const auto &medium : QStringList{"cd", "vinyl", "cassette", "tp7"}) {
+ local.setMedium(medium);
+ for (bool threeD : {false, true}) {
+ if (threeD && !qmlContext(window)->contextProperty("supports3D").toBool())
+ continue;
+ local.setThreeD(threeD);
+ QTest::qWait(500);
+ check(window->property("deckPlayer").value<QObject *>() == p,
+ "physical deck uses YouTube transport");
+ if (threeD)
+ check(until([&] { return window->property("threeDActive").toBool(); }),
+ "3D scene ready");
+ p->seek(4000);
+ p->play();
+ check(until([&] { return p->position() > 4100; }),
+ "deck playback clock advances");
+ p->pause();
+ capture(medium + (threeD ? "-3d" : "-2d"));
+ }
+ }
+ local.setMedium("vinyl");
+ local.setVinylAlbumMode(true);
+ p->setVinylAlbumMode(true);
+ check(p->playAlbumPosition(QString("https://music.youtube.com/watch?v=") +
+ second["id"].toString(),
+ 6000),
+ "vinyl album needle accepts YouTube track");
+ check(until([&] { return p->position() >= 6000; }),
+ "vinyl album seek applies after resolution");
+ p->pause();
+ QTest::qWait(350);
+ {
+ Youtube restored(QFileInfo(temp + "/player.ini").absolutePath() +
+ "/youtube");
+ check(restored.favorite(first["id"].toString()) &&
+ restored.playlists().size() == 1,
+ "favorites and playlists persist without account");
+ check(restored.transport()->count() == 2,
+ "queue references restored without auto playback");
+ }
+ yt.deletePlaylist(playlist);
+ check(yt.playlists().isEmpty(), "playlist deleted");
+ p->clear();
+ check(p->count() == 0 && !p->playing(), "queue clears safely");
+ const auto corrupt = temp + "/corrupt-youtube";
+ QDir().mkpath(corrupt);
+ {
+ QFile f(corrupt + "/library.json");
+ check(f.open(QIODevice::WriteOnly), "corrupt-library fixture writable");
+ f.write("broken fixture");
+ }
+ {
+ Youtube corruptLibrary(corrupt);
+ corruptLibrary.createPlaylist("Do not overwrite");
+ }
+ QFile original(corrupt + "/library.json");
+ check(original.open(QIODevice::ReadOnly), "corrupt-library fixture readable");
+ check(original.readAll() == "broken fixture",
+ "corrupt library is not overwritten");
+ check(Youtube::cleanItem({{"id", "../bad"}, {"kind", "song"}}).isEmpty(),
+ "invalid provider identity rejected");
+ std::cout << "YouTube checks " << checks << ", failures " << failures
+ << std::endl;
+ return failures ? 1 : 0;
+}
+
+int exerciseYoutubeLive(Player &local, Youtube &yt, QQuickWindow *window,
+ const QString &captures) {
+ int checks = 0, failures = 0;
+ auto check = [&](bool ok, const char *label) {
+ ++checks;
+ if (!ok)
+ ++failures;
+ std::cout << (ok ? "PASS " : "FAIL ") << label << std::endl;
+ return ok;
+ };
+ auto *p = yt.transport();
+ p->setVolume(0);
+ window->setProperty("useYoutube", true);
+ window->setProperty("libraryOpen", true);
+ if (!check(until([&] { return !yt.busy() && yt.ready(); }, 45000),
+ "live provider ready without account"))
+ return 1;
+ yt.search("Kevin MacLeod Carefree", "songs");
+ if (!check(until([&] { return !yt.busy() && !yt.items().isEmpty(); }, 45000),
+ "live catalog search"))
+ return 1;
+ auto first = yt.items().first().toMap();
+ yt.playItem(first);
+ if (!check(
+ until([&] { return p->position() > 1000 || !p->error().isEmpty(); },
+ 90000) &&
+ p->error().isEmpty(),
+ "live anonymous audio playback"))
+ return 1;
+ check(until([&] { return !p->artwork().isNull(); }, 16000),
+ "live artwork is decoded for physical players");
+ p->pause();
+ p->seek(30000);
+ check(until([&] { return qAbs(p->position() - 30000) < 500; }),
+ "live buffered audio seeking");
+ p->play();
+ check(until([&] { return p->position() > 30500; }), "live resume after seek");
+ p->pause();
+ auto capture = [&](const QString &name) {
+ if (captures.isEmpty())
+ return;
+ QDir().mkpath(captures);
+ QTest::qWait(350);
+ auto frame = captureTestWindow(window);
+ check(!frame.isNull() && frame.save(captures + "/" + name + ".png"),
+ "live rendered capture saved");
+ };
+ capture("live-search");
+ for (const auto &medium : QStringList{"cd", "vinyl", "cassette", "tp7"}) {
+ local.setMedium(medium);
+ for (bool threeD : {false, true}) {
+ if (threeD && !qmlContext(window)->contextProperty("supports3D").toBool())
+ continue;
+ local.setThreeD(threeD);
+ QTest::qWait(600);
+ if (threeD)
+ check(until([&] { return window->property("threeDActive").toBool(); }),
+ "live 3D player ready");
+ capture(medium + (threeD ? "-3d" : "-2d"));
+ }
+ }
+ auto *mixer = qmlContext(window)->contextProperty("tx6").value<Tx6 *>();
+ mixer->setVisible(true);
+ capture("tp7-tx6");
+ yt.setActive(true);
+ check(until([&] { return !yt.loading(); }, 45000),
+ "live lyrics or empty instrumental lyrics handled");
+ std::cout << "Live YouTube checks " << checks << ", failures " << failures
+ << std::endl;
+ return failures ? 1 : 0;
+}
diff --git a/src/youtubetest.h b/src/youtubetest.h
new file mode 100644
index 0000000..bce819d
--- /dev/null
+++ b/src/youtubetest.h
@@ -0,0 +1,10 @@
+#pragma once
+#include <QString>
+class Player;
+class Youtube;
+class QQuickWindow;
+int exerciseYoutube(Player &local, Youtube &youtube, QQuickWindow *window,
+ const QString &temp, const QString &captures);
+
+int exerciseYoutubeLive(Player &local, Youtube &youtube, QQuickWindow *window,
+ const QString &captures);
diff --git a/tests/test_youtube.py b/tests/test_youtube.py
new file mode 100644
index 0000000..ad7862f
--- /dev/null
+++ b/tests/test_youtube.py
@@ -0,0 +1,24 @@
+import importlib.util
+from pathlib import Path
+import unittest
+from unittest.mock import patch,MagicMock
+spec=importlib.util.spec_from_file_location('youtube',Path(__file__).parents[1]/'helper/youtube.py')
+youtube=importlib.util.module_from_spec(spec);spec.loader.exec_module(youtube)
+class CatalogTest(unittest.TestCase):
+ def test_album_metadata(self):
+ r=youtube.normalize({'videoId':'abcdefghijk','title':'Track','duration_seconds':30},'song',{'type':'album','title':'Album','browseId':'MPRE123','artists':[{'name':'Artist','id':'UC123'}]})
+ self.assertEqual(r['albumId'],'MPRE123');self.assertEqual(r['artist'],'Artist');self.assertEqual(r['seconds'],30)
+ def test_lyrics(self):
+ self.assertEqual(youtube.normalize_lyrics({'lyrics':'Plain lyrics'})['lyrics'],'Plain lyrics')
+ self.assertEqual(youtube.normalize_lyrics({'lyrics':[{'text':'Timed','start_time':1200,'end_time':2300}]})['lines'][0]['start'],1200)
+ def test_bad_video(self):
+ with patch.dict('sys.modules',{'yt_dlp':MagicMock()}):
+ with self.assertRaises(ValueError):youtube.run({'op':'buffer','id':'../../file','directory':'/tmp'})
+ def test_foreign_link(self):
+ with patch.dict('sys.modules',{'ytmusicapi':MagicMock()}):
+ with self.assertRaises(ValueError):youtube.run({'op':'link','url':'https://example.com/watch?v=abcdefghijk'})
+ def test_anonymous(self):
+ api=MagicMock();api.search.return_value=[];factory=MagicMock(return_value=api)
+ with patch.dict('sys.modules',{'ytmusicapi':MagicMock(YTMusic=factory)}):youtube.run({'op':'search','query':'music','filter':'songs','limit':50})
+ factory.assert_called_once_with(requests_session=True)
+if __name__=='__main__':unittest.main()
diff --git a/tests/youtube_fixture.py b/tests/youtube_fixture.py
new file mode 100644
index 0000000..94d5cf6
--- /dev/null
+++ b/tests/youtube_fixture.py
@@ -0,0 +1,31 @@
+"""Deterministic provider process for cancellation, transport and UI regression tests."""
+import json
+import os
+from pathlib import Path
+import shutil
+import sys
+import time
+
+req=json.load(sys.stdin)
+op=req['op']
+def song(i=1):
+ return dict(id=f'fixture00{i:02}',kind='song',title=f'First Light {i}',artist='Spun Sound Lab',album='The first mixtape',albumId='MPREfixture',seconds=32)
+result={'ok':True}
+if op=='check':result['ready']=True
+elif op=='buffer':
+ if req['id']=='fixture0003':time.sleep(2)
+ if req['id']=='fixture0004':result={'ok':False,'error':'Unavailable'}
+ else:
+ path=Path(req['directory'])/'song.flac';shutil.copyfile(os.environ['SPUN_YOUTUBE_FIXTURE_AUDIO'],path);result['file']=str(path)
+elif op=='lyrics':result['lines']=[{'start':0,'end':5000,'text':'First light through the window'},{'start':5000,'end':30000,'text':'A quiet room, a new day'}]
+elif op=='search':
+ if req['query']=='slow':time.sleep(2)
+ if req['query']=='error':result={'ok':False,'error':'Test network failure'}
+ elif req['query']=='empty':result['items']=[]
+ elif req.get('filter')=='albums':result['items']=[dict(id='MPREfixture',kind='album',title='The first mixtape',artist='Spun Sound Lab')]
+ elif req.get('filter')=='artists':result['items']=[dict(id='UCfixture',kind='artist',title='Spun Sound Lab')]
+ elif req.get('filter')=='playlists':result['items']=[dict(id='PLfixture',kind='playlist',title='Fixture playlist')]
+ else:result['items']=[song(1),song(2)]
+elif op in ('album','playlist','radio','link'):result.update(items=[song(1),song(2)],title='The first mixtape')
+elif op in ('artist','home'):result['sections']=[dict(title='Songs',items=[song(1),song(2)])]
+print(json.dumps(result))