~kf5jwc/sms-printer

ref: cdb588488d49dee23d5ec1df35c935a0ba35e064 sms-printer/sms_printer/utils.py -rw-r--r-- 1.8 KiB View raw
cdb58848 — Kyle Jones Use loguru 1 year, 5 months 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
55
56
57
58
59
60
61
62
63
64
from os import path
from random import choice as rand_choice
from string import ascii_uppercase, digits
from subprocess import CalledProcessError, run
from tempfile import NamedTemporaryFile
from time import strftime

from flask import json

from .config import Environment

ENV = Environment()


def suffix(length=ENV.ARCHIVE_SUFFIX_LENGTH, chars=ascii_uppercase + digits) -> str:
    "Random suffix string"
    return "".join(rand_choice(chars) for x in range(length))


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)
    """
    return not bool(ENV.ALLOWED_SENDERS) or sender in ENV.ALLOWED_SENDERS


def log_request(data: str):
    """
    Log this request to the data path for this application.

    The format for these logs is the current timestamp to the second
    with a random suffix.
    """
    msg_id = "{}-{}".format(strftime("%Y%m%d-%H%M%S"), suffix())
    with open(path.join(ENV.ARCHIVE, msg_id), "w+") as archive_file:
        json.dump(data, archive_file)


def print_message(message: str) -> bool:
    """
    Sends a plaintext message to CUPS for printing.

    The message format can be customized by setting the environment's
    MESSAGE_FORMAT to a string, where `{message}` is replaced with
    the message text.
    """
    with NamedTemporaryFile(mode="w+") as tmp_file:
        tmp_file.write(ENV.MESSAGE_FORMAT.format(message=message))
        tmp_file.flush()

        try:
            run(
                ENV.print_command(tmp_file.name),
                check=True,
                timeout=ENV.PRINT_JOB_TIMEOUT,
            )

        except CalledProcessError:
            return False

    return True