From 7e294724ea57e3bd328ca8cf4e482800746c8e90 Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Sun, 25 Oct 2026 02:59:03 +0700 Subject: [PATCH] feat(link): download original Subsonic files and decode song paths Add SubsonicClient.download, which saves a song's original file through the pinned connection with progress and cancellation, and the subsonicSongPath/subsonicSongIdFromPath helpers that map scanned network rows to catalog ids. --- lib/services/network_storage_subsonic.dart | 81 +++++++++++++++++++++- test/link_subsonic_download_test.dart | 80 +++++++++++++++++++++ test/support/subsonic_fixture.dart | 9 ++- 3 files changed, 166 insertions(+), 4 deletions(-) create mode 100644 test/link_subsonic_download_test.dart diff --git a/lib/services/network_storage_subsonic.dart b/lib/services/network_storage_subsonic.dart index 23009b6c1..9daf7275c 100644 --- a/lib/services/network_storage_subsonic.dart +++ b/lib/services/network_storage_subsonic.dart @@ -20,6 +20,26 @@ String _decodeSubsonicId(String encoded) { return utf8.decode(base64Url.decode(base64Url.normalize(encoded))); } +/// The library path of the Subsonic song [id]: `subsonic/song/.`. +String subsonicSongPath(String id, String format) => + 'subsonic/song/${_subsonicId(id)}.$format'; + +/// The Subsonic song id behind a [subsonicSongPath], or null for any other +/// path. +String? subsonicSongIdFromPath(String path) { + final segments = path.split('/'); + if (segments.length != 3 || + segments.first != 'subsonic' || + segments[1] != 'song') { + return null; + } + try { + return _decodeSubsonicId(segments.last.split('.').first); + } on FormatException { + return null; + } +} + Uri _subsonicTarget( NetworkConnection connection, String method, @@ -129,7 +149,7 @@ class SubsonicSong { }; } - String get path => 'subsonic/song/${_subsonicId(id)}.$format'; + String get path => subsonicSongPath(id, format); String? get coverPath => coverId.isEmpty ? null : 'subsonic/cover/${_subsonicId(coverId)}.image'; NetworkEntry get entry => NetworkEntry( @@ -450,6 +470,65 @@ class SubsonicClient { } } + /// Saves the original file of the song [id] (the `download` method) to + /// [output]. [progress] receives the bytes written and the size the server + /// announced; [checkpoint] may throw between chunks to cancel. + Future download( + String id, + File output, { + void Function()? checkpoint, + void Function(int received, int? total)? progress, + }) => _protectTransport( + () => _download(id, output, checkpoint: checkpoint, progress: progress), + ); + + Future _download( + String id, + File output, { + void Function()? checkpoint, + void Function(int received, int? total)? progress, + }) async { + if (_closed) throw StateError('Subsonic request cancelled'); + final response = await _storage._request( + _http, + connection, + 'GET', + _subsonicTarget(connection, 'download', {'id': id}), + ); + if (response.statusCode != 200 || + const { + 'application/json', + 'application/xml', + 'text/xml', + }.contains(response.headers.contentType?.mimeType)) { + await _storage._discardResponse(response); + throw HttpException( + response.statusCode == 200 + ? 'Subsonic media unavailable' + : 'Server returned ${response.statusCode}', + ); + } + final total = response.contentLength >= 0 ? response.contentLength : null; + final writer = output.openWrite(); + var received = 0; + try { + await for (final chunk in response.timeout( + NetworkStorageService.timeout, + )) { + if (_closed) throw StateError('Subsonic request cancelled'); + checkpoint?.call(); + writer.add(chunk); + received += chunk.length; + progress?.call(received, total); + } + if (total != null && received != total) { + throw const HttpException('Subsonic download ended early'); + } + } finally { + await writer.close(); + } + } + Future saveCover(SubsonicSong song, File output) => _protectTransport(() => _saveCover(song, output)); diff --git a/test/link_subsonic_download_test.dart b/test/link_subsonic_download_test.dart new file mode 100644 index 000000000..41cac5bd3 --- /dev/null +++ b/test/link_subsonic_download_test.dart @@ -0,0 +1,80 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/services/network_storage_service.dart'; +import 'package:path/path.dart' as p; + +import 'support/subsonic_fixture.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + HttpOverrides.global = null; + late SubsonicFixture server; + late NetworkStorageService storage; + late Directory directory; + + setUp(() async { + server = await SubsonicFixture.start(); + directory = await Directory.systemTemp.createTemp('subsonic-download-'); + String? saved; + storage = NetworkStorageService( + read: () async => saved, + write: (value) async => saved = value, + ensureAccess: (_) async {}, + ); + await storage.save(server.connection()); + }); + + tearDown(() async { + await storage.dispose(); + await server.close(); + await directory.delete(recursive: true); + }); + + Future open() async { + final client = storage.openSubsonic(await storage.connection('fixture')); + addTearDown(client.close); + return client; + } + + test('download saves the original file and reports progress', () async { + server.audio = List.generate(4096, (index) => index % 256); + final client = await open(); + final output = File(p.join(directory.path, 'song.flac')); + final progress = <(int, int?)>[]; + await client.download( + 'song / 1', + output, + progress: (received, total) => progress.add((received, total)), + ); + expect(await output.readAsBytes(), server.audio); + expect(server.requests.last.pathSegments.last, startsWith('download')); + expect(server.requests.last.queryParameters['id'], 'song / 1'); + expect(progress.last, (4096, 4096)); + }); + + test('download refuses a Subsonic error reply', () async { + server.mediaError = true; + final client = await open(); + final output = File(p.join(directory.path, 'song.flac')); + await expectLater( + client.download('song', output), + throwsA(isA()), + ); + expect(output.existsSync(), isFalse); + }); + + test('a throwing checkpoint stops the download', () async { + server.audio = List.filled(1024, 7); + final client = await open(); + final output = File(p.join(directory.path, 'song.flac')); + await expectLater( + client.download( + 'song', + output, + checkpoint: () => throw const FileSystemException('stopped'), + ), + throwsA(isA()), + ); + }); +} diff --git a/test/support/subsonic_fixture.dart b/test/support/subsonic_fixture.dart index 18d86a853..4dd9bdf4d 100644 --- a/test/support/subsonic_fixture.dart +++ b/test/support/subsonic_fixture.dart @@ -113,14 +113,17 @@ class SubsonicFixture { }, }), ); - } else if ((method == 'stream' || method == 'getCoverArt') && + } else if ((method == 'stream' || + method == 'download' || + method == 'getCoverArt') && !mediaError) { + final isAudio = method != 'getCoverArt'; response.headers.contentType = ContentType.parse( - method == 'stream' ? song['contentType'] as String : 'image/png', + isAudio ? song['contentType'] as String : 'image/png', ); final range = request.headers.value('range'); response.statusCode = range == null ? 200 : 206; - final media = method == 'stream' ? audio ?? [0, 1, 2, 3] : [0, 1, 2, 3]; + final media = isAudio ? audio ?? [0, 1, 2, 3] : [0, 1, 2, 3]; final part = networkByteRange(range, media.length); if (range != null) { response.headers.set(