From 349908858debf75e8a9802fa368bffc947f11c40 Mon Sep 17 00:00:00 2001 From: thrrgilag Date: Wed, 28 Dec 2022 07:38:52 -0800 Subject: [PATCH] initial commit --- .dockerignore | 15 ++++ .gitignore | 66 +++++++++++++++ Dockerfile | 22 +++++ Jenkinsfile | 28 +++++++ LICENSE | 9 ++ clacksme/clacksme.py | 193 +++++++++++++++++++++++++++++++++++++++++++ clacksme/model.py | 45 ++++++++++ setup.py | 20 +++++ 8 files changed, 398 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 Jenkinsfile create mode 100644 LICENSE create mode 100644 clacksme/clacksme.py create mode 100644 clacksme/model.py create mode 100644 setup.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..5026a5e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,15 @@ +__pycache__/ +*.py[cod] +*.yaml +*.db +*.sublime-project +*.sublime-workspace +.vscode/ +.git/ +.gitignore +Dockerfile +.dockerignore +snap/ +Jenkinsfile +.gitlab-ci.yml +contrib/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..081067d --- /dev/null +++ b/.gitignore @@ -0,0 +1,66 @@ +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# my other cruft +*.db +# *.yaml +# *.sublime-project +# *.sublime-workspace +# .vscode/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ffe182c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +FROM python:3.11-slim-bullseye AS builder + +RUN pip install --no-cache-dir --upgrade pip setuptools wheel + +WORKDIR /usr/src/app + +COPY . . + +RUN pip wheel . --wheel-dir /wheels --find-links /wheels + + + +FROM python:3.11-slim-bullseye AS run + +COPY --from=builder /wheels /wheels + +RUN pip --no-cache-dir install --find-links /wheels --no-index clacksme + +VOLUME /data +WORKDIR /data + +CMD ["clacksme","-s","/data/store.db"] diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..2b5ff37 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,28 @@ +pipeline { + agent none + environment { + IMAGE_TAG = "git.dreamfall.space/thrrgilag/clacksme:latest" + } + stages { + stage('Build docker image') { + agent { label 'docker-build' } + steps { + mattermostSend "Docker build started - ${env.JOB_NAME} ${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)" + script { + docker.withRegistry('https://git.dreamfall.space/thrrgilag', 'docker-gitea-creds') { + def customImage = docker.build(${env.IMAGE_TAG}) + customImage.push() + } + } + } + post { + success { + mattermostSend color: "good", message: "Docker build success - ${env.JOB_NAME} ${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)" + } + failure { + mattermostSend color: "danger", message: "Docker build failure - ${env.JOB_NAME} ${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)" + } + } + } + } +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..684048a --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2022 Morgan McMillian + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/clacksme/clacksme.py b/clacksme/clacksme.py new file mode 100644 index 0000000..86ec45c --- /dev/null +++ b/clacksme/clacksme.py @@ -0,0 +1,193 @@ +import argparse +import threading +import logging +import signal +import requests + +from multiprocessing import Process, Event, Queue +from logging.handlers import QueueHandler +from imapclient import IMAPClient, exceptions +from datetime import datetime +from clacksme.model import * + +_shutdown = Event() + +class MailboxNotifier(object): + + def __init__(self, mailbox): + self.mailbox = mailbox + + def start(self, log_queue): + imap_log = logging.getLogger('imapclient') + imap_log.level = logging.INFO + log_queue_handler = QueueHandler(log_queue) + self.log = logging.getLogger(self.mailbox.user) + self.log.level = logging.DEBUG + self.log.addHandler(log_queue_handler) + imap_log.addHandler(log_queue_handler) + + self.log.info( + f"Starting up IMAP connection for {self.mailbox.user}") + while not _shutdown.is_set(): + try: + with IMAPClient(self.mailbox.imap_host) as self.imap: + self.imap.login(self.mailbox.imap_user, + self.mailbox.imap_pass) + self.imap.select_folder("INBOX", readonly=True) + self.log.info("Connected to INBOX") + messages = self.imap.search("UNSEEN") + if len(messages) > 0: + notify = self.check_events(messages) + + self.imap_idle() + + except Exception: + self.log.error("IMAP exception of some kind") + self.log.exception("IMAP") + + def imap_idle(self): + while not _shutdown.is_set(): + try: + self.imap.idle() + self.log.info("Waiting for new messages") + responses = self.imap.idle_check(timeout=30) + self.log.debug(responses) + for resp in responses: + if len(resp) == 2: + if resp[1] == b"RECENT": + self.imap.idle_done() + messages = self.imap.search("UNSEEN") + if len(messages) > 0: + notify = self.check_events(messages) + self.imap.idle() + + self.log.info("IDLE done") + self.imap.idle_done() + + except IMAPClient.AbortError: + self.log.error("IMAP abort, break") + break + + def check_events(self, messages): + notify = False + events = Events.select().where(Events.user == self.mailbox.user) + event_ids = [event.event_id for event in events] + for uid in messages: + if str(uid) not in event_ids: + self.log.info("New message") + new_event = Events( + user=self.mailbox.user, + service="imap", + event_id=uid) + new_event.save() + now = datetime.now() + if self.mailbox.last_check is not None: + delta = now - self.mailbox.last_check + if delta.seconds > 60: + notify = True + else: + notify = True + + if notify: + self.log.debug("Notify") + self.mailbox.last_check = now + self.mailbox.save() + self.on_notify() + + def on_notify(self): + self.log.info("Triggering notifications") + text = f"New messages have been recieved at {self.mailbox.imap_user}" + targets = Services.select().where(Services.user == self.mailbox.user) + for target in targets: + + if target.service == "pushover" and target.enabled: + self.send_pushover(target.target, text) + + elif target.service == "mattermost" and target.enabled: + self.send_mattermost(target.target, text) + + else: + self.log.info("unknown notifiaction service") + + def send_pushover(self, po_user, text): + notifier = Notifier.get(Notifier.service == "pushover") + url = "https://api.pushover.net/1/messages.json" + params = { + "token": notifier.secret, + "user": po_user, + "message": text + } + response = requests.post(url, data=params) + self.log.debug(response.status_code) + self.log.debug(response.text) + + def send_mattermost(self, url, text): + params = { + "text": text + } + response = requests.post(url, json=params) + self.log.debug(response.status_code) + self.log.debug(response.text) + + +def shutdown_handler(signal, frame): + _shtudown.set() + +def logger_thread(log_queue): + logging.debug("starting logger thread") + while True: + logging.debug(".") + entry = log_queue.get() + if entry is None: + logging.debug(".break.") + break + logger = logging.getLogger(entry.name) + logger.handle(entry) + +def main(): + signal.signal(signal.SIGTERM, shutdown_handler) + + a_parser = argparse.ArgumentParser( + description="IMAP notification suite") + a_parser.add_argument( + '-s', '--store', default="store.db", + help="sqlite database filepath") + args = a_parser.parse_args() + + db.init(args.store) + create_tables() + + log_queue = Queue() + processes = [] + for mailbox in Mailbox.select(): + imap_process = MailboxNotifier(mailbox) + p = Process( + target=imap_process.start, name=mailbox.user, args=(log_queue,)) + processes.append(p) + p.daemon = True + p.start() + + logging.basicConfig(level=logging.DEBUG) + logging.debug("starting up main") + log_thread = threading.Thread(target=logger_thread, args=(log_queue,)) + log_thread.start() + + logging.debug(processes) + try: + for p in processes: + p.join() + + except KeyboardInterrupt: + logging.debug("CTRL+C") + logging.debug("Keyboard interrupt, shutting down from main") + for p in processes: + p.terminate() + logging.debug("..terminate..") + _shutdown.set() + + log_queue.put(None) + log_thread.join() + logging.debug("exiting main") + +if __name__ == "__main__": + main() diff --git a/clacksme/model.py b/clacksme/model.py new file mode 100644 index 0000000..072578f --- /dev/null +++ b/clacksme/model.py @@ -0,0 +1,45 @@ +from peewee import * +from playhouse.migrate import * + +db = SqliteDatabase(None) +migrator = SqliteMigrator(db) + +db_schema = "1" + +class BaseModel(Model): + class Meta: + database = db + +class System(BaseModel): + key = CharField(unique=True) + value = CharField() + +class Mailbox(BaseModel): + user = CharField() + imap_host = CharField() + imap_user = CharField() + imap_pass = CharField() + last_check = DateTimeField(null=True) + +class Events(BaseModel): + user = CharField() + service = CharField() + event_id = CharField() + +class Notifier(BaseModel): + service = CharField() + client_id = CharField(null=True) + secret = CharField(null=True) + url = CharField(null=True) + +class Services(BaseModel): + user = CharField() + service = CharField() + target = CharField() + enabled = CharField(default=True) + +def create_tables(): + tables = [System, Mailbox, Events, Notifier] + with db: + if not db.table_exists(System._meta.table_name): + db.create_tables(tables) diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..2ff90f1 --- /dev/null +++ b/setup.py @@ -0,0 +1,20 @@ +from setuptools import setup + +setup( + name="clacksme", + version="0.1.0", + py_modules=[ + "clacksme.clacksme", + "clacksme.model", + ], + install_requires=[ + "imapclient", + "peewee", + "requests", + ], + entry_points={ + "console_scripts": [ + "clacksme = clacksme.clacksme:main", + ] + }, +)