Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
rvasilev committed Jan 2, 2021
1 parent 666e48e commit 5a3ba87
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 79 deletions.
18 changes: 18 additions & 0 deletions .SRCINFO
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pkgbase = m2a
pkgdesc = M2A Mail to Apprise Message Relay
pkgver = 0.0.1
pkgrel = 1
install = m2a.install
arch = any
license = custom
source = m2a.py
source = m2a.service
source = m2a.yaml.example
source = m2a.install
md5sums = 9a5629ee16bb9d74c112c50abb6adbb6
md5sums = 4db2e9c1988faed295fa247e591110fd
md5sums = 8499b4996f7f8db02603d59b259b2971
md5sums = 6ee502e286e2c91559e4a9d637a8d528

pkgname = m2a

4 changes: 2 additions & 2 deletions PKGBUILD
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ options=()
install=${pkgname}.install
changelog=
source=('m2a.py' 'm2a.service' 'm2a.yaml.example' 'm2a.install')
md5sums=('7208ba4c9d9788271c525ee66147214c'
'24f517e7dd31ff6bdb6845fb143a7850'
md5sums=('9a5629ee16bb9d74c112c50abb6adbb6'
'4db2e9c1988faed295fa247e591110fd'
'8499b4996f7f8db02603d59b259b2971'
'6ee502e286e2c91559e4a9d637a8d528')

Expand Down
133 changes: 58 additions & 75 deletions m2a.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,37 @@
#!/usr/bin/env python

from time import sleep
import signal
import asyncio
import logging

import email
from email.message import Message

from aiosmtpd.controller import Controller
from aiosmtpd.smtp import Envelope, Session, SMTP

from aiosmtpd.handlers import Sink

import email
from email.message import Message

import apprise

import logging
log = logging.getLogger("smtphandler")


class GracefulKiller:
"""
SystemD Friendly ShutDown
"""

kill_now = False

def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)

def exit_gracefully(self, signum, frame):
self.kill_now = True


class Notification:

def _default_configuration_file(self):
Expand Down Expand Up @@ -51,10 +68,10 @@ def __init__(self):
def info(self):
return self.config, self.config_file

async def send(self, title, body):
self.send_sync(title, body)
# async def send(self, title, body):
# self.send_sync(title, body)

def send_sync(self, title, body):
def send(self, title, body):
# Create an Apprise instance
tg_auth = f"tgram://{self.config['telegram']['bot_token']}/{self.config['telegram']['chat_ids'][0]}"

Expand All @@ -73,12 +90,12 @@ def send_sync(self, title, body):

def daemon_start(self):
if self.config['m2a']['notify']['on_start']:
self.send_sync(title='M2A Daemon Started',
body='All Systems Nominal')
self.send(title='M2A Daemon Started',
body='All Systems Nominal')

def daemon_stop(self):
if self.config['m2a']['notify']['on_stop']:
self.send_sync(title='M2A Daemon Stopped', body='')
self.send(title='M2A Daemon Stopped', body='')


def message_to_display(message: Message):
Expand All @@ -99,6 +116,16 @@ def __init__(self, notify: Notification):
self.notify = notify
# self.loop = loop

def message_to_display(self, message: Message):
result = ''
if message.is_multipart():
for sub_message in message.get_payload():
result += message_to_display(sub_message)
else:
result = f"Content-type: {message.get_content_type()}\n" \
f"{message.get_payload()}\n" + "*" * 76 + '\n'
return result

async def handle_DATA(self, server: SMTP, session: Session, envelope: Envelope):
message: Message = email.message_from_bytes(envelope.content)

Expand All @@ -113,87 +140,43 @@ async def handle_DATA(self, server: SMTP, session: Session, envelope: Envelope):
print(f"Message data:\n {message_to_display(message)}")

# await Notification().send(title=f"SUBJECT: {message['Subject']}", body=f"Message data:\n {message_to_display(message)}")
await self.notify.send(title=f"SUBJECT: {message['Subject']}", body=f"Message data:\n {message_to_display(message)}")
self.notify.send(
title=f"SUBJECT: {message['Subject']}", body=f"Message data:\n {message_to_display(message)}")

return '250 OK Message Accepted'


async def smtpd(notify):
import systemd.daemon
def main(notification):

HOSTNAME = ''
PORT = int(notify.config['m2a']['port'])

try:

cont = Controller(Handler(notify), hostname=HOSTNAME, port=PORT)
cont.start()
PORT = 12525

systemd.daemon.notify('READY=1')
controller = Controller(Handler(notification),
hostname=HOSTNAME, port=PORT)

notify.daemon_start()

# n = Notification()
# if n.config['m2a']['notify']['on_start']:
# await n.send(title='M2A Daemon Started', body='All systems nominal')

input(
f"Server started on HOSTNAME='{HOSTNAME}' PORT={PORT}. Press Return to quit.\n")
cont.stop()
except Exception as e:
print('Error starting daemon:', e, '\n')
if e.errno == 98:
print('Please try to bind config to other PORT.')
print(f'Config: {notify.config_file}')
print('Variable: "m2a.PORT"')
systemd.daemon.notify('READY=0')
cont.stop()
# finally:


class GracefulKiller:

kill_now = False

def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)

def exit_gracefully(self, signum, frame):
self.kill_now = True


notify = Notification()


async def main(loop):
try:
await smtpd(notify)
# notify.daemon_start()
controller.start()
except Exception as e:
print(e)
print(f'Error: {e}')


if __name__ == '__main__':

killer = GracefulKiller()

loop = asyncio.get_event_loop()

while not killer.kill_now:

# n = Notification()
# app wide notification
notification = Notification()

# print(n.info())
main(notification)

# logging.basicConfig(level=logging.DEBUG)
# loop.create_task(main(loop=loop))
try:
loop.run_until_complete(main(loop=loop))
# loop.run_forever()
except KeyboardInterrupt:
pass
print('Started')
notification.daemon_start()

loop.stop()
# try:
while not killer.kill_now:
sleep(2)
pass
# except KeyboardInterrupt:

notify.daemon_stop()
notification.daemon_stop()
print('\nFinishied')
4 changes: 2 additions & 2 deletions m2a.service
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
[Unit]
Description=Mail to Apprise Message Relay
Description=M2A Mail to Apprise Message Relay
Documentation=
After=nss-lookup.target
After=network.target

[Service]
ExecStart=/usr/bin/python /usr/local/bin/m2a.py
Restart=on-failure
Type=notify
# Type=notify

[Install]
WantedBy=default.target

0 comments on commit 5a3ba87

Please sign in to comment.