00b409c4bad975b09fe7665d01cb8c56e90b81a2 — Kyle Jones 1 year, 2 months ago 6f22e7c master v0.1.0
An HTTP server for sms-printer!
A sms_printer_server/__init__.py => sms_printer_server/__init__.py +7 -0
@@ 0,0 1,7 @@
from .restrictions import env_allowed_senders as __env_allowed_senders

ALLOWED_SENDERS = __env_allowed_senders()

from .server import application

A sms_printer_server/restrictions.py => sms_printer_server/restrictions.py +5 -0
@@ 0,0 1,5 @@
from os import getenv

def env_allowed_senders():
    return [num for num in getenv("ALLOWED_SENDERS", "").split(",") if num]

A sms_printer_server/server.py => sms_printer_server/server.py +64 -0
@@ 0,0 1,64 @@
from loguru import logger
from flask import Flask, Response, request
from sms_printer import parse_messages, print_message, parser_errors
from . import ALLOWED_SENDERS

application = Flask(__name__)

@application.route("/", methods=["GET"])
def main() -> Response:
    return Response(status=204)

@application.route("/sms-printer", methods=["POST"])
def sms_printer() -> Response:
        logger.trace("Request recieved:\n{}", request)
        messages = parse_messages(request.data)

    except parser_errors.NoParserForMessage:
        logger.warning("No parser could be found for this message!")
        return Response("", status=415)

    for message in messages:
        logger.info("Recieved message from %s", message.sender)

        if not allowed_sender(message.sender):
            logger.warning("Unauthorized sender %s", message.sender)

        logger.info("Printing message from %s", message.sender)
        logger.debug("Text: %s", message.text)

        except Exception:
            logger.error("Error printing message!")
            return Response("", status=500)

    return Response("", status=204)

# TODO Improve different number handling/parsing for comparisons
def allowed_sender(sender: str) -> bool:
    Checks the sender against our environment $ALLOWED_SENDERS

    ALLOWED_SENDERS is a comma-delimited list, with numbers strictly
    in the format copied from your provider. +12223334444 (string)
    logger.debug("Check allowed: {}", sender)
    if not bool(ALLOWED_SENDERS):
        logger.debug("No sender filter installed.")
        return True

    elif sender in ALLOWED_SENDERS:
        logger.debug("Sender is allowed")
        return True

        logger.debug("Sender is not allowed")
        return False