Skip to content

Commit

Permalink
fix: fix channels and add more logging
Browse files Browse the repository at this point in the history
  • Loading branch information
LeslieLeung committed Jan 15, 2024
1 parent de3ef5a commit fd04593
Show file tree
Hide file tree
Showing 11 changed files with 87 additions and 71 deletions.
6 changes: 6 additions & 0 deletions heimdallr/api/base.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import logging

from heimdallr.channel.factory import build_message
from heimdallr.response import Response, success
from heimdallr.shared.config import Config

logger = logging.getLogger(__name__)


def serve(key: str, title: str = "", body: str = "", **kwargs):
config = Config()
group = config.get_group(key)
if group is None:
return Response(code=-1, message="key not authorized").render()
logger.info(f"Group: {group.name}, token: {group.token}")
errors = {}
for chan in group.channels:
logger.info(f"Channel: {chan.get_name()}")
message = build_message(chan.get_name(), title, body, **kwargs)
rs, msg = chan.send(message)
if not rs:
Expand Down
15 changes: 6 additions & 9 deletions heimdallr/channel/bark.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@
from heimdallr.config.definition import SUFFIX_BARK_KEY, SUFFIX_BARK_URL
from heimdallr.exception import ParamException

logger = logging.getLogger(__name__)

class BarkMessage(Message):
category: str
param: str
jump_url: str

class BarkMessage(Message):
def __init__(
self,
title: str,
Expand Down Expand Up @@ -42,11 +40,10 @@ def render_message(self) -> str:


class Bark(Channel):
base_url: str = "https://api.day.app"
key: str = ""

def __init__(self, name: str) -> None:
super().__init__(name)
self.base_url: str = "https://api.day.app"
self.key: str
self._build_channel()

def _build_channel(self) -> None:
Expand All @@ -62,9 +59,9 @@ def send(self, message: Message) -> Tuple[bool, str]:
Send a message to bark server.
"""
url = f"{self.base_url}/{self.key}{message.render_message()}"
logging.info(f"Bark requested: {url}")
logger.info(f"Bark requested: {url}")
rs = requests.get(url)
logging.info(f"Bark response: {rs.text}")
logger.info(f"Bark response: {rs.text}")
rs_json = rs.json()
if rs_json["code"] == 200:
return True, rs_json["message"]
Expand Down
5 changes: 0 additions & 5 deletions heimdallr/channel/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@


class Message:
title: str
body: str

def __init__(self, title: str, body: str) -> None:
self.title = title
self.body = body
Expand All @@ -20,8 +17,6 @@ class Channel:
Base class for all channels.
"""

name: str

def __init__(self, name: str) -> None:
self.name = name

Expand Down
9 changes: 5 additions & 4 deletions heimdallr/channel/chanify.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
from heimdallr.config.definition import SUFFIX_CHANIFY_ENDPOINT, SUFFIX_CHANIFY_TOKEN
from heimdallr.exception import ParamException

logger = logging.getLogger(__name__)


class ChanifyMessage(Message):
def __init__(self, title: str, body: str):
Expand All @@ -19,11 +21,10 @@ def render_message(self) -> Any:


class Chanify(Channel):
base_url: str = "https://api.chanify.net/v1/sender"
token: str

def __init__(self, name: str):
super().__init__(name)
self.base_url: str = "https://api.chanify.net/v1/sender"
self.token: str
self._build_channel()

def _build_channel(self) -> None:
Expand All @@ -36,7 +37,7 @@ def _build_channel(self) -> None:

def send(self, message: Message):
url = f"{self.base_url}/{self.token}/{message.render_message()}"
logging.info(f"Chanify requested: {url}")
logger.info(f"Chanify requested: {url}")
rs = requests.get(url).json()
if "request-uid" in rs:
return True, "success"
Expand Down
28 changes: 11 additions & 17 deletions heimdallr/channel/email.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Expand All @@ -18,35 +17,32 @@


class EmailMessage(Message):
sender: str
user: str
to: str

def __init__(self, title: str, body: str):
super().__init__(title, body)
self.sender: str
self.user: str
self.to: str

def render_message(self) -> Any:
message = MIMEMultipart()
message["From"] = f"{self.sender} <{self.user}>"
message["To"] = self.to
message["Subject"] = self.title
message.attach(MIMEText(self.body, "plain", "utf-8"))
logging.info(f"Email message body: {message.as_string()}")
return message.as_string()


class Email(Channel):
host: str = ""
port: int = 25
user: str = ""
password: str = ""
sender: str = "Heimdallr"
to: str = ""
starttls: bool = False
smtp_object: smtplib.SMTP

def __init__(self, name: str):
super().__init__(name)
self.host: str = ""
self.port: int = 25
self.user: str = ""
self.password: str = ""
self.sender: str = "Heimdallr"
self.to: str = ""
self.starttls: bool = False
self.smtp_object: smtplib.SMTP
self._build_channel()

def _build_channel(self):
Expand Down Expand Up @@ -83,6 +79,4 @@ def send(self, message: Message):
self.smtp_object.sendmail(self.user, self.to, message.render_message())
except smtplib.SMTPException as e:
return False, f"SMTPException: {e}"
finally:
self.smtp_object.quit()
return True, "success"
9 changes: 5 additions & 4 deletions heimdallr/channel/pushdeer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from heimdallr.config.definition import SUFFIX_PUSHDEER_TOKEN
from heimdallr.exception.param_exception import ParamException

logger = logging.getLogger(__name__)


class PushDeerMessage(Message):
def __init__(self, title: str, body: str):
Expand All @@ -18,11 +20,10 @@ def render_message(self) -> str:


class PushDeer(Channel):
base_url = "https://api2.pushdeer.com/message/push?"
push_key = ""

def __init__(self, name: str):
super().__init__(name)
self.base_url = "https://api2.pushdeer.com/message/push?"
self.push_key: str
self._build_channel()

def _build_channel(self):
Expand All @@ -34,7 +35,7 @@ def _build_channel(self):

def send(self, message: Message):
url = f"{self.base_url}pushkey={self.push_key}&text={message.render_message()}"
logging.info(f"PushDeer requested: {url}")
logger.info(f"PushDeer requested: {url}")
rs = requests.post(url).json()
if rs["code"] == 0:
return True, rs["content"]
Expand Down
7 changes: 3 additions & 4 deletions heimdallr/channel/pushover.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@ def render_message(self) -> Any:


class Pushover(Channel):
base_url: str = "https://api.pushover.net/1/messages.json"
token: str
user: str

def __init__(self, name: str) -> None:
super().__init__(name)
self.base_url = "https://api.pushover.net/1/messages.json"
self.token: str
self.user: str
self._build_channel()

def _build_channel(self) -> None:
Expand Down
34 changes: 16 additions & 18 deletions heimdallr/channel/wecom.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@
)
from heimdallr.exception import WecomException

