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 response - - -

Error response

-

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 = ('%d %s

%d %s

' % ( + status, message, status, message)).encode(BODY_ENCODING) + return self.reply(request, status, page, {'Content-Type': 'text/html; charset=' + BODY_ENCODING}) + + async def _handle(self, request): + path = request.path + query_string = urllib.parse.parse_qs(request.rel_url.raw_query_string) + handler = self.handlers.get(path) + if request.method == 'POST': + if not handler: + return self.error(request, 404, 'Not Found') + # only urlencoded form bodies are understood; fields arrive as {name: [values]}, like query_string + body = (await request.read()).decode(BODY_ENCODING, 'replace') + postreq = urllib.parse.parse_qs(body, keep_blank_values=True) + return self.run_handler(request, handler, dict(query_string=query_string, postreq=postreq)) + if request.method not in ('GET', 'HEAD'): + return self.error(request, 501, 'Unsupported method (%r)' % request.method) + if handler: + gatherer = ResponseGatherer() + return self.run_handler(request, handler, dict(query_string=query_string, resp=gatherer), gatherer) + return self.static(request, path) + + def run_handler(self, request, handler, kwargs, gatherer=None): + try: + result = handler(**kwargs) + if isinstance(result, Redirect): + return self.reply(request, 303, b'', {'Location': result.location}) + (f, ctype) = _body_file(*result) + headers = dict(gatherer.headers) if gatherer else {} + headers['Content-Type'] = ctype + body = f.read() f.close() + return self.reply(request, 200, body, headers) + except Exception: + print(traceback.format_exc()) + return self.error(request, 500, 'Internal Server Error') - def do_HEAD(self): - """Serve a HEAD request.""" - f = self.send_head() - if f: - f.close() + def translate_path(self, path): + """The file under the web root for a /-separated URL path. Components that mean something to the + file system (drives, '..') are ignored, so a request can't leave the web root.""" + path = posixpath.normpath(urllib.parse.unquote(path)) + result = self.webroot + for word in [w for w in path.split('/') if w]: + drive, word = os.path.splitdrive(word) + head, word = os.path.split(word) + if word in (os.curdir, os.pardir): + continue + result = os.path.join(result, word) + return result - def send_head(self): - """Common code for GET and HEAD commands. - - This sends the response code and MIME headers. - - Return value is either a file object (which has to be copied - to the outputfile by the caller unless the command was HEAD, - and must be closed by the caller under all circumstances), or - None, in which case the caller has nothing further to do. - - """ - class ResponseGatherer(): - def __init__(self): - self.headers = [] - def add_header(self, key, value): - self.headers.append((key, value)) - def write_headers(self, connection): - for (k,v) in self.headers: - connection.send_header(k,v) - - handler = self.handlers.get(self.path) - if (handler): - try: - resp = ResponseGatherer() - result = handler(query_string=self.query_string, resp=resp) - if isinstance(result, Redirect): - self.send_redirect(result) - return None - (f, ctype) = _body_file(*result) - self.send_response(200) - resp.write_headers(self) - self.send_header("Content-type", ctype) - f.seek(0, os.SEEK_END) - self.send_header("Content-Length", str(f.tell())) - # self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) - self.end_headers() - f.seek(0) - return f - except: - tb = traceback.format_exc() - print(tb) - self.send_error(500, "File not found") - return None - - path = self.translate_path(self.path) - f = None + def static(self, request, urlpath): + path = self.translate_path(urlpath) if os.path.isdir(path): - if not self.path.endswith('/'): + if not urlpath.endswith('/'): # redirect browser - doing basically what apache does - self.send_response(301) - self.send_header("Location", self.path + "/") - self.end_headers() - return None - for index in "index.html", "index.htm": - index = os.path.join(path, index) - if os.path.exists(index): - path = index + return self.reply(request, 301, b'', {'Location': urlpath + '/'}) + for index in ('index.html', 'index.htm'): + if os.path.exists(os.path.join(path, index)): + path = os.path.join(path, index) break else: - return self.list_directory(path) - ctype = self.guess_type(path) - try: - # Always read in binary mode. Opening files in text mode may cause - # newline translations, making the actual size of the content - # transmitted *less* than the content-length! - f = open(path, 'rb') - except IOError: - tb = traceback.format_exc() - print(tb) - self.send_error(404, "File not found") - return None - self.send_response(200) - self.send_header("Content-type", ctype) - fs = os.fstat(f.fileno()) - self.send_header("Content-Length", str(fs[6])) - self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) - self.end_headers() - return f - - def send_redirect(self, redirect): - self.send_response(303) - self.send_header("Location", redirect.location) - self.send_header("Content-Length", "0") - self.end_headers() - - def list_directory(self, path): - """Helper to produce a directory listing (absent index.html). - - Return value is either a file object, or None (indicating an - error). In either case, the headers are sent, making the - interface the same as for send_head(). - - """ + return self.error(request, 404, 'Not Found') try: - list = os.listdir(path) - except os.error: - self.send_error(404, "No permission to list directory") - return None - list.sort(key=lambda a: a.lower()) - f = io.StringIO() - displaypath = html.escape(urllib.parse.unquote(self.path)) - f.write('') - f.write("\nDirectory listing for %s\n" % displaypath) - f.write("\n

Directory listing for %s

\n" % displaypath) - f.write("
\n\n
\n\n\n") - f = io.BytesIO(f.getvalue().encode(sys.getfilesystemencoding(), 'replace')) - length = len(f.getvalue()) - self.send_response(200) - encoding = sys.getfilesystemencoding() - self.send_header("Content-type", "text/html; charset=%s" % encoding) - self.send_header("Content-Length", str(length)) - self.end_headers() - return f + # binary, so that newline translation can't change the size of what is sent + with open(path, 'rb') as f: + body = f.read() + mtime = os.fstat(f.fileno()).st_mtime + except OSError: + return self.error(request, 404, 'Not Found') + return self.reply(request, 200, body, {'Content-Type': guess_type(path), 'Last-Modified': formatdate(mtime, usegmt=True)}) - def translate_path(self, path): - """Translate a /-separated PATH to the local filename syntax. - - Components that mean special things to the local file system - (e.g. drive or directory names) are ignored. (XXX They should - probably be diagnosed.) - - """ - # abandon query parameters - path = path.split('?',1)[0] - path = path.split('#',1)[0] - path = posixpath.normpath(urllib.parse.unquote(path)) - words = path.split('/') - words = [w for w in words if w] - path = self.webroot - for word in words: - drive, word = os.path.splitdrive(word) - head, word = os.path.split(word) - if word in (os.curdir, os.pardir): continue - path = os.path.join(path, word) - return path - - def guess_type(self, path): - """Guess the type of a file. - - Argument is a PATH (a filename). - - Return value is a string of the form type/subtype, - usable for a MIME Content-type header. - - The default implementation looks the file's extension - up in the table self.extensions_map, using application/octet-stream - as a default; however it would be permissible (if - slow) to look inside the data to make a better guess. - - """ - - base, ext = posixpath.splitext(path) - if ext in self.extensions_map: - return self.extensions_map[ext] - ext = ext.lower() - if ext in self.extensions_map: - return self.extensions_map[ext] - else: - return self.extensions_map[''] - - 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', - }) - -class RequestHandler(SimpleHTTPRequestHandler): - - def __init__(self,conn,addr, webroot=os.getcwd(), path_handlers={}): - asynchat.async_chat.__init__(self,conn) - - self.client_address = addr - self.id = "[httpd-%d]" % addr[1] - self.webroot = webroot - self.handlers = path_handlers - - # set the terminator : when it is received, this means that the - # http request is complete ; control will be passed to - # self.found_terminator - self.reset_terminator(); - - def reset_terminator(self): - self.set_terminator (b'\r\n\r\n') - self.found_terminator = self.handle_request_line - self.rfile = io.BytesIO() - - def collect_incoming_data(self,data): - self.rfile.write(data) - - def do_POST(self): - """Begins serving a POST request. The request data must be readable - on a file-like object called self.rfile""" - # only urlencoded form bodies are understood; fields arrive as {name: [values]}, like query_string - body = self.rfile.getvalue().decode(BODY_ENCODING, 'replace') - postreq = urllib.parse.parse_qs(body, keep_blank_values=True) - - handler = self.handlers.get(self.path) - if (handler): - try: - result = handler(query_string=self.query_string, postreq=postreq) - if isinstance(result, Redirect): - self.send_redirect(result) - return None - (f, ctype) = _body_file(*result) - self.send_response(200) - self.send_header("Content-type", ctype) - f.seek(0, os.SEEK_END) - self.send_header("Content-Length", str(f.tell())) - # self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) - self.end_headers() - f.seek(0) - self.push(f.read()) - f.close() - return None - except: - tb = traceback.format_exc() - print(tb) - self.send_error(500, "File not found") - return None - else: - self.send_error(404, "File not found") - return None - - def handle_request_line(self): - """Called when the http request line and headers have been received""" - # prepare attributes needed in parse_request() - self.rfile.seek(0) - requestline = self.rfile.readline() - self.parse_request( requestline ) - - # if browser indicates POST data follows, read it before generating the response - bytesToRead = int(self.headers.getheader('content-length', '0')) - if bytesToRead > 0: - self.set_terminator(bytesToRead) - self.rfile = io.BytesIO() - # control will be passed to a new found_terminator - self.found_terminator = self.dispatch_handler - - else: - # no content from brower - generate response now - self.dispatch_handler() - - def dispatch_handler(self): - mname = 'do_' + self.command - if not hasattr(self, mname): - self.send_error(501, "Unsupported method (%r)" % self.command) - return - getattr(self, mname)() - - if self.close_connection: - """Send data, then close""" - self.log_message("close_connection set, closing connection") - self.close_when_done() - - self.reset_terminator() - - def handle_error(self): - traceback.print_exc(sys.stderr) - self.close() - - def log_message(self, format, *args): - sys.stdout.write("%s %s %s %s\n" % - (self.id, self.log_date_time_string(), self.address_string(), format%args)) - -class ToyHttpServer(asyncore.dispatcher): - - def __init__ (self, ip='', port=8081, webroot=os.getcwd(), handler=RequestHandler, pathhandlers={}): - - self.webroot=webroot - self.path_handlers = pathhandlers - self.handler = handler - asyncore.dispatcher.__init__ (self) - self.create_socket(socket.AF_INET, socket.SOCK_STREAM) - - self.set_reuse_addr() - self.bind ((ip, port)) - self.listen (100) - - print("[httpd] ToyHTTPServer running on port %s, serving from %s" % (port, self.webroot)) - - def handle_accept (self): - try: - pair = self.accept() - if pair is not None: - sock, addr = pair - self.handler(sock,addr,webroot=self.webroot, path_handlers=self.path_handlers) - except socket.error: - self.log_info ('[https] warning: server accept() threw an exception', 'warning') - return if __name__=="__main__": - def about(query_string=''): + def about(query_string='', resp=None): return ("hi %s" % query_string, 'text/plain') - # launch the server on the specified port - s = ToyHttpServer(port=8081, pathhandlers={'/about': about}) + async def main(): + # launch the server on the specified port + await HttpServer({'/about': about}, os.getcwd(), port=8081).start() + await asyncio.Event().wait() try: - while True: - asyncore.loop(timeout=2, count=10) - print('[control] poll') + asyncio.run(main()) except KeyboardInterrupt: print("Crtl+C pressed. Shutting down.") diff --git a/init.d/printerface b/init.d/printerface index b631965..931b85d 100755 --- a/init.d/printerface +++ b/init.d/printerface @@ -29,7 +29,7 @@ # Location of printerface binary printerface=~/repos/printerface/main.py -# Interpreter to run it with. Needs python 3.11 (asyncore was removed in 3.12) plus the packages from +# Interpreter to run it with. Needs python 3.11 or later plus the packages from # requirements.txt, so default to a venv made from /opt/python311/bin/python3.11: # /opt/python311/bin/python3.11 -m venv ~/.venv311 && ~/.venv311/bin/pip install -r requirements.txt # Set PRINTERFACE_PYTHON to use another one. diff --git a/lpdserver.py b/lpdserver.py index d3c9319..c434ded 100644 --- a/lpdserver.py +++ b/lpdserver.py @@ -1,130 +1,173 @@ -# Line Printer Daemon implementation, using asynchat +# Line Printer Daemon implementation (RFC 1179 receive side), using asyncio # Chris Shucksmith 2013 -import asynchat, asyncore, socket, os +import asyncio +import os import sys +import traceback # LPD is a byte protocol and print data is 8-bit. Decode everything as latin-1 so that one byte is # always one character (columns in the fixed-width documents must not shift) and so it round-trips. ENCODING = 'latin-1' -(AwaitingCommand, NewJob, NewJobControl, NewJobData, EndOfFile ) = range(0,5) +# a client that goes quiet in the middle of a job is dropped after this many seconds +IDLE_TIMEOUT = 120 -class LpdHandler(asynchat.async_chat): +ACK = b'\x00' - def __init__(self, sock, addr, controller): - asynchat.async_chat.__init__(self, sock=sock) - self.ibuffer = [] - self.sm = AwaitingCommand - self.set_terminator(b"\n") - self.sock = sock + +class LpdHandler(object): + """One connection. The conversation is: a receive-job command naming the queue, then a control file and a + data file, each announced by a subcommand giving its size and acknowledged with a zero byte, and each + followed by a zero byte of its own. Many senders close the connection after the data file.""" + + def __init__(self, reader, writer, controller): + self.reader = reader + self.writer = writer self.controller = controller - self.id = "[lpd-%d]" % addr[1] + peer = writer.get_extra_info('peername') or ('?', 0) + self.id = "[lpd-%d]" % peer[1] + + async def _read(self, coro): + return await asyncio.wait_for(coro, IDLE_TIMEOUT) + + async def _line(self): + """The next command line without its newline, or None if the client has gone.""" + try: + return (await self._read(self.reader.readuntil(b'\n')))[:-1] + except asyncio.IncompleteReadError: + return None + + async def _ack(self): + self.writer.write(ACK) + await self.writer.drain() + + async def run(self): print('%s installed LpdHandler' % self.id) + try: + await self._conversation() + except (asyncio.TimeoutError, ConnectionError): + print('%s connection lost' % self.id) + except Exception: + traceback.print_exc(file=sys.stdout) + finally: + print('%s handle_close' % self.id) + try: + self.writer.close() + await self.writer.wait_closed() + except Exception: + pass - def collect_incoming_data(self, data): - self.ibuffer.append(data) - print('%s collect_data - %d bytes' % (self.id, len(data))) - - def found_terminator(self): - # the terminator can arrive split over several recv()s, so gather every fragment - chunk = b''.join(self.ibuffer) - self.ibuffer = [] - cmd = chunk[:1] - if self.sm == AwaitingCommand: # Main command verb - if cmd == b'\x02': + async def _conversation(self): + # main command verb: 02 LF + while True: + chunk = await self._line() + if chunk is None: + return + if chunk[:1] == b'\x02': self.queue = chunk[1:].decode(ENCODING) print('%s Incoming job to queue \'%s\'' % (self.id, self.queue)) - self.push(b'\x00') - self.sm = NewJob - else: - print('%s unknown message type %r' % (self.id, cmd)) - elif self.sm == NewJob: # Recieve Job - if cmd == b'\x02': # Subcommand - Control filename - sz,name = chunk[1:].decode(ENCODING).split(' ', 1) - rdlength = int(sz) - print('%s Incoming header: control file sz %d filename %s' % (self.id, rdlength,name)) - self.sm = NewJobControl - self.set_terminator(rdlength+1) # include the trailing null - self.push(b'\x00') - elif cmd == b'\x03': # Subcommand - Data filename - sz,name = chunk[1:].decode(ENCODING).split(' ', 1) - rdlength = int(sz) - print('%s incoming header: data file sz %d filename %s' % (self.id, rdlength,name)) - self.sm = NewJobData - # windows seems to set a stupidly large length here and kill the socket to - # indicate eof. Handle either - self.set_terminator(rdlength+1) # include the trailing null - # self.set_terminator(None) # terminated by close of socket - self.push(b'\x00') + await self._ack() + break + print('%s unknown message type %r' % (self.id, chunk[:1])) + + self.control = {} + while True: + chunk = await self._line() + if chunk is None: + print('%s unexpected close of stream' % self.id) + return + cmd = chunk[:1] + if cmd == b'\x02': # subcommand: control file, 02 LF + size, name = chunk[1:].decode(ENCODING).split(' ', 1) + length = int(size) + print('%s Incoming header: control file sz %d filename %s' % (self.id, length, name)) + await self._ack() + try: + body = await self._read(self.reader.readexactly(length + 1)) # include the trailing null + except asyncio.IncompleteReadError: + print('%s unexpected close of stream' % self.id) + return + self.control = dict([(x[0], x[1:]) for x in body[:-1].decode(ENCODING).split('\n') if len(x) > 1]) + print('%s control file: %s' % (self.id, repr(self.control))) + await self._ack() + elif cmd == b'\x03': # subcommand: data file, 03 LF + size, name = chunk[1:].decode(ENCODING).split(' ', 1) + length = int(size) + print('%s incoming header: data file sz %d filename %s' % (self.id, length, name)) + await self._ack() + # Windows sends a stupidly large size and closes the connection to mark the end of the data; + # either way we dispatch what arrived. A well formed file keeps its trailing null, as it always has. + data, complete = await self._data_file(length + 1) + if complete: + print('%s end of data file' % self.id) + await self._ack() + self.dispatch(data) + else: + # the sender has closed: the job must still be kept even if it can no longer hear the ack + print('%s data file: %s' % (self.id, repr(data)[:100])) + self.dispatch(data) + try: + await self._ack() + except ConnectionError: + pass + return else: print('%s recieve job unknown subcommand: %r' % (self.id, cmd)) - elif self.sm == NewJobControl: # Recieve - Job Control file (null terminated) - self.controldata = dict([ (x[0], x[1:]) for x in chunk[:-1].decode(ENCODING).split('\n') if len(x) > 1]) - print('%s control file: %s' % (self.id, repr(self.controldata))) - self.push(b'\x00') - self.sm = NewJob - self.set_terminator(b"\n") - elif self.sm == NewJobData: # Recieve - Job Data file (terminated by close) - # Windows NT4 lpr sends a well formed size, hits this code - print('%s end of data file' % self.id) - # put the chunk back on the ibuffer for dispatch() - self.ibuffer.insert(0, chunk) - self.sm = EndOfFile - self.push(b'\x00') - self.close_when_done() - self.dispatch() - else: - print('%s Unknown state, woken up by terminator, chunk was: %s' % (self.id, repr(chunk))) - self.close_when_done() - - def handle_close(self): - print('%s handle_close' % (self.id)) - if self.sm == NewJobData: - print('%s data file: %s' % (self.id, repr(self.ibuffer)[:100])) - # calling push() after the client has closed the socket will re-invoke handle_close, so - # switch to terminal state to avoid inf recursion - self.sm = EndOfFile - self.dispatch() - self.push(b'\x00') - self.close_when_done() - elif self.sm == EndOfFile: - self.close() - else: - print('%s unexpected close of stream, sm=%d' % (self.id, self.sm)) - self.close() - - def dispatch(self): - data = b''.join(self.ibuffer).decode(ENCODING) - # log exceptions during dispatch so that we get the thread back to perform socket clean up + + async def _data_file(self, size): + """(bytes, complete): the data file, or what arrived of it before the sender closed or reset the connection.""" + chunks, got = [], 0 + while got < size: + try: + chunk = await self._read(self.reader.read(min(65536, size - got))) + except ConnectionError: + break + if not chunk: + break + chunks.append(chunk) + got += len(chunk) + return b''.join(chunks), got >= size + + def dispatch(self, data): + # log exceptions during dispatch so that we still get to close the connection try: - print('%s dispatching' % (self.id)) - self.controller(self.queue, self.sock.getpeername(), self.sock.getsockname(), self.controldata, data) + print('%s dispatching' % self.id) + self.controller(self.queue, self.writer.get_extra_info('peername'), self.writer.get_extra_info('sockname'), + self.control, data.decode(ENCODING)) except Exception as e: print('LPD dispatch of print job threw exception: %s' % sys.exc_info()[0]) print(e) sys.stdout.flush() - print('%s dispatch complete' % (self.id)) - -class LpdServer(asyncore.dispatcher): - def __init__ (self, lpd_controller, ip='127.0.0.1', port=515): - asyncore.dispatcher.__init__ (self) - self.create_socket (socket.AF_INET, socket.SOCK_STREAM) - self.set_reuse_addr() - self.bind ((ip, port)) - self.listen (100) + print('%s dispatch complete' % self.id) + + +class LpdServer(object): + """Listens for LPD connections and hands each received job to lpd_controller(queue, peer, local, control, data), + called on the event loop, so it shares the loop's single thread with everything else. Use as + `await server.start()`; `server.port` is the port actually bound (pass port=0 to be given one).""" + + def __init__(self, lpd_controller, ip='127.0.0.1', port=515): self.lpd_controller = lpd_controller - print('[lpd] listening on port %s' % port) + self.ip = ip + self.port = port + self.server = None + + async def start(self): + self.server = await asyncio.start_server(self._accept, self.ip or None, self.port, backlog=100) + self.port = self.server.sockets[0].getsockname()[1] + print('[lpd] listening on port %s' % self.port) + return self + + async def _accept(self, reader, writer): + print('[lpd] Incoming connection from %s' % repr(writer.get_extra_info('peername'))) + await LpdHandler(reader, writer, self.lpd_controller).run() + + async def close(self): + if self.server: + self.server.close() + await self.server.wait_closed() - def handle_accept(self): - try: - pair = self.accept() - if pair is not None: - sock, addr = pair - print('[lpd] Incoming connection from %s' % repr(addr)) - LpdHandler(sock, addr, self.lpd_controller) - except socket.error: - print('[lpd] warning: server accept() threw an exception') def jobPrinter(queue, local, remote, control, data): print(' %s' % queue) @@ -142,8 +185,10 @@ def defaultPort(): # rather than run as root, use iptables nat to redirect to a common service port: # iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080 # iptables -t nat -I OUTPUT -p tcp -d 127.0.0.1 --dport 80 -j REDIRECT --to-ports 8080 - s = LpdServer(jobPrinter, ip='localhost', port=defaultPort()) + async def main(): + await LpdServer(jobPrinter, ip='localhost', port=defaultPort()).start() + await asyncio.Event().wait() try: - asyncore.loop(timeout=2) + asyncio.run(main()) except KeyboardInterrupt: print('Crtl+C pressed. Shutting down.') diff --git a/mailer.py b/mailer.py index bcdd8c4..537cfa1 100644 --- a/mailer.py +++ b/mailer.py @@ -1,6 +1,6 @@ # -# Asynchronous mail sender to Gmail, using a seperate thread. -# Keeps the last 10 results around if you want to check results +# Mail sender to Gmail: a queue worked by the event loop, with the blocking smtplib calls in a worker thread. +# Keeps the last result_count results around if you want to check results # Import smtplib for the actual sending function import smtplib @@ -13,8 +13,8 @@ # http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python import datetime -import os, re, threading -import queue +import asyncio +import os, re import traceback import pickle @@ -42,10 +42,17 @@ def sent_from_job(results, job_name): return out class JobMailer(object): + """Sends queued emails one at a time, in the order they were queued, and keeps the outcome of the last + `result_count` of them (newest first) in mailer.pickle. + + The sending itself, smtplib, blocks, so it runs in a worker thread (asyncio.to_thread) while the event loop + carries on serving; everything else, the queue and the results list, is only touched on the loop. `append` + is called from page handlers and `start` / `close` from main.serve.""" def __init__(self, queuesz=10): - self.queue = queue.Queue(queuesz) + self.queue = asyncio.Queue(queuesz) self.results = [] + self.task = None self.resultLimit = config.getint('Gmail', 'result_count') try: @@ -59,47 +66,58 @@ def __init__(self, queuesz=10): while len(self.results) > self.resultLimit: self.results.pop() - self.thread = threading.Thread(target=self.run) - self.thread.daemon = True - self.thread.start() + def start(self): + """Begin sending. Needs the running event loop.""" + self.task = asyncio.get_running_loop().create_task(self.run()) + + async def close(self, timeout=30): + """Stop after sending what is already queued, for up to `timeout` seconds.""" + if self.task: + try: + await asyncio.wait_for(self.queue.join(), timeout) + except asyncio.TimeoutError: + print('mailq: %d emails still queued at shutdown' % self.queue.qsize()) + self.task.cancel() + self.task = None def append(self, job): + """Queue an email. Raises asyncio.QueueFull if too many are waiting.""" job['added'] = datetime.datetime.now() job['completed']=None job['status']=None - self.queue.put( job ) + self.queue.put_nowait( job ) - def run(self): + def send(self, work): + """Send one queued email (blocking: runs in a worker thread) and record the outcome on it.""" + try: + filename = os.path.basename(work['attachment']) + with open(os.path.expanduser(work['attachment']), 'rb') as fileobj: + self.sendJobAttachment(work['body'], fileobj, filename, work['subject'], work['to']) + work['completed'] = datetime.datetime.now() + work['error'] = None + except Exception as e: + print('mailq: failed to send email: ' + repr(e)) + work['completed'] = datetime.datetime.now() + work['error'] = repr(e) + + async def run(self): print("mailq: run is called") while True: + work = await self.queue.get() try: - work = self.queue.get(block=True, timeout=60) print('mailq: Got work ' + repr(work)) - - try: - filename = os.path.basename(work['attachment']) - with open(os.path.expanduser(work['attachment']), 'rb') as fileobj: - - x = self.sendJobAttachment(work['body'], fileobj, filename, work['subject'], work['to']) - - work['completed'] = datetime.datetime.now() - work['error'] = None - - except Exception as e: - print('mailq: failed to send email: ' + repr(e)) - - work['completed'] = datetime.datetime.now() - work['error'] = repr(e) - + await asyncio.to_thread(self.send, work) print('mailq: finished ' + repr(work)) self.results.insert(0, work) if len(self.results) > self.resultLimit: self.results.pop() - self.pickleResults() - - except queue.Empty: - print('mailq: idling for jobs') + except asyncio.CancelledError: + raise + except Exception: + traceback.print_exc() + finally: + self.queue.task_done() def pickleResults(self): try: @@ -159,21 +177,130 @@ def test_sent_from_job(self): self.assertEqual([('newest', 'B'), ('a', 'A')], [(r['subject'], key) for r, key in found]) self.assertEqual([], sent_from_job(results, 'job-20000101-000000')) -if __name__=="__main__": - - import time - mailq = JobMailer(100) +class TestJobMailer(unittest.TestCase): + def setUp(self): + import tempfile + global pickle_file + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + old, pickle_file = pickle_file, os.path.join(self.dir.name, 'mailer.pickle') + self.addCleanup(lambda: globals().update(pickle_file=old)) + + def mailer(self, size=10, limit=3, sender=None): + m = JobMailer(size) + m.resultLimit = limit + self.sent = [] + def fake(text, fileobj, filename, subject, email_to): + if sender: + sender(subject) + self.sent.append((subject, filename, fileobj.read(), list(email_to))) + m.sendJobAttachment = fake + return m + + def attachment(self, name='a.pdf', data=b'%PDF'): + path = os.path.join(self.dir.name, name) + with open(path, 'wb') as f: + f.write(data) + return path + + def job(self, subject, **kw): + return dict(to=['x@example.com'], body='b', subject=subject, attachment=kw.get('attachment') or self.attachment()) + + def test_sends_in_order_records_newest_first_and_persists(self): + async def go(): + m = self.mailer() + m.start() + for n in 'abc': + m.append(self.job(n)) + await m.close() + return m + m = asyncio.run(go()) + self.assertEqual(['a', 'b', 'c'], [x[0] for x in self.sent]) + self.assertEqual(('a.pdf', b'%PDF', ['x@example.com']), self.sent[0][1:]) + self.assertEqual(['c', 'b', 'a'], [r['subject'] for r in m.results]) + self.assertTrue(all(r['error'] is None and r['completed'] for r in m.results)) + with open(pickle_file, 'rb') as f: + self.assertEqual(['c', 'b', 'a'], [r['subject'] for r in pickle.load(f)]) + + def test_a_failure_is_recorded_and_the_next_still_goes(self): + def sender(subject): + if subject == 'bad': + raise RuntimeError('smtp down') + async def go(): + m = self.mailer(sender=sender) + m.start() + m.append(self.job('bad')) + m.append(self.job('good')) + m.append(dict(self.job('gone'), attachment=os.path.join(self.dir.name, 'missing.pdf'))) + await m.close() + return m + m = asyncio.run(go()) + by = {r['subject']: r['error'] for r in m.results} + self.assertIn('smtp down', by['bad']) + self.assertIsNone(by['good']) + self.assertIn('FileNotFoundError', by['gone']) + + def test_keeps_only_the_newest_results(self): + async def go(): + m = self.mailer(limit=2) + m.start() + for n in '1234': + m.append(self.job(n)) + await m.close() + return m + self.assertEqual(['4', '3'], [r['subject'] for r in asyncio.run(go()).results]) + + def test_sending_does_not_block_the_event_loop(self): + import threading + gate = threading.Event() + async def go(): + m = self.mailer(sender=lambda subject: gate.wait(5)) + m.start() + m.append(self.job('slow')) + await asyncio.sleep(0.1) # the worker thread is now stuck inside "smtplib" + ticks = 0 + for _ in range(5): + await asyncio.sleep(0.01) + ticks += 1 + gate.set() + await m.close() + return ticks, m + ticks, m = asyncio.run(go()) + self.assertEqual(5, ticks) + self.assertEqual(['slow'], [r['subject'] for r in m.results]) + + def test_too_many_queued_is_an_error_not_a_stall(self): + async def go(): + m = self.mailer(size=2) + m.append(self.job('1')) + m.append(self.job('2')) + with self.assertRaises(asyncio.QueueFull): + m.append(self.job('3')) + asyncio.run(go()) + + def test_results_survive_a_restart_and_a_smaller_limit_trims(self): + async def go(): + m = self.mailer(limit=5) + m.start() + for n in '123': + m.append(self.job(n)) + await m.close() + asyncio.run(go()) + async def again(): + return JobMailer(10) + m = asyncio.run(again()) + self.assertEqual(['3', '2', '1'], [r['subject'] for r in m.results]) - for i in range(60): - time.sleep(1) - if i == 5: - mailq.append(dict( - to=['chris@shucksmith.co.uk'], body='body text here', subject='Statement for XX', - attachment="~/repos/printerface/web/pdf/job-20130404-145700%f-accounts.pdf")) +if __name__=="__main__": + async def demo(): + mailq = JobMailer(100) + mailq.start() + mailq.append(dict( + to=['chris@shucksmith.co.uk'], body='body text here', subject='Statement for XX', + attachment="~/repos/printerface/web/pdf/job-20130404-145700%f-accounts.pdf")) + await mailq.close() print(mailq.results) - print('done') - - + asyncio.run(demo()) diff --git a/main.py b/main.py index ee9210d..c0a43a1 100755 --- a/main.py +++ b/main.py @@ -4,10 +4,10 @@ from mako.lookup import TemplateLookup from mako import exceptions -import asynchat, asyncore, socket, os, re +import asyncio, os, re, signal from datetime import datetime from lpdserver import LpdServer -from httpserver import ToyHttpServer, Redirect +from httpserver import HttpServer, Redirect import mailer from mailer import JobMailer from docparser import DocParser @@ -15,6 +15,9 @@ from printing import getPrinters, printFile import printing import printstatus +import derived +import uploader +import webupload import sys, pickle import html @@ -40,6 +43,8 @@ web_dir = os.path.join(base_dir, 'web') jobs = [] mailqueue = JobMailer(100) +uploadqueue = uploader.WebUploader() +derivedcache = derived.DerivedCache() # seed some 'system' accounts email_accounts = { 'accounts': 'Accounts', 'plain': 'printerface', 'transport': 'Transport'} @@ -68,20 +73,85 @@ def saveJob(queue, local, remote, control, data): with open(os.path.join(jobdir, subdir, jobname), "wb") as f: pickle.dump(d, f, protocol=PICKLE_PROTOCOL) + d['stat'] = file_stat(os.path.join(jobdir, subdir, jobname)) cleanJob(d) - try: - autoPrint(d) - except Exception: - # a printing problem (no lpr, no CUPS...) must not lose the job: it is already saved to disk, and - # not registering it here would hide it from the web interface until the next restart - traceback.print_exc(file=sys.stdout) + run_arrival_actions(d) jobs.insert(0, d) if len(jobs) > loadQty: jobs.pop() + derivedcache.dirty = True time.sleep(1) # hack for unique filenames - oh dear +# Job files that scan_for_jobs has decided about without loading them (older than the loaded history), and ones that +# would not load, by (size, mtime) so that a file that is then completed is tried again +_skipped = set() +_unreadable = {} + +# a job file younger than this (seconds) may still be being copied in +SETTLING = 2 + +def scan_for_jobs(): + """Pick up job pickles that have appeared in the job directory without arriving over LPD, such as copied in from + another instance, and treat each as a job that has just arrived: loaded into the history in its place (the + history is kept in file name order, newest first) and put through auto-print and auto-upload like any other. A + file older than everything in a full history is left alone. Returns the jobs found, oldest first.""" + known = set(j['name'] for j in jobs) + months = sorted((m for m in os.listdir(jobdir) if os.path.isdir(os.path.join(jobdir, m))), reverse=True)[:2] + found = [] + for month in months: + for name in sorted(os.listdir(os.path.join(jobdir, month))): + path = os.path.join(jobdir, month, name) + if not name.startswith('job-') or name in known or name in _skipped or not os.path.isfile(path): + continue + if jobs and len(jobs) >= loadQty and name < jobs[-1]['name']: + _skipped.add(name) + continue + try: + stat = file_stat(path) + if time.time() - os.stat(path).st_mtime < SETTLING or _unreadable.get(name) == stat: + continue # still being written, or already known to be unreadable at this size + with open(path, 'rb') as f: + job = load_job_pickle(f) + job['name'], job['stat'] = name, stat + cleanJob(job, derivedcache.lookup(name, stat)) + except Exception as e: + print('[control] cannot load new job file %s: %r' % (path, e)) + _unreadable[name] = stat + continue + _unreadable.pop(name, None) + index = next((i for i, j in enumerate(jobs) if j['name'] < name), len(jobs)) + jobs.insert(index, job) + if len(jobs) > loadQty: jobs.pop() + derivedcache.dirty = True + print('[control] new job file %s' % path) + found.append(job) + found.sort(key=lambda j: j['name']) + for job in found: + run_arrival_actions(job) + return found + +def file_stat(path): + """What says a job file is the one a cache entry was made from.""" + st = os.stat(path) + return (st.st_size, st.st_mtime_ns) + +def run_arrival_actions(job): + """What happens to a job when it arrives: auto-print, and auto-upload.""" + try: + autoPrint(job) + except Exception: + # a printing problem (no lpr, no CUPS...) must not lose the job: it is already saved to disk, and + # not registering it would hide it from the web interface until the next restart + traceback.print_exc(file=sys.stdout) + + try: + autoUpload(job) + except Exception: + # likewise: a conversion or queue problem must not lose the job. It shows on the Uploads page if it got that far + traceback.print_exc(file=sys.stdout) + def autoPrint(job): if job['autoprint']: printer = job['autoprint'] @@ -95,6 +165,19 @@ def autoPrint(job): # recorded in the print history; carry on with the other documents print( 'auto printing: Document %s NOT sent to printer %s: %s' % (doc, printer, e)) +def autoUpload(job): + """Queue the documents of a job of a kind listed under [Web] auto_types, if uploading is set up.""" + if not uploader.enabled() or job.get('templ') not in uploader.auto_types() or not job.get('groupfiles'): + return + try: + items = uploader.prepare(job, 'accounts', pdfdir) + except webupload.UploadError as e: + print('auto upload: %s NOT uploaded: %s' % (job['name'], e)) + return + for item in items: + uploadqueue.append(item) + print('auto upload: %d document(s) from %s queued' % (len(items), job['name'])) + def saveEmails(): with open(email_pickle, 'wb') as f: p = pickle.Pickler(f, protocol=PICKLE_PROTOCOL) @@ -133,20 +216,26 @@ def recover(): with open(p, "rb") as f: s = load_job_pickle(f) s['name'] = x; + s['stat'] = file_stat(p) jobs.append(s) except Exception as e: print("Cannot load {} caught {}".format(p, e)) if len(jobs) > loadQty: break if len(jobs) > loadQty: break - for j in jobs: - cleanJob(j) + outcomes = collections.Counter(cleanJob(j, derivedcache.lookup(j['name'], j['stat'])) for j in jobs) + print('[control] %d jobs: %d from the cache, %d redrawn, %d parsed' % (len(jobs), outcomes['hit'], outcomes['drawn'], outcomes['parsed'])) + if outcomes['drawn'] or outcomes['parsed'] or set(derivedcache.entries) != set(j['name'] for j in jobs): + derivedcache.dirty = True # re.ASCII: python 2 str patterns only ever treated ASCII as word/space characters, so any 8-bit # character in the print data becomes a space. Without it \x85 etc. count as whitespace and survive. control_char_re = re.compile(r'[^\w\s%s_\'=/]' % re.escape('.*+()-\\;:,#?%$^&!<>|`"'), re.ASCII) -def cleanJob(j): +def cleanJob(j, entry=None): + """Work out everything about a job that is not in its pickle. `entry` is what the derived cache holds for it, if + that is still good: then the parse is taken from it, and so are the PDFs if they are all still on disk. Returns + 'hit', 'drawn' (parsed pages from the cache, PDFs drawn again) or 'parsed' (all of it worked out).""" print(' recovering %s' % j['name']) # crucial to preserve \f (formfeed) in 'plain', as some parsers need it to @@ -172,9 +261,27 @@ def cleanJob(j): j['autofmt'] = formatter.getBestPageFormat(j['plain']) - (j['colouring'],j['parsed']) = mainparser.parse(j) - if not j['colouring']: del j['colouring'] + # the parser also returns the fields it found, for the debug page to colour in; that is bulky and only wanted + # there, so it isn't kept: debug() parses again + outcome = 'hit' if entry else 'parsed' + j['parsed'] = entry['parsed'] if entry else mainparser.parse(j)[1] + + register_accounts(j) + + if entry and all(os.path.exists(pdfdir + f) for f in entry['groupfiles'].values() if f): + (j['groupfiles'], j['groupkey'], j['render_stamp']) = (entry['groupfiles'], entry['groupkey'], entry['render_stamp']) + else: + draw(j) + if outcome == 'hit': outcome = 'drawn' + + # all done + j['autoprint'] = None + if j['doctype'] in config.get('Robot', 'auto_types').split(','): + j['autoprint'] = config.get('Robot', 'auto_printer') + return outcome +def register_accounts(j): + """Note the accounts a job is for, and a first line of their address, for the email address book.""" if j['parsed']: for y in j['parsed'].values(): for x in y: @@ -195,24 +302,16 @@ def cleanJob(j): print(" got email %s -> %s" % (acc, addr)) email_accounts[acc] = (addr), - # if colouring succeded, might be able to generate docs - if j.get('colouring'): +def draw(j): + """Make the PDFs for a job from its parsed pages (or, if nothing parsed, from the plain text).""" + # if parsing succeeded, might be able to generate docs + if j['parsed']: # protocol: PDF file names are dict values. keys are document # groups {('all'): p}, ('all') (j['groupfiles'], j['groupkey']) = formatter.format(j) - - #for f in j['groupfiles'].values(): - # from subprocess import call - # proc = ['convert','-size','150x150','%s[0]' % f, '%s.png' % f] - # print(proc) - # call(proc) else: (j['groupfiles'], j['groupkey']) = formatter.plainFormat(j) - - # all done - j['autoprint'] = None - if j['doctype'] in config.get('Robot', 'auto_types').split(','): - j['autoprint'] = config.get('Robot', 'auto_printer') + j['render_stamp'] = derivedcache.render_stamp def identify(j): types = { @@ -228,8 +327,9 @@ def identify(j): def home(query_string='', resp=None): email_fails = sum([1 for x in mailqueue.results if x['error']]) + upload_fails = sum([1 for x in uploadqueue.log.records if x['error']]) if uploader.enabled() else None account = sum([ 1 for k in email_accounts if len(email_addresses[k]) > 0 ]), len(email_accounts.keys()) - return template_lookup.get_template("/home.html").render(email_fails=email_fails, account=account), 'text/html' + return template_lookup.get_template("/home.html").render(email_fails=email_fails, upload_fails=upload_fails, account=account), 'text/html' def getrows_byslice(seq, rowlen): for start in range(0, len(seq), rowlen): @@ -311,6 +411,42 @@ def printed(query_string='', resp=None): rows = [dict(p=p, loaded=p.get('job') in loaded) for p in results[:SENT_SHOWN]] return ( template_lookup.get_template("/printed.html").render(rows=rows, total=len(results)), 'text/html') +def uploads(query_string='', resp=None): + results = uploadqueue.log.records # newest first + loaded = set(j['name'] for j in jobs) + rows = [dict(u=u, loaded=u.get('job') in loaded) for u in results[:SENT_SHOWN]] + return ( template_lookup.get_template("/uploads.html").render(rows=rows, total=len(results), waiting=uploadqueue.queue.qsize()), 'text/html') + +def regenerate_stationery(): + """Draw the PDFs again, under today's stationery, for every loaded job drawn under older stationery. The jobs + are not parsed again. Returns how many were redrawn.""" + stale = derivedcache.stale(jobs) + for j in stale: + draw(j) + if stale: + derivedcache.dirty = True + return len(stale) + +def settings_stationery(query_string='', postreq=None, resp=None): + """How many loaded jobs have PDFs drawn under older stationery (a change to stationary.py, or to the company + details or logos under [Printing]), with the button that draws them again. It blocks the server while it works, + about a second for every few hundred jobs, so it is an admin action rather than something done on its own.""" + if postreq is not None: + n = regenerate_stationery() if 'regenerate' in postreq else 0 + return Redirect('/settings/stationery?' + urllib.parse.urlencode({'redrawn': n})) + try: + redrawn = int(query_string.get('redrawn', [''])[0]) + except ValueError: + redrawn = None + return ( template_lookup.get_template("/settings_stationery.html").render(stale=len(derivedcache.stale(jobs)), total=len(jobs), redrawn=redrawn), 'text/html') + +def settings_web(query_string='', resp=None): + """Where documents are uploaded to. Read only: it is set under [Web] in email.cfg. The API key is never shown, only + its last three characters so that the right one can be recognised.""" + base_url, api_key = uploader.settings() + return ( template_lookup.get_template("/settings_web.html").render(base_url=base_url, key=uploader.mask_key(api_key), + enabled=uploader.enabled(), auto_types=uploader.auto_types(), waiting=uploadqueue.queue.qsize(), fails=sum(1 for x in uploadqueue.log.records if x['error'])), 'text/html') + def settings_email(query_string='', postreq=None, resp=None): """The address book. Adding and removing a contact change it, so they only happen on a POST, which then redirects back here: a refresh (or a bookmarked URL) shows the list and never repeats the change.""" @@ -467,13 +603,33 @@ def pdf(query_string=dict(), postreq=None, resp=None): else: email_error = "Oh snap! Some fields missing or incomplete!" typed = dict(subject=email_subject, body=email_body, ticked=addresses) + elif postreq is not None and params.get('action', [''])[0] == 'upload': + try: + if not uploader.enabled(): + raise webupload.UploadError('Uploading to the website is not set up: see [Web] in email.cfg') + items = uploader.prepare(job, key, pdfdir) + if not items: + raise webupload.UploadError('There is nothing to upload for %s' % key) + for item in items: + uploadqueue.append(item) + return Redirect('/pdf?' + urllib.parse.urlencode({'name': job['name'], 'key': key, 'uploading': len(items)})) + except Exception as e: + if not isinstance(e, webupload.UploadError): + traceback.print_exc(file=sys.stdout) + email_error = 'Not uploaded. %s' % html.escape(str(e) or 'The upload queue is full.') elif postreq is None: # a redirect from a send or a print lands here; the note only says what happened try: queued = int(query_string.get('queued', ['0'])[0]) except ValueError: queued = 0 - if queued: + try: + uploading = int(query_string.get('uploading', ['0'])[0]) + except ValueError: + uploading = 0 + if uploading: + email_outcome = 'Queued %d document%s for the website. %s listed under "Uploaded from this job" once done.' % (uploading, '' if uploading == 1 else 's', 'It is' if uploading == 1 else 'They are') + elif queued: email_outcome = 'Queued the email to %d recipient%s. It is listed under "Sent from this job" once it has gone.' % (queued, '' if queued == 1 else 's') elif query_string.get('printed'): email_outcome = 'Sent the document to printer %s.' % html.escape(query_string['printed'][0]) @@ -495,6 +651,9 @@ def pdf(query_string=dict(), postreq=None, resp=None): sent_from_this_job = mailer.sent_from_job(mailqueue.results, job['name']) # and what was sent to a printer from it, with the CUPS request ids printed_from_this_job = printing.printlog.for_job(job['name']) + # and what was uploaded to the website + uploaded_from_this_job = uploadqueue.log.for_job(job['name']) + can_upload = uploader.enabled() and job.get('templ') in ('invoice', 'crednote', 'statement') # what the editor's preview filter should be set to so that it shows this document if template_kind == emailtemplates.DEFAULT: @@ -505,7 +664,7 @@ def pdf(query_string=dict(), postreq=None, resp=None): template_docnum = pages[0].get('doc_num', '').strip() return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, email_subject_default=email_subject_default, ticked=typed['ticked'] if typed else None, - template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, sent_from_this_job=sent_from_this_job, printed_from_this_job=printed_from_this_job, + template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, sent_from_this_job=sent_from_this_job, printed_from_this_job=printed_from_this_job, uploaded_from_this_job=uploaded_from_this_job, can_upload=can_upload, email_body_url='/email_body?' + urllib.parse.urlencode({'name': job['name'], 'key': key}), email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html') @@ -565,7 +724,7 @@ def debug(query_string=dict(), resp=None): pformatted = json.dumps(job.get('parsed'), indent=4) - colouring = job.get('colouring', []) + colouring = mainparser.parse(job)[0] or [] lines = split_lines(job['plain']) (rows, cols) = (len(lines), max([len(line) for line in lines])) @@ -621,13 +780,57 @@ def htmlcol(rgb): '/pdf_file': pdf_file, '/sent':sent, '/printed':printed, + '/uploads':uploads, '/print' : printfn, '/plaintext':plain, '/settings/email':settings_email, '/settings/templates':settings_templates, + '/settings/web':settings_web, + '/settings/stationery':settings_stationery, '/email_body':email_body } +async def serve(): + """Run the LPD receiver and the web server on one event loop until interrupted.""" + mailqueue.start() + uploadqueue.start() + lpd = await LpdServer(saveJob, ip='', port=int(config.get('Main', 'lpd_port'))).start() + http = await HttpServer(path_handlers, web_dir, port=int(config.get('Main', 'http_port'))).start() + stopping = asyncio.Event() + for sig in (signal.SIGINT, signal.SIGTERM): + try: + asyncio.get_running_loop().add_signal_handler(sig, stopping.set) + except NotImplementedError: + pass # windows: Ctrl+C is raised as KeyboardInterrupt instead + try: + while not stopping.is_set(): + try: + await asyncio.wait_for(stopping.wait(), 10) + except asyncio.TimeoutError: + pass + print('[control] poll %s' % str(datetime.now())) + try: + scan_for_jobs() + except Exception: + traceback.print_exc(file=sys.stdout) + printing.printlog.flush() + uploadqueue.log.flush() + derivedcache.flush(jobs) + sys.stdout.flush() + print("Shutting down.") + except BaseException as e: + print("Terminating: Unexpected error: %s" % repr(e)) + sys.stdout.flush() + raise + finally: + printing.printlog.flush() + await uploadqueue.close() + uploadqueue.log.flush() + derivedcache.flush(jobs, force=True) + await lpd.close() + await http.close() + await mailqueue.close() + if __name__=="__main__": # launch the server on the specified port for x in [jobdir, pdfdir]: @@ -635,20 +838,7 @@ def htmlcol(rgb): recover() - s = LpdServer(saveJob, ip='', port=int(config.get('Main', 'lpd_port'))) - ToyHttpServer(port=int(config.get('Main', 'http_port')), pathhandlers=path_handlers, webroot=web_dir) try: - while True: - asyncore.loop(timeout=1, count=10) - print('[control] poll %s' % str(datetime.now())) - printing.printlog.flush() - sys.stdout.flush() - + asyncio.run(serve()) except KeyboardInterrupt: print("Crtl+C pressed. Shutting down.") - printing.printlog.flush() - except: - print("Terminating: Unexpected error: %s" % sys.exc_info()[0]) - sys.stdout.flush() - raise - diff --git a/printing.py b/printing.py index 66ed047..5b1b327 100644 --- a/printing.py +++ b/printing.py @@ -24,12 +24,11 @@ class PrintError(Exception): class PrintLog(object): """What was sent to CUPS, newest first, one record per document: the job and key it came from, the printer, and the CUPS request id (the name lpstat knows the job by) or the error. Kept in a side pickle, like the sent - emails, so the job pickles are never rewritten. The newest `limit` records are kept (the same setting as the - email history) and the file is only written, by flush(), when something changed.""" + emails, so the job pickles are never rewritten. The newest `limit` records are kept ([Printing] result_count) and the file is only written, by flush(), when something changed.""" def __init__(self, path=None, limit=None): self.path = path - self.limit = limit if limit is not None else config.getint('Gmail', 'result_count') + self.limit = limit if limit is not None else config.getint('Printing', 'result_count') self.records = [] self.dirty = False if path: diff --git a/requirements.txt b/requirements.txt index ce372f6..8c8ccd0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,4 +2,6 @@ Mako>=1.2.2 MarkupSafe>=2.0 reportlab>=4.0,<6 pillow>=9.0 +aiohttp>=3.9,<4 pytz>=2023.3 +pypdf>=4,<7 diff --git a/test_derived.py b/test_derived.py new file mode 100644 index 0000000..1491c99 --- /dev/null +++ b/test_derived.py @@ -0,0 +1,102 @@ +# The derived cache on its own: when an entry is trusted, how the file is written, what the stamps follow. +import os +import pickle +import tempfile +import unittest + +import derived +from derived import DerivedCache +from settings import config + + +def job(name, **kw): + j = dict(name=name, stat=(10, 20), parsed={'ACC': [{'doc_num': '1'}]}, groupkey=('Group',), groupfiles={('ACC',): '2026/ACC/%s-ACC.pdf' % name}, render_stamp='r1') + j.update(kw) + return j + + +class TestDerivedCache(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + self.path = os.path.join(self.dir.name, 'derived.pickle') + + def written(self, jobs, **kw): + c = DerivedCache(self.path) + c.dirty = True + self.assertTrue(c.flush(jobs, **kw)) + return DerivedCache(self.path) + + def test_round_trip_and_what_makes_an_entry_good(self): + c = self.written([job('job-1')], force=True) + e = c.lookup('job-1', (10, 20)) + self.assertEqual(({'ACC': [{'doc_num': '1'}]}, ('Group',), {('ACC',): '2026/ACC/job-1-ACC.pdf'}, 'r1'), + (e['parsed'], e['groupkey'], e['groupfiles'], e['render_stamp'])) + self.assertIsNone(c.lookup('job-1', (11, 20))) # the file changed size + self.assertIsNone(c.lookup('job-1', (10, 21))) # or was replaced + self.assertIsNone(c.lookup('job-2', (10, 20))) # never cached + c.entries['job-1']['parse_stamp'] = 'older parser' + self.assertIsNone(c.lookup('job-1', (10, 20))) + + def test_only_the_jobs_still_loaded_are_written(self): + self.written([job('job-1'), job('job-2')], force=True) + c = self.written([job('job-2'), job('job-3')], force=True) # job-1 left the history, job-3 arrived + self.assertEqual({'job-2', 'job-3'}, set(c.entries)) + c = self.written([job('job-9', stat=None)], force=True) # a job with no file to vouch for it is not cached + self.assertEqual(set(), set(c.entries)) + + def test_flush_waits_unless_forced_and_only_when_dirty(self): + c = DerivedCache(self.path) + self.assertFalse(c.flush([job('a')])) # nothing changed + c.dirty = True + self.assertTrue(c.flush([job('a')])) # the first write is not delayed + c.dirty = True + self.assertFalse(c.flush([job('a'), job('b')])) # too soon + self.assertTrue(c.dirty) + self.assertTrue(c.flush([job('a'), job('b')], force=True)) + self.assertFalse(c.dirty) + self.assertFalse(os.path.exists(self.path + '.tmp')) + + def test_an_unreadable_or_foreign_file_means_a_cold_start(self): + for content in (b'', b'not a pickle', pickle.dumps({'format': 99, 'entries': {'x': 1}}), pickle.dumps([1, 2])): + with open(self.path, 'wb') as f: + f.write(content) + self.assertEqual({}, DerivedCache(self.path).entries) + + def test_a_failed_write_is_survived(self): + c = DerivedCache(os.path.join(self.dir.name, 'missing-dir', 'derived.pickle')) + c.dirty = True + self.assertFalse(c.flush([job('a')], force=True)) + self.assertTrue(c.dirty) # try again next time + + def test_stale_counts_jobs_drawn_under_other_stationery(self): + c = DerivedCache(self.path) + jobs = [job('a', render_stamp=c.render_stamp), job('b', render_stamp='old'), job('c', render_stamp=None)] + self.assertEqual(['b', 'c'], [j['name'] for j in c.stale(jobs)]) + + +class TestStamps(unittest.TestCase): + def test_render_stamp_follows_the_company_details_and_logos(self): + before = derived.render_stamp() + self.assertEqual(before, derived.render_stamp()) + old = config.get('Printing', 'terms') + config.set('Printing', 'terms', old + ' and more') + self.addCleanup(config.set, 'Printing', 'terms', old) + self.assertNotEqual(before, derived.render_stamp()) + config.set('Printing', 'terms', old) + with tempfile.NamedTemporaryFile(suffix='.jpg') as logo: + config.set('Printing', 'logo2', logo.name) + self.addCleanup(config.set, 'Printing', 'logo2', '') + with_logo = derived.render_stamp() + self.assertNotEqual(before, with_logo) + logo.write(b'changed') + logo.flush() + self.assertNotEqual(with_logo, derived.render_stamp()) + + def test_parse_stamp_is_steady(self): + self.assertEqual(derived.parse_stamp(), derived.parse_stamp()) + self.assertNotEqual(derived.parse_stamp(), derived.render_stamp()) + + +if __name__ == '__main__': + unittest.main() diff --git a/test_integration.py b/test_integration.py index c245b70..909cbae 100644 --- a/test_integration.py +++ b/test_integration.py @@ -1,6 +1,6 @@ # End to end tests: a real RFC 1179 client -> LpdServer -> main.saveJob -> parse -> PDF, then read back # over HTTP. Runs against a throwaway PRINTERFACE_HOME, never ~/printerface. -import asyncore +import asyncio import http.client import io import re @@ -21,10 +21,12 @@ import mailer import printing import printstatus +import derived +import uploader import emailtemplates from stationary import DocFormatter from lpdserver import LpdServer -from httpserver import ToyHttpServer +from httpserver import HttpServer from textutil import split_lines def put(lines, row, col, text): @@ -32,7 +34,7 @@ def put(lines, row, col, text): line = lines[row + i] lines[row + i] = line[:col] + part + line[col + len(part):] -def make_invoice(doc_num='12345', acc='ACC001', pages=2, doc_nums=None, totals=None): +def make_invoice(doc_num='12345', acc='ACC001', pages=2, doc_nums=None, totals=None, net=None, vat=None): """A synthetic Invoice print: 48 blank lines, then 48 lines per page. Each page ends in a form feed, and the totals carry an 8-bit pound sign as the Windows print driver sends it. By default every page is part of invoice doc_num; doc_nums gives each page its own invoice (and totals its own amount).""" @@ -51,6 +53,9 @@ def make_invoice(doc_num='12345', acc='ACC001', pages=2, doc_nums=None, totals=N put(lines, base + 19, 19, 'BAUCHET Customer Label\nDRAPPIER Carte D\'Or') put(lines, base + 19, 55, '12\n6') put(lines, base + 42, 89, totals[p] if totals else '\xa3123.45') + if net: + put(lines, base + 37, 89, net) + put(lines, base + 39, 89, vat) lines[base + 47] = lines[base + 47][:100] + '\x0c' return '\r\n'.join(lines) + '\r\n' @@ -73,13 +78,24 @@ def mailer_results(): return main.mailqueue.results class ServerThread(threading.Thread): + """An event loop in a thread, so that the servers run as they do in main.py (handlers and the LPD receiver + on one loop thread) while the tests, in this thread, are their clients.""" def __init__(self): threading.Thread.__init__(self) self.daemon = True - self.running = True + self.loop = asyncio.new_event_loop() + def run(self): - while self.running: - asyncore.loop(timeout=0.05, count=1) + asyncio.set_event_loop(self.loop) + self.loop.run_forever() + + def call(self, coro): + return asyncio.run_coroutine_threadsafe(coro, self.loop).result(30) + + def stop(self): + self.loop.call_soon_threadsafe(self.loop.stop) + self.join() + self.loop.close() class TestPrinterface(unittest.TestCase): @classmethod @@ -92,6 +108,8 @@ def setUpClass(cls): main.pdfdir = os.path.join(cls.home, 'data', 'pdf') + os.sep main.formatter = DocFormatter(main.pdfdir) mailer.pickle_file = os.path.join(cls.home, 'mailer.pickle') + cls.old_derived, main.derivedcache = main.derivedcache, derived.DerivedCache(os.path.join(cls.home, 'derived.pickle')) + cls.old_uploadlog, main.uploadqueue.log = main.uploadqueue.log, uploader.UploadLog(os.path.join(cls.home, 'upload.pickle')) cls.old_printlog, printing.printlog = printing.printlog, printing.PrintLog(os.path.join(cls.home, 'printer.pickle')) cls.old_user_dir, emailtemplates.USER_DIR = emailtemplates.USER_DIR, os.path.join(cls.home, 'templates') for x in [main.jobdir, main.pdfdir]: @@ -103,22 +121,23 @@ def setUpClass(cls): # likewise the Printers page: lpstat is only ever the canned text, never the machine's own CUPS cls.lpstat_patch = mock.patch.object(printstatus, 'run_lpstat', return_value=printstatus.SAMPLE) cls.lpstat_patch.start() - cls.lpd = LpdServer(main.saveJob, ip='127.0.0.1', port=0) - cls.http = ToyHttpServer(ip='127.0.0.1', port=0, pathhandlers=main.path_handlers, webroot=main.web_dir) - cls.lpd_port = cls.lpd.socket.getsockname()[1] - cls.http_port = cls.http.socket.getsockname()[1] cls.thread = ServerThread() cls.thread.start() + cls.lpd = cls.thread.call(LpdServer(main.saveJob, ip='127.0.0.1', port=0).start()) + cls.http = cls.thread.call(HttpServer(main.path_handlers, main.web_dir, ip='127.0.0.1', port=0).start()) + cls.lpd_port = cls.lpd.port + cls.http_port = cls.http.port @classmethod def tearDownClass(cls): - cls.thread.running = False - cls.thread.join() - cls.lpd.close() - cls.http.close() + cls.thread.call(cls.lpd.close()) + cls.thread.call(cls.http.close()) + cls.thread.stop() cls.print_patch.stop() cls.lpstat_patch.stop() printing.printlog = cls.old_printlog + main.uploadqueue.log = cls.old_uploadlog + main.derivedcache = cls.old_derived emailtemplates.USER_DIR = cls.old_user_dir shutil.rmtree(cls.home, ignore_errors=True) @@ -718,6 +737,268 @@ def test_printing_is_a_post_that_redirects(self): self.assertEqual(200, r.status) printed.assert_called_once() + def test_uploading_to_the_website_is_a_post_that_queues_every_document_in_the_pdf(self): + sent = [] + async def start(): + main.uploadqueue.transport = lambda item, base, key: (sent.append((item, base, key)) or (201, '{}')) + main.uploadqueue.start() + j = self.send_invoice(pages=2, doc_nums=['501', '502'], totals=['72.00', '48.00'], net='60.00', vat='12.00') + # not configured: no button, and a POST is refused with a reason + self.assertNotIn(b'Upload to website', self.get('/pdf?name=%s&key=ACC001' % j['name'])[1]) + r, body = self.post('/pdf', name=j['name'], key='ACC001', action='upload') + self.assertEqual(200, r.status) + self.assertIn(b'not set up', body) + with mock.patch.object(uploader, 'settings', lambda: ('https://stage.example/', 'tok')): + self.thread.call(start()) + try: + self.assertIn(b'Upload to website', self.get('/pdf?name=%s&key=ACC001' % j['name'])[1]) + r, data = self.post('/pdf', name=j['name'], key='ACC001', action='upload') + self.assertEqual(303, r.status) + self.assertEqual('/pdf?name=%s&key=ACC001&uploading=2' % j['name'], r.getheader('Location')) + deadline = time.time() + 10 + while len(main.uploadqueue.log.for_job(j['name'])) < 2 and time.time() < deadline: + time.sleep(0.05) + self.assertEqual(['502', '501'], [rec['docnum'] for rec in main.uploadqueue.log.for_job(j['name'])]) + self.assertEqual({('https://stage.example/', 'tok')}, {(b, k) for _, b, k in sent}) + first = json.loads(sent[0][0]['payload']) + self.assertEqual(('501', '60.00', '72.00'), (first['docnum'], first['total_net'], first['total_gross'])) + from pypdf import PdfReader + self.assertEqual([1, 1], [len(PdfReader(io.BytesIO(i['pdf'])).pages) for i, _, _ in sent]) # one page each + body = self.get('/pdf?name=%s&key=ACC001&uploading=2' % j['name'])[1] + self.assertIn(b'Uploaded from this job', body) + self.assertIn(b'>501 / ACC001', body) + self.assertIn(b'Queued 2 documents for the website', body) + # other types of document have no button + d = self.send_invoice(jtype='Delvnote') + self.assertNotIn(b'Upload to website', self.get('/pdf?name=%s&key=ACC001' % d['name'])[1]) + finally: + self.thread.call(main.uploadqueue.close()) + + def test_web_uploads_settings_and_uploads_pages(self): + from unittest import mock + r, body = self.get('/settings/web') + self.assertEqual(200, r.status) + self.assertIn(b'not set', body) + self.assertIn(b'Web Uploads', self.get('/home')[1]) # in the Settings menu + self.assertIn(b'href="/uploads"', self.get('/home')[1]) + with mock.patch.object(uploader, 'settings', lambda: ('https://stage.example/', 'abcdefghijklmnopXYZ')): + body = self.get('/settings/web')[1] + self.assertIn(b'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
  • 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 + +

    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 + +

    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: + + + % for row in rows: + <% u = row['u'] %> + % if u['error']: + + % else: + + % endif + + + + % endfor +
    DocumentTypeResultProblems?
    + % 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}
    + % 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)