do not grow too large

This commit is contained in:
lelo 2025-04-01 21:29:20 +00:00
parent fc4a72288c
commit 7c19735e24

View File

@ -57,11 +57,9 @@ def get_device_type(user_agent):
return 'Other' return 'Other'
def log_file_access(rel_path, filesize, mime, ip_address, user_agent, device_id, cached): 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 global file_access_temp
timestamp = datetime.now() # a datetime object timestamp = datetime.now()
# Store the ISO timestamp in the database for easy lexical comparison
iso_ts = timestamp.isoformat() iso_ts = timestamp.isoformat()
with log_db: 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) (timestamp, rel_path, filesize, mime, ip_address, user_agent, device_id, cached)
VALUES (?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (iso_ts, rel_path, filesize, mime, ip_address, user_agent, device_id, cached)) ''', (iso_ts, rel_path, filesize, mime, ip_address, user_agent, device_id, cached))
file_access_temp.insert(0, [iso_ts, rel_path, filesize, mime, ip_address, user_agent, device_id, cached])
return iso_ts # 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 True
def return_file_access(): 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 global file_access_temp
if file_access_temp: return 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 []
@require_secret @require_secret
def connections(): def connections():