logger = logging.getLogger(__name__)

class WecomWebhookMessage(Message):
msg_type: str

class WecomWebhookMessage(Message):
def __init__(self, title: str, body: str, msg_type: str = "text"):
super().__init__(title, body)
self.msg_type = msg_type
self.msg_type: str = msg_type

def render_message(self) -> Any:
match self.msg_type:
Expand All @@ -40,12 +40,10 @@ def render_message(self) -> Any:


class WecomAppMessage(Message):
msg_type: str
agent_id: int

def __init__(self, title: str, body: str, msg_type: str = "text"):
super().__init__(title, body)
self.msg_type = msg_type
self.agent_id: int

def render_message(self) -> Any:
match self.msg_type:
Expand All @@ -71,11 +69,10 @@ def render_message(self) -> Any:


class WecomWebhook(Channel):
base_url: str = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="
key: str = ""

def __init__(self, name: str):
super().__init__(name)
self.base_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="
self.key: str = ""
self._build_channel()

def _build_channel(self) -> None:
Expand All @@ -92,21 +89,22 @@ def send(self, message: Message):
data=message.render_message(),
headers={"Content-Type": "application/json"},
).json()
logging.info(f"WecomWebhook response: {rs}")
logger.info(f"WecomWebhook response: {rs}")
if rs["errcode"] == 0:
return True, rs["errmsg"]
return False, rs["errmsg"]


class WecomApp(Channel):
base_url: str = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
corp_id: str
secret: str
access_token: str
agent_id: int

def __init__(self, name: str):
super().__init__(name)
self.base_url: str = (
"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
)
self.corp_id: str
self.secret: str
self.access_token: str
self.agent_id: int
self._build_channel()

def _build_channel(self) -> None:
Expand All @@ -130,13 +128,13 @@ def send(self, message: Message):
message.agent_id = self.agent_id
msg = message.render_message()
url = f"{self.base_url}{self.access_token}"
logging.info(f"WecomApp requested: {url}, with message: {msg}")
logger.info(f"WecomApp requested: {url}, with message: {msg}")
rs = requests.post(
url,
data=msg,
headers={"Content-Type": "application/json"},
).json()
logging.info(f"WecomApp response: {rs}")
logger.info(f"WecomApp response: {rs}")
if rs["errcode"] == 0:
return True, rs["errmsg"]
return False, rs["errmsg"]
13 changes: 13 additions & 0 deletions heimdallr/config/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import logging
import os
from typing import List

from environs import Env

logger = logging.getLogger(__name__)

env = Env()
env.read_env(recurse=False)

Expand All @@ -16,3 +20,12 @@ def get_config_list(name: str, suffix: str, default: List[str] = []) -> List[str
if suffix == "":
return env.list(name, default)
return env.list(name + "_" + suffix, default)


def log_env_vars():
for key, value in os.environ.items():
logger.debug(f"{key}: {value}")


def is_debug():
return env.bool("DEBUG", False)
14 changes: 8 additions & 6 deletions heimdallr/group/group.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from typing import List

from heimdallr.channel.base import Channel
Expand All @@ -7,16 +8,17 @@


class Group:
token: str
channels: List[Channel] = []

def __init__(self, name: str) -> None:
self._build_group(name)
self.name = name
self.token: str
self.channels: List[Channel] = []
self._build_group()

def _build_group(self, name: str) -> None:
def _build_group(self) -> None:
# get enabled channels
group_name = str.upper(name)
group_name = str.upper(self.name)
enabled_channels = get_config_list(group_name, SUFFIX_ENABLED_CHANNELS, [])
logging.info(f"Group: {group_name}, enabled channels: {enabled_channels}")
self.token = get_config_str(group_name, SUFFIX_TOKEN, "")

for channel_name in enabled_channels:
Expand Down
18 changes: 14 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@
from fastapi.responses import JSONResponse

from heimdallr.api.api import router
from heimdallr.config.config import get_config_str
from heimdallr.config.config import get_config_str, is_debug, log_env_vars
from heimdallr.exception import ParamException, WecomException

app = FastAPI()
if is_debug():
logging.basicConfig(level=logging.DEBUG)
log_env_vars()
else:
logging.basicConfig(level=logging.INFO)

logging.basicConfig(level=logging.INFO)
app = FastAPI()

app.include_router(router)

Expand All @@ -22,4 +26,10 @@ async def exception_handler(request, exc):


if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=int(get_config_str("PORT", "", "9000")))
uvicorn.run(
"main:app",
host="0.0.0.0",
port=int(get_config_str("PORT", "", "9000")),
log_level="info",
access_log=True,
)

0 comments on commit fd04593

Please sign in to comment.