~kf5jwc/sms-printer

ref: 1f13487e66a7511ddcc612d0fbe9a6d12abb9576 sms-printer/sms_printer/printer.py -rw-r--r-- 1.7 KiB
1f13487e — Kyle Jones Merge branch 'namespaces' 1 year, 8 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
from subprocess import CalledProcessError, run
from tempfile import NamedTemporaryFile
from typing import List
from loguru import logger
from . import ENV, PARSERS
from .parser_errors import NoParserForMessage, NoValidParserForMessage


def parse_messages(data: str) -> List:
    logger.trace("Parsing: {}", data)

    parsers = [parser for parser in PARSERS if parser.validate(data)]
    logger.trace("Parsers for this mesage:")
    [logger.trace("{}", repr(parser)) for parser in parsers]
    logger.info("Parsers found for this message: {}", len(parsers))

    if not len(parsers):
        raise NoValidParserForMessage

    for parser in parsers:
        try:
            messages = parser.parse(data)
        except Exception as e:
            logger.trace("Parser encountered error while parsing message: {}", parser)
            logger.trace("Exception: {}", e)
        else:
            return messages

    raise NoParserForMessage


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.
    """
    logger.info("Printing message!")
    logger.debug("{}", message)

    with NamedTemporaryFile(mode="w+") as tmp_file:
        logger.debug("Print file: {}", tmp_file.name)
        tmp_file.write(ENV.MESSAGE_FORMAT.format(message=message))
        tmp_file.flush()

        try:
            print_cmd = ENV.print_command(tmp_file.name)
            logger.debug("Print command: {}", print_cmd)
            run(print_cmd, check=True, timeout=ENV.PRINT_JOB_TIMEOUT)

        except CalledProcessError:
            return False

    return True