diff --git a/Dockerfile b/Dockerfile index 7eb9964..956a472 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -# asyncore/asynchat (used by lpdserver.py and httpserver.py) were removed in python 3.12 +# the LPD receiver and web server run on asyncio and aiohttp, so any python from 3.9 will do FROM python:3.11-slim MAINTAINER chris@shucksmith.co.uk diff --git a/README.md b/README.md index ba00282..6169be4 100644 --- a/README.md +++ b/README.md @@ -22,26 +22,33 @@ The following will checkout the source code, build a docker image and start an i ## Source code & implementation notes -* `lpdserver.py` implements a UNIX LPD daemon for recieving print jobs -* `httpserver.py` simple http server using asynchat +* `lpdserver.py` implements a UNIX LPD daemon for recieving print jobs, on asyncio +* `httpserver.py` the web server: path handlers and static files on aiohttp, handlers run on the event loop one at a time * `mailer.py` asynchronous mail queue to Gmail * `docparser` recognise and parse some plain-text formats from 1990 to JSON * `stationary.py` format JSON to nice PDF files -* `printing.py` printing with CUPS via `lp`. Each document sent is recorded (job, key, printer, CUPS request id or the error) in `~/printerface/printer.pickle`, newest first and trimmed to `result_count` like the sent emails, and listed on the job page. The file is written from the main loop only when something changed +* `printing.py` printing with CUPS via `lp`. Each document sent is recorded (job, key, printer, CUPS request id or the error) in `~/printerface/printer.pickle`, newest first and trimmed to `[Printing] result_count` (the sent emails and uploads have their own `result_count` under `[Gmail]` and `[Web]`), and listed on the job page. The file is written from the main loop only when something changed +* `derived.py` a cache, `~/printerface/derived.pickle`, of what is slow to work out from a stored job: its parsed pages and the names of its PDFs. At startup a job whose file is unchanged and whose parser is unchanged takes these from the cache (a thousand jobs in under a second, against about eight), and a job that has left the loaded history drops out of the file the next time it is written (at most every three minutes, and at shutdown). The PDFs are not redrawn when the stationery changes: Settings > Stationery counts the documents drawn under older stationery and redraws them on request * `printstatus.py` read-only CUPS status for the Printers page (one `lpstat -t` in the C locale, cached for 10s), and the check of whether auto-printing can work. lpstat can show a stuck or stopped queue but not that a page was printed +Job pickles that appear in `~/printerface/data/pickle` without arriving over LPD (copied in from another instance, say) +are picked up every few seconds, once they have been still for a couple of seconds, and are treated exactly like a job +that has just arrived: they go into the history in file name order and are auto-printed and auto-uploaded if their +type says so. So copy in only what should be acted on: a file older than everything in a full history is ignored, but +one inside it is not. + A GET never changes anything: sending an email, printing, editing the address book and saving or reverting a template are POSTs, and their handlers return `httpserver.Redirect(...)` (a 303) to a page that is safe to refresh, carrying at most a harmless note in the query string ("queued=1"). A POST that is refused re-renders the form instead, with what was typed. New actions should follow the same pattern. -Requires **python 3.11** (3.9+ for the dependencies, but `asyncore`/`asynchat` were removed from the standard library in 3.12). +Requires **python 3.11** or later. The LPD receiver and the web server share one asyncio event loop (so the job list needs no locking); mail is queued on the loop and sent with smtplib in a worker thread. Requirements are specified in requirements.txt Unit tests run during `docker build` or with: $ python3.11 -m unittest discover --pattern=*.py -Uses python asyncore/smtp, bootstrap web framework +Uses python asyncio/aiohttp/smtplib, bootstrap web framework Jobs, rendered PDFs, the email address book and `email.cfg` overrides live in `~/printerface`. Set the `PRINTERFACE_HOME` environment variable to use a different directory, for example to run a second instance diff --git a/defaults.cfg b/defaults.cfg index 0057a81..227ed7e 100644 --- a/defaults.cfg +++ b/defaults.cfg @@ -17,6 +17,8 @@ purch_instruction_fr=Veuillez confirmer reception de cette commande et sa\ndate purch_instruction_en=Please contact immediately if any problems or\nqueries. logo=logo.jpg logo2= +# How many printed documents to remember (newest first) on the Printed Documents page +result_count=200 [Main] summary_trim=AAAA,BBBBBB @@ -25,6 +27,16 @@ http_port=8081 baseuri=localhost:8081 tz=Europe/London +# Where invoices, credit notes and statements are uploaded as they are printed. Blank turns it off. +# base_url is the site, e.g. https://abfw-stage.herokuapp.com/ ; api_key is that site's token for the Printerface user. +[Web] +base_url= +api_key= +# Kinds of document uploaded as soon as they arrive, comma separated: invoice, crednote, statement +auto_types= +# How many uploads to remember (newest first) on the Uploads page +result_count=120 + [Robot] auto_types=Delvnote,Pick lst auto_printer=HP_TONY diff --git a/derived.py b/derived.py new file mode 100644 index 0000000..9f11847 --- /dev/null +++ b/derived.py @@ -0,0 +1,121 @@ +""" +A cache of what is slow to work out from a stored job: the parsed pages, and the names of the PDFs made from them. +Reading the job pickles is quick (0.1 s for a thousand); parsing them and drawing the PDFs is what makes a start +slow, so the next start can take those from here. + +The cache is only ever an optimisation. The job pickles stay the record, and anything wrong with an entry (a +different job file, newer parser code, a missing PDF) means that job is worked out again. One file, written +atomically; one entry per job file name, so it follows the history: a job that leaves the loaded history is +dropped from the file the next time it is written. + +An entry is only trusted if + * the job file is the one it was made from (size and modification time), + * it was parsed by the same parser (`parse_stamp`: docparser.py and textutil.py), +and the PDFs it names are still on disk. How the PDFs were drawn (`render_stamp`: stationary.py, the [Printing] +company details and the logos) is recorded with it, but a change does not redraw them by itself: the Stationery +settings page counts the jobs drawn under older stationery and has the button that redraws them. +""" + +import hashlib +import os +import pickle +import time +import traceback + +from settings import BASE_DIR, HOME, config + +PATH = os.path.join(HOME, 'derived.pickle') + +# bumped if the layout of an entry changes +FORMAT = 1 + +# the file is rewritten at most this often (seconds) while something is changing +FLUSH_EVERY = 180 + + +def _digest(parts): + h = hashlib.sha256() + for p in parts: + h.update(p if isinstance(p, bytes) else repr(p).encode('utf-8')) + h.update(b'\0') + return h.hexdigest()[:16] + + +def _source(name): + with open(os.path.join(BASE_DIR, name), 'rb') as f: + return f.read() + + +def parse_stamp(): + return _digest([FORMAT, _source('docparser.py'), _source('textutil.py')]) + + +def render_stamp(): + parts = [FORMAT, _source('stationary.py'), sorted(config.items('Printing'))] + for key in ('logo', 'logo2'): + path = os.path.expanduser(config.get('Printing', key, fallback='')) + try: + st = os.stat(path) if path else None + except OSError: + st = None + parts.append((path, st and (st.st_size, st.st_mtime_ns))) + return _digest(parts) + + +class DerivedCache(object): + def __init__(self, path=PATH): + self.path = path + self.entries = {} + self.dirty = False + self.last_flush = 0 + self.parse_stamp = parse_stamp() + self.render_stamp = render_stamp() + try: + with open(path, 'rb') as f: + data = pickle.load(f) + if data.get('format') == FORMAT: + self.entries = data['entries'] + except FileNotFoundError: + pass + except Exception: + print('[derived] ignoring an unreadable cache %s' % path) + traceback.print_exc() + + def lookup(self, name, stat): + """The entry for this job file if it is still good, else None.""" + e = self.entries.get(name) + if e and e['stat'] == stat and e['parse_stamp'] == self.parse_stamp: + return e + return None + + def snapshot(self, jobs): + """The entries for the jobs as they are now: what a flush writes.""" + out = {} + for j in jobs: + if j.get('stat') and 'groupfiles' in j: + out[j['name']] = dict(stat=j['stat'], parse_stamp=self.parse_stamp, render_stamp=j.get('render_stamp'), + parsed=j['parsed'], groupkey=j['groupkey'], groupfiles=j['groupfiles']) + return out + + def flush(self, jobs, force=False): + """Write the cache if it changed, and not more than every FLUSH_EVERY seconds unless forced. Never raises: a + full disk mustn't stop the server.""" + if not self.dirty or (not force and time.time() - self.last_flush < FLUSH_EVERY): + return False + try: + entries = self.snapshot(jobs) + tmp = self.path + '.tmp' + with open(tmp, 'wb') as f: + pickle.dump(dict(format=FORMAT, entries=entries), f, protocol=pickle.HIGHEST_PROTOCOL) + os.replace(tmp, self.path) + self.entries = entries + self.dirty = False + self.last_flush = time.time() + return True + except Exception: + traceback.print_exc() + return False + + def stale(self, jobs): + """The jobs whose PDFs were drawn under different stationery from today's.""" + return [j for j in jobs if j.get('render_stamp') != self.render_stamp] diff --git a/httpserver.py b/httpserver.py index 46b023b..50b7d12 100644 --- a/httpserver.py +++ b/httpserver.py @@ -1,88 +1,36 @@ """ -Simple HTTP server build on the asyncore/asynchat module. +The web server, on aiohttp. -Python's built-in SimpleHTTPServer is mixed up with SocketServer blocking/ -threading semantics in the classes it inherits. The various adapters to make -it work with asynchat are pretty auful. This file class strips it back to -work only with asynchat. +Pages are plain functions registered by path (`pathhandlers`), the same ones the asyncore server called: +`handler(query_string=..., resp=...)` for GET and HEAD and `handler(query_string=..., postreq=...)` for POST, +where the query string and the form fields arrive as {name: [values]}. A handler returns `(body, content type)`, +with body a str, bytes or binary file object, or a `Redirect`. Anything else is served as a file from the +web root. -Incorporates basic support for dynamic pages, simple logging, connection re-use, -and allows http root to be specified. - -There are plenty of capable web servers for python, absoutely nobody should use -this class. _Except_ in the rare case you need a co-operative single -threaded HTTP to mix inline with other protocol handlers to avoid locking a -datamodel. +Handlers run on the event loop, one at a time, exactly as before: they and the LPD receiver share one thread, so +the job list and the other data they touch need no locking. A handler that blocks (printing, rendering a big +PDF) holds up everything else for its duration, and that is deliberate, not an oversight. """ -import asynchat, asyncore, socket -import posixpath, sys, io, os, traceback -import html +import asyncio +import io +import mimetypes +import os +import posixpath +import sys import time +import traceback import urllib.parse -import mimetypes - -# HTTP headers and the request line are latin-1 on the wire; bodies we generate are utf-8 -HEADER_ENCODING = 'latin-1' -BODY_ENCODING = 'utf-8' +from email.utils import formatdate -"""HTTP server base class. +from aiohttp import web -Note: the class in this module doesn't implement any HTTP request; see -SimpleHTTPServer for simple implementations of GET, HEAD and POST -(including CGI scripts). It does, however, optionally implement HTTP/1.1 -persistent connections, as of version 0.3. - -Contents: - -- BaseHTTPRequestHandler: HTTP request handler base class -""" -__version__ = "0.3" - -class CaseInsensitiveDict(dict): - """Dictionary with case-insensitive keys - Replacement for the deprecated mimetools.Message class. infile is a binary file of header lines. - """ - def __init__(self, infile, *args): - self._ci_dict = {} - lines = infile.readlines() - for line in lines: - line = line.decode(HEADER_ENCODING) - if ':' not in line: - continue - k,v=line.split(":",1) - self._ci_dict[k.lower()] = self[k] = v.strip() - self.headers = list(self.keys()) - - def getheader(self,key,default=""): - return self._ci_dict.get(key.lower(),default) - - def get(self,key,default=""): - return self._ci_dict.get(key.lower(),default) - - def __getitem__(self,key): - return self._ci_dict[key.lower()] - - def __contains__(self,key): - return key.lower() in self._ci_dict - -# Default error message template -DEFAULT_ERROR_MESSAGE = """\ -
-Error code %(code)d. -
Message: %(message)s. -
Error code explanation: %(code)s = %(explain)s. - -""" +# bodies we generate are utf-8 +BODY_ENCODING = 'utf-8' -DEFAULT_ERROR_CONTENT_TYPE = "text/html" +# a form post (an email body, a template) is small; this only stops a runaway client +MAX_REQUEST_BYTES = 16 * 1024 * 1024 -def _quote_html(text): - return text.replace("&", "&").replace("<", "<").replace(">", ">") class Redirect(object): """A path handler returns this instead of (body, content type) to answer with a redirect. It is a 303 See @@ -91,6 +39,7 @@ class Redirect(object): def __init__(self, location): self.location = location + def _body_file(f, ctype): """Normalise whatever a path handler returned into (binary file object, content type). Handlers return str (json, plain), bytes (mako output, pdf) or a binary file object.""" @@ -102,670 +51,153 @@ def _body_file(f, ctype): ctype += '; charset=' + BODY_ENCODING return f, ctype -class BaseHTTPRequestHandler(asynchat.async_chat): - - # The Python system version, truncated to its first component. - sys_version = "Python/" + sys.version.split()[0] - - # The server software version. You may want to override this. - # The format is multiple whitespace-separated strings, - # where each string is of the form name[/version]. - server_version = "BaseHTTP/" + __version__ - - # The default request version. This only affects responses up until - # the point where the request line is parsed, so it mainly decides what - # the client gets back when sending a malformed request line. - # Most web servers default to HTTP 0.9, i.e. don't send a status line. - default_request_version = "HTTP/0.9" - - def parse_request(self, requestline): - """Parse a request (internal). - the results are in self.command, self.path, self.request_version, - self.headers and self.close_connection. - - Return True for success, False for failure; on failure a call to - send_error is made before returning. - - """ - self.command = None # set in case of error on the first line - self.request_version = version = self.default_request_version - self.close_connection = 1 - - requestline = requestline.decode(HEADER_ENCODING).rstrip('\r\n') - self.requestline = requestline - words = requestline.split() - if len(words) == 3: - command, path, version = words - if version[:5] != 'HTTP/': - self.send_error(400, "Bad request version (%r)" % version) - return False - try: - base_version_number = version.split('/', 1)[1] - version_number = base_version_number.split(".") - # RFC 2145 section 3.1 says there can be only one "." and - # - major and minor numbers MUST be treated as - # separate integers; - # - HTTP/2.4 is a lower version than HTTP/2.13, which in - # turn is lower than HTTP/12.3; - # - Leading zeros MUST be ignored by recipients. - if len(version_number) != 2: - raise ValueError - version_number = int(version_number[0]), int(version_number[1]) - except (ValueError, IndexError): - self.send_error(400, "Bad request version (%r)" % version) - return False - if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1": - self.close_connection = 0 - if version_number >= (2, 0): - self.send_error(505, "Invalid HTTP Version (%s)" % base_version_number) - return False - elif len(words) == 2: - command, path = words - self.close_connection = 1 - if command != 'GET': - self.send_error(400, "Bad HTTP/0.9 request type (%r)" % command) - return False - elif not words: - return False - else: - self.send_error(400, "Bad request syntax (%r)" % requestline) - return False - - querystring = dict() - qparts = path.split('?', 1) - if len(qparts) > 1: - path = qparts[0] - querystring = urllib.parse.parse_qs(qparts[1]) - self.command, self.path, self.request_version, self.query_string = command, path, version, querystring - - # Examine the headers and look for a Connection directive - self.headers = CaseInsensitiveDict(self.rfile, 0) - - conntype = self.headers.get('Connection', "") - if conntype.lower() == 'close': - self.close_connection = 1 - elif (conntype.lower() == 'keep-alive' and - self.protocol_version >= "HTTP/1.1"): - self.close_connection = 0 - return True - - def send_error(self, code, message=None): - """Send and log an error reply. - - Arguments are the error code, and a detailed message. - The detailed message defaults to the short entry matching the - response code. - - This sends an error response (so it must be called before any - output has been generated), logs the error, and finally sends - a piece of HTML explaining the error to the user. - - """ - - try: - short, long = self.responses[code] - except KeyError: - short, long = '???', '???' - if message is None: - message = short - explain = long - self.log_error("code %d, message %s", code, message) - # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201) - content = (self.error_message_format % - {'code': code, 'message': _quote_html(message), 'explain': explain}) - self.send_response(code, message) - self.send_header("Content-Type", self.error_content_type) - self.send_header('Connection', 'close') - self.end_headers() - if self.command != 'HEAD' and code >= 200 and code not in (204, 304): - self.push(content.encode(BODY_ENCODING)) - - error_message_format = DEFAULT_ERROR_MESSAGE - error_content_type = DEFAULT_ERROR_CONTENT_TYPE - - def send_response(self, code, message=None): - """Send the response header and log the response code. - - Also send two standard headers with the server software - version and the current date. - - """ - self.log_request(code) - if message is None: - if code in self.responses: - message = self.responses[code][0] - else: - message = '' - if self.request_version != 'HTTP/0.9': - self.push(("%s %d %s\r\n" % (self.protocol_version, code, message)).encode(HEADER_ENCODING, 'replace')) - self.send_header('Server', self.version_string()) - self.send_header('Date', self.date_time_string()) - def send_header(self, keyword, value): - """Send a MIME header.""" - if self.request_version != 'HTTP/0.9': - self.push(("%s: %s\r\n" % (keyword, value)).encode(HEADER_ENCODING, 'replace')) +if not mimetypes.inited: + mimetypes.init() # try to read system mime.types +extensions_map = mimetypes.types_map.copy() +extensions_map.update({ + '': 'application/octet-stream', # Default + '.py': 'text/plain', + '.c': 'text/plain', + '.h': 'text/plain', +}) - if keyword.lower() == 'connection': - if value.lower() == 'close': - self.close_connection = 1 - elif value.lower() == 'keep-alive': - self.close_connection = 0 - def end_headers(self): - """Send the blank line ending the MIME headers.""" - if self.request_version != 'HTTP/0.9': - self.push(b"\r\n") - - def log_request(self, code='-', size='-'): - """Log requests, called by send_response(). """ - self.log_message('"%s" %s %s', self.requestline, str(code), str(size)) - - def log_error(self, format, *args): - """Log an error. - - This is called when a request cannot be fulfilled. By - default it passes the message on to log_message(). - - Arguments are the same as for log_message(). - - XXX This should go to the separate error log. - - """ - - self.log_message(format, *args) - - def log_message(self, format, *args): - """Log an arbitrary message. - - This is used by all other logging functions. Override - it if you have specific logging wishes. - - The first argument, FORMAT, is a format string for the - message to be logged. If the format string contains - any % escapes requiring parameters, they should be - specified as subsequent arguments (it's just like - printf!). - - The client host and current date/time are prefixed to - every message. - - """ - - sys.stderr.write("%s - - [%s] %s\n" % - (self.address_string(), - self.log_date_time_string(), - format%args)) - - def version_string(self): - """Return the server software version string.""" - return self.server_version + ' ' + self.sys_version - - def date_time_string(self, timestamp=None): - """Return the current date and time formatted for a message header.""" - if timestamp is None: - timestamp = time.time() - year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp) - s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( - self.weekdayname[wd], - day, self.monthname[month], year, - hh, mm, ss) - return s - - def log_date_time_string(self): - """Return the current time formatted for logging.""" - now = time.time() - year, month, day, hh, mm, ss, x, y, z = time.localtime(now) - s = "%02d/%3s/%04d %02d:%02d:%02d" % ( - day, self.monthname[month], year, hh, mm, ss) - return s - - weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] - - monthname = [None, - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - - def address_string(self): - """Return the client address formatted for logging. - - This version looks up the full hostname using gethostbyaddr(), - and tries to find a name that contains at least one dot. - - """ - - host, port = self.client_address[:2] - # return socket.getfqdn(host) - return host - - # Essentially static class variables - - # The version of the HTTP protocol we support. - # Set this to HTTP/1.1 to enable automatic keepalive - protocol_version = "HTTP/1.1" - - # Table mapping response codes to messages; entries have the - # form {code: (shortmessage, longmessage)}. - # See RFC 2616. - responses = { - 100: ('Continue', 'Request received, please continue'), - 101: ('Switching Protocols', - 'Switching to new protocol; obey Upgrade header'), - - 200: ('OK', 'Request fulfilled, document follows'), - 201: ('Created', 'Document created, URL follows'), - 202: ('Accepted', - 'Request accepted, processing continues off-line'), - 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), - 204: ('No Content', 'Request fulfilled, nothing follows'), - 205: ('Reset Content', 'Clear input form for further input.'), - 206: ('Partial Content', 'Partial content follows.'), - - 300: ('Multiple Choices', - 'Object has several resources -- see URI list'), - 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), - 302: ('Found', 'Object moved temporarily -- see URI list'), - 303: ('See Other', 'Object moved -- see Method and URL list'), - 304: ('Not Modified', - 'Document has not changed since given time'), - 305: ('Use Proxy', - 'You must use proxy specified in Location to access this ' - 'resource.'), - 307: ('Temporary Redirect', - 'Object moved temporarily -- see URI list'), - - 400: ('Bad Request', - 'Bad request syntax or unsupported method'), - 401: ('Unauthorized', - 'No permission -- see authorization schemes'), - 402: ('Payment Required', - 'No payment -- see charging schemes'), - 403: ('Forbidden', - 'Request forbidden -- authorization will not help'), - 404: ('Not Found', 'Nothing matches the given URI'), - 405: ('Method Not Allowed', - 'Specified method is invalid for this resource.'), - 406: ('Not Acceptable', 'URI not available in preferred format.'), - 407: ('Proxy Authentication Required', 'You must authenticate with ' - 'this proxy before proceeding.'), - 408: ('Request Timeout', 'Request timed out; try again later.'), - 409: ('Conflict', 'Request conflict.'), - 410: ('Gone', - 'URI no longer exists and has been permanently removed.'), - 411: ('Length Required', 'Client must specify Content-Length.'), - 412: ('Precondition Failed', 'Precondition in headers is false.'), - 413: ('Request Entity Too Large', 'Entity is too large.'), - 414: ('Request-URI Too Long', 'URI is too long.'), - 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), - 416: ('Requested Range Not Satisfiable', - 'Cannot satisfy request range.'), - 417: ('Expectation Failed', - 'Expect condition could not be satisfied.'), - - 500: ('Internal Server Error', 'Server got itself in trouble'), - 501: ('Not Implemented', - 'Server does not support this operation'), - 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), - 503: ('Service Unavailable', - 'The server cannot process the request due to a high load'), - 504: ('Gateway Timeout', - 'The gateway server did not receive a timely response'), - 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), - } - - -"""Simple HTTP Server. - -This module builds on BaseHTTPServer by implementing the standard GET -and HEAD requests in a fairly straightforward manner. - -""" -class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): +def guess_type(path): + base, ext = posixpath.splitext(path) + return extensions_map.get(ext) or extensions_map.get(ext.lower()) or extensions_map[''] - """Simple HTTP request handler with GET and HEAD commands. - This serves files from the current directory and any of its - subdirectories. The MIME type for files is determined by - calling the .guess_type() method. +class ResponseGatherer(object): + """What a GET handler is given to add response headers to (a download's Content-Disposition).""" + def __init__(self): + self.headers = [] - The GET and HEAD requests are identical except that the HEAD - request omits the actual contents of the file. + def add_header(self, key, value): + self.headers.append((key, value)) - """ - server_version = "SimpleHTTP/" + __version__ +class HttpServer(object): + """Serves pathhandlers and the files under webroot. Use as `await server.start()`; `server.port` is the + port actually bound (pass port=0 to be given one).""" - def do_GET(self): - """Serve a GET request.""" - f = self.send_head() - if f: - self.push(f.read()) + def __init__(self, pathhandlers, webroot, ip='', port=8081): + self.handlers = pathhandlers + self.webroot = webroot + self.ip = ip + self.port = port + self.runner = None + + async def start(self): + app = web.Application(client_max_size=MAX_REQUEST_BYTES) + app.router.add_route('*', '/{tail:.*}', self._handle) + self.runner = web.AppRunner(app, access_log=None) + await self.runner.setup() + site = web.TCPSite(self.runner, self.ip or None, self.port, backlog=100) + await site.start() + self.port = self.runner.addresses[0][1] + print("[httpd] aiohttp running on port %s, serving from %s" % (self.port, self.webroot)) + return self + + async def close(self): + if self.runner: + await self.runner.cleanup() + + def log(self, request, status, size): + peer = request.transport.get_extra_info('peername') if request.transport else None + peer = peer or ('-', 0) + print('[httpd-%d] %s %s "%s %s HTTP/%d.%d" %s %s' % (peer[1], time.strftime('%d/%b/%Y %H:%M:%S'), peer[0], + request.method, request.raw_path, request.version.major, request.version.minor, status, size)) + + def reply(self, request, status, body=b'', headers=None): + response = web.Response(status=status, body=body, headers=headers) + self.log(request, status, len(body) if body else '-') + return response + + def error(self, request, status, message): + page = ('
https://stage.example/', body)
+ self.assertIn(b'****XYZ', body)
+ self.assertNotIn(b'abcdefghijklmnop', body)
+ with mock.patch.object(uploader, 'settings', lambda: ('https://stage.example/', 'short')):
+ body = self.get('/settings/web')[1]
+ self.assertIn(b'****', body) # too short to give any of it away
+ self.assertNotIn(b'short', body)
+ j = self.send_invoice()
+ main.uploadqueue.log.add(dict(job=j['name'], key='ACC001', kind='invoice', account='ACC001', docnum='777', added=datetime.now(), outcome='created', status=201, error=None))
+ main.uploadqueue.log.add(dict(job='job-19990101-000000', key='ACC001', kind='statement', account='ACC002', docnum='st1', added=datetime.now(), outcome='failed', status=400, error='HTTP 400 bad'))
+ body = self.get('/uploads')[1]
+ self.assertIn(b'>777 / ACC001', body) # a loaded job links to its page
+ self.assertIn(b'st1 / ACC002', body)
+ self.assertNotIn(b'job-19990101-000000&', body)
+ self.assertIn(b'HTTP 400 bad', body)
+
+ def test_documents_of_the_auto_upload_types_are_uploaded_on_arrival(self):
+ sent = []
+ async def start():
+ main.uploadqueue.transport = lambda item, base, key: (sent.append(item) or (201, '{}'))
+ main.uploadqueue.start()
+ def wait_for(n):
+ deadline = time.time() + 10
+ while len(sent) < n and time.time() < deadline:
+ time.sleep(0.05)
+ def arrive(**kw):
+ return self.send_invoice(pages=1, totals=['144.00'], net='120.00', vat='24.00', **kw)
+ main.config.set('Web', 'auto_types', 'statement, invoice')
+ self.addCleanup(main.config.set, 'Web', 'auto_types', '')
+ self.assertIn(b'invoice', self.get('/settings/web')[1].replace(b'statement,', b''))
+ with mock.patch.object(uploader, 'settings', lambda: ('https://stage.example/', 'tok')):
+ self.thread.call(start())
+ try:
+ j = arrive(doc_num='6001')
+ wait_for(1)
+ self.assertEqual(['6001'], [i['docnum'] for i in sent])
+ self.assertEqual('created', main.uploadqueue.log.for_job(j['name'])[0]['outcome'])
+ self.send_invoice(jtype='Delvnote') # not a listed kind
+ arrive(doc_num='6002', jtype='Cr-note') # a credit note: not listed either
+ time.sleep(0.5)
+ self.assertEqual(['6001'], [i['docnum'] for i in sent])
+ main.config.set('Web', 'auto_types', '')
+ arrive(doc_num='6003')
+ time.sleep(0.5)
+ self.assertEqual(['6001'], [i['docnum'] for i in sent]) # off when blank
+ finally:
+ self.thread.call(main.uploadqueue.close())
+
+ def test_the_colouring_is_not_kept_but_the_debug_page_still_shows_it(self):
+ j = self.send_invoice()
+ self.assertNotIn('colouring', j)
+ self.assertTrue(j['parsed'] and j['groupfiles']) # the PDFs are made from the parsed pages alone
+ r, body = self.get('/debug?name=%s' % j['name'])
+ self.assertEqual(200, r.status)
+ self.assertIn(b'background-color: #', body) # the fields are coloured in
+ self.assertIn(b'title="doc_num"', body)
+ d = self.send_invoice(jtype='Delvnote')
+ self.assertNotIn('colouring', d)
+ raw = self.send_invoice(jtype='Mystery') # nothing recognises it: plain PDF, no colouring
+ self.assertFalse(raw['parsed'])
+ self.assertEqual(200, self.get('/debug?name=%s' % raw['name'])[0].status)
+
+ def reload_raw(self, j):
+ """The job as it is when read back from its pickle at startup, before cleanJob."""
+ for root, dirs, files in os.walk(main.jobdir):
+ if j['name'] in files:
+ p = os.path.join(root, j['name'])
+ with open(p, 'rb') as f:
+ raw = main.load_job_pickle(f)
+ raw['name'], raw['stat'] = j['name'], main.file_stat(p)
+ return raw
+
+ def test_a_job_with_a_good_cache_entry_is_not_parsed_or_drawn_again(self):
+ j = self.send_invoice(pages=1, totals=['144.00'], net='120.00', vat='24.00')
+ main.derivedcache.dirty = True
+ main.derivedcache.flush(main.jobs, force=True)
+ cache = derived.DerivedCache(main.derivedcache.path) # as read at the next start
+ raw = self.reload_raw(j)
+ with mock.patch.object(main.mainparser, 'parse', side_effect=AssertionError('parsed')), \
+ mock.patch.object(main.formatter, 'format', side_effect=AssertionError('drawn')):
+ self.assertEqual('hit', main.cleanJob(raw, cache.lookup(raw['name'], raw['stat'])))
+ for key in ('parsed', 'groupkey', 'groupfiles', 'render_stamp', 'summary', 'doctype', 'templ', 'plain', 'autoprint'):
+ self.assertEqual(j[key], raw[key], key)
+ self.assertIn('ACC001', main.email_accounts) # the address book is still filled in from the cached pages
+
+ # a PDF that has gone is drawn again, from the cached pages
+ os.remove(main.pdfdir + next(iter(raw['groupfiles'].values())))
+ raw2 = self.reload_raw(j)
+ with mock.patch.object(main.mainparser, 'parse', side_effect=AssertionError('parsed')):
+ self.assertEqual('drawn', main.cleanJob(raw2, cache.lookup(raw2['name'], raw2['stat'])))
+ self.assertTrue(os.path.exists(main.pdfdir + next(iter(raw2['groupfiles'].values()))))
+
+ # a job file that is not the one the entry was made from is parsed again
+ raw3 = self.reload_raw(j)
+ self.assertIsNone(cache.lookup(raw3['name'], (raw3['stat'][0] + 1, raw3['stat'][1])))
+ self.assertEqual('parsed', main.cleanJob(raw3, None))
+ self.assertEqual(j['parsed'], raw3['parsed'])
+
+ def test_stationery_page_redraws_jobs_drawn_under_older_stationery(self):
+ j = self.send_invoice(pages=1, totals=['144.00'], net='120.00', vat='24.00')
+ self.assertEqual(main.derivedcache.render_stamp, j['render_stamp'])
+ self.assertIn(b'were drawn under today', self.get('/settings/stationery')[1])
+ old = config_terms = main.config.get('Printing', 'terms')
+ main.config.set('Printing', 'terms', old + ' (changed)')
+ self.addCleanup(main.config.set, 'Printing', 'terms', old)
+ main.derivedcache.render_stamp = derived.render_stamp() # what the next start would see
+ self.addCleanup(setattr, main.derivedcache, 'render_stamp', derived.render_stamp())
+ body = self.get('/settings/stationery')[1]
+ self.assertIn(b'were drawn under older stationery', body)
+ self.assertIn(b'Draw them again', body)
+ self.assertIn(b'href="/settings/stationery"', self.get('/home')[1])
+ pdf = main.pdfdir + next(iter(j['groupfiles'].values()))
+ before = os.path.getmtime(pdf)
+ time.sleep(0.05)
+ r, data = self.post('/settings/stationery') # no button: nothing happens
+ self.assertEqual(303, r.status)
+ self.assertEqual(before, os.path.getmtime(pdf))
+ r, data = self.post('/settings/stationery', regenerate='1')
+ self.assertEqual(303, r.status)
+ self.assertRegex(r.getheader('Location'), r'redrawn=\d+')
+ self.assertGreater(os.path.getmtime(pdf), before)
+ self.assertEqual(main.derivedcache.render_stamp, j['render_stamp'])
+ body = self.get(r.getheader('Location'))[1]
+ self.assertIn(b'again.', body)
+ self.assertIn(b'were drawn under today', body)
+ self.assertTrue(main.derivedcache.dirty) # the new stamps are written at the next flush
+
+ def drop_in(self, jtype, offset, **kw):
+ """Write a job pickle into the job directory as another instance's copy would be: a name dated `offset` from
+ now, and the file back-dated so that it has settled. Returns its path and name."""
+ from datetime import timedelta
+ ts = datetime.utcnow() + offset
+ name = 'job-%s' % ts.strftime('%Y%m%d-%H%M%S')
+ raw = {'queue': 'RAW', 'from': 'x', 'to': 'y', 'control': {'H': 'other', 'P': 'u', 'J': jtype}, 'data': make_invoice(**kw), 'ts': ts, 'name': name}
+ month = os.path.join(main.jobdir, ts.strftime('%Y%m'))
+ os.makedirs(month, exist_ok=True)
+ path = os.path.join(month, name)
+ with open(path, 'wb') as f:
+ pickle.dump(raw, f, protocol=2)
+ os.utime(path, (time.time() - 60, time.time() - 60))
+ return path, name
+
+ def scan(self):
+ async def run():
+ return main.scan_for_jobs()
+ return self.thread.call(run())
+
+ def test_job_files_that_appear_in_the_directory_are_taken_in_like_new_arrivals(self):
+ from datetime import timedelta
+ time.sleep(main.SETTLING + 0.1) # let what earlier tests wrote settle
+ self.scan() # files that earlier tests left on disk, not in the history
+ self.send_invoice()
+ self.assertEqual([], self.scan()) # what arrived over LPD is not found again
+ main.config.set('Web', 'auto_types', 'invoice')
+ self.addCleanup(main.config.set, 'Web', 'auto_types', '')
+ sent = []
+ async def start():
+ main.uploadqueue.transport = lambda item, base, key: (sent.append(item) or (201, '{}'))
+ main.uploadqueue.start()
+ with mock.patch.object(uploader, 'settings', lambda: ('https://stage.example/', 'tok')):
+ self.thread.call(start())
+ try:
+ printed_before = self.printed.call_count
+ _, delnote = self.drop_in('Delvnote', timedelta(hours=1))
+ _, invoice = self.drop_in('Invoice', timedelta(hours=1, seconds=5), doc_num='7001', pages=1, totals=['144.00'], net='120.00', vat='24.00')
+ found = self.scan()
+ self.assertEqual([delnote, invoice], [j['name'] for j in found]) # oldest first
+ self.assertEqual([invoice, delnote], [j['name'] for j in main.jobs[:2]]) # in the history by name, newest first
+ self.assertGreater(self.printed.call_count, printed_before) # the delivery note was auto-printed
+ self.assertTrue(self.printed.call_args[0][0].endswith('-accounts.pdf'))
+ deadline = time.time() + 10
+ while not sent and time.time() < deadline:
+ time.sleep(0.05)
+ self.assertEqual(['7001'], [i['docnum'] for i in sent]) # and the invoice was uploaded
+ self.assertEqual('' % invoice, '' % main.jobs[0]['name'])
+ # only once
+ printed = self.printed.call_count
+ self.assertEqual([], self.scan())
+ self.assertEqual(printed, self.printed.call_count)
+ self.assertTrue(main.derivedcache.dirty)
+ finally:
+ self.thread.call(main.uploadqueue.close())
+
+ def test_a_file_still_being_copied_or_unreadable_is_left_until_it_is_complete(self):
+ from datetime import timedelta
+ path, name = self.drop_in('Delvnote', timedelta(hours=2))
+ now = time.time()
+ os.utime(path, (now, now)) # written this moment: may be half copied
+ self.assertEqual([], self.scan())
+ os.utime(path, (now - 60, now - 60))
+ self.assertEqual([name], [j['name'] for j in self.scan()])
+
+ path, name = self.drop_in('Delvnote', timedelta(hours=3))
+ whole = open(path, 'rb').read()
+ with open(path, 'wb') as f:
+ f.write(whole[:50]) # cut off
+ os.utime(path, (now - 60, now - 60))
+ self.assertEqual([], self.scan())
+ self.assertEqual([], self.scan()) # not tried again at the same size
+ with open(path, 'wb') as f:
+ f.write(whole)
+ os.utime(path, (now - 60, now - 60))
+ self.assertEqual([name], [j['name'] for j in self.scan()])
+
+ def test_a_file_older_than_a_full_history_is_ignored(self):
+ from datetime import timedelta
+ self.send_invoice()
+ old_qty = main.loadQty
+ main.loadQty = len(main.jobs)
+ self.addCleanup(setattr, main, 'loadQty', old_qty)
+ printed = self.printed.call_count
+ _, name = self.drop_in('Delvnote', -timedelta(days=3650))
+ self.assertEqual([], self.scan())
+ self.assertNotIn(name, [j['name'] for j in main.jobs])
+ self.assertEqual(printed, self.printed.call_count) # nothing printed for a file that old
+
def test_print_history_is_listed_on_the_job_page(self):
j = self.send_invoice()
self.assertNotIn(b'Printed from this job', self.get('/pdf?name=%s&key=ACC001' % j['name'])[1])
diff --git a/test_servers.py b/test_servers.py
new file mode 100644
index 0000000..b3c602e
--- /dev/null
+++ b/test_servers.py
@@ -0,0 +1,250 @@
+# The LPD receiver and the web server on their own, without main.py: protocol behaviour that the end to end
+# tests in test_integration.py take for granted.
+import asyncio
+import http.client
+import os
+import socket
+import tempfile
+import threading
+import unittest
+
+from httpserver import HttpServer, Redirect
+from lpdserver import LpdServer
+
+
+class LoopThread(object):
+ def __init__(self):
+ self.loop = asyncio.new_event_loop()
+ self.thread = threading.Thread(target=lambda: (asyncio.set_event_loop(self.loop), self.loop.run_forever()), daemon=True)
+ self.thread.start()
+
+ def call(self, coro):
+ return asyncio.run_coroutine_threadsafe(coro, self.loop).result(10)
+
+ def stop(self):
+ self.loop.call_soon_threadsafe(self.loop.stop)
+ self.thread.join()
+ self.loop.close()
+
+
+class TestLpd(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.loop = LoopThread()
+ cls.received = []
+ cls.controller_fails = False
+
+ def controller(queue, peer, local, control, data):
+ if cls.controller_fails:
+ raise RuntimeError('boom')
+ cls.received.append((queue, control, data))
+ cls.server = cls.loop.call(LpdServer(controller, ip='127.0.0.1', port=0).start())
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.loop.call(cls.server.close())
+ cls.loop.stop()
+
+ def setUp(self):
+ del self.received[:]
+ type(self).controller_fails = False
+
+ def connect(self):
+ s = socket.create_connection(('127.0.0.1', self.server.port), timeout=5)
+ self.addCleanup(s.close)
+ return s
+
+ def ack(self, s):
+ self.assertEqual(b'\x00', s.recv(1), 'no ack')
+
+ def to_data_file(self, s, queue=b'q', control=b'Hhost\nPuser\n', size=None, size_of=None):
+ s.sendall(b'\x02' + queue + b'\n'); self.ack(s)
+ s.sendall(b'\x02%d cfA001host\n' % len(control)); self.ack(s)
+ s.sendall(control + b'\x00'); self.ack(s)
+
+ def wait_for(self, n):
+ for _ in range(100):
+ if len(self.received) >= n:
+ return
+ threading.Event().wait(0.02)
+ self.fail('job not received')
+
+ def test_well_formed_job_keeps_its_trailing_null(self):
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 6); self.ack(s)
+ s.sendall(b'hello\n\x00'); self.ack(s)
+ self.assertEqual(b'', s.recv(1)) # the server closes after the data file
+ self.wait_for(1)
+ self.assertEqual([('q', {'H': 'host', 'P': 'user'}, 'hello\n\x00')], self.received)
+
+ def test_sender_that_closes_to_mark_the_end(self):
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 0x7fffffff); self.ack(s)
+ s.sendall(b'caf\xe9 \x0c\n')
+ s.shutdown(socket.SHUT_WR)
+ self.assertEqual(b'\x00', s.recv(1))
+ self.wait_for(1)
+ self.assertEqual('caf\xe9 \x0c\n', self.received[0][2]) # one byte, one character
+
+ def test_sender_that_vanishes_after_the_data_still_gets_its_job_kept(self):
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 0x7fffffff); self.ack(s)
+ s.sendall(b'abc')
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b'\x01\x00\x00\x00\x00\x00\x00\x00') # RST on close
+ s.close()
+ self.wait_for(1)
+ self.assertEqual('abc', self.received[0][2])
+
+ def test_a_job_cut_off_before_its_data_is_dropped(self):
+ s = self.connect()
+ self.to_data_file(s)
+ s.close()
+ threading.Event().wait(0.3)
+ self.assertEqual([], self.received)
+
+ def test_a_failing_controller_does_not_stop_the_server(self):
+ type(self).controller_fails = True
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 1); self.ack(s)
+ s.sendall(b'x\x00'); self.ack(s)
+ self.assertEqual(b'', s.recv(1))
+ type(self).controller_fails = False
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 1); self.ack(s)
+ s.sendall(b'y\x00'); self.ack(s)
+ self.wait_for(1)
+ self.assertEqual('y\x00', self.received[0][2])
+
+ def test_unknown_commands_are_ignored(self):
+ s = self.connect()
+ s.sendall(b'\x09nonsense\n') # not acknowledged, and not fatal
+ self.to_data_file(s)
+ s.sendall(b'\x07what\n') # an unknown subcommand between files
+ s.sendall(b'\x03%d dfA001host\n' % 1); self.ack(s)
+ s.sendall(b'z\x00'); self.ack(s)
+ self.wait_for(1)
+
+ def test_two_senders_at_once(self):
+ a, b = self.connect(), self.connect()
+ self.to_data_file(a, queue=b'A')
+ self.to_data_file(b, queue=b'B')
+ for s, text in ((b, b'bb\x00'), (a, b'aa\x00')):
+ s.sendall(b'\x03%d dfA001host\n' % 2); self.ack(s)
+ s.sendall(text); self.ack(s)
+ self.wait_for(2)
+ self.assertEqual({('A', 'aa\x00'), ('B', 'bb\x00')}, {(q, d) for q, c, d in self.received})
+
+
+class TestHttp(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.webroot = tempfile.mkdtemp(prefix='printerface-web-')
+ cls.addClassCleanup(lambda: __import__('shutil').rmtree(cls.webroot, ignore_errors=True))
+ os.makedirs(os.path.join(cls.webroot, 'css'))
+ os.makedirs(os.path.join(cls.webroot, 'withindex'))
+ with open(os.path.join(cls.webroot, 'css', 'x.css'), 'wb') as f:
+ f.write(b'body { color: red }\n')
+ with open(os.path.join(cls.webroot, 'withindex', 'index.html'), 'wb') as f:
+ f.write(b'index
')
+ with open(os.path.join(os.path.dirname(cls.webroot), 'outside.txt'), 'wb') as f:
+ f.write(b'secret')
+ cls.addClassCleanup(lambda: os.remove(os.path.join(os.path.dirname(cls.webroot), 'outside.txt')))
+ cls.seen = {}
+
+ def echo(query_string=None, resp=None, postreq=None):
+ cls.seen = dict(query=query_string, post=postreq)
+ if postreq is not None:
+ return Redirect('/echo?done=1')
+ resp.add_header('X-Extra', 'yes')
+ return ('caf\xe9 %s' % query_string, 'text/plain')
+
+ def broken(query_string=None, resp=None, postreq=None):
+ raise RuntimeError('boom')
+
+ def blob(query_string=None, resp=None):
+ import io
+ return (io.BytesIO(b'%PDF-1.4 data'), 'application/pdf')
+
+ cls.loop = LoopThread()
+ cls.server = cls.loop.call(HttpServer({'/echo': echo, '/broken': broken, '/blob': blob}, cls.webroot, ip='127.0.0.1', port=0).start())
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.loop.call(cls.server.close())
+ cls.loop.stop()
+
+ def request(self, method, path, body=None, headers=None):
+ conn = http.client.HTTPConnection('127.0.0.1', self.server.port, timeout=5)
+ conn.request(method, path, body=body, headers=headers or {})
+ r = conn.getresponse()
+ data = r.read()
+ conn.close()
+ return r, data
+
+ def test_handler_get_with_query_string_and_extra_header(self):
+ r, body = self.request('GET', '/echo?a=1&a=2&b=x%20y&empty=')
+ self.assertEqual(200, r.status)
+ self.assertEqual({'a': ['1', '2'], 'b': ['x y']}, self.seen['query']) # blank values are dropped, as before
+ self.assertEqual('yes', r.getheader('X-Extra'))
+ self.assertEqual('text/plain; charset=utf-8', r.getheader('Content-Type'))
+ self.assertEqual('caf\xe9', body.decode().split()[0])
+ self.assertEqual(str(len(body)), r.getheader('Content-Length'))
+
+ def test_head_has_the_headers_but_no_body(self):
+ r, body = self.request('HEAD', '/echo')
+ self.assertEqual((200, b''), (r.status, body))
+ self.assertTrue(int(r.getheader('Content-Length')) > 0)
+
+ def test_post_form_fields_and_redirect(self):
+ r, body = self.request('POST', '/echo?from=url', 'name=a+b&name=c&empty=',
+ {'Content-Type': 'application/x-www-form-urlencoded'})
+ self.assertEqual(303, r.status)
+ self.assertEqual('/echo?done=1', r.getheader('Location'))
+ self.assertEqual({'name': ['a b', 'c'], 'empty': ['']}, self.seen['post'])
+ self.assertEqual({'from': ['url']}, self.seen['query'])
+
+ def test_file_object_bodies(self):
+ r, body = self.request('GET', '/blob')
+ self.assertEqual((200, b'%PDF-1.4 data', 'application/pdf'), (r.status, body, r.getheader('Content-Type')))
+
+ def test_a_failing_handler_is_a_500_and_the_server_carries_on(self):
+ self.assertEqual(500, self.request('GET', '/broken')[0].status)
+ self.assertEqual(500, self.request('POST', '/broken', 'a=1')[0].status)
+ self.assertEqual(200, self.request('GET', '/echo')[0].status)
+
+ def test_unknown_paths_and_methods(self):
+ self.assertEqual(404, self.request('GET', '/nothing')[0].status)
+ self.assertEqual(404, self.request('POST', '/nothing', 'a=1')[0].status)
+ self.assertEqual(501, self.request('DELETE', '/echo')[0].status)
+
+ def test_static_files(self):
+ r, body = self.request('GET', '/css/x.css')
+ self.assertEqual((200, b'body { color: red }\n', 'text/css'), (r.status, body, r.getheader('Content-Type')))
+ self.assertIsNotNone(r.getheader('Last-Modified'))
+ self.assertEqual(b'index
', self.request('GET', '/withindex/')[1])
+ r, _ = self.request('GET', '/withindex')
+ self.assertEqual((301, '/withindex/'), (r.status, r.getheader('Location')))
+ self.assertEqual(404, self.request('GET', '/css/')[0].status) # no directory listings
+
+ def test_static_files_cannot_leave_the_web_root(self):
+ for path in ('/../outside.txt', '/css/../../outside.txt', '/%2e%2e/outside.txt', '/..%2foutside.txt'):
+ r, body = self.request('GET', path)
+ self.assertNotEqual(b'secret', body, path)
+
+ def test_keep_alive_serves_several_requests_on_one_connection(self):
+ conn = http.client.HTTPConnection('127.0.0.1', self.server.port, timeout=5)
+ for _ in range(3):
+ conn.request('GET', '/echo')
+ r = conn.getresponse()
+ r.read()
+ self.assertEqual(200, r.status)
+ conn.close()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/test_uploader.py b/test_uploader.py
new file mode 100644
index 0000000..ad367a7
--- /dev/null
+++ b/test_uploader.py
@@ -0,0 +1,158 @@
+# The website upload queue: the wire format against a throwaway local server, retry behaviour, and the record kept.
+import asyncio
+import email
+import http.server
+import json
+import tempfile
+import threading
+import unittest
+from unittest import mock
+
+import uploader
+from uploader import WebUploader, UploadLog
+
+
+def item(docnum='100', kind='invoice'):
+ return dict(job='job-20261102-090507', key='ACC1', kind=kind, account='ACC1', docnum=docnum, payload=json.dumps({'docnum': docnum}), pdf=b'%PDF-1.4 x')
+
+
+class FakeSite(http.server.BaseHTTPRequestHandler):
+ replies = [] # (status, body) taken in turn; the last one repeats
+ seen = []
+
+ def do_POST(self):
+ body = self.rfile.read(int(self.headers['Content-Length']))
+ FakeSite.seen.append((self.path, self.headers['Authorization'], self.headers['Content-Type'], body))
+ status, text = FakeSite.replies[min(len(FakeSite.seen), len(FakeSite.replies)) - 1]
+ self.send_response(status)
+ self.send_header('Content-Type', 'application/json')
+ self.end_headers()
+ self.wfile.write(text.encode())
+
+ def log_message(self, *a):
+ pass
+
+
+class TestWire(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.httpd = http.server.HTTPServer(('127.0.0.1', 0), FakeSite)
+ threading.Thread(target=cls.httpd.serve_forever, daemon=True).start()
+ cls.url = 'http://127.0.0.1:%d/' % cls.httpd.server_port
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.httpd.shutdown()
+ cls.httpd.server_close()
+
+ def setUp(self):
+ FakeSite.replies, FakeSite.seen = [(201, '{}')], []
+ self.log = UploadLog(None, limit=5)
+ patch = mock.patch.object(uploader, 'settings', lambda: (self.url, 'secret'))
+ patch.start()
+ self.addCleanup(patch.stop)
+ patch = mock.patch.object(uploader, 'RETRY_DELAYS', (0.01, 0.01))
+ patch.start()
+ self.addCleanup(patch.stop)
+
+ def run_queue(self, *items):
+ async def go():
+ up = WebUploader(log=self.log)
+ up.start()
+ for i in items:
+ up.append(i)
+ await up.close(10)
+ asyncio.run(go())
+
+ def test_request_is_a_multipart_post_with_the_token(self):
+ self.run_queue(item('100'), item('7', 'statement'))
+ (path, auth, ctype, body), (spath, _, _, _) = FakeSite.seen
+ self.assertEqual(('/api/ingest/invoice/', 'Token secret', '/api/ingest/statement/'), (path, auth, spath))
+ msg = email.message_from_bytes(b'Content-Type: ' + ctype.encode() + b'\r\n\r\n' + body)
+ parts = {p.get_param('name', header='content-disposition'): p for p in msg.get_payload()}
+ self.assertEqual({'docnum': '100'}, json.loads(parts['payload'].get_payload(decode=True)))
+ self.assertEqual(b'%PDF-1.4 x', parts['pdf'].get_payload(decode=True))
+
+ def test_created_and_replaced_are_recorded(self):
+ FakeSite.replies = [(201, '{}'), (200, '{}')]
+ self.run_queue(item('1'), item('1'))
+ self.assertEqual(['replaced', 'created'], [r['outcome'] for r in self.log.records]) # newest first
+ self.assertEqual([None, None], [r['error'] for r in self.log.records])
+
+ def test_a_refusal_is_final_and_says_why(self):
+ FakeSite.replies = [(400, '{"date": ["bad"]}')]
+ self.run_queue(item())
+ (rec,) = self.log.records
+ self.assertEqual(('failed', 400), (rec['outcome'], rec['status']))
+ self.assertIn('bad', rec['error'])
+ self.assertEqual(1, len(FakeSite.seen)) # not retried
+ self.assertNotIn('secret', repr(rec))
+
+ def test_a_server_error_is_retried_then_succeeds(self):
+ FakeSite.replies = [(503, ''), (500, ''), (201, '{}')]
+ self.run_queue(item())
+ self.assertEqual(3, len(FakeSite.seen))
+ self.assertEqual('created', self.log.records[0]['outcome'])
+
+ def test_gives_up_after_the_last_retry(self):
+ FakeSite.replies = [(502, '')]
+ self.run_queue(item())
+ self.assertEqual(3, len(FakeSite.seen))
+ self.assertEqual(('failed', 502), (self.log.records[0]['outcome'], self.log.records[0]['status']))
+ self.assertNotIn('', self.log.records[0]['error'])
+
+ def test_an_unreachable_site_is_retried_and_reported(self):
+ with mock.patch.object(uploader, 'settings', lambda: ('http://127.0.0.1:1/', 'secret')):
+ self.run_queue(item())
+ (rec,) = self.log.records
+ self.assertEqual('failed', rec['outcome'])
+ self.assertIn('could not reach', rec['error'])
+
+ def test_the_next_document_goes_after_a_failure(self):
+ FakeSite.replies = [(400, '{}'), (201, '{}')]
+ self.run_queue(item('1'), item('2'))
+ self.assertEqual(['created', 'failed'], [r['outcome'] for r in self.log.records])
+
+
+class TestSettings(unittest.TestCase):
+ def test_off_by_default(self):
+ self.assertFalse(uploader.enabled())
+
+ def test_needs_both_settings(self):
+ with mock.patch.object(uploader, 'settings', lambda: ('https://x/', '')):
+ self.assertFalse(uploader.enabled())
+ with mock.patch.object(uploader, 'settings', lambda: ('https://x/', 'k')):
+ self.assertTrue(uploader.enabled())
+
+
+class TestLog(unittest.TestCase):
+ def test_print_history_has_its_own_setting_too(self):
+ import printing
+ from settings import config
+ self.assertEqual(200, printing.PrintLog(None).limit) # the default
+ config.set('Printing', 'result_count', '3')
+ self.addCleanup(config.set, 'Printing', 'result_count', '200')
+ self.assertEqual(3, printing.PrintLog(None).limit)
+
+ def test_capped_by_the_web_setting_not_the_gmail_one(self):
+ from settings import config
+ config.set('Web', 'result_count', '2')
+ self.addCleanup(config.set, 'Web', 'result_count', '120')
+ log = UploadLog(None)
+ for n in range(5):
+ log.add(dict(job='j%d' % n, error=None))
+ self.assertEqual(['j4', 'j3'], [r['job'] for r in log.records])
+
+ def test_persisted_and_capped(self):
+ with tempfile.TemporaryDirectory() as d:
+ log = UploadLog(d + '/upload.pickle', limit=2)
+ for n in range(3):
+ log.add(dict(job='j%d' % n, error=None))
+ log.flush()
+ again = UploadLog(d + '/upload.pickle', limit=2)
+ self.assertEqual(['j2', 'j1'], [r['job'] for r in again.records])
+ self.assertEqual(['j2'], [r['job'] for r in again.for_job('j2')])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/test_webupload.py b/test_webupload.py
new file mode 100644
index 0000000..1ac12b5
--- /dev/null
+++ b/test_webupload.py
@@ -0,0 +1,158 @@
+# The document layer for the website upload: what a job becomes on the wire. The corpus test runs only when
+# WEBUPLOAD_CORPUS points at a directory laid out like ~/printerface (data/pickle/YYYYMM/job-*); it checks every
+# stored invoice, credit note and statement.
+import datetime
+import glob
+import io
+import os
+import unittest
+from decimal import Decimal
+
+import webupload
+from webupload import UploadError
+
+
+def page(doc_num='100', lines=(), totals=('120.00', '24.00', '144.00'), date='02/11/26', accno='ACC1', summ=('1', '120.00', '20.00', '24.00')):
+ col = lambda key: '\n'.join(l[key] for l in lines) + '\n' * 3
+ p = dict(accno=accno, doc_num=doc_num, date=date, custref='PO9', ourref='555', salesperson='SAM',
+ addr_invoice='A WINE BAR\n1 HIGH ST\nTOWN\n\n', tot_net=totals[0], tot_vat=totals[1], tot_due=totals[2],
+ summ_code='%s\n\n' % summ[0], summ_netamt='%s\n\n' % summ[1], summ_rate='%s\n\n' % summ[2], summ_vat='%s\n\n' % summ[3])
+ for key in webupload.LINE_FIELDS:
+ p[key] = col(key)
+ return p
+
+
+def line(code='', desc='', qty='', price='', unit='', net='', vat=''):
+ return dict(prod_code=code, prod_desc=desc, prod_qty=qty, prod_price=price, prod_unit=unit, prod_net=net, prod_vcode=vat)
+
+
+def job(templ, parsed, name='job-20261102-090507'):
+ return dict(name=name, templ=templ, ts=datetime.datetime(2026, 11, 2, 9, 5, 7), parsed=parsed)
+
+
+class TestHelpers(unittest.TestCase):
+ def test_amount(self):
+ self.assertEqual('1234.50', webupload.amount(' 1,234.50 '))
+ self.assertEqual('-12.00', webupload.amount('12.00CR'))
+ self.assertEqual('-12.00', webupload.amount('-12.00'))
+ self.assertIsNone(webupload.amount(' '))
+ self.assertRaises(UploadError, webupload.amount, '12.0.0')
+
+ def test_dates(self):
+ self.assertEqual('2026-11-02', webupload.iso_date('02/11/26'))
+ self.assertRaises(UploadError, webupload.iso_date, '2026-11-02')
+ self.assertEqual('2026-11-02T09:05:07Z', webupload.received(dict(ts=datetime.datetime(2026, 11, 2, 9, 5, 7))))
+ bst = datetime.timezone(datetime.timedelta(hours=1))
+ self.assertEqual('2026-07-02T08:05:07Z', webupload.received(dict(ts=datetime.datetime(2026, 7, 2, 9, 5, 7, tzinfo=bst))))
+
+
+class TestInvoices(unittest.TestCase):
+ LINES = [line('BOR00101', 'Bordeaux 2015', '12', '10.00', 'BOTT', '120.00', '1')]
+
+ def test_invoice(self):
+ (doc,) = webupload.documents(job('invoice', {'ACC1': [page(lines=self.LINES)]}))
+ p = doc.payload
+ self.assertEqual(('invoice', 'ACC1', '100', [0]), (doc.kind, doc.account, doc.docnum, doc.pages))
+ self.assertEqual(('2026-11-02', False, 'PO9', '555', '120.00', '24.00', '144.00'),
+ (p['date'], p['is_credit_note'], p['cust_ref'], p['our_ref'], p['total_net'], p['total_vat'], p['total_gross']))
+ self.assertEqual(dict(acc='ACC1', name='A WINE BAR, 1 HIGH ST, TOWN', salesperson='SAM'), p['account'])
+ self.assertEqual([dict(product_code='BOR00101', description='Bordeaux 2015', quantity='12', unit='BOTT', unit_price='10.00',
+ net='120.00', vat_code='1', vat_rate='20.00')], p['lines'])
+ self.assertEqual([dict(vat_code='1', net='120.00', rate='20.00', vat='24.00')], p['vat_summary'])
+ self.assertEqual(('job-20261102-090507', '2026-11-02T09:05:07Z'), (p['job_name'], p['printed_at']))
+
+ def test_text_rows_are_not_lines_and_credit_notes_keep_their_references(self):
+ lines = [line('B0321001', 'BAUCHET Rose', '3', '21.53', 'BOTT', '64.59', '5'), line(desc='RE: KIR105 REF: 1452')]
+ (doc,) = webupload.documents(job('crednote', {'ACC1': [page('21636', lines, ('64.59', '0.00', '64.59'))]}))
+ self.assertTrue(doc.payload['is_credit_note'])
+ self.assertEqual(1, len(doc.payload['lines']))
+ self.assertEqual('RE: KIR105 REF: 1452', doc.payload['credit_refs'])
+ (inv,) = webupload.documents(job('invoice', {'ACC1': [page(lines=lines)]}))
+ self.assertEqual('', inv.payload['credit_refs'])
+
+ def test_a_document_over_several_pages_takes_its_totals_from_the_last(self):
+ first = page('7', [line('BOR00101', 'a', '1', '5.00', 'BOTT', '5.00', '1')], ('', '', ''))
+ second = page('7', [line('BOR00102', 'b', '2', '5.00', 'BOTT', '10.00', '1')], ('15.00', '3.00', '18.00'))
+ other = page('8', self.LINES)
+ (a, b) = webupload.documents(job('invoice', {'ACC1': [first, second, other]}))
+ self.assertEqual(([0, 1], '18.00', ['BOR00101', 'BOR00102']), (a.pages, a.payload['total_gross'], [l['product_code'] for l in a.payload['lines']]))
+ self.assertEqual(([2], '7' != '8'), (b.pages, True))
+
+ def test_missing_totals_are_an_error(self):
+ self.assertRaises(UploadError, webupload.documents, job('invoice', {'ACC1': [page(totals=('', '', ''))]}))
+
+ def test_other_types_are_not_uploaded(self):
+ self.assertEqual([], webupload.documents(job('delnote', {'ACC1': [page()]})))
+
+
+class TestStatements(unittest.TestCase):
+ def stmt(self, **ages):
+ p = dict(accno='ACC1', date='30/10/26', addr_invoice='A WINE BAR\n', age_curr='10.00', age_1m='5.00CR', age_2m='0.00', age_3m='', age_due='5.00')
+ p.update(ages)
+ return p
+
+ def test_statement(self):
+ (doc,) = webupload.documents(job('statement', {'ACC1': [self.stmt(age_3m='1.00')]}))
+ p = doc.payload
+ self.assertEqual('261102-090507-ACC1', p['docnum'])
+ self.assertEqual(('10.00', '-5.00', '0.00', '1.00', '5.00'), (p['amt_current'], p['amt_1month'], p['amt_2month'], p['amt_3month'], p['amt_due']))
+
+ def test_details_are_on_the_last_page(self):
+ blank = self.stmt(age_curr='', age_1m='', age_2m='', age_3m='', age_due='')
+ (doc,) = webupload.documents(job('statement', {'ACC1': [blank, self.stmt(age_3m='0.00')]}))
+ self.assertEqual(([0, 1], '5.00'), (doc.pages, doc.payload['amt_due']))
+
+ def test_incomplete_statement_is_an_error(self):
+ self.assertRaises(UploadError, webupload.documents, job('statement', {'ACC1': [self.stmt(age_due='')]}))
+
+
+class TestSplitPdf(unittest.TestCase):
+ def test_split(self):
+ from pypdf import PdfReader
+ from reportlab.pdfgen import canvas
+ buf = io.BytesIO()
+ c = canvas.Canvas(buf)
+ for n in range(3):
+ c.drawString(100, 100, 'page %d' % n)
+ c.showPage()
+ c.save()
+ out = PdfReader(io.BytesIO(webupload.split_pdf(buf.getvalue(), [2, 0])))
+ self.assertEqual(['page 2', 'page 0'], [p.extract_text().strip() for p in out.pages])
+ self.assertRaises(UploadError, webupload.split_pdf, buf.getvalue(), [3])
+
+
+@unittest.skipUnless(os.environ.get('WEBUPLOAD_CORPUS'), 'set WEBUPLOAD_CORPUS to a directory like ~/printerface')
+class TestCorpus(unittest.TestCase):
+ def test_every_document_adds_up(self):
+ import main
+ from docparser import DocParser
+ from textutil import load_job_pickle
+ seen, rejected = 0, []
+ for f in sorted(glob.glob(os.path.join(os.environ['WEBUPLOAD_CORPUS'], 'data/pickle/*/job-*'))):
+ with open(f, 'rb') as fh:
+ j = load_job_pickle(fh)
+ doctype = (j.get('control') or {}).get('J', '').strip()
+ if main.identify(dict(doctype=doctype)) not in ('invoice', 'crednote', 'statement'):
+ continue
+ j['doctype'], j['plain'] = doctype, main.control_char_re.sub(' ', j['data'])
+ j['templ'] = main.identify(j)
+ j['parsed'] = DocParser().parse(j)[1] or {}
+ try:
+ docs = webupload.documents(j)
+ except UploadError as e:
+ rejected.append('%s: %s' % (j['name'], e)) # the empty test documents sent while developing
+ continue
+ for doc in docs:
+ seen += 1
+ p = doc.payload
+ if doc.kind == 'invoice':
+ net = sum(Decimal(l['net']) for l in p['lines'])
+ self.assertEqual(Decimal(p['total_net']), net, '%s %s' % (j['name'], doc.docnum))
+ self.assertEqual(Decimal(p['total_gross']), Decimal(p['total_net']) + Decimal(p['total_vat']), '%s %s' % (j['name'], doc.docnum))
+ self.assertEqual(Decimal(p['total_vat']), sum(Decimal(v['vat']) for v in p['vat_summary']), '%s %s' % (j['name'], doc.docnum))
+ self.assertTrue(seen)
+ self.assertTrue(all('ACC001' in r or '12345' in r for r in rejected), rejected)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/replay_corpus.py b/tools/replay_corpus.py
index fa266cd..f9bb94a 100755
--- a/tools/replay_corpus.py
+++ b/tools/replay_corpus.py
@@ -8,7 +8,7 @@
side is a recording callback rather than main.saveJob.
"""
import argparse
-import asyncore
+import asyncio
import os
import sys
import threading
@@ -23,13 +23,12 @@
args = ap.parse_args()
received = []
-server = LpdServer(lambda queue, local, remote, control, data: received.append((queue, control, data)), ip='127.0.0.1', port=0)
-port = server.socket.getsockname()[1]
-running = True
-def loop():
- while running:
- asyncore.loop(timeout=0.02, count=1)
-threading.Thread(target=loop, daemon=True).start()
+loop = asyncio.new_event_loop()
+threading.Thread(target=lambda: (asyncio.set_event_loop(loop), loop.run_forever()), daemon=True).start()
+server = asyncio.run_coroutine_threadsafe(
+ LpdServer(lambda queue, local, remote, control, data: received.append((queue, control, data)), ip='127.0.0.1', port=0).start(),
+ loop).result(10)
+port = server.port
import socket
def send(queue, control, data, eof_by_close=False):
@@ -86,6 +85,5 @@ def ack():
if rdata != j['data'] or rcontrol != j['control'] or queue != j.get('queue', 'RAW'):
bad += 1; print('MISMATCH', name, len(rdata), len(j['data']), rcontrol == j['control'])
-running = False
print('replayed=%d (%.1f MiB): sized transfers=%d, eof-by-close transfers=%d, mismatches=%d' % (sent, sizes / 1048576.0, nul_terminated, sent - nul_terminated, bad))
sys.exit(1 if bad else 0)
diff --git a/uploader.py b/uploader.py
new file mode 100644
index 0000000..b8c104d
--- /dev/null
+++ b/uploader.py
@@ -0,0 +1,165 @@
+#
+# Pushes invoices, credit notes and statements to the website as they are printed. A queue worked by the event
+# loop, like the mailer, with the blocking HTTP call in a worker thread. Each document is a multipart POST: a
+# JSON `payload` part (see webupload.py) and its own `pdf`. The website replaces a document it already has, so
+# sending one twice is harmless, and a failed one can simply be sent again.
+#
+# The outcome of the last `result_count` uploads is kept (newest first) in upload.pickle, flushed from the main loop.
+
+import asyncio
+import datetime
+import json
+import os
+import traceback
+import urllib.error
+import urllib.request
+import uuid
+
+import printing
+import webupload
+from settings import config, HOME
+
+pickle_file = os.path.join(HOME, 'upload.pickle')
+
+# a network failure or a 5xx is tried again after each of these delays (seconds); anything else is final
+RETRY_DELAYS = (5, 30)
+TIMEOUT = 30
+
+
+class UploadLog(printing.PrintLog):
+ """What was uploaded, newest first, one record per document: the job and key it came from, what the website
+ did with it and any error. Kept in a side pickle, like the printed history, and capped at [Web] result_count,
+ which is set independently of the email and print histories."""
+
+ def __init__(self, path=None, limit=None):
+ super().__init__(path, limit if limit is not None else config.getint('Web', 'result_count'))
+
+
+def settings():
+ """(base_url, api_key); both blank when the feature is off."""
+ return (config.get('Web', 'base_url', fallback='').strip(), config.get('Web', 'api_key', fallback='').strip())
+
+
+def mask_key(key):
+ """'****abc' for a page that shows which key is configured without showing it. A key too short to give three
+ characters away safely is only stars."""
+ if not key:
+ return ''
+ return '****' + key[-3:] if len(key) >= 12 else '****'
+
+
+def auto_types():
+ """The kinds of document ([Web] auto_types: invoice, crednote, statement) uploaded as soon as they arrive."""
+ return [t.strip() for t in config.get('Web', 'auto_types', fallback='').split(',') if t.strip()]
+
+
+def enabled():
+ return all(settings())
+
+
+def prepare(job, key, pdfdir):
+ """The uploads for a job page's key (an account, or 'accounts' for all of them), ready to queue. The PDF is cut
+ into one per document. Raises webupload.UploadError for a job that can't be converted."""
+ items = []
+ for doc in webupload.documents(job):
+ if key != 'accounts' and doc.account != key:
+ continue
+ with open(os.path.join(pdfdir, job['groupfiles'][(doc.account,)]), 'rb') as f:
+ pdf = webupload.split_pdf(f.read(), doc.pages)
+ items.append(dict(job=job['name'], key=doc.account, kind=doc.kind, account=doc.account, docnum=doc.docnum,
+ payload=webupload.payload_json(doc), pdf=pdf))
+ return items
+
+
+def multipart(fields, files):
+ """(content type, body) for a multipart/form-data post. fields: {name: text}; files: {name: (filename, bytes)}."""
+ boundary = uuid.uuid4().hex
+ out = []
+ for name, value in fields.items():
+ out.append(('--%s\r\nContent-Disposition: form-data; name="%s"\r\n\r\n' % (boundary, name)).encode() + value.encode('utf-8') + b'\r\n')
+ for name, (filename, data) in files.items():
+ out.append(('--%s\r\nContent-Disposition: form-data; name="%s"; filename="%s"\r\nContent-Type: application/pdf\r\n\r\n'
+ % (boundary, name, filename)).encode() + data + b'\r\n')
+ out.append(('--%s--\r\n' % boundary).encode())
+ return 'multipart/form-data; boundary=' + boundary, b''.join(out)
+
+
+def post(item, base_url, api_key):
+ """Blocking: POST one document. Returns (status, reply text), also for an error status. Raises OSError (which
+ URLError is) when the website could not be reached."""
+ kind = 'statement' if item['kind'] == 'statement' else 'invoice'
+ ctype, body = multipart({'payload': item['payload']}, {'pdf': ('%s-%s.pdf' % (item['kind'], item['docnum']), item['pdf'])})
+ req = urllib.request.Request(base_url.rstrip('/') + '/api/ingest/%s/' % kind, data=body, method='POST',
+ headers={'Content-Type': ctype, 'Authorization': 'Token ' + api_key, 'Accept': 'application/json'})
+ try:
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
+ return r.status, r.read().decode('utf-8', 'replace')
+ except urllib.error.HTTPError as e:
+ return e.code, e.read().decode('utf-8', 'replace')
+
+
+def describe(status, text):
+ """A short message for a refusal: the website's own field errors if it sent them."""
+ try:
+ text = json.dumps(json.loads(text))
+ except ValueError:
+ text = '' # an HTML error page is no use in a table cell
+ return ('HTTP %d %s' % (status, text)).strip()[:300]
+
+
+class WebUploader(object):
+ """Uploads queued documents one at a time, in order. Like JobMailer, `append` is called from page handlers and
+ `start` / `close` from main.serve, all on the event loop."""
+
+ def __init__(self, queuesz=200, log=None, transport=None):
+ self.queue = asyncio.Queue(queuesz)
+ self.log = log if log is not None else UploadLog(pickle_file)
+ self.transport = transport or post # replaced in tests
+ self.task = None
+
+ def start(self):
+ self.task = asyncio.get_running_loop().create_task(self.run())
+
+ async def close(self, timeout=30):
+ if self.task:
+ try:
+ await asyncio.wait_for(self.queue.join(), timeout)
+ except asyncio.TimeoutError:
+ print('upload: %d documents still queued at shutdown' % self.queue.qsize())
+ self.task.cancel()
+ self.task = None
+
+ def append(self, item):
+ """Queue one document. Raises asyncio.QueueFull if too many are waiting."""
+ self.queue.put_nowait(item)
+
+ def attempt(self, item):
+ """One try (blocking: runs in a worker thread): (outcome, status, message, retry)."""
+ base_url, api_key = settings()
+ try:
+ status, text = self.transport(item, base_url, api_key)
+ except OSError as e:
+ return 'failed', None, 'could not reach the website: %s' % (e.reason if hasattr(e, 'reason') else e), True
+ if status in (200, 201):
+ return ('created' if status == 201 else 'replaced'), status, None, False
+ return 'failed', status, describe(status, text), status >= 500
+
+ async def run(self):
+ while True:
+ item = await self.queue.get()
+ try:
+ for delay in (0,) + RETRY_DELAYS:
+ if delay:
+ await asyncio.sleep(delay)
+ outcome, status, message, retry = await asyncio.to_thread(self.attempt, item)
+ if not retry:
+ break
+ print('upload: %s %s -> %s %s' % (item['kind'], item['docnum'], outcome, message or ''))
+ self.log.add(dict(job=item['job'], key=item['key'], kind=item['kind'], account=item['account'], docnum=item['docnum'],
+ added=datetime.datetime.now(), outcome=outcome, status=status, error=message if outcome == 'failed' else None))
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ traceback.print_exc()
+ finally:
+ self.queue.task_done()
diff --git a/web/bootstrap.html b/web/bootstrap.html
index f8305d3..390d571 100644
--- a/web/bootstrap.html
+++ b/web/bootstrap.html
@@ -38,12 +38,15 @@
Recent Documents
Sent Emails
Printed Documents
+ Uploads
Settings
diff --git a/web/home.html b/web/home.html
index cd95c68..180f0ff 100644
--- a/web/home.html
+++ b/web/home.html
@@ -44,6 +44,10 @@ Email
${email_fails} recent failure(s) sending email
+ % if upload_fails is not None:
+ ${upload_fails} recent failure(s) uploading to the website
+
+ % endif
Email Addresses » Sent Emails »
diff --git a/web/pdf.html b/web/pdf.html
index 3c6daf2..aee1ab8 100644
--- a/web/pdf.html
+++ b/web/pdf.html
@@ -21,6 +21,14 @@ Document Pages
% endfor
+ % if can_upload:
+
+ % endif
+
+ % else:
+ All ${total} loaded documents were drawn under today's stationery.
+ % endif
diff --git a/web/settings_web.html b/web/settings_web.html
new file mode 100644
index 0000000..75e9abe
--- /dev/null
+++ b/web/settings_web.html
@@ -0,0 +1,47 @@
+<%inherit file="bootstrap.html"/>
+<%block name="title">- Web Uploads%block>
+
+ Web Uploads
+
+ Invoices, credit notes and statements are uploaded to the website from their job page, or automatically.
+
+ Automatic upload
+
+ % if auto_types:
+ Documents of type
+ % for t in auto_types:
+ ${t | h}${',' if not loop.last else ''}
+ % endfor
+ are uploaded as soon as they arrive${'' if enabled else ', once a website and API key are set'}.
+ % else:
+ Nothing is uploaded automatically. Documents are uploaded from their job page.
+ % endif
+ This is set by auto_types under [Web] in ~/printerface/email.cfg
+ (invoice, crednote and statement).
+
+ Website
+
+ Website
+ % if base_url:
+ ${base_url | h}
+ % else:
+ not set
+ % endif
+
+ API key
+ % if key:
+ ${key | h}
+ % else:
+ not set
+ % endif
+
+ Uploading
+ % if enabled:
+ on
+ % else:
+ off needs both a website and an API key
+ % endif
+
+ Waiting ${waiting}
+ Recent failures ${fails}
+
diff --git a/web/uploads.html b/web/uploads.html
new file mode 100644
index 0000000..d7dfbee
--- /dev/null
+++ b/web/uploads.html
@@ -0,0 +1,38 @@
+<%inherit file="bootstrap.html"/>
+<%block name="title">- Uploads%block>
+
+ Uploads
+
+ % if waiting:
+ ${waiting} document${'' if waiting == 1 else 's'} waiting to be uploaded.
+ % endif
+
+ % if total > len(rows):
+ Showing the latest ${len(rows)} of ${total} uploads.
+ % endif
+
+ % if not rows:
+ Nothing has been uploaded yet. Invoices, credit notes and statements are uploaded from their job page.
+ Web Uploads settings
+ % else:
+
+ Document Type Result Problems?
+ % for row in rows:
+ <% u = row['u'] %>
+ % if u['error']:
+
+ % else:
+
+ % endif
+
+ % if row['loaded']:
+ ${u['docnum'] | h} / ${u['account'] | h}
+ % else:
+ ${u['docnum'] | h} / ${u['account'] | h}
+ % endif
+
+ ${u['kind'] | h} ${u['outcome'] | h} ${u['error'] or '' | h}
+
+ % endfor
+
+ % endif
diff --git a/webupload.py b/webupload.py
new file mode 100644
index 0000000..30b8bcd
--- /dev/null
+++ b/webupload.py
@@ -0,0 +1,158 @@
+"""
+Turns parsed Printerface documents into what the website's ingest endpoints take, with no network code so it
+can be tested on its own. See the website's README ("Sales documents from Printerface").
+
+Each function takes a job (as stored: `name`, `ts`, `parsed`) and returns a list of `Document`s, one per
+invoice, credit note or statement. A document records which pages of its account's PDF it occupies, because
+one PDF holds every document the account was sent in the print run, and a document may run to several pages
+(the totals are then on its last page).
+"""
+
+import collections
+import datetime
+import io
+import json
+import re
+
+Document = collections.namedtuple('Document', 'kind account docnum pages payload')
+
+LINE_FIELDS = ('prod_code', 'prod_desc', 'prod_qty', 'prod_price', 'prod_unit', 'prod_net', 'prod_vcode')
+VAT_FIELDS = ('summ_code', 'summ_netamt', 'summ_rate', 'summ_vat')
+
+
+class UploadError(Exception):
+ pass
+
+
+def amount(text):
+ """'1,234.50' -> '1234.50'; a trailing CR (credit) makes it negative. Blank is None. Kept as text so no
+ float rounding can creep in; the website parses it as a decimal."""
+ text = (text or '').strip().replace(',', '')
+ if not text:
+ return None
+ negative = text.endswith('CR')
+ text = text[:-2].strip() if negative else text
+ if not re.match(r'^-?\d+(\.\d+)?$', text):
+ raise UploadError('not an amount: %r' % text)
+ return '-' + text.lstrip('-') if negative and not text.startswith('-') else text
+
+
+def iso_date(text):
+ """Printerface prints dd/mm/yy"""
+ try:
+ return datetime.datetime.strptime(text.strip(), '%d/%m/%y').date().isoformat()
+ except ValueError:
+ raise UploadError('not a date: %r' % text)
+
+
+def received(job):
+ """When Printerface received the job, as UTC. job['ts'] is a naive utcnow() unless it was made aware."""
+ ts = job['ts']
+ if ts.tzinfo:
+ ts = ts.astimezone(datetime.timezone.utc).replace(tzinfo=None)
+ return ts.strftime('%Y-%m-%dT%H:%M:%SZ')
+
+
+def columns(page, names):
+ """The rows of a page's columns, which are newline joined strings, as a list of dicts. Short columns are padded."""
+ cols = [page.get(n, '').split('\n') for n in names]
+ height = max(len(c) for c in cols)
+ return [dict(zip(names, [(c[i] if i < len(c) else '').strip() for c in cols])) for i in range(height)]
+
+
+def lines_of(pages):
+ """(lines, notes) for the pages of one document. A line has a product code, a quantity or an amount; a row with none of
+ those is text (a reference printed under a credit note's lines) and goes in notes."""
+ lines, notes = [], []
+ for page in pages:
+ for row in columns(page, LINE_FIELDS):
+ if row['prod_code'] or row['prod_qty'] or row['prod_net'] or row['prod_price']:
+ lines.append(dict(product_code=row['prod_code'], description=row['prod_desc'],
+ quantity=amount(row['prod_qty']) or '0', unit=row['prod_unit'], unit_price=amount(row['prod_price']) or '0',
+ net=amount(row['prod_net']) or '0', vat_code=row['prod_vcode']))
+ elif row['prod_desc']:
+ notes.append(row['prod_desc'])
+ return lines, notes
+
+
+def vat_summary(page):
+ return [dict(vat_code=r['summ_code'], net=amount(r['summ_netamt']), rate=amount(r['summ_rate']), vat=amount(r['summ_vat']))
+ for r in columns(page, VAT_FIELDS) if r['summ_code']]
+
+
+def sales_documents(job):
+ """Invoices or credit notes, depending on the job's template."""
+ credit = job.get('templ') == 'crednote'
+ docs = []
+ for account, pages in (job.get('parsed') or {}).items():
+ by_number = collections.OrderedDict()
+ for index, page in enumerate(pages):
+ if not page.get('doc_num', '').strip():
+ continue # a blank page, not a document
+ by_number.setdefault(page['doc_num'].strip(), []).append(index)
+ for docnum, indexes in by_number.items():
+ doc_pages = [pages[i] for i in indexes]
+ last = doc_pages[-1]
+ if not last.get('tot_due', '').strip():
+ raise UploadError('%s %s has no totals on its last page' % (account, docnum))
+ lines, notes = lines_of(doc_pages)
+ vat = vat_summary(last)
+ for line in lines:
+ rate = [v['rate'] for v in vat if v['vat_code'] == line['vat_code']]
+ line['vat_rate'] = rate[0] if rate else None
+ if amount(last['tot_net']) is None:
+ raise UploadError('%s %s has no net total' % (account, docnum))
+ first = doc_pages[0]
+ desc = [x for x in first['addr_invoice'].split('\n') if x.strip()]
+ payload = dict(docnum=docnum, is_credit_note=credit, date=iso_date(first['date']),
+ account=dict(acc=account, name=', '.join(x.strip() for x in desc[:3]), salesperson=first['salesperson'].strip()),
+ cust_ref=first['custref'].strip(), our_ref=first['ourref'].strip(),
+ total_net=amount(last['tot_net']), total_vat=amount(last['tot_vat']) or '0', total_gross=amount(last['tot_due']),
+ vat_summary=vat, credit_refs='; '.join(notes)[:200] if credit else '',
+ job_name=job['name'], printed_at=received(job), lines=lines)
+ docs.append(Document('invoice', account, docnum, indexes, payload))
+ return docs
+
+
+def statements(job):
+ """One statement per account: its details are on the last page when it runs to several."""
+ docs = []
+ for account, pages in (job.get('parsed') or {}).items():
+ last = pages[-1]
+ desc = [x for x in last['addr_invoice'].split('\n') if x.strip()]
+ payload = dict(docnum='%s-%s' % (job['name'][6:], account), date=iso_date(last['date']),
+ account=dict(acc=account, name=', '.join(x.strip() for x in desc[:3]), salesperson=''),
+ amt_current=amount(last['age_curr']), amt_1month=amount(last['age_1m']), amt_2month=amount(last['age_2m']),
+ amt_3month=amount(last['age_3m']), amt_due=amount(last['age_due']), printed_at=received(job))
+ missing = [k for k, v in payload.items() if v is None]
+ if missing:
+ raise UploadError('statement for %s has no %s' % (account, ', '.join(missing)))
+ docs.append(Document('statement', account, payload['docnum'], list(range(len(pages))), payload))
+ return docs
+
+
+def documents(job):
+ """Everything uploadable in a job, or [] for a type that is not uploaded."""
+ if job.get('templ') in ('invoice', 'crednote'):
+ return sales_documents(job)
+ if job.get('templ') == 'statement':
+ return statements(job)
+ return []
+
+
+def split_pdf(pdf_bytes, pages):
+ """A PDF holding just the given (0 based) pages of pdf_bytes."""
+ from pypdf import PdfReader, PdfWriter
+ reader = PdfReader(io.BytesIO(pdf_bytes))
+ if pages and max(pages) >= len(reader.pages):
+ raise UploadError('page %d wanted but the PDF has %d' % (max(pages) + 1, len(reader.pages)))
+ writer = PdfWriter()
+ for i in pages:
+ writer.add_page(reader.pages[i])
+ out = io.BytesIO()
+ writer.write(out)
+ return out.getvalue()
+
+
+def payload_json(document):
+ return json.dumps(document.payload)