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