From efd44da3abc856963d2cfe5cd081ba4ca6a2a81d Mon Sep 17 00:00:00 2001 From: Fred Boniface Date: Fri, 19 Apr 2024 20:38:11 +0100 Subject: [PATCH] Add check for downloading old data. Prevent operating on old download --- cif/metadata.go | 19 ++++++++++++++++--- cif/metadata_test.go | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/cif/metadata.go b/cif/metadata.go index 9198ead..e0c030f 100644 --- a/cif/metadata.go +++ b/cif/metadata.go @@ -17,11 +17,15 @@ func checkMetadata(oldMeta *dbAccess.CifMetadata, newMeta *upstreamApi.JsonTimet return "nil-pointer", false } - // Handle non-matching sequence numbers between full and daily download types - if isAfterYesterdayAt0600(oldMeta.LastUpdate) { - return "last-update-full", true + if !isTimestampWithinLastFiveDays(newMeta.Timestamp) { + return "downloaded-data-is-too-old", false } + // Handle non-matching sequence numbers between full and daily download types + // if isAfterYesterdayAt0600(oldMeta.LastUpdate) { + // return "last-update-full", true + // } + // Check that the new metadata sequence is as expected. if newMeta.Metadata.Sequence == oldMeta.LastSequence+1 { return "correct-sequence", true @@ -49,3 +53,12 @@ func generateMetadata(header *upstreamApi.JsonTimetableV1) *dbAccess.CifMetadata return &newMetadata } + +// Accepts a unix timestamp and returns true if the timestamp is within the last five days, else false +func isTimestampWithinLastFiveDays(ts int64) bool { + timestamp := time.Unix(ts, 0) + timeNow := time.Now() + fiveDaysAgo := timeNow.AddDate(0, 0, -5) + + return !timestamp.Before(fiveDaysAgo) +} diff --git a/cif/metadata_test.go b/cif/metadata_test.go index f934ebb..02d460d 100644 --- a/cif/metadata_test.go +++ b/cif/metadata_test.go @@ -80,3 +80,22 @@ func TestIsAfterYesterdayAt0600(t *testing.T) { } } } + +func TestIsTimestampWithinLastFiveDays(t *testing.T) { + testCases := []struct { + name string + ts int64 + expect bool + }{ + {"WithinLastFiveDays", time.Now().AddDate(0, 0, -3).Unix(), true}, + {"ExactlyFiveDaysAgo", time.Now().AddDate(0, 0, -5).Unix(), false}, //False due to elapsed time during test + {"MoreThanFiveDaysAgo", time.Now().AddDate(0, 0, -7).Unix(), false}, + } + + for _, tc := range testCases { + result := isTimestampWithinLastFiveDays(tc.ts) + if result != tc.expect { + t.Errorf("For %s (%d), expected %t, but got %t", tc.name, tc.ts, tc.expect, result) + } + } +}