π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Handle ISO-like EXIF dates
Neeraj Gupta3db8cde49a89
diff --git a/mobile/apps/photos/lib/utils/exif_util.dart b/mobile/apps/photos/lib/utils/exif_util.dartindex f66f4f24aa..e9476bb62d 100644--- a/mobile/apps/photos/lib/utils/exif_util.dart+++ b/mobile/apps/photos/lib/utils/exif_util.dart@@ -25,6 +25,13 @@ const kExifDateTimePattern = "yyyy:MM:dd HH:mm:ss";const kEmptyExifDateTime = "0000:00:00 00:00:00";final _logger = Logger("ExifUtil");+final _standardExifDateTimePattern = RegExp(+ r'^\d{4}:(0[1-9]|1[0-2]):(0[1-9]|[12]\d|3[01]) ([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$',+);+final _isoExifDateTimePattern = RegExp(+ r'^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])[T ]([01]\d|2[0-3]):([0-5]\d):([0-5]\d)([\.:]\d+)?([Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)?$',+);+final _offsetPattern = RegExp(r'^([Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)$');Future<Map<String, IfdTag>> getExif(EnteFile file) async {try {@@ -61,8 +68,9 @@ Future<FFProbeProps?> getVideoPropsAsync(File originalFile) async {try {final stopwatch = Stopwatch()..start();- final mediaInfo =- await IsolatedFfmpegService.instance.getVideoInfo(originalFile.path);+ final mediaInfo = await IsolatedFfmpegService.instance.getVideoInfo(+ originalFile.path,+ );if (mediaInfo.isEmpty) {return null;}@@ -112,8 +120,8 @@ Future<ParsedExifDateTime?> tryParseExifDateTime(final exifTime = exif.containsKey(kDateTimeOriginal)? exif[kDateTimeOriginal]!.printable: exif.containsKey(kImageDateTime)- ? exif[kImageDateTime]!.printable- : null;+ ? exif[kImageDateTime]!.printable+ : null;if (exifTime == null || exifTime == kEmptyExifDateTime) {return null;}@@ -135,36 +143,153 @@ ParsedExifDateTime getDateTimeInDeviceTimezone(String exifTime,String? offsetString,) {- final hasOffset = (offsetString ?? '') != '';- final DateTime result =- DateFormat(kExifDateTimePattern).parse(exifTime, hasOffset);- if (hasOffset && offsetString!.toUpperCase() != "Z") {- try {- final List<String> splitHHMM = offsetString.split(":");- final int offsetHours = int.parse(splitHHMM[0]);- final int offsetMinutes =- int.parse(splitHHMM[1]) * (offsetHours.isNegative ? -1 : 1);- // Adjust the date for the offset to get the photo's correct UTC time- final photoUtcDate =- result.add(Duration(hours: -offsetHours, minutes: -offsetMinutes));- // Convert the UTC time to the device's local time- final deviceLocalTime = photoUtcDate.toLocal();- return ParsedExifDateTime(- deviceLocalTime,- result.toIso8601String(),- offsetString,- );- } catch (e, s) {- _logger.severe("offset parsing failed $exifTime && $offsetString", e, s);- }+ final trimmedExifTime = exifTime.trim();+ if (_isoExifDateTimePattern.hasMatch(trimmedExifTime)) {+ return _getIsoExifDateTimeInDeviceTimezone(trimmedExifTime, offsetString);+ }+ if (_standardExifDateTimePattern.hasMatch(trimmedExifTime)) {+ return _getStandardExifDateTimeInDeviceTimezone(+ trimmedExifTime,+ offsetString,+ );+ }+ throw FormatException("Unsupported EXIF date time format", exifTime);+}++ParsedExifDateTime _getStandardExifDateTimeInDeviceTimezone(+ String exifTime,+ String? offsetString,+) {+ final offsetTime = _normalizeOffset(offsetString, throwOnInvalid: true);+ final hasOffset = offsetTime != null;+ final DateTime result = DateFormat(+ kExifDateTimePattern,+ ).parseStrict(exifTime, hasOffset);+ if (hasOffset && offsetTime != "Z") {+ final List<String> splitHHMM = offsetTime.split(":");+ final int offsetHours = int.parse(splitHHMM[0]);+ final int offsetMinutes =+ int.parse(splitHHMM[1]) * (offsetHours.isNegative ? -1 : 1);+ // Adjust the date for the offset to get the photo's correct UTC time+ final photoUtcDate = result.add(+ Duration(hours: -offsetHours, minutes: -offsetMinutes),+ );+ // Convert the UTC time to the device's local time+ final deviceLocalTime = photoUtcDate.toLocal();+ return ParsedExifDateTime(+ deviceLocalTime,+ result.toIso8601String(),+ offsetTime,+ );}return ParsedExifDateTime(result,result.toIso8601String(),- (offsetString ?? '').toUpperCase() == 'Z' ? 'Z' : null,+ offsetTime == "Z" ? "Z" : null,);}+ParsedExifDateTime _getIsoExifDateTimeInDeviceTimezone(+ String exifTime,+ String? offsetString,+) {+ final match = _isoExifDateTimePattern.firstMatch(exifTime.trim());+ if (match == null) {+ throw FormatException("Unsupported EXIF date time format", exifTime);+ }++ final metadataDateTime = _parseIsoDateTimeComponents(match);+ final localDateTimeString = _dateTimeWithoutUtcMarker(metadataDateTime);+ final offsetTime =+ _normalizeOffset(match.group(8)) ??+ _normalizeOffset(offsetString, throwOnInvalid: true);++ if (offsetTime != null) {+ final deviceLocalTime = DateTime.parse(+ "$localDateTimeString$offsetTime",+ ).toLocal();+ return ParsedExifDateTime(+ deviceLocalTime,+ metadataDateTime.toIso8601String(),+ offsetTime,+ );+ }++ return ParsedExifDateTime(+ DateTime(+ metadataDateTime.year,+ metadataDateTime.month,+ metadataDateTime.day,+ metadataDateTime.hour,+ metadataDateTime.minute,+ metadataDateTime.second,+ metadataDateTime.millisecond,+ metadataDateTime.microsecond,+ ),+ metadataDateTime.toIso8601String(),+ null,+ );+}++String? _normalizeOffset(+ String? offsetString, {+ bool throwOnInvalid = false,+}) {+ final offset = offsetString?.trim();+ if (offset == null || offset.isEmpty) {+ return null;+ }+ if (!_offsetPattern.hasMatch(offset)) {+ if (throwOnInvalid) {+ throw FormatException("Invalid EXIF offset", offsetString);+ }+ return null;+ }+ return offset.toUpperCase();+}++DateTime _parseIsoDateTimeComponents(RegExpMatch match) {+ final year = int.parse(match.group(1)!);+ final month = int.parse(match.group(2)!);+ final day = int.parse(match.group(3)!);+ final hour = int.parse(match.group(4)!);+ final minute = int.parse(match.group(5)!);+ final second = int.parse(match.group(6)!);+ final microsecond = _parseFractionalMicroseconds(match.group(7));+ final dateTime = DateTime.utc(+ year,+ month,+ day,+ hour,+ minute,+ second,+ microsecond ~/ Duration.microsecondsPerMillisecond,+ microsecond % Duration.microsecondsPerMillisecond,+ );+ if (dateTime.year != year ||+ dateTime.month != month ||+ dateTime.day != day ||+ dateTime.hour != hour ||+ dateTime.minute != minute ||+ dateTime.second != second) {+ throw FormatException("Invalid EXIF date time", match.group(0));+ }+ return dateTime;+}++int _parseFractionalMicroseconds(String? fraction) {+ if (fraction == null) {+ return 0;+ }+ final paddedFraction = fraction.substring(1).padRight(6, "0");+ return int.parse(paddedFraction.substring(0, 6));+}++String _dateTimeWithoutUtcMarker(DateTime dateTime) {+ final value = dateTime.toIso8601String();+ return value.endsWith("Z") ? value.substring(0, value.length - 1) : value;+}+Location? locationFromExif(Map<String, IfdTag> exif) {try {return gpsDataFromExif(exif).toLocationObj();@@ -212,15 +337,13 @@ GPSData gpsDataFromExif(Map<String, IfdTag> exif) {"longRef": null,};if (exif["GPS GPSLatitude"] != null) {- exifLocationData["lat"] = exif["GPS GPSLatitude"]!- .values+ exifLocationData["lat"] = exif["GPS GPSLatitude"]!.values.toList().map((e) => ((e as Ratio).numerator / e.denominator)).toList();}if (exif["GPS GPSLongitude"] != null) {- exifLocationData["long"] = exif["GPS GPSLongitude"]!- .values+ exifLocationData["long"] = exif["GPS GPSLongitude"]!.values.toList().map((e) => ((e as Ratio).numerator / e.denominator)).toList();diff --git a/mobile/apps/photos/scripts/internal_changes.txt b/mobile/apps/photos/scripts/internal_changes.txtindex 315e290f02..97b5ee10a1 100644--- a/mobile/apps/photos/scripts/internal_changes.txt+++ b/mobile/apps/photos/scripts/internal_changes.txt@@ -1,4 +1,5 @@Latest changes:+- Neeraj: Fix incorrect upload dates for photos with ISO-like metadata timestamps- Neeraj: Fix iOS crash when playing Pixel Long Shot (.LS) videos- Neeraj: Fix Android video preview/export generation by restoring ffmpeg x264 support- Neeraj: Fix video edit delete navigationdiff --git a/mobile/apps/photos/test/utils/exif_util_test.dart b/mobile/apps/photos/test/utils/exif_util_test.dartnew file mode 100644index 0000000000..51ad038f76--- /dev/null+++ b/mobile/apps/photos/test/utils/exif_util_test.dart@@ -0,0 +1,172 @@+import "package:photos/utils/exif_util.dart";+import "package:test/test.dart";++void main() {+ group("getDateTimeInDeviceTimezone", () {+ test("parses standard EXIF date time", () {+ final parsed = getDateTimeInDeviceTimezone(+ "2025:01:30 08:59:50",+ null,+ );++ expect(parsed.dateTime, "2025-01-30T08:59:50.000");+ expect(parsed.offsetTime, isNull);+ expect(parsed.time!.year, 2025);+ expect(parsed.time!.month, 1);+ expect(parsed.time!.day, 30);+ expect(parsed.time!.hour, 8);+ expect(parsed.time!.minute, 59);+ expect(parsed.time!.second, 50);+ });++ test("parses standard EXIF date time with separate offset", () {+ final parsed = getDateTimeInDeviceTimezone(+ "2025:01:30 08:59:50",+ "+01:00",+ );++ expect(parsed.dateTime, "2025-01-30T08:59:50.000");+ expect(parsed.offsetTime, "+01:00");+ expect(parsed.time!.toUtc(), DateTime.utc(2025, 1, 30, 7, 59, 50));+ });++ test("parses ISO date time with numeric offset", () {+ final parsed = getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50+01:00",+ null,+ );++ expect(parsed.dateTime, "2025-01-30T08:59:50.000");+ expect(parsed.offsetTime, "+01:00");+ expect(parsed.time!.toUtc(), DateTime.utc(2025, 1, 30, 7, 59, 50));+ });++ test("parses ISO date time with half-hour numeric offset", () {+ final parsed = getDateTimeInDeviceTimezone(+ "2024-04-01T19:17:29+05:30",+ null,+ );++ expect(parsed.dateTime, "2024-04-01T19:17:29.000");+ expect(parsed.offsetTime, "+05:30");+ expect(parsed.time!.toUtc(), DateTime.utc(2024, 4, 1, 13, 47, 29));+ });++ test("parses ISO date time with separate numeric offset", () {+ final parsed = getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50",+ "+01:00",+ );++ expect(parsed.dateTime, "2025-01-30T08:59:50.000");+ expect(parsed.offsetTime, "+01:00");+ expect(parsed.time!.toUtc(), DateTime.utc(2025, 1, 30, 7, 59, 50));+ });++ test("parses ISO date time with Z offset", () {+ final parsed = getDateTimeInDeviceTimezone(+ "2026-04-20T00:00:00Z",+ null,+ );++ expect(parsed.dateTime, "2026-04-20T00:00:00.000");+ expect(parsed.offsetTime, "Z");+ expect(parsed.time!.toUtc(), DateTime.utc(2026, 4, 20));+ });++ test("parses ISO date time with space separator and no offset", () {+ final parsed = getDateTimeInDeviceTimezone(+ "2025-11-12 15:12:01",+ null,+ );++ expect(parsed.dateTime, "2025-11-12T15:12:01.000");+ expect(parsed.offsetTime, isNull);+ expect(parsed.time!.year, 2025);+ expect(parsed.time!.month, 11);+ expect(parsed.time!.day, 12);+ expect(parsed.time!.hour, 15);+ expect(parsed.time!.minute, 12);+ expect(parsed.time!.second, 1);+ expect(parsed.time!.isUtc, isFalse);+ });++ test("parses date time with colon-separated milliseconds", () {+ final parsed = getDateTimeInDeviceTimezone(+ "2019-11-28 14:38:40:794",+ null,+ );++ expect(parsed.dateTime, "2019-11-28T14:38:40.794");+ expect(parsed.offsetTime, isNull);+ expect(parsed.time!.year, 2019);+ expect(parsed.time!.month, 11);+ expect(parsed.time!.day, 28);+ expect(parsed.time!.hour, 14);+ expect(parsed.time!.minute, 38);+ expect(parsed.time!.second, 40);+ expect(parsed.time!.millisecond, 794);+ });++ test("does not guess timezone abbreviations", () {+ expect(+ () => getDateTimeInDeviceTimezone(+ "2024-09-07T16:29:28CDT",+ null,+ ),+ throwsFormatException,+ );+ });++ test("rejects trailing data in standard EXIF date time", () {+ expect(+ () => getDateTimeInDeviceTimezone(+ "2024:09:07 16:29:28CDT",+ null,+ ),+ throwsFormatException,+ );+ expect(+ () => getDateTimeInDeviceTimezone(+ "2024:09:07 16:29:28+05:30",+ null,+ ),+ throwsFormatException,+ );+ });++ test("rejects invalid ISO date time components", () {+ expect(+ () => getDateTimeInDeviceTimezone(+ "2025-02-30T08:00:00Z",+ null,+ ),+ throwsFormatException,+ );+ expect(+ () => getDateTimeInDeviceTimezone(+ "2025-01-30T24:00:00+01:00",+ null,+ ),+ throwsFormatException,+ );+ expect(+ () => getDateTimeInDeviceTimezone(+ "2025-01-30T08:00:00+99:99",+ null,+ ),+ throwsFormatException,+ );+ });++ test("rejects invalid separate offset", () {+ expect(+ () => getDateTimeInDeviceTimezone(+ "2025-01-30T08:59:50",+ "CDT",+ ),+ throwsFormatException,+ );+ });+ });+}