From 419fef8ddca6174786e8d5efa8af4d3ebefb4525 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Fri, 15 Jan 2021 21:29:23 +0100 Subject: [PATCH] First working notify version --- app/notifier.py | 59 ++++++++++++++++++++++++++++++++++++++++-- app/specs/directory.py | 2 +- app/specs/spec.py | 5 ++-- 3 files changed, 61 insertions(+), 5 deletions(-) diff --git a/app/notifier.py b/app/notifier.py index 0fb808b..1848775 100644 --- a/app/notifier.py +++ b/app/notifier.py @@ -1,4 +1,59 @@ +from typing import List +import os +import requests + + class Notifier: + # (positive, negative) + _EVENTS = { + "backup": ( + "Backup for {name} succeeded.", + "Backup for {name} failed.", + ), + "restore": ( + "{name} successfully restored.", + "Couldn't restore {name}.", + ), + } + # Placeholder - def __init__(*args, **kwargs): - pass + def __init__( + self, title: str, events: List[str], endpoint: str, api_key: str = None + ): + self.title = title + self.events = events + self.endpoint = endpoint + self.api_key = api_key + + def notify(self, category: str, name: str, status_code: int): + """ + Args: + category: type of notify (e.g. backup or restore) + name: name of the spec + status_code: exit code of the command + """ + + event = "{}_{}".format( + category, "success" if status_code == 0 else "failure" + ) + + # stop if it's not a valid event + if event not in self._EVENTS: + return + + api_key = self.api_key or os.environ["IFTTT_API_KEY"] + + # Can't do anything without a key + if not api_key: + return + + url = " https://maker.ifttt.com/trigger/{}/with/key/{}".format( + self.endpoint, api_key + ) + + data = { + "value1": self.title, + "value2": self._EVENTS[event][int(status_code != 0)], + } + + requests.post(url, data=data) diff --git a/app/specs/directory.py b/app/specs/directory.py index 43aa22c..9747b5b 100644 --- a/app/specs/directory.py +++ b/app/specs/directory.py @@ -57,4 +57,4 @@ class DirectorySpec(Spec): ) if self.notifier: - self.notifier.notify(process.returncode) + self.notifier.notify("backup", self.name, process.returncode) diff --git a/app/specs/spec.py b/app/specs/spec.py index b838aa6..35481ae 100644 --- a/app/specs/spec.py +++ b/app/specs/spec.py @@ -18,6 +18,8 @@ class Spec: "notify": { "title": "Backup Notification", "events": ["backup_sucess"], + "endpoint": None, + "api_key": "", }, "extension": "tar.gz", } @@ -67,7 +69,7 @@ class Spec: """ files = sorted( - self.destination.glob(self.extension), + self.destination.glob("*." + self.extension), key=os.path.getmtime, reverse=True, ) @@ -86,7 +88,6 @@ class Spec: def from_dict(cls, name, obj: Dict, defaults: Dict) -> Spec: # Combine defaults with skeleton, creating new skeleton skel = skeleton.merge(cls.skeleton(), defaults) - print(skel) # Then, combine actual values with new skeleton obj = skeleton.merge_with_skeleton(obj, skel)