~kf5jwc/sms-printer

ref: 83f141d0bd34662859108a44509a56292fe3bc1d sms-printer/sms_printer/application.py -rw-r--r-- 1.6 KiB View raw
83f141d0 — Kyle Jones Break out the library. 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import logging

from flask import Flask, Response, json, request

from sms_broker_parsers import get_mimetype_parser
from sms_broker_parsers.errors import NoMatchingSchema, NoParserForMimeType
from .utils import allowed_sender, log_request, print_message

APP = Flask(__name__)
logging.basicConfig(level=logging.DEBUG)


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


@APP.route("/sms-printer", methods=["POST"])
def sms_printer() -> Response:
    # If this throws, flask takes care of it
    sms_input = request.get_json(force=True)

    try:
        parser = get_mimetype_parser(request.mimetype)

    except NoParserForMimeType:
        logging.warning("No parsers available for the given mimetype!")
        logging.debug("mimetype: {}".format(request.mimetype))
        logging.debug("header: {}".format(request.headers["Content-Type"]))
        return Response(status=415)

    try:
        sms_list = parser(sms_input)
        log_request(sms_input)

    except NoMatchingSchema:
        logging.warning("Unrecognized message format!")
        logging.debug(json.dumps(sms_input))
        return Response(status=415)

    for sms in sms_list:

        logging.info("Recieved sms from %s", sms.sender)
        if not allowed_sender(sms.sender):
            logging.warning("Unauthorized sender %s", sms.sender)
            return Response(status=401)

        logging.info("Printing sms from %s", sms.sender)
        logging.debug("Text: %s", sms.text)
        if not print_message(sms.text):
            logging.error("Error printing sms")
            return Response(status=500)

        return Response(status=200)