2024-02-07 23:28:54 +01:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
import subprocess
|
|
|
|
import logging
|
|
|
|
import logging.handlers
|
|
|
|
|
|
|
|
|
2024-03-24 17:52:14 +01:00
|
|
|
def notify(message: str, channel: str, markdown: bool = False) -> None:
|
2024-03-15 04:40:58 +01:00
|
|
|
print(f"{channel} -> {message}")
|
|
|
|
|
|
|
|
chan_list = ["dev", "apps", "doc"]
|
|
|
|
|
2024-03-15 04:55:06 +01:00
|
|
|
if not any(channel in x for x in chan_list):
|
|
|
|
logging.error(
|
2024-03-15 04:40:58 +01:00
|
|
|
f"Provided chan '{channel}' is not part of the available options ('dev', 'apps', 'doc')."
|
|
|
|
)
|
|
|
|
|
|
|
|
for char in ["'", "`", "!", ";", "$"]:
|
|
|
|
message = message.replace(char, "")
|
|
|
|
|
2024-03-24 17:52:14 +01:00
|
|
|
command = [
|
|
|
|
"/var/www/webhooks/matrix-commander",
|
|
|
|
"--message",
|
|
|
|
message,
|
|
|
|
"--credentials",
|
|
|
|
"/var/www/webhooks/credentials.json",
|
|
|
|
"--store",
|
|
|
|
"/var/www/webhooks/store",
|
|
|
|
"--room",
|
|
|
|
f"yunohost-{channel}",
|
|
|
|
]
|
|
|
|
if markdown:
|
|
|
|
command.append("--markdown")
|
|
|
|
|
2024-03-15 04:40:58 +01:00
|
|
|
try:
|
2024-03-24 17:52:14 +01:00
|
|
|
subprocess.call(command, stdout=subprocess.DEVNULL)
|
2024-04-02 12:36:24 +02:00
|
|
|
except FileNotFoundError:
|
2024-04-02 17:45:34 +02:00
|
|
|
logging.warning(
|
|
|
|
"The logging sender tool /var/www/webhooks/matrix-commander does not exist."
|
|
|
|
)
|
2024-03-15 04:40:58 +01:00
|
|
|
except subprocess.CalledProcessError as e:
|
|
|
|
logging.warning(
|
|
|
|
f"""Could not send a notification on {channel}.
|
|
|
|
Message: {message}
|
|
|
|
Error: {e}"""
|
|
|
|
)
|
2024-02-24 18:41:11 +01:00
|
|
|
|
|
|
|
|
2024-02-08 22:18:59 +01:00
|
|
|
class LogSenderHandler(logging.Handler):
|
2024-03-24 17:18:42 +01:00
|
|
|
def __init__(self) -> None:
|
2024-02-07 23:28:54 +01:00
|
|
|
logging.Handler.__init__(self)
|
|
|
|
self.is_logging = False
|
|
|
|
|
2024-03-24 17:18:42 +01:00
|
|
|
def emit(self, record: logging.LogRecord) -> None:
|
2024-04-29 21:22:59 +02:00
|
|
|
msg = f"[Apps tools error] {record.message}"
|
2024-03-15 04:40:58 +01:00
|
|
|
notify(msg, "dev")
|
2024-02-07 23:28:54 +01:00
|
|
|
|
|
|
|
@classmethod
|
2024-03-24 17:18:42 +01:00
|
|
|
def add(cls, level: int = logging.ERROR) -> None:
|
2024-02-07 23:28:54 +01:00
|
|
|
if not logging.getLogger().handlers:
|
|
|
|
logging.basicConfig()
|
|
|
|
|
|
|
|
# create handler
|
|
|
|
handler = cls()
|
|
|
|
handler.setLevel(level)
|
|
|
|
# add the handler
|
|
|
|
logging.getLogger().handlers.append(handler)
|
|
|
|
|
|
|
|
|
2024-03-24 17:18:42 +01:00
|
|
|
def enable() -> None:
|
2024-02-08 22:18:59 +01:00
|
|
|
"""Enables the LogSenderHandler"""
|
|
|
|
LogSenderHandler.add(logging.ERROR)
|