From 7c19735e2438b250031d0802997cd9f660b19b75 Mon Sep 17 00:00:00 2001 From: lelo Date: Tue, 1 Apr 2025 21:29:20 +0000 Subject: [PATCH] do not grow too large --- analytics.py | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/analytics.py b/analytics.py index 152d066..cf3ac60 100644 --- a/analytics.py +++ b/analytics.py @@ -57,11 +57,9 @@ def get_device_type(user_agent): return 'Other' def log_file_access(rel_path, filesize, mime, ip_address, user_agent, device_id, cached): - """Insert a file access record into the database.""" + """Insert a file access record into the database and prune entries older than 10 minutes.""" global file_access_temp - timestamp = datetime.now() # a datetime object - - # Store the ISO timestamp in the database for easy lexical comparison + timestamp = datetime.now() iso_ts = timestamp.isoformat() with log_db: @@ -70,23 +68,22 @@ def log_file_access(rel_path, filesize, mime, ip_address, user_agent, device_id, (timestamp, rel_path, filesize, mime, ip_address, user_agent, device_id, cached) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ''', (iso_ts, rel_path, filesize, mime, ip_address, user_agent, device_id, cached)) + + # Remove entries older than 10 minutes + cutoff_time = datetime.now() - timedelta(minutes=10) + file_access_temp[:] = [ + entry for entry in file_access_temp + if datetime.fromisoformat(entry[0]) >= cutoff_time + ] + + # Add the new entry at the beginning of the list file_access_temp.insert(0, [iso_ts, rel_path, filesize, mime, ip_address, user_agent, device_id, cached]) - - return iso_ts + return True def return_file_access(): - """Return recent file access logs from memory (the last 10 minutes).""" + """Return recent file access logs from memory.""" global file_access_temp - if file_access_temp: - cutoff_time = datetime.now() - timedelta(minutes=10) - # Convert each stored timestamp (ISO string) back to datetime - file_access_temp[:] = [ - entry for entry in file_access_temp - if datetime.fromisoformat(entry[0]) >= cutoff_time - ] - return file_access_temp - else: - return [] + return file_access_temp @require_secret def connections():