π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Use Rust metadata for local photos
Neeraj Guptae6a63222a119
diff --git a/mobile/apps/photos/lib/db/files_db.dart b/mobile/apps/photos/lib/db/files_db.dartindex 5a00e29802..b0c615e2dd 100644--- a/mobile/apps/photos/lib/db/files_db.dart+++ b/mobile/apps/photos/lib/db/files_db.dart@@ -1,4 +1,5 @@import "dart:async";+import "dart:convert";import "dart:io";import "dart:math";@@ -16,6 +17,7 @@ import 'package:photos/models/file_load_result.dart';import 'package:photos/models/freeable_space_info.dart';import 'package:photos/models/location/location.dart';import "package:photos/models/metadata/common_keys.dart";+import "package:photos/models/metadata/file_magic.dart";import "package:photos/services/filter/db_filters.dart";import 'package:sqlite_async/sqlite_async.dart';@@ -1179,33 +1181,72 @@ class FilesDB with SqlDbBase {);}- Future<void> updateOfflineImportMetadataForLocalID(+ Future<void> refreshLocalDimensions(List<EnteFile> files) async {+ final db = await instance.sqliteAsyncDB;+ await db.writeTransaction((tx) async {+ for (final file in files) {+ await tx.execute(+ '''+ UPDATE $filesTable+ SET $columnModificationTime = ?,+ $columnPubMMdEncodedJson = json_patch(COALESCE($columnPubMMdEncodedJson, '{}'), ?),+ $columnMetadataVersion = -1+ WHERE $columnLocalID = ? AND $columnModificationTime != ?+ AND ($columnUploadedFileID IS NULL OR $columnUploadedFileID = -1)+ ''',+ [+ file.modificationTime,+ jsonEncode({+ widthKey: file.hasDimensions ? file.width : null,+ heightKey: file.hasDimensions ? file.height : null,+ }),+ file.localID,+ file.modificationTime,+ ],+ );+ }+ });+ }++ Future<bool> updateOfflineImportMetadataForLocalID(String localID, {required int processingVersion,+ required int modificationTime,int? creationTime,Location? location,int? fileSize,+ ({int width, int height})? dimensions,}) async {final db = await instance.sqliteAsyncDB;- await db.execute(+ final result = await db.execute('''UPDATE $filesTableSET $columnCreationTime = COALESCE(?, $columnCreationTime),$columnLatitude = COALESCE(?, $columnLatitude),$columnLongitude = COALESCE(?, $columnLongitude),$columnFileSize = COALESCE(?, $columnFileSize),+ $columnPubMMdEncodedJson = json_patch(COALESCE($columnPubMMdEncodedJson, '{}'), ?),$columnMetadataVersion = ?- WHERE $columnLocalID = ? AND ($columnUploadedFileID IS NULL OR $columnUploadedFileID = -1);+ WHERE $columnLocalID = ? AND $columnModificationTime = ?+ AND ($columnUploadedFileID IS NULL OR $columnUploadedFileID = -1)+ RETURNING $columnLocalID;''',[creationTime,location?.latitude,location?.longitude,fileSize,+ jsonEncode(+ dimensions == null+ ? {}+ : {widthKey: dimensions.width, heightKey: dimensions.height},+ ),processingVersion,localID,+ modificationTime,],);+ return result.isNotEmpty;}Future<List<EnteFile>> getUnlinkedLocalMatchesForRemoteFile(diff --git a/mobile/apps/photos/lib/module/metadata/local_file.dart b/mobile/apps/photos/lib/module/metadata/local_file.dartindex 043c0968f8..599bd6dc13 100644--- a/mobile/apps/photos/lib/module/metadata/local_file.dart+++ b/mobile/apps/photos/lib/module/metadata/local_file.dart@@ -1,3 +1,4 @@+import "dart:convert";import "dart:io";import "package:ente_pure_utils/ente_pure_utils.dart";@@ -5,12 +6,13 @@ import "package:photo_manager/photo_manager.dart";import "package:photos/models/file/file.dart";import "package:photos/models/file/file_type.dart";import "package:photos/models/location/location.dart";+import "package:photos/models/metadata/file_magic.dart";import "package:photos/module/metadata/asset_date_times.dart";import "package:photos/module/metadata/exif.dart";EnteFile fileFromAsset(String deviceFolder, AssetEntity asset) {final resolvedDateTimes = resolveAssetDateTimes(asset);- return EnteFile()+ final file = EnteFile()..localID = asset.id..title = asset.title..deviceFolder = deviceFolder@@ -20,6 +22,17 @@ EnteFile fileFromAsset(String deviceFolder, AssetEntity asset) {..modificationTime = resolvedDateTimes.modificationTime..fileSubType = asset.subtype..metadataVersion = -1;+ applyDisplayDimensions(file, asset.orientatedWidth, asset.orientatedHeight);+ return file;+}++void applyDisplayDimensions(EnteFile file, int width, int height) {+ if (width <= 0 || height <= 0) return;+ file.pubMmdEncodedJson = jsonEncode({+ ...jsonDecode(file.pubMmdEncodedJson ?? '{}') as Map<String, dynamic>,+ widthKey: width,+ heightKey: height,+ });}void applyCreationTimeMetadata(EnteFile file, ParsedExifDateTime? exifTime) {diff --git a/mobile/apps/photos/lib/module/metadata/photo.dart b/mobile/apps/photos/lib/module/metadata/photo.dartnew file mode 100644index 0000000000..688c70ecaf--- /dev/null+++ b/mobile/apps/photos/lib/module/metadata/photo.dart@@ -0,0 +1,39 @@+import "dart:io";++import "package:logging/logging.dart";+import "package:photos/models/location/location.dart";+import "package:photos/module/metadata/exif.dart";+import "package:photos/src/rust/api/metadata_api.dart";++final _logger = Logger("PhotoMetadata");++Future<PhotoMetadata?> tryReadPhotoMetadata(File file) async {+ try {+ return await readPhotoMetadata(filePath: file.path);+ } catch (e, s) {+ _logger.warning("Failed to read photo metadata", e, s);+ return null;+ }+}++extension PhotoMetadataValues on PhotoMetadata {+ ParsedExifDateTime? get creationDateTime {+ final date = captureDateTime;+ if (date == null) return null;+ final timestamp = date.timestampMicros;+ return ParsedExifDateTime(+ timestamp == null+ ? DateTime.parse(date.dateTime)+ : DateTime.fromMicrosecondsSinceEpoch(timestamp.toInt()),+ date.dateTime,+ date.offsetTime,+ );+ }++ Location? get embeddedLocation {+ final value = location;+ return value == null+ ? null+ : Location(latitude: value.latitude, longitude: value.longitude);+ }+}diff --git a/mobile/apps/photos/lib/services/sync/local_sync_service.dart b/mobile/apps/photos/lib/services/sync/local_sync_service.dartindex 8ccaf3e6be..302fc10f16 100644--- a/mobile/apps/photos/lib/services/sync/local_sync_service.dart+++ b/mobile/apps/photos/lib/services/sync/local_sync_service.dart@@ -472,6 +472,7 @@ class LocalSyncService {"track ${updatedFiles.length}/ $updateCount files due to modification change",);if (updatedFiles.isNotEmpty) {+ await _db.refreshLocalDimensions(updatedFiles);await FileUpdationDB.instance.insertMultiple(updatedFiles.map((file) => file.localID!).toList(),FileUpdationDB.modificationTimeUpdated,diff --git a/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dart b/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dartindex f817dbcd33..1df052b111 100644--- a/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dart+++ b/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dart@@ -1,7 +1,6 @@import "dart:async";import "dart:io";-import "package:exif_reader/exif_reader.dart";import "package:logging/logging.dart";import "package:photos/core/event_bus.dart";import "package:photos/db/files_db.dart";@@ -14,11 +13,12 @@ import "package:photos/module/download/file.dart";import "package:photos/module/metadata/exif.dart";import "package:photos/module/metadata/local_file.dart";import 'package:photos/module/metadata/location.dart';+import "package:photos/module/metadata/photo.dart";import "package:photos/service_locator.dart";import "package:photos/services/process_activity.dart";class OfflineImportMetadataService {- static const kProcessingVersion = 1;+ static const kProcessingVersion = 2;static const kDefaultBatchSize = 25;final _logger = Logger("OfflineImportMetadataService");@@ -99,32 +99,41 @@ class OfflineImportMetadataService {}Future<bool> _processFile(EnteFile file) async {- File? originFile;try {- originFile = await getFile(file, isOrigin: true);+ final originFile = await getFile(file, isOrigin: true);if (originFile == null || !originFile.existsSync()) {return false;}final fileSize = await originFile.length();- final exifData = shouldReadExif(file)- ? await tryExifFromFile(originFile)- : null;- final exifTime = exifData != null- ? await tryParseExifDateTime(null, exifData)+ final metadata = shouldReadExif(file)+ ? await tryReadPhotoMetadata(originFile): null;+ final dimensions = metadata?.dimensions;+ if (dimensions != null) {+ applyDisplayDimensions(file, dimensions.width, dimensions.height);+ }- await _updateLocationForOfflineFile(file, originFile, exifData);+ await _updateLocationAndDimensions(+ file,+ originFile,+ metadata?.embeddedLocation,+ );- applyCreationTimeMetadata(file, exifTime);+ applyCreationTimeMetadata(file, metadata?.creationDateTime);- await _db.updateOfflineImportMetadataForLocalID(+ final updated = await _db.updateOfflineImportMetadataForLocalID(file.localID!,processingVersion: kProcessingVersion,+ modificationTime: file.modificationTime!,creationTime: file.creationTime,location: file.location,fileSize: fileSize,+ dimensions: file.hasDimensions+ ? (width: file.width, height: file.height)+ : null,);+ if (!updated) return false;file.fileSize = fileSize;file.metadataVersion = kProcessingVersion;@@ -132,39 +141,40 @@ class OfflineImportMetadataService {} catch (e, s) {_logger.warning("Failed to process ${file.tag}", e, s);return false;- } finally {- if (Platform.isIOS &&- originFile != null &&- !file.isSharedMediaToAppSandbox) {- try {- await originFile.delete();- } catch (_) {}- }}}- Future<void> _updateLocationForOfflineFile(+ Future<void> _updateLocationAndDimensions(EnteFile file,File originFile,- Map<String, IfdTag>? exifData,+ Location? embeddedLocation,) async {- final shouldFetchAssetLocation =- file.location == null ||- ((file.location?.latitude ?? 0) == 0 &&- (file.location?.longitude ?? 0) == 0);- if (shouldFetchAssetLocation) {+ if (Location.isValidLocation(embeddedLocation)) {+ file.location = embeddedLocation;+ }+ final shouldFetchAssetLocation = !Location.isValidLocation(file.location);+ if (shouldFetchAssetLocation || !file.hasDimensions) {final asset = await file.getAsset;if (asset != null) {- final latLong = await asset.latlngAsync();- if (latLong != null) {- file.location = Location(- latitude: latLong.latitude,- longitude: latLong.longitude,+ if (!file.hasDimensions) {+ applyDisplayDimensions(+ file,+ asset.orientatedWidth,+ asset.orientatedHeight,);}+ if (shouldFetchAssetLocation) {+ final latLong = await asset.latlngAsync();+ if (latLong != null) {+ file.location = Location(+ latitude: latLong.latitude,+ longitude: latLong.longitude,+ );+ }+ }}}- await updateLocationFromEmbeddedMetadata(file, originFile, exifData);+ await updateLocationFromEmbeddedMetadata(file, originFile, null);}}diff --git a/mobile/apps/photos/test/db/offline_metadata_test.dart b/mobile/apps/photos/test/db/offline_metadata_test.dartnew file mode 100644index 0000000000..a60df84bdc--- /dev/null+++ b/mobile/apps/photos/test/db/offline_metadata_test.dart@@ -0,0 +1,129 @@+import "dart:convert";+import "dart:io";++import "package:flutter_test/flutter_test.dart";+import "package:path_provider_platform_interface/path_provider_platform_interface.dart";+import "package:photos/db/files_db.dart";+import "package:photos/models/file/file.dart";+import "package:photos/module/metadata/local_file.dart";++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ final files = FilesDB.instance;+ late Directory directory;+ late PathProviderPlatform previousPathProvider;++ setUpAll(() async {+ directory = await Directory.systemTemp.createTemp("offline_metadata_");+ previousPathProvider = PathProviderPlatform.instance;+ PathProviderPlatform.instance = _PathProvider(directory.path);+ });++ tearDownAll(() async {+ await (await files.sqliteAsyncDB).close();+ PathProviderPlatform.instance = previousPathProvider;+ await directory.delete(recursive: true);+ });++ test(+ "persists dimensions, refreshes edits and rejects stale results only for local rows",+ () async {+ final db = await files.sqliteAsyncDB;+ for (final (uploadedID, collectionID) in [(-1, 1), (-1, 2), (99, 3)]) {+ await db.execute(+ '''+ INSERT INTO ${FilesDB.filesTable}+ (${FilesDB.columnLocalID}, ${FilesDB.columnUploadedFileID},+ ${FilesDB.columnCollectionID}, ${FilesDB.columnTitle},+ ${FilesDB.columnCreationTime}, ${FilesDB.columnModificationTime},+ ${FilesDB.columnMetadataVersion}, ${FilesDB.columnPubMMdEncodedJson})+ VALUES ('local', ?, ?, 'photo.jpg', 100, 100, 1, ?)+ ''',+ [uploadedID, collectionID, '{"caption":"Keep me","w":4000,"h":3000}'],+ );+ }++ expect(+ await files.updateOfflineImportMetadataForLocalID(+ "local",+ processingVersion: 2,+ modificationTime: 100,+ dimensions: (width: 3000, height: 4000),+ ),+ isTrue,+ );++ final rows = await db.getAll(+ 'SELECT * FROM ${FilesDB.filesTable} ORDER BY ${FilesDB.columnCollectionID}',+ );+ for (final row in rows.take(2)) {+ final file = EnteFile()+ ..pubMmdEncodedJson = row[FilesDB.columnPubMMdEncodedJson] as String;+ expect((file.width, file.height), (3000, 4000));+ expect(file.pubMagicMetadata!.caption, "Keep me");+ expect(row[FilesDB.columnMetadataVersion], 2);+ }+ expect(+ jsonDecode(rows.last[FilesDB.columnPubMMdEncodedJson] as String)['w'],+ 4000,+ );+ expect(rows.last[FilesDB.columnMetadataVersion], 1);++ final edited = EnteFile()+ ..localID = "local"+ ..modificationTime = 200;+ applyDisplayDimensions(edited, 800, 600);+ await files.refreshLocalDimensions([edited]);+ expect(+ await files.updateOfflineImportMetadataForLocalID(+ "local",+ processingVersion: 2,+ modificationTime: 100,+ dimensions: (width: 3000, height: 4000),+ ),+ isFalse,+ );+ final pending = await db.getAll(+ 'SELECT * FROM ${FilesDB.filesTable} WHERE ${FilesDB.columnMetadataVersion} = -1',+ );+ expect(pending, hasLength(2));+ expect(+ jsonDecode(pending.first[FilesDB.columnPubMMdEncodedJson] as String),+ {"caption": "Keep me", "w": 800, "h": 600},+ );++ expect(+ await files.updateOfflineImportMetadataForLocalID(+ "local",+ processingVersion: 2,+ modificationTime: 200,+ ),+ isTrue,+ );+ await files.refreshLocalDimensions([edited]);+ expect(+ await db.getAll(+ 'SELECT * FROM ${FilesDB.filesTable} WHERE ${FilesDB.columnMetadataVersion} = -1',+ ),+ isEmpty,+ );+ final refreshed = await db.getAll(+ 'SELECT * FROM ${FilesDB.filesTable} WHERE ${FilesDB.columnUploadedFileID} = -1',+ );+ expect(+ jsonDecode(+ refreshed.first[FilesDB.columnPubMMdEncodedJson] as String,+ )['w'],+ 800,+ );+ },+ );+}++class _PathProvider extends PathProviderPlatform {+ _PathProvider(this.path);+ final String path;++ @override+ Future<String?> getApplicationDocumentsPath() async => path;+}diff --git a/mobile/apps/photos/test/module/metadata/photo_test.dart b/mobile/apps/photos/test/module/metadata/photo_test.dartnew file mode 100644index 0000000000..b8a419ecd0--- /dev/null+++ b/mobile/apps/photos/test/module/metadata/photo_test.dart@@ -0,0 +1,71 @@+import "package:flutter_test/flutter_test.dart";+import "package:photo_manager/photo_manager.dart";+import "package:photos/models/file/file.dart";+import "package:photos/module/metadata/local_file.dart";+import "package:photos/module/metadata/photo.dart";+import "package:photos/src/rust/api/metadata_api.dart";++void main() {+ test("local discovery supplies oriented mosaic dimensions", () {+ final file = fileFromAsset(+ "Camera",+ AssetEntity(+ id: "rotated",+ typeInt: 1,+ width: 4000,+ height: 3000,+ orientation: 90,+ createDateSecond: 1704110400,+ modifiedDateSecond: 1704110400,+ ),+ );+ expect((file.width, file.height), (3000, 4000));+ expect(file.metadataVersion, -1);+ });++ test(+ "refined dimensions invalidate the model cache and preserve other fields",+ () {+ final file = EnteFile()+ ..pubMmdEncodedJson = '{"w":4000,"h":3000,"caption":"Keep me"}';+ expect(file.width, 4000);+ expect(file.pubMagicMetadata!.caption, "Keep me");+ applyDisplayDimensions(file, 1200, 1600);+ expect((file.width, file.height), (1200, 1600));+ expect(file.pubMagicMetadata!.caption, "Keep me");+ applyDisplayDimensions(file, 0, 100);+ expect((file.width, file.height), (1200, 1600));+ },+ );++ test("uses the parsed instant without applying the offset twice", () {+ const metadata = PhotoMetadata(+ dimensions: null,+ location: null,+ captureDateTime: CaptureDateTime(+ dateTime: "2024-01-01T12:00:00.123456",+ offsetTime: "-00:30",+ timestampMicros: 1704112200123456,+ ),+ );+ final date = metadata.creationDateTime!;+ expect(date.time.toUtc(), DateTime.utc(2024, 1, 1, 12, 30, 0, 123, 456));+ expect(date.dateTime, "2024-01-01T12:00:00.123456");+ expect(date.offsetTime, "-00:30");+ });++ test("resolves an offset-free time locally without inventing an offset", () {+ const metadata = PhotoMetadata(+ dimensions: null,+ location: null,+ captureDateTime: CaptureDateTime(+ dateTime: "2024-01-01T12:00:00",+ offsetTime: null,+ timestampMicros: null,+ ),+ );+ final date = metadata.creationDateTime!;+ expect(date.time, DateTime(2024, 1, 1, 12));+ expect(date.offsetTime, isNull);+ });+}diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 54c953677b..791a0e84ba 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2732,6 +2732,7 @@ name = "ente-photos"version = "0.0.0"dependencies = ["ente-assets",+ "ente-exif","ente-location","quick-xml","rusqlite",diff --git a/rust/bindings/frb/photos/src/api/metadata_api.rs b/rust/bindings/frb/photos/src/api/metadata_api.rsnew file mode 100644index 0000000000..63b44e02c3--- /dev/null+++ b/rust/bindings/frb/photos/src/api/metadata_api.rs@@ -0,0 +1,41 @@+use super::location_api::LocationCoordinate;++#[derive(Clone, Debug)]+pub struct PhotoMetadata {+ pub dimensions: Option<Dimensions>,+ pub capture_date_time: Option<CaptureDateTime>,+ pub location: Option<LocationCoordinate>,+}++#[derive(Clone, Debug)]+pub struct Dimensions {+ pub width: u32,+ pub height: u32,+}++#[derive(Clone, Debug)]+pub struct CaptureDateTime {+ pub date_time: String,+ pub offset_time: Option<String>,+ pub timestamp_micros: Option<i64>,+}++pub fn read_photo_metadata(file_path: String) -> Result<PhotoMetadata, String> {+ let metadata =+ ente_photos::metadata::read_photo_metadata(file_path).map_err(|error| error.to_string())?;+ Ok(PhotoMetadata {+ dimensions: metadata.dimensions.map(|dimensions| Dimensions {+ width: dimensions.width,+ height: dimensions.height,+ }),+ capture_date_time: metadata.capture_date_time.map(|date| CaptureDateTime {+ date_time: date.date_time,+ offset_time: date.offset_time,+ timestamp_micros: date.timestamp_micros,+ }),+ location: metadata.location.map(|location| LocationCoordinate {+ latitude: location.latitude,+ longitude: location.longitude,+ }),+ })+}diff --git a/rust/bindings/frb/photos/src/api/mod.rs b/rust/bindings/frb/photos/src/api/mod.rsindex b4e97a960a..87cebac3e2 100644--- a/rust/bindings/frb/photos/src/api/mod.rs+++ b/rust/bindings/frb/photos/src/api/mod.rs@@ -5,6 +5,7 @@ pub mod location_api;#[cfg(any(feature = "flutter", frb_expand))]pub mod log;pub mod map_cluster_api;+pub mod metadata_api;pub mod ml_db_api;pub mod ml_indexing_api;pub mod motion_photo_api;diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.tomlindex 33033b822a..d06d47fd4f 100644--- a/rust/crates/photos/Cargo.toml+++ b/rust/crates/photos/Cargo.toml@@ -4,6 +4,7 @@ edition.workspace = true[dependencies]ente-assets.workspace = true+ente-exif.workspace = trueente-location.workspace = truequick-xml.workspace = truerusqlite = { workspace = true, default-features = true }diff --git a/rust/crates/photos/src/lib.rs b/rust/crates/photos/src/lib.rsindex 893827368c..c06e85f79b 100644--- a/rust/crates/photos/src/lib.rs+++ b/rust/crates/photos/src/lib.rs@@ -1,5 +1,6 @@pub mod db;pub mod location;+pub mod metadata;pub mod ml_db;pub mod motion_photo;diff --git a/rust/crates/photos/src/metadata.rs b/rust/crates/photos/src/metadata.rsnew file mode 100644index 0000000000..6a54e345ac--- /dev/null+++ b/rust/crates/photos/src/metadata.rs@@ -0,0 +1,19 @@+use std::{fs::File, path::Path};++use ente_exif::{CaptureDateTime, Dimensions, Error, Limits, Location, Mode};++#[derive(Debug)]+pub struct PhotoMetadata {+ pub dimensions: Option<Dimensions>,+ pub capture_date_time: Option<CaptureDateTime>,+ pub location: Option<Location>,+}++pub fn read_photo_metadata(path: impl AsRef<Path>) -> Result<PhotoMetadata, Error> {+ let metadata = ente_exif::read(&mut File::open(path)?, Mode::Summary, Limits::default())?;+ Ok(PhotoMetadata {+ dimensions: metadata.display_dimensions(),+ capture_date_time: metadata.capture_date_time(),+ location: metadata.exif_location().or_else(|| metadata.xmp_location()),+ })+}diff --git a/rust/crates/photos/tests/metadata_test.rs b/rust/crates/photos/tests/metadata_test.rsnew file mode 100644index 0000000000..a657aa92b5--- /dev/null+++ b/rust/crates/photos/tests/metadata_test.rs@@ -0,0 +1,41 @@+use std::io::Write;++use ente_exif::{Dimensions, Location};+use ente_photos::metadata::read_photo_metadata;++#[test]+fn reads_display_dimensions_capture_time_and_xmp_location() {+ let properties = r#"tiff:Orientation="6" exif:DateTimeOriginal="2024-01-01T12:00:00.123456-00:30"+ exif:GPSLatitude="40,30N" exif:GPSLongitude="74,15W""#;+ let xmp = format!(+ "http://ns.adobe.com/xap/1.0/\0<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description xmlns:exif=\"http://ns.adobe.com/exif/1.0/\" xmlns:tiff=\"http://ns.adobe.com/tiff/1.0/\" {properties}/></rdf:RDF>"+ );+ let mut file = tempfile::NamedTempFile::new().unwrap();+ file.write_all(&[0xff, 0xd8, 0xff, 0xe1]).unwrap();+ file.write_all(&u16::try_from(xmp.len() + 2).unwrap().to_be_bytes())+ .unwrap();+ file.write_all(xmp.as_bytes()).unwrap();+ file.write_all(&[+ 0xff, 0xc0, 0, 11, 8, 0, 48, 0, 64, 1, 1, 0x11, 0, 0xff, 0xd9,+ ])+ .unwrap();+ let metadata = read_photo_metadata(file.path()).unwrap();+ assert_eq!(+ metadata.dimensions,+ Some(Dimensions {+ width: 48,+ height: 64+ })+ );+ let date = metadata.capture_date_time.unwrap();+ assert_eq!(date.date_time, "2024-01-01T12:00:00.123456000");+ assert_eq!(date.offset_time.as_deref(), Some("-00:30"));+ assert_eq!(date.timestamp_micros, Some(1_704_112_200_123_456));+ assert_eq!(+ metadata.location,+ Some(Location {+ latitude: 40.5,+ longitude: -74.25+ })+ );+}