2022-07-04 01:03:24 +02:00
|
|
|
import logging
|
|
|
|
|
|
|
|
from aiohttp import web, web_request
|
2022-07-06 00:54:13 +02:00
|
|
|
from diskcache import Cache
|
2022-07-04 01:03:24 +02:00
|
|
|
from nio import AsyncClient, SendRetryError
|
|
|
|
|
|
|
|
from matrix_alertbot.chat_functions import send_text_to_room
|
|
|
|
from matrix_alertbot.config import Config
|
|
|
|
from matrix_alertbot.storage import Alert
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
routes = web.RouteTableDef()
|
|
|
|
|
|
|
|
|
|
|
|
@routes.post("/alert")
|
|
|
|
async def create_alert(request: web_request.Request) -> web.Response:
|
|
|
|
data = await request.json()
|
|
|
|
logger.info(f"Received alert: {data}")
|
2022-07-06 00:54:13 +02:00
|
|
|
client: AsyncClient = request.app["client"]
|
|
|
|
config: Config = request.app["config"]
|
|
|
|
cache: Cache = request.app["cache"]
|
2022-07-04 01:03:24 +02:00
|
|
|
|
|
|
|
plaintext = ""
|
|
|
|
html = ""
|
|
|
|
for i, alert in enumerate(data["alerts"]):
|
|
|
|
alert = Alert.from_dict(alert)
|
|
|
|
|
|
|
|
if i != 0:
|
|
|
|
plaintext += "\n"
|
|
|
|
html += "<br/>\n"
|
|
|
|
plaintext += alert.plaintext()
|
|
|
|
html += alert.html()
|
|
|
|
|
|
|
|
try:
|
2022-07-05 23:35:19 +02:00
|
|
|
event = await send_text_to_room(
|
2022-07-06 00:54:13 +02:00
|
|
|
client, config.room, plaintext, html, notice=False
|
2022-07-05 23:35:19 +02:00
|
|
|
)
|
2022-07-04 01:03:24 +02:00
|
|
|
except SendRetryError as e:
|
|
|
|
logger.error(e)
|
|
|
|
return web.Response(status=500)
|
|
|
|
|
2022-07-06 00:54:13 +02:00
|
|
|
fingerprints = tuple(alert["fingerprint"] for alert in data["alerts"])
|
|
|
|
cache.set(
|
|
|
|
event.event_id, fingerprints, expire=config.cache_expire_time, tag="event"
|
|
|
|
)
|
2022-07-04 01:03:24 +02:00
|
|
|
return web.Response(status=200)
|
|
|
|
|
|
|
|
|
|
|
|
class Webhook:
|
2022-07-06 01:04:06 +02:00
|
|
|
def __init__(self, client: AsyncClient, cache: Cache, config: Config) -> None:
|
2022-07-04 01:03:24 +02:00
|
|
|
self.app = web.Application(logger=logger)
|
|
|
|
self.app["client"] = client
|
2022-07-06 00:54:13 +02:00
|
|
|
self.app["config"] = config
|
2022-07-04 01:03:24 +02:00
|
|
|
self.app["cache"] = cache
|
|
|
|
self.app.add_routes(routes)
|
|
|
|
self.runner = web.AppRunner(self.app)
|
|
|
|
|
|
|
|
self.config = config
|
|
|
|
self.address = config.address
|
|
|
|
self.port = config.port
|
|
|
|
self.socket = config.socket
|
|
|
|
|
|
|
|
async def start(self) -> None:
|
|
|
|
await self.runner.setup()
|
|
|
|
|
|
|
|
site: web.BaseSite
|
|
|
|
if self.address and self.port:
|
|
|
|
site = web.TCPSite(self.runner, self.address, self.port)
|
|
|
|
logger.info(f"Listenning on {self.address}:{self.port}")
|
|
|
|
elif self.socket:
|
|
|
|
site = web.UnixSite(self.runner, self.socket)
|
|
|
|
logger.info(f"Listenning on unix://{self.socket}")
|
|
|
|
|
|
|
|
await site.start()
|
|
|
|
|
|
|
|
async def close(self) -> None:
|
|
|
|
await self.runner.cleanup()
|