From 4018dca184742a28c5879bc7336a584f5f32e7f0 Mon Sep 17 00:00:00 2001 From: Houkime <> Date: Mon, 10 Apr 2023 16:35:35 +0000 Subject: [PATCH] feature(backups): automatic backup --- selfprivacy_api/backup/__init__.py | 22 +++++++++++++++++----- selfprivacy_api/backup/tasks.py | 22 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/selfprivacy_api/backup/__init__.py b/selfprivacy_api/backup/__init__.py index 1676ca5..d9b811c 100644 --- a/selfprivacy_api/backup/__init__.py +++ b/selfprivacy_api/backup/__init__.py @@ -52,17 +52,29 @@ class Backups: def enable_autobackup(service: Service): Storage.set_autobackup(service) + @staticmethod + def _service_ids_to_back_up(time: datetime) -> List[str]: + services = Storage.services_with_autobackup() + return [id for id in services if Backups.is_time_to_backup_service(id, time)] + + # untestable until the dummy service is registered + @staticmethod + def services_to_back_up(time: datetime) -> List[Service]: + result = [] + for id in Backups._service_ids_to_back_up(time): + service = get_service_by_id(id) + if service is None: + raise ValueError("Cannot look up a service scheduled for backup!") + result.append(service) + return result + @staticmethod def is_time_to_backup(time: datetime) -> bool: """ Intended as a time validator for huey cron scheduler of automatic backups """ - enabled_services = Storage.services_with_autobackup() - for service_id in enabled_services: - if Backups.is_time_to_backup_service(service_id, time): - return True - return False + return Backups._service_ids_to_back_up(time) != [] @staticmethod def is_time_to_backup_service(service_id: str, time: datetime): diff --git a/selfprivacy_api/backup/tasks.py b/selfprivacy_api/backup/tasks.py index f1715cc..4f6ab16 100644 --- a/selfprivacy_api/backup/tasks.py +++ b/selfprivacy_api/backup/tasks.py @@ -1,9 +1,31 @@ +from datetime import datetime + from selfprivacy_api.utils.huey import huey from selfprivacy_api.services.service import Service from selfprivacy_api.backup import Backups + +def validate_datetime(dt: datetime): + # dt = datetime.now(timezone.utc) + if dt.timetz is None: + raise ValueError( + """ + huey passed in the timezone-unaware time! + Post it in support chat or maybe try uncommenting a line above + """ + ) + return Backups.is_time_to_backup(dt) + + # huey tasks need to return something @huey.task() def start_backup(service: Service) -> bool: Backups.back_up(service) return True + + +@huey.periodic_task(validate_datetime=validate_datetime) +def automatic_backup(): + time = datetime.now() + for service in Backups.services_to_back_up(time): + start_backup(service)