~kf5jwc/sms-printer

ref: 88d91e19f2499a3933341a270f81e30ebc048ac3 sms-printer/sms_printer/utils.py -rw-r--r-- 1.4 KiB View raw
88d91e19 — Kyle Jones Refactor for adding JSON schema based parsing 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
"""
This file feels like it has way too much configuration to make sense
in its current state.
"""


import os
from math import floor
from subprocess import CalledProcessError, run
from tempfile import NamedTemporaryFile
from time import strftime

from flask import json
from xdg import BaseDirectory

ARCHIVE = os.getenv('ARCHIVE_DIR', BaseDirectory.save_data_path(__name__))
ALLOWED_SENDERS = [
    num for num in os.getenv('ALLOWED_SENDERS', '').split(',') if num
]
PRINTER_FORMAT = "\n\n" + "      {message}"*2
TEXT_SCALE = 0.6
CPI_DEFAULT = 10
LPI_DEFAULT = 6
TOP_MARGIN = None
SIDE_MARGIN = None


def allowed_sender(sender: str) -> bool:
    return (not bool(ALLOWED_SENDERS) or sender in ALLOWED_SENDERS)

def log_request(data: str):
    timestamp = strftime("%Y%m%d-%H%M%S")
    with open(os.path.join(ARCHIVE, timestamp), 'w+') as archive_file:
        json.dump(data, archive_file)

def print_message(message: str) -> bool:
    with NamedTemporaryFile(mode='w+') as tmp_file:
        print(PRINTER_FORMAT.format(message=message), file=tmp_file)
        tmp_file.flush()

        command = [
            "lp",
            "-o cpi={}".format(floor(CPI_DEFAULT*(1/TEXT_SCALE))),
            "-o lpi={}".format(floor(LPI_DEFAULT*(1/TEXT_SCALE))),
            tmp_file.name]
        try:
            run(command, check=True, timeout=10)

        except CalledProcessError:
            return False

    return True