2021-01-15 21:29:23 +01:00
|
|
|
from typing import List
|
|
|
|
import os
|
|
|
|
import requests
|
|
|
|
|
|
|
|
|
2021-01-15 21:08:56 +01:00
|
|
|
class Notifier:
|
2021-01-15 21:29:23 +01:00
|
|
|
# (positive, negative)
|
|
|
|
_EVENTS = {
|
|
|
|
"backup": (
|
|
|
|
"Backup for {name} succeeded.",
|
|
|
|
"Backup for {name} failed.",
|
|
|
|
),
|
|
|
|
"restore": (
|
|
|
|
"{name} successfully restored.",
|
|
|
|
"Couldn't restore {name}.",
|
|
|
|
),
|
|
|
|
}
|
|
|
|
|
2021-01-15 21:08:56 +01:00
|
|
|
# Placeholder
|
2021-01-15 21:29:23 +01:00
|
|
|
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)
|