fix(download): resolve SAF conversion filenames from document metadata (#768)

This commit is contained in:
zarzet committed 2026-11-03 00:12:23 +07:00
commit ec5a355bfa
5 files changed
+160 -3

No files matched your search

@@ -10,6 +10,7 @@ internal fun querySafDocumentStat(resolver: ContentResolver, uri: Uri): JSONObje
DocumentsContract.Document.COLUMN_SIZE,
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
)
// DocumentFile.exists/length swallow provider and security exceptions.
// Query once, keep nullable metadata, and let failures reach the channel.
@@ -24,11 +25,13 @@ internal fun querySafDocumentStat(resolver: ContentResolver, uri: Uri): JSONObje
return if (index < 0 || it.isNull(index)) null else it.getLong(index)
}
val mimeIndex = it.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE)
val nameIndex = it.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
safDocumentStatResult(
hasRow = true,
size = nullableLong(DocumentsContract.Document.COLUMN_SIZE),
modified = nullableLong(DocumentsContract.Document.COLUMN_LAST_MODIFIED),
mimeType = if (mimeIndex < 0 || it.isNull(mimeIndex)) null else it.getString(mimeIndex),
displayName = if (nameIndex < 0 || it.isNull(nameIndex)) null else it.getString(nameIndex),
)
}
}
@@ -10,6 +10,7 @@ internal fun safDocumentStatResult(
size: Long? = null,
modified: Long? = null,
mimeType: String? = null,
displayName: String? = null,
): JSONObject {
if (hasRow == null || loading) throw IOException("SAF document metadata is unavailable")
return JSONObject()
@@ -17,4 +18,5 @@ internal fun safDocumentStatResult(
.put("size", if (hasRow) size ?: JSONObject.NULL else JSONObject.NULL)
.put("modified", if (hasRow) modified ?: JSONObject.NULL else JSONObject.NULL)
.put("mime_type", if (hasRow) mimeType ?: JSONObject.NULL else JSONObject.NULL)
.put("display_name", if (hasRow) displayName ?: JSONObject.NULL else JSONObject.NULL)
}
@@ -38,4 +38,10 @@ class SafDocumentStatPolicyTest {
assertEquals(123L, result.getLong("modified"))
assertEquals("audio/flac", result.getString("mime_type"))
}
@Test fun displayNameIsPreservedOnlyForExistingDocuments() {
val name = "Song: Live 100%.flac"
assertEquals(name, safDocumentStatResult(true, displayName = name).getString("display_name"))
assertTrue(safDocumentStatResult(false, displayName = name).isNull("display_name"))
}
}
+55 -3
View File
@@ -4,6 +4,7 @@ import 'package:mornye/models/download_result.dart';
import 'package:mornye/services/download_saf_file_replacer.dart';
import 'package:mornye/services/ffmpeg_models.dart';
import 'package:mornye/services/ffmpeg_probe.dart';
import 'package:mornye/services/platform_bridge.dart';
import 'package:mornye/utils/audio_conversion_utils.dart';
import 'package:mornye/utils/audio_format_utils.dart';
import 'package:mornye/utils/file_access.dart';
@@ -59,6 +60,7 @@ class DownloadFileFinalizer {
required this.replaceSafFile,
required this.warn,
required this.info,
this.readDocumentStat = PlatformBridge.safStat,
});
final DecryptDownloadFile decryptFile;
@@ -69,6 +71,7 @@ class DownloadFileFinalizer {
final ReplaceSafDownloadFile replaceSafFile;
final void Function(String) warn;
final void Function(String) info;
final Future<Map<String, dynamic>> Function(String) readDocumentStat;
Future<String> _normalizeIsoBmffPath(
String path,
@@ -227,9 +230,21 @@ class DownloadFileFinalizer {
)) {
return original;
}
final baseName = fileName?.trim().isNotEmpty == true
? fileName!.trim()
: File(filePath).uri.pathSegments.last;
final String baseName;
try {
baseName = fileName?.trim().isNotEmpty == true
? fileName!.trim()
: await downloadSourceFileName(
filePath,
readDocumentStat: readDocumentStat,
);
} catch (e) {
result['auto_conversion_warning'] = e.toString();
warn(
'Cannot determine conversion filename; keeping downloaded source: $e',
);
return original;
}
final convertedName = convertedOutputFileName(
originalFileName: baseName,
targetFormat: targetFormat,
@@ -372,6 +387,43 @@ class DownloadFileFinalizer {
}
}
/// Reads the document's display name instead of treating an opaque ID as a name.
Future<String> downloadSourceFileName(
String filePath, {
Future<Map<String, dynamic>> Function(String) readDocumentStat =
PlatformBridge.safStat,
}) async {
if (!isContentUri(filePath)) return File(filePath).uri.pathSegments.last;
bool usable(String? name) =>
name != null &&
name.trim().isNotEmpty &&
name != '.' &&
name != '..' &&
!RegExp(r'[/\\\x00]').hasMatch(name);
try {
final stat = await readDocumentStat(filePath);
final name = stat['display_name'] as String?;
if (stat['exists'] != false && usable(name)) return name!;
} catch (_) {
// Older hosts may omit display_name; only the external-storage provider
// defines document IDs as volume:path. Other providers use opaque IDs.
}
final uri = Uri.parse(filePath);
if (uri.host == 'com.android.externalstorage.documents') {
final parts = uri.pathSegments;
final document = parts.indexOf('document');
if (document >= 0 && document + 1 < parts.length) {
final id = parts[document + 1];
final colon = id.indexOf(':');
if (colon >= 0) {
final name = id.substring(colon + 1).split('/').last;
if (usable(name)) return name;
}
}
}
throw const FormatException('Document filename is unavailable');
}
bool _isMp4Container(String path) {
final lower = path.toLowerCase();
return lower.endsWith('.m4a') || lower.endsWith('.mp4');
+94
View File
@@ -22,6 +22,7 @@ void main() {
Future<String?> Function(String)? probe,
Future<PrimaryAudioProperties> Function(String)? properties,
Future<void> Function(String, String)? repair,
Future<Map<String, dynamic>> Function(String)? documentStat,
}) => DownloadFileFinalizer(
decryptFile:
decrypt ??
@@ -56,6 +57,7 @@ void main() {
repairAc4: repair ?? (_, _) async => throw StateError('Unexpected repair'),
warn: warnings.add,
info: (_) {},
readDocumentStat: documentStat ?? (_) async => {},
);
DownloadResult encrypted({bool existing = false}) => DownloadResult.fromMap({
@@ -424,6 +426,98 @@ void main() {
},
);
test('SAF filenames come from metadata, with a path-based fallback', () async {
const opaque =
'content://com.android.providers.downloads.documents/document/msf%3A1234';
expect(
await downloadSourceFileName(
opaque,
readDocumentStat: (_) async => {
'exists': true,
'display_name': 'Song: Live 100%.flac',
},
),
'Song: Live 100%.flac',
);
expect(
await downloadSourceFileName(
'content://com.android.externalstorage.documents/tree/primary%3AMusic/document/primary%3AMusic%2FSong%3A%20Live.flac',
readDocumentStat: (_) async => {},
),
'Song: Live.flac',
);
for (final invalid in [null, '../escape.flac', 'dir/song.flac']) {
await expectLater(
downloadSourceFileName(
opaque,
readDocumentStat: (_) async => {'display_name': invalid},
),
throwsFormatException,
);
}
expect(await downloadSourceFileName('/music/Song.flac'), 'Song.flac');
});
test(
'SAF conversion uses the document name when history has no filename',
() async {
String? published;
final output = File('${directory.path}/cache.opus');
final stage = finalizer(
documentStat: (_) async => {
'exists': true,
'display_name': 'Song.flac',
},
replaceSaf:
({
required uri,
required treeUri,
required relativeDir,
required op,
avoidOverwrite = false,
onPublishedFileName,
}) async {
published = (await op(
'${directory.path}/cache.flac',
(_) {},
))?.$2;
return 'content://converted';
},
convert:
({
required inputPath,
required targetFormat,
required bitrate,
required deleteOriginal,
required losslessQuality,
}) async => (await output.writeAsString('converted')).path,
);
final result = await convert(
stage,
encrypted(),
path: 'content://downloads/document/msf%3A1234',
name: null,
saf: true,
);
expect(result.converted, isTrue);
expect(published, 'Song.opus');
},
);
test('unknown SAF filename keeps the source and skips conversion', () async {
final result = encrypted();
final outcome = await convert(
finalizer(),
result,
path: 'content://downloads/document/msf%3A1234',
name: null,
saf: true,
);
expect(outcome.converted, isFalse);
expect(outcome.filePath, 'content://downloads/document/msf%3A1234');
expect(result['auto_conversion_warning'], isNotNull);
});
for (final format in ['opus', 'flac']) {
test(
'SAF $format conversion adopts the published name and cleans temps',