~kf5jwc/sms-printer

ref: 5be96bf4f52a694579a9119b84c93c4744d18a7e sms-printer/sms_printer/application.py -rw-r--r-- 1.1 KiB View raw
5be96bf4 — Kyle Jones Initial 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
import os
from subprocess import CalledProcessError, run
from tempfile import NamedTemporaryFile

from flask import Flask, Response, json, request
from xdg import BaseDirectory

APP = Flask(__name__)
ARCHIVE = os.getenv('ARCHIVE_DIR', BaseDirectory.save_data_path(__name__))
ALLOWED_SENDERS = [
    num for num in os.getenv('ALLOWED_SENDERS', '').split(',') if num
]


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


@APP.route("/sms-printer", methods=['POST'])
def sms_printer():
    for sms in request.get_json(force=True):
        if ALLOWED_SENDERS and sms['message']['from'] not in ALLOWED_SENDERS:
            return Response(status=401)

        with open(os.path.join(ARCHIVE, sms['message']['id']), 'w+') as f:
            json.dump(sms, f)

        with NamedTemporaryFile(mode='w+') as f:
            print("{}".format(sms['message']['text']), file=f)
            f.flush()
            try:
                run(['lp', f.name], check=True, timeout=10)
            except CalledProcessError:
                return Response(status=500)

    return Response(status=200)