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.
This commit is contained in:
zarzet committed 2026-10-25 02:59:03 +07:00
1 parent 47f61bf46a
commit 7e294724ea
3 files changed
+166 -4

No files matched your search

+80 -1
View File
@@ -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/<id>.<format>`.
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<void> download(
String id,
File output, {
void Function()? checkpoint,
void Function(int received, int? total)? progress,
}) => _protectTransport(
() => _download(id, output, checkpoint: checkpoint, progress: progress),
);
Future<void> _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<void> saveCover(SubsonicSong song, File output) =>
_protectTransport(() => _saveCover(song, output));
+80
View File
@@ -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<SubsonicClient> 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<HttpException>()),
);
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<FileSystemException>()),
);
});
}
+6 -3
View File
@@ -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(