horetu  Artifact Content

Artifact 3460d6212c9cffd12210fa3929ad22614a85d543:


#!/usr/bin/env python3
import os
import concurrent.futures as f
import subprocess
import re
from tempfile import NamedTemporaryFile

# horetu
import sys
sys.path.insert(0, os.path.abspath(os.path.join(__file__, '..', '..')))
import horetu
from horetu.annotations import InputBinaryFile

def PageList(x):
    if not re.match(r'^[0-9,]+$', x):
        raise ValueError('Not a page list: %s' % repr(x))
    return x

SIDES = ('one-sided', 'two-sided-long-edge', 'two-sided-short-edge')

# Utilities
def run(argv):
    p = subprocess.Popen(argv,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p.wait()
    if p.returncode:
        raw = p.stderr.read()
        err = raw.decode('utf-8')
        raise horetu.Error(err)
    else:
        raw = p.stdout.read()
        out = raw.decode('utf-8')
        return out

JOB_ID = re.compile(r'^request id is ([^ ]+) \(.+$')

# lp commands
def lp(pdf: InputBinaryFile, sides: SIDES='two-sided-long-edge', copies: int=1,
       page_list: PageList=None):
    '''
    :param pdf: PDF file to print
    :param sides: One-sided or two-sided
    :param int copies: Number of copies
    :param page_list: Specifies which pages to print in the document.
        The list can contain a list of numbers and ranges (#-#)
        separated  by  commas,  e.g.,  "1,3-5,16".
    '''
    argv = [
        'lp',
        '-n', str(copies),
        '-o', 'sides=%s' % sides,
        '-o', 'media=a4',
    ]
    if page_list:
        argv.extend(['-P', page_list])

    with NamedTemporaryFile('wb') as tmp:
        tmp.file.write(pdf.read())
        tmp.file.flush()
        argv.append(tmp.name)
        out = run(argv)
    return out

if __name__ == '__main__':
    wd = os.path.dirname(os.path.abspath(os.path.join(__file__)))
    ini = os.path.join(wd, 'print-server.ini')
    if os.getcwd() == wd:
        p = subprocess.Popen(['uwsgi', '--ini', ini])
        p.wait()
    else:
        sys.stderr.write('Run this from %s\n' % wd)
        sys.exit(1)
else:
    application = horetu.wsgi_form(lp, debug=True)