Files
downloads-all-bot/bot/cleanup.py

54 lines
1.6 KiB
Python

# cleanup.py
import os
import time
def get_size_in_mb(path: str) -> float:
total_size = 0
for dirpath, _, filenames in os.walk(path):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if os.path.exists(filepath):
total_size += os.path.getsize(filepath)
return total_size / (1024 ** 2)
def clear_old_files(directory: str, max_age_seconds: int = 3600):
now = time.time()
for root, _, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
try:
if now - os.path.getmtime(file_path) > max_age_seconds:
os.remove(file_path)
except Exception as e:
pass
def ensure_cache_size(limit_mb: float, cleanup_directory: str):
while get_size_in_mb(cleanup_directory) > limit_mb:
oldest_mtime = float('inf')
oldest_file = None
for root, _, files in os.walk(cleanup_directory):
for file in files:
file_path = os.path.join(root, file)
try:
mtime = os.path.getmtime(file_path)
if mtime < oldest_mtime:
oldest_mtime = mtime
oldest_file = file_path
except Exception:
continue
if oldest_file:
try:
os.remove(oldest_file)
except Exception:
break
else:
break
def cleanup_tmp(path: str, max_age: int = 3600):
clear_old_files(path, max_age)