feat: breakout formatters into their own plugin-like module to ease additonal formatters

This commit is contained in:
Alex Kelly 2021-11-03 17:02:22 -04:00
parent d82a0ba9bd
commit 0d92c378c4
6 changed files with 13 additions and 19 deletions

1
.gitignore vendored
View file

@ -3,3 +3,4 @@
.mypy_cache
coverage.xml
htmlcov
**__pycache__

View file

@ -1,8 +1,4 @@
import plugins
@plugins.register
def github(data, headers):
def formatter(data, headers):
"""Pretty-print a github notification."""
# TODO: Write nice useful formatters. This is only an example.
if headers["X-GitHub-Event"] == "push":

View file

@ -1,8 +1,4 @@
import plugins
@plugins.register
def grafana(data, headers):
def formatter(data, headers):
"""Pretty-print a grafana notification."""
text = ""
if "title" in data:

View file

@ -1,8 +1,7 @@
import plugins
from datetime import datetime
@plugin.register
def pingdom(data, headers):
def formatter(data, headers):
"""Pretty-print a pingdom notification."""
#JSON data formatting was obtained from https://www.pingdom.com/resources/webhooks/
check_id = data["check_id"]

View file

@ -4,11 +4,11 @@ import json
import logging
from http import HTTPStatus
from hmac import HMAC
import plugins
import importlib
from markdown import markdown
from . import conf, formatters, utils
from . import conf, utils
LOGGER = logging.getLogger("matrix_webhook.handler")
@ -19,7 +19,6 @@ async def matrix_webhook(request):
This one handles a POST, checks its content, and forwards it to the matrix room.
"""
formatters = plugins.names_factory(__package__)
LOGGER.debug(f"Handling {request=}")
data_b = await request.read()
@ -38,9 +37,12 @@ async def matrix_webhook(request):
if "formatter" in request.rel_url.query:
try:
data = getattr(formatters, request.rel_url.query["formatter"])(
data, request.headers
)
# data = getattr(formatters, request.rel_url.query["formatter"])(
# data, request.headers
# )
format = request.rel_url.query["formatter"]
plugin = importlib.import_module(f"matrix_webhook.formatters.{format}", "formatter")
data = plugin.formatter(data, request.headers)
except AttributeError:
return utils.create_json_response(
HTTPStatus.BAD_REQUEST, "Unknown formatter"