mirror of
https://github.com/zarzet/SpotiFLAC-Mobile.git
synced 2026-11-30 08:04:19 +01:00
feat(library): save network songs offline with independent copies
This commit is contained in:
1 parent
39d3ba6c53
commit
6e07941b35
61 files changed
+2408
-116
No files matched your search
+13
-1
@@ -99,7 +99,19 @@ cover caches. Playback and Lyrics share in-flight reads and cache results for
|
||||
five minutes. Large HTTP files require server byte-range support; a tag read
|
||||
failure leaves playback available with filename/folder artwork fallbacks.
|
||||
|
||||
Remote metadata editing, separate sidecar lyric files, offline downloads,
|
||||
Library songs can be saved for offline playback from their song menu, selection
|
||||
toolbar, album, playlist or folder. This copies the original audio file into the
|
||||
device's normal download folder, preserving the relative server folder and file
|
||||
name (Subsonic uses its original path when supplied, otherwise artist/album).
|
||||
No conversion or quality selection is applied. A stable network origin links
|
||||
the independent local History file to the retained scanned server row. Library
|
||||
shows one preferred local entry and offers an On this device filter, availability
|
||||
status, and separate removal of the local and server copies. A later scan that
|
||||
finds the server file gone leaves the offline copy alone. Playback prefers an
|
||||
available local copy even for network songs already queued. This does not change
|
||||
the network destination for new provider downloads or synchronize later edits.
|
||||
|
||||
Remote metadata editing, separate sidecar lyric files,
|
||||
AutoMix and direct USB/DAP bit-perfect output are not part of this browser.
|
||||
Normal playback uses the platform audio decoder, so codec support follows the
|
||||
device.
|
||||
|
||||
@@ -14,7 +14,7 @@ import java.util.Locale
|
||||
internal object NativeHistoryStore {
|
||||
private const val TAG = "NativeFinalizer"
|
||||
// Keep this schema contract in sync with Dart HistoryDatabase before bumping either side.
|
||||
const val HISTORY_SCHEMA_VERSION = 17
|
||||
const val HISTORY_SCHEMA_VERSION = 18
|
||||
|
||||
// One guarded native writer prevents interleaved transactions. Flutter/sqflite
|
||||
// uses its own WAL connection, so configure the busy timeout once per connection.
|
||||
@@ -31,6 +31,7 @@ internal object NativeHistoryStore {
|
||||
"album_artist" to "TEXT",
|
||||
"cover_url" to "TEXT",
|
||||
"file_path" to "TEXT NOT NULL",
|
||||
"origin_file_path" to "TEXT",
|
||||
"storage_mode" to "TEXT",
|
||||
"download_tree_uri" to "TEXT",
|
||||
"saf_relative_dir" to "TEXT",
|
||||
@@ -80,6 +81,7 @@ internal object NativeHistoryStore {
|
||||
"sort_album", "sort_album_artist", "sort_genre", "sort_release", "sort_added",
|
||||
"explicit", "has_lyrics", "lyrics_metadata_scan_version", "has_replaygain",
|
||||
"replaygain_metadata_scan_version",
|
||||
"origin_file_path",
|
||||
)
|
||||
private val unusedHistoryIndexes = listOf(
|
||||
"idx_downloaded_at", "idx_album", "idx_history_track_artist",
|
||||
@@ -123,6 +125,7 @@ internal object NativeHistoryStore {
|
||||
validateHistorySchema(db)
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS idx_spotify_id ON history(spotify_id)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS idx_isrc ON history(isrc)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS idx_history_origin ON history(origin_file_path)")
|
||||
// v16 dropped these unused indexes; an older writer may have recreated them.
|
||||
for (index in unusedHistoryIndexes) db.execSQL("DROP INDEX IF EXISTS $index")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS idx_history_spotify_id_norm ON history(spotify_id_norm)")
|
||||
|
||||
@@ -652,7 +652,9 @@ Future<void> deleteLibraryTracks(
|
||||
final confirmed = await showAppConfirmDialog(
|
||||
context,
|
||||
title: context.l10n.dialogDeleteSelectedTitle,
|
||||
message: context.l10n.dialogDeleteSelectedMessage(selected.length),
|
||||
message: selected.every((item) => item.historyItem?.originFilePath != null)
|
||||
? context.l10n.offlineRemoveMessage
|
||||
: context.l10n.dialogDeleteSelectedMessage(selected.length),
|
||||
confirmLabel: context.l10n.dialogDelete,
|
||||
destructive: true,
|
||||
cancelIsDefault: true,
|
||||
|
||||
@@ -303,7 +303,13 @@ class PlayerMetadataController extends ChangeNotifier {
|
||||
}
|
||||
|
||||
String _metadataPath(String source, String? resolved) =>
|
||||
!source.startsWith('network://') && resolved?.isNotEmpty == true
|
||||
resolved?.isNotEmpty == true &&
|
||||
(!source.startsWith('network://') ||
|
||||
!const {
|
||||
'http',
|
||||
'https',
|
||||
'network',
|
||||
}.contains(Uri.tryParse(resolved!)?.scheme))
|
||||
? resolved!
|
||||
: source;
|
||||
|
||||
|
||||
@@ -10269,6 +10269,33 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"offlineSave": "Save offline",
|
||||
"offlineOnDevice": "On this device",
|
||||
"offlineOnIPhone": "On iPhone",
|
||||
"offlineOnPhone": "On phone",
|
||||
"offlineServerOnly": "Server only",
|
||||
"offlineServerAndDevice": "Server + device",
|
||||
"offlineDeviceOnly": "Device only",
|
||||
"offlineRemove": "Remove offline copy",
|
||||
"offlineRemoveMessage": "Remove the offline copy from this device? The server file will be kept.",
|
||||
"offlineDeleteServer": "Delete server copy",
|
||||
"offlineServerReadOnly": "This server connection does not support deleting files.",
|
||||
"offlineDeleteServerMessage": "Delete the original file from the server? The offline copy on this device will be kept.",
|
||||
"offlineSaving": "Saving offline",
|
||||
"offlineResult": "Saved {saved}, already available {skipped}, failed {failed}",
|
||||
"@offlineResult": {
|
||||
"placeholders": {
|
||||
"saved": {"type": "int"},
|
||||
"skipped": {"type": "int"},
|
||||
"failed": {"type": "int"}
|
||||
}
|
||||
},
|
||||
"offlineFailed": "Couldn't save the offline copy. Check the server connection and download folder access.",
|
||||
"offlineNoSongs": "No network Library songs in this selection.",
|
||||
"offlineCopyUnavailable": "The offline copy is unavailable. Save it again before deleting the server copy.",
|
||||
"offlinePlayingLocal": "Playing from this device",
|
||||
"offlineStreaming": "Streaming from {server}",
|
||||
"@offlineStreaming": {"placeholders": {"server": {"type": "String"}}},
|
||||
"reorganizeLibraryFailed": "Couldn't reorganize your files: {error}",
|
||||
"@reorganizeLibraryFailed": {
|
||||
"description": "Snackbar when planning or applying the reorganization fails",
|
||||
|
||||
+20
-1
@@ -8421,5 +8421,24 @@
|
||||
"lyricsAiModeFast": "Cepat",
|
||||
"lyricsAiModeFastDescription": "Menerjemahkan per baris tanpa timing kata. Lebih cepat dengan keluaran lebih sedikit.",
|
||||
"lyricsAiModeSynced": "Sinkron",
|
||||
"lyricsAiModeSyncedDescription": "Menyelaraskan terjemahan dan romanisasi dengan kata serta frasa yang dinyanyikan. Lebih lama dan memerlukan lirik dengan timing kata."
|
||||
"lyricsAiModeSyncedDescription": "Menyelaraskan terjemahan dan romanisasi dengan kata serta frasa yang dinyanyikan. Lebih lama dan memerlukan lirik dengan timing kata.",
|
||||
"offlineSave": "Simpan offline",
|
||||
"offlineOnDevice": "Di perangkat ini",
|
||||
"offlineOnIPhone": "Di iPhone",
|
||||
"offlineOnPhone": "Di ponsel",
|
||||
"offlineServerOnly": "Hanya server",
|
||||
"offlineServerAndDevice": "Server + perangkat",
|
||||
"offlineDeviceOnly": "Hanya perangkat",
|
||||
"offlineRemove": "Hapus salinan offline",
|
||||
"offlineRemoveMessage": "Hapus salinan offline dari perangkat ini? File di server tetap disimpan.",
|
||||
"offlineDeleteServer": "Hapus salinan server",
|
||||
"offlineServerReadOnly": "Koneksi server ini tidak mendukung penghapusan file.",
|
||||
"offlineDeleteServerMessage": "Hapus file asli dari server? Salinan offline di perangkat ini tetap disimpan.",
|
||||
"offlineSaving": "Menyimpan offline",
|
||||
"offlineResult": "Disimpan {saved}, sudah tersedia {skipped}, gagal {failed}",
|
||||
"offlineFailed": "Gagal menyimpan salinan offline. Periksa koneksi server dan izin folder download.",
|
||||
"offlineNoSongs": "Tidak ada lagu Library jaringan dalam pilihan ini.",
|
||||
"offlineCopyUnavailable": "Salinan offline tidak tersedia. Simpan kembali sebelum menghapus salinan server.",
|
||||
"offlinePlayingLocal": "Memutar dari perangkat ini",
|
||||
"offlineStreaming": "Streaming dari {server}"
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
import 'package:mornye/utils/string_utils.dart';
|
||||
|
||||
/// Another transfer published the same origin while this one was fetching.
|
||||
class OfflineCopyAlreadySaved implements Exception {
|
||||
const OfflineCopyAlreadySaved();
|
||||
}
|
||||
|
||||
class DownloadHistoryItem {
|
||||
final String id;
|
||||
final String trackName;
|
||||
@@ -8,6 +13,12 @@ class DownloadHistoryItem {
|
||||
final String? albumArtist;
|
||||
final String? coverUrl;
|
||||
final String filePath;
|
||||
|
||||
/// Stable network source of an independently saved offline copy.
|
||||
final String? originFilePath;
|
||||
|
||||
/// Whether the latest Library scan still contains the original file.
|
||||
final bool originAvailable;
|
||||
final String? storageMode;
|
||||
final String? downloadTreeUri;
|
||||
final String? safRelativeDir;
|
||||
@@ -41,6 +52,14 @@ class DownloadHistoryItem {
|
||||
/// [hasReplayGain] a confirmed absence.
|
||||
final int replayGainMetadataScanVersion;
|
||||
|
||||
/// File copies retain their scanned Library identity for playlists/likes.
|
||||
/// The legacy spotifyId column also stores foreign ids from other sources.
|
||||
bool get _offlineLibraryFile =>
|
||||
originFilePath != null &&
|
||||
const {'Network offline', 'Mornye Link'}.contains(service);
|
||||
String get collectionTrackId => _offlineLibraryFile ? spotifyId ?? id : id;
|
||||
String get collectionTrackSource => _offlineLibraryFile ? 'local' : service;
|
||||
|
||||
const DownloadHistoryItem({
|
||||
required this.id,
|
||||
required this.trackName,
|
||||
@@ -49,6 +68,8 @@ class DownloadHistoryItem {
|
||||
this.albumArtist,
|
||||
this.coverUrl,
|
||||
required this.filePath,
|
||||
this.originFilePath,
|
||||
this.originAvailable = false,
|
||||
this.storageMode,
|
||||
this.downloadTreeUri,
|
||||
this.safRelativeDir,
|
||||
@@ -88,6 +109,7 @@ class DownloadHistoryItem {
|
||||
'albumArtist': albumArtist,
|
||||
'coverUrl': coverUrl,
|
||||
'filePath': filePath,
|
||||
'originFilePath': originFilePath,
|
||||
'storageMode': storageMode,
|
||||
'downloadTreeUri': downloadTreeUri,
|
||||
'safRelativeDir': safRelativeDir,
|
||||
@@ -128,6 +150,9 @@ class DownloadHistoryItem {
|
||||
albumArtist: normalizeOptionalString(json['albumArtist'] as String?),
|
||||
coverUrl: normalizeCoverReference(json['coverUrl']?.toString()),
|
||||
filePath: json['filePath'] as String,
|
||||
originFilePath: json['originFilePath'] as String?,
|
||||
originAvailable:
|
||||
json['originAvailable'] == true || json['originAvailable'] == 1,
|
||||
storageMode: json['storageMode'] as String?,
|
||||
downloadTreeUri: json['downloadTreeUri'] as String?,
|
||||
safRelativeDir: json['safRelativeDir'] as String?,
|
||||
@@ -169,6 +194,8 @@ class DownloadHistoryItem {
|
||||
String? albumArtist,
|
||||
String? coverUrl,
|
||||
String? filePath,
|
||||
String? originFilePath,
|
||||
bool? originAvailable,
|
||||
String? storageMode,
|
||||
String? downloadTreeUri,
|
||||
String? safRelativeDir,
|
||||
@@ -205,6 +232,8 @@ class DownloadHistoryItem {
|
||||
albumArtist: albumArtist ?? this.albumArtist,
|
||||
coverUrl: normalizeCoverReference(coverUrl ?? this.coverUrl),
|
||||
filePath: filePath ?? this.filePath,
|
||||
originFilePath: originFilePath ?? this.originFilePath,
|
||||
originAvailable: originAvailable ?? this.originAvailable,
|
||||
storageMode: storageMode ?? this.storageMode,
|
||||
downloadTreeUri: downloadTreeUri ?? this.downloadTreeUri,
|
||||
safRelativeDir: safRelativeDir ?? this.safRelativeDir,
|
||||
|
||||
@@ -120,8 +120,8 @@ class UnifiedLibraryItem {
|
||||
String get collectionKey {
|
||||
if (historyItem != null) {
|
||||
return libraryTrackCollectionKey(
|
||||
id: historyItem!.id,
|
||||
source: historyItem!.service,
|
||||
id: historyItem!.collectionTrackId,
|
||||
source: historyItem!.collectionTrackSource,
|
||||
isrc: historyItem!.isrc,
|
||||
);
|
||||
}
|
||||
@@ -139,7 +139,7 @@ class UnifiedLibraryItem {
|
||||
if (historyItem != null) {
|
||||
final h = historyItem!;
|
||||
return Track(
|
||||
id: h.id,
|
||||
id: h.collectionTrackId,
|
||||
name: h.trackName,
|
||||
artistName: h.artistName,
|
||||
albumName: h.albumName,
|
||||
@@ -150,7 +150,7 @@ class UnifiedLibraryItem {
|
||||
trackNumber: h.trackNumber,
|
||||
discNumber: h.discNumber,
|
||||
releaseDate: h.releaseDate,
|
||||
source: h.service,
|
||||
source: h.collectionTrackSource,
|
||||
);
|
||||
}
|
||||
if (localItem != null) {
|
||||
|
||||
@@ -85,6 +85,8 @@ bool _sameHistoryItem(DownloadHistoryItem a, DownloadHistoryItem b) =>
|
||||
a.albumArtist == b.albumArtist &&
|
||||
a.coverUrl == b.coverUrl &&
|
||||
a.filePath == b.filePath &&
|
||||
a.originFilePath == b.originFilePath &&
|
||||
a.originAvailable == b.originAvailable &&
|
||||
a.storageMode == b.storageMode &&
|
||||
a.downloadTreeUri == b.downloadTreeUri &&
|
||||
a.safRelativeDir == b.safRelativeDir &&
|
||||
@@ -397,6 +399,32 @@ class DownloadHistoryNotifier extends Notifier<DownloadHistoryState> {
|
||||
),
|
||||
);
|
||||
|
||||
/// Serialized with Link, NAS transfers and ordinary History mutations.
|
||||
/// A concurrent transfer must not publish a second row for one origin.
|
||||
Future<void> saveOfflineCopy(DownloadHistoryItem item) =>
|
||||
_enqueueHistoryWrite(() async {
|
||||
final origin = item.originFilePath;
|
||||
if (origin == null || !origin.startsWith('network://')) {
|
||||
throw const FormatException('An offline copy needs a network origin');
|
||||
}
|
||||
final existing = await _db.findOfflineCopy(origin);
|
||||
var incoming = item;
|
||||
if (existing != null) {
|
||||
final path = existing['filePath'] as String;
|
||||
if (path != item.filePath && await fileExists(path)) {
|
||||
throw const OfflineCopyAlreadySaved();
|
||||
}
|
||||
incoming = DownloadHistoryItem.fromJson(
|
||||
item.toJson()..['id'] = existing['id'],
|
||||
);
|
||||
}
|
||||
await _persistHistoryItem(
|
||||
incoming,
|
||||
'save offline copy',
|
||||
preserveTrackVariant: true,
|
||||
);
|
||||
});
|
||||
|
||||
Future<void> adoptNativeHistoryItem(
|
||||
DownloadHistoryItem item, {
|
||||
bool preserveTrackVariant = false,
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:mornye/l10n/supported_locales.dart';
|
||||
import 'package:mornye/models/unified_library_item.dart';
|
||||
import 'package:mornye/providers/download_history_provider.dart';
|
||||
import 'package:mornye/providers/settings_provider.dart';
|
||||
import 'package:mornye/providers/local_library_provider.dart';
|
||||
import 'package:mornye/services/library_database.dart';
|
||||
import 'package:mornye/services/history_database.dart';
|
||||
import 'package:mornye/services/link/features/link_save_offline.dart';
|
||||
import 'package:mornye/services/network_offline_saver.dart';
|
||||
import 'package:mornye/services/network_storage_service.dart';
|
||||
import 'package:mornye/services/notification_service.dart';
|
||||
import 'package:mornye/utils/file_access.dart';
|
||||
|
||||
final networkOfflineProvider =
|
||||
NotifierProvider<NetworkOfflineNotifier, LinkOfflineProgress?>(
|
||||
NetworkOfflineNotifier.new,
|
||||
);
|
||||
|
||||
final networkOfflineStorageProvider = Provider<NetworkStorageService>(
|
||||
(ref) => NetworkStorageService.instance,
|
||||
);
|
||||
|
||||
/// One owned transfer at a time, shared by both themes and every Library
|
||||
/// entry point. Leaving a screen keeps it running; cancellation closes only
|
||||
/// the transfer's own network connections.
|
||||
class NetworkOfflineNotifier extends Notifier<LinkOfflineProgress?> {
|
||||
LinkOfflineCancel? _cancel;
|
||||
|
||||
@override
|
||||
LinkOfflineProgress? build() {
|
||||
ref.onDispose(() => _cancel?.cancel());
|
||||
return null;
|
||||
}
|
||||
|
||||
void cancel() => _cancel?.cancel();
|
||||
|
||||
Future<LinkOfflineResult?> save(List<UnifiedLibraryItem> items) async {
|
||||
if (_cancel != null) return null;
|
||||
final songs = networkOfflineSongs(items);
|
||||
if (songs.isEmpty) return null;
|
||||
final songsByOrigin = {for (final song in songs) song.songId: song};
|
||||
final cancel = LinkOfflineCancel();
|
||||
_cancel = cancel;
|
||||
final storage = ref.read(networkOfflineStorageProvider);
|
||||
final transport = NetworkOfflineTransport(storage: storage);
|
||||
final settings = ref.read(settingsProvider);
|
||||
final history = ref.read(downloadHistoryProvider.notifier);
|
||||
final library = ref.read(localLibraryProvider.notifier);
|
||||
final remoteHistoryIds = {
|
||||
for (final item in items)
|
||||
if (item.historyItem != null && item.filePath.startsWith('network://'))
|
||||
item.filePath: item.historyItem!.id,
|
||||
};
|
||||
final remoteHistory = {
|
||||
for (final item in items)
|
||||
if (item.historyItem != null && networkOfflineOrigin(item) != null)
|
||||
networkOfflineOrigin(item)!: item.historyItem!,
|
||||
};
|
||||
final notices = NotificationService();
|
||||
final l10n = appLocalizationsFor(settings.locale);
|
||||
state = LinkOfflineProgress(done: 0, total: songs.length, title: '');
|
||||
var lastProgressAt = DateTime.fromMillisecondsSinceEpoch(0);
|
||||
try {
|
||||
await notices.beginBackgroundWork(
|
||||
'network_offline',
|
||||
title: l10n.offlineSave,
|
||||
);
|
||||
final originSources = remoteHistoryIds.isEmpty
|
||||
? <LocalLibrarySource>[]
|
||||
: [...await LibraryDatabase.instance.getSources()];
|
||||
return await LinkOfflineSaver(
|
||||
serverId: 'network',
|
||||
idPrefix: 'offline',
|
||||
serviceName: 'Network offline',
|
||||
openTransport: () => transport,
|
||||
prepareSong: transport.prepare,
|
||||
destination: LinkDownloadFolderDestination(settings),
|
||||
historyIdForSong: (song) =>
|
||||
remoteHistoryIds[song.songId] ??
|
||||
networkOfflineHistoryId(song.songId),
|
||||
record: (item) async {
|
||||
final origin = item.originFilePath!;
|
||||
if (remoteHistoryIds.containsKey(origin)) {
|
||||
// Downloads sent directly to NAS originally have only a History
|
||||
// row. Retain a scanned server row before its local alias can be
|
||||
// removed, just as for an ordinary scanned network song.
|
||||
final uri = Uri.parse(origin);
|
||||
final candidates =
|
||||
originSources
|
||||
.where(
|
||||
(source) =>
|
||||
source.path == origin ||
|
||||
origin.startsWith(
|
||||
source.path.endsWith('/')
|
||||
? source.path
|
||||
: '${source.path}/',
|
||||
),
|
||||
)
|
||||
.toList()
|
||||
..sort((a, b) => b.path.length.compareTo(a.path.length));
|
||||
final connection = await storage.connection(uri.host);
|
||||
final source =
|
||||
candidates.firstOrNull ??
|
||||
await library.addSource(
|
||||
path: NetworkStorageService.source(
|
||||
uri.host,
|
||||
'${uri.pathSegments.take(uri.pathSegments.length - 1).join('/')}/',
|
||||
),
|
||||
displayName: connection.name,
|
||||
);
|
||||
if (candidates.isEmpty) originSources.add(source);
|
||||
if (ref.mounted &&
|
||||
!ref.read(settingsProvider).localLibraryEnabled) {
|
||||
ref.read(settingsProvider.notifier).setLocalLibraryEnabled(true);
|
||||
}
|
||||
final song = songsByOrigin[origin]!;
|
||||
await LibraryDatabase.instance.retainOfflineOrigin(
|
||||
song.item,
|
||||
source.id,
|
||||
);
|
||||
}
|
||||
final original = remoteHistory[origin];
|
||||
await history.saveOfflineCopy(
|
||||
original == null
|
||||
? item
|
||||
: DownloadHistoryItem.fromJson({
|
||||
...item.toJson(),
|
||||
'service': original.service,
|
||||
'spotifyId': original.spotifyId,
|
||||
}),
|
||||
);
|
||||
},
|
||||
existsOrigin: (origin) async {
|
||||
final row = await HistoryDatabase.instance.findOfflineCopy(origin);
|
||||
final path = row?['filePath'] as String?;
|
||||
return path != null &&
|
||||
!path.startsWith('network://') &&
|
||||
await fileExists(path);
|
||||
},
|
||||
temporaryDirectory: getTemporaryDirectory,
|
||||
exists: (id) async {
|
||||
final row = await HistoryDatabase.instance.getById(id);
|
||||
final path = row?['filePath'] as String?;
|
||||
return path != null &&
|
||||
!path.startsWith('network://') &&
|
||||
await fileExists(path);
|
||||
},
|
||||
).save(
|
||||
songs,
|
||||
cancel: cancel,
|
||||
onProgress: (progress) {
|
||||
final now = DateTime.now();
|
||||
if (ref.mounted &&
|
||||
(state?.title != progress.title ||
|
||||
state?.done != progress.done ||
|
||||
now.difference(lastProgressAt).inMilliseconds >= 120)) {
|
||||
lastProgressAt = now;
|
||||
state = progress;
|
||||
}
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
transport.close();
|
||||
try {
|
||||
if (ref.mounted) await library.reloadFromStorage();
|
||||
} finally {
|
||||
try {
|
||||
await notices.endBackgroundWork('network_offline');
|
||||
} finally {
|
||||
_cancel = null;
|
||||
if (ref.mounted) state = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ import 'package:mornye/widgets/animation_utils.dart';
|
||||
import 'package:mornye/widgets/library_track_selection_bar.dart';
|
||||
import 'package:mornye/widgets/library_selection_playback_actions.dart';
|
||||
import 'package:mornye/widgets/link/link_actions.dart';
|
||||
import 'package:mornye/widgets/network_offline_actions.dart';
|
||||
import 'package:mornye/widgets/disc_separator_chip.dart';
|
||||
import 'package:mornye/widgets/album_detail_header.dart';
|
||||
import 'package:mornye/widgets/mornye_artist_header.dart';
|
||||
@@ -440,16 +441,21 @@ class _DownloadedAlbumScreenState extends ConsumerState<DownloadedAlbumScreen>
|
||||
meta: tracks.isNotEmpty
|
||||
? _buildDownloadedHeaderMeta(context, tracks, commonQuality)
|
||||
: null,
|
||||
appBarActions: ref.watch(linkPhoneClientProvider) == null
|
||||
? null
|
||||
: [
|
||||
LinkTransferButtons(
|
||||
items: [
|
||||
for (final track in tracks)
|
||||
UnifiedLibraryItem.fromDownloadHistory(track),
|
||||
],
|
||||
),
|
||||
appBarActions: [
|
||||
NetworkOfflineButton(
|
||||
items: [
|
||||
for (final track in tracks)
|
||||
UnifiedLibraryItem.fromDownloadHistory(track),
|
||||
],
|
||||
),
|
||||
if (ref.watch(linkPhoneClientProvider) != null)
|
||||
LinkTransferButtons(
|
||||
items: [
|
||||
for (final track in tracks)
|
||||
UnifiedLibraryItem.fromDownloadHistory(track),
|
||||
],
|
||||
),
|
||||
],
|
||||
actions: tracks.isNotEmpty
|
||||
? AlbumPlayActions(
|
||||
playLabel: context.l10n.tooltipPlay,
|
||||
|
||||
@@ -46,6 +46,7 @@ import 'package:mornye/screens/track_metadata_screen.dart';
|
||||
import 'package:mornye/widgets/selection_action_button.dart';
|
||||
import 'package:mornye/widgets/in_library_badge.dart';
|
||||
import 'package:mornye/widgets/link/link_actions.dart';
|
||||
import 'package:mornye/widgets/network_offline_actions.dart';
|
||||
import 'package:mornye/widgets/playlist_picker_sheet.dart';
|
||||
import 'package:mornye/widgets/collection_suggestions_section.dart';
|
||||
import 'package:mornye/widgets/animation_utils.dart';
|
||||
@@ -914,6 +915,10 @@ class _LibraryTracksFolderScreenState
|
||||
child: Text(context.l10n.dialogSave),
|
||||
),
|
||||
if (!_editingOrder) ...[
|
||||
if (!isSelectionMode && entries.isNotEmpty)
|
||||
NetworkOfflineTracksButton(
|
||||
tracks: [for (final entry in entries) entry.track],
|
||||
),
|
||||
if (!isSelectionMode && entries.isNotEmpty)
|
||||
HeaderCircleButton(
|
||||
icon: Icons.ios_share,
|
||||
|
||||
@@ -46,6 +46,7 @@ import 'package:mornye/widgets/animation_utils.dart';
|
||||
import 'package:mornye/widgets/app_snack_bar.dart';
|
||||
import 'package:mornye/widgets/library_track_selection_bar.dart';
|
||||
import 'package:mornye/widgets/link/link_actions.dart';
|
||||
import 'package:mornye/widgets/network_offline_actions.dart';
|
||||
import 'package:mornye/widgets/library_selection_playback_actions.dart';
|
||||
import 'package:mornye/widgets/local_library_artwork_builder.dart';
|
||||
import 'package:mornye/widgets/disc_separator_chip.dart';
|
||||
@@ -440,9 +441,11 @@ class _LocalAlbumScreenState extends ConsumerState<LocalAlbumScreen>
|
||||
),
|
||||
),
|
||||
meta: _buildLocalHeaderMeta(context, qualityLabelMode),
|
||||
appBarActions: ref.watch(linkPhoneClientProvider) == null
|
||||
? null
|
||||
: [LinkTransferButtons(items: _albumItems())],
|
||||
appBarActions: [
|
||||
NetworkOfflineButton(items: _albumItems()),
|
||||
if (ref.watch(linkPhoneClientProvider) != null)
|
||||
LinkTransferButtons(items: _albumItems()),
|
||||
],
|
||||
actions: Consumer(
|
||||
builder: (context, ref, _) {
|
||||
final isCurrent = ref.watch(
|
||||
|
||||
@@ -35,6 +35,7 @@ import 'package:mornye/widgets/desktop/desktop_commands.dart'
|
||||
show DesktopCommand, desktopTooltip;
|
||||
import 'package:mornye/widgets/desktop/desktop_inspector.dart';
|
||||
import 'package:mornye/widgets/link/link_actions.dart';
|
||||
import 'package:mornye/widgets/network_offline_actions.dart';
|
||||
import 'package:mornye/widgets/link/link_devices_sheet.dart';
|
||||
import 'package:mornye/widgets/lyrics_options_button.dart';
|
||||
import 'package:mornye/widgets/lyrics_screen_awake.dart';
|
||||
@@ -1171,6 +1172,13 @@ class _NowPlayingScreenState extends ConsumerState<NowPlayingScreen> {
|
||||
title: sheetContext.l10n.linkSaveToPhone,
|
||||
onTap: () => Navigator.of(sheetContext).pop('linkSave'),
|
||||
),
|
||||
if (!saveToPhone && canSaveNetworkOfflineSource(source))
|
||||
SettingsItem(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
title: sheetContext.l10n.offlineSave,
|
||||
onTap: () =>
|
||||
Navigator.of(sheetContext).pop('networkOffline'),
|
||||
),
|
||||
SettingsItem(
|
||||
icon: Icons.bedtime_outlined,
|
||||
title: sheetContext.l10n.nowPlayingSleepTimer,
|
||||
@@ -1245,6 +1253,9 @@ class _NowPlayingScreenState extends ConsumerState<NowPlayingScreen> {
|
||||
case 'linkSave':
|
||||
linkSaveSongsToPhone(context, ref, transfer.desktop);
|
||||
break;
|
||||
case 'networkOffline':
|
||||
await savePlayingNetworkOffline(context, ref, mediaItem);
|
||||
break;
|
||||
case 'details':
|
||||
unawaited(
|
||||
showPlayerDetailsSheet(
|
||||
|
||||
@@ -61,6 +61,7 @@ import 'package:mornye/utils/saf_download_tree.dart';
|
||||
import 'package:mornye/models/download_item.dart';
|
||||
import 'package:mornye/models/settings.dart';
|
||||
import 'package:mornye/models/unified_library_item.dart';
|
||||
import 'package:mornye/widgets/network_offline_actions.dart';
|
||||
import 'package:mornye/providers/download_queue_provider.dart';
|
||||
import 'package:mornye/providers/extension_provider.dart';
|
||||
import 'package:mornye/providers/library_collections_provider.dart';
|
||||
|
||||
@@ -49,6 +49,7 @@ extension _QueueTabFilterSheet on _QueueTabState {
|
||||
(null, context.l10n.libraryFilterAll),
|
||||
('downloaded', context.l10n.libraryFilterDownloaded),
|
||||
('local', context.l10n.libraryFilterLocal),
|
||||
('on-device', offlineDeviceFilterLabel(context)),
|
||||
])
|
||||
AppChoiceChip(
|
||||
label: Text(label),
|
||||
|
||||
@@ -670,14 +670,29 @@ extension _QueueTabItemWidgets on _QueueTabState {
|
||||
|
||||
// Scanned SAF tracks also recover artwork after a transient provider error.
|
||||
if (isDownloaded || item.filePath.startsWith('content://')) {
|
||||
return ValueListenableBuilder<int>(
|
||||
valueListenable: _embeddedCoverVersion,
|
||||
builder: (context, _, child) =>
|
||||
_buildUnifiedCoverImageInner(item, colorScheme, isDownloaded, size),
|
||||
return OfflineAvailabilityCover(
|
||||
item: item,
|
||||
child: ValueListenableBuilder<int>(
|
||||
valueListenable: _embeddedCoverVersion,
|
||||
builder: (context, _, child) => _buildUnifiedCoverImageInner(
|
||||
item,
|
||||
colorScheme,
|
||||
isDownloaded,
|
||||
size,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return _buildUnifiedCoverImageInner(item, colorScheme, isDownloaded, size);
|
||||
return OfflineAvailabilityCover(
|
||||
item: item,
|
||||
child: _buildUnifiedCoverImageInner(
|
||||
item,
|
||||
colorScheme,
|
||||
isDownloaded,
|
||||
size,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUnifiedCoverImageInner(
|
||||
@@ -1123,6 +1138,18 @@ extension _QueueTabItemWidgets on _QueueTabState {
|
||||
listStyle: true,
|
||||
),
|
||||
],
|
||||
if (offlineAvailabilityLabel(context, item)
|
||||
case final status?) ...[
|
||||
const SizedBox(width: 8),
|
||||
Flexible(
|
||||
child: Text(
|
||||
status,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
|
||||
@@ -169,7 +169,9 @@ extension _TrackMetadataFileActions on _TrackMetadataScreenState {
|
||||
final confirmed = await showAppConfirmDialog(
|
||||
screenContext,
|
||||
title: l10n.trackDeleteConfirmTitle,
|
||||
message: _isNetworkItem
|
||||
message: _downloadItem?.originFilePath != null
|
||||
? l10n.offlineRemoveMessage
|
||||
: _isNetworkItem
|
||||
? l10n.trackDeleteNetworkConfirmMessage
|
||||
: l10n.trackDeleteConfirmMessage,
|
||||
confirmLabel: l10n.dialogDelete,
|
||||
|
||||
@@ -22,6 +22,7 @@ import 'package:mornye/services/metadata_persistence_service.dart';
|
||||
import 'package:mornye/services/library_database.dart';
|
||||
import 'package:mornye/services/cue_split_library_service.dart';
|
||||
import 'package:mornye/services/link/features/link_save_offline.dart';
|
||||
import 'package:mornye/widgets/network_offline_actions.dart';
|
||||
import 'package:mornye/models/unified_library_item.dart';
|
||||
import 'package:mornye/utils/file_access.dart';
|
||||
import 'package:mornye/utils/re_enrich_result.dart';
|
||||
|
||||
@@ -46,6 +46,17 @@ extension _TrackMetadataMenu on _TrackMetadataScreenState {
|
||||
UnifiedLibraryItem.fromDownloadHistory(downloadItem),
|
||||
]);
|
||||
return <_MetadataOption>[
|
||||
if (canSaveNetworkOfflineSource(cleanFilePath) && desktopSongs.isEmpty)
|
||||
_MetadataOption(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
label: l10n.offlineSave,
|
||||
onTap: () => saveNetworkOffline(screenContext, ref, [
|
||||
if (localItem != null)
|
||||
UnifiedLibraryItem.fromLocalLibrary(localItem)
|
||||
else if (downloadItem != null)
|
||||
UnifiedLibraryItem.fromDownloadHistory(downloadItem),
|
||||
]),
|
||||
),
|
||||
if (_fileExists && showPlayer)
|
||||
_MetadataOption(
|
||||
icon: Icons.playlist_play,
|
||||
@@ -173,12 +184,23 @@ extension _TrackMetadataMenu on _TrackMetadataScreenState {
|
||||
dividerAbove: _spotifyId == null && !(isrc?.isNotEmpty ?? false),
|
||||
onTap: () => _shareFile(screenContext),
|
||||
),
|
||||
if (downloadItem?.originFilePath != null)
|
||||
_MetadataOption(
|
||||
icon: Icons.cloud_off_outlined,
|
||||
label: l10n.offlineDeleteServer,
|
||||
destructive: true,
|
||||
onTap: () => deleteOfflineServerCopies(screenContext, ref, [
|
||||
UnifiedLibraryItem.fromDownloadHistory(downloadItem!),
|
||||
]),
|
||||
),
|
||||
if (remoteFile)
|
||||
remote(LinkLibraryAction.delete)
|
||||
else if (_canDeleteFile)
|
||||
_MetadataOption(
|
||||
icon: Icons.delete_outline,
|
||||
label: _isNetworkItem
|
||||
label: downloadItem?.originFilePath != null
|
||||
? l10n.offlineRemove
|
||||
: _isNetworkItem
|
||||
? l10n.trackMetadataDelete
|
||||
: l10n.trackRemoveFromDevice,
|
||||
destructive: true,
|
||||
|
||||
@@ -4,6 +4,8 @@ import 'dart:io';
|
||||
/// Owns SAF playback copies, including copies that finish after invalidation.
|
||||
/// Transport pins keep active and prepared decks alive until they release them.
|
||||
class ContentUriPlaybackCache {
|
||||
bool ownsPath(String path) =>
|
||||
_entries.values.any((entry) => entry.path == path);
|
||||
ContentUriPlaybackCache({
|
||||
required Future<String?> Function(String) copy,
|
||||
required bool Function() isDisposed,
|
||||
|
||||
@@ -105,7 +105,7 @@ class HistoryDatabase {
|
||||
// the existing schema migration. The background native writer shares
|
||||
// history.db and must accept the same schema contract and
|
||||
// user_version without depending on FTS5.
|
||||
static const int schemaVersion = 17;
|
||||
static const int schemaVersion = 18;
|
||||
static const String searchFtsTable = 'history_search_fts';
|
||||
static final HistoryDatabase instance = HistoryDatabase._init();
|
||||
static final sqlite.SingleFlightInitializer<Database> _database =
|
||||
@@ -434,6 +434,11 @@ class HistoryDatabase {
|
||||
Future<List<String>> getPhysicalFileIds(Iterable<String> filePaths) async =>
|
||||
sqlite.findPhysicalFileRowIds(await database, 'history', filePaths);
|
||||
|
||||
/// Origin aliases are deliberately separate from physical path keys:
|
||||
/// deleting a server file must never delete its independent offline copy.
|
||||
Future<Map<String, dynamic>?> findOfflineCopy(String origin) async =>
|
||||
_firstRow(await database, 'origin_file_path = ?', [origin]);
|
||||
|
||||
Future<Map<String, dynamic>?> getBySpotifyId(String spotifyId) async =>
|
||||
_firstRow(await database, 'spotify_id = ?', [spotifyId]);
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ abstract final class HistoryRowMapper {
|
||||
'album_artist': json['albumArtist'],
|
||||
'cover_url': json['coverUrl'],
|
||||
'file_path': json['filePath'],
|
||||
'origin_file_path': json['originFilePath'],
|
||||
'storage_mode': json['storageMode'],
|
||||
'download_tree_uri': json['downloadTreeUri'],
|
||||
'saf_relative_dir': json['safRelativeDir'],
|
||||
@@ -146,6 +147,9 @@ abstract final class HistoryRowMapper {
|
||||
'albumArtist': row['album_artist'],
|
||||
'coverUrl': row['cover_url'],
|
||||
'filePath': filePath,
|
||||
'originFilePath': row['origin_file_path'],
|
||||
if (row.containsKey('origin_available'))
|
||||
'originAvailable': row['origin_available'] == 1,
|
||||
'storageMode': row['storage_mode'],
|
||||
'downloadTreeUri': row['download_tree_uri'],
|
||||
'safRelativeDir': row['saf_relative_dir'],
|
||||
|
||||
@@ -22,6 +22,7 @@ abstract final class HistorySchema {
|
||||
album_artist TEXT,
|
||||
cover_url TEXT,
|
||||
file_path TEXT NOT NULL,
|
||||
origin_file_path TEXT,
|
||||
storage_mode TEXT,
|
||||
download_tree_uri TEXT,
|
||||
saf_relative_dir TEXT,
|
||||
@@ -71,6 +72,7 @@ abstract final class HistorySchema {
|
||||
await _createNormalizedIndexes(db);
|
||||
await _createQueueIndexes(db);
|
||||
await _createPathKeyTable(db);
|
||||
await _createOriginIndex(db);
|
||||
final searchFtsAvailable = await createSearchFts(db);
|
||||
|
||||
_log.i('Database schema created with indexes');
|
||||
@@ -161,8 +163,16 @@ abstract final class HistorySchema {
|
||||
}
|
||||
await _createQueueIndexes(db);
|
||||
}
|
||||
if (oldVersion < 18) {
|
||||
await addColumn('origin_file_path', 'TEXT');
|
||||
await _createOriginIndex(db);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> _createOriginIndex(DatabaseExecutor db) => db.execute(
|
||||
'CREATE INDEX IF NOT EXISTS idx_history_origin ON history(origin_file_path)',
|
||||
);
|
||||
|
||||
/// No query seeks or orders by these. v16 and the native writer drop them.
|
||||
static const unusedIndexes = [
|
||||
'idx_downloaded_at',
|
||||
|
||||
@@ -251,6 +251,30 @@ class LibraryDatabase {
|
||||
required String sourceId,
|
||||
}) => _ingestion.upsertBatchExcludingHistory(items, sourceId: sourceId);
|
||||
|
||||
/// Retains the original of a NAS download before History moves to its local
|
||||
/// copy. Unlike a scan import this must keep the currently shadowed row.
|
||||
Future<void> retainOfflineOrigin(
|
||||
LocalLibraryItem item,
|
||||
String sourceId,
|
||||
) async {
|
||||
final db = await database;
|
||||
await db.transaction((txn) async {
|
||||
final batch = txn.batch();
|
||||
batch.insert(
|
||||
'library',
|
||||
LibraryRowMapper.encode(item.toJson(), sourceId: sourceId),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
sqlite.putPathKeysInBatch(
|
||||
batch,
|
||||
'library_path_keys',
|
||||
item.id,
|
||||
item.filePath,
|
||||
);
|
||||
await batch.commit(noResult: true);
|
||||
});
|
||||
}
|
||||
|
||||
Future<List<LocalLibrarySource>> getSources() async {
|
||||
final db = await database;
|
||||
final rows = await db.rawQuery('''
|
||||
|
||||
@@ -395,6 +395,9 @@ class LibraryQueueStore {
|
||||
h.album_artist,
|
||||
h.cover_url,
|
||||
h.file_path,
|
||||
h.origin_file_path,
|
||||
EXISTS(SELECT 1 FROM library origin
|
||||
WHERE origin.file_path = h.origin_file_path) AS origin_available,
|
||||
h.storage_mode,
|
||||
h.download_tree_uri,
|
||||
h.saf_relative_dir,
|
||||
@@ -472,6 +475,8 @@ class LibraryQueueStore {
|
||||
l.album_artist,
|
||||
NULL AS cover_url,
|
||||
l.file_path,
|
||||
NULL AS origin_file_path,
|
||||
0 AS origin_available,
|
||||
NULL AS storage_mode,
|
||||
NULL AS download_tree_uri,
|
||||
NULL AS saf_relative_dir,
|
||||
@@ -536,6 +541,8 @@ class LibraryQueueStore {
|
||||
NULL AS album_artist,
|
||||
NULL AS cover_url,
|
||||
NULL AS file_path,
|
||||
NULL AS origin_file_path,
|
||||
0 AS origin_available,
|
||||
NULL AS storage_mode,
|
||||
NULL AS download_tree_uri,
|
||||
NULL AS saf_relative_dir,
|
||||
@@ -785,6 +792,9 @@ class LibraryQueueStore {
|
||||
bool hasCompletenessJoin = false,
|
||||
bool albumCompleteness = true,
|
||||
}) {
|
||||
if (request.source == 'on-device') {
|
||||
where.add("h.file_path NOT LIKE 'network://%'");
|
||||
}
|
||||
if (albumCompleteness) {
|
||||
_appendAlbumCompletenessFilter(
|
||||
where,
|
||||
@@ -844,6 +854,9 @@ class LibraryQueueStore {
|
||||
bool hasCompletenessJoin = false,
|
||||
bool albumCompleteness = true,
|
||||
}) {
|
||||
if (request.source == 'on-device') {
|
||||
where.add("l.file_path NOT LIKE 'network://%'");
|
||||
}
|
||||
if (albumCompleteness) {
|
||||
_appendAlbumCompletenessFilter(
|
||||
where,
|
||||
@@ -1225,6 +1238,8 @@ class LibraryQueueStore {
|
||||
'fileModTime': row['file_mod_time'],
|
||||
} else ...{
|
||||
'coverUrl': row['cover_url'],
|
||||
'originFilePath': row['origin_file_path'],
|
||||
'originAvailable': row['origin_available'] == 1,
|
||||
'storageMode': row['storage_mode'],
|
||||
'downloadTreeUri': row['download_tree_uri'],
|
||||
'safRelativeDir': row['saf_relative_dir'],
|
||||
|
||||
@@ -17,4 +17,7 @@ String libraryNotShadowedSql(String alias, {bool snapshot = false}) => snapshot
|
||||
FROM library_path_keys lpk
|
||||
JOIN history_db.history_path_keys hpk ON hpk.path_key = lpk.path_key
|
||||
WHERE lpk.item_id = $alias.id
|
||||
UNION ALL
|
||||
SELECT 1 FROM history_db.history offline
|
||||
WHERE offline.origin_file_path = $alias.file_path
|
||||
)''';
|
||||
@@ -129,7 +129,11 @@ final linkOfflineSaverProvider = Provider<LinkOfflineSaver?>((ref) {
|
||||
serverId: client.server.serverId,
|
||||
openTransport: () => LinkSubsonicTransport(connectionId: connectionId),
|
||||
destination: LinkDownloadFolderDestination(ref.watch(settingsProvider)),
|
||||
record: history.addToHistory,
|
||||
record: history.saveOfflineCopy,
|
||||
existsOrigin: (origin) async {
|
||||
final row = await HistoryDatabase.instance.findOfflineCopy(origin);
|
||||
return row != null && await fileExists(row['filePath'] as String);
|
||||
},
|
||||
temporaryDirectory: getTemporaryDirectory,
|
||||
exists: linkHistoryFileExists,
|
||||
);
|
||||
|
||||
@@ -15,10 +15,16 @@ import 'package:mornye/services/link/link_client_api.dart';
|
||||
import 'package:mornye/services/link/link_protocol.dart';
|
||||
import 'package:mornye/services/network_storage_service.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:mornye/utils/file_access.dart' show deleteFile;
|
||||
|
||||
/// A Library song scanned from the paired desktop, which the phone can save.
|
||||
/// A Library original from Link or network storage, which this device can save.
|
||||
class LinkOfflineSong {
|
||||
const LinkOfflineSong({required this.item, required this.songId});
|
||||
const LinkOfflineSong({
|
||||
required this.item,
|
||||
required this.songId,
|
||||
this.relativeDir,
|
||||
this.fileName,
|
||||
});
|
||||
|
||||
/// A song the desktop offered (`transfers.offer`), named and recorded with
|
||||
/// the tags it sent.
|
||||
@@ -29,19 +35,20 @@ class LinkOfflineSong {
|
||||
String? text(String? value) =>
|
||||
value == null || value.trim().isEmpty ? null : value.trim();
|
||||
final durationMs = song.durationMs;
|
||||
final source = linkDesktopSongSource(
|
||||
server,
|
||||
song.songId,
|
||||
format: song.suffix,
|
||||
);
|
||||
return LinkOfflineSong(
|
||||
songId: song.songId,
|
||||
item: LocalLibraryItem(
|
||||
id: 'link_offer_${song.songId}',
|
||||
id: 'network_${sha256.convert(utf8.encode(source))}',
|
||||
trackName: song.title,
|
||||
artistName: song.artist,
|
||||
albumName: text(song.album) ?? '',
|
||||
albumArtist: text(song.albumArtist),
|
||||
filePath: linkDesktopSongSource(
|
||||
server,
|
||||
song.songId,
|
||||
format: song.suffix,
|
||||
),
|
||||
filePath: source,
|
||||
scannedAt: DateTime.fromMillisecondsSinceEpoch(0),
|
||||
isrc: text(song.isrc),
|
||||
trackNumber: song.track,
|
||||
@@ -62,8 +69,10 @@ class LinkOfflineSong {
|
||||
|
||||
final LocalLibraryItem item;
|
||||
|
||||
/// The desktop catalog id of [item].
|
||||
/// The desktop catalog id or stable network source of [item].
|
||||
final String songId;
|
||||
final String? relativeDir;
|
||||
final String? fileName;
|
||||
}
|
||||
|
||||
/// The songs of [items] that stream from [server]'s Subsonic connection.
|
||||
@@ -124,6 +133,11 @@ abstract interface class LinkOfflineDestination {
|
||||
});
|
||||
}
|
||||
|
||||
abstract interface class OfflineRollbackDestination
|
||||
implements LinkOfflineDestination {
|
||||
Future<void> discard(LinkOfflineStored stored);
|
||||
}
|
||||
|
||||
/// The download folder is unavailable (no storage access granted), so no
|
||||
/// song can be saved.
|
||||
class LinkOfflineNoFolder implements Exception {
|
||||
@@ -203,7 +217,7 @@ class _Cancelled implements Exception {
|
||||
const _Cancelled();
|
||||
}
|
||||
|
||||
/// Saves desktop songs to the phone as downloads: the original file goes
|
||||
/// Saves Library originals to this device as downloads: the original file goes
|
||||
/// into the download folder and a history record with the song's tags makes
|
||||
/// it a Library download straight away.
|
||||
class LinkOfflineSaver {
|
||||
@@ -214,10 +228,15 @@ class LinkOfflineSaver {
|
||||
required this.record,
|
||||
required this.temporaryDirectory,
|
||||
this.exists,
|
||||
this.idPrefix = 'link',
|
||||
this.serviceName = service,
|
||||
this.prepareSong,
|
||||
this.historyIdForSong,
|
||||
this.existsOrigin,
|
||||
DateTime Function()? now,
|
||||
}) : _now = now ?? DateTime.now;
|
||||
|
||||
/// The paired desktop the songs come from ([LinkServerRecord.serverId]).
|
||||
/// The source namespace, or the paired desktop's [LinkServerRecord.serverId].
|
||||
final String serverId;
|
||||
|
||||
/// A transport for one [save] run, closed when the run ends.
|
||||
@@ -231,6 +250,11 @@ class LinkOfflineSaver {
|
||||
/// Whether the history record with this id exists and its file is still
|
||||
/// there; such songs are skipped. Without it every song is fetched.
|
||||
final Future<bool> Function(String historyId)? exists;
|
||||
final String idPrefix;
|
||||
final String serviceName;
|
||||
final Future<LinkOfflineSong> Function(LinkOfflineSong song)? prepareSong;
|
||||
final String Function(LinkOfflineSong song)? historyIdForSong;
|
||||
final Future<bool> Function(String origin)? existsOrigin;
|
||||
final DateTime Function() _now;
|
||||
|
||||
static const service = 'Mornye Link';
|
||||
@@ -238,18 +262,25 @@ class LinkOfflineSaver {
|
||||
/// The history id of [songId] (contract section 13.2): the same song
|
||||
/// saved again replaces its record.
|
||||
String historyId(String songId) =>
|
||||
'link_${sha256.convert(utf8.encode('$serverId/$songId'))}';
|
||||
'${idPrefix}_${sha256.convert(utf8.encode('$serverId/$songId'))}';
|
||||
|
||||
Future<bool> _has(LinkOfflineSong song) async {
|
||||
final exists = this.exists;
|
||||
if (exists == null) return false;
|
||||
try {
|
||||
return await exists(historyId(song.songId));
|
||||
if (await existsOrigin?.call(song.item.filePath) ?? false) return true;
|
||||
} on Object {
|
||||
// Older records can still be found by their stable transfer id.
|
||||
}
|
||||
try {
|
||||
return await exists?.call(_songHistoryId(song)) ?? false;
|
||||
} on Object {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
String _songHistoryId(LinkOfflineSong song) =>
|
||||
historyIdForSong?.call(song) ?? historyId(song.songId);
|
||||
|
||||
static String _extension(LocalLibraryItem item) {
|
||||
final format = item.format?.trim().toLowerCase() ?? '';
|
||||
if (RegExp(r'^[a-z0-9]{1,10}$').hasMatch(format)) return format;
|
||||
@@ -283,20 +314,22 @@ class LinkOfflineSaver {
|
||||
final item = song.item;
|
||||
final saf = stored.storageMode == 'saf';
|
||||
return DownloadHistoryItem(
|
||||
id: historyId(song.songId),
|
||||
id: _songHistoryId(song),
|
||||
trackName: item.trackName,
|
||||
artistName: item.artistName,
|
||||
albumName: item.albumName,
|
||||
albumArtist: item.albumArtist,
|
||||
coverUrl: item.coverPath,
|
||||
filePath: stored.filePath,
|
||||
originFilePath: item.filePath,
|
||||
storageMode: stored.storageMode,
|
||||
downloadTreeUri: saf ? stored.treeUri : null,
|
||||
safRelativeDir: saf ? stored.relativeDir : null,
|
||||
safFileName: saf ? stored.fileName : null,
|
||||
service: service,
|
||||
service: serviceName,
|
||||
downloadedAt: _now(),
|
||||
isrc: item.isrc,
|
||||
spotifyId: item.id,
|
||||
trackNumber: item.trackNumber,
|
||||
totalTracks: item.totalTracks,
|
||||
discNumber: item.discNumber,
|
||||
@@ -362,7 +395,11 @@ class LinkOfflineSaver {
|
||||
),
|
||||
);
|
||||
LinkOfflineOutcome outcome;
|
||||
LinkOfflineStored? published;
|
||||
var recorded = false;
|
||||
try {
|
||||
final prepared = await prepareSong?.call(song) ?? song;
|
||||
checkpoint();
|
||||
await transport.download(
|
||||
song.songId,
|
||||
file,
|
||||
@@ -378,23 +415,39 @@ class LinkOfflineSaver {
|
||||
),
|
||||
);
|
||||
checkpoint();
|
||||
final fileName = fileNameFor(song.item);
|
||||
final fileName = prepared.fileName ?? fileNameFor(song.item);
|
||||
final stored = await destination.store(
|
||||
file,
|
||||
relativeDir: relativeDirFor(song.item),
|
||||
relativeDir: prepared.relativeDir ?? relativeDirFor(song.item),
|
||||
fileName: fileName,
|
||||
mimeType: networkContentType(fileName),
|
||||
);
|
||||
published = stored;
|
||||
await record(_history(song, stored));
|
||||
recorded = true;
|
||||
saved++;
|
||||
outcome = LinkOfflineOutcome.saved;
|
||||
} on LinkOfflineNoFolder {
|
||||
rethrow;
|
||||
} on OfflineCopyAlreadySaved {
|
||||
skipped++;
|
||||
outcome = LinkOfflineOutcome.skipped;
|
||||
} on Object {
|
||||
if (cancel?.cancelled ?? false) break;
|
||||
failed++;
|
||||
outcome = LinkOfflineOutcome.failed;
|
||||
} finally {
|
||||
if (!recorded &&
|
||||
published != null &&
|
||||
destination is OfflineRollbackDestination) {
|
||||
try {
|
||||
await (destination as OfflineRollbackDestination).discard(
|
||||
published,
|
||||
);
|
||||
} catch (_) {
|
||||
// Cleanup must not hide the original persistence failure.
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (await file.exists()) await file.delete();
|
||||
} on FileSystemException {
|
||||
@@ -466,11 +519,26 @@ class LinkSubsonicTransport implements LinkOfflineTransport {
|
||||
/// [LinkOfflineDestination] for the download folder the settings choose:
|
||||
/// Android's storage access tree in `saf` mode, else the download directory
|
||||
/// (through its security-scoped bookmark on iOS), else `Documents/Mornye`.
|
||||
class LinkDownloadFolderDestination implements LinkOfflineDestination {
|
||||
class LinkDownloadFolderDestination implements OfflineRollbackDestination {
|
||||
const LinkDownloadFolderDestination(this.settings);
|
||||
|
||||
final AppSettings settings;
|
||||
|
||||
@override
|
||||
Future<void> discard(LinkOfflineStored stored) async {
|
||||
IosSecurityScopedAccess? access;
|
||||
try {
|
||||
if (Platform.isIOS && settings.downloadDirectoryBookmark.isNotEmpty) {
|
||||
access = await PlatformBridge.startAccessingIosBookmark(
|
||||
settings.downloadDirectoryBookmark,
|
||||
);
|
||||
}
|
||||
await deleteFile(stored.filePath);
|
||||
} finally {
|
||||
if (access != null) await PlatformBridge.stopAccessingIosBookmark(access);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<LinkOfflineStored> store(
|
||||
File file, {
|
||||
|
||||
@@ -118,7 +118,9 @@ class _MusicGapless {
|
||||
}
|
||||
final path = lease?.path ?? await handler._resolveSource(next);
|
||||
if (path == null || !_current(generation)) return;
|
||||
final isCopy = next.isContentUri && lease == null;
|
||||
final isCopy =
|
||||
(next.isContentUri && lease == null) ||
|
||||
handler._sourceCache.ownsPath(path);
|
||||
if (isCopy) _pins.add(path);
|
||||
final volume = await handler._normalizationVolumeFor(
|
||||
path,
|
||||
|
||||
@@ -46,6 +46,7 @@ import 'package:mornye/services/source_metadata_events.dart';
|
||||
import 'package:mornye/services/system_volume_service.dart';
|
||||
import 'package:mornye/utils/desktop_platform.dart';
|
||||
import 'package:mornye/utils/logger.dart';
|
||||
import 'package:mornye/utils/file_access.dart' show fileExists;
|
||||
|
||||
final _log = AppLogger('MusicPlayerRuntime');
|
||||
|
||||
@@ -64,6 +65,7 @@ class PlaybackDependencies {
|
||||
this.readMetadata = PlatformBridge.readFileMetadata,
|
||||
this.readNetworkMetadata = _readNetworkMetadata,
|
||||
this.resolveNetworkSource = _resolveNetworkSource,
|
||||
this.offlineCopy = _offlineCopy,
|
||||
this.networkSourceReachable = _networkSourceReachable,
|
||||
this.recoverMissingFile = _recoverMissingFile,
|
||||
this.recoverMovedDownload = _recoverMovedDownload,
|
||||
@@ -110,6 +112,7 @@ class PlaybackDependencies {
|
||||
readMetadata;
|
||||
final Future<Map<String, dynamic>> Function(String) readNetworkMetadata;
|
||||
final Future<String> Function(String) resolveNetworkSource;
|
||||
final Future<String?> Function(String) offlineCopy;
|
||||
|
||||
/// Whether a `network://` Library song can play now, as autoplay asks
|
||||
/// before queueing it.
|
||||
@@ -202,6 +205,12 @@ class PlaybackDependencies {
|
||||
NetworkMetadataService.instance.read(source);
|
||||
static Future<String> _resolveNetworkSource(String source) =>
|
||||
NetworkStorageService.instance.resolve(source);
|
||||
static Future<String?> _offlineCopy(String source) async {
|
||||
final row = await HistoryDatabase.instance.findOfflineCopy(source);
|
||||
final path = row?['filePath'] as String?;
|
||||
return path != null && await fileExists(path) ? path : null;
|
||||
}
|
||||
|
||||
static Future<bool> _networkSourceReachable(String source) =>
|
||||
NetworkStorageService.instance.reachable(source);
|
||||
static Future<String?> _recoverMissingFile(String path) async {
|
||||
|
||||
@@ -45,6 +45,7 @@ import 'package:mornye/utils/playback_artwork.dart';
|
||||
import 'package:mornye/services/downloaded_embedded_cover_resolver.dart';
|
||||
import 'package:mornye/utils/logger.dart';
|
||||
import 'package:mornye/services/playable_media.dart';
|
||||
import 'package:mornye/utils/file_access.dart' show fileExists;
|
||||
|
||||
export 'autoplay_signal.dart';
|
||||
export 'music_player_runtime.dart';
|
||||
@@ -1166,6 +1167,17 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
|
||||
Future<String?> _resolveSource(PlayableMedia media) async {
|
||||
if (media.source.startsWith('network://')) {
|
||||
try {
|
||||
final copy = await _dependencies.offlineCopy(media.source);
|
||||
if (copy != null) {
|
||||
final resolved = copy.startsWith('content://')
|
||||
? await _sourceCache.resolve(copy)
|
||||
: copy;
|
||||
if (resolved != null) return resolved;
|
||||
}
|
||||
} catch (_) {
|
||||
// An unavailable local copy leaves the server source usable.
|
||||
}
|
||||
try {
|
||||
return await _dependencies.resolveNetworkSource(media.source);
|
||||
} catch (_) {
|
||||
@@ -1173,6 +1185,15 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (media.originSource case final origin?) {
|
||||
if (!await fileExists(media.source)) {
|
||||
try {
|
||||
return await _dependencies.resolveNetworkSource(origin);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!media.isContentUri) {
|
||||
if (_runtime.arrivingFile(media.source) case final arriving?) {
|
||||
return arriving.url;
|
||||
@@ -1187,7 +1208,13 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return _sourceCache.resolve(media.source);
|
||||
final resolved = await _sourceCache.resolve(media.source);
|
||||
if (resolved == null && media.originSource != null) {
|
||||
try {
|
||||
return await _dependencies.resolveNetworkSource(media.originSource!);
|
||||
} catch (_) {}
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
Future<void> _cleanupPendingResolvedPaths() => _sourceCache.releaseUnpinned();
|
||||
@@ -1665,6 +1692,19 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
}) async {
|
||||
await _cast.applyOutput();
|
||||
if (!_isCurrentPlayRequest(generation, media)) return;
|
||||
if (media.source.startsWith('network://')) {
|
||||
try {
|
||||
final copy = await _dependencies.offlineCopy(media.source);
|
||||
if (!_isCurrentPlayRequest(generation, media)) return;
|
||||
if (copy != null) {
|
||||
_relocateQueuedSource(media.source, copy, origin: media.source);
|
||||
media = _media[_index];
|
||||
}
|
||||
} catch (_) {
|
||||
// Keep the original source when a local lookup is unavailable.
|
||||
}
|
||||
}
|
||||
if (!_isCurrentPlayRequest(generation, media)) return;
|
||||
_pausedByInterruption = false;
|
||||
_interruptionActive = false;
|
||||
_userPaused = startPaused;
|
||||
@@ -2387,7 +2427,11 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
Future<void> playMediaItem(MediaItem mediaItem) =>
|
||||
playFromMediaId(mediaItem.id);
|
||||
|
||||
void _relocateQueuedSource(String previous, String replacement) {
|
||||
void _relocateQueuedSource(
|
||||
String previous,
|
||||
String replacement, {
|
||||
String? origin,
|
||||
}) {
|
||||
_normalizationCache.invalidate(previous);
|
||||
unawaited(_sourceCache.invalidate(previous));
|
||||
for (var i = 0; i < _media.length; i++) {
|
||||
@@ -2396,10 +2440,16 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
_media[i] = PlayableMedia.fromJson({
|
||||
...media.toJson(),
|
||||
'source': replacement,
|
||||
'originSource': ?origin,
|
||||
})!;
|
||||
final old = _queueItems[i];
|
||||
final next = old.copyWith(
|
||||
extras: {...?old.extras, 'source': replacement, 'resolvedSource': null},
|
||||
extras: {
|
||||
...?old.extras,
|
||||
'source': replacement,
|
||||
'resolvedSource': null,
|
||||
'originSource': ?origin,
|
||||
},
|
||||
);
|
||||
_queueItems[i] = next;
|
||||
final original = _originalQueueOrder?.indexWhere(
|
||||
@@ -2516,6 +2566,11 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
Future<void> onSourceDeleted(String source) async {
|
||||
final target = source.trim();
|
||||
if (_disposed || target.isEmpty) return;
|
||||
if (target.startsWith('network://')) {
|
||||
try {
|
||||
if (await _dependencies.offlineCopy(target) != null) return;
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
final hadPendingResolution = await _sourceCache.invalidate(target);
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:mornye/models/library_database_models.dart';
|
||||
import 'package:mornye/models/unified_library_item.dart';
|
||||
import 'package:mornye/services/folder_path_template.dart';
|
||||
import 'package:mornye/services/link/features/link_save_offline.dart';
|
||||
import 'package:mornye/services/network_storage_service.dart';
|
||||
|
||||
String networkOfflineHistoryId(String origin) =>
|
||||
'offline_${sha256.convert(utf8.encode('network/$origin'))}';
|
||||
|
||||
bool canSaveNetworkOfflineSource(String source) {
|
||||
final uri = Uri.tryParse(source);
|
||||
return uri?.scheme == 'network' &&
|
||||
uri!.host.isNotEmpty &&
|
||||
uri.userInfo.isEmpty &&
|
||||
!uri.hasPort &&
|
||||
!uri.hasQuery &&
|
||||
!uri.hasFragment &&
|
||||
NetworkStorageService.instance.virtualFor(uri.host) == null;
|
||||
}
|
||||
|
||||
/// A stable origin, never title/artist matching. Download history supplies the
|
||||
/// preferred local copy while the scanned server row remains independently owned.
|
||||
String? networkOfflineOrigin(UnifiedLibraryItem item) {
|
||||
final origin = item.historyItem?.originFilePath ?? item.filePath;
|
||||
return canSaveNetworkOfflineSource(origin) ? origin : null;
|
||||
}
|
||||
|
||||
List<LinkOfflineSong> networkOfflineSongs(Iterable<UnifiedLibraryItem> items) {
|
||||
final origins = <String>{};
|
||||
return [
|
||||
for (final item in items)
|
||||
if (networkOfflineOrigin(item) case final origin?)
|
||||
if (origins.add(origin))
|
||||
LinkOfflineSong(
|
||||
songId: origin,
|
||||
item:
|
||||
item.localItem ??
|
||||
LocalLibraryItem.fromJson({
|
||||
...item.historyItem!.toJson(),
|
||||
'id': 'network_${sha256.convert(utf8.encode(origin))}',
|
||||
'filePath': origin,
|
||||
'coverPath': item.coverUrl ?? item.localCoverPath,
|
||||
'scannedAt': item.addedAt.toIso8601String(),
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// Relative paths are decoded once by Uri, then sanitized component by
|
||||
/// component. A server path must never escape the selected download folder.
|
||||
({String relativeDir, String fileName}) networkOfflineLayout(
|
||||
LocalLibraryItem item,
|
||||
String? path,
|
||||
) {
|
||||
if (path == null || path.trim().isEmpty) {
|
||||
return (
|
||||
relativeDir: LinkOfflineSaver.relativeDirFor(item),
|
||||
fileName: LinkOfflineSaver.fileNameFor(item),
|
||||
);
|
||||
}
|
||||
final parts = path
|
||||
.replaceAll('\\', '/')
|
||||
.split('/')
|
||||
.where((part) => part.isNotEmpty)
|
||||
.toList();
|
||||
if (parts.isEmpty || parts.any((part) => part == '.' || part == '..')) {
|
||||
throw const FormatException('Invalid original file path');
|
||||
}
|
||||
final safe = parts.map(FolderPathTemplate.sanitizeComponent).toList();
|
||||
return (
|
||||
relativeDir: safe.take(safe.length - 1).join('/'),
|
||||
fileName: safe.last,
|
||||
);
|
||||
}
|
||||
|
||||
class NetworkOfflineTransport implements LinkOfflineTransport {
|
||||
NetworkOfflineTransport({NetworkStorageService? storage})
|
||||
: downloadFile = NetworkFileDownload(
|
||||
storage ?? NetworkStorageService.instance,
|
||||
);
|
||||
|
||||
final NetworkFileDownload downloadFile;
|
||||
|
||||
Future<LinkOfflineSong> prepare(LinkOfflineSong song) async {
|
||||
final path = await downloadFile.originalPath(song.songId);
|
||||
final layout = networkOfflineLayout(song.item, path);
|
||||
return LinkOfflineSong(
|
||||
item: song.item,
|
||||
songId: song.songId,
|
||||
relativeDir: layout.relativeDir,
|
||||
fileName: layout.fileName,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> download(
|
||||
String songId,
|
||||
File output, {
|
||||
required void Function() checkpoint,
|
||||
required void Function(int received, int? total) progress,
|
||||
}) => downloadFile.download(
|
||||
songId,
|
||||
output,
|
||||
checkpoint: checkpoint,
|
||||
progress: progress,
|
||||
);
|
||||
|
||||
@override
|
||||
void close() => downloadFile.close();
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
part of 'network_storage_service.dart';
|
||||
|
||||
/// One cancellable, original-file download. HTTP connections and SMB leases
|
||||
/// belong to this transfer, so cancellation never interrupts another reader.
|
||||
class NetworkFileDownload {
|
||||
NetworkFileDownload(this.storage);
|
||||
|
||||
final NetworkStorageService storage;
|
||||
HttpClient? _http;
|
||||
NetworkSmbClient? _smb;
|
||||
bool _closed = false;
|
||||
|
||||
void close() {
|
||||
_closed = true;
|
||||
_http?.close(force: true);
|
||||
unawaited(_smb?.close());
|
||||
}
|
||||
|
||||
void _check() {
|
||||
if (_closed) throw StateError('Offline download cancelled');
|
||||
}
|
||||
|
||||
/// A Subsonic catalog may expose the original relative file path. Other
|
||||
/// protocols already encode that path in their network source.
|
||||
Future<String?> originalPath(String source) async {
|
||||
final (:host, :path) = NetworkStorageService._sourceParts(source);
|
||||
final connection = await storage.connection(host);
|
||||
if (connection.protocol != NetworkProtocol.subsonic) {
|
||||
if (path.isEmpty && connection.protocol == NetworkProtocol.http) {
|
||||
return connection.root.pathSegments.lastOrNull;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
_check();
|
||||
final client = storage.openSubsonic(connection);
|
||||
_http = client._http;
|
||||
try {
|
||||
final song = await client.song(path);
|
||||
_check();
|
||||
return song.data['path'] as String?;
|
||||
} finally {
|
||||
client.close();
|
||||
_http = null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> download(
|
||||
String source,
|
||||
File output, {
|
||||
required void Function() checkpoint,
|
||||
required void Function(int received, int? total) progress,
|
||||
}) async {
|
||||
_check();
|
||||
checkpoint();
|
||||
final (:host, :path) = NetworkStorageService._sourceParts(source);
|
||||
final connection = await storage._readyConnection(host, path);
|
||||
_check();
|
||||
final Stream<List<int>> bytes;
|
||||
final int? total;
|
||||
try {
|
||||
if (connection.protocol == NetworkProtocol.smb) {
|
||||
final smb = await storage._smb(
|
||||
connection,
|
||||
networkTarget(connection, path),
|
||||
shared: true,
|
||||
);
|
||||
_smb = smb;
|
||||
_check();
|
||||
final stat = await smb.stat().timeout(NetworkStorageService.timeout);
|
||||
if (!stat.isFile) throw const HttpException('Not an audio file');
|
||||
total = stat.size;
|
||||
bytes = smb.read(0, stat.size).timeout(NetworkStorageService.timeout);
|
||||
} else {
|
||||
final client = storage._client();
|
||||
_http = client;
|
||||
final subsonic = connection.protocol == NetworkProtocol.subsonic;
|
||||
final target = subsonic
|
||||
? _subsonicTarget(connection, 'download', {
|
||||
'id':
|
||||
subsonicSongIdFromPath(path) ??
|
||||
(throw const FormatException('Expected a song')),
|
||||
})
|
||||
: networkTarget(connection, path);
|
||||
final response = await storage._request(
|
||||
client,
|
||||
connection,
|
||||
'GET',
|
||||
target,
|
||||
);
|
||||
final mime = response.headers.contentType?.mimeType ?? '';
|
||||
if (response.statusCode != HttpStatus.ok ||
|
||||
mime.startsWith('text/') ||
|
||||
const {'application/json', 'application/xml'}.contains(mime)) {
|
||||
throw HttpException(
|
||||
'Audio download unavailable (${response.statusCode})',
|
||||
);
|
||||
}
|
||||
total = response.contentLength < 0 ? null : response.contentLength;
|
||||
bytes = response.timeout(NetworkStorageService.timeout);
|
||||
}
|
||||
var received = 0;
|
||||
final writer = output.openWrite();
|
||||
try {
|
||||
await writer.addStream(
|
||||
bytes.map((chunk) {
|
||||
_check();
|
||||
checkpoint();
|
||||
received += chunk.length;
|
||||
progress(received, total);
|
||||
return chunk;
|
||||
}),
|
||||
);
|
||||
_check();
|
||||
checkpoint();
|
||||
if (received == 0 || (total != null && received != total)) {
|
||||
throw const HttpException('Audio download ended early');
|
||||
}
|
||||
} finally {
|
||||
await writer.close();
|
||||
}
|
||||
} on HttpException catch (error) {
|
||||
// Request URLs can contain credentials. Never forward those URLs.
|
||||
throw HttpException(error.message);
|
||||
} finally {
|
||||
_http?.close(force: true);
|
||||
_http = null;
|
||||
await _smb?.close();
|
||||
_smb = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ part 'network_storage_upload.dart';
|
||||
part 'network_storage_delete.dart';
|
||||
part 'network_storage_edit.dart';
|
||||
part 'network_storage_subsonic.dart';
|
||||
part 'network_storage_download.dart';
|
||||
|
||||
typedef _SmbListingInput = ({
|
||||
List<({String name, bool directory, int size, int modifiedTime})> files,
|
||||
|
||||
@@ -13,6 +13,7 @@ import 'package:mornye/utils/string_utils.dart';
|
||||
class PlayableMedia {
|
||||
final String id;
|
||||
final String source;
|
||||
final String? originSource;
|
||||
final String title;
|
||||
final String artist;
|
||||
final String album;
|
||||
@@ -31,6 +32,7 @@ class PlayableMedia {
|
||||
const PlayableMedia({
|
||||
required this.id,
|
||||
required this.source,
|
||||
this.originSource,
|
||||
required this.title,
|
||||
required this.artist,
|
||||
this.album = '',
|
||||
@@ -60,6 +62,7 @@ class PlayableMedia {
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'source': source,
|
||||
if (originSource != null) 'originSource': originSource,
|
||||
'title': title,
|
||||
'artist': artist,
|
||||
'album': album,
|
||||
@@ -104,6 +107,7 @@ class PlayableMedia {
|
||||
return PlayableMedia(
|
||||
id: id,
|
||||
source: source,
|
||||
originSource: json['originSource'] as String?,
|
||||
title: json['title'] as String? ?? '',
|
||||
artist: json['artist'] as String? ?? '',
|
||||
album: json['album'] as String? ?? '',
|
||||
@@ -161,6 +165,7 @@ class PlayableMedia {
|
||||
: null,
|
||||
extras: {
|
||||
'source': source,
|
||||
if (originSource != null) 'originSource': originSource,
|
||||
if (displayMetadata.isNotEmpty) 'displayMetadata': displayMetadata,
|
||||
if (resolvedSource != null && resolvedSource.isNotEmpty)
|
||||
'resolvedSource': resolvedSource,
|
||||
@@ -214,6 +219,7 @@ PlayableMedia playableFromHistory(DownloadHistoryItem item) {
|
||||
return PlayableMedia(
|
||||
id: item.id,
|
||||
source: item.filePath,
|
||||
originSource: item.originFilePath,
|
||||
title: item.trackName,
|
||||
artist: item.artistName,
|
||||
album: item.albumName,
|
||||
|
||||
@@ -714,7 +714,10 @@ class LibraryShadowSnapshot {
|
||||
..execute('DROP TABLE IF EXISTS temp.library_shadowed_next')
|
||||
..execute(
|
||||
'CREATE TEMP TABLE library_shadowed_next AS '
|
||||
'${_shadowPairsSql(fromHistory: historyRows * 2 < libraryRows)}',
|
||||
'${_shadowPairsSql(fromHistory: historyRows * 2 < libraryRows)} '
|
||||
'UNION SELECT l.id AS item_id, h.id AS history_id '
|
||||
'FROM history_db.history h JOIN library l '
|
||||
'ON l.file_path = h.origin_file_path',
|
||||
)
|
||||
..execute('DROP TABLE IF EXISTS $libraryShadowTable')
|
||||
..execute(
|
||||
|
||||
@@ -654,6 +654,7 @@ class AlbumPlayActions extends StatelessWidget {
|
||||
required this.onShuffle,
|
||||
this.isPlaying = false,
|
||||
this.onAddToPlaylist,
|
||||
this.onDownload,
|
||||
});
|
||||
|
||||
final String playLabel;
|
||||
@@ -664,6 +665,7 @@ class AlbumPlayActions extends StatelessWidget {
|
||||
|
||||
/// Desktop only: a round "+" after Play that adds the songs to a playlist.
|
||||
final VoidCallback? onAddToPlaylist;
|
||||
final VoidCallback? onDownload;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -673,6 +675,14 @@ class AlbumPlayActions extends StatelessWidget {
|
||||
if (context.isMornye) {
|
||||
return Row(
|
||||
children: [
|
||||
if (onDownload != null) ...[
|
||||
HeaderCircleButton(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
tooltip: context.l10n.offlineSave,
|
||||
onPressed: onDownload,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
],
|
||||
Expanded(
|
||||
child: HeaderFilledButton(
|
||||
icon: isPlaying
|
||||
@@ -694,10 +704,16 @@ class AlbumPlayActions extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
return ExpressiveButtonGroup(
|
||||
flexible: const {0},
|
||||
flexible: {onDownload == null ? 0 : 1},
|
||||
spacing: tokens.gapMd,
|
||||
slotWidth: tokens.minTouchTarget,
|
||||
children: [
|
||||
if (onDownload != null)
|
||||
HeaderCircleButton(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
tooltip: context.l10n.offlineSave,
|
||||
onPressed: onDownload,
|
||||
),
|
||||
ExpressiveButton(
|
||||
onPressed: onPlay,
|
||||
icon: AppIcon(isPlaying ? Icons.pause : Icons.play_arrow, size: 20),
|
||||
@@ -731,6 +747,12 @@ class AlbumPlayActions extends StatelessWidget {
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: 10,
|
||||
children: [
|
||||
if (onDownload != null)
|
||||
HeaderCircleButton(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
tooltip: context.l10n.offlineSave,
|
||||
onPressed: onDownload,
|
||||
),
|
||||
HeaderCircleButton(
|
||||
icon: CupertinoIcons.shuffle,
|
||||
tooltip: shuffleTooltip,
|
||||
@@ -758,6 +780,12 @@ class AlbumPlayActions extends StatelessWidget {
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: 8,
|
||||
children: [
|
||||
if (onDownload != null)
|
||||
HeaderCircleButton(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
tooltip: context.l10n.offlineSave,
|
||||
onPressed: onDownload,
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: onPlay,
|
||||
icon: AppIcon(isPlaying ? Icons.pause : Icons.play_arrow, size: 20),
|
||||
|
||||
@@ -26,6 +26,7 @@ import 'package:mornye/widgets/no_scrollbars.dart';
|
||||
import 'package:mornye/widgets/player_artwork.dart';
|
||||
import 'package:mornye/widgets/player_lyrics_section.dart';
|
||||
import 'package:mornye/widgets/player_metadata_title.dart';
|
||||
import 'package:mornye/widgets/playback_source_label.dart';
|
||||
import 'package:mornye/widgets/player_playback_controls.dart';
|
||||
import 'package:mornye/widgets/player_volume_control.dart';
|
||||
|
||||
@@ -458,6 +459,10 @@ class _PlayerColumn extends StatelessWidget {
|
||||
(mornye ? textTheme.bodyMedium : textTheme.titleSmall)
|
||||
?.copyWith(color: colorScheme.onSurfaceVariant),
|
||||
),
|
||||
PlaybackSourceLabel(
|
||||
item: mediaItem,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -6,6 +6,8 @@ import 'package:mornye/providers/music_player_provider.dart';
|
||||
import 'package:mornye/widgets/desktop/context_menu.dart';
|
||||
import 'package:mornye/widgets/desktop/desktop_link_transfer_actions.dart';
|
||||
import 'package:mornye/widgets/playlist_picker_sheet.dart';
|
||||
import 'package:mornye/services/network_offline_saver.dart';
|
||||
import 'package:mornye/widgets/network_offline_actions.dart';
|
||||
|
||||
/// Context menu groups for library files (downloaded or scanned), acting on
|
||||
/// [items]: the selection the menu was opened on.
|
||||
@@ -76,6 +78,17 @@ List<List<ContextMenuAction>> libraryTrackMenuGroups(
|
||||
),
|
||||
],
|
||||
desktopLinkTransferActions(context, ref, items, onDone: onDone),
|
||||
[
|
||||
if (items.any((item) => networkOfflineOrigin(item) != null))
|
||||
ContextMenuAction(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
label: l10n.offlineSave,
|
||||
onSelected: () {
|
||||
onDone?.call();
|
||||
saveNetworkOffline(root, ref, items);
|
||||
},
|
||||
),
|
||||
],
|
||||
[
|
||||
if (onOpenDetails != null && count == 1)
|
||||
ContextMenuAction(
|
||||
@@ -102,10 +115,22 @@ List<List<ContextMenuAction>> libraryTrackMenuGroups(
|
||||
),
|
||||
],
|
||||
[
|
||||
if (items.every((item) => item.historyItem?.originFilePath != null))
|
||||
ContextMenuAction(
|
||||
icon: Icons.cloud_off_outlined,
|
||||
label: l10n.offlineDeleteServer,
|
||||
destructive: true,
|
||||
onSelected: () {
|
||||
onDone?.call();
|
||||
deleteOfflineServerCopies(root, ref, items);
|
||||
},
|
||||
),
|
||||
if (onDelete != null)
|
||||
ContextMenuAction(
|
||||
icon: Icons.delete_outline,
|
||||
label: l10n.selectionDeleteTracksCount(count),
|
||||
label: items.every((item) => item.historyItem?.originFilePath != null)
|
||||
? l10n.offlineRemove
|
||||
: l10n.selectionDeleteTracksCount(count),
|
||||
destructive: true,
|
||||
onSelected: onDelete,
|
||||
),
|
||||
|
||||
@@ -42,6 +42,7 @@ import 'package:mornye/widgets/desktop/track_table.dart';
|
||||
import 'package:mornye/widgets/error_card.dart';
|
||||
import 'package:mornye/widgets/expressive_button.dart';
|
||||
import 'package:mornye/widgets/library_selection_playback_actions.dart';
|
||||
import 'package:mornye/widgets/network_offline_actions.dart';
|
||||
import 'package:mornye/widgets/library_track_selection_bar.dart';
|
||||
import 'package:mornye/widgets/local_library_artwork_builder.dart';
|
||||
import 'package:mornye/widgets/playlist_picker_sheet.dart';
|
||||
@@ -517,6 +518,14 @@ class _LibraryDirectoryViewState extends ConsumerState<LibraryDirectoryView>
|
||||
onPlay: () => _playFolder(folder),
|
||||
onShuffle: () => _playFolder(folder, shuffle: true),
|
||||
onAddToPlaylist: () => _addFolderToPlaylist(folder),
|
||||
onDownload: !folder.key.startsWith('network://')
|
||||
? null
|
||||
: () async {
|
||||
final items = await ref.read(libraryDirectoryItemsLoaderProvider)(
|
||||
folder.allTracks,
|
||||
);
|
||||
if (mounted) await saveNetworkOffline(context, ref, items);
|
||||
},
|
||||
);
|
||||
|
||||
/// The album pages' desktop header: the folder's cover, name and path,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:mornye/l10n/l10n.dart';
|
||||
@@ -7,6 +9,8 @@ import 'package:mornye/utils/desktop_platform.dart';
|
||||
import 'package:mornye/widgets/link/link_actions.dart';
|
||||
import 'package:mornye/widgets/playlist_picker_sheet.dart';
|
||||
import 'package:mornye/widgets/selection_action_button.dart';
|
||||
import 'package:mornye/services/network_offline_saver.dart';
|
||||
import 'package:mornye/widgets/network_offline_actions.dart';
|
||||
|
||||
/// Collection actions stay separate from actions that modify audio files.
|
||||
class LibrarySelectionPlaybackActions extends ConsumerWidget {
|
||||
@@ -24,6 +28,17 @@ class LibrarySelectionPlaybackActions extends ConsumerWidget {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final showPlayer = ref.watch(playerUiEnabledProvider);
|
||||
final actions = <Widget>[
|
||||
if (items.any((item) => networkOfflineOrigin(item) != null))
|
||||
SelectionActionButton(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
label: context.l10n.offlineSave,
|
||||
colorScheme: colors,
|
||||
onPressed: () {
|
||||
final root = Navigator.of(context, rootNavigator: true).context;
|
||||
unawaited(saveNetworkOffline(root, ref, items));
|
||||
onClose();
|
||||
},
|
||||
),
|
||||
SelectionActionButton(
|
||||
icon: Icons.playlist_add,
|
||||
label: context.l10n.collectionAddToPlaylist,
|
||||
|
||||
@@ -15,6 +15,7 @@ import 'package:mornye/widgets/player_compact_bar.dart';
|
||||
import 'package:mornye/widgets/player_gesture_regions.dart';
|
||||
import 'package:mornye/widgets/player_lyrics_controls.dart';
|
||||
import 'package:mornye/widgets/player_metadata_title.dart';
|
||||
import 'package:mornye/widgets/playback_source_label.dart';
|
||||
import 'package:mornye/widgets/player_playback_controls.dart';
|
||||
import 'package:mornye/widgets/player_volume_control.dart';
|
||||
|
||||
@@ -371,6 +372,10 @@ class MaterialPlayerLayout extends StatelessWidget {
|
||||
maxLines: compact ? 1 : 2,
|
||||
),
|
||||
SizedBox(height: compact ? 4 : 6),
|
||||
PlaybackSourceLabel(
|
||||
item: mediaItem,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
Consumer(
|
||||
builder: (context, ref, _) {
|
||||
final track = ref
|
||||
|
||||
@@ -8,6 +8,7 @@ import 'package:mornye/providers/music_player_provider.dart';
|
||||
import 'package:mornye/theme/cover_palette.dart';
|
||||
import 'package:mornye/theme/mornye_theme.dart';
|
||||
import 'package:mornye/widgets/mornye_context_menu.dart';
|
||||
import 'package:mornye/services/network_offline_saver.dart';
|
||||
|
||||
/// Navigation for the title/artist, separate from playback and file actions.
|
||||
class MornyePlayerNavigationMenu extends StatelessWidget {
|
||||
@@ -148,6 +149,16 @@ class MornyePlayerActionsSheet extends ConsumerWidget {
|
||||
context.l10n.linkSaveToPhone,
|
||||
CupertinoIcons.device_phone_portrait,
|
||||
),
|
||||
if (!saveToPhone &&
|
||||
canSaveNetworkOfflineSource(
|
||||
mediaItem.extras?['source']?.toString() ?? '',
|
||||
))
|
||||
_action(
|
||||
context,
|
||||
'networkOffline',
|
||||
context.l10n.offlineSave,
|
||||
CupertinoIcons.arrow_down_circle,
|
||||
),
|
||||
],
|
||||
[
|
||||
_action(
|
||||
|
||||
@@ -20,6 +20,7 @@ import 'package:mornye/widgets/player_gesture_regions.dart';
|
||||
import 'package:mornye/widgets/player_lyrics.dart';
|
||||
import 'package:mornye/widgets/player_lyrics_controls.dart';
|
||||
import 'package:mornye/widgets/player_metadata_title.dart';
|
||||
import 'package:mornye/widgets/playback_source_label.dart';
|
||||
import 'package:mornye/widgets/player_playback_controls.dart';
|
||||
import 'package:mornye/widgets/player_track_swipe.dart';
|
||||
|
||||
@@ -548,6 +549,10 @@ class MornyePlayerLayout extends ConsumerWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
PlaybackSourceLabel(
|
||||
item: mediaItem,
|
||||
color: colorScheme.onSurface.withValues(alpha: 0.72),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:audio_service/audio_service.dart' show MediaItem;
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:mornye/l10n/l10n.dart';
|
||||
import 'package:mornye/models/unified_library_item.dart';
|
||||
import 'package:mornye/models/track.dart';
|
||||
import 'package:mornye/models/library_database_models.dart';
|
||||
import 'package:mornye/providers/download_history_provider.dart';
|
||||
import 'package:mornye/providers/local_library_provider.dart';
|
||||
import 'package:mornye/providers/settings_provider.dart';
|
||||
import 'package:mornye/services/link/features/link_library_lookup.dart';
|
||||
import 'package:mornye/providers/deleted_library_files.dart';
|
||||
import 'package:mornye/services/network_storage_service.dart';
|
||||
import 'package:mornye/utils/file_access.dart' show deleteFile, fileExists;
|
||||
import 'package:mornye/widgets/app_alert_dialog.dart';
|
||||
import 'package:mornye/providers/network_offline_provider.dart';
|
||||
import 'package:mornye/services/network_offline_saver.dart';
|
||||
import 'package:mornye/widgets/album_detail_header.dart';
|
||||
import 'package:mornye/widgets/app_bottom_sheet.dart';
|
||||
import 'package:mornye/widgets/app_progress_indicator.dart';
|
||||
import 'package:mornye/widgets/app_icon.dart';
|
||||
import 'package:mornye/widgets/link/link_library_actions.dart';
|
||||
import 'package:mornye/services/link/link_library_jobs.dart';
|
||||
|
||||
export 'package:mornye/services/network_offline_saver.dart'
|
||||
show canSaveNetworkOfflineSource;
|
||||
|
||||
String offlineDeviceFilterLabel(BuildContext context) =>
|
||||
switch (defaultTargetPlatform) {
|
||||
TargetPlatform.iOS => context.l10n.offlineOnIPhone,
|
||||
TargetPlatform.android => context.l10n.offlineOnPhone,
|
||||
_ => context.l10n.offlineOnDevice,
|
||||
};
|
||||
|
||||
Future<void> savePlayingNetworkOffline(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
MediaItem media,
|
||||
) async {
|
||||
final source = media.extras?['source']?.toString() ?? '';
|
||||
if (!source.startsWith('network://')) return;
|
||||
final history = await ref
|
||||
.read(downloadHistoryProvider.notifier)
|
||||
.getByFilePathAsync(source);
|
||||
if (!context.mounted) return;
|
||||
final local = history == null
|
||||
? await ref.read(localLibraryProvider.notifier).getById(media.id)
|
||||
: null;
|
||||
if (!context.mounted) return;
|
||||
await saveNetworkOffline(context, ref, [
|
||||
if (history != null)
|
||||
UnifiedLibraryItem.fromDownloadHistory(history)
|
||||
else
|
||||
UnifiedLibraryItem.fromLocalLibrary(
|
||||
local ??
|
||||
LocalLibraryItem(
|
||||
id: media.id,
|
||||
filePath: source,
|
||||
trackName: media.title,
|
||||
artistName: media.artist ?? '',
|
||||
albumName: media.album ?? '',
|
||||
coverPath: media.artUri?.toString(),
|
||||
duration: media.duration?.inSeconds,
|
||||
format: media.extras?['format']?.toString(),
|
||||
scannedAt: DateTime.now(),
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
String? offlineAvailabilityLabel(
|
||||
BuildContext context,
|
||||
UnifiedLibraryItem item,
|
||||
) {
|
||||
if (item.historyItem?.originFilePath != null) {
|
||||
return item.historyItem!.originAvailable
|
||||
? context.l10n.offlineServerAndDevice
|
||||
: context.l10n.offlineDeviceOnly;
|
||||
}
|
||||
return item.filePath.startsWith('network://')
|
||||
? context.l10n.offlineServerOnly
|
||||
: null;
|
||||
}
|
||||
|
||||
Future<void> deleteOfflineServerCopies(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
List<UnifiedLibraryItem> items,
|
||||
) async {
|
||||
final origins = {
|
||||
for (final item in items)
|
||||
if (item.historyItem?.originFilePath case final String origin) origin,
|
||||
};
|
||||
if (origins.isEmpty) return;
|
||||
for (final item in items) {
|
||||
if (!await fileExists(item.filePath)) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(context.l10n.offlineCopyUnavailable)),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
final container = ProviderScope.containerOf(context, listen: false);
|
||||
final originalItems = [
|
||||
for (final item in items)
|
||||
if (item.historyItem case final history?
|
||||
when history.originFilePath != null)
|
||||
UnifiedLibraryItem.fromLocalLibrary(
|
||||
LocalLibraryItem.fromJson({
|
||||
...history.toJson(),
|
||||
'filePath': history.originFilePath,
|
||||
'coverPath': history.coverUrl,
|
||||
'scannedAt': history.downloadedAt.toIso8601String(),
|
||||
}),
|
||||
),
|
||||
];
|
||||
if (hasLinkLibrarySongs(container, originalItems)) {
|
||||
await runLinkLibraryAction(
|
||||
context,
|
||||
container,
|
||||
originalItems,
|
||||
LinkLibraryAction.delete,
|
||||
);
|
||||
return;
|
||||
}
|
||||
final storage = NetworkStorageService.instance;
|
||||
for (final origin in origins) {
|
||||
if (!await storage.canDeleteFile(origin)) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(context.l10n.offlineServerReadOnly)),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!context.mounted ||
|
||||
!await showAppConfirmDialog(
|
||||
context,
|
||||
title: context.l10n.offlineDeleteServer,
|
||||
message: context.l10n.offlineDeleteServerMessage,
|
||||
confirmLabel: context.l10n.dialogDelete,
|
||||
destructive: true,
|
||||
cancelIsDefault: true,
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
final deleted = <String>[];
|
||||
for (final origin in origins) {
|
||||
try {
|
||||
if (await deleteFile(origin)) deleted.add(origin);
|
||||
} catch (_) {
|
||||
// Keep failed sources indexed; never touch the independent local path.
|
||||
}
|
||||
}
|
||||
await removeDeletedLibraryFileEntries(container, deleted);
|
||||
if (deleted.isNotEmpty) {
|
||||
await container.read(downloadHistoryProvider.notifier).reloadFromStorage();
|
||||
}
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
deleted.length == origins.length
|
||||
? context.l10n.snackbarDeletedTracks(deleted.length)
|
||||
: context.l10n.snackbarDeleteTracksFailed(
|
||||
origins.length - deleted.length,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveNetworkOffline(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
List<UnifiedLibraryItem> items,
|
||||
) async {
|
||||
final controller = ref.read(networkOfflineProvider.notifier);
|
||||
final root = Navigator.of(context, rootNavigator: true).context;
|
||||
if (ref.read(networkOfflineProvider) == null) {
|
||||
if (!items.any((item) => networkOfflineOrigin(item) != null)) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(context.l10n.offlineNoSongs)));
|
||||
return;
|
||||
}
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final l10n = context.l10n;
|
||||
unawaited(() async {
|
||||
try {
|
||||
final result = await controller.save(items);
|
||||
if (result != null && messenger.mounted) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
result.cancelled
|
||||
? l10n.linkSaveToPhoneCancelled
|
||||
: l10n.offlineResult(
|
||||
result.saved,
|
||||
result.skipped,
|
||||
result.failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
if (messenger.mounted) {
|
||||
messenger.showSnackBar(SnackBar(content: Text(l10n.offlineFailed)));
|
||||
}
|
||||
}
|
||||
}());
|
||||
}
|
||||
if (!root.mounted) return;
|
||||
await showAppBottomSheet<void>(
|
||||
context: root,
|
||||
useRootNavigator: true,
|
||||
title: root.l10n.offlineSaving,
|
||||
builder: (_) => const _OfflineProgress(),
|
||||
);
|
||||
}
|
||||
|
||||
class _OfflineProgress extends ConsumerStatefulWidget {
|
||||
const _OfflineProgress();
|
||||
|
||||
@override
|
||||
ConsumerState<_OfflineProgress> createState() => _OfflineProgressState();
|
||||
}
|
||||
|
||||
class _OfflineProgressState extends ConsumerState<_OfflineProgress> {
|
||||
bool _closing = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final progress = ref.watch(networkOfflineProvider);
|
||||
if (progress == null && !_closing) {
|
||||
_closing = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && ModalRoute.of(context)?.isCurrent == true) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
});
|
||||
}
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
progress?.title ?? '',
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
AppProgressIndicator.linear(value: progress?.fraction),
|
||||
const SizedBox(height: 8),
|
||||
Text('${progress?.done ?? 0} / ${progress?.total ?? 0}'),
|
||||
const SizedBox(height: 16),
|
||||
AppSheetOption(
|
||||
title: Text(context.l10n.dialogCancel),
|
||||
onTap: () => ref.read(networkOfflineProvider.notifier).cancel(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NetworkOfflineButton extends ConsumerWidget {
|
||||
const NetworkOfflineButton({super.key, required this.items});
|
||||
final List<UnifiedLibraryItem> items;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
if (!items.any((item) => networkOfflineOrigin(item) != null)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return HeaderCircleButton(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
tooltip: context.l10n.offlineSave,
|
||||
onPressed: () => saveNetworkOffline(context, ref, items),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NetworkOfflineTracksButton extends ConsumerWidget {
|
||||
const NetworkOfflineTracksButton({super.key, required this.tracks});
|
||||
final List<Track> tracks;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) => HeaderCircleButton(
|
||||
icon: Icons.download_for_offline_outlined,
|
||||
tooltip: context.l10n.offlineSave,
|
||||
onPressed: () async {
|
||||
final items = await linkLibraryItemsFor(
|
||||
tracks,
|
||||
includeLocal: ref.read(settingsProvider).localLibraryEnabled,
|
||||
);
|
||||
if (context.mounted) {
|
||||
await saveNetworkOffline(context, ref, items);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class OfflineAvailabilityCover extends StatelessWidget {
|
||||
const OfflineAvailabilityCover({
|
||||
super.key,
|
||||
required this.item,
|
||||
required this.child,
|
||||
});
|
||||
final UnifiedLibraryItem item;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final label = offlineAvailabilityLabel(context, item);
|
||||
if (label == null) return child;
|
||||
final local = item.historyItem?.originFilePath != null;
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
return Tooltip(
|
||||
message: label,
|
||||
child: Stack(
|
||||
children: [
|
||||
child,
|
||||
PositionedDirectional(
|
||||
bottom: 0,
|
||||
end: 0,
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surfaceContainerHigh,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(2),
|
||||
child: AppIcon.adaptive(
|
||||
local ? Icons.offline_pin_outlined : Icons.cloud_outlined,
|
||||
size: 14,
|
||||
color: colors.onSurface,
|
||||
semanticLabel: label,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'package:audio_service/audio_service.dart' show MediaItem;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:mornye/l10n/l10n.dart';
|
||||
import 'package:mornye/services/link/link_source_names.dart';
|
||||
import 'package:mornye/services/network_storage_service.dart';
|
||||
|
||||
final _sourceNameProvider = FutureProvider.family<String?, String>((
|
||||
ref,
|
||||
id,
|
||||
) async {
|
||||
try {
|
||||
return (await NetworkStorageService.instance.connection(id)).name;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
/// Describes the file actually opened, including an offline copy preferred
|
||||
/// over a network source already in the queue.
|
||||
class PlaybackSourceLabel extends ConsumerWidget {
|
||||
const PlaybackSourceLabel({super.key, required this.item, this.color});
|
||||
final MediaItem item;
|
||||
final Color? color;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final source = item.extras?['source']?.toString() ?? '';
|
||||
final origin = item.extras?['originSource']?.toString();
|
||||
final network = source.startsWith('network://') ? source : origin;
|
||||
if (network == null) return const SizedBox.shrink();
|
||||
final resolved = item.extras?['resolvedSource']?.toString() ?? source;
|
||||
final local = !const {
|
||||
'network',
|
||||
'http',
|
||||
'https',
|
||||
}.contains(Uri.tryParse(resolved)?.scheme);
|
||||
var label = context.l10n.offlinePlayingLocal;
|
||||
if (!local) {
|
||||
final host = Uri.tryParse(network)?.host ?? '';
|
||||
final name =
|
||||
ref.watch(linkSourceNamesProvider)[host] ??
|
||||
ref.watch(_sourceNameProvider(host)).value ??
|
||||
host;
|
||||
label = context.l10n.offlineStreaming(name);
|
||||
}
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(color: color),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ const COLUMNS: &[(&str, &str)] = &[
|
||||
("albumArtist", "album_artist"),
|
||||
("coverUrl", "cover_url"),
|
||||
("filePath", "file_path"),
|
||||
("originFilePath", "origin_file_path"),
|
||||
("storageMode", "storage_mode"),
|
||||
("downloadTreeUri", "download_tree_uri"),
|
||||
("safRelativeDir", "saf_relative_dir"),
|
||||
@@ -89,10 +90,10 @@ fn open(request: &Value, writable: bool) -> Result<Connection, String> {
|
||||
let version: i64 = db
|
||||
.pragma_query_value(None, "user_version", |row| row.get(0))
|
||||
.map_err(|e| err("History schema", e))?;
|
||||
// v17 refreshes path identities without changing History columns.
|
||||
if version != 17 && version != 16 {
|
||||
// v18 adds the independent offline copy's network origin.
|
||||
if version != 18 && version != 17 && version != 16 {
|
||||
return Err(format!(
|
||||
"History schema v{version} is incompatible with native v16/v17"
|
||||
"History schema v{version} is incompatible with native v16/v17/v18"
|
||||
));
|
||||
}
|
||||
db.execute_batch("PRAGMA recursive_triggers=ON; PRAGMA synchronous=NORMAL;")
|
||||
|
||||
@@ -149,11 +149,35 @@ impl Fixture {
|
||||
fn backup_replace_round_trip_preserves_flags_dates_keys_order_and_fts() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.restore(&[track("old")], 1, &|| Ok(())).unwrap();
|
||||
fixture.db.execute_batch("PRAGMA user_version=17").unwrap();
|
||||
fixture.db.execute_batch("PRAGMA user_version=18").unwrap();
|
||||
let mut saved = track("a");
|
||||
saved["originFilePath"] = "network://nas/Artist/Album/a.flac".into();
|
||||
fixture
|
||||
.restore(&[track("b"), track("a")], 2, &|| Ok(()))
|
||||
.restore(&[track("b"), saved], 2, &|| Ok(()))
|
||||
.unwrap();
|
||||
assert_eq!(fixture.ids(), ["a", "b"]);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.db
|
||||
.query_row(
|
||||
"SELECT origin_file_path FROM history WHERE id='a'",
|
||||
[],
|
||||
|row| row.get::<_, String>(0)
|
||||
)
|
||||
.unwrap(),
|
||||
"network://nas/Artist/Album/a.flac"
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.db
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM history_path_keys WHERE path_key LIKE 'network://%'",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0)
|
||||
)
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
assert!(
|
||||
fixture
|
||||
.db
|
||||
|
||||
@@ -387,9 +387,9 @@ fn prune(request: &Value, check: Check<'_>) -> Result<Value, String> {
|
||||
let version: i64 = db
|
||||
.pragma_query_value(None, "user_version", |row| row.get(0))
|
||||
.map_err(|e| e.to_string())?;
|
||||
if version != 17 {
|
||||
if version != 17 && version != 18 {
|
||||
return Err(format!(
|
||||
"Cover reference schema v{version} is incompatible with native v17"
|
||||
"Cover reference schema v{version} is incompatible with native v17/v18"
|
||||
));
|
||||
}
|
||||
Some(db)
|
||||
|
||||
@@ -41,6 +41,14 @@ class _StoredHistory implements HistoryDatabase {
|
||||
@override
|
||||
Future<Map<String, dynamic>?> findByFilePath(String filePath) async => null;
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>?> findOfflineCopy(String origin) async {
|
||||
for (final row in rows) {
|
||||
if (row.originFilePath == origin) return row.toJson();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> upsert(Map<String, dynamic> json) async {
|
||||
final item = DownloadHistoryItem.fromJson(json);
|
||||
@@ -109,6 +117,41 @@ void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
test(
|
||||
'concurrent offline saves keep one row and retain its identity after a missing copy',
|
||||
() async {
|
||||
final directory = await Directory.systemTemp.createTemp(
|
||||
'history-offline-',
|
||||
);
|
||||
addTearDown(() => directory.delete(recursive: true));
|
||||
final first = await File(
|
||||
'${directory.path}/first.flac',
|
||||
).writeAsBytes([1]);
|
||||
final second = await File(
|
||||
'${directory.path}/second.flac',
|
||||
).writeAsBytes([2]);
|
||||
final db = _StoredHistory();
|
||||
final loaded = await _loadedHistory(db);
|
||||
final a = _item(
|
||||
1,
|
||||
).copyWith(filePath: first.path, originFilePath: 'network://nas/a.flac');
|
||||
final b = _item(
|
||||
2,
|
||||
).copyWith(filePath: second.path, originFilePath: 'network://nas/a.flac');
|
||||
final firstSave = loaded.notifier.saveOfflineCopy(a);
|
||||
final secondSave = loaded.notifier.saveOfflineCopy(b);
|
||||
await firstSave;
|
||||
await expectLater(secondSave, throwsA(isA<OfflineCopyAlreadySaved>()));
|
||||
expect(db.rows, hasLength(1));
|
||||
expect(db.rows.single.filePath, first.path);
|
||||
await first.delete();
|
||||
await loaded.notifier.saveOfflineCopy(b);
|
||||
expect(db.rows, hasLength(1));
|
||||
expect(db.rows.single.id, a.id);
|
||||
expect(db.rows.single.filePath, second.path);
|
||||
},
|
||||
);
|
||||
|
||||
test('disposed startup skips the deferred history load', () async {
|
||||
final db = _StoredHistory();
|
||||
final container = ProviderContainer(
|
||||
@@ -257,6 +300,7 @@ void main() {
|
||||
albumArtist: 'Album artist',
|
||||
coverUrl: 'https://example.com/cover.jpg',
|
||||
filePath: '/music/song.flac',
|
||||
originFilePath: 'network://nas/Artist/Album/song.flac',
|
||||
storageMode: 'saf',
|
||||
downloadTreeUri: 'content://tree/music',
|
||||
safRelativeDir: 'Artist/Album',
|
||||
|
||||
+21
@@ -8,6 +8,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -46,6 +47,7 @@
|
||||
"album_artist": " Album Artist ",
|
||||
"cover_url": "https://example.test/cover.jpg",
|
||||
"file_path": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"origin_file_path": "network://nas/Artist/Album/Track.flac",
|
||||
"storage_mode": "saf",
|
||||
"download_tree_uri": "content://nas.provider/tree/root",
|
||||
"saf_relative_dir": "Album",
|
||||
@@ -96,6 +98,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -152,6 +155,7 @@
|
||||
"albumArtist": "",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -190,6 +194,7 @@
|
||||
"album_artist": "",
|
||||
"cover_url": "https://example.test/cover.jpg",
|
||||
"file_path": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"origin_file_path": "network://nas/Artist/Album/Track.flac",
|
||||
"storage_mode": "saf",
|
||||
"download_tree_uri": "content://nas.provider/tree/root",
|
||||
"saf_relative_dir": "Album",
|
||||
@@ -240,6 +245,7 @@
|
||||
"albumArtist": "",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -296,6 +302,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -335,6 +342,7 @@
|
||||
"album_artist": " Album Artist ",
|
||||
"cover_url": "https://example.test/cover.jpg",
|
||||
"file_path": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"origin_file_path": "network://nas/Artist/Album/Track.flac",
|
||||
"storage_mode": "saf",
|
||||
"download_tree_uri": "content://nas.provider/tree/root",
|
||||
"saf_relative_dir": "Album",
|
||||
@@ -385,6 +393,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -441,6 +450,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -479,6 +489,7 @@
|
||||
"album_artist": " Album Artist ",
|
||||
"cover_url": "https://example.test/cover.jpg",
|
||||
"file_path": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"origin_file_path": "network://nas/Artist/Album/Track.flac",
|
||||
"storage_mode": "saf",
|
||||
"download_tree_uri": "content://nas.provider/tree/root",
|
||||
"saf_relative_dir": "Album",
|
||||
@@ -529,6 +540,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -585,6 +597,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -623,6 +636,7 @@
|
||||
"album_artist": " Album Artist ",
|
||||
"cover_url": "https://example.test/cover.jpg",
|
||||
"file_path": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"origin_file_path": "network://nas/Artist/Album/Track.flac",
|
||||
"storage_mode": "saf",
|
||||
"download_tree_uri": "content://nas.provider/tree/root",
|
||||
"saf_relative_dir": "Album",
|
||||
@@ -673,6 +687,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -729,6 +744,7 @@
|
||||
"albumArtist": null,
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -767,6 +783,7 @@
|
||||
"album_artist": null,
|
||||
"cover_url": "https://example.test/cover.jpg",
|
||||
"file_path": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"origin_file_path": "network://nas/Artist/Album/Track.flac",
|
||||
"storage_mode": "saf",
|
||||
"download_tree_uri": "content://nas.provider/tree/root",
|
||||
"saf_relative_dir": "Album",
|
||||
@@ -817,6 +834,7 @@
|
||||
"albumArtist": null,
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "content://nas.provider/tree/root/document/Ab%252FC.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -873,6 +891,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "/Music/a%zz.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
@@ -912,6 +931,7 @@
|
||||
"album_artist": " Album Artist ",
|
||||
"cover_url": "https://example.test/cover.jpg",
|
||||
"file_path": "/Music/a%zz.flac",
|
||||
"origin_file_path": "network://nas/Artist/Album/Track.flac",
|
||||
"storage_mode": "saf",
|
||||
"download_tree_uri": "content://nas.provider/tree/root",
|
||||
"saf_relative_dir": "Album",
|
||||
@@ -962,6 +982,7 @@
|
||||
"albumArtist": " Album Artist ",
|
||||
"coverUrl": "https://example.test/cover.jpg",
|
||||
"filePath": "/Music/a%zz.flac",
|
||||
"originFilePath": "network://nas/Artist/Album/Track.flac",
|
||||
"storageMode": "saf",
|
||||
"downloadTreeUri": "content://nas.provider/tree/root",
|
||||
"safRelativeDir": "Album",
|
||||
|
||||
@@ -177,107 +177,107 @@ final _filters =
|
||||
/// Library order, filter or paging SQL changed.
|
||||
const _expectedDigests = <String, String>{
|
||||
'sort:latest':
|
||||
'5f454cc6e3addbb5b29f51e08ef541a84749ed5bcf9da1a22e43d23bd0f923f2',
|
||||
'32ffe03bb221e2fc726157498930566e85940a10bf20aceba69514b433a0e6d5',
|
||||
'sort:oldest':
|
||||
'177aa1bdba1118287dcd6edda7bd0d115d04d0b778f627ea0425b9e5dda6a442',
|
||||
'ba51c4e62b17d822161346ee6ced68794b782fcb5cbafe4fb0e4c08c5f18a4ee',
|
||||
'sort:a-z':
|
||||
'6f8f5ecf435ab9dcfdb8c86e670f52e3c8e1a4bbd800565c84691f98ed720ea4',
|
||||
'6dc7e3f325b8a9f2ae9444234f275fb0567fdb9ff2fcc65dc102645b2bcfe72e',
|
||||
'sort:z-a':
|
||||
'6f1909c35b1a22a1e0881bbbc241125fde2b28803f7bb08435851e26f72ba88a',
|
||||
'8d1361fc81213bf98e8ee6c1375771173f7b3a6f1cc7bc680ae204c0f72c520c',
|
||||
'sort:artist-asc':
|
||||
'8da0fb1dce55964159a5862a7a20889bb186474a70f9595b870f9034b05e577f',
|
||||
'e535993aec4175f1e00d6e74d0d4ee5d29e8b968d50c0c71299f4261ad0805a2',
|
||||
'sort:artist-desc':
|
||||
'abcf7dc4e3b8332471d2f84d34083a08a09b60200932ec40d0418a3ac0ad902c',
|
||||
'60fc7f31e3f897fbccea4a00e41440e2dc5f32b02f54f7af3b5af9ee443912b1',
|
||||
'sort:album-asc':
|
||||
'e906b8567021383055d27a47ace61c85b7723207abb51e95d21a454587a72996',
|
||||
'a987ba7eb7473f3b1548fcae81b762ec2944443fadd3663a5eec23dc262481fc',
|
||||
'sort:album-desc':
|
||||
'0aaabf7f7157d3be3abfa623b4e70108f79b5dff1adf37c5345cadd2f4224a9e',
|
||||
'b990d8b5ef7bf71f731469caf3d7018ac4c023f9c5711e2ea118b34313032c4a',
|
||||
'sort:release-oldest':
|
||||
'ce5b91a0f34a176d920ea5ff5aced295e6c0b0f740349c37b89f6e435240cbeb',
|
||||
'04a5e44291f4f04e2a2c4f1b942d48173fbf7cacf71ffe12dd5d1e3ef9dd1d7d',
|
||||
'sort:release-newest':
|
||||
'b3bda6b40da843ceca124b89618b9815e20592ed853cf58b0b81e8e2a6f1bac9',
|
||||
'63d219f44e5a2c3c67347adbc3635b74c6025c3dd6f35b26bda3612cadcc3417',
|
||||
'sort:genre-asc':
|
||||
'd844ecb66d6d468c4f1332800f2a112df22bb69c2478f9f0b0646a321eb1c96d',
|
||||
'aaae49c02f9eca25ee01161414e899aca00b3a184c1f6cce67c1f431ed89ecd6',
|
||||
'sort:genre-desc':
|
||||
'8d16a3bcfc6471912396d1240de0eab1ef06478a7f4c0d3616bf7c25f7090d82',
|
||||
'a8658b4c0661dd131b9ba5fad68817d4163772453ca727b43506a1a3d91d8675',
|
||||
'sort:size-asc':
|
||||
'f4bdefd7794a3bc8cd57019e5aefc0aef97e60689338c15f86e94381ea8946e6',
|
||||
'85218343e8e68e7c05d84bff284463fee4501e3b804f547b1957b24434dee79e',
|
||||
'sort:size-desc':
|
||||
'9b8841e028660b08d392dc77d64c1822e1008866385688bd57152a8359afb7be',
|
||||
'00ef42759ab1af305bda3c4a1875038b946b181185b1bb4a46fa043460e3c771',
|
||||
'sort:unknown-sort':
|
||||
'5f454cc6e3addbb5b29f51e08ef541a84749ed5bcf9da1a22e43d23bd0f923f2',
|
||||
'32ffe03bb221e2fc726157498930566e85940a10bf20aceba69514b433a0e6d5',
|
||||
'filter:default':
|
||||
'e3f8eeddb2299b73c2865b59d93f347720df749f846e60c0a6c3f794bd197b83',
|
||||
'f8e8b800aa99f603496d38e15d9c4ead288a0e9e4d158f0415e7ca67c7ead00f',
|
||||
'filter:source-downloaded':
|
||||
'0b134efd64358ad588f2390ea2bc57d5a2aafda976e1705ed3516625e6b491a6',
|
||||
'c2153d2bc80e3188864c6bfccd2ec606178d52a8c74a69ce5234e0ba48f92fe3',
|
||||
'filter:source-local':
|
||||
'43f5da5f7084c124f202519ef1633cf964667ca07682ad4929070ee063401121',
|
||||
'ebd56e568a9469ed178e79b067f5a54a133b40b68fe51f497fa2cd2d5a09d7ce',
|
||||
'filter:source-other':
|
||||
'baca88d62f3bcd81f9b513a1daa11647cc1f949971ab18bfa51eb0b8aabe2991',
|
||||
'bc15c152e43c7e7325b105267968792bb786e2b3f1d810b0851b3b4b4022ca25',
|
||||
'filter:no-local':
|
||||
'faade8268d94dc81445ba77c8e1def463109f09366136fac53dd1be9d9855423',
|
||||
'b131db8ad9f9ba235314012f8be51851ec58e98293c97993e8817801cb5748b1',
|
||||
'filter:no-local-source-local':
|
||||
'2f37e8a9acfbb6130cf424745afb972bd0cb930392c8b972cce4382a6d9fe3b9',
|
||||
'fbec44ea7617b9173b666d4b7abccefddb9be67a7e969c0a41a5a8c1b3e9852f',
|
||||
'filter:singles':
|
||||
'acd67fb0d8a21569a99acf442b297ffff2c58d1fab7dfe48f0929421a8b4b15c',
|
||||
'b83b23da96551c86af760c319bf5448efea37de8f5c8d6504f9842bf82801962',
|
||||
'filter:singles-downloaded':
|
||||
'80a4a9998c8b661a8691c03e081e02d2d28d80caf1aed075bdd9cf89b77e291a',
|
||||
'8b3924736eeeb5a4c595b71047f7399dfc5a4991e68dfe7ae206455c6cb5034d',
|
||||
'filter:search':
|
||||
'e855653be9c292d81b1245c28c82b2fc71c4c3bb1572042548552f5f422f152e',
|
||||
'0679a61fe34ab604f1077c1b56521497c8ac2ab25bc6ec144c339b2de90c5002',
|
||||
'filter:album-artist':
|
||||
'22dfba8ce62daa420034585fdae0a4176d10e498b3c93db557f48a73ef3a2680',
|
||||
'bbfb7efcf0e81fb97fabf4b71e2a9069b5e011b6aed9c8c27e92c61682799385',
|
||||
'filter:quality-hires':
|
||||
'8523278e250c9d9a50be1676ad11db2bf5183912e2aac24e8e7c5e874bf9490e',
|
||||
'9670ee9e4a35ca125174faf289e8ee24094d231ec448150cc7710add70ae79af',
|
||||
'filter:quality-cd':
|
||||
'7aa8c2ad040fb9620cc13dccf6f4e436f0a42340fa29095f0fe02e35aff3c2b2',
|
||||
'0fbf399bc35c5c27e6a470094ca11037cabff3c67a42a9fdc8f65ae3ca71c4d1',
|
||||
'filter:quality-lossy':
|
||||
'72aed01e020a72d0f96019316bddc72a2dabd7f5e4894c176f3bfc1ecec5440f',
|
||||
'd29c6608f891d9c7487c4dc275f6ba0b1bf3e33919d1b00494b71484d74b74d9',
|
||||
'filter:format-m4a':
|
||||
'2a8b0782af25d44ce5e79b8cff56d41aaecb281777ca8a99674044a44c47376c',
|
||||
'05059fab1b27d8672b4b345aba216642e9f0f19391b7fb572f234d539d11d903',
|
||||
'filter:format-unknown':
|
||||
'e8835f9a3feaa000eadcb3116dbfcf09e3313b25ff75a2516f11819f81972d99',
|
||||
'634ada18b7e552481383a768afbd2948c177d28c3dccd3607d441c37032161da',
|
||||
'filter:metadata-complete':
|
||||
'e568d9798c828d2a313cc4b7cc740eb0593df095ff95a56837f51f83bad54840',
|
||||
'99036bb9aeaf8cbce22a32d78eda90fc98bb2c7aa5bd1f440a34c80512320e85',
|
||||
'filter:metadata-missing-any':
|
||||
'461ec155fdfe79fee43559815e55369a53509c81e6cbd3d5142aa3ab39a1e2dc',
|
||||
'2c214f254061c8e69caf9992156ba41509027b22ff9b409b23cb03c8477e4883',
|
||||
'filter:metadata-missing-year':
|
||||
'4558bb9d750603622e4584caf1919f48b41b6c349bbc681150c4079b3777991a',
|
||||
'533c5e3e3fed7610951dae2c21c0a43a2c59c93946ecab23e40db15b7de3ead9',
|
||||
'filter:metadata-missing-genre':
|
||||
'8e249101ee5b6a4a144943e22f8623cbe6b937b04756685824d25da435d9fdad',
|
||||
'9460096ab3aaf124b580b54069f79dccd207e66e779ea90b1854c66ea4432c33',
|
||||
'filter:metadata-missing-album-artist':
|
||||
'33745cb4b821d499aef70d477e5475db1fec6be440b8493dc4f8bbc325fcd5fe',
|
||||
'56b6e32d70da0e23519ab2aa20e459f1e53d6bc3cd893bd4ebcb146bd4674dd0',
|
||||
'filter:metadata-missing-track-number':
|
||||
'b3f758c7cad16b67359a164a8448c90a6eddcd1ec6dddc6d739cbd257dd751c7',
|
||||
'eace037c0e2ab758b1c75496808d009262a04e57df6d3d691d30143071c59b8d',
|
||||
'filter:metadata-missing-disc-number':
|
||||
'fd5076ccc74093f863558c22c2c6f7acbe8df0d3ff12f9e4f1737c432808b483',
|
||||
'856c66ea491673b1e90e1dbde218e94e508a23b552cd205b6452ba56ca8e7eaf',
|
||||
'filter:metadata-missing-artist':
|
||||
'c2508a3489e2a586c1fc9ca30e19bfa740f55a0bab2c14e3d1b22bc5ff26e73b',
|
||||
'98c2f428a14e2b562922964b622e2340e9f2e7878f85110360f3ca54398a50a6',
|
||||
'filter:metadata-incorrect-isrc-format':
|
||||
'd1c6eb09dc78fb3a314e95b93cea9373060dab90d3dc0baeaa0840e0280b2523',
|
||||
'be35b2ed6e4de358ff7647143ef83467116784293d953234bcd3a8d4b9dc1719',
|
||||
'filter:metadata-missing-isrc':
|
||||
'd4c6bfb2c200f5c36e6911d7e7b1cbf0b4065acf6ba5adb3c933f32ffef5a989',
|
||||
'1e7ebc3f425b94674789d5b8ea24d669f8fd93920a0128567f4c386a9d95a126',
|
||||
'filter:metadata-missing-label':
|
||||
'68a36f7747535f9ce76af09eca9ed462e5741ae5c5e6580c3c6d5cb0c647e71d',
|
||||
'd1cf1947cb5303d997ef5a7f52e0f46eff23d37384f39fcdee3d9ae9a19b0a14',
|
||||
'filter:metadata-missing-lyrics':
|
||||
'8300622c7fbe922ff5ab3e308f569418194bbf5b606edab2deab94093a830d71',
|
||||
'bd20a87abb81d3c9b5ddbb51a7da6083e06efec09a41a4c511fd7ebc6303ce02',
|
||||
'filter:metadata-has-replaygain':
|
||||
'4429725b2cde12ad850f5174c727dbe790e2885dcb24053d93fff57530a75aa9',
|
||||
'26d596a27cb091379793ed804b425ddb6dbab7d96bdf6e8c83c569ab146beb25',
|
||||
'filter:metadata-missing-replaygain':
|
||||
'8a2d1efe5e59c51e379249bf1c9bfee09fff87fd9b11722588fc3ddc32b5cba9',
|
||||
'f378707aa77eb2cfe04b1309171235a0a4b6e2deedad2744dbfef41602ca8b72',
|
||||
'filter:metadata-incomplete-album':
|
||||
'36864a5cacd0a6abb9b5fda6ae1093aeea40cc6649944c7434cb88f92a05322b',
|
||||
'4e12bfad869e1da52432b4105081cd829b254a67b05f3e293693bbdfb1f1078a',
|
||||
'filter:metadata-unknown-album-completeness':
|
||||
'ffc8d309d9c307380aa04eec8be1479a160ab6c6646650fe64847eb80b51a1bc',
|
||||
'adc2a80d9bb9083775726af06d504afd094bdf28ef18e2752feb30d814489e5e',
|
||||
'filter:metadata-unknown-metadata':
|
||||
'18457139305325fec69390099668c4a3a1003a4dbfc42e1883cfacad035de652',
|
||||
'a4897e14edaea96ca23afbf37caaccc05e97e44f544f809eb5407dcb073076ca',
|
||||
'filter:single-track-albums':
|
||||
'98909aa3debb5bd1979501e58a524ea430bed5312fc9600532710f5ff4f54331',
|
||||
'209408ded261ee9d70ab9a1a7642cac06da48585b455fc3582c72d7a51c243f9',
|
||||
'filter:single-track-albums-incomplete':
|
||||
'36864a5cacd0a6abb9b5fda6ae1093aeea40cc6649944c7434cb88f92a05322b',
|
||||
'4e12bfad869e1da52432b4105081cd829b254a67b05f3e293693bbdfb1f1078a',
|
||||
'filter:combined':
|
||||
'2a6bddab48e992a448448aee0803b28325d79ef83cc78a65f347d31ad9de68cc',
|
||||
'6ae0f5d51d04f27ea4cc66922c54c82e7b94e828089bb222b356d737b3391454',
|
||||
'filter:combined-local':
|
||||
'e0dbe15bc2ed66fde25a50f7d4f3eec9722f93fbab6e95bf9a6b248083309341',
|
||||
'0ff1f1f66bb5f8ceed9ba78aee2cc715e9311db0b9eb58d0841cbfce695ebc8b',
|
||||
};
|
||||
|
||||
/// Each shadow check of the snapshot SQL, with the row check it replaces.
|
||||
|
||||
@@ -46,6 +46,7 @@ void main() {
|
||||
String artist = 'Artist',
|
||||
String title = 'Song',
|
||||
String? path,
|
||||
String? origin,
|
||||
}) async {
|
||||
final file = path ?? '/$id.flac';
|
||||
await db.insert('history_db.history', {
|
||||
@@ -55,6 +56,7 @@ void main() {
|
||||
'album_name': album,
|
||||
'album_artist': artist,
|
||||
'file_path': file,
|
||||
'origin_file_path': origin,
|
||||
'downloaded_at': '2026-01-01',
|
||||
'service': 'example-provider',
|
||||
'album_key': '${album.toLowerCase()}|${artist.toLowerCase()}',
|
||||
@@ -147,6 +149,111 @@ void main() {
|
||||
});
|
||||
tearDown(() => db.close());
|
||||
|
||||
test(
|
||||
'offline originals stay indexed, one row plays locally, removal reveals server',
|
||||
() async {
|
||||
const origin = 'network://nas/Artist/Album/01.flac';
|
||||
await addLocal('server', 1, path: origin, album: 'Offline album');
|
||||
await addHistory(
|
||||
'offline-copy',
|
||||
'Offline album',
|
||||
1,
|
||||
path: '/phone/Artist/Album/01.flac',
|
||||
origin: origin,
|
||||
);
|
||||
final before = await store.trackPage(
|
||||
const QueueLibraryDbQuery(searchQuery: 'offline album'),
|
||||
);
|
||||
expect(_tracks(before), ['downloaded:offline-copy']);
|
||||
expect((before.rows.single['item'] as Map)['originAvailable'], isTrue);
|
||||
expect(
|
||||
(await db.query('library', where: 'id = ?', whereArgs: ['server'])),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(
|
||||
await db.rawQuery(
|
||||
'SELECT * FROM history_db.history_path_keys WHERE path_key = ?',
|
||||
[origin],
|
||||
),
|
||||
isEmpty,
|
||||
);
|
||||
|
||||
final local = await store.trackPage(
|
||||
const QueueLibraryDbQuery(
|
||||
source: 'on-device',
|
||||
searchQuery: 'offline album',
|
||||
),
|
||||
);
|
||||
expect(_tracks(local), ['downloaded:offline-copy']);
|
||||
await db.delete(
|
||||
'history_db.history',
|
||||
where: 'id = ?',
|
||||
whereArgs: ['offline-copy'],
|
||||
);
|
||||
await db.delete(
|
||||
'history_db.history_path_keys',
|
||||
where: 'item_id = ?',
|
||||
whereArgs: ['offline-copy'],
|
||||
);
|
||||
expect(
|
||||
_tracks(
|
||||
await store.trackPage(
|
||||
const QueueLibraryDbQuery(searchQuery: 'offline album'),
|
||||
),
|
||||
),
|
||||
['local:server'],
|
||||
);
|
||||
expect(
|
||||
(await store.trackPage(
|
||||
const QueueLibraryDbQuery(
|
||||
source: 'on-device',
|
||||
searchQuery: 'offline album',
|
||||
),
|
||||
)).rows,
|
||||
isEmpty,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'server deletion preserves phone copy, unrelated same-title file stays separate',
|
||||
() async {
|
||||
const origin = 'network://nas/Artist/Album/01.flac';
|
||||
await addLocal('server', 1, path: origin, album: 'Offline album');
|
||||
await addLocal(
|
||||
'other-server',
|
||||
1,
|
||||
path: 'network://other/01.flac',
|
||||
album: 'Offline album',
|
||||
);
|
||||
await addHistory(
|
||||
'offline-copy',
|
||||
'Offline album',
|
||||
1,
|
||||
path: '/phone/01.flac',
|
||||
origin: origin,
|
||||
);
|
||||
expect(
|
||||
_tracks(
|
||||
await store.trackPage(
|
||||
const QueueLibraryDbQuery(searchQuery: 'offline album'),
|
||||
),
|
||||
),
|
||||
['downloaded:offline-copy', 'local:other-server'],
|
||||
);
|
||||
await db.delete('library', where: 'id = ?', whereArgs: ['server']);
|
||||
final after = await store.trackPage(
|
||||
const QueueLibraryDbQuery(
|
||||
source: 'on-device',
|
||||
searchQuery: 'offline album',
|
||||
),
|
||||
);
|
||||
expect(_tracks(after), ['downloaded:offline-copy']);
|
||||
expect((after.rows.single['item'] as Map)['originAvailable'], isFalse);
|
||||
expect((after.rows.single['item'] as Map)['filePath'], '/phone/01.flac');
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'network exclusion happens before paging and keeps local URI rows',
|
||||
() async {
|
||||
|
||||
@@ -485,6 +485,67 @@ void main() {
|
||||
);
|
||||
}
|
||||
|
||||
test(
|
||||
'offline origins are shadowed in both query paths without physical aliases',
|
||||
() async {
|
||||
await _seed();
|
||||
final db = await LibraryDatabase.instance.database;
|
||||
const origin = 'network://nas/Artist/Album/original.flac';
|
||||
await _addScanned(
|
||||
db,
|
||||
_scanned('server-original', origin, album: 40, number: 1),
|
||||
);
|
||||
final offline = {
|
||||
..._download(
|
||||
'offline-copy',
|
||||
'/phone/original.flac',
|
||||
album: 40,
|
||||
number: 1,
|
||||
),
|
||||
'originFilePath': origin,
|
||||
};
|
||||
await HistoryDatabase.instance.upsert(offline);
|
||||
await LibraryDatabase.instance.getQueueTrackPage(
|
||||
const QueueLibraryDbQuery(),
|
||||
);
|
||||
final snapshot = sqlite.LibraryShadowSnapshot();
|
||||
expect(await snapshot.read(db, (ready) async => ready), isTrue);
|
||||
for (final useSnapshot in [false, true]) {
|
||||
final store = LibraryQueueStore(
|
||||
db,
|
||||
historyFts: false,
|
||||
localFts: false,
|
||||
shadowSnapshot: useSnapshot,
|
||||
);
|
||||
final page = await store.trackPage(
|
||||
const QueueLibraryDbQuery(searchQuery: 'album 40'),
|
||||
);
|
||||
expect(page.rows, hasLength(1));
|
||||
expect((page.rows.single['item'] as Map)['id'], 'offline-copy');
|
||||
}
|
||||
expect(
|
||||
await db.rawQuery(
|
||||
'SELECT item_id FROM library_path_keys WHERE path_key = ?',
|
||||
[origin],
|
||||
),
|
||||
isNotEmpty,
|
||||
);
|
||||
expect(
|
||||
await HistoryDatabase.instance.getPhysicalFileIds([origin]),
|
||||
isEmpty,
|
||||
);
|
||||
await HistoryDatabase.instance.deleteByIds(['offline-copy']);
|
||||
await snapshot.refresh(db);
|
||||
final after = await LibraryQueueStore(
|
||||
db,
|
||||
historyFts: false,
|
||||
localFts: false,
|
||||
shadowSnapshot: true,
|
||||
).trackPage(const QueueLibraryDbQuery(searchQuery: 'album 40'));
|
||||
expect((after.rows.single['item'] as Map)['id'], 'server-original');
|
||||
},
|
||||
);
|
||||
|
||||
test('every writer refreshes the snapshot before the next read', () async {
|
||||
await _seed();
|
||||
final library = LibraryDatabase.instance;
|
||||
@@ -774,7 +835,9 @@ void main() {
|
||||
addTearDown(db.close);
|
||||
await db.execute('ATTACH DATABASE ? AS history_db', [':memory:']);
|
||||
// Without History tables every build fails.
|
||||
await db.execute('CREATE TABLE library(id TEXT PRIMARY KEY)');
|
||||
await db.execute(
|
||||
'CREATE TABLE library(id TEXT PRIMARY KEY, file_path TEXT)',
|
||||
);
|
||||
await db.execute(
|
||||
'CREATE TABLE library_path_keys(item_id TEXT NOT NULL, '
|
||||
'path_key TEXT NOT NULL)',
|
||||
@@ -790,7 +853,9 @@ void main() {
|
||||
expect(snapshot.rebuilds, 2);
|
||||
expect(_warnings('Download shadow snapshot unavailable'), 1);
|
||||
|
||||
await db.execute('CREATE TABLE history_db.history(id TEXT)');
|
||||
await db.execute(
|
||||
'CREATE TABLE history_db.history(id TEXT, origin_file_path TEXT)',
|
||||
);
|
||||
await db.execute(
|
||||
'CREATE TABLE history_db.history_path_keys(item_id TEXT NOT NULL, '
|
||||
'path_key TEXT NOT NULL)',
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:io';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mornye/models/download_history.dart';
|
||||
import 'package:mornye/models/library_database_models.dart';
|
||||
import 'package:mornye/models/settings.dart';
|
||||
import 'package:mornye/services/link/features/link_save_offline.dart';
|
||||
import 'package:mornye/services/link/features/link_track_refs.dart';
|
||||
import 'package:mornye/services/link/link_protocol.dart';
|
||||
@@ -134,6 +135,41 @@ void main() {
|
||||
now: () => DateTime(2026, 10, 25),
|
||||
);
|
||||
|
||||
for (final conflict in [false, true]) {
|
||||
test(
|
||||
'failed publication cleans the saved file (concurrent copy: $conflict)',
|
||||
() async {
|
||||
final transport = _FakeTransport();
|
||||
final saver = LinkOfflineSaver(
|
||||
serverId: linkTestServer.serverId,
|
||||
openTransport: () => transport,
|
||||
destination: LinkDownloadFolderDestination(
|
||||
AppSettings(downloadDirectory: root.path),
|
||||
),
|
||||
record: (_) async {
|
||||
if (conflict) throw const OfflineCopyAlreadySaved();
|
||||
throw StateError('History write failed');
|
||||
},
|
||||
temporaryDirectory: () async => temp,
|
||||
);
|
||||
final result = await saver.save([
|
||||
LinkOfflineSong(item: _row('1'), songId: '1'),
|
||||
]);
|
||||
expect(result.saved, 0);
|
||||
expect(result.failed, conflict ? 0 : 1);
|
||||
expect(result.skipped, conflict ? 1 : 0);
|
||||
expect(
|
||||
await root
|
||||
.list(recursive: true)
|
||||
.where((entry) => entry is File)
|
||||
.toList(),
|
||||
isEmpty,
|
||||
);
|
||||
expect(await temp.list().toList(), isEmpty);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test('only rows streamed from the paired desktop can be saved', () {
|
||||
final songs = linkOfflineSongs([
|
||||
_row('1'),
|
||||
|
||||
@@ -651,6 +651,7 @@ MusicPlayerRuntime _runtime({
|
||||
Future<String?> Function(String)? recoverMissingFile,
|
||||
Future<String?> Function(String, String, AppSettings)? recoverMovedDownload,
|
||||
Future<String> Function(String)? resolveNetworkSource,
|
||||
Future<String?> Function(String)? offlineCopy,
|
||||
Future<Map<String, dynamic>> Function(String)? readNetworkMetadata,
|
||||
CoverStore? coverStore,
|
||||
}) {
|
||||
@@ -690,6 +691,7 @@ MusicPlayerRuntime _runtime({
|
||||
recoverMovedDownload: recoverMovedDownload ?? (_, _, _) async => null,
|
||||
resolveNetworkSource:
|
||||
resolveNetworkSource ?? NetworkStorageService.instance.resolve,
|
||||
offlineCopy: offlineCopy ?? (_) async => null,
|
||||
readNetworkMetadata:
|
||||
readNetworkMetadata ?? NetworkMetadataService.instance.read,
|
||||
coverStore: coverStore,
|
||||
@@ -1865,6 +1867,76 @@ void main() {
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'queued network song prefers its offline original and retains its origin',
|
||||
() async {
|
||||
final temp = await Directory.systemTemp.createTemp('player-offline-');
|
||||
addTearDown(() => temp.delete(recursive: true));
|
||||
final local = await File(
|
||||
'${temp.path}/song.flac',
|
||||
).writeAsBytes([1, 2, 3]);
|
||||
final decks = <_Deck>[];
|
||||
var remoteRequests = 0;
|
||||
final handler = await _runtime(
|
||||
decks: decks,
|
||||
offlineCopy: (_) async => local.path,
|
||||
resolveNetworkSource: (_) async {
|
||||
remoteRequests++;
|
||||
throw const SocketException('Offline');
|
||||
},
|
||||
).initialize();
|
||||
await handler.setQueueAndPlay([
|
||||
const PlayableMedia(
|
||||
id: 'nas-song',
|
||||
source: 'network://nas/a.flac',
|
||||
title: 'NAS song',
|
||||
artist: 'Artist',
|
||||
),
|
||||
]);
|
||||
expect(decks.single.sources, [local.path]);
|
||||
expect(remoteRequests, 0);
|
||||
expect(handler.mediaItem.value!.extras!['source'], local.path);
|
||||
expect(
|
||||
handler.mediaItem.value!.extras!['originSource'],
|
||||
'network://nas/a.flac',
|
||||
);
|
||||
await handler.onSourceDeleted('network://nas/a.flac');
|
||||
expect(handler.queue.value, hasLength(1));
|
||||
expect(handler.playbackState.value.playing, isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'missing offline file falls back to its server without requiring a rescan',
|
||||
() async {
|
||||
final temp = await Directory.systemTemp.createTemp(
|
||||
'player-offline-missing-',
|
||||
);
|
||||
addTearDown(() => temp.delete(recursive: true));
|
||||
final decks = <_Deck>[];
|
||||
final requests = <String>[];
|
||||
final handler = await _runtime(
|
||||
decks: decks,
|
||||
resolveNetworkSource: (source) async {
|
||||
requests.add(source);
|
||||
return 'http://127.0.0.1:1/original';
|
||||
},
|
||||
).initialize();
|
||||
await handler.setQueueAndPlay([
|
||||
PlayableMedia(
|
||||
id: 'saved-song',
|
||||
source: '${temp.path}/gone.flac',
|
||||
originSource: 'network://nas/a.flac',
|
||||
title: 'NAS song',
|
||||
artist: 'Artist',
|
||||
),
|
||||
]);
|
||||
expect(requests, ['network://nas/a.flac']);
|
||||
expect(decks.single.sources, ['stream http://127.0.0.1:1/original']);
|
||||
expect(handler.playbackState.value.playing, isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
for (final resolved in [
|
||||
'/received/Phone song.flac',
|
||||
'http://127.0.0.1:1/song.flac',
|
||||
|
||||
@@ -91,6 +91,7 @@ void main() {
|
||||
albumName: ' Album ',
|
||||
albumArtist: ' Album Artist ',
|
||||
coverUrl: 'https://example.test/cover.jpg',
|
||||
originFilePath: 'network://nas/Artist/Album/Track.flac',
|
||||
filePath: 'content://nas.provider/tree/root/document/Ab%252FC.flac',
|
||||
storageMode: 'saf',
|
||||
downloadTreeUri: 'content://nas.provider/tree/root',
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
import 'package:mornye/models/settings.dart';
|
||||
import 'package:mornye/models/unified_library_item.dart';
|
||||
import 'package:mornye/providers/download_history_provider.dart';
|
||||
import 'package:mornye/providers/local_library_provider.dart';
|
||||
import 'package:mornye/providers/network_offline_provider.dart';
|
||||
import 'package:mornye/providers/settings_provider.dart';
|
||||
import 'package:mornye/services/history_database.dart';
|
||||
import 'package:mornye/services/library_database.dart';
|
||||
import 'package:mornye/services/network_storage_service.dart';
|
||||
|
||||
class _Settings extends SettingsNotifier {
|
||||
_Settings(this.settings);
|
||||
final AppSettings settings;
|
||||
@override
|
||||
AppSettings build() => settings;
|
||||
@override
|
||||
void setLocalLibraryEnabled(bool enabled) =>
|
||||
state = state.copyWith(localLibraryEnabled: enabled);
|
||||
}
|
||||
|
||||
class _History extends DownloadHistoryNotifier {
|
||||
@override
|
||||
DownloadHistoryState build() => DownloadHistoryState();
|
||||
}
|
||||
|
||||
class _Library extends LocalLibraryNotifier {
|
||||
int _added = 0;
|
||||
@override
|
||||
LocalLibraryState build() => LocalLibraryState();
|
||||
@override
|
||||
Future<void> reloadFromStorage() async {}
|
||||
@override
|
||||
Future<LocalLibrarySource> addSource({
|
||||
required String path,
|
||||
required String displayName,
|
||||
String? bookmark,
|
||||
String? volumeId,
|
||||
bool isRemovable = false,
|
||||
}) async {
|
||||
final source = LocalLibrarySource(
|
||||
id: 'source-${++_added}',
|
||||
path: path,
|
||||
displayName: displayName,
|
||||
);
|
||||
await LibraryDatabase.instance.upsertSource(source);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = null;
|
||||
|
||||
test(
|
||||
'NAS downloads keep one entry through save, repeat, local removal and server removal',
|
||||
() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
final root = await Directory.systemTemp.createTemp('offline-provider-');
|
||||
final previous = databaseFactoryOrNull;
|
||||
sqfliteFfiInit();
|
||||
databaseFactory = databaseFactoryFfi;
|
||||
const paths = MethodChannel('plugins.flutter.io/path_provider');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(paths, (_) async => root.path);
|
||||
addTearDown(() async {
|
||||
await LibraryDatabase.instance.close();
|
||||
await HistoryDatabase.instance.close();
|
||||
messenger.setMockMethodCallHandler(paths, null);
|
||||
databaseFactory = previous;
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(() => server.close(force: true));
|
||||
var reads = 0;
|
||||
server.listen((request) async {
|
||||
reads++;
|
||||
expect(request.method, 'GET');
|
||||
request.response.headers.contentType = ContentType('audio', 'flac');
|
||||
request.response.add([102, 76, 97, 67, 1, 2, 3]);
|
||||
await request.response.close();
|
||||
});
|
||||
final storage = NetworkStorageService(
|
||||
read: () async => null,
|
||||
write: (_) async {},
|
||||
ensureAccess: (_) async {},
|
||||
);
|
||||
addTearDown(storage.dispose);
|
||||
await storage.save(
|
||||
NetworkConnection(
|
||||
id: 'nas',
|
||||
name: 'Music NAS',
|
||||
protocol: NetworkProtocol.webdav,
|
||||
address: 'http://127.0.0.1:${server.port}/',
|
||||
),
|
||||
);
|
||||
final settings = AppSettings(
|
||||
downloadDirectory: '${root.path}/downloads',
|
||||
networkDownloadFolder: 'network://nas/New downloads/',
|
||||
);
|
||||
final library = _Library();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
settingsProvider.overrideWith(() => _Settings(settings)),
|
||||
downloadHistoryProvider.overrideWith(_History.new),
|
||||
localLibraryProvider.overrideWith(() => library),
|
||||
networkOfflineStorageProvider.overrideWithValue(storage),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
final originals = [
|
||||
for (final number in [1, 2])
|
||||
DownloadHistoryItem(
|
||||
id: 'download-$number',
|
||||
trackName: 'Song $number',
|
||||
artistName: 'Artist',
|
||||
albumName: 'Album',
|
||||
filePath: 'network://nas/Artist/Album/$number.flac',
|
||||
service: 'example-provider',
|
||||
spotifyId: 'catalog-$number',
|
||||
downloadedAt: DateTime(2026),
|
||||
),
|
||||
];
|
||||
await HistoryDatabase.instance.upsertBatch([
|
||||
for (final item in originals) item.toJson(),
|
||||
]);
|
||||
final selected = [
|
||||
for (final item in originals)
|
||||
UnifiedLibraryItem.fromDownloadHistory(item),
|
||||
];
|
||||
final result = await container
|
||||
.read(networkOfflineProvider.notifier)
|
||||
.save(selected);
|
||||
expect(result!.saved, 2);
|
||||
expect(result.failed, 0);
|
||||
expect(library._added, 1);
|
||||
expect(container.read(settingsProvider).localLibraryEnabled, isTrue);
|
||||
final sources = await LibraryDatabase.instance.getSources();
|
||||
expect(sources.single.path, 'network://nas/Artist/Album/');
|
||||
expect(sources.single.displayName, 'Music NAS');
|
||||
final saved = await HistoryDatabase.instance.getAll();
|
||||
expect(saved, hasLength(2));
|
||||
for (final row in saved) {
|
||||
final item = DownloadHistoryItem.fromJson(row);
|
||||
expect(item.filePath, startsWith(settings.downloadDirectory));
|
||||
expect(await File(item.filePath).readAsBytes(), [
|
||||
102,
|
||||
76,
|
||||
97,
|
||||
67,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
]);
|
||||
final original = originals.firstWhere(
|
||||
(original) => original.id == item.id,
|
||||
);
|
||||
expect(item.originFilePath, original.filePath);
|
||||
expect(item.service, original.service);
|
||||
expect(item.spotifyId, original.spotifyId);
|
||||
}
|
||||
final page = await LibraryDatabase.instance.getQueueTrackPage(
|
||||
const QueueLibraryDbQuery(),
|
||||
);
|
||||
expect(page, hasLength(2));
|
||||
expect(page.every((row) => row['source'] == 'downloaded'), isTrue);
|
||||
final repeat = await container
|
||||
.read(networkOfflineProvider.notifier)
|
||||
.save(selected);
|
||||
expect(repeat!.skipped, 2);
|
||||
expect(reads, 2);
|
||||
expect(
|
||||
container.read(settingsProvider).networkDownloadFolder,
|
||||
settings.networkDownloadFolder,
|
||||
);
|
||||
|
||||
final removed = DownloadHistoryItem.fromJson(saved.first);
|
||||
await File(removed.filePath).delete();
|
||||
await container
|
||||
.read(downloadHistoryProvider.notifier)
|
||||
.removePhysicalFiles([removed.filePath]);
|
||||
final afterLocal = await LibraryDatabase.instance.getQueueTrackPage(
|
||||
QueueLibraryDbQuery(
|
||||
includeLocal: container.read(settingsProvider).localLibraryEnabled,
|
||||
),
|
||||
);
|
||||
expect(afterLocal, hasLength(2));
|
||||
expect(afterLocal.where((row) => row['source'] == 'local'), hasLength(1));
|
||||
final kept = DownloadHistoryItem.fromJson(saved.last);
|
||||
final originalsOnServer = await (await LibraryDatabase.instance.database)
|
||||
.query(
|
||||
'library',
|
||||
columns: ['id'],
|
||||
where: 'file_path = ?',
|
||||
whereArgs: [kept.originFilePath],
|
||||
);
|
||||
await LibraryDatabase.instance.deleteByIds([
|
||||
originalsOnServer.single['id'] as String,
|
||||
]);
|
||||
final onDevice = await LibraryDatabase.instance.getQueueTrackPage(
|
||||
const QueueLibraryDbQuery(source: 'on-device'),
|
||||
);
|
||||
expect(onDevice, hasLength(1));
|
||||
expect((onDevice.single['item'] as Map)['originAvailable'], isFalse);
|
||||
expect(await File(kept.filePath).exists(), isTrue);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mornye/models/download_history.dart';
|
||||
import 'package:mornye/models/library_database_models.dart';
|
||||
import 'package:mornye/models/settings.dart';
|
||||
import 'package:mornye/models/unified_library_item.dart';
|
||||
import 'package:mornye/services/link/features/link_save_offline.dart';
|
||||
import 'package:mornye/services/network_offline_saver.dart';
|
||||
import 'package:mornye/services/network_storage_service.dart';
|
||||
|
||||
LocalLibraryItem song(String path) => LocalLibraryItem(
|
||||
id: 'server-song',
|
||||
filePath: path,
|
||||
trackName: 'Song',
|
||||
artistName: 'Artist',
|
||||
albumName: 'Album',
|
||||
format: 'flac',
|
||||
scannedAt: DateTime(2026),
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = null;
|
||||
|
||||
test(
|
||||
'origins deduplicate by connection and path, never title and artist',
|
||||
() {
|
||||
final a = UnifiedLibraryItem.fromLocalLibrary(
|
||||
song('network://one/a.flac'),
|
||||
);
|
||||
final b = UnifiedLibraryItem.fromLocalLibrary(
|
||||
song('network://two/a.flac'),
|
||||
);
|
||||
expect(networkOfflineSongs([a, a, b]).map((song) => song.songId), [
|
||||
'network://one/a.flac',
|
||||
'network://two/a.flac',
|
||||
]);
|
||||
final saved = DownloadHistoryItem(
|
||||
id: 'saved',
|
||||
trackName: 'Song',
|
||||
artistName: 'Artist',
|
||||
albumName: 'Album',
|
||||
filePath: '/phone/a.flac',
|
||||
originFilePath: a.filePath,
|
||||
service: 'Network offline',
|
||||
downloadedAt: DateTime(2026),
|
||||
);
|
||||
expect(
|
||||
networkOfflineSongs([a, UnifiedLibraryItem.fromDownloadHistory(saved)]),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(
|
||||
DownloadHistoryItem.fromJson(saved.toJson()).originFilePath,
|
||||
a.filePath,
|
||||
);
|
||||
expect(saved.copyWith(trackName: 'Edited').originFilePath, a.filePath);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'original layout preserves Unicode, percent and filename, rejects traversal',
|
||||
() {
|
||||
final item = song('network://nas/Artist/Album/01.flac');
|
||||
final layout = networkOfflineLayout(
|
||||
item,
|
||||
'/Артист/Album 100%/01 Hello.flac',
|
||||
);
|
||||
expect(layout.relativeDir, 'Артист/Album 100%');
|
||||
expect(layout.fileName, '01 Hello.flac');
|
||||
for (final path in [
|
||||
'../outside.flac',
|
||||
'Album/../../outside.flac',
|
||||
r'Album\..\outside.flac',
|
||||
]) {
|
||||
expect(() => networkOfflineLayout(item, path), throwsFormatException);
|
||||
}
|
||||
expect(networkOfflineLayout(item, null).fileName, 'Song - Artist.flac');
|
||||
},
|
||||
);
|
||||
|
||||
for (final protocol in [
|
||||
NetworkProtocol.http,
|
||||
NetworkProtocol.webdav,
|
||||
NetworkProtocol.subsonic,
|
||||
]) {
|
||||
test(
|
||||
'${protocol.name} saves original bytes once with durable origin and original folders',
|
||||
() async {
|
||||
final temp = await Directory.systemTemp.createTemp(
|
||||
'network_offline_test_',
|
||||
);
|
||||
addTearDown(() => temp.delete(recursive: true));
|
||||
final root = Directory('${temp.path}/downloads');
|
||||
final staged = await Directory('${temp.path}/stage').create();
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(() => server.close(force: true));
|
||||
final payload = List.generate(180000, (i) => i % 251);
|
||||
final requests = <Uri>[];
|
||||
server.listen((request) async {
|
||||
requests.add(request.uri);
|
||||
if (request.uri.path.contains('getSong')) {
|
||||
request.response.headers.contentType = ContentType.json;
|
||||
request.response.write(
|
||||
jsonEncode({
|
||||
'subsonic-response': {
|
||||
'status': 'ok',
|
||||
'song': {
|
||||
'id': 'song-1',
|
||||
'title': 'Song',
|
||||
'path': 'Artist/Album/01 Original.flac',
|
||||
'suffix': 'flac',
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
request.response.headers.contentType = ContentType('audio', 'flac');
|
||||
request.response.contentLength = payload.length;
|
||||
request.response.add(payload);
|
||||
}
|
||||
await request.response.close();
|
||||
});
|
||||
final storage = NetworkStorageService(
|
||||
read: () async => null,
|
||||
write: (_) async {},
|
||||
ensureAccess: (_) async {},
|
||||
);
|
||||
addTearDown(storage.dispose);
|
||||
await storage.save(
|
||||
NetworkConnection(
|
||||
id: 'nas',
|
||||
name: 'NAS',
|
||||
protocol: protocol,
|
||||
address: 'http://127.0.0.1:${server.port}/',
|
||||
),
|
||||
);
|
||||
final path = protocol == NetworkProtocol.subsonic
|
||||
? subsonicSongPath('song-1', 'flac')
|
||||
: 'Artist/Album/01 Original.flac';
|
||||
final source = NetworkStorageService.source('nas', path);
|
||||
final rows = <DownloadHistoryItem>[];
|
||||
final transport = NetworkOfflineTransport(storage: storage);
|
||||
final saver = LinkOfflineSaver(
|
||||
serverId: 'network',
|
||||
idPrefix: 'offline',
|
||||
serviceName: 'Network offline',
|
||||
openTransport: () => transport,
|
||||
prepareSong: transport.prepare,
|
||||
destination: LinkDownloadFolderDestination(
|
||||
AppSettings(downloadDirectory: root.path),
|
||||
),
|
||||
record: (item) async => rows.add(item),
|
||||
temporaryDirectory: () async => staged,
|
||||
);
|
||||
final result = await saver.save([
|
||||
LinkOfflineSong(item: song(source), songId: source),
|
||||
]);
|
||||
expect(result.saved, 1);
|
||||
expect(result.failed, 0);
|
||||
expect(rows.single.originFilePath, source);
|
||||
expect(
|
||||
UnifiedLibraryItem.fromDownloadHistory(rows.single).collectionKey,
|
||||
UnifiedLibraryItem.fromLocalLibrary(song(source)).collectionKey,
|
||||
);
|
||||
expect(
|
||||
UnifiedLibraryItem.fromDownloadHistory(rows.single).toTrack().id,
|
||||
song(source).id,
|
||||
);
|
||||
expect(
|
||||
rows.single.filePath,
|
||||
'${root.path}/Artist/Album/01 Original.flac',
|
||||
);
|
||||
expect(await File(rows.single.filePath).readAsBytes(), payload);
|
||||
expect(await staged.list().toList(), isEmpty);
|
||||
if (protocol == NetworkProtocol.subsonic) {
|
||||
expect(requests.last.path, endsWith('/download.view'));
|
||||
expect(requests.last.queryParameters['id'], 'song-1');
|
||||
expect(requests.any((uri) => uri.path.contains('stream')), isFalse);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test(
|
||||
'direct HTTP audio keeps the original file name without copying URL tokens',
|
||||
() async {
|
||||
final storage = NetworkStorageService(
|
||||
read: () async => null,
|
||||
write: (_) async {},
|
||||
ensureAccess: (_) async {},
|
||||
);
|
||||
addTearDown(storage.dispose);
|
||||
await storage.save(
|
||||
const NetworkConnection(
|
||||
id: 'nas',
|
||||
name: 'NAS',
|
||||
protocol: NetworkProtocol.http,
|
||||
address:
|
||||
'https://example.test/music/Original%20Song.flac?token=private',
|
||||
),
|
||||
);
|
||||
final transport = NetworkOfflineTransport(storage: storage);
|
||||
addTearDown(transport.close);
|
||||
final source = NetworkStorageService.source('nas', '');
|
||||
final prepared = await transport.prepare(
|
||||
LinkOfflineSong(item: song(source), songId: source),
|
||||
);
|
||||
expect(prepared.fileName, 'Original Song.flac');
|
||||
expect(prepared.relativeDir, '');
|
||||
},
|
||||
);
|
||||
|
||||
test('a 200 HTML error never becomes an offline song', () async {
|
||||
final temp = await Directory.systemTemp.createTemp(
|
||||
'network_offline_error_',
|
||||
);
|
||||
addTearDown(() => temp.delete(recursive: true));
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(() => server.close(force: true));
|
||||
server.listen((request) async {
|
||||
request.response.headers.contentType = ContentType.html;
|
||||
request.response.write('<html>Login required</html>');
|
||||
await request.response.close();
|
||||
});
|
||||
final storage = NetworkStorageService(
|
||||
read: () async => null,
|
||||
write: (_) async {},
|
||||
ensureAccess: (_) async {},
|
||||
);
|
||||
addTearDown(storage.dispose);
|
||||
await storage.save(
|
||||
NetworkConnection(
|
||||
id: 'nas',
|
||||
name: 'NAS',
|
||||
protocol: NetworkProtocol.webdav,
|
||||
address: 'http://127.0.0.1:${server.port}/',
|
||||
),
|
||||
);
|
||||
final transport = NetworkFileDownload(storage);
|
||||
addTearDown(transport.close);
|
||||
await expectLater(
|
||||
transport.download(
|
||||
NetworkStorageService.source('nas', 'a.flac'),
|
||||
File('${temp.path}/a.flac'),
|
||||
checkpoint: () {},
|
||||
progress: (_, _) {},
|
||||
),
|
||||
throwsA(isA<HttpException>()),
|
||||
);
|
||||
expect(await File('${temp.path}/a.flac').exists(), isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'cancel interrupts a stalled read and never records or publishes a partial song',
|
||||
() async {
|
||||
final temp = await Directory.systemTemp.createTemp(
|
||||
'network_offline_cancel_',
|
||||
);
|
||||
addTearDown(() => temp.delete(recursive: true));
|
||||
final staged = await Directory('${temp.path}/stage').create();
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(() => server.close(force: true));
|
||||
final started = Completer<void>();
|
||||
final release = Completer<void>();
|
||||
addTearDown(() {
|
||||
if (!release.isCompleted) release.complete();
|
||||
});
|
||||
server.listen((request) async {
|
||||
request.response.headers.contentType = ContentType('audio', 'flac');
|
||||
request.response.contentLength = 1000;
|
||||
request.response.add(List.filled(10, 1));
|
||||
await request.response.flush();
|
||||
started.complete();
|
||||
await release.future;
|
||||
try {
|
||||
await request.response.close();
|
||||
} catch (_) {}
|
||||
});
|
||||
final storage = NetworkStorageService(
|
||||
read: () async => null,
|
||||
write: (_) async {},
|
||||
ensureAccess: (_) async {},
|
||||
);
|
||||
addTearDown(storage.dispose);
|
||||
await storage.save(
|
||||
NetworkConnection(
|
||||
id: 'nas',
|
||||
name: 'NAS',
|
||||
protocol: NetworkProtocol.http,
|
||||
address: 'http://127.0.0.1:${server.port}/',
|
||||
),
|
||||
);
|
||||
final transport = NetworkOfflineTransport(storage: storage);
|
||||
final cancel = LinkOfflineCancel();
|
||||
final source = NetworkStorageService.source('nas', 'a.flac');
|
||||
final recorded = <DownloadHistoryItem>[];
|
||||
final saved =
|
||||
LinkOfflineSaver(
|
||||
serverId: 'network',
|
||||
openTransport: () => transport,
|
||||
prepareSong: transport.prepare,
|
||||
destination: LinkDownloadFolderDestination(
|
||||
AppSettings(downloadDirectory: '${temp.path}/downloads'),
|
||||
),
|
||||
record: (item) async => recorded.add(item),
|
||||
temporaryDirectory: () async => staged,
|
||||
).save([
|
||||
LinkOfflineSong(item: song(source), songId: source),
|
||||
], cancel: cancel);
|
||||
await started.future;
|
||||
cancel.cancel();
|
||||
final result = await saved.timeout(const Duration(seconds: 3));
|
||||
expect(result.cancelled, isTrue);
|
||||
expect(result.saved, 0);
|
||||
expect(recorded, isEmpty);
|
||||
expect(await staged.list().toList(), isEmpty);
|
||||
expect(await Directory('${temp.path}/downloads').exists(), isFalse);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -254,6 +254,33 @@ void main() {
|
||||
return response.fold<List<int>>([], (bytes, chunk) => bytes..addAll(chunk));
|
||||
}
|
||||
|
||||
test(
|
||||
'offline copies reuse read sessions and leave playback ranges available',
|
||||
() async {
|
||||
setUpStorage();
|
||||
await storage.save(_connection());
|
||||
final directory = await Directory.systemTemp.createTemp('smb-offline-');
|
||||
addTearDown(() => directory.delete(recursive: true));
|
||||
final download = NetworkFileDownload(storage);
|
||||
addTearDown(download.close);
|
||||
for (final path in ['A/01.flac', 'A/02.flac']) {
|
||||
final output = File('${directory.path}/${path.split('/').last}');
|
||||
await download.download(
|
||||
NetworkStorageService.source('nas', path),
|
||||
output,
|
||||
checkpoint: () {},
|
||||
progress: (_, _) {},
|
||||
);
|
||||
expect(await output.readAsBytes(), _bytes(4000));
|
||||
}
|
||||
download.close();
|
||||
expect(await get('B/01.flac', 'bytes=0-3'), [0, 1, 2, 3]);
|
||||
expect(server.opened, 1);
|
||||
expect(server.closed, 0);
|
||||
expect(server.openHandles, 0);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a scan, its tag reads, covers and parallel reads share one SMB logon',
|
||||
() async {
|
||||
|
||||
Reference in new issue
Block a user