Procházet zdrojové kódy

DateTimeParseing: Avoid potential incorrect parsing results

Neeraj Gupta před 2 roky
rodič
revize
39ade36e6b

+ 15 - 3
lib/utils/date_time_util.dart

@@ -45,7 +45,7 @@ Map<int, String> _days = {
   7: "Sun",
 };
 
-final currentYear = int.parse(DateTime.now().year.toString());
+final currentYear = DateTime.now().year;
 const searchStartYear = 1970;
 
 //Jun 2022
@@ -269,7 +269,16 @@ bool isValidDate({
 
 final RegExp exp = RegExp('[\\.A-Za-z]*');
 
-DateTime? parseDateTimeFromFileNameV2(String fileName) {
+DateTime? parseDateTimeFromFileNameV2(
+  String fileName, {
+  /* to avoid parsing incorrect date time from the filename, the max and min
+    year limits the chances of parsing incorrect date times
+    */
+  int minYear = 1990,
+  int? maxYear,
+}) {
+  // add next year to avoid corner cases for 31st Dec
+  maxYear ??= currentYear + 1;
   String val = fileName.replaceAll(exp, '');
   if (val.isNotEmpty && !isNumeric(val[0])) {
     val = val.substring(1, val.length);
@@ -298,7 +307,10 @@ DateTime? parseDateTimeFromFileNameV2(String fileName) {
   if (kDebugMode && result == null) {
     debugPrint("Failed to parse $fileName dateTime from $valForParser");
   }
-  return result;
+  if (result != null && result.year >= minYear && result.year <= maxYear) {
+    return result;
+  }
+  return null;
 }
 
 bool isNumeric(String? s) {

+ 17 - 2
test/utils/date_time_util_test.dart

@@ -9,14 +9,14 @@ void main() {
       "IMG-20221109-WA0000",
       '''Screenshot_20220807-195908_Firefox''',
       '''Screenshot_20220507-195908''',
-      "2019-02-18 16.00.12-DCMX.png",
+      "2022-02-18 16.00.12-DCMX.png",
       "20221107_231730",
       "2020-11-01 02.31.02",
       "IMG_20210921_144423",
       "2019-10-31 155703",
       "IMG_20210921_144423_783",
       "Screenshot_2022-06-21-16-51-29-164_newFormat.heic",
-      "Screenshot 20221106 211633.com.google.android.apps.nbu.paisa.user.jpg"
+      "Screenshot 20221106 211633.com.google.android.apps.nbu.paisa.user.jpg",
     ];
     for (String val in validParsing) {
       final parsedValue = parseDateTimeFromFileNameV2(val);
@@ -31,6 +31,21 @@ void main() {
     }
   });
 
+  test("test invalid datetime parsing", () {
+    final List<String> badParsing = ["Snapchat-431959199.mp4."];
+    for (String val in badParsing) {
+      final parsedValue = parseDateTimeFromFileNameV2(val);
+      expect(
+        parsedValue == null,
+        true,
+        reason: "parsing should have failed $val",
+      );
+      if (kDebugMode) {
+        debugPrint("Parsed $val as ${parsedValue?.toIso8601String()}");
+      }
+    }
+  });
+
   test("verify constants", () {
     final date = DateTime.fromMicrosecondsSinceEpoch(jan011981Time).toUtc();
     expect(