diff options
| author | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
|---|---|---|
| committer | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
| commit | 449d8b74bd6d9dae98a07254cdfad677b920e7b0 (patch) | |
| tree | c131c3528c4d517f56e19b854a7453fedb097d40 /lib/services/metadata | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'lib/services/metadata')
| -rw-r--r-- | lib/services/metadata/metadata_edit_service.dart | 180 | ||||
| -rw-r--r-- | lib/services/metadata/metadata_fetch_service.dart | 306 | ||||
| -rw-r--r-- | lib/services/metadata/svg_metadata_service.dart | 92 | ||||
| -rw-r--r-- | lib/services/metadata/xmp.dart | 40 |
4 files changed, 618 insertions, 0 deletions
diff --git a/lib/services/metadata/metadata_edit_service.dart b/lib/services/metadata/metadata_edit_service.dart new file mode 100644 index 0000000..92f63f8 --- /dev/null +++ b/lib/services/metadata/metadata_edit_service.dart @@ -0,0 +1,180 @@ +import 'dart:async'; + +import 'package:aves/convert/convert.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +abstract class MetadataEditService { + Future<Map<String, dynamic>> rotate(AvesEntry entry, {required bool clockwise}); + + Future<Map<String, dynamic>> flip(AvesEntry entry); + + Future<Map<String, dynamic>> editExifDate(AvesEntry entry, DateModifier modifier); + + Future<Map<String, dynamic>> editMetadata(AvesEntry entry, Map<MetadataType, dynamic> modifier, {bool autoCorrectTrailerOffset = true}); + + Future<Map<String, dynamic>> removeTrailerVideo(AvesEntry entry); + + Future<Map<String, dynamic>> removeTypes(AvesEntry entry, Set<MetadataType> types); +} + +class PlatformMetadataEditService implements MetadataEditService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/metadata_edit'); + + @override + Future<Map<String, dynamic>> rotate(AvesEntry entry, {required bool clockwise}) async { + try { + // returns map with: 'rotationDegrees' 'isFlipped' + final result = await _platform.invokeMethod('rotate', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + 'clockwise': clockwise, + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> flip(AvesEntry entry) async { + try { + // returns map with: 'rotationDegrees' 'isFlipped' + final result = await _platform.invokeMethod('flip', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> editExifDate(AvesEntry entry, DateModifier modifier) async { + try { + final result = await _platform.invokeMethod('editDate', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + 'dateMillis': modifier.setDateTime?.millisecondsSinceEpoch, + 'shiftSeconds': modifier.shiftSeconds, + 'fields': modifier.fields.where((v) => v.type == MetadataType.exif).map((v) => v.toPlatform).nonNulls.toList(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> editMetadata( + AvesEntry entry, + Map<MetadataType, dynamic> metadata, { + bool autoCorrectTrailerOffset = true, + }) async { + try { + final result = await _platform.invokeMethod('editMetadata', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + 'metadata': metadata.map((type, value) => MapEntry(type.toPlatform, value)), + 'autoCorrectTrailerOffset': autoCorrectTrailerOffset, + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> removeTrailerVideo(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('removeTrailerVideo', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> removeTypes(AvesEntry entry, Set<MetadataType> types) async { + try { + final result = await _platform.invokeMethod('removeTypes', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + 'types': types.map((v) => v.toPlatform).toList(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + Future<void> _processPlatformException(AvesEntry entry, PlatformException e, StackTrace stack) async { + if (entry.isValid) { + final code = e.code; + final customException = CustomPlatformException.fromStandard(e); + if (code.endsWith('mp4largemoov')) { + await mp4LargeMoov(customException); + } else if (code.endsWith('mp4largeother')) { + await mp4LargeOther(customException); + } else if (code.endsWith('filenotfound')) { + await fileNotFound(customException); + } else { + await reportService.recordError(e, stack); + } + } + } + + // distinct exceptions to convince Crashlytics to split reports into distinct issues + // The distinct debug statement is there to make the body unique, so that the methods are not merged at compile time. + + Future<void> mp4LargeMoov(CustomPlatformException e) { + debugPrint('mp4LargeMoov $e'); + return reportService.recordError(e); + } + + Future<void> mp4LargeOther(CustomPlatformException e) { + debugPrint('mp4LargeOther $e'); + return reportService.recordError(e); + } + + Future<void> fileNotFound(CustomPlatformException e) { + debugPrint('fileNotFound $e'); + return reportService.recordError(e); + } +} + +class CustomPlatformException { + final String code; + final String? message; + final dynamic details; + final String? stacktrace; + + CustomPlatformException({ + required this.code, + this.message, + this.details, + this.stacktrace, + }); + + factory CustomPlatformException.fromStandard(PlatformException e) { + return CustomPlatformException( + code: e.code, + message: e.message, + details: e.details, + stacktrace: e.stacktrace, + ); + } + + @override + String toString() => '$runtimeType($code, $message, $details, $stacktrace)'; +} diff --git a/lib/services/metadata/metadata_fetch_service.dart b/lib/services/metadata/metadata_fetch_service.dart new file mode 100644 index 0000000..6fc95b9 --- /dev/null +++ b/lib/services/metadata/metadata_fetch_service.dart @@ -0,0 +1,306 @@ +import 'package:aves/convert/convert.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/media/geotiff.dart'; +import 'package:aves/model/media/panorama.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/metadata/overlay.dart'; +import 'package:aves/model/multipage.dart'; +import 'package:aves/services/common/service_policy.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/metadata/xmp.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:aves/services/common/channel.dart'; + +abstract class MetadataFetchService { + // returns Map<Map<Key, Value>> (map of directories, each directory being a map of metadata label and value description) + Future<Map> getAllMetadata(AvesEntry entry); + + Future<CatalogMetadata?> getCatalogMetadata(AvesEntry entry, {bool background = false}); + + Future<OverlayMetadata> getOverlayMetadata(AvesEntry entry, Set<MetadataSyntheticField> fields); + + Future<GeoTiffInfo?> getGeoTiffInfo(AvesEntry entry); + + Future<MultiPageInfo?> getMultiPageInfo(AvesEntry entry); + + Future<PanoramaInfo?> getPanoramaInfo(AvesEntry entry); + + Future<List<Map<String, dynamic>>?> getIptc(AvesEntry entry); + + Future<AvesXmp?> getXmp(AvesEntry entry); + + Future<bool> hasContentResolverProp(String prop); + + Future<String?> getContentResolverProp(AvesEntry entry, String prop); + + Future<DateTime?> getDate(AvesEntry entry, MetadataField field); + + Future<Map<String, dynamic>> getFields(AvesEntry entry, Set<MetadataField> fields); +} + +class PlatformMetadataFetchService implements MetadataFetchService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/metadata_fetch'); + + @override + Future<Map> getAllMetadata(AvesEntry entry) async { + if (entry.isSvg) return {}; + + try { + final result = await _platform.invokeMethod('getAllMetadata', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return {}; + } + + @override + Future<CatalogMetadata?> getCatalogMetadata(AvesEntry entry, {bool background = false}) async { + if (entry.isSvg) return null; + + Future<CatalogMetadata?> call() async { + try { + // returns map with: + // 'mimeType': MIME type as reported by metadata extractors, not Media Store (string) + // 'dateMillis': date taken in milliseconds since Epoch (long) + // 'isAnimated': animated gif/webp (bool) + // 'isFlipped': flipped according to EXIF orientation (bool) + // 'rating': rating in [-1,5] (int) + // 'rotationDegrees': rotation degrees according to EXIF orientation or other metadata (int) + // 'latitude': latitude (double) + // 'longitude': longitude (double) + // 'xmpSubjects': ';' separated XMP subjects (string) + // 'xmpTitle': XMP title (string) + final result = await _platform.invokeMethod('getCatalogMetadata', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'path': entry.path, + 'sizeBytes': entry.sizeBytes, + }) as Map; + result['id'] = entry.id; + AvesEntry.normalizeMimeTypeFields(result); + return CatalogMetadata.fromMap(result); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + return background + ? servicePolicy.call( + call, + priority: ServiceCallPriority.getMetadata, + ) + : call(); + } + + @override + Future<OverlayMetadata> getOverlayMetadata(AvesEntry entry, Set<MetadataSyntheticField> fields) async { + if (fields.isNotEmpty && !entry.isSvg) { + try { + // returns fields on demand, with various value types: + // 'aperture' (double), + // 'description' (string) + // 'exposureTime' (string), + // 'focalLength' (double), + // 'iso' (int), + final result = await _platform.invokeMethod('getOverlayMetadata', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'fields': fields.map((v) => v.toPlatform).toList(), + }) as Map; + return OverlayMetadata.fromMap(result); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + } + return const OverlayMetadata(); + } + + @override + Future<GeoTiffInfo?> getGeoTiffInfo(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('getGeoTiffInfo', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }) as Map; + return GeoTiffInfo.fromMap(result); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<MultiPageInfo?> getMultiPageInfo(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('getMultiPageInfo', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'isMotionPhoto': entry.isMotionPhoto, + }); + final pageMaps = ((result as List?) ?? []).cast<Map>(); + if (entry.isMotionPhoto && pageMaps.isNotEmpty) { + final imagePage = pageMaps[0]; + imagePage['width'] = entry.width; + imagePage['height'] = entry.height; + imagePage['rotationDegrees'] = entry.rotationDegrees; + } + pageMaps.forEach(AvesEntry.normalizeMimeTypeFields); + return MultiPageInfo.fromPageMaps(entry, pageMaps); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<PanoramaInfo?> getPanoramaInfo(AvesEntry entry) async { + try { + // returns map with values for: + // 'croppedAreaLeft' (int), 'croppedAreaTop' (int), 'croppedAreaWidth' (int), 'croppedAreaHeight' (int), + // 'fullPanoWidth' (int), 'fullPanoHeight' (int) + final result = await _platform.invokeMethod('getPanoramaInfo', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }) as Map; + return PanoramaInfo.fromMap(result); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<List<Map<String, dynamic>>?> getIptc(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('getIptc', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + }); + if (result != null) return (result as List).cast<Map>().map((fields) => fields.cast<String, dynamic>()).toList(); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<AvesXmp?> getXmp(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('getXmp', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }); + if (result != null) return AvesXmp.fromList((result as List).cast<String>()); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + final Map<String, bool> _contentResolverProps = {}; + + @override + Future<bool> hasContentResolverProp(String prop) async { + var exists = _contentResolverProps[prop]; + if (exists != null) return SynchronousFuture(exists); + + try { + exists = await _platform.invokeMethod('hasContentResolverProp', <String, dynamic>{ + 'prop': prop, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + exists ??= false; + _contentResolverProps[prop] = exists; + return exists; + } + + @override + Future<String?> getContentResolverProp(AvesEntry entry, String prop) async { + try { + return await _platform.invokeMethod('getContentResolverProp', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'prop': prop, + }); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<DateTime?> getDate(AvesEntry entry, MetadataField field) async { + try { + final result = await _platform.invokeMethod('getDate', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'field': field.toPlatform, + }); + if (result is int) { + return dateTimeFromMillis(result, isUtc: false); + } + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<Map<String, dynamic>> getFields(AvesEntry entry, Set<MetadataField> fields) async { + if (fields.isNotEmpty && !entry.isSvg) { + try { + final result = await _platform.invokeMethod('getFields', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'fields': fields.map((v) => v.toPlatform).toList(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + } + return {}; + } +} diff --git a/lib/services/metadata/svg_metadata_service.dart b/lib/services/metadata/svg_metadata_service.dart new file mode 100644 index 0000000..4160f1b --- /dev/null +++ b/lib/services/metadata/svg_metadata_service.dart @@ -0,0 +1,92 @@ +import 'dart:convert'; +import 'dart:ui'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/string_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:xml/xml.dart'; + +class SvgMetadataService { + static const docDirectory = 'Document'; + static const metadataDirectory = 'Metadata'; + + static const _attributes = ['x', 'y', 'width', 'height', 'preserveAspectRatio', 'viewBox']; + static const _textElements = ['title', 'desc']; + static const _metadataElement = 'metadata'; + + static Future<Size?> getSize(AvesEntry entry) async { + try { + final data = await mediaFetchService.getOriginalBytes(entry); + final document = XmlDocument.parse(utf8.decode(data)); + final root = document.rootElement; + + String? getAttribute(String attributeName) => root.attributes.firstWhereOrNull((a) => a.name.qualified == attributeName)?.value; + double? tryParseWithoutUnit(String? s) => s == null ? null : double.tryParse(s.replaceAll(RegExp(r'[a-z%]'), '')); + + // prefer the viewbox over the viewport to determine size + + // viewbox + final viewBox = getAttribute('viewBox'); + if (viewBox != null) { + final parts = viewBox.split(RegExp(r'[\s,]+')); + if (parts.length == 4) { + final vbWidth = tryParseWithoutUnit(parts[2]); + final vbHeight = tryParseWithoutUnit(parts[3]); + if (vbWidth != null && vbWidth > 0 && vbHeight != null && vbHeight > 0) { + return Size(vbWidth, vbHeight); + } + } + } + + // viewport + final width = tryParseWithoutUnit(getAttribute('width')); + final height = tryParseWithoutUnit(getAttribute('height')); + if (width != null && height != null) { + return Size(width, height); + } + } catch (error, stack) { + debugPrint('failed to parse XML from SVG with error=$error\n$stack'); + } + return null; + } + + static Future<Map<String, Map<String, String>>> getAllMetadata(AvesEntry entry) async { + String formatKey(String key) { + switch (key) { + case 'desc': + return 'Description'; + default: + return key.toSentenceCase(); + } + } + + try { + final data = await mediaFetchService.getOriginalBytes(entry); + final document = XmlDocument.parse(utf8.decode(data)); + final root = document.rootElement; + + final docDir = Map.fromEntries([ + ...root.attributes.where((a) => _attributes.contains(a.name.qualified)).map((a) => MapEntry(formatKey(a.name.qualified), a.value)), + ..._textElements.map((name) { + final value = root.getElement(name)?.innerText; + return value != null ? MapEntry(formatKey(name), value) : null; + }).nonNulls, + ]); + + final metadata = root.getElement(_metadataElement); + final metadataDir = Map.fromEntries([ + if (metadata != null) MapEntry('Metadata', metadata.toXmlString(pretty: true)), + ]); + + return { + if (docDir.isNotEmpty) docDirectory: docDir, + if (metadataDir.isNotEmpty) metadataDirectory: metadataDir, + }; + } catch (error, stack) { + debugPrint('failed to parse XML from SVG with error=$error\n$stack'); + } + return {}; + } +} diff --git a/lib/services/metadata/xmp.dart b/lib/services/metadata/xmp.dart new file mode 100644 index 0000000..e56adec --- /dev/null +++ b/lib/services/metadata/xmp.dart @@ -0,0 +1,40 @@ +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class AvesXmp extends Equatable { + final String? xmpString; + final String? extendedXmpString; + + @override + List<Object?> get props => [xmpString, extendedXmpString]; + + const AvesXmp({ + required this.xmpString, + this.extendedXmpString, + }); + + static AvesXmp fromList(List<String> xmpStrings) { + switch (xmpStrings.length) { + case 0: + return const AvesXmp(xmpString: null); + case 1: + return AvesXmp(xmpString: xmpStrings.single); + default: + final byExtending = groupBy<String, bool>(xmpStrings, (v) => v.contains(':HasExtendedXMP=')); + final extending = byExtending[true] ?? []; + final extension = byExtending[false] ?? []; + if (extending.length == 1 && extension.length == 1) { + return AvesXmp( + xmpString: extending.single, + extendedXmpString: extension.single, + ); + } + + // take the first XMP and ignore the rest when the file is weirdly constructed + debugPrint('warning: entry has ${xmpStrings.length} XMP directories, xmpStrings=$xmpStrings'); + return AvesXmp(xmpString: xmpStrings.firstOrNull); + } + } +} |
