diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml
index 194d077..fb06496 100644
--- a/.github/workflows/docker-image.yml
+++ b/.github/workflows/docker-image.yml
@@ -10,6 +10,6 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v4
- name: Build the Docker image
run: docker build . --file Dockerfile --tag pritnerface:$(date +%s)
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
new file mode 100644
index 0000000..7291780
--- /dev/null
+++ b/.github/workflows/tests.yml
@@ -0,0 +1,18 @@
+name: Tests
+
+on:
+ push:
+ branches: [ master, py311 ]
+ pull_request:
+ branches: [ master ]
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+ - run: pip install -r requirements.txt
+ - run: python -m unittest discover --pattern=*.py
diff --git a/.gitignore b/.gitignore
index 61c89c6..4c5c37c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
*.py[cod]
venv
+.venv
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 1e7273c..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-language: python
-python:
- - "2.7"
-install: "pip install -r requirements.txt"
-
-script:
- - python -m unittest discover --pattern=*.py
diff --git a/Dockerfile b/Dockerfile
index a81998c..7eb9964 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,15 +1,11 @@
-FROM python:2.7-alpine as builder
+# asyncore/asynchat (used by lpdserver.py and httpserver.py) were removed in python 3.12
+FROM python:3.11-slim
MAINTAINER chris@shucksmith.co.uk
-# add the dev dependencies
-RUN apk add --no-cache python make gcc g++ libc-dev
-
-# use cached layer for node modules
COPY requirements.txt /app/
WORKDIR /app/
-RUN pip install -r requirements.txt
-# RUN python -m unittest
+RUN pip install --no-cache-dir -r requirements.txt
RUN echo $HOME
VOLUME ["/root/printerface"]
@@ -21,4 +17,3 @@ COPY . /app/
WORKDIR /app
RUN python -m unittest discover --pattern=*.py
-# RUN ls -la /app/
diff --git a/README.md b/README.md
index ca1e57c..ba00282 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,5 @@
# printerface
-[](https://travis-ci.org/shuckc/printerface) [](https://opensource.org/licenses/BSD-3-Clause)
+[](https://github.com/shuckc/printerface/actions/workflows/tests.yml) [](https://opensource.org/licenses/BSD-3-Clause)
Printerface is an application that acts as a virtual printer, accepting LPD (Line Printer Daemon) documents and parses/renders them to PDF files. Documents are stored, searchable to users on your LAN using the build in web interface. Results can be browsed, emailed and automatically printed to modern network printers (anything with a CUPS/ppd driver). It has been used in production for over eight years by customers with legacy stock control/management systems, alarm pannels and fire pannels. Tea Engineering Ltd. provides commercial support and custom/integration services in the UK.
@@ -27,15 +27,75 @@ The following will checkout the source code, build a docker image and start an i
* `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` Linux printing with CUPS via. command line
+* `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
+* `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
+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).
Requirements are specified in requirements.txt
Unit tests run during `docker build` or with:
- $ python -m unittest discover --pattern=*.py
+ $ python3.11 -m unittest discover --pattern=*.py
Uses python asyncore/smtp, 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
+against a copy of the data on other ports (`lpd_port` and `http_port` in `defaults.cfg`/`email.cfg`).
+
+### Email templates
+
+The text offered when emailing a document comes from a template per document type: `invoice`, `purchase` and
+`statement`, and `default` for every other kind of document (delivery notes, credit notes, reports...).
+Templates are Mako files.
+`~/printerface/templates/.mako` is used if it exists, otherwise the copy shipped in `templates/` in the
+source, so an install that never customises a template follows the repository. Edit them under
+Settings > Email Templates, which previews the result against a real document (leave the filter blank for the
+newest, or enter a document number or account).
+
+The first line of the rendered template is the email's subject and the rest is the body (blank lines between
+them don't count), so subjects can be generated from the document like the rest of the text, for example
+`Invoice ${doc.ourref} from ${company.name}`. Both are filled into the compose form.
+
+The default template has `${email.name}`, `${email.address}`, `${job.name}`, `${job.doctype}`, `${job.host}` and
+`${company.name}`, `${company.email}`, `${company.website}`, but no document fields, since printerface doesn't read
+the contents of those documents. Earlier releases kept one email
+text in `email.pickle`; if there is one and no `default.mako` yet, it is saved as `~/printerface/templates/default.mako`
+the first time this release starts (once only: reverting to the shipped default isn't undone by a restart).
+
+In the email compose form, ticking or unticking a contact re-renders the suggested text for the chosen recipients
+(`${email.name}` and `${email.address}` follow the ticks). Text you have already edited is kept, with a notice
+offering to replace it. The form's script is `web/js/compose.js`; `test_compose.js` tests it with node and is skipped
+where node isn't installed.
+
+The other templates also have: `${doc.}` (the document: `doc.ourref`, `doc.doc_num`, `doc.accno`, `doc.tot_due`,
+`doc.customer`, ... - the editor lists them), `${email.name}`, `${email.address}`, `${job.name}`,
+`${company.name}`. If an account has several documents in one print run `doc` is the last, and `all` describes them together:
+`${all.numbers}` writes the document numbers as operations do in a subject (`336806/7`, from the first digit
+that differs from the first number), `${all.list}` as words (`336806 and 336807`), `${all.total}` is the sum
+(`all.tot_due`, `all.tot_net`, `all.tot_vat` likewise), and `${all.count}`, `${all.many}` (true for several)
+and `${all.s}` (`s` for several) help with wording, for example `New Invoice${all.s} ${all.numbers}`. Use
+`% for d in docs:` ... `% endfor` to visit each document. `% if doc.field:` / `% else:` / `% endif` and `##` comments work too.
+
+The web interface has no authentication and Mako can run arbitrary python, so the editor only accepts that
+subset (no calls, operators, `<% %>` blocks or names starting with an underscore; see `emailtemplates.validate`).
+Files placed in `~/printerface/templates` by hand are trusted, but one that no longer renders falls back to the
+shipped template with a warning.
+
+`tools/compare_corpus.py` and `tools/replay_corpus.py` check a port or upgrade against real data: given a copy of
+`data/pickle` and `data/pdf` from a running system, the first re-renders every job and compares the PDF text
+with the PDFs the previous release produced, the second replays every stored payload through the LPD server.
+`tools/compare_http.py` compares the read-only `/recent`, `/job` and `/raw` API of two running instances over the
+jobs they both hold, for checking a candidate against the live release.
+
+Jobs and the address book are stored as pickles. They are written with pickle protocol 2 (see
+`PICKLE_PROTOCOL` in `textutil.py`) so that python 2.7 can still read them, and python 2 pickles from earlier
+releases are converted when loaded. Print data is treated as latin-1 throughout, one byte per column.
+
### Detailed docker deploy
The Dockfile fully describes how to build a containerised printerface, including dependancies.
@@ -66,10 +126,12 @@ On windows you may wish to mount the job storage directory externally, as follow
### From-scratch userland python install
$ mkdir ~/opt
- $ wget https://www.python.org/ftp/python/2.7.18/Python-2.7.18.tgz
- $ tar -xzf Python-2.7.18.tgz
- $ cd Python-2.7.18
+ $ wget https://www.python.org/ftp/python/3.11.10/Python-3.11.10.tgz
+ $ tar -xzf Python-3.11.10.tgz
+ $ cd Python-3.11.10
$ ./configure prefix=$HOME/opt --with-ensurepip=install
$ make && make install
- $ ~/opt/bin/pip install -r ~/repos/printerface/requirements.txt
+ $ ~/opt/bin/python3.11 -m pip install -r ~/repos/printerface/requirements.txt
+On older distributions pip has no prebuilt wheels for `pillow`, so you also need a compiler and the
+`libjpeg` and `zlib` development headers installed to build it.
diff --git a/datamine.py b/datamine.py
index 3a07bda..5585433 100644
--- a/datamine.py
+++ b/datamine.py
@@ -1,19 +1,18 @@
-#!/usr/bin/env python2.7
-from __future__ import with_statement
-
+#!/usr/bin/env python3.11
from datetime import datetime
from docparser import DocParser
from printing import getPrinters, printFile
+from settings import HOME
+from textutil import load_job_pickle, split_lines
import sys
import pickle
import os
import re
-from StringIO import StringIO
import collections
import traceback
-data_dir = os.path.expanduser("~/printerface/data/")
+data_dir = os.path.join(HOME, "data")
jobdir = os.path.join(data_dir, 'pickle')
jobs = []
@@ -29,8 +28,8 @@ def recover(invf, invl):
for x in reversed(sorted( os.listdir(os.path.join(jobdir, yyyymmdir)) )):
p = os.path.join(jobdir, yyyymmdir, x)
if not os.path.isfile(p): continue
- with file(p, "rb") as f:
- s = pickle.load(f)
+ with open(p, "rb") as f:
+ s = load_job_pickle(f)
s['name'] = x;
jobs.append(s)
print(' recovering %s %s' % (p, s['name']))
@@ -38,7 +37,7 @@ def recover(invf, invl):
if len(jobs) > loadQty: break
if len(jobs) > loadQty: break
-control_char_re = re.compile('[^\w\s%s_\'=/]' % re.escape('.*+()-\\;:,#?%$^&!<>|`"'))
+control_char_re = re.compile(r'[^\w\s%s_\'=/]' % re.escape('.*+()-\\;:,#?%$^&!<>|`"'), re.ASCII)
def cleanJob(j, invf, invl):
@@ -67,9 +66,9 @@ def handlePr1(j, dest=os.path.expanduser('/tmp/pr1')):
suppliers = collections.defaultdict(int)
szs = collections.defaultdict(int)
with open(dest, 'w') as f:
- for part in filter(None, j['plain'].split("\f")):
+ for part in [p for p in j['plain'].split("\f") if p]:
if len(part.strip()) > 0:
- for l in part.splitlines():
+ for l in split_lines(part):
if len(l.strip()) == 0: continue
if 'STOCK MANAGEMENT' in l: continue
if '=' * 46 in l: continue
@@ -87,22 +86,22 @@ def handlePr1(j, dest=os.path.expanduser('/tmp/pr1')):
suppliers[sup] += 1
sz = l[48:52]
szs[sz] += 1
- print l
+ print(l)
# l can spill over 130 characters if last column is negative (1)
if len(l) > 129: l = l[0:129]
f.write(l)
f.write('\n')
- print groups
- print suppliers
- print szs
+ print(groups)
+ print(suppliers)
+ print(szs)
with open(os.path.expanduser('/tmp/groups'), 'w') as f:
- for k,v in groups.iteritems():
+ for k,v in groups.items():
f.write("%3d %-40s\n" % (k, v))
with open(os.path.expanduser('/tmp/sizes'), 'w') as f:
- for k,v in szs.iteritems():
+ for k,v in szs.items():
f.write("%s\n" % k)
with open(os.path.expanduser('/tmp/suppliers'), 'w') as f:
- for k,v in suppliers.iteritems():
+ for k,v in suppliers.items():
f.write("%s\n" % k)
def handleInv(j, invf, invl):
@@ -113,7 +112,7 @@ def handleInv(j, invf, invl):
# doc_num ourref accno custref salesperson ord_date tot_net tot_due
# layout - lines
# doc_num prod_code prod_desc prod_qty prod_price prod_unit prod_net
- for acc,pages in j['parsed'].iteritems():
+ for acc,pages in j['parsed'].items():
for page in pages:
if len(page['tot_due'].strip()) > 0:
invf.write("%6s %6s %7s %-12s %-20s %8s %10s %10s\n" % (page['doc_num'], page['ourref'], page['accno'], page['custref'],
@@ -148,4 +147,4 @@ def identify(j):
with open(os.path.expanduser('/tmp/inv'), 'w') as f:
with open(os.path.expanduser('/tmp/invline'), 'w') as l:
recover(f, l)
- print 'done'
+ print('done')
diff --git a/docparser.py b/docparser.py
index 9457730..135a161 100755
--- a/docparser.py
+++ b/docparser.py
@@ -1,26 +1,26 @@
-#!/usr/bin/python
+#!/usr/bin/env python3
import sys
import os
import itertools
import collections
-from StringIO import StringIO
+from textutil import split_lines
jobdir = os.path.expanduser("~/printerface/pickle/")
import colorsys
N=20
HSV_tuples = [(x*1.0/N, 0.5, 0.8) for x in range(N)]
-colours = itertools.cycle(map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples))
+colours = itertools.cycle([colorsys.hsv_to_rgb(*x) for x in HSV_tuples])
def field(col, r, c, w=10, h=1, t='??'):
- col.append(dict(r=r,c=c,w=w,h=h,t=t,line=r,rgb=colours.next()))
+ col.append(dict(r=r,c=c,w=w,h=h,t=t,line=r,rgb=next(colours)))
class DocParser(object):
def parse(self, job):
if job['templ']:
mname = 'extract' + job['templ'].title()
- lines = job['plain'].splitlines()
+ lines = split_lines(job['plain'])
dims = (len(lines), max([len(line) for line in lines]))
if hasattr(self, mname):
fields, page_data = getattr(self, mname)(job, lines, dims)
@@ -33,11 +33,12 @@ def parse(self, job):
def extractCrednote(self, job, lines, dims):
return self.extractInvoice(job, lines, dims)
- def extractInvoice(self, job, lines, (rows,cols)):
+ def extractInvoice(self, job, lines, dims):
+ (rows, cols) = dims
all_fields = []
page_data = collections.OrderedDict()
- pages = (rows-48)/48
+ pages = (rows-48)//48
for page in range(pages):
line =(page+1) * 48
fs = []
@@ -83,11 +84,12 @@ def extractInvoice(self, job, lines, (rows,cols)):
return (all_fields, page_data)
- def extractDelnote(self, job, lines, (rows,cols)):
+ def extractDelnote(self, job, lines, dims):
+ (rows, cols) = dims
all_fields = []
page_data = collections.OrderedDict()
- pages = (rows-48)/48
+ pages = (rows-48)//48
for page in range(pages):
line =(page+1) * 48
fs = []
@@ -122,13 +124,14 @@ def extractDelnote(self, job, lines, (rows,cols)):
return (all_fields, page_data)
- def extractStatement(self, job, lines, (rows,cols)):
+ def extractStatement(self, job, lines, dims):
+ (rows, cols) = dims
# any lines after line containing 'PRINT STATEMENT SUMMARY' should be ignored
rows = min([rows] + [lnum for (lnum,text) in enumerate(lines) if 'PRINT STATEMENT SUMMARY' in text])
all_fields = []
page_data = collections.OrderedDict()
- pages = (rows-51)/51
+ pages = (rows-51)//51
for page in range(pages):
line =(page+1) * 51
fs = []
@@ -169,11 +172,12 @@ def extractStatement(self, job, lines, (rows,cols)):
return (all_fields, page_data)
- def extractPurchase(self, job, lines, (rows,cols)):
+ def extractPurchase(self, job, lines, dims):
+ (rows, cols) = dims
all_fields = []
page_data = collections.OrderedDict()
- pages = (rows-48)/48
+ pages = (rows-48)//48
for page in range(pages):
line =(page+1) * 48
fs = []
@@ -204,11 +208,12 @@ def extractPurchase(self, job, lines, (rows,cols)):
return (all_fields, page_data)
- def extractRemittance(self, job, lines, (rows,cols)):
+ def extractRemittance(self, job, lines, dims):
+ (rows, cols) = dims
all_fields = []
page_data = collections.OrderedDict()
- pages = (rows-48)/48
+ pages = (rows-48)//48
for page in range(pages):
line =(page+1) * 48
fs = []
@@ -235,7 +240,8 @@ def extractRemittance(self, job, lines, (rows,cols)):
return (all_fields, page_data)
- def extractPicklist(self, job, lines, (rows,cols)):
+ def extractPicklist(self, job, lines, dims):
+ (rows, cols) = dims
all_fields = []
page_data = collections.defaultdict(list)
diff --git a/emailtemplates.py b/emailtemplates.py
new file mode 100644
index 0000000..a6c09d9
--- /dev/null
+++ b/emailtemplates.py
@@ -0,0 +1,639 @@
+# Email body templates, one per document type.
+#
+# The text offered when emailing a document is rendered from a Mako template chosen by the type of the
+# job: invoice, purchase order or statement, and 'default' for every other kind of document (credit notes,
+# delivery notes, reports...). Templates are looked up in USER_DIR (~/printerface/templates)
+# first and fall back to the copies shipped with the source in SEED_DIR, so an install that has never
+# customised a template keeps following the repository. The web editor saves into USER_DIR.
+#
+# SECURITY: Mako can run arbitrary python and the web interface has no authentication. Anything that
+# comes from the editor (previews included) is therefore checked by validate() first, which only allows
+# plain text, ${field.lookups}, 'for ... in docs', simple 'if' tests and comments. There are no calls, no
+# <% %> blocks, no operators and no names starting with an underscore, so a template cannot reach
+# anything but the document data it is given.
+#
+# The first line of the rendered text is the email's subject; the rest is the body. So a template can
+# compute the subject from the document as well, and subjects are generated mechanically.
+import collections
+import os
+import re
+import unittest
+from decimal import Decimal, InvalidOperation
+
+from mako.template import Template
+
+from settings import BASE_DIR, HOME
+
+KINDS = collections.OrderedDict([('invoice', 'Invoice'), ('purchase', 'Purchase order'), ('statement', 'Statement'), ('default', 'Default')])
+# job['templ'] -> template kind. Anything else uses 'default', which can only see the recipients and the job.
+KIND_FOR_TEMPL = {'invoice': 'invoice', 'purchase': 'purchase', 'statement': 'statement'}
+DEFAULT = 'default'
+
+SEED_DIR = os.path.join(BASE_DIR, 'templates')
+USER_DIR = os.path.join(HOME, 'templates')
+
+ENCODING = 'utf-8'
+NO_NAME = 'Sir or Madam'
+
+class TemplateError(Exception):
+ def __init__(self, errors):
+ Exception.__init__(self, '; '.join(errors))
+ self.errors = errors
+
+# ---------------------------------------------------------------------------------------------- context
+
+class Fields(object):
+ """Read-only attribute access to a dict of values. A field that does not exist reads as '' so that a
+ template written for one document layout never fails on another."""
+ def __init__(self, values):
+ self.__dict__.update(values)
+
+ def __getattr__(self, name):
+ if name.startswith('_'):
+ raise AttributeError(name)
+ return ''
+
+def field_names(fields):
+ return sorted(k for k in vars(fields))
+
+def merge_documents(pages):
+ """Pages of one account in a job -> one dict per document (grouped by document number, in print order).
+ A document's totals are only printed on its last page, so a later non-empty value replaces an earlier
+ one. Statements have no document number: all their pages are one document."""
+ docs = collections.OrderedDict()
+ for page in pages:
+ d = docs.setdefault(page.get('doc_num', '').strip(), {})
+ for k, v in page.items():
+ v = v.strip() if isinstance(v, str) else v
+ if v or k not in d:
+ d[k] = v
+ for d in docs.values():
+ d['customer'] = d.get('addr_invoice', '').split('\n')[0].strip()
+ return list(docs.values())
+
+# the field that is "the total" for each kind of document, for all.total
+KIND_TOTAL = {'invoice': 'tot_due', 'purchase': 'tot_net', 'statement': 'tot_topay'}
+
+def collapse_numbers(numbers):
+ """Document numbers the way the operations team writes them in a subject: the first in full, then each of
+ the others from the first digit that differs from the first one onward. ['336806', '336807'] gives
+ '336806/7', ['336769', '336771'] gives '336769/71' and ['335909', '335910', '335911'] gives '335909/10/11'.
+ Numbers that aren't all digits of the same length are just listed."""
+ if len(numbers) < 2 or not all(re.fullmatch(r'\d+', n) and len(n) == len(numbers[0]) for n in numbers):
+ return ', '.join(numbers)
+ first = numbers[0]
+ tails = []
+ for n in numbers[1:]:
+ i = 0
+ while i < len(first) - 1 and first[i] == n[i]:
+ i += 1
+ tails.append(n[i:])
+ return '/'.join([first] + tails)
+
+def and_list(items):
+ """['A'] -> 'A', ['A', 'B'] -> 'A and B', ['A', 'B', 'C'] -> 'A, B and C'"""
+ if len(items) < 2:
+ return ''.join(items)
+ return ', '.join(items[:-1]) + ' and ' + items[-1]
+
+def summarise(docs, kind):
+ """The 'all' helper: facts about every document of this account in the print run (docs, as dicts), so that
+ a subject and body can be written for one invoice or for several.
+ all.count, all.many ('1' if there is more than one, else ''), all.s ('s' or '': 'Invoice${all.s}')
+ all.numbers the document numbers as operations write them: '336806/7'
+ all.list the document numbers in words: '336806 and 336807'
+ all.total the total of all of them (invoices: amount due); all.tot_due, all.tot_net, all.tot_vat... likewise
+ Amounts are summed exactly and shown with two decimals. A total that isn't a plain amount is left empty."""
+ numbers = [d['doc_num'] for d in docs if d.get('doc_num')]
+ many = len(docs) > 1
+ values = {'count': str(len(docs)), 'many': '1' if many else '', 's': 's' if many else '',
+ 'numbers': collapse_numbers(numbers), 'list': and_list(numbers)}
+ for field in sorted(set(k for d in docs for k in d if k.startswith('tot_'))):
+ try:
+ amounts = [Decimal(d.get(field, '').replace(',', '')) for d in docs]
+ except InvalidOperation:
+ continue
+ values[field] = format(sum(amounts).quantize(Decimal('0.01')), 'f')
+ values['total'] = values.get(KIND_TOTAL.get(kind), '')
+ return Fields(values)
+
+def account_for_key(parsed, key):
+ """PDF group key -> account code. Purchase orders also have '-admin' and '-transport'."""
+ if key in parsed:
+ return key
+ for suffix in ('-admin', '-transport'):
+ if key.endswith(suffix) and key[:-len(suffix)] in parsed:
+ return key[:-len(suffix)]
+ return None
+
+def join_names(names):
+ names = [n.strip() for n in dict.fromkeys(names) if n and n.strip()]
+ if not names:
+ return NO_NAME
+ if len(names) == 1:
+ return names[0]
+ return ', '.join(names[:-1]) + ' and ' + names[-1]
+
+def kind_for_job(job):
+ return KIND_FOR_TEMPL.get(job.get('templ'), DEFAULT)
+
+def build_context(job, key, names=(), addresses=(), company=None):
+ """The variables a template sees:
+ doc the document (the last one, if the account has several in this print run); doc.
+ docs every document for the account in this print run, for '% for d in docs:'
+ all facts about all of them together, see summarise(): all.numbers, all.total, all.many, all.s
+ email the recipients: email.name ('Ann and Bob', or 'Sir or Madam' with none), email.address
+ job job.name, job.doctype, job.host
+ company company.name, company.email, company.website, from the [Printing] settings
+ The default template has email, job and company but no doc or docs: for the other document types there
+ are no fields we know of."""
+ addresses = [a for a in addresses if a]
+ context = dict(
+ email=Fields({'name': join_names(names), 'address': addresses[0] if addresses else ''}),
+ job=Fields({'name': job.get('name', ''), 'doctype': job.get('doctype', ''), 'host': (job.get('control') or {}).get('H', '')}),
+ company=Fields(company or {}))
+ if kind_for_job(job) == DEFAULT:
+ return context
+ parsed = job.get('parsed') or {}
+ acc = account_for_key(parsed, key)
+ docs = merge_documents(parsed[acc]) if acc else []
+ context.update(doc=Fields(docs[-1] if docs else {}), docs=[Fields(d) for d in docs], all=summarise(docs, kind_for_job(job)))
+ return context
+
+def find_document(jobs, kind, term=''):
+ """The filter behind the editor's preview. jobs is newest first. Returns (job, key) for the newest
+ document of this kind whose document number, or account code, equals term (ignoring case and spaces),
+ or for the newest document of this kind if term is empty. None if there isn't one.
+ For the default kind there are no document numbers: term matches the job name or the document type
+ (for example 'Delvnote'), and key is the job's first PDF group, as the compose form would use."""
+ norm = lambda s: re.sub(r'\s+', '', s or '').lower()
+ want = norm(term)
+ for job in jobs:
+ if kind_for_job(job) != kind:
+ continue
+ if kind == DEFAULT:
+ if not want or want in (norm(job.get('name')), norm(job.get('doctype'))):
+ return job, next(iter(job.get('groupfiles') or {}), ('',))[0]
+ continue
+ for acc, pages in (job.get('parsed') or {}).items():
+ for d in merge_documents(pages):
+ if not want or want in (norm(d.get('doc_num')), norm(d.get('accno'))):
+ return job, acc
+ return None
+
+# ------------------------------------------------------------------------------------------ validation
+
+# a name may contain, but not start with, an underscore: field names are like tot_due, and this keeps __dunder__ out
+_PATH = r'[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*'
+_EXPR = re.compile(r'^\s*(%s)\s*(?:\|\s*trim\s*)?$' % _PATH)
+_FOR = re.compile(r'^\s*%\s*for\s+([a-z][a-z0-9]*)\s+in\s+docs\s*:\s*$')
+_IF = re.compile(r'^\s*%%\s*if\s+(?:not\s+)?(%s)\s*:\s*$' % _PATH)
+_ELSE = re.compile(r'^\s*%\s*else\s*:\s*$')
+_END = re.compile(r'^\s*%\s*(?:endif|endfor)\s*$')
+_ROOTS = frozenset(['doc', 'all', 'email', 'job', 'company'])
+_DEFAULT_ROOTS = frozenset(['email', 'job', 'company'])
+
+def validate(text, kind=None):
+ """Returns a list of 'line N: problem' strings; empty if the template is safe to render as this kind
+ of template (the default template has no doc or docs)."""
+ errors = []
+ loop_vars = set()
+ lines = text.replace('\r\n', '\n').replace('\r', '\n').split('\n')
+ for line in lines:
+ m = _FOR.match(line)
+ if m:
+ loop_vars.add(m.group(1))
+ roots = (_DEFAULT_ROOTS if kind == DEFAULT else _ROOTS) | loop_vars
+
+ def check_path(n, path, where):
+ root = path.split('.')[0]
+ if root not in roots:
+ errors.append('line %d: unknown name "%s" in %s (use %s)' % (n, root, where, ', '.join(sorted(roots))))
+
+ for n, line in enumerate(lines, 1):
+ if line.endswith('\\'):
+ errors.append('line %d: a line may not end with a backslash' % n)
+ if '<%' in line or '%' in line:
+ errors.append('line %d: <%% %%> blocks are not allowed' % n)
+ continue
+ stripped = line.lstrip()
+ if stripped.startswith('##'):
+ continue
+ if stripped.startswith('%'):
+ m = _IF.match(line)
+ if m:
+ check_path(n, m.group(1), 'the condition')
+ elif _FOR.match(line) and kind == DEFAULT:
+ errors.append('line %d: there are no documents to loop over in the default template' % n)
+ elif not (_FOR.match(line) or _ELSE.match(line) or _END.match(line)):
+ errors.append('line %d: only "%% for x in docs:", "%% if field:", "%% if not field:", "%% else:", "%% endif" and "%% endfor" are allowed' % n)
+ continue
+ found = 0
+ for em in re.finditer(r'\$\{(.*?)\}', line):
+ found += 1
+ m = _EXPR.match(em.group(1))
+ if not m:
+ errors.append('line %d: "${%s}" is not allowed; use ${doc.field} or ${doc.field | trim}' % (n, em.group(1).strip()))
+ else:
+ check_path(n, m.group(1), '${%s}' % em.group(1).strip())
+ if line.count('${') != found:
+ errors.append('line %d: unterminated ${' % n)
+ if not errors:
+ try:
+ Template(text)
+ except Exception as e:
+ errors.append('template structure: %s' % (str(e).splitlines() or ['invalid'])[0])
+ return errors
+
+Message = collections.namedtuple('Message', 'subject body')
+
+def split_subject(rendered):
+ """The first line of the rendered text is the subject, the rest is the body. Blank lines between them
+ (a separator, for readability in the template) are not part of the body."""
+ first, _, rest = rendered.partition('\n')
+ rest = re.sub(r'\A(?:[ \t]*\n)+', '', rest)
+ return Message(first.strip(), (rest.rstrip() + '\n') if rest.strip() else '')
+
+def render(text, context, kind=None):
+ errors = validate(text, kind)
+ if errors:
+ raise TemplateError(errors)
+ try:
+ out = Template(text, strict_undefined=True).render_unicode(**context)
+ except Exception as e:
+ raise TemplateError(['%s: %s' % (type(e).__name__, e)])
+ return out.rstrip() + '\n'
+
+def render_message(text, context, kind=None):
+ return split_subject(render(text, context, kind))
+
+# ------------------------------------------------------------------------------------------ storage
+
+def _check_kind(kind):
+ if kind not in KINDS:
+ raise KeyError('unknown template %r' % (kind,))
+
+def user_path(kind):
+ _check_kind(kind)
+ return os.path.join(USER_DIR, kind + '.mako')
+
+def seed_path(kind):
+ _check_kind(kind)
+ return os.path.join(SEED_DIR, kind + '.mako')
+
+def load(kind):
+ """(text, 'custom' | 'default'): the user's template if they have one, else the one shipped in the source."""
+ for source, path in (('custom', user_path(kind)), ('default', seed_path(kind))):
+ if os.path.isfile(path):
+ with open(path, encoding=ENCODING) as f:
+ return f.read(), source
+ raise FileNotFoundError(seed_path(kind))
+
+def save(kind, text):
+ text = text.replace('\r\n', '\n').replace('\r', '\n')
+ if not text.endswith('\n'):
+ text += '\n'
+ errors = validate(text, kind)
+ if errors:
+ raise TemplateError(errors)
+ path = user_path(kind)
+ os.makedirs(USER_DIR, exist_ok=True)
+ tmp = path + '.tmp'
+ with open(tmp, 'w', encoding=ENCODING, newline='\n') as f:
+ f.write(text)
+ os.replace(tmp, path)
+
+def revert(kind):
+ """Delete the user's copy so the shipped template applies again. True if there was one."""
+ path = user_path(kind)
+ if os.path.isfile(path):
+ os.remove(path)
+ return True
+ return False
+
+MIGRATED_MARKER = '.legacy-default-text-migrated'
+
+def migrate_legacy_default(text):
+ """Before there were per type templates a single email text was kept in email.pickle. Offer that text as
+ the default template, once, unless the user already has a default.mako. A marker file stops it coming back
+ if they later revert to the shipped default. Returns a message to log, or None if there was nothing to do."""
+ marker = os.path.join(USER_DIR, MIGRATED_MARKER)
+ if not (text or '').strip() or os.path.exists(marker) or os.path.exists(user_path(DEFAULT)):
+ return None
+ try:
+ # the old text had no subject line (the user typed one in); give it the shipped default's
+ with open(seed_path(DEFAULT), encoding=ENCODING) as f:
+ subject_line = f.readline().rstrip('\n')
+ save(DEFAULT, subject_line + '\n\n' + text.lstrip('\r\n'))
+ message = 'migrated the old email text to %s' % user_path(DEFAULT)
+ except TemplateError as e:
+ message = 'could not migrate the old email text (%s); it is still in email.pickle' % e
+ os.makedirs(USER_DIR, exist_ok=True)
+ open(marker, 'w').close()
+ return message
+
+def render_for_job(job, key, names=(), addresses=(), company=None):
+ """(Message(subject, body), kind, warning) for the compose form. A user template that no longer renders
+ falls back to the shipped one, with a warning."""
+ kind = kind_for_job(job)
+ context = build_context(job, key, names, addresses, company)
+ text, source = load(kind)
+ try:
+ return render_message(text, context, kind), kind, None
+ except TemplateError as e:
+ if source != 'custom':
+ raise
+ message = render_message(open(seed_path(kind), encoding=ENCODING).read(), context, kind)
+ return message, kind, 'Your %s template could not be used (%s); showing the default.' % (KINDS[kind].lower(), e)
+
+# ----------------------------------------------------------------------------------------------- tests
+
+class TestEmailTemplates(unittest.TestCase):
+ def pages(self):
+ return [
+ {'doc_num': '336769', 'ourref': '289073', 'accno': 'HAR108', 'tot_due': '', 'addr_invoice': 'HISTORIC HOUSE\nAYLESBURY\n\n', 'page': '1'},
+ {'doc_num': '336769', 'ourref': '289073', 'accno': 'HAR108', 'tot_due': '1,234.50', 'addr_invoice': 'HISTORIC HOUSE\nAYLESBURY\n\n', 'page': '2'},
+ {'doc_num': '336770', 'ourref': '289099', 'accno': 'HAR108', 'tot_due': '10.00', 'addr_invoice': 'HISTORIC HOUSE\n', 'page': '1'},
+ ]
+
+ def job(self, templ='invoice', name='job-1'):
+ return {'name': name, 'templ': templ, 'doctype': 'Invoice', 'control': {'H': 'SALES-PC'}, 'parsed': {'HAR108': self.pages()}}
+
+ def test_merge_documents_takes_totals_from_the_last_page(self):
+ docs = merge_documents(self.pages())
+ self.assertEqual(['336769', '336770'], [d['doc_num'] for d in docs])
+ self.assertEqual('1,234.50', docs[0]['tot_due'])
+ self.assertEqual('HISTORIC HOUSE', docs[0]['customer'])
+ self.assertEqual('2', docs[0]['page'])
+
+ def test_statement_pages_without_doc_num_are_one_document(self):
+ docs = merge_documents([{'accno': 'A', 'tot_topay': ''}, {'accno': 'A', 'tot_topay': '5.00'}])
+ self.assertEqual(1, len(docs))
+ self.assertEqual('5.00', docs[0]['tot_topay'])
+
+ def test_account_for_key(self):
+ parsed = {'APA100': [], 'MULTI-21': []}
+ self.assertEqual('APA100', account_for_key(parsed, 'APA100'))
+ self.assertEqual('APA100', account_for_key(parsed, 'APA100-admin'))
+ self.assertEqual('APA100', account_for_key(parsed, 'APA100-transport'))
+ self.assertEqual('MULTI-21', account_for_key(parsed, 'MULTI-21'))
+ self.assertIsNone(account_for_key(parsed, 'accounts'))
+
+ def test_join_names(self):
+ self.assertEqual(NO_NAME, join_names([]))
+ self.assertEqual('Ann', join_names(['Ann', 'Ann', ' ']))
+ self.assertEqual('Ann and Bob', join_names(['Ann', 'Bob']))
+ self.assertEqual('Ann, Bob and Cy', join_names(['Ann', 'Bob', 'Cy']))
+
+ def test_shipped_templates_are_valid_and_the_invoice_says_what_it_should(self):
+ for kind in KINDS:
+ text = open(seed_path(kind), encoding=ENCODING).read()
+ self.assertEqual([], validate(text, kind), kind)
+ text = open(seed_path('invoice'), encoding=ENCODING).read()
+ # the wording of the shipped templates is theirs to change; these are the facts they must keep stating
+ two = render_message(text, build_context(self.job(), 'HAR108', names=['Ann'], company={'name': 'ABFW'}))
+ self.assertEqual('New Invoices 336769/70', two.subject) # as operations write it
+ self.assertRegex(two.body, r'\ATo Ann,?\n\nPlease find your latest invoices attached for account HAR108, for a total of \xa31244\.50')
+ self.assertRegex(two.body, r'336769 +\xa31,234\.50\n336770 +\xa310\.00\n') # each invoice and its amount
+ one_job = self.job()
+ one_job['parsed'] = {'HAR108': self.pages()[2:]}
+ one = render_message(text, build_context(one_job, 'HAR108', names=['Ann'], company={'name': 'ABFW'}))
+ self.assertEqual('New Invoice 336770', one.subject)
+ self.assertRegex(one.body, r'\ATo Ann,?\n\nPlease find your latest invoice 336770 attached for account HAR108, for \xa310\.00\.\n')
+
+ def test_shipped_templates_render_with_no_data_at_all(self):
+ for kind in KINDS:
+ message = render_message(open(seed_path(kind), encoding=ENCODING).read(), build_context({'templ': kind}, 'nothing'), kind)
+ self.assertTrue(message.body.startswith('To ' + NO_NAME), kind)
+ self.assertTrue(message.subject, kind)
+
+ def test_other_document_types_use_the_default_template(self):
+ for templ in ('delnote', 'crednote', 'picklist', None):
+ message, kind, warning = render_for_job({'templ': templ, 'name': 'job-9', 'doctype': 'Delvnote'}, 'X', ['Ann'])
+ self.assertEqual((DEFAULT, None), (kind, warning), templ)
+ self.assertRegex(message.subject, r'\ADocument\b.*attached\Z')
+ self.assertRegex(message.body, r'\ATo Ann,?\n\nPlease find your (?:\w+ )?document attached\.\n')
+
+ def test_the_default_context_has_no_document_fields(self):
+ ctx = build_context({'templ': 'delnote', 'name': 'job-9', 'doctype': 'Delvnote', 'control': {'H': 'PC1'}}, 'X', ['Ann'], ['a@b.c'], {'name': 'ABFW', 'email': 'sales@abfw.test'})
+ self.assertEqual(['company', 'email', 'job'], sorted(ctx))
+ self.assertEqual(('Ann', 'a@b.c', 'job-9', 'Delvnote', 'PC1'), (ctx['email'].name, ctx['email'].address, ctx['job'].name, ctx['job'].doctype, ctx['job'].host))
+ self.assertEqual(('ABFW', 'sales@abfw.test', ''), (ctx['company'].name, ctx['company'].email, ctx['company'].website))
+ self.assertEqual([], validate('${email.name} ${job.doctype | trim} ${company.name}\n% if company.website:\nx\n% endif\n% if job.host:\nx\n% endif', DEFAULT))
+ message = render_message('From ${company.name}\n\nHi ${email.name}\n', ctx, DEFAULT)
+ self.assertEqual(('From ABFW', 'Hi Ann\n'), tuple(message))
+ for text in ('${doc.ourref}', '% for d in docs:\n% endfor', '% if doc.x:\n% endif'):
+ self.assertTrue(validate(text, DEFAULT), text)
+ if 'docs' not in text:
+ self.assertEqual([], validate(text, 'invoice'), text) # fine for a document type that has them
+
+ def test_migrate_legacy_default_text_once(self):
+ import tempfile
+ global USER_DIR
+ old, USER_DIR = USER_DIR, os.path.join(tempfile.mkdtemp(prefix='printerface-test-'), 'templates')
+ try:
+ self.assertIsNone(migrate_legacy_default(''))
+ self.assertIsNone(migrate_legacy_default(' \r\n'))
+ self.assertFalse(os.path.exists(user_path(DEFAULT)))
+ self.assertIn('migrated', migrate_legacy_default('Please find it attached.\r\n\r\nRegards,\r\nTony'))
+ # the old text had no subject, so it gets the shipped default's, and the old text stays the body
+ with open(seed_path(DEFAULT), encoding=ENCODING) as f:
+ shipped_subject = f.readline().rstrip('\n')
+ self.assertEqual((shipped_subject + '\n\nPlease find it attached.\n\nRegards,\nTony\n', 'custom'), load(DEFAULT))
+ message = render_message(load(DEFAULT)[0], build_context({}, 'x'), DEFAULT)
+ self.assertEqual('Please find it attached.\n\nRegards,\nTony\n', message.body)
+ self.assertTrue(message.subject.startswith('Document'), message.subject)
+ # a user who reverts to the shipped text does not get the old text back at the next start
+ revert(DEFAULT)
+ self.assertIsNone(migrate_legacy_default('Please find it attached.'))
+ self.assertEqual('default', load(DEFAULT)[1])
+ finally:
+ import shutil
+ shutil.rmtree(os.path.dirname(USER_DIR), ignore_errors=True)
+ USER_DIR = old
+
+ def test_migrate_never_overwrites_or_imports_unsafe_text(self):
+ import tempfile
+ global USER_DIR
+ old, USER_DIR = USER_DIR, os.path.join(tempfile.mkdtemp(prefix='printerface-test-'), 'templates')
+ try:
+ save(DEFAULT, 'mine')
+ self.assertIsNone(migrate_legacy_default('legacy'))
+ self.assertEqual('mine\n', load(DEFAULT)[0])
+ revert(DEFAULT)
+ self.assertIn('could not migrate', migrate_legacy_default("${__import__('os')}"))
+ self.assertEqual('default', load(DEFAULT)[1])
+ finally:
+ import shutil
+ shutil.rmtree(os.path.dirname(USER_DIR), ignore_errors=True)
+ USER_DIR = old
+
+ def test_validate_accepts_the_safe_subset(self):
+ ok = '''## a comment ${anything()}
+To ${email.name | trim}
+% for d in docs:
+Invoice ${d.ourref}: ${d.tot_due}
+% endfor
+% if doc.tot_due:
+Total ${doc.tot_due}
+% else:
+none
+% endif
+% if not doc.customer:
+x
+% endif
+50% off, 100% sure
+'''
+ self.assertEqual([], validate(ok))
+
+ def test_validate_rejects_anything_that_could_run_code(self):
+ bad = [
+ "${__import__('os').system('id')}",
+ '${doc.__class__}',
+ '${doc.ourref()}',
+ '${doc.ourref + doc.accno}',
+ '${open("/etc/passwd").read()}',
+ '${os.getcwd}',
+ '${doc.ourref | h}',
+ '${doc.ourref',
+ '<% import os %>',
+ '<%! import os %>',
+ '<%include file="x"/>',
+ '% import os',
+ '% for x in range(3):\n% endfor',
+ '% if doc.a == 1:\n% endif',
+ '% if doc.a:\n% endif\n%% x',
+ '${doc.ourref}\\\n% import os',
+ '% for x in docs:\n${y.ourref}\n% endfor',
+ ]
+ for text in bad:
+ self.assertTrue(validate(text), text)
+ with self.assertRaises(TemplateError):
+ render("${__import__('os').system('true')}", build_context({}, 'x'))
+
+ def test_comments_are_never_evaluated(self):
+ # validate() skips '##' lines, so make sure mako really does too (strict_undefined would raise)
+ self.assertEqual('hello\n', render('## ${nothing.defined.here}\nhello', build_context({}, 'x')))
+ # ...but <% is refused everywhere, comment or not
+ self.assertTrue(validate('## <% x %>'))
+
+ def test_split_subject(self):
+ self.assertEqual(('Hello', 'Body\n'), tuple(split_subject('Hello\nBody\n')))
+ self.assertEqual(('Hello', 'Body\nmore\n'), tuple(split_subject('Hello\n\n\n \nBody\nmore\n\n\n'))) # separator lines are not the body
+ self.assertEqual(('Hello', 'Para 1\n\nPara 2\n'), tuple(split_subject('Hello\n\nPara 1\n\nPara 2\n'))) # blank lines inside the body stay
+ self.assertEqual(('Only a subject', ''), tuple(split_subject('Only a subject\n')))
+ self.assertEqual(('Only a subject', ''), tuple(split_subject('Only a subject\n\n \n')))
+ self.assertEqual(('', 'Body\n'), tuple(split_subject('\nBody\n'))) # an empty first line: no subject
+ self.assertEqual(('Trim me', 'x\n'), tuple(split_subject(' Trim me \t\nx\n')))
+ self.assertEqual(('', ''), tuple(split_subject('')))
+
+ def test_the_subject_is_the_first_rendered_line_so_it_can_be_computed(self):
+ job = self.job()
+ ctx = build_context(job, 'HAR108', names=['Ann'], company={'name': 'ABFW'})
+ text = '## a comment before the subject is not output\n% if doc.tot_due:\nInvoice ${doc.ourref}, \xa3${doc.tot_due}\n% else:\nInvoice ${doc.ourref}\n% endif\n\nHi ${email.name}\n'
+ self.assertEqual(('Invoice 289099, \xa310.00', 'Hi Ann\n'), tuple(render_message(text, ctx)))
+ ctx = build_context({'templ': 'invoice', 'parsed': {'A': [{'doc_num': '1', 'ourref': '77', 'accno': 'A', 'tot_due': ''}]}}, 'A')
+ self.assertEqual('Invoice 77', render_message(text, ctx).subject)
+ # a template whose first line is blank has no subject, and nothing else moves up into its place
+ self.assertEqual(('', 'Hi\n'), tuple(render_message('\nHi\n', ctx)))
+
+ def test_collapse_numbers_matches_the_operations_convention(self):
+ for numbers, want in (
+ ([], ''), (['336806'], '336806'), (['336806', '336807'], '336806/7'), (['336829', '336830'], '336829/30'),
+ (['336769', '336771'], '336769/71'), (['336696', '336698'], '336696/8'), (['336813', '336814', '336815'], '336813/4/5'),
+ (['335909', '335910', '335911'], '335909/10/11'), (['331279', '331280', '331282'], '331279/80/82'),
+ (['332058', '332059', '332060', '332061', '332066'], '332058/9/60/61/66'),
+ # numbers that can't be abbreviated are just listed
+ (['99999', '100000'], '99999, 100000'), (['34529/ 1', '34529/ 2'], '34529/ 1, 34529/ 2')):
+ self.assertEqual(want, collapse_numbers(numbers), numbers)
+
+ def test_summarise_all_documents(self):
+ docs = [{'doc_num': '336806', 'tot_due': '569.73', 'tot_net': '474.78', 'tot_vat': '94.95'},
+ {'doc_num': '336807', 'tot_due': '44.92', 'tot_net': '37.44', 'tot_vat': '7.48'}]
+ a = summarise(docs, 'invoice')
+ self.assertEqual(('2', '1', 's', '336806/7', '336806 and 336807'), (a.count, a.many, a.s, a.numbers, a.list))
+ self.assertEqual(('614.65', '614.65', '512.22', '102.43'), (a.total, a.tot_due, a.tot_net, a.tot_vat))
+ one = summarise(docs[:1], 'invoice')
+ self.assertEqual(('1', '', '', '336806', '569.73'), (one.count, one.many, one.s, one.numbers, one.total))
+ # amounts are added exactly, with or without thousands separators
+ self.assertEqual('0.30', summarise([{'tot_due': '0.1'}, {'tot_due': '0.2'}], 'invoice').total)
+ self.assertEqual('1235.00', summarise([{'tot_due': '1,234.50'}, {'tot_due': '0.50'}], 'invoice').total)
+ # something that isn't a plain amount is left out rather than guessed at
+ self.assertEqual('', summarise([{'tot_due': '5.00'}, {'tot_due': 'CR'}], 'invoice').total)
+ # statements have no document number; their total is the amount to pay
+ st = summarise([{'accno': 'A', 'tot_topay': '3485.99'}], 'statement')
+ self.assertEqual(('', '3485.99', '1'), (st.numbers, st.total, st.count))
+ self.assertEqual(('', '', ''), (summarise([], 'invoice').numbers, summarise([], 'invoice').total, summarise([], 'invoice').many))
+
+ def test_all_exists_for_documents_with_fields_but_not_for_the_default_template(self):
+ ctx = build_context(self.job(), 'HAR108', names=['Ann'])
+ self.assertEqual(('2', '336769/70', '336769 and 336770'), (ctx['all'].count, ctx['all'].numbers, ctx['all'].list))
+ self.assertEqual([], validate('${all.numbers} ${all.total}\n% if all.many:\nx\n% endif', 'invoice'))
+ self.assertTrue(validate('${all.numbers}', DEFAULT))
+ self.assertNotIn('all', build_context({'templ': 'delnote'}, 'X'))
+
+ def test_validate_reports_unbalanced_blocks(self):
+ self.assertTrue(validate('% if doc.a:\nx\n'))
+
+ def test_storage_custom_overrides_shipped_and_revert_restores(self):
+ import tempfile
+ global USER_DIR
+ old, USER_DIR = USER_DIR, os.path.join(tempfile.mkdtemp(prefix='printerface-test-'), 'templates')
+ try:
+ text, source = load('invoice')
+ self.assertEqual('default', source)
+ save('invoice', 'Hello ${email.name}\r\nbye')
+ text, source = load('invoice')
+ self.assertEqual(('Hello ${email.name}\nbye\n', 'custom'), (text, source))
+ with self.assertRaises(TemplateError):
+ save('invoice', '${__import__("os")}')
+ self.assertEqual('Hello ${email.name}\nbye\n', load('invoice')[0])
+ self.assertTrue(revert('invoice'))
+ self.assertFalse(revert('invoice'))
+ self.assertEqual('default', load('invoice')[1])
+ with self.assertRaises(KeyError):
+ user_path('../../etc/passwd')
+ finally:
+ import shutil
+ shutil.rmtree(os.path.dirname(USER_DIR), ignore_errors=True)
+ USER_DIR = old
+
+ def test_a_broken_custom_template_falls_back_to_the_shipped_one(self):
+ import tempfile
+ global USER_DIR
+ old, USER_DIR = USER_DIR, os.path.join(tempfile.mkdtemp(prefix='printerface-test-'), 'templates')
+ try:
+ os.makedirs(USER_DIR)
+ with open(user_path('invoice'), 'w') as f:
+ f.write('${__import__("os")}') # written to disk behind the editor's back
+ message, kind, warning = render_for_job(self.job(), 'HAR108', ['Ann'])
+ self.assertRegex(message.body, r'\ATo Ann,?\n\nPlease find your latest invoices? ')
+ self.assertTrue(message.subject.startswith('New Invoice'), message.subject)
+ self.assertIn('could not be used', warning)
+ finally:
+ import shutil
+ shutil.rmtree(os.path.dirname(USER_DIR), ignore_errors=True)
+ USER_DIR = old
+
+ def test_find_document(self):
+ a, b = self.job(name='job-new'), self.job(name='job-old')
+ b['parsed'] = {'ZZZ999': [{'doc_num': '500 100', 'accno': 'ZZZ999'}]}
+ jobs = [self.job('delnote', 'job-d'), a, b]
+ self.assertEqual(('job-new', 'HAR108'), (lambda r: (r[0]['name'], r[1]))(find_document(jobs, 'invoice')))
+ self.assertEqual('job-new', find_document(jobs, 'invoice', '336770')[0]['name'])
+ self.assertEqual('job-old', find_document(jobs, 'invoice', '500100')[0]['name'])
+ self.assertEqual('job-old', find_document(jobs, 'invoice', 'zzz999')[0]['name'])
+ self.assertIsNone(find_document(jobs, 'invoice', 'nope'))
+ self.assertIsNone(find_document(jobs, 'statement'))
+
+ def test_find_document_for_the_default_kind_matches_job_name_or_type(self):
+ d1 = {'name': 'job-2', 'templ': 'delnote', 'doctype': 'Delvnote', 'groupfiles': {('accounts',): 'x.pdf'}}
+ d2 = {'name': 'job-1', 'templ': None, 'doctype': 'Batch', 'groupfiles': {('plain',): 'y.pdf'}}
+ jobs = [self.job('invoice', 'job-3'), d1, d2]
+ self.assertEqual(('job-2', 'accounts'), (lambda r: (r[0]['name'], r[1]))(find_document(jobs, DEFAULT)))
+ self.assertEqual(('job-1', 'plain'), (lambda r: (r[0]['name'], r[1]))(find_document(jobs, DEFAULT, 'batch')))
+ self.assertEqual('job-1', find_document(jobs, DEFAULT, 'JOB-1')[0]['name'])
+ self.assertIsNone(find_document(jobs, DEFAULT, 'nope'))
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/httpserver.py b/httpserver.py
index 1f1ee7c..46b023b 100644
--- a/httpserver.py
+++ b/httpserver.py
@@ -15,15 +15,16 @@
datamodel.
"""
-import asynchat, asyncore, socket, select, urllib
-import posixpath, sys, cgi, cStringIO, os, traceback, shutil
-import mimetools, time
-import cgi
+import asynchat, asyncore, socket
+import posixpath, sys, io, os, traceback
+import html
+import time
+import urllib.parse
import mimetypes
-try:
- from cStringIO import StringIO
-except ImportError:
- from StringIO import StringIO
+
+# 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'
"""HTTP server base class.
@@ -40,15 +41,18 @@
class CaseInsensitiveDict(dict):
"""Dictionary with case-insensitive keys
- Replacement for the deprecated mimetools.Message class
+ 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 = self.keys()
+ self.headers = list(self.keys())
def getheader(self,key,default=""):
return self._ci_dict.get(key.lower(),default)
@@ -77,8 +81,26 @@ def __contains__(self,key):
DEFAULT_ERROR_CONTENT_TYPE = "text/html"
-def _quote_html(html):
- return html.replace("&", "&").replace("<", "<").replace(">", ">")
+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
+ Other, so the browser fetches the location with GET: after handling a POST this means the page the user ends
+ up on can be refreshed without repeating the POST."""
+ 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."""
+ if isinstance(f, str):
+ f = f.encode(BODY_ENCODING)
+ if isinstance(f, (bytes, bytearray)):
+ f = io.BytesIO(f)
+ if ctype.startswith('text/') and 'charset' not in ctype:
+ ctype += '; charset=' + BODY_ENCODING
+ return f, ctype
class BaseHTTPRequestHandler(asynchat.async_chat):
@@ -109,7 +131,7 @@ def parse_request(self, requestline):
self.request_version = version = self.default_request_version
self.close_connection = 1
- requestline = requestline.rstrip('\r\n')
+ requestline = requestline.decode(HEADER_ENCODING).rstrip('\r\n')
self.requestline = requestline
words = requestline.split()
if len(words) == 3:
@@ -150,10 +172,10 @@ def parse_request(self, requestline):
return False
querystring = dict()
- qparts = path.split('?', 1);
+ qparts = path.split('?', 1)
if len(qparts) > 1:
path = qparts[0]
- querystring = cgi.parse_qs(qparts[1])
+ 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
@@ -196,7 +218,7 @@ def send_error(self, code, message=None):
self.send_header('Connection', 'close')
self.end_headers()
if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
- self.push(content)
+ self.push(content.encode(BODY_ENCODING))
error_message_format = DEFAULT_ERROR_MESSAGE
error_content_type = DEFAULT_ERROR_CONTENT_TYPE
@@ -215,15 +237,14 @@ def send_response(self, code, message=None):
else:
message = ''
if self.request_version != 'HTTP/0.9':
- self.push("%s %d %s\r\n" % (self.protocol_version, code, message))
- # print (self.protocol_version, code, message)
+ 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))
+ self.push(("%s: %s\r\n" % (keyword, value)).encode(HEADER_ENCODING, 'replace'))
if keyword.lower() == 'connection':
if value.lower() == 'close':
@@ -234,7 +255,7 @@ def send_header(self, keyword, value):
def end_headers(self):
"""Send the blank line ending the MIME headers."""
if self.request_version != 'HTTP/0.9':
- self.push("\r\n")
+ self.push(b"\r\n")
def log_request(self, code='-', size='-'):
"""Log requests, called by send_response(). """
@@ -451,11 +472,11 @@ def write_headers(self, connection):
if (handler):
try:
resp = ResponseGatherer()
- (f, ctype) = handler(query_string=self.query_string, resp=resp)
- if type(f) is str:
- c = StringIO()
- c.write(f)
- f = c
+ 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)
@@ -467,7 +488,7 @@ def write_headers(self, connection):
return f
except:
tb = traceback.format_exc()
- print tb
+ print(tb)
self.send_error(500, "File not found")
return None
@@ -495,7 +516,7 @@ def write_headers(self, connection):
f = open(path, 'rb')
except IOError:
tb = traceback.format_exc()
- print tb
+ print(tb)
self.send_error(404, "File not found")
return None
self.send_response(200)
@@ -506,6 +527,12 @@ def write_headers(self, connection):
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).
@@ -520,8 +547,8 @@ def list_directory(self, path):
self.send_error(404, "No permission to list directory")
return None
list.sort(key=lambda a: a.lower())
- f = StringIO()
- displaypath = cgi.escape(urllib.unquote(self.path))
+ 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)
@@ -537,10 +564,10 @@ def list_directory(self, path):
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
f.write('
%s\n'
- % (urllib.quote(linkname), cgi.escape(displayname)))
+ % (urllib.parse.quote(linkname), html.escape(displayname)))
f.write("\n\n\n\n")
- length = f.tell()
- f.seek(0)
+ 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)
@@ -559,9 +586,9 @@ def translate_path(self, path):
# abandon query parameters
path = path.split('?',1)[0]
path = path.split('#',1)[0]
- path = posixpath.normpath(urllib.unquote(path))
+ path = posixpath.normpath(urllib.parse.unquote(path))
words = path.split('/')
- words = filter(None, words)
+ words = [w for w in words if w]
path = self.webroot
for word in words:
drive, word = os.path.splitdrive(word)
@@ -620,9 +647,9 @@ def __init__(self,conn,addr, webroot=os.getcwd(), path_handlers={}):
self.reset_terminator();
def reset_terminator(self):
- self.set_terminator ('\r\n\r\n')
+ self.set_terminator (b'\r\n\r\n')
self.found_terminator = self.handle_request_line
- self.rfile = cStringIO.StringIO()
+ self.rfile = io.BytesIO()
def collect_incoming_data(self,data):
self.rfile.write(data)
@@ -630,19 +657,18 @@ def collect_incoming_data(self,data):
def do_POST(self):
"""Begins serving a POST request. The request data must be readable
on a file-like object called self.rfile"""
- ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
- postreq = cgi.FieldStorage(fp=self.rfile,
- headers=self.headers, environ = {'REQUEST_METHOD':'POST'},
- keep_blank_values = 1)
+ # 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:
- (f, ctype) = handler(query_string=self.query_string, postreq=postreq)
- if type(f) is str:
- c = StringIO()
- c.write(f)
- f = c
+ 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)
@@ -650,10 +676,12 @@ def do_POST(self):
# self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.end_headers()
f.seek(0)
- return f
+ self.push(f.read())
+ f.close()
+ return None
except:
tb = traceback.format_exc()
- print tb
+ print(tb)
self.send_error(500, "File not found")
return None
else:
@@ -671,7 +699,7 @@ def handle_request_line(self):
bytesToRead = int(self.headers.getheader('content-length', '0'))
if bytesToRead > 0:
self.set_terminator(bytesToRead)
- self.rfile = cStringIO.StringIO()
+ self.rfile = io.BytesIO()
# control will be passed to a new found_terminator
self.found_terminator = self.dispatch_handler
@@ -697,11 +725,6 @@ 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))
-
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))
@@ -720,7 +743,7 @@ def __init__ (self, ip='', port=8081, webroot=os.getcwd(), handler=RequestHandle
self.bind ((ip, port))
self.listen (100)
- print "[httpd] ToyHTTPServer running on port %s, serving from %s" % (port, self.webroot)
+ print("[httpd] ToyHTTPServer running on port %s, serving from %s" % (port, self.webroot))
def handle_accept (self):
try:
@@ -735,9 +758,7 @@ def handle_accept (self):
if __name__=="__main__":
def about(query_string=''):
- f = StringIO()
- f.write("hi %s" % query_string)
- return (f,'text/plain')
+ return ("hi %s" % query_string, 'text/plain')
# launch the server on the specified port
s = ToyHttpServer(port=8081, pathhandlers={'/about': about})
@@ -745,6 +766,6 @@ def about(query_string=''):
try:
while True:
asyncore.loop(timeout=2, count=10)
- print '[control] poll'
+ print('[control] poll')
except KeyboardInterrupt:
- print "Crtl+C pressed. Shutting down."
+ print("Crtl+C pressed. Shutting down.")
diff --git a/init.d/printerface b/init.d/printerface
index 0b3b098..b631965 100755
--- a/init.d/printerface
+++ b/init.d/printerface
@@ -29,6 +29,11 @@
# 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
+# 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.
+python=${PRINTERFACE_PYTHON:-~/.venv311/bin/python}
lock=~/printerface/lock
pidfile=~/printerface/run
work=~/repos/printerface/
@@ -47,12 +52,19 @@ then
fi
# Check that binary exists
-if ! [ -f $printerface ]
+if ! [ -f $printerface ]
then
echo "printerface binary not found"
exit 0
fi
+# Check that the interpreter exists
+if ! [ -x $python ]
+then
+ echo "python interpreter $python not found"
+ exit 0
+fi
+
# See how we were called.
case "$1" in
start)
@@ -77,7 +89,7 @@ case "$1" in
errors=0
successes=0
export TZ=:/etc/localtime
- daemonize -a -E PATH=$PATH -c $work -e $logfile.err -o $logfile.out -p $pidfile $printerface
+ daemonize -a -E PATH=$PATH -c $work -e $logfile.err -o $logfile.out -p $pidfile $python $printerface
if [ $? = 0 ]; then
successes=1
diff --git a/lpdserver.py b/lpdserver.py
index 151ab30..d3c9319 100644
--- a/lpdserver.py
+++ b/lpdserver.py
@@ -1,88 +1,92 @@
# Line Printer Daemon implementation, using asynchat
# Chris Shucksmith 2013
-import asynchat, asyncore, socket, exceptions, os
+import asynchat, asyncore, socket, os
import sys
+# 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)
class LpdHandler(asynchat.async_chat):
def __init__(self, sock, addr, controller):
- try:
- asynchat.async_chat.__init__(self, sock=sock)
- except exceptions.TypeError:
- # compat python 2.5.2 bugfix for http://bugs.python.org/issue1519
- asynchat.async_chat.__init__(self, conn=sock)
+ asynchat.async_chat.__init__(self, sock=sock)
self.ibuffer = []
self.sm = AwaitingCommand
- self.set_terminator("\n")
+ self.set_terminator(b"\n")
self.sock = sock
self.controller = controller
self.id = "[lpd-%d]" % addr[1]
print('%s installed LpdHandler' % self.id)
-
+
def collect_incoming_data(self, data):
self.ibuffer.append(data)
print('%s collect_data - %d bytes' % (self.id, len(data)))
def found_terminator(self):
- chunk = self.ibuffer.pop(0)
+ # 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 chunk[0] == '\x02':
- self.queue = chunk[1:]
+ if cmd == b'\x02':
+ self.queue = chunk[1:].decode(ENCODING)
print('%s Incoming job to queue \'%s\'' % (self.id, self.queue))
- self.push('\x00')
+ self.push(b'\x00')
self.sm = NewJob
else:
- print('%s unknown message type %d' + (self.id, self.ibuffer[0]))
+ print('%s unknown message type %r' % (self.id, cmd))
elif self.sm == NewJob: # Recieve Job
- if chunk[0] == '\x02': # Subcommand - Control filename
- sz,name = chunk[1:].split(' ', 1)
+ 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('\x00')
- elif chunk[0] == '\x03': # Subcommand - Data filename
- sz,name = chunk[1:].split(' ', 1)
+ 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
+ # 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('\x00')
+ self.push(b'\x00')
else:
- print('%s recieve job unknown subcommand: 0x%x' % (self.id, chunk[0]))
+ 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].split('\n') if len(x) > 1])
+ 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('\x00')
+ self.push(b'\x00')
self.sm = NewJob
- self.set_terminator("\n")
+ 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('\x00')
+ self.push(b'\x00')
self.close_when_done()
self.dispatch()
else:
- print('%s Unknown state, woken up by terminator, buffer was: %s' % (self.id, repr(self.ibuffer)))
+ 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
+ # 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('\x00')
+ self.push(b'\x00')
self.close_when_done()
elif self.sm == EndOfFile:
self.close()
@@ -91,13 +95,13 @@ def handle_close(self):
self.close()
def dispatch(self):
- data = ''.join(self.ibuffer)
+ data = b''.join(self.ibuffer).decode(ENCODING)
# log exceptions during dispatch so that we get the thread back to perform socket clean up
try:
print('%s dispatching' % (self.id))
self.controller(self.queue, self.sock.getpeername(), self.sock.getsockname(), self.controldata, data)
except Exception as e:
- print('LPD dispatch of print job threw exception: %s', sys.exc_info()[0])
+ print('LPD dispatch of print job threw exception: %s' % sys.exc_info()[0])
print(e)
sys.stdout.flush()
print('%s dispatch complete' % (self.id))
diff --git a/mailer.py b/mailer.py
index 06c9f24..bcdd8c4 100644
--- a/mailer.py
+++ b/mailer.py
@@ -5,43 +5,64 @@
# Import smtplib for the actual sending function
import smtplib
from email.mime.text import MIMEText
-from email.MIMEMultipart import MIMEMultipart
-from email.MIMEBase import MIMEBase
-from email import Encoders
+from email.mime.multipart import MIMEMultipart
+from email.mime.base import MIMEBase
+from email import encoders
+from settings import config, HOME
+from textutil import load_user_pickles, PICKLE_PROTOCOL
# http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python
import datetime
-import ConfigParser, os, threading
-import Queue
+import os, re, threading
+import queue
import traceback
import pickle
-pickle_file = '~/printerface/mailer.pickle'
-
-config = ConfigParser.ConfigParser()
-config.read('defaults.cfg')
-config.read(os.path.expanduser('~/printerface/email.cfg'))
+pickle_file = os.path.join(HOME, 'mailer.pickle')
+
+# An emailed PDF is stored as ///-.pdf (or /raw//-.pdf), so
+# the attachment path of a sent item says which job and which of its documents it came from. is the name
+# the job page knows the document by (an account, 'accounts', 'plain', ...) and is job-YYYYMMDD-HHMMSS.
+_job_ref = re.compile(r'(job-\d{8}-\d{6})-(.+)\.pdf$')
+
+def job_ref(attachment):
+ """(job name, key) for the attachment path of a sent item, or None if it isn't one of ours."""
+ m = _job_ref.search(attachment or '')
+ return (m.group(1), m.group(2)) if m else None
+
+def sent_from_job(results, job_name):
+ """The sent items made from this job, newest first, each with its job key. results is newest first."""
+ prefix = job_name + '-'
+ out = []
+ for r in list(results):
+ if prefix in (r.get('attachment') or ''):
+ ref = job_ref(r['attachment'])
+ if ref and ref[0] == job_name:
+ out.append((r, ref[1]))
+ return out
class JobMailer(object):
def __init__(self, queuesz=10):
- self.queue = Queue.Queue(queuesz)
- self.thread = threading.Thread(target=self.run)
- self.thread.daemon = True
- self.thread.start()
+ self.queue = queue.Queue(queuesz)
self.results = []
- self.resultLimit = config.get('Gmail', 'result_count')
+ self.resultLimit = config.getint('Gmail', 'result_count')
try:
- with open(os.path.expanduser(pickle_file), 'rb') as f:
- p = pickle.Unpickler(f)
- self.results = p.load()
+ with open(pickle_file, 'rb') as f:
+ [self.results] = load_user_pickles(f)
+ except FileNotFoundError:
+ pass
except:
traceback.print_exc()
while len(self.results) > self.resultLimit:
self.results.pop()
+ self.thread = threading.Thread(target=self.run)
+ self.thread.daemon = True
+ self.thread.start()
+
def append(self, job):
job['added'] = datetime.datetime.now()
job['completed']=None
@@ -65,7 +86,7 @@ def run(self):
work['error'] = None
except Exception as e:
- print 'mailq: failed to send email: ' + repr(e)
+ print('mailq: failed to send email: ' + repr(e))
work['completed'] = datetime.datetime.now()
work['error'] = repr(e)
@@ -77,13 +98,13 @@ def run(self):
self.pickleResults()
- except Queue.Empty:
+ except queue.Empty:
print('mailq: idling for jobs')
def pickleResults(self):
try:
- with open(os.path.expanduser(pickle_file), 'wb') as f:
- p = pickle.Pickler(f)
+ with open(pickle_file, 'wb') as f:
+ p = pickle.Pickler(f, protocol=PICKLE_PROTOCOL)
p.dump(self.results)
except Exception as e:
traceback.print_exc()
@@ -105,7 +126,7 @@ def sendJobAttachment(self, text, file, filename, subject="sending with gmail",
part = MIMEBase('application', "octet-stream")
part.set_payload(file.read())
- Encoders.encode_base64(part)
+ encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename)
@@ -118,6 +139,26 @@ def sendJobAttachment(self, text, file, filename, subject="sending with gmail",
s.set_debuglevel(2)
s.close()
+import unittest
+
+class TestSentItemLinks(unittest.TestCase):
+ def test_job_ref(self):
+ self.assertEqual(('job-20261111-111416', 'HAR108'), job_ref('/home/printerface/printerface/data/pdf/2026/HAR108/job-20261111-111416-HAR108.pdf'))
+ self.assertEqual(('job-20150715-101010', 'plain'), job_ref('/x/data/pdf/raw/201507/job-20150715-101010-plain.pdf'))
+ self.assertEqual(('job-20261020-112058', 'AYU100-admin'), job_ref('/x/2026/AYU100/job-20261020-112058-AYU100-admin.pdf'))
+ self.assertEqual(('job-20261020-112058', 'MULTI-21'), job_ref('/x/2026/MULTI-21/job-20261020-112058-MULTI-21.pdf'))
+ self.assertEqual(('job-20261020-112058', 'accounts'), job_ref('C:\\\\x\\\\2026\\\\accounts\\\\job-20261020-112058-accounts.pdf'))
+ for bad in ('', None, '/x/report.pdf', '/x/job-1-2-3.pdf', '/x/job-20261020-112058.pdf', '/x/job-20261020-112058-A.txt'):
+ self.assertIsNone(job_ref(bad), bad)
+
+ def test_sent_from_job(self):
+ mk = lambda att, n: {'attachment': att, 'subject': n}
+ results = [mk('/p/2026/B/job-20261111-111416-B.pdf', 'newest'), mk('/p/2026/A/job-20261111-111416-A.pdf', 'a'),
+ mk('/p/2026/A/job-20261111-111417-A.pdf', 'other job'), mk('', 'no attachment'), {'subject': 'no key'}]
+ found = sent_from_job(results, 'job-20261111-111416')
+ 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
@@ -133,6 +174,6 @@ def sendJobAttachment(self, text, file, filename, subject="sending with gmail",
print(mailq.results)
- print 'done'
+ print('done')
diff --git a/main.py b/main.py
index e13561b..ee9210d 100755
--- a/main.py
+++ b/main.py
@@ -1,6 +1,4 @@
-#!/usr/bin/env python2.7
-
-from __future__ import with_statement
+#!/usr/bin/env python3.11
from mako.template import Template
from mako.lookup import TemplateLookup
@@ -9,27 +7,31 @@
import asynchat, asyncore, socket, os, re
from datetime import datetime
from lpdserver import LpdServer
-from httpserver import ToyHttpServer
+from httpserver import ToyHttpServer, Redirect
+import mailer
from mailer import JobMailer
from docparser import DocParser
from stationary import DocFormatter
from printing import getPrinters, printFile
+import printing
+import printstatus
-import sys, pickle, ConfigParser
-from StringIO import StringIO
+import sys, pickle
+import html
+import urllib.parse
+from io import StringIO
import collections
import traceback
import json
import time
import pytz
+from settings import config, HOME
+import emailtemplates
+from textutil import split_lines, load_job_pickle, load_user_pickles, PICKLE_PROTOCOL
-config = ConfigParser.ConfigParser()
-config.readfp(open(os.path.expanduser('defaults.cfg')))
-config.read(os.path.expanduser('~/printerface/email.cfg'))
-
-email_pickle = os.path.expanduser('~/printerface/email.pickle')
+email_pickle = os.path.join(HOME, 'email.pickle')
-data_dir = os.path.expanduser("~/printerface/data/")
+data_dir = os.path.join(HOME, 'data') + os.sep
jobdir = os.path.join(data_dir, 'pickle')
pdfdir = os.path.join(data_dir, 'pdf/')
@@ -42,6 +44,8 @@
# seed some 'system' accounts
email_accounts = { 'accounts': 'Accounts', 'plain': 'printerface', 'transport': 'Transport'}
email_addresses = collections.defaultdict(dict)
+# the single email text from before there were templates. Kept (and written back) so email.pickle keeps its
+# layout, but only used to migrate it to templates/default.mako, see emailtemplates.migrate_legacy_default
email_template = ''
mainparser = DocParser()
@@ -60,17 +64,18 @@ def saveJob(queue, local, remote, control, data):
subdir = ts.strftime('%Y%m')
d = {'queue':queue, 'from':repr(local), 'to':repr(remote), 'control':control, 'data':data, 'ts': ts, 'name':jobname}
- try:
- os.makedirs(os.path.join(jobdir, subdir))
- except:
- pass
+ os.makedirs(os.path.join(jobdir, subdir), exist_ok=True)
- f = file(os.path.join(jobdir, subdir, jobname), "wb")
- pickle.dump(d, f)
- f.close()
+ with open(os.path.join(jobdir, subdir, jobname), "wb") as f:
+ pickle.dump(d, f, protocol=PICKLE_PROTOCOL)
cleanJob(d)
- autoPrint(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)
jobs.insert(0, d)
if len(jobs) > loadQty: jobs.pop()
@@ -81,14 +86,18 @@ def autoPrint(job):
if job['autoprint']:
printer = job['autoprint']
for (groupnum, gname) in enumerate(job['groupkey']):
- for (dockey, doc) in job['groupfiles'].iteritems():
+ for (dockey, doc) in job['groupfiles'].items():
if doc:
- printFile(pdfdir + doc, printer )
- print( 'auto printing: Document %s sent to printer %s' % (doc, printer))
+ try:
+ printFile(pdfdir + doc, printer )
+ print( 'auto printing: Document %s sent to printer %s' % (doc, printer))
+ except Exception as e:
+ # 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 saveEmails():
with open(email_pickle, 'wb') as f:
- p = pickle.Pickler(f)
+ p = pickle.Pickler(f, protocol=PICKLE_PROTOCOL)
p.dump(email_addresses)
p.dump(email_accounts)
p.dump(email_template)
@@ -98,17 +107,20 @@ def recover():
global email_template
try:
with open(email_pickle, 'rb') as f:
- p = pickle.Unpickler(f)
- for (k,v) in p.load().iteritems():
+ (addresses, accounts, email_template) = load_user_pickles(f, 3)
+ for (k,v) in addresses.items():
email_addresses[k].update(v)
- email_accounts.update(p.load())
- email_template = p.load()
+ email_accounts.update(accounts)
print('recovered emails: %s' % email_addresses)
print('recovered accounts: %s' % email_accounts)
except IOError:
print('[control] email pickle load failed')
+ migrated = emailtemplates.migrate_legacy_default(email_template)
+ if migrated:
+ print('[control] ' + migrated)
+
# jobdir structured /YYYYMM/job-blah-blah.pickle. We want to avoid stating
# more dated directories than necessary, so load the
# xs = sorted([ x for x in os.listdir(jobdir) if x != 'raw'])
@@ -118,8 +130,8 @@ def recover():
p = os.path.join(jobdir, yyyymmdir, x)
if not os.path.isfile(p): continue
try:
- with file(p, "rb") as f:
- s = pickle.load(f)
+ with open(p, "rb") as f:
+ s = load_job_pickle(f)
s['name'] = x;
jobs.append(s)
except Exception as e:
@@ -130,7 +142,9 @@ def recover():
for j in jobs:
cleanJob(j)
-control_char_re = re.compile('[^\w\s%s_\'=/]' % re.escape('.*+()-\\;:,#?%$^&!<>|`"'))
+# 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):
print(' recovering %s' % j['name'])
@@ -139,10 +153,10 @@ def cleanJob(j):
# handle input
j['plain'] = control_char_re.sub(' ', j['data'])
- summary = re.compile('[^\w\s]').sub('', j['data'])
+ summary = re.compile(r'[^\w\s]', re.ASCII).sub('', j['data'])
for r in summary_regexps:
summary = r.sub(' ', summary)
- summary = re.compile('\s+').sub(' ', summary)
+ summary = re.compile(r'\s+', re.ASCII).sub(' ', summary)
summary = summary.strip()[0:120]
j['summary'] = summary
@@ -162,7 +176,7 @@ def cleanJob(j):
if not j['colouring']: del j['colouring']
if j['parsed']:
- for y in j['parsed'].itervalues():
+ for y in j['parsed'].values():
for x in y:
acc = None
addr = None
@@ -187,7 +201,7 @@ def cleanJob(j):
# groups {('all'): p}, ('all')
(j['groupfiles'], j['groupkey']) = formatter.format(j)
- #for f in j['groupfiles'].itervalues():
+ #for f in j['groupfiles'].values():
# from subprocess import call
# proc = ['convert','-size','150x150','%s[0]' % f, '%s.png' % f]
# print(proc)
@@ -214,12 +228,12 @@ def identify(j):
def home(query_string='', resp=None):
email_fails = sum([1 for x in mailqueue.results if x['error']])
- account = sum([ 1 for k in email_accounts.iterkeys() if len(email_addresses[k]) > 0 ]), len(email_accounts.keys())
+ 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'
def getrows_byslice(seq, rowlen):
- for start in xrange(0, len(seq), rowlen):
- yield seq[start:start+rowlen]
+ for start in range(0, len(seq), rowlen):
+ yield seq[start:start+rowlen]
def recent(query_string=dict(), resp=None):
query = query_string.get('query', [''])[0]
@@ -239,7 +253,7 @@ def recent(query_string=dict(), resp=None):
if fmt == 'json':
nextQry = base_uri + '/recent?query={query}&templ={templ}&doctype={doctype}&page={page}&fmt={fmt}'.format(query=query, templ=templ, doctype=doctype, page=page+1, fmt=fmt)
output = { 'results': [
- { 'name': p['name'], 'host': p['control'].get('H'), 'doctype': p['doctype'], 'ts': j['ts'].isoformat(), 'details':
+ { 'name': p['name'], 'host': p['control'].get('H'), 'doctype': p['doctype'], 'ts': p['ts'].isoformat(), 'details':
('' if not p['templ'] else '{base}/job?name={name}'.format(base=base_uri, name=p['name'])) }
for p in pagejobs[page]
], 'next': '' if page >= len(pagejobs)-1 else nextQry }
@@ -259,104 +273,241 @@ def job(query_string=dict(), resp=None):
'doctype': job.get('doctype'),
'autofmt': job.get('autofmt'),
'stationary':
- dict([ (' '.join(k), '{base}/pdf/{pdf}'.format(base=base_uri, pdf=v)) for k,v in job.get('groupfiles', {}).iteritems() ])
+ dict([ (' '.join(k), '{base}/pdf/{pdf}'.format(base=base_uri, pdf=v)) for k,v in job.get('groupfiles', {}).items() ])
}
return json.dumps(output, indent=3), 'text/json'
def printers(query_string='', resp=None):
- return ( template_lookup.get_template("/printers.html").render(printers=getPrinters()), 'text/html')
+ """What CUPS says about the printers and the auto-print setup. Read-only: lpstat is the only thing run."""
+ auto_types = [t for t in config.get('Robot', 'auto_types').split(',') if t]
+ auto_printer = config.get('Robot', 'auto_printer')
+ try:
+ st = printstatus.status()
+ error = None
+ verdict = printstatus.assess(st, auto_printer)
+ except printstatus.LpstatError as e:
+ st, error, verdict = None, str(e), None
+ return ( template_lookup.get_template("/printers.html").render(st=st, error=error, verdict=verdict,
+ auto_types=auto_types, auto_printer=auto_printer, humanise=printstatus.humanise,
+ now=datetime.now(), stale=printstatus.STALE_AFTER), 'text/html')
+
+# The Sent Emails page only shows this many of the most recent emails, however long the history is: the
+# history goes back years and the whole of it makes a page of many MB.
+SENT_SHOWN = 100
def sent(query_string='', resp=None):
- return ( template_lookup.get_template("/sent.html").render(mailqueue=mailqueue), 'text/html')
+ results = mailqueue.results # newest first; the mail thread inserts at the front
+ loaded = set(j['name'] for j in jobs)
+ rows = []
+ for p in results[:SENT_SHOWN]:
+ ref = mailer.job_ref(p.get('attachment'))
+ # only jobs still in memory can be opened; for older ones the name is shown without a link
+ rows.append(dict(p=p, job=ref[0] if ref else None, key=ref[1] if ref else None, loaded=bool(ref and ref[0] in loaded)))
+ return ( template_lookup.get_template("/sent.html").render(rows=rows, total=len(results)), 'text/html')
+
+def printed(query_string='', resp=None):
+ results = printing.printlog.records # newest first
+ loaded = set(j['name'] for j in jobs)
+ 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 settings_email(query_string='', postreq=None, resp=None):
- warning=None
- print('query_string=%s' % query_string)
- try:
- acc = query_string['account'][0]
- email = query_string['email'][0]
- contact = query_string['contact'][0]
- try:
- email_accounts[acc]
- if not email.strip() in email_addresses[acc]:
- email_addresses[acc][email.strip()] = contact
+ """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."""
+ if postreq is not None:
+ account = postreq.get('account', [''])[0]
+ warning = None
+ if 'delete' in postreq:
+ if email_addresses[account].pop(postreq['delete'][0], None):
saveEmails()
- except KeyError:
- warning='Unknown account %s' % acc
- except KeyError:
- pass
-
- try:
- acc = query_string['account'][0]
- delete_email = query_string['delete'][0]
- if email_addresses[acc].pop(delete_email, None):
- saveEmails()
- except KeyError:
- pass
+ elif 'email' in postreq and 'contact' in postreq:
+ email = postreq['email'][0].strip()
+ if account not in email_accounts:
+ warning = 'Unknown account %s' % account
+ elif email not in email_addresses[account]:
+ email_addresses[account][email] = postreq['contact'][0]
+ saveEmails()
+ return Redirect('/settings/email' + ('?' + urllib.parse.urlencode({'warning': warning}) if warning else ''))
+ warning = html.escape(query_string.get('warning', [''])[0]) or None
email_list = []
- for key in sorted(email_accounts.iterkeys()):
- email_list.append( (key, email_accounts[key], email_addresses[key].iteritems()) )
+ for key in sorted(email_accounts):
+ email_list.append( (key, email_accounts[key], list(email_addresses[key].items())) )
return ( template_lookup.get_template("/settings_email.html").render(emails=email_list, warning=warning), 'text/html')
-def settings_template(query_string='', postreq=None, resp=None):
- global email_template
-
- print('query_string=%s' % query_string)
- message = None
- try:
- template = query_string.get('template', None)
- if template:
- email_template = template[0]
- saveEmails()
- message = 'Thanks! Template updated'
- except:
- message = 'Ohno! Template failed'
- return ( template_lookup.get_template("/settings_template.html").render(template=email_template, message=message), 'text/html')
-
-def printfn(query_string='', resp=None):
- docf = getJobFile(query_string)
- if docf:
+def printfn(query_string='', postreq=None, resp=None):
+ """Print a document on one of the printers. Paper comes out, so only a POST does it, and it redirects back
+ to the job page so that a refresh doesn't print it again."""
+ if postreq is None:
+ return doMessage(title='Printing', message='Documents are printed from their job page.')
+ job = getJob(postreq)
+ docf = getJobFile(postreq, job)
+ printer = postreq.get('printer', [''])[0]
+ if docf and printer:
try:
- printFile(pdfdir + docf, ''.join(query_string['printer']) )
- return doMessage(title='Printing', message='Document %s sent to printer %s ' % (docf, query_string['printer']))
- except:
+ printFile(pdfdir + docf, printer)
+ key = postreq.get('key', [next(iter(job['groupfiles']))[0]])[0]
+ return Redirect('/pdf?' + urllib.parse.urlencode({'name': job['name'], 'key': key, 'printed': printer}))
+ except Exception as e:
traceback.print_exc(file=sys.stdout)
- return doMessage(title='Printing', message='Could not find document, problem printing! Source: %s sent to printer %s ' % (docf, query_string['printer']))
-
-def pdf(query_string=dict(), resp=None):
+ return doMessage(title='Printing', message='The document was not printed: %s Source: %s sent to printer %s ' % (html.escape(str(e)), html.escape(str(docf)), html.escape(printer)))
+ return doMessage(title='Printing', message='Could not find the document, or a problem printing it! Source: %s sent to printer %s ' % (html.escape(str(docf)), html.escape(printer)))
+
+def company_info():
+ printing = lambda k: config.get('Printing', k, fallback='')
+ return {'name': printing('address').split('\\n')[0].strip(), 'email': printing('email'), 'website': printing('website')}
+
+def settings_templates(query_string='', postreq=None, resp=None):
+ """Editor for the per document type email templates, with a preview against a real document. A POST
+ (postreq is not None) carries the edited text and one of the actions preview, save or revert."""
+ params = dict((k, v[0]) for k, v in query_string.items())
+ posted = postreq is not None
+ params.update(dict((k, v[0]) for k, v in (postreq or {}).items()))
+ kind = params.get('kind', 'invoice')
+ if kind not in emailtemplates.KINDS:
+ kind = 'invoice'
+ term = params.get('docnum', '').strip()
+ action = params.get('action', '') if posted else ''
+
+ def back(**flash):
+ return Redirect('/settings/templates?' + urllib.parse.urlencode(dict(kind=kind, docnum=term, **flash)))
+
+ text, source = emailtemplates.load(kind)
+ message, errors = None, []
+ if action == 'revert':
+ return back(reverted='1' if emailtemplates.revert(kind) else '0')
+ elif action in ('preview', 'save'):
+ text = params.get('template', '').replace('\r\n', '\n').replace('\r', '\n')
+ if action == 'save':
+ try:
+ emailtemplates.save(kind, text)
+ return back(saved='1')
+ except emailtemplates.TemplateError as e:
+ errors = e.errors
+ elif not posted:
+ # back from a save or revert: the redirect only says which
+ if params.get('saved'):
+ message = 'Saved the %s template.' % emailtemplates.KINDS[kind].lower()
+ elif params.get('reverted') == '1':
+ message = 'Reverted to the shipped %s template.' % emailtemplates.KINDS[kind].lower()
+ elif params.get('reverted') == '0':
+ message = 'Already using the shipped template.'
+
+ # preview: the newest document of this type, or the one whose document number / account matches the filter
+ # (for the default template: the newest other document, or the job name / document type that matches)
+ found = emailtemplates.find_document(jobs, kind, term)
+ is_default = kind == emailtemplates.DEFAULT
+ preview, preview_subject, preview_job, preview_acc, fields, summary_fields, names = None, None, None, None, [], [], []
+ if not found:
+ what = 'document' if is_default else '%s document' % emailtemplates.KINDS[kind].lower()
+ preview_note = 'No %s found%s.' % (what, (' matching "%s"' % term) if term else '')
+ else:
+ preview_job, preview_acc = found
+ contacts = email_addresses.get(preview_acc, {})
+ names = list(contacts.values())
+ ctx = emailtemplates.build_context(preview_job, preview_acc, names=names, addresses=list(contacts.keys()), company=company_info())
+ fields = emailtemplates.field_names(ctx['doc']) if 'doc' in ctx else []
+ summary_fields = emailtemplates.field_names(ctx['all']) if 'all' in ctx else []
+ preview_note = None
+ try:
+ rendered = emailtemplates.render_message(text, ctx, kind)
+ preview, preview_subject = rendered.body, rendered.subject
+ except emailtemplates.TemplateError as e:
+ errors = errors or e.errors
+
+ return ( template_lookup.get_template("/settings_templates.html").render(
+ kinds=emailtemplates.KINDS, kind=kind, text=text, source=source, filename=os.path.basename(emailtemplates.user_path(kind)),
+ term=term, message=message, errors=errors, preview=preview, preview_subject=preview_subject, preview_note=preview_note,
+ preview_job=preview_job, preview_acc=preview_acc, names=names, fields=fields, summary_fields=summary_fields, is_default=is_default), 'text/html')
+
+def email_body(query_string=dict(), resp=None):
+ """The suggested email text for a document if only the contacts whose addresses are in 'em' are
+ recipients. The compose form asks for this when contacts are ticked or unticked, since a template can use
+ the recipients' names. No 'em' means no recipients. Answers {"subject": ..., "body": ..., "warning": ...}."""
job = getJob(query_string)
- default_key = job['groupfiles'].iterkeys().next()[0]
+ default_key = next(iter(job.get('groupfiles') or {}), ('',))[0]
key = query_string.get('key', [default_key])[0]
+ known = email_addresses.get(key, {})
+ ticked = query_string.get('em', [])
+ message, kind, warning = emailtemplates.render_for_job(
+ job, key, names=[known[a] for a in ticked if a in known], addresses=ticked, company=company_info())
+ return json.dumps({'subject': message.subject, 'body': message.body, 'warning': warning}), 'text/json'
+
+def pdf(query_string=dict(), postreq=None, resp=None):
+ """A job's document page. Sending the email is a POST (the form); it redirects back here, so a refresh of
+ the page never sends it again. A GET only ever shows the page."""
+ params = dict(query_string)
+ if postreq is not None:
+ params.update(postreq)
+ job = getJob(params)
+ if not job.get('groupfiles'):
+ name = params.get('name', [''])[0]
+ return doMessage(title='Job not found', message='There is no job %s loaded. Only the most recent jobs are kept in memory, so older ones '
+ 'can\'t be opened here. Recent documents' % (html.escape(name) or '(none given)'))
+ default_key = next(iter(job['groupfiles']))[0]
+ key = params.get('key', [default_key])[0]
email_dest = email_addresses.get(key, {})
email_outcome, email_error = None, None
+ typed = None # what the user typed, kept if the send is refused so that nothing has to be retyped
- # test if callback from email form
- try:
- addresses = query_string.get('em', [])
- email_body = ''.join(query_string.get('emailbody', ['']))
- email_subject = ''.join(query_string.get('subject', ['no subject']))
- action = query_string.get('action', None)
-
- docf = getJobFile(query_string)
-
+ if postreq is not None and params.get('action', [''])[0] == 'send':
+ addresses = params.get('em', [])
+ email_subject = ''.join(params.get('subject', ['']))
+ email_body = ''.join(params.get('emailbody', ['']))
+ docf = getJobFile(params, job)
if len(addresses) > 0 and docf and len(email_subject) > 1:
- email_outcome = "Queueing email to " + ','.join(addresses) + ' - check the result later!';
- print(email_outcome)
try:
- mailqueue.append(dict(
- to=addresses, body=email_body, subject=email_subject,
- attachment=pdfdir + docf))
- except:
+ mailqueue.append(dict(to=addresses, body=email_body, subject=email_subject, attachment=pdfdir + docf))
+ print('Queueing email to ' + ','.join(addresses))
+ return Redirect('/pdf?' + urllib.parse.urlencode({'name': job['name'], 'key': key, 'queued': len(addresses)}))
+ except Exception:
traceback.print_exc(file=sys.stdout)
email_error = "Problem! unable to queue email!"
- elif action:
+ else:
email_error = "Oh snap! Some fields missing or incomplete!"
- except:
- raise
+ typed = dict(subject=email_subject, body=email_body, ticked=addresses)
+ 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:
+ 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])
+
+ # the suggested subject and body come from the template for this type of document (or the default template)
+ email_subject_default, email_body_default = '', ''
+ template_kind, template_warning, template_docnum = emailtemplates.DEFAULT, None, ''
+ try:
+ message, template_kind, template_warning = emailtemplates.render_for_job(
+ job, key, names=list(email_dest.values()), addresses=list(email_dest.keys()), company=company_info())
+ email_subject_default, email_body_default = message.subject, message.body
+ except Exception:
+ traceback.print_exc(file=sys.stdout)
+ template_warning = 'The email template for this document could not be used.'
+ if typed:
+ email_subject_default, email_body_default = typed['subject'], typed['body']
+
+ # emails made from this job that are still in the sent history, newest first
+ 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'])
+
+ # what the editor's preview filter should be set to so that it shows this document
+ if template_kind == emailtemplates.DEFAULT:
+ template_docnum = job.get('name', '')
+ else:
+ parsed = job.get('parsed') or {}
+ pages = parsed.get(emailtemplates.account_for_key(parsed, key)) or [{}]
+ 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_template, email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html')
+ 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,
+ 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')
def pdf_file(query_string='', resp=None):
@@ -390,12 +541,14 @@ def getJob(query_string, returnLast=False):
def getJobFile(query_string, job=None):
if not job:
job = getJob(query_string)
- default_key = job['groupfiles'].iterkeys().next()[0]
+ if not job.get('groupfiles'):
+ return None
+ default_key = next(iter(job['groupfiles']))[0]
key = query_string.get('key', [default_key])[0]
docf = None
for (groupnum, gname) in enumerate(job['groupkey']):
- for (dockey,doc) in job['groupfiles'].iteritems():
+ for (dockey,doc) in job['groupfiles'].items():
if dockey[groupnum] == key:
docf = doc
@@ -414,7 +567,7 @@ def debug(query_string=dict(), resp=None):
colouring = job.get('colouring', [])
- lines = job['plain'].splitlines()
+ lines = split_lines(job['plain'])
(rows, cols) = (len(lines), max([len(line) for line in lines]))
cols = max([cols] + [c['c']+c['w'] for c in colouring])
@@ -427,7 +580,7 @@ def debug(query_string=dict(), resp=None):
for col in range(c['c'], c['c']+c['w']):
high[row][col] = c
- chunks10 = (cols+9)/10
+ chunks10 = (cols+9)//10
f = StringIO()
f.write(' ' + ''.join(["%-10d" % (d*10) for d in range(chunks10)]))
f.write('\n ' + ('0123456789' * chunks10))
@@ -457,42 +610,45 @@ def htmlcol(rgb):
return ( template_lookup.get_template("/debug.html").render( job=job,
rows=rows, cols=cols, coloured_plaintext=f.getvalue(), pformatted=pformatted), 'text/html')
+path_handlers = {
+ '/recent': recent,
+ '/home':home,
+ '/debug':debug,
+ '/raw':raw,
+ '/job': job,
+ '/printers':printers,
+ '/pdf':pdf,
+ '/pdf_file': pdf_file,
+ '/sent':sent,
+ '/printed':printed,
+ '/print' : printfn,
+ '/plaintext':plain,
+ '/settings/email':settings_email,
+ '/settings/templates':settings_templates,
+ '/email_body':email_body
+ }
+
if __name__=="__main__":
# launch the server on the specified port
for x in [jobdir, pdfdir]:
- try:
- os.makedirs(x)
- except:
- pass
+ os.makedirs(x, exist_ok=True)
recover()
s = LpdServer(saveJob, ip='', port=int(config.get('Main', 'lpd_port')))
- ToyHttpServer(port=int(config.get('Main', 'http_port')), pathhandlers={
- '/recent': recent,
- '/home':home,
- '/debug':debug,
- '/raw':raw,
- '/job': job,
- '/printers':printers,
- '/pdf':pdf,
- '/pdf_file': pdf_file,
- '/sent':sent,
- '/print' : printfn,
- '/plaintext':plain,
- '/settings/email':settings_email,
- '/settings/template':settings_template
- }, webroot=web_dir)
+ 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()
except KeyboardInterrupt:
print("Crtl+C pressed. Shutting down.")
+ printing.printlog.flush()
except:
- print("Terminating: Unexpected error: %s", sys.exc_info()[0])
+ print("Terminating: Unexpected error: %s" % sys.exc_info()[0])
sys.stdout.flush()
raise
diff --git a/printing.py b/printing.py
index f71f8aa..66ed047 100644
--- a/printing.py
+++ b/printing.py
@@ -1,33 +1,187 @@
-#!/usr/bin/python
-import sys
+#!/usr/bin/env python3
+import datetime
+import os
+import pickle
+import re
import subprocess
+import traceback
+import unittest
+import unittest.mock as mock
+
+import mailer
+import printstatus
+from settings import config, HOME
+from textutil import PICKLE_PROTOCOL
+
+PRINT_TIMEOUT = 30
+pickle_file = os.path.join(HOME, 'printer.pickle')
+
+
+class PrintError(Exception):
+ pass
+
+
+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."""
+
+ 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.records = []
+ self.dirty = False
+ if path:
+ try:
+ with open(path, 'rb') as f:
+ self.records = pickle.load(f)
+ except FileNotFoundError:
+ pass
+ except Exception:
+ traceback.print_exc()
+ del self.records[self.limit:]
+
+ def add(self, record):
+ self.records.insert(0, record)
+ del self.records[self.limit:]
+ self.dirty = True
+
+ def for_job(self, job_name):
+ """The records made from this job, newest first."""
+ return [r for r in self.records if r.get('job') == job_name]
+
+ def flush(self):
+ """Write the history if it changed. Never raises: a full disk mustn't stop the server."""
+ if not self.dirty or not self.path:
+ return
+ try:
+ tmp = self.path + '.tmp'
+ with open(tmp, 'wb') as f:
+ pickle.dump(self.records, f, protocol=PICKLE_PROTOCOL)
+ os.replace(tmp, self.path)
+ self.dirty = False
+ except Exception:
+ traceback.print_exc()
+
+
+printlog = PrintLog(pickle_file)
-printers = []
def getPrinters():
- global printers
- if not sys.platform == "linux2":
- return ['default']
- if len(printers) > 0: return printers
+ """Names of the CUPS queues, as the Printers page sees them (same lpstat call, so the two always agree).
+ Empty if CUPS can't be asked, so the print menu is empty rather than offering a queue that doesn't exist."""
try:
- process = subprocess.Popen(["lpstat", "-a"], stdout=subprocess.PIPE)
- result = process.communicate()[0].strip()
- # KONICA_bizhub_192.168.12.10 accepting requests since Sun 16 Dec 2012 07:43:59 PM GMT
- print(result)
- printers = [x.split(' ')[0] for x in result.split('\n')]
- print('[print] printers=%s' % repr(printers))
- except OSError as e:
- print('[print] %s' % repr(e))
- return printers
+ return [p.name for p in printstatus.status().printers]
+ except printstatus.LpstatError as e:
+ print('[print] %s' % e)
+ return []
def printFile(file, printer):
- cmd = ["lpr","-P", printer, file]
- print("[print] printer=%s file=%s cmd=%s" %(printer, file, repr(cmd) ))
- process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
- results = process.communicate()
- results = (None,None)
- print("[print] printer=%s file=%s cmd=%s result=%s" %(printer, file, repr(cmd), repr(results)))
+ """Send a PDF to a CUPS queue with lp, record the outcome in printlog and return the record. lp reports the
+ job's CUPS request id (KONICA_bizhub_192.168.12.10-12345), which is how the job shows up in lpstat.
+ Raises PrintError, after recording it, if the job was not accepted."""
+ cmd = ['lp', '-d', printer, file]
+ ref = mailer.job_ref(file)
+ record = {'job': ref[0] if ref else None, 'key': ref[1] if ref else None, 'file': file, 'printer': printer,
+ 'request_id': None, 'added': datetime.datetime.now(), 'error': None}
+ try:
+ p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=PRINT_TIMEOUT,
+ env=dict(os.environ, LC_ALL='C', LANG='C'), universal_newlines=True)
+ m = re.search(r'request id is (\S+)', p.stdout)
+ record['request_id'] = m.group(1) if m else None
+ if p.returncode != 0:
+ record['error'] = (p.stderr or p.stdout).strip() or 'lp failed (exit %d)' % p.returncode
+ except FileNotFoundError:
+ record['error'] = 'lp is not installed on this machine'
+ except subprocess.TimeoutExpired:
+ record['error'] = 'lp did not finish within %d seconds' % PRINT_TIMEOUT
+ except OSError as e:
+ record['error'] = 'lp could not be run: %s' % e
+ print("[print] printer=%s file=%s request=%s error=%s" % (printer, file, record['request_id'], record['error']))
+ printlog.add(record)
+ if record['error']:
+ raise PrintError(record['error'])
+ return record
+
+
+class TestPrintFile(unittest.TestCase):
+ PDF = '/p/2026/ACC001/job-20261119-101010-ACC001.pdf'
+
+ def setUp(self):
+ self.log = PrintLog(None, limit=3)
+ patch = mock.patch.object(__import__(__name__), 'printlog', self.log)
+ patch.start()
+ self.addCleanup(patch.stop)
+
+ def lp(self, stdout='', stderr='', code=0):
+ return mock.patch('subprocess.run', return_value=subprocess.CompletedProcess([], code, stdout, stderr))
+
+ def test_records_the_request_id_against_job_and_key(self):
+ with self.lp('request id is KONICA_bizhub_192.168.12.10-12345 (1 file(s))\n') as run:
+ rec = printFile(self.PDF, 'KONICA_bizhub_192.168.12.10')
+ self.assertEqual(['lp', '-d', 'KONICA_bizhub_192.168.12.10', self.PDF], run.call_args[0][0])
+ self.assertEqual('KONICA_bizhub_192.168.12.10-12345', rec['request_id'])
+ self.assertEqual(('job-20261119-101010', 'ACC001', None), (rec['job'], rec['key'], rec['error']))
+ self.assertEqual([rec], self.log.for_job('job-20261119-101010'))
+ self.assertEqual([], self.log.for_job('job-20000101-000000'))
+ self.assertTrue(self.log.dirty)
+
+ def test_a_refused_job_is_recorded_and_raised(self):
+ with self.lp(stderr='lp: The printer or class does not exist.\n', code=1):
+ with self.assertRaisesRegex(PrintError, 'does not exist'):
+ printFile(self.PDF, 'default')
+ self.assertEqual('lp: The printer or class does not exist.', self.log.records[0]['error'])
+ self.assertIsNone(self.log.records[0]['request_id'])
+
+ def test_no_lp_and_timeouts(self):
+ with mock.patch('subprocess.run', side_effect=FileNotFoundError()):
+ with self.assertRaisesRegex(PrintError, 'not installed'):
+ printFile(self.PDF, 'x')
+ with mock.patch('subprocess.run', side_effect=subprocess.TimeoutExpired('lp', 30)):
+ with self.assertRaisesRegex(PrintError, 'did not finish'):
+ printFile(self.PDF, 'x')
+ self.assertEqual(2, len(self.log.records))
+
+ def test_a_file_that_is_not_ours_has_no_job(self):
+ with self.lp('request id is Q-1 (1 file(s))'):
+ rec = printFile('/tmp/report.pdf', 'Q')
+ self.assertEqual((None, None), (rec['job'], rec['key']))
+
+ def test_keeps_only_the_newest(self):
+ with self.lp('request id is Q-1 (1 file(s))'):
+ for _ in range(5):
+ printFile(self.PDF, 'Q')
+ self.assertEqual(3, len(self.log.records))
+
+
+class TestPrintLog(unittest.TestCase):
+ def test_flush_only_when_dirty_and_survives_a_restart(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, 'printer.pickle')
+ log = PrintLog(path, limit=2)
+ log.flush()
+ self.assertFalse(os.path.exists(path)) # nothing to write yet
+ for n in range(3):
+ log.add({'job': 'job-1', 'n': n})
+ self.assertTrue(log.dirty)
+ log.flush()
+ self.assertFalse(log.dirty)
+ self.assertEqual([2, 1], [r['n'] for r in PrintLog(path, limit=2).records])
+ self.assertEqual([2], [r['n'] for r in PrintLog(path, limit=1).records]) # a smaller limit trims on load
+ os.remove(path)
+ log.flush()
+ self.assertFalse(os.path.exists(path)) # clean: not rewritten
+
+ def test_a_corrupt_file_starts_empty(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, 'printer.pickle')
+ open(path, 'wb').write(b'garbage')
+ with mock.patch('traceback.print_exc'):
+ self.assertEqual([], PrintLog(path, limit=2).records)
+
if __name__=="__main__":
print ('Installed printers: %s' % repr(getPrinters()))
-
diff --git a/printstatus.py b/printstatus.py
new file mode 100644
index 0000000..3c6d49c
--- /dev/null
+++ b/printstatus.py
@@ -0,0 +1,339 @@
+#!/usr/bin/env python3
+# Read-only view of CUPS for the Printers page: one `lpstat -t` call, parsed, plus a plain-English verdict on
+# whether automatic printing can be expected to work.
+#
+# lpstat only produces text meant for people, and in the locale of the server, so we ask for the C locale
+# ("Wed Sep 9 15:02:14 2026", no timezone). It says nothing about whether a job came out of the printer:
+# a job leaves the queue when CUPS has handed it to the device, and a queue stuck "Connecting to printer..."
+# is the only sign of trouble. So this page can show a stuck queue, but never prove a page was printed.
+import os
+import re
+import subprocess
+import time
+from collections import namedtuple
+from datetime import datetime, timedelta
+
+LPSTAT_TIMEOUT = 5
+CACHE_SECONDS = 10
+STALE_AFTER = timedelta(hours=1) # a job waiting longer than this on a working printer is not "about to print"
+
+Printer = namedtuple('Printer', 'name device state job since accepting accepting_since message reason reject_reason')
+Job = namedtuple('Job', 'id printer user size submitted')
+Status = namedtuple('Status', 'scheduler default printers jobs fetched')
+
+
+class LpstatError(Exception):
+ pass
+
+
+def run_lpstat():
+ """Text of `lpstat -t` in the C locale, or LpstatError if it can't be had."""
+ env = dict(os.environ, LC_ALL='C', LANG='C')
+ try:
+ p = subprocess.run(['lpstat', '-t'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
+ timeout=LPSTAT_TIMEOUT, universal_newlines=True)
+ except FileNotFoundError:
+ raise LpstatError('lpstat is not installed on this machine')
+ except subprocess.TimeoutExpired:
+ raise LpstatError('lpstat did not answer within %d seconds' % LPSTAT_TIMEOUT)
+ except OSError as e:
+ raise LpstatError('lpstat could not be run: %s' % e)
+ if p.returncode != 0:
+ # cupsd stopped: "lpstat: Bad file descriptor" / "Unable to connect to server"
+ raise LpstatError((p.stderr or p.stdout).strip() or 'lpstat failed (exit %d)' % p.returncode)
+ return p.stdout
+
+
+def mask_uri(uri):
+ """A device URI can carry a password (ipp://user:secret@host/...): never show that part."""
+ return re.sub(r'^([a-z][a-z0-9+.-]*://)[^/@]*@', r'\1', uri.strip(), flags=re.I)
+
+
+def parse_date(text):
+ """'Wed Sep 9 15:02:14 2026' (C locale) as a naive local datetime, else None."""
+ text = ' '.join(text.split())
+ # a trailing zone name ("BST") is dropped: strptime's %Z only knows UTC, GMT and the local zone's names, so
+ # it would parse on one machine and not another
+ text = re.sub(r' [A-Z]{2,5}$', '', text)
+ for fmt in ('%a %b %d %H:%M:%S %Y', '%a %d %b %Y %I:%M:%S %p', '%a %d %b %Y %H:%M:%S'):
+ try:
+ return datetime.strptime(text, fmt)
+ except ValueError:
+ continue
+ return None
+
+
+_SINCE = r'(?P.*?)(?:\s+-)?'
+_ACCEPTING = re.compile(r'^(?P\S+) (?Paccepting|not accepting) requests since ' + _SINCE + r'$')
+_DEVICE = re.compile(r'^device for (?P[^:]+): (?P.*)$')
+_PRINTER = re.compile(r'^printer (?P\S+) (?:(?Pis idle)|now printing (?P\S+?)|(?Pdisabled))\.?\s+'
+ r'(?:enabled )?since ' + _SINCE + r'$')
+_JOB = re.compile(r'^(?P\S+)-(?P\d+)\s+(?P\S+)\s+(?P\d+)\s+(?P\S.*)$')
+
+
+def parse(text, fetched=None):
+ """Parse `lpstat -t` output. Lines we don't recognise are ignored rather than fatal."""
+ scheduler = None
+ default = None
+ devices = {}
+ accepting = {}
+ states = {}
+ order = []
+ jobs = []
+ last = None # the printer record that following tab-indented lines belong to
+ for line in text.splitlines():
+ if not line.strip():
+ continue
+ if line[0] in ' \t':
+ if last is not None and last in states:
+ states[last]['text'] = line.strip()
+ continue
+ last = None
+ if line.startswith('scheduler is '):
+ scheduler = line[len('scheduler is '):].strip().rstrip('.')
+ elif line.startswith('system default destination: '):
+ default = line.split(': ', 1)[1].strip()
+ elif line.startswith('no system default destination'):
+ default = None
+ elif _DEVICE.match(line):
+ m = _DEVICE.match(line)
+ devices[m.group('name')] = mask_uri(m.group('uri'))
+ elif _ACCEPTING.match(line):
+ m = _ACCEPTING.match(line)
+ accepting[m.group('name')] = (m.group('ok') == 'accepting', parse_date(m.group('since')))
+ if m.group('name') not in order:
+ order.append(m.group('name'))
+ last = ('acc', m.group('name'))
+ states[last] = {}
+ elif _PRINTER.match(line):
+ m = _PRINTER.match(line)
+ state = 'disabled' if m.group('disabled') else 'idle' if m.group('idle') else 'printing'
+ states[m.group('name')] = {'state': state, 'job': m.group('job'), 'since': parse_date(m.group('since'))}
+ if m.group('name') not in order:
+ order.append(m.group('name'))
+ last = m.group('name')
+ elif _JOB.match(line):
+ m = _JOB.match(line)
+ jobs.append(Job(m.group('printer') + '-' + m.group('id'), m.group('printer'), m.group('user'),
+ int(m.group('size')), parse_date(m.group('date'))))
+ printers = []
+ for name in order:
+ st = states.get(name, {})
+ acc = accepting.get(name, (None, None))
+ # the indented line after "not accepting" is why; after "disabled" it is why; otherwise it is a status message
+ why = states.get(('acc', name), {}).get('text') if acc[0] is False else None
+ text_ = st.get('text')
+ state = st.get('state', 'unknown')
+ printers.append(Printer(name, devices.get(name), state, st.get('job'), st.get('since'), acc[0], acc[1],
+ text_ if state != 'disabled' else None, text_ if state == 'disabled' else None, why))
+ return Status(scheduler, default, printers, jobs, fetched or datetime.now())
+
+
+_cache = {'when': 0, 'value': None}
+
+
+def reset_cache():
+ _cache['when'] = 0
+ _cache['value'] = None
+
+
+def status():
+ """The current Status (cached a few seconds so a refreshing page can't hammer cupsd), or LpstatError."""
+ now = time.time()
+ if _cache['value'] is None or now - _cache['when'] > CACHE_SECONDS:
+ _cache['value'] = parse(run_lpstat())
+ _cache['when'] = now
+ return _cache['value']
+
+
+def humanise(delta):
+ secs = int(delta.total_seconds())
+ if secs < 0:
+ return 'in the future'
+ if secs < 90:
+ return 'just now' if secs < 10 else '%d seconds' % secs
+ for unit, size in (('year', 365 * 86400), ('month', 30 * 86400), ('day', 86400), ('hour', 3600), ('minute', 60)):
+ if secs >= size * (1.5 if unit in ('hour', 'minute') else 1):
+ n = secs // size
+ return '%d %s%s' % (n, unit, '' if n == 1 else 's')
+ return '%d minutes' % (secs // 60)
+
+
+Verdict = namedtuple('Verdict', 'level problems') # level: ok | warning | error
+
+
+def assess(st, printer_name, now=None):
+ """Can automatic printing to `printer_name` be expected to work? Plain-English problems, worst first."""
+ now = now or st.fetched
+ errors, warnings = [], []
+ if st.scheduler != 'running':
+ errors.append('The CUPS scheduler is not running, so nothing can print.')
+ p = next((x for x in st.printers if x.name == printer_name), None)
+ if p is None:
+ errors.append('CUPS has no printer called %s, so automatic printing fails.' % printer_name)
+ else:
+ if p.state == 'disabled':
+ errors.append('%s is disabled%s.' % (p.name, ': ' + p.reason if p.reason else ''))
+ if p.accepting is False:
+ errors.append('%s is not accepting jobs%s.' % (p.name, ': ' + p.reject_reason if p.reject_reason else ''))
+ waiting = [j for j in st.jobs if j.printer == p.name]
+ old = [j for j in waiting if j.submitted and now - j.submitted > STALE_AFTER]
+ if old:
+ oldest = min(j.submitted for j in old)
+ warnings.append('%d job%s for %s %s been waiting for %s or more, so this printer may be stuck.' % (
+ len(old), '' if len(old) == 1 else 's', p.name, 'has' if len(old) == 1 else 'have', humanise(now - oldest)))
+ if errors:
+ return Verdict('error', errors + warnings)
+ if warnings:
+ return Verdict('warning', warnings)
+ return Verdict('ok', [])
+
+
+import unittest
+
+SAMPLE = """scheduler is running
+no system default destination
+device for OFFICE_MFP: lpd://192.0.2.100/MF8200C
+device for DESK_LASER: socket://192.0.2.212
+device for HALL_COPIER_192.0.2.10: socket://192.0.2.10
+OFFICE_MFP accepting requests since Wed Sep 9 15:02:14 2026
+DESK_LASER accepting requests since Wed Oct 25 12:01:17 2023
+HALL_COPIER_192.0.2.10 accepting requests since Thu Nov 19 16:33:41 2026
+printer OFFICE_MFP now printing OFFICE_MFP-41070. enabled since Wed Sep 9 15:02:14 2026
+\tConnecting to printer...
+printer DESK_LASER is idle. enabled since Wed Oct 25 12:01:17 2023
+printer HALL_COPIER_192.0.2.10 is idle. enabled since Thu Nov 19 16:33:41 2026
+\tReady to print.
+OFFICE_MFP-41070 printerface 91136 Wed Jun 29 13:27:57 2016
+OFFICE_MFP-41071 printerface 5120 Wed Jun 29 13:28:27 2016
+DESK_LASER-56672 printerface 64512 Tue May 30 09:14:10 2017
+"""
+
+# The two failure shapes below were written from CUPS 1.4's lpstat.c, not captured: no queue on our server has been
+# disabled or stopped from accepting jobs.
+BROKEN = """scheduler is running
+system default destination: DESK_LASER
+device for DESK_LASER: ipp://admin:s3cret@192.0.2.212/ipp/print
+DESK_LASER not accepting requests since Thu Nov 19 10:00:00 2026 -
+\tRejecting Jobs
+printer DESK_LASER disabled since Thu Nov 19 10:00:00 2026 -
+\tPaused
+"""
+
+NOW = datetime(2026, 11, 19, 17, 0, 0)
+
+
+class TestParse(unittest.TestCase):
+ def setUp(self):
+ self.st = parse(SAMPLE, NOW)
+
+ def test_scheduler_and_default(self):
+ self.assertEqual(self.st.scheduler, 'running')
+ self.assertIsNone(self.st.default)
+ self.assertEqual(parse(BROKEN, NOW).default, 'DESK_LASER')
+
+ def test_printers_in_order(self):
+ self.assertEqual([p.name for p in self.st.printers], ['OFFICE_MFP', 'DESK_LASER', 'HALL_COPIER_192.0.2.10'])
+ hall = self.st.printers[2]
+ self.assertEqual((hall.state, hall.accepting, hall.message, hall.device), ('idle', True, 'Ready to print.', 'socket://192.0.2.10'))
+ self.assertEqual(hall.since, datetime(2026, 11, 19, 16, 33, 41))
+
+ def test_busy_printer_has_its_job_and_message(self):
+ p = self.st.printers[0]
+ self.assertEqual((p.state, p.job, p.message), ('printing', 'OFFICE_MFP-41070', 'Connecting to printer...'))
+
+ def test_jobs(self):
+ self.assertEqual([j.id for j in self.st.jobs], ['OFFICE_MFP-41070', 'OFFICE_MFP-41071', 'DESK_LASER-56672'])
+ self.assertEqual(self.st.jobs[0].size, 91136)
+ self.assertEqual(self.st.jobs[2].submitted, datetime(2017, 5, 30, 9, 14, 10))
+
+ def test_stopped_printer_gives_reasons(self):
+ p = parse(BROKEN, NOW).printers[0]
+ self.assertEqual((p.state, p.accepting, p.reason), ('disabled', False, 'Paused'))
+
+ def test_not_accepting_reason(self):
+ text = BROKEN.replace('printer DESK_LASER disabled since Thu Nov 19 10:00:00 2026 -\n\tPaused\n',
+ 'printer DESK_LASER is idle. enabled since Thu Nov 19 10:00:00 2026\n')
+ p = parse(text, NOW).printers[0]
+ self.assertEqual((p.state, p.accepting, p.reject_reason), ('idle', False, 'Rejecting Jobs'))
+
+ def test_credentials_never_shown(self):
+ p = parse(BROKEN, NOW).printers[0]
+ self.assertEqual(p.device, 'ipp://192.0.2.212/ipp/print')
+ self.assertNotIn('s3cret', repr(p))
+
+ def test_junk_is_ignored(self):
+ st = parse('\nwhat is this\n' + SAMPLE, NOW)
+ self.assertEqual(len(st.printers), 3)
+
+ def test_dates(self):
+ self.assertEqual(parse_date('Wed Sep 9 15:02:14 2026'), datetime(2026, 9, 9, 15, 2, 14))
+ self.assertEqual(parse_date('Wed 09 Sep 2026 03:02:14 PM BST'), datetime(2026, 9, 9, 15, 2, 14))
+ self.assertIsNone(parse_date('yesterday'))
+
+
+class TestAssess(unittest.TestCase):
+ def test_stuck_queue_is_a_warning_for_that_printer_only(self):
+ st = parse(SAMPLE, NOW)
+ self.assertEqual(assess(st, 'HALL_COPIER_192.0.2.10').level, 'ok')
+ v = assess(st, 'OFFICE_MFP')
+ self.assertEqual(v.level, 'warning')
+ self.assertIn('2 jobs', v.problems[0])
+
+ def test_missing_printer(self):
+ v = assess(parse(SAMPLE, NOW), 'NOPE')
+ self.assertEqual(v.level, 'error')
+ self.assertIn('no printer called NOPE', v.problems[0])
+
+ def test_disabled_and_not_accepting(self):
+ v = assess(parse(BROKEN, NOW), 'DESK_LASER')
+ self.assertEqual(v.level, 'error')
+ self.assertEqual(len(v.problems), 2)
+ self.assertTrue(any('Paused' in x for x in v.problems) and any('Rejecting Jobs' in x for x in v.problems))
+
+ def test_scheduler_down(self):
+ self.assertEqual(assess(parse(SAMPLE.replace('is running', 'is not running'), NOW), 'DESK_LASER').level, 'error')
+
+ def test_recent_jobs_are_fine(self):
+ st = parse(SAMPLE.replace('Wed Jun 29 13:27:57 2016', 'Thu Nov 19 16:50:00 2026')
+ .replace('Wed Jun 29 13:28:27 2016', 'Thu Nov 19 16:51:00 2026'), NOW)
+ self.assertEqual(assess(st, 'OFFICE_MFP').level, 'ok')
+
+ def test_humanise(self):
+ self.assertEqual(humanise(timedelta(seconds=3)), 'just now')
+ self.assertEqual(humanise(timedelta(minutes=5)), '5 minutes')
+ self.assertEqual(humanise(timedelta(hours=3)), '3 hours')
+ self.assertEqual(humanise(timedelta(days=1)), '1 day')
+ self.assertEqual(humanise(timedelta(days=800)), '2 years')
+
+
+class TestRun(unittest.TestCase):
+ def tearDown(self):
+ reset_cache()
+
+ def test_missing_lpstat_is_an_error_not_a_crash(self):
+ import unittest.mock as mock
+ with mock.patch('subprocess.run', side_effect=FileNotFoundError()):
+ with self.assertRaises(LpstatError):
+ run_lpstat()
+
+ def test_cupsd_down(self):
+ import unittest.mock as mock
+ r = subprocess.CompletedProcess([], 1, '', 'lpstat: Bad file descriptor\n')
+ with mock.patch('subprocess.run', return_value=r):
+ with self.assertRaisesRegex(LpstatError, 'Bad file descriptor'):
+ run_lpstat()
+
+ def test_cached_between_calls(self):
+ import unittest.mock as mock
+ with mock.patch(__name__ + '.run_lpstat', return_value=SAMPLE) as run:
+ status()
+ status()
+ self.assertEqual(run.call_count, 1)
+ reset_cache()
+ status()
+ self.assertEqual(run.call_count, 2)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/requirements.txt b/requirements.txt
index 47d9e33..ce372f6 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,5 +1,5 @@
-Mako==1.2.2
-MarkupSafe==0.19
-reportlab==2.7
-wsgiref==0.1.2
-pytz==2018.9
+Mako>=1.2.2
+MarkupSafe>=2.0
+reportlab>=4.0,<6
+pillow>=9.0
+pytz>=2023.3
diff --git a/settings.py b/settings.py
new file mode 100644
index 0000000..8ec57f6
--- /dev/null
+++ b/settings.py
@@ -0,0 +1,19 @@
+# Locations and configuration shared by main, mailer and stationary.
+#
+# PRINTERFACE_HOME holds the stored jobs, rendered PDFs, email address book and email.cfg overrides.
+# It defaults to ~/printerface; set the environment variable to run a second instance (for example a
+# shadow instance on a copy of the data) without touching the live one.
+import configparser
+import os
+
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+HOME = os.path.expanduser(os.environ.get('PRINTERFACE_HOME', '~/printerface'))
+
+def load_config():
+ config = configparser.ConfigParser()
+ with open(os.path.join(BASE_DIR, 'defaults.cfg')) as f:
+ config.read_file(f)
+ config.read(os.path.join(HOME, 'email.cfg'))
+ return config
+
+config = load_config()
diff --git a/stationary.py b/stationary.py
index ba74a85..6023ec6 100644
--- a/stationary.py
+++ b/stationary.py
@@ -1,13 +1,12 @@
-import ConfigParser
import reportlab
import os
+import shutil
import sys
from reportlab.pdfgen import canvas
-config = ConfigParser.ConfigParser()
-config.read('defaults.cfg')
-config.read(os.path.expanduser('~/printerface/email.cfg'))
+from settings import config
+from textutil import split_lines
from reportlab.lib.units import cm
from reportlab.lib.pagesizes import A4, landscape
@@ -62,7 +61,7 @@ def topBox(c, x, y, title="Title", content="The quick brown", w=2*cm, h=2.0*cm,
c.setFont("Helvetica", hfontsz)
lineheight = hfontsz * 1.2
if align=='c':
- for lineno, text in enumerate(title.splitlines()):
+ for lineno, text in enumerate(split_lines(title)):
c.drawCentredString(w*0.5, -.33*cm*(lineno+1), text)
else:
c.drawString(0.8*cm, -.33*cm, title)
@@ -331,8 +330,8 @@ def statementPage(c, ctx, mark):
c.translate(0.8*cm,0.8*cm)
# entire page breaks at 12cm, LHS is tear off (originally perferated)
- watermark(c, mark=mark, x=6*cm, fontsz=36)
- watermark(c, mark=mark, x=16*cm, fontsz=20)
+ watermark(c, mark=mark, x=6*cm, fontsz=36)
+ watermark(c, mark=mark, x=16*cm, fontsz=20)
headerDetails(c, ctx, 'Statement')
@@ -348,7 +347,7 @@ def statementPage(c, ctx, mark):
h = 0.85*cm
y = 24.6*cm
- (x,y0) = topBox(c, 0*cm, y, h=3.8*cm, w=8.2*cm, title='TO', content=ctx['addr_invoice'])
+ (x,y0) = topBox(c, 0*cm, y, h=3.8*cm, w=8.2*cm, title='TO', content=ctx['addr_invoice'])
w = divide - vpad - (x + vpad)
(x0,y) = topBox(c, x+vpad, y, h=1.25*cm, w=w, title='ACCOUNT NO.', content=ctx['accno'])
(x0,y) = topBox(c, x+vpad, y, h=1.25*cm, w=w, title='DATE', content=ctx['date'])
@@ -438,10 +437,7 @@ def genericPage(c, data, title=None, fontsz=7, landsc=False, overlay=None, decor
class DocFormatter(object):
def __init__(self, pdfdir):
self.jobdir = pdfdir
- try:
- os.makedirs(jobdir)
- except:
- pass
+ os.makedirs(self.jobdir, exist_ok=True)
def format(self, ctx):
mname = 'write' + ctx['templ'].title()
@@ -458,7 +454,7 @@ def plainFormat(self, ctx):
def writeInvoice(self, ctx ):
rendered_pdfs = {}
- for (acc,v) in ctx['parsed'].iteritems():
+ for (acc,v) in ctx['parsed'].items():
p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), acc, "%s-%s.pdf" % (ctx['name'], acc))
self.create_dirs(p)
c = canvas.Canvas(p, pagesize=A4)
@@ -474,14 +470,14 @@ def writeInvoice(self, ctx ):
c = canvas.Canvas(p, pagesize=A4)
pages_by_docnum = dict()
- for (acc,v) in ctx['parsed'].iteritems():
+ for (acc,v) in ctx['parsed'].items():
for page in v:
pages_by_docnum.setdefault(page['doc_num'], []).append(page)
for k in reversed(sorted(pages_by_docnum.keys())):
for page in pages_by_docnum[k]:
accountNotePage(c, page, 'ACCOUNTS COPY')
- c.save()
+ c.save()
rendered_pdfs[ ('accounts',) ] = os.path.relpath(p, self.jobdir)
return rendered_pdfs, ('Group',)
@@ -492,7 +488,7 @@ def writePicklist(self, ctx):
self.create_dirs(p)
c = canvas.Canvas(p, pagesize=A4)
- for (acc,v) in ctx['parsed'].iteritems():
+ for (acc,v) in ctx['parsed'].items():
for page in v:
data = page['data']
@@ -524,7 +520,7 @@ def writeRaw(self, ctx):
c = canvas.Canvas(p, pagesize=A4)
landsc, fontsz, row, cols = ctx['autofmt']
- pages = filter(None, ctx['plain'].strip().split("\f"))
+ pages = [p for p in ctx['plain'].strip().split("\f") if p]
for page in pages:
genericPage(c, page, title=None, fontsz=fontsz, landsc=landsc)
@@ -554,26 +550,26 @@ def writeCrednote(self, ctx):
def writeStatement(self, ctx):
rendered_pdfs = {}
- for (acc,v) in ctx['parsed'].iteritems():
+ for (acc,v) in ctx['parsed'].items():
p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), acc, "%s-%s.pdf" % (ctx['name'], acc))
self.create_dirs(p)
c = canvas.Canvas(p, pagesize=A4)
- for page in v:
+ for page in v:
statementPage(c, page, 'CUSTOMER COPY')
- c.save()
+ c.save()
rendered_pdfs[ (acc,) ] = os.path.relpath(p, self.jobdir)
p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), 'accounts', "%s-%s.pdf" % (ctx['name'], 'accounts'))
self.create_dirs(p)
c = canvas.Canvas(p, pagesize=A4)
- for (acc,v) in ctx['parsed'].iteritems():
- for page in v:
+ for (acc,v) in ctx['parsed'].items():
+ for page in v:
statementPage(c, page, 'ACCOUNTS COPY')
- c.save()
+ c.save()
rendered_pdfs[ ('accounts',) ] = os.path.relpath(p, self.jobdir)
# protocol: key tuples must all be same length, second tuple is key descriptions
@@ -585,12 +581,12 @@ def writeDelnote(self, ctx):
self.create_dirs(p)
c = canvas.Canvas(p, pagesize=A4)
- for (acc,v) in ctx['parsed'].iteritems():
+ for (acc,v) in ctx['parsed'].items():
for mark in ['CUSTOMER COPY', 'ACCOUNTS COPY']:
for page in v:
deliveryNotePage(c, page, mark)
- c.save()
+ c.save()
rendered_pdfs[ ('accounts',) ] = os.path.relpath(p, self.jobdir)
return rendered_pdfs, ('type',)
@@ -598,28 +594,28 @@ def writeRemittance(self, ctx):
rendered_pdfs = {}
- for (acc,v) in ctx['parsed'].iteritems():
+ for (acc,v) in ctx['parsed'].items():
p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), acc, "%s-%s.pdf" % (ctx['name'], acc))
self.create_dirs(p)
c = canvas.Canvas(p, pagesize=A4)
- for page in v:
+ for page in v:
remittancePage(c, page, 'CUSTOMER COPY')
- c.save()
+ c.save()
rendered_pdfs[ (acc,) ] = os.path.relpath(p, self.jobdir)
p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), 'accounts', "%s-%s.pdf" % (ctx['name'], 'accounts'))
self.create_dirs(p)
c = canvas.Canvas(p, pagesize=A4)
- for (acc,v) in ctx['parsed'].iteritems():
+ for (acc,v) in ctx['parsed'].items():
- for page in v:
+ for page in v:
remittancePage(c, page, 'ACCOUNTS COPY')
- c.save()
+ c.save()
rendered_pdfs[ ('accounts',) ] = os.path.relpath(p, self.jobdir)
# protocol: key tuples must all be same length, second tuple is key descriptions
@@ -629,7 +625,7 @@ def writePurchase(self, ctx):
rendered_pdfs = {}
- for (acc,v) in ctx['parsed'].iteritems():
+ for (acc,v) in ctx['parsed'].items():
for (bundle, marks) in [ ( '', ['SUPPLIER COPY']), ('-transport', ['TRANSPORTER COPY']), ('-admin', ['MASTER COPY', 'BOOKING IN COPY', 'PRE LOCATION COPY']) ]:
p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), acc, "%s-%s%s.pdf" % (ctx['name'], acc, bundle))
@@ -637,10 +633,10 @@ def writePurchase(self, ctx):
c = canvas.Canvas(p, pagesize=A4)
for mark in marks:
- for page in v:
+ for page in v:
purchasePage(c, page, mark)
- c.save()
+ c.save()
rendered_pdfs[ ("%s%s" % (acc, bundle),) ] = os.path.relpath(p, self.jobdir)
return rendered_pdfs, ('type', )
@@ -664,11 +660,11 @@ def writePurchase(self, ctx):
# port 12 55 76
# port 13 51 71
def getBestPageFormat(self, plaintext):
- pages = filter(None, plaintext.strip().split("\f"))
+ pages = [p for p in plaintext.strip().split("\f") if p]
worst_rows, worst_cols = 0, 0
for pi, page in enumerate(pages):
- lines = page.splitlines()
+ lines = split_lines(page)
(rows, cols) = (len(lines), max([len(line) for line in lines]))
# print (' page %d rows %d cols %d' % (pi, rows, cols))
worst_cols = max(worst_cols, cols)
@@ -695,7 +691,7 @@ def getBestPageFormat(self, plaintext):
(True, 6 , 78, 224),
]
- soln = filter( lambda x: x[2] > worst_rows and x[3] > worst_cols, a4_cand)
+ soln = [x for x in a4_cand if x[2] > worst_rows and x[3] > worst_cols]
if len(soln):
sol = soln[0]
# print(' solution for pages=%d worst r=%d c=%d is %s' % (len(pages), worst_rows, worst_cols, sol))
@@ -707,9 +703,10 @@ def getBestPageFormat(self, plaintext):
class TestStationary(unittest.TestCase):
def setUp(self):
- pdir = os.path.expanduser("~/printerface/")
- jobdir = pdir + 'pdf/'
- self.formatter = DocFormatter(jobdir)
+ import tempfile
+ self.tmp = tempfile.mkdtemp(prefix='printerface-test-')
+ self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True)
+ self.formatter = DocFormatter(os.path.join(self.tmp, 'pdf') + os.sep)
self.chuff = dict(date='04/10/12',
doc_num='731/289073',
@@ -758,23 +755,23 @@ def test_delnote(self):
amt_encl='amt_encl',
)
- s.append( dict(order.items() + self.chuff.items()))
+ s.append( {**order, **self.chuff})
ctx['parsed'] = { 'SMP109': s}
p = self.formatter.format(ctx)
- self.assertEquals( ({('accounts',): '2014/accounts/blahdel-accounts.pdf'}, ('type',) ), p)
+ self.assertEqual( ({('accounts',): '2014/accounts/blahdel-accounts.pdf'}, ('type',) ), p)
ctx['templ'] = 'purchase'
ctx['name'] = 'blahpurch'
p = self.formatter.format(ctx)
- self.assertEquals( ({ ('SMP109',): '2014/SMP109/blahpurch-SMP109.pdf',
+ self.assertEqual( ({ ('SMP109',): '2014/SMP109/blahpurch-SMP109.pdf',
('SMP109-admin',): '2014/SMP109/blahpurch-SMP109-admin.pdf',
('SMP109-transport',): '2014/SMP109/blahpurch-SMP109-transport.pdf'}, ('type',) ), p)
ctx['templ'] = 'remittance'
ctx['name'] = 'blahremit'
p = self.formatter.format(ctx)
- self.assertEquals( ({('SMP109',): '2014/SMP109/blahremit-SMP109.pdf',
+ self.assertEqual( ({('SMP109',): '2014/SMP109/blahremit-SMP109.pdf',
('accounts',): '2014/accounts/blahremit-accounts.pdf'}, ('Group',) ), p)
def test_statement(self):
@@ -813,14 +810,14 @@ def test_statement(self):
age_due="16.00"
)
- s.append( dict(order.items() + self.chuff.items()))
+ s.append( {**order, **self.chuff})
ctx['parsed'] = { 'SMP109': s}
p = self.formatter.format(ctx)
- self.assertEquals( ({('SMP109',): '2014/SMP109/blahstate-SMP109.pdf', ('accounts',): '2014/accounts/blahstate-accounts.pdf'}, ('Group',) ), p)
+ self.assertEqual( ({('SMP109',): '2014/SMP109/blahstate-SMP109.pdf', ('accounts',): '2014/accounts/blahstate-accounts.pdf'}, ('Group',) ), p)
def test_cnote(self):
- # CREDIT NOTE / INVOICE paperwork
+ # CREDIT NOTE / INVOICE paperwork
extra = dict( doctype='CREDIT NOTE',
summ_code='5\n'*4,
summ_netamt='12345.67\n'*4,
@@ -849,10 +846,10 @@ def test_cnote(self):
prod_net="1499.40\n"*sz,
prod_vcode="5\n"*sz
)
- s.append( dict(order.items() + self.chuff.items() + extra.items()))
+ s.append( {**order, **self.chuff, **extra})
ctx['parsed'] = { 'SMP109': s}
p = self.formatter.format(ctx)
- self.assertEquals( ({('SMP109',): '2014/SMP109/blahcn-SMP109.pdf', ('accounts',): '2014/accounts/blahcn-accounts.pdf'}, ('Group',) ), p)
+ self.assertEqual( ({('SMP109',): '2014/SMP109/blahcn-SMP109.pdf', ('accounts',): '2014/accounts/blahcn-accounts.pdf'}, ('Group',) ), p)
def test_picklist(self):
ctx = {}
@@ -865,16 +862,16 @@ def test_picklist(self):
{'data': 'fluff '*22, 'hdr': 'Picking list 5342', 'dt': 'Monday 03/12/18', 'page': 'PAGE 1'}
]}
p = self.formatter.format(ctx)
- self.assertEquals( ({('pick',): 'raw/201403/pick-a-pick.pdf'}, ('Group',) ), p)
+ self.assertEqual( ({('pick',): 'raw/201403/pick-a-pick.pdf'}, ('Group',) ), p)
def test_calibrate(self):
# test document to calibrate width/height fontsize matrix
cols = 240
rows = 120
- import StringIO
- chunks10 = (cols+9)/10
- f = StringIO.StringIO()
+ import io
+ chunks10 = (cols+9)//10
+ f = io.StringIO()
f.write('' + ''.join(["%-10d" % (d*10) for d in range(chunks10)]))
f.write('\n' + ('0123456789' * chunks10))
for row in range(2,rows):
@@ -888,9 +885,9 @@ def test_calibrate(self):
p = self.formatter.format(ctx)
def test_rawformat(self):
- self.assertEquals( (False, 13,51,71), self.formatter.getBestPageFormat('ABCDEF') )
- self.assertEquals( (True, 13,35,102), self.formatter.getBestPageFormat('test'*20) )
- self.assertEquals( (False, 8, 83,115), self.formatter.getBestPageFormat('ABCDEF\n'*80) )
+ self.assertEqual( (False, 13,51,71), self.formatter.getBestPageFormat('ABCDEF') )
+ self.assertEqual( (True, 13,35,102), self.formatter.getBestPageFormat('test'*20) )
+ self.assertEqual( (False, 8, 83,115), self.formatter.getBestPageFormat('ABCDEF\n'*80) )
ctx = {}
ctx['templ'] = 'raw'
@@ -900,7 +897,7 @@ def test_rawformat(self):
ctx['plain'] = 'test12 ' * 20
ctx['autofmt'] = self.formatter.getBestPageFormat(ctx['plain'])
p = self.formatter.format(ctx)
- self.assertEquals( ({('plain',): 'raw/201402/rawtest-plain.pdf'}, ('Type',) ), p)
+ self.assertEqual( ({('plain',): 'raw/201402/rawtest-plain.pdf'}, ('Type',) ), p)
def test_plainformat(self):
ctx = {}
@@ -909,7 +906,7 @@ def test_plainformat(self):
ctx['ts'] = datetime(2014, 3, 4, 20, 53, 0, 0)
ctx['autofmt'] = self.formatter.getBestPageFormat(ctx['plain'])
p = self.formatter.plainFormat(ctx)
- self.assertEquals( ({('plain',): 'raw/201403/rawtest2-plain.pdf'}, ('Type',) ), p)
+ self.assertEqual( ({('plain',): 'raw/201403/rawtest2-plain.pdf'}, ('Type',) ), p)
if __name__=="__main__":
unittest.main()
diff --git a/templates/default.mako b/templates/default.mako
new file mode 100644
index 0000000..6ffe6ae
--- /dev/null
+++ b/templates/default.mako
@@ -0,0 +1,8 @@
+Document ${job.doctype} attached
+
+To ${email.name},
+
+Please find your ${job.doctype} document attached.
+
+Kind regards
+${company.name}
diff --git a/templates/invoice.mako b/templates/invoice.mako
new file mode 100644
index 0000000..1675677
--- /dev/null
+++ b/templates/invoice.mako
@@ -0,0 +1,16 @@
+New Invoice${all.s} ${all.numbers}
+
+To ${email.name},
+
+% if all.many:
+Please find your latest invoices attached for account ${doc.accno}, for a total of £${all.total}:
+
+% for d in docs:
+${d.doc_num} £${d.tot_due}
+% endfor
+% else:
+Please find your latest invoice ${doc.doc_num} attached for account ${doc.accno}, for £${doc.tot_due}.
+% endif
+
+Kind regards
+${company.name}
diff --git a/templates/purchase.mako b/templates/purchase.mako
new file mode 100644
index 0000000..5ce4058
--- /dev/null
+++ b/templates/purchase.mako
@@ -0,0 +1,10 @@
+Purchase order ${doc.doc_num} from ${company.name}
+
+To ${email.name}
+
+Please find attached purchase order ${doc.doc_num}, dated ${doc.orderdate}, for account ${doc.accno}.
+
+Please confirm receipt and let us know when it will be ready for collection.
+
+Kind regards
+${company.name}
diff --git a/templates/statement.mako b/templates/statement.mako
new file mode 100644
index 0000000..477fb51
--- /dev/null
+++ b/templates/statement.mako
@@ -0,0 +1,10 @@
+Statement dated ${doc.date} from ${company.name}
+
+To ${email.name},
+
+Please find attached your statement dated ${doc.date} for account ${doc.accno}.
+
+The balance to pay is £${doc.tot_topay}.
+
+Kind regards
+${company.name}
diff --git a/test_compose.js b/test_compose.js
new file mode 100644
index 0000000..bbda915
--- /dev/null
+++ b/test_compose.js
@@ -0,0 +1,149 @@
+// Tests for web/js/compose.js with a minimal stand-in for the DOM. Run by test_compose_js.py, or: node test_compose.js
+const assert = require('assert');
+const {init, initPrint, initSend} = require('./web/js/compose.js');
+
+function element(props) {
+ const handlers = {};
+ return Object.assign({
+ style: {},
+ addEventListener(type, fn) { (handlers[type] = handlers[type] || []).push(fn); },
+ fire(type) { (handlers[type] || []).forEach(fn => fn({preventDefault() {}})); },
+ getAttribute(name) { return (this.attrs || {})[name]; },
+ }, props);
+}
+
+// options.subject: initial subject text, or null for a page without a subject box
+function setup(addresses, text, options = {}) {
+ const url = 'url' in options ? options.url : '/email_body?name=job-1&key=ACC1';
+ const boxes = addresses.map(a => element({name: 'em', value: a, checked: true}));
+ const area = element({value: text, attrs: url ? {'data-url': url} : {}});
+ const subject = 'subject' in options && options.subject === null ? undefined : element({value: options.subject || ''});
+ const notice = element({style: {display: 'none'}});
+ const reapply = element({});
+ const byId = {inputBody: area, inputSubject: subject, bodyNotice: notice, bodyReapply: reapply};
+ const doc = {getElementById: id => byId[id], querySelectorAll: () => boxes};
+ const requests = [];
+ // answer({subject, body}) or answer('body only')
+ const fetchFn = u => new Promise(resolve => requests.push({
+ url: u,
+ answer: a => resolve({json: () => Promise.resolve(typeof a === 'string' ? {body: a} : a)}),
+ }));
+ return {boxes, area, subject, notice, reapply, requests, api: init(doc, fetchFn)};
+}
+const settle = () => new Promise(resolve => setImmediate(resolve));
+const untick = (t, i) => { t.boxes[i].checked = false; t.boxes[i].fire('change'); };
+
+(async () => {
+ // ticking and unticking asks the server with exactly the ticked addresses, in page order, and uses the answer
+ let t = setup(['ann@x.com', 'bob+co@x.com'], 'To Ann and Bob\n', {subject: 'Invoice 1'});
+ untick(t, 0);
+ assert.strictEqual(t.requests.length, 1);
+ assert.strictEqual(t.requests[0].url, '/email_body?name=job-1&key=ACC1&em=bob%2Bco%40x.com');
+ t.requests[0].answer({subject: 'Invoice 1 for Bob', body: 'To Bob\n'});
+ await settle();
+ assert.strictEqual(t.area.value, 'To Bob\n');
+ assert.strictEqual(t.subject.value, 'Invoice 1 for Bob');
+ assert.strictEqual(t.notice.style.display, 'none');
+
+ // nothing ticked: no em at all
+ untick(t, 1);
+ assert.strictEqual(t.requests[1].url, '/email_body?name=job-1&key=ACC1');
+ t.requests[1].answer({subject: 'Invoice 1', body: 'To Sir or Madam\n'});
+ await settle();
+ assert.strictEqual(t.area.value, 'To Sir or Madam\n');
+ assert.strictEqual(t.subject.value, 'Invoice 1');
+
+ // an edited body is kept, with a notice, while the untouched subject still follows the recipients
+ t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n', {subject: 'For Ann and Bob'});
+ t.area.value = 'To Ann and Bob\nmy own words\n';
+ untick(t, 1);
+ t.requests[0].answer({subject: 'For Ann', body: 'To Ann\n'});
+ await settle();
+ assert.strictEqual(t.area.value, 'To Ann and Bob\nmy own words\n');
+ assert.strictEqual(t.subject.value, 'For Ann');
+ assert.strictEqual(t.notice.style.display, '');
+
+ // the link replaces everything using the current ticks
+ t.reapply.fire('click');
+ assert.strictEqual(t.requests[1].url, '/email_body?name=job-1&key=ACC1&em=ann%40x.com');
+ t.requests[1].answer({subject: 'For Ann', body: 'To Ann\n'});
+ await settle();
+ assert.strictEqual(t.area.value, 'To Ann\n');
+ assert.strictEqual(t.notice.style.display, 'none');
+
+ // an edited subject is kept while the body follows; and both edited means both kept
+ t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n', {subject: 'For Ann and Bob'});
+ t.subject.value = 'My own subject';
+ untick(t, 1);
+ t.requests[0].answer({subject: 'For Ann', body: 'To Ann\n'});
+ await settle();
+ assert.strictEqual(t.subject.value, 'My own subject');
+ assert.strictEqual(t.area.value, 'To Ann\n');
+ assert.strictEqual(t.notice.style.display, '');
+ t.area.value = 'typed';
+ t.boxes[1].checked = true; t.boxes[1].fire('change');
+ t.requests[1].answer({subject: 'For Ann and Bob', body: 'To Ann and Bob\n'});
+ await settle();
+ assert.deepStrictEqual([t.subject.value, t.area.value], ['My own subject', 'typed']);
+ t.reapply.fire('click');
+ t.requests[2].answer({subject: 'For Ann and Bob', body: 'To Ann and Bob\n'});
+ await settle();
+ assert.deepStrictEqual([t.subject.value, t.area.value, t.notice.style.display], ['For Ann and Bob', 'To Ann and Bob\n', 'none']);
+
+ // text that was refreshed by us is not "edited": a second tick updates it again without a notice
+ t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n', {subject: 'S1'});
+ untick(t, 0); t.requests[0].answer({subject: 'S2', body: 'To Bob\n'}); await settle();
+ t.boxes[0].checked = true; t.boxes[0].fire('change'); t.requests[1].answer({subject: 'S1', body: 'To Ann and Bob\n'}); await settle();
+ assert.deepStrictEqual([t.subject.value, t.area.value, t.notice.style.display], ['S1', 'To Ann and Bob\n', 'none']);
+
+ // answers arriving out of order: only the answer to the latest tick is used
+ t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n', {subject: 'S1'});
+ untick(t, 0); untick(t, 1);
+ t.requests[1].answer({subject: 'Latest', body: 'To Sir or Madam\n'});
+ await settle();
+ t.requests[0].answer({subject: 'Stale', body: 'To Bob\n'});
+ await settle();
+ assert.deepStrictEqual([t.subject.value, t.area.value], ['Latest', 'To Sir or Madam\n']);
+
+ // a page with no subject box still updates the body
+ t = setup(['ann@x.com'], 'To Ann\n', {subject: null});
+ untick(t, 0); t.requests[0].answer({subject: 'x', body: 'To Sir or Madam\n'}); await settle();
+ assert.strictEqual(t.area.value, 'To Sir or Madam\n');
+
+ // an answer missing a field leaves that box as it was (never the text 'undefined')
+ t = setup(['ann@x.com'], 'To Ann\n', {subject: 'Keep me'});
+ untick(t, 0); t.requests[0].answer('To Sir or Madam\n'); await settle();
+ assert.deepStrictEqual([t.subject.value, t.area.value], ['Keep me', 'To Sir or Madam\n']);
+
+ // a failed request leaves the text alone
+ t = setup(['ann@x.com'], 'To Ann\n', {subject: 'S'});
+ const failing = {getElementById: id => ({inputBody: t.area, inputSubject: t.subject}[id]), querySelectorAll: () => t.boxes};
+ const api = init(failing, () => Promise.reject(new Error('offline')));
+ await api.refresh(false);
+ assert.deepStrictEqual([t.subject.value, t.area.value], ['S', 'To Ann\n']);
+
+ // a page without the compose form is left alone
+ assert.strictEqual(setup(['a@x.com'], 'x', {url: null}).api, undefined);
+ // printing posts a form: choosing a printer fills it in and submits it, and the click itself is cancelled
+ const submitted = [];
+ const printerField = {value: ''};
+ const printForm = {elements: {printer: printerField}, submit() { submitted.push(printerField.value); }};
+ const clickHandlers = [];
+ const printItem = {getAttribute: () => 'HP_TONY', addEventListener: (type, fn) => clickHandlers.push(fn)};
+ initPrint({getElementById: id => ({printForm}[id]), querySelectorAll: () => [printItem]});
+ let prevented = 0;
+ clickHandlers[0]({preventDefault() { prevented++; }});
+ assert.deepStrictEqual([submitted, prevented], [['HP_TONY'], 1]);
+ assert.strictEqual(initPrint({getElementById: () => null, querySelectorAll: () => []}), undefined); // no print form: nothing to do
+
+ // the send button is disabled as the form is submitted, so a double click can't send twice
+ const sendButton = {disabled: false};
+ let onSubmit;
+ initSend({getElementById: id => id === 'composeForm' ? {addEventListener: (type, fn) => { if (type === 'submit') onSubmit = fn; }} : sendButton});
+ assert.strictEqual(sendButton.disabled, false);
+ onSubmit();
+ assert.strictEqual(sendButton.disabled, true);
+ assert.strictEqual(initSend({getElementById: () => null}), undefined);
+
+ console.log('compose.js: all tests passed');
+})().catch(e => { console.error(e); process.exit(1); });
diff --git a/test_compose_js.py b/test_compose_js.py
new file mode 100644
index 0000000..eefbcf3
--- /dev/null
+++ b/test_compose_js.py
@@ -0,0 +1,16 @@
+# Runs the node tests for web/js/compose.js (skipped where node isn't installed, e.g. the docker image).
+import os
+import shutil
+import subprocess
+import unittest
+
+@unittest.skipUnless(shutil.which('node'), 'node is not installed')
+class TestComposeJs(unittest.TestCase):
+ def test_compose_js(self):
+ here = os.path.dirname(os.path.abspath(__file__))
+ r = subprocess.run(['node', 'test_compose.js'], cwd=here, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
+ self.assertEqual(0, r.returncode, r.stdout)
+ self.assertIn('all tests passed', r.stdout)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_integration.py b/test_integration.py
new file mode 100644
index 0000000..c245b70
--- /dev/null
+++ b/test_integration.py
@@ -0,0 +1,860 @@
+# 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 http.client
+import io
+import re
+import json
+import os
+import pickle
+import shutil
+import socket
+import tempfile
+import urllib.parse
+import threading
+import time
+import unittest
+from datetime import datetime
+from unittest import mock
+
+import main
+import mailer
+import printing
+import printstatus
+import emailtemplates
+from stationary import DocFormatter
+from lpdserver import LpdServer
+from httpserver import ToyHttpServer
+from textutil import split_lines
+
+def put(lines, row, col, text):
+ for i, part in enumerate(text.split('\n')):
+ 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):
+ """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)."""
+ lines = [' ' * 130 for _ in range(48 * (pages + 1))]
+ for p in range(pages):
+ base = (p + 1) * 48
+ put(lines, base + 0, 0, 'INVOICE')
+ put(lines, base + 0, 95, '01/10/26')
+ put(lines, base + 2, 95, 'Page %d' % (p + 1))
+ put(lines, base + 4, 95, doc_nums[p] if doc_nums else doc_num)
+ put(lines, base + 8, 12, 'ACME WINES LTD\n1 HIGH STREET\nLONDON')
+ put(lines, base + 16, 0, acc)
+ put(lines, base + 16, 9, 'PO-7')
+ put(lines, base + 16, 20, '289073')
+ put(lines, base + 19, 0, 'B0321021\nB0308206')
+ 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')
+ lines[base + 47] = lines[base + 47][:100] + '\x0c'
+ return '\r\n'.join(lines) + '\r\n'
+
+def lpr(port, queue, control, data):
+ """Minimal RFC 1179 'receive a printer job' client. control is str, data is bytes."""
+ s = socket.create_connection(('127.0.0.1', port), timeout=10)
+ def ack():
+ assert s.recv(1) == b'\x00', 'no ack'
+ try:
+ s.sendall(b'\x02' + queue.encode() + b'\n'); ack()
+ c = control.encode('latin-1')
+ s.sendall(b'\x02%d cfA001testhost\n' % len(c)); ack()
+ s.sendall(c + b'\x00'); ack()
+ s.sendall(b'\x03%d dfA001testhost\n' % len(data)); ack()
+ s.sendall(data + b'\x00'); ack()
+ finally:
+ s.close()
+
+def mailer_results():
+ return main.mailqueue.results
+
+class ServerThread(threading.Thread):
+ def __init__(self):
+ threading.Thread.__init__(self)
+ self.daemon = True
+ self.running = True
+ def run(self):
+ while self.running:
+ asyncore.loop(timeout=0.05, count=1)
+
+class TestPrinterface(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ # test discovery imports main before we get here, so repoint it (and everything derived from
+ # settings.HOME) at a scratch directory rather than the real ~/printerface
+ cls.home = tempfile.mkdtemp(prefix='printerface-test-')
+ main.email_pickle = os.path.join(cls.home, 'email.pickle')
+ main.jobdir = os.path.join(cls.home, 'data', 'pickle')
+ 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_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]:
+ os.makedirs(x, exist_ok=True)
+ # Nothing in these tests may print. Delivery notes and pick lists are auto-printed (defaults.cfg), which
+ # would run lpr: on a machine without CUPS that fails, and on one with a printer called HP_TONY it would print.
+ cls.print_patch = mock.patch.object(main, 'printFile')
+ cls.printed = cls.print_patch.start()
+ # 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()
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.thread.running = False
+ cls.thread.join()
+ cls.lpd.close()
+ cls.http.close()
+ cls.print_patch.stop()
+ cls.lpstat_patch.stop()
+ printing.printlog = cls.old_printlog
+ emailtemplates.USER_DIR = cls.old_user_dir
+ shutil.rmtree(cls.home, ignore_errors=True)
+
+ def test_printers_page(self):
+ printstatus.reset_cache()
+ old = main.config.get('Robot', 'auto_printer')
+ try:
+ main.config.set('Robot', 'auto_printer', 'DESK_LASER')
+ r, body = self.get('/printers')
+ self.assertEqual(r.status, 200)
+ text = body.decode()
+ for expected in ['OFFICE_MFP', 'HALL_COPIER_192.0.2.10', 'Connecting to printer...', 'socket://192.0.2.10', 'OFFICE_MFP-41071']:
+ self.assertIn(expected, text)
+ # DESK_LASER has a 2017 job waiting
+ self.assertIn('may not be working', text)
+ main.config.set('Robot', 'auto_printer', 'NOPE')
+ printstatus.reset_cache()
+ self.assertIn('no printer called NOPE', self.get('/printers')[1].decode())
+ finally:
+ main.config.set('Robot', 'auto_printer', old)
+ printstatus.reset_cache()
+
+ def test_printers_page_without_cups(self):
+ printstatus.reset_cache()
+ with mock.patch.object(printstatus, 'run_lpstat', side_effect=printstatus.LpstatError('cupsd is ')):
+ r, body = self.get('/printers')
+ self.assertEqual(r.status, 200)
+ self.assertIn("Can't read the printer status", body.decode())
+ self.assertIn('cupsd is <down>', body.decode())
+ printstatus.reset_cache()
+
+ def get(self, path, headers=None):
+ conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10)
+ conn.request('GET', path, headers=headers or {})
+ r = conn.getresponse()
+ body = r.read()
+ conn.close()
+ return r, body
+
+ def post(self, path, **fields):
+ conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10)
+ body = urllib.parse.urlencode(fields, doseq=True).encode('utf-8')
+ conn.request('POST', path, body=body, headers={'Content-Type': 'application/x-www-form-urlencoded'})
+ r = conn.getresponse()
+ data = r.read()
+ conn.close()
+ return r, data
+
+ def post_redirect(self, path, **fields):
+ """POST, expect the 303 that sends the browser back to a GET page, and return (location, that page)."""
+ r, data = self.post(path, **fields)
+ self.assertEqual(303, r.status, data[:300])
+ location = r.getheader('Location')
+ r2, page = self.get(location)
+ self.assertEqual(200, r2.status, location)
+ return location, page
+
+ def add_contact(self, account, email, name):
+ self.post_redirect('/settings/email', account=account, email=email, contact=name)
+
+ def setUp(self):
+ self.printed.reset_mock()
+ main.jobs.clear()
+ main.email_addresses.clear()
+ shutil.rmtree(emailtemplates.USER_DIR, ignore_errors=True)
+
+ def send_invoice(self, jtype='Invoice', **kw):
+ before = len(main.jobs)
+ lpr(self.lpd_port, 'RAW', 'Hlocalhost\nPtester\nJ%s\nldfA001testhost\n' % jtype, make_invoice(**kw).encode('latin-1'))
+ deadline = time.time() + 20
+ while len(main.jobs) == before and time.time() < deadline:
+ time.sleep(0.05)
+ self.assertEqual(before + 1, len(main.jobs), 'job was not received')
+ return main.jobs[0]
+
+ def test_lpd_to_parsed_job(self):
+ j = self.send_invoice()
+ # 8-bit data survives the transport as latin-1, and is blanked in the cleaned 'plain' text
+ self.assertEqual('Invoice', j['doctype'])
+ self.assertEqual('invoice', j['templ'])
+ self.assertIn('\xa3123.45', j['data'])
+ self.assertNotIn('\xa3', j['plain'])
+ self.assertEqual(['ACC001'], list(j['parsed']))
+ pages = j['parsed']['ACC001']
+ self.assertEqual(2, len(pages))
+ # fixed row/column extraction must not be thrown off by the form feeds at the end of each page
+ self.assertEqual('12345', pages[0]['doc_num'])
+ self.assertEqual('ACC001', pages[1]['accno'])
+ self.assertEqual('ACME WINES LTD\n1 HIGH STREET\nLONDON\n\n\n', pages[0]['addr_invoice'])
+ self.assertEqual('B0321021\nB0308206', pages[0]['prod_code'].strip('\n'))
+ self.assertEqual('123.45', pages[0]['tot_due'].strip())
+ self.assertEqual(('ACME WINES LTD',), main.email_accounts['ACC001'])
+ self.assertEqual({('ACC001',), ('accounts',)}, set(j['groupfiles']))
+
+ def test_job_pickle_is_protocol_2_and_recoverable(self):
+ j = self.send_invoice()
+ matches = [os.path.join(d, f) for d, _, fs in os.walk(main.jobdir) for f in fs if f == j['name']]
+ self.assertEqual(1, len(matches))
+ with open(matches[0], 'rb') as f:
+ raw = f.read()
+ self.assertEqual(b'\x80\x02', raw[:2])
+ name, data = j['name'], j['data']
+ main.jobs.clear()
+ main.recover()
+ again = [x for x in main.jobs if x['name'] == name]
+ self.assertEqual(1, len(again))
+ self.assertEqual(data, again[0]['data'])
+ self.assertEqual('12345', again[0]['parsed']['ACC001'][0]['doc_num'])
+
+ def test_http_endpoints(self):
+ j = self.send_invoice()
+ name = j['name']
+
+ r, body = self.get('/recent?fmt=json')
+ self.assertEqual(200, r.status)
+ self.assertTrue(r.getheader('Content-Type').startswith('text/json'))
+ results = json.loads(body.decode('utf-8'))['results']
+ self.assertEqual(name, results[0]['name'])
+ self.assertEqual('Invoice', results[0]['doctype'])
+
+ r, body = self.get('/recent?templ=invoice')
+ self.assertEqual(200, r.status)
+ self.assertIn(name.encode(), body)
+
+ r, body = self.get('/job?name=' + name)
+ parsed = json.loads(body.decode('utf-8'))
+ self.assertEqual('12345', parsed['parsed']['ACC001'][0]['doc_num'])
+ pdf_uri = parsed['stationary']['ACC001']
+ self.assertTrue(pdf_uri.endswith('.pdf'))
+
+ r, body = self.get('/raw?name=' + name)
+ self.assertEqual(j['plain'], body.decode('utf-8'))
+ self.assertEqual(len(body), int(r.getheader('Content-Length')))
+ # page 1 starts on row 48 and page 2 on row 96, i.e. form feeds did not add rows
+ rows = split_lines(j['plain'])
+ self.assertTrue(rows[48].startswith('INVOICE'))
+ self.assertTrue(rows[96].startswith('INVOICE'))
+
+ r, body = self.get('/pdf_file?name=%s&key=ACC001' % name)
+ self.assertEqual(200, r.status)
+ self.assertEqual('application/pdf', r.getheader('Content-Type'))
+ self.assertEqual(b'%PDF', body[:4])
+ self.assertEqual(len(body), int(r.getheader('Content-Length')))
+
+ r, body = self.get('/pdf_file?name=%s&key=ACC001&attach=1' % name)
+ self.assertIn('attachment', r.getheader('Content-Disposition'))
+
+ for path in ['/home', '/sent', '/printed', '/printers', '/settings/email', '/settings/templates',
+ '/pdf?name=' + name, '/debug?name=' + name, '/plaintext?name=' + name, '/']:
+ r, body = self.get(path)
+ self.assertEqual(200, r.status, path)
+ self.assertTrue(body.strip(), path)
+ # mako (format_exceptions=True) renders a template failure as a normal 200 page
+ self.assertNotIn(b'Mako Runtime Error', body, path)
+ self.assertNotIn(b'Traceback', body, path)
+
+ # one
per printed page: the two invoice pages are separated by form feeds
+ r, body = self.get('/plaintext?name=' + name)
+ self.assertEqual(2, body.count(b'
Template invoice.mako
', body)
+ self.assertNotIn(b'Revert to default', body) # nothing customised yet, so nothing to revert
+ self.assertIn(b'Please find your latest invoice 424242 attached', body) # preview of the newest invoice
+ for kind in ('purchase', 'statement'):
+ r, body = self.get('/settings/templates?kind=' + kind)
+ self.assertEqual(200, r.status)
+ self.assertNotIn(b'Mako Runtime Error', body)
+ self.assertIn(b'No ' + emailtemplates.KINDS[kind].lower().encode() + b' document found', body)
+
+ # the filter picks the document; unknown numbers say so
+ r, body = self.get('/settings/templates?kind=invoice&docnum=424242')
+ self.assertIn(j['name'].encode(), body)
+ r, body = self.get('/settings/templates?kind=invoice&docnum=nope')
+ self.assertIn(b'No invoice document found matching', body)
+ self.assertIn(b'nope', body)
+
+ # preview renders what is typed without saving it
+ r, body = self.post('/settings/templates', kind='invoice', action='preview', docnum='424242',
+ template='Re ${doc.doc_num}\n\nHi ${email.name}, invoice ${doc.doc_num} for \xa3${doc.tot_due}.')
+ self.assertEqual(200, r.status)
+ self.assertIn(b'Subject: Re 424242', body)
+ self.assertIn('Hi Sir or Madam, invoice 424242 for \xa3123.45.'.encode('utf-8'), body)
+ self.assertFalse(os.path.exists(path))
+ # a first line that renders empty means no subject, and the editor says so
+ r, body = self.post('/settings/templates', kind='invoice', action='preview', docnum='424242', template='\nJust text')
+ self.assertIn(b'the first line of the template is empty', body)
+ self.assertIn(b'Just text', body)
+
+ # save writes the user template, and the compose form then uses it
+ location, body = self.post_redirect('/settings/templates', kind='invoice', action='save', docnum='',
+ template='Dear ${email.name}\r\nInvoice ${doc.doc_num}\r\n')
+ self.assertEqual('/settings/templates?kind=invoice&docnum=&saved=1', location)
+ self.assertIn(b'Saved the invoice template', body)
+ self.assertIn(b'
Template invoice.mako
', body) # the same line, customised or not
+ self.assertIn(b'Revert to default', body)
+ with open(path, encoding='utf-8') as f:
+ self.assertEqual('Dear ${email.name}\nInvoice ${doc.doc_num}\n', f.read())
+ r, body = self.get('/pdf?name=%s&key=ACC001' % j['name'])
+ self.assertIn(b'value="Dear Sir or Madam"', body) # the first line is the subject...
+ self.assertIn(b'Invoice 424242', body) # ...and the rest is the text
+ self.assertNotIn(b'Dear Sir or Madam\nInvoice', body)
+
+ # revert goes back to the shipped text
+ location, body = self.post_redirect('/settings/templates', kind='invoice', action='revert')
+ self.assertIn(b'Reverted to the shipped invoice template', body)
+ for _ in range(2): # refreshing the page after it just says the same
+ self.assertIn(b'Reverted to the shipped invoice template', self.get(location)[1])
+ self.assertFalse(os.path.exists(path))
+ r, body = self.get('/pdf?name=%s&key=ACC001' % j['name'])
+ self.assertInvoiceBody(body, 'Sir or Madam', doc_num='424242')
+ self.assertSubjectBox(body, self.INVOICE_SUBJECT)
+
+ def test_template_editor_refuses_templates_that_could_run_code(self):
+ self.send_invoice()
+ canary = os.path.join(emailtemplates.USER_DIR, '..', 'canary')
+ evil = [
+ "${__import__('os').makedirs(%r)}" % canary,
+ "<%% import os; os.makedirs(%r) %%>" % canary,
+ "% import os",
+ "${doc.__class__}",
+ ]
+ for text in evil:
+ for action in ('preview', 'save'):
+ r, body = self.post('/settings/templates', kind='invoice', action=action, template=text)
+ self.assertEqual(200, r.status)
+ self.assertIn(b"This template can", body, text)
+ self.assertFalse(os.path.exists(emailtemplates.user_path('invoice')), text)
+ self.assertFalse(os.path.exists(canary), text)
+ # the kind comes from a fixed list, never from a path
+ r, body = self.post('/settings/templates', kind='../../etc/passwd', action='save', template='x')
+ self.assertEqual(303, r.status)
+ self.assertIn('kind=invoice', r.getheader('Location')) # an unknown kind means the first one, not a path
+ self.assertFalse(os.path.exists(os.path.join(emailtemplates.USER_DIR, '..', '..', 'etc')))
+ self.assertEqual(['invoice.mako'], os.listdir(emailtemplates.USER_DIR))
+
+ def test_email_body_follows_the_ticked_contacts(self):
+ j = self.send_invoice()
+ self.add_contact('ACC001', 'ann@x.com', 'Ann')
+ self.add_contact('ACC001', 'bob@x.com', 'Bob')
+
+ def body(*ticked):
+ query = ['name=' + j['name'], 'key=ACC001'] + ['em=' + urllib.parse.quote(e) for e in ticked]
+ r, data = self.get('/email_body?' + '&'.join(query))
+ self.assertEqual(200, r.status)
+ self.assertTrue(r.getheader('Content-Type').startswith('text/json'))
+ answer = json.loads(data.decode('utf-8'))
+ self.assertIsNone(answer['warning'])
+ return answer['body']
+
+ self.assertRegex(body('ann@x.com', 'bob@x.com'), r'\ATo Ann and Bob,?\n\nPlease find your latest invoice 12345')
+ self.assertRegex(body('bob@x.com'), r'\ATo Bob,?\n\nPlease find')
+ self.assertRegex(body(), r'\ATo Sir or Madam,?\n\nPlease find') # nobody ticked
+ self.assertRegex(body('stranger@x.com'), r'\ATo Sir or Madam,?\n') # not in the address book: no name to use
+ query = 'name=%s&key=ACC001&em=bob%%40x.com&em=ann%%40x.com' % j['name']
+ self.assertTrue(json.loads(self.get('/email_body?' + query)[1].decode())['subject'].startswith('New Invoice '))
+ # subject and body both follow the recipients: first line is the subject, the rest the body
+ self.post('/settings/templates', kind='invoice', action='save', template='For ${email.name}\n\n${email.name} <${email.address}>')
+ answer = json.loads(self.get('/email_body?' + query)[1].decode())
+ self.assertEqual(('For Bob and Ann', 'Bob and Ann \n'), (answer['subject'], answer['body'])) # the first ticked address
+ answer = json.loads(self.get('/email_body?name=%s&key=ACC001' % j['name'])[1].decode())
+ self.assertEqual(('For Sir or Madam', 'Sir or Madam <>\n'), (answer['subject'], answer['body']))
+
+ def test_compose_form_is_wired_for_live_updates(self):
+ j = self.send_invoice()
+ self.add_contact('ACC001', 'bob@x.com', 'Bob & Co')
+ r, body = self.get('/pdf?name=%s&key=ACC001' % j['name'])
+ self.assertNotIn(b'Mako Runtime Error', body)
+ self.assertIn(('data-url="/email_body?name=%s&key=ACC001"' % j['name']).encode(), body)
+ self.assertIn(b'id="bodyNotice"', body)
+ self.assertIn(b'', body)
+ # contact names and addresses are escaped where they are shown and where they are values
+ self.assertIn(b' Bob & Co', body)
+ r, js = self.get('/js/compose.js')
+ self.assertEqual(200, r.status)
+ self.assertIn('javascript', r.getheader('Content-Type'))
+
+ def test_default_template_editor(self):
+ self.send_invoice(doc_num='111') # an invoice does not count as "another document"
+ r, body = self.get('/settings/templates?kind=default')
+ self.assertEqual(200, r.status)
+ self.assertNotIn(b'Mako Runtime Error', body)
+ self.assertIn(b'No document found', body)
+ j = self.send_invoice('Delvnote')
+ r, body = self.get('/settings/templates?kind=default')
+ self.assertNotIn(b'Mako Runtime Error', body)
+ self.assertIn(j['name'].encode(), body)
+ self.assertIn(b'Delvnote', body)
+ self.assertIn(b'job name or document type', body)
+ self.assertIn(b'${company.name}', body) # the company details are available here too
+ self.assertNotIn(b'${doc.', body)
+ self.assertIn(b'Default', body) # the tab
+ # the filter takes a job name or a document type
+ for term in (j['name'], 'delvnote'):
+ r, body = self.get('/settings/templates?kind=default&docnum=' + term)
+ self.assertIn(j['name'].encode(), body, term)
+ r, body = self.get('/settings/templates?kind=default&docnum=Nonesuch')
+ self.assertIn(b'No document found matching', body)
+
+ r, body = self.post('/settings/templates', kind='default', action='preview', docnum='', template='${job.doctype} for ${email.name}')
+ self.assertIn(b'Delvnote for Sir or Madam', body)
+ r, body = self.post('/settings/templates', kind='default', action='preview', docnum='', template='From ${company.name} <${company.email}>\n\nHi ${email.name}')
+ self.assertIn(b'From YOUR DOMAIN LTD. <sales@yourdomain.com>', body) # the placeholder company in defaults.cfg
+ # only email and job exist here
+ for text in ('${doc.ourref}', '% for d in docs:\n% endfor'):
+ r, body = self.post('/settings/templates', kind='default', action='save', template=text)
+ self.assertIn(b"This template can", body, text)
+ self.assertFalse(os.path.exists(emailtemplates.user_path('default')), text)
+ location, body = self.post_redirect('/settings/templates', kind='default', action='save', template='Hello ${email.name}, re ${job.doctype}')
+ self.assertIn(b'Saved the default template', body)
+ r, body = self.get('/pdf?name=' + j['name'])
+ self.assertIn(b'Hello Sir or Madam, re Delvnote', body)
+ location, body = self.post_redirect('/settings/templates', kind='default', action='revert')
+ self.assertIn(b'Reverted to the shipped default template', body)
+ r, body = self.get('/pdf?name=' + j['name'])
+ self.assertDefaultBody(body, 'Sir or Madam')
+
+ def test_the_old_single_email_text_is_migrated_once_at_startup(self):
+ import contextlib
+ j = self.send_invoice('Delvnote')
+ # the old text lives in email.pickle, which recover() reads back at startup
+ main.email_template = 'Please find it attached.\r\n\r\nRegards,\r\nTony Page'
+ try:
+ with contextlib.redirect_stdout(io.StringIO()):
+ main.saveEmails()
+ main.jobs.clear(); main.recover()
+ r, body = self.get('/pdf?name=' + j['name'])
+ self.assertIn(b'Please find it attached.\n\nRegards,\nTony Page', body)
+ self.assertSubjectBox(body, self.DEFAULT_SUBJECT_PATTERN)
+ with open(emailtemplates.seed_path('default'), encoding='utf-8') as f:
+ shipped_subject_line = f.readline().rstrip('\n')
+ with open(emailtemplates.user_path('default'), encoding='utf-8') as f:
+ self.assertEqual(shipped_subject_line + '\n\nPlease find it attached.\n\nRegards,\nTony Page\n', f.read())
+ # reverting is not undone by the next restart
+ self.post('/settings/templates', kind='default', action='revert')
+ with contextlib.redirect_stdout(io.StringIO()):
+ main.jobs.clear(); main.recover()
+ self.assertFalse(os.path.exists(emailtemplates.user_path('default')))
+ finally:
+ main.email_template = ''
+ with contextlib.redirect_stdout(io.StringIO()):
+ main.saveEmails()
+
+ def test_the_old_default_text_editor_is_gone(self):
+ r, body = self.get('/settings/template')
+ self.assertEqual(404, r.status)
+ r, body = self.get('/home')
+ self.assertNotIn(b'Default Email Text', body)
+ self.assertIn(b'/settings/templates', body)
+
+ def test_sent_items_shows_only_the_latest_100(self):
+ import datetime
+ def fake(i):
+ now = datetime.datetime(2026, 11, 19, 12, 0, 0)
+ return dict(to=['a%d@x.com' % i], subject='subject-%d' % i, added=now, completed=now, error=None, status=None, body='', attachment='')
+ original = list(mailer_results())
+ try:
+ mailer_results()[:] = [fake(i) for i in range(250)] # newest first, as the mail thread keeps it
+ r, body = self.get('/sent')
+ self.assertEqual(200, r.status)
+ self.assertNotIn(b'Mako Runtime Error', body)
+ self.assertEqual(100, len(re.findall(rb'
', body)))
+ self.assertIn(b'subject-0<', body)
+ self.assertIn(b'subject-99<', body)
+ self.assertNotIn(b'subject-100<', body)
+ self.assertIn(b'Showing the latest 100 of 250 sent emails.', body)
+ # a history that fits is shown whole, with no note
+ mailer_results()[:] = [fake(i) for i in range(3)]
+ r, body = self.get('/sent')
+ self.assertEqual(3, len(re.findall(rb'
', body)))
+ self.assertNotIn(b'Showing the latest', body)
+ finally:
+ mailer_results()[:] = original
+
+ def fake_sent(self, attachment, subject, to=('a@x.com',), error=None):
+ import datetime
+ now = datetime.datetime(2026, 11, 19, 12, 0, 0)
+ return dict(to=list(to), subject=subject, added=now, completed=now, error=error, status=None, body='', attachment=attachment)
+
+ def test_sent_items_link_to_the_job_and_the_job_lists_them(self):
+ j = self.send_invoice(doc_num='777')
+ other = self.send_invoice(doc_num='888')
+ name = j['name']
+ made_here = main.pdfdir + '2026/ACC001/%s-ACC001.pdf' % name
+ long_gone = '/home/printerface/printerface/data/pdf/2015/OLD001/job-20150715-101010-OLD001.pdf'
+ original = list(mailer_results())
+ try:
+ mailer_results()[:] = [ # newest first
+ self.fake_sent(long_gone, 'sent long ago'),
+ self.fake_sent(made_here, 'second mail', to=['ann@x.com', 'bob@x.com'], error='boom '),
+ self.fake_sent(made_here, 'first mail'),
+ self.fake_sent('', 'no attachment'),
+ ]
+ r, body = self.get('/sent')
+ self.assertEqual(200, r.status)
+ self.assertNotIn(b'Mako Runtime Error', body)
+ self.assertEqual(2, body.count(('href="/pdf?name=%s&key=ACC001"' % name).encode())) # one link per email from the loaded job
+ self.assertEqual(2, body.count(('>%s / ACC001' % name).encode())) # the whole "job / key" is the link text
+ self.assertIn(b'job-20150715-101010 / OLD001', body) # the old job is named...
+ self.assertNotIn(b'name=job-20150715-101010', body) # ...but not linked
+ self.assertLess(body.index(b'
Document
'), body.index(b'
To
')) # Document is the first column
+ self.assertIn(b'font-size: 11px', body) # the table is set small
+
+ # the job page lists the emails made from it, and only those
+ r, body = self.get('/pdf?name=%s&key=ACC001' % name)
+ self.assertNotIn(b'Mako Runtime Error', body)
+ self.assertIn(b'
Sent from this job
', body)
+ self.assertIn(b'first mail', body)
+ self.assertIn(b'second mail', body)
+ self.assertLess(body.index(b'second mail'), body.index(b'first mail')) # newest first
+ self.assertIn(b'ann@x.com, bob@x.com', body)
+ self.assertIn(b'boom <b>', body) # escaped
+ self.assertNotIn(b'sent long ago', body)
+ # a job nothing was sent from has no such section
+ r, body = self.get('/pdf?name=%s&key=ACC001' % other['name'])
+ self.assertNotIn(b'Sent from this job', body)
+ finally:
+ mailer_results()[:] = original
+
+ def test_several_invoices_for_one_account_make_one_email(self):
+ # two invoices for one account in one print run, as for VAD101: one PDF, one email
+ j = self.send_invoice(doc_nums=['777', '778'], totals=['\xa3569.73', '\xa344.92'])
+ self.assertEqual(['777', '778'], [p['doc_num'] for p in j['parsed']['ACC001']])
+ r, body = self.get('/pdf?name=%s&key=ACC001' % j['name'])
+ self.assertNotIn(b'Mako Runtime Error', body)
+ self.assertSubjectBox(body, 'New Invoices 777/8')
+ page = body.decode('utf-8')
+ self.assertRegex(page, r'Please find your latest invoices attached for account ACC001, for a total of \xa3614\.65:')
+ self.assertRegex(page, r'777 +\xa3569\.73\n778 +\xa344\.92\n')
+ self.assertNotIn('\xa344.92.', page) # not "for \xa344.92", the last invoice alone
+ # the live update and the editor preview say the same
+ answer = json.loads(self.get('/email_body?name=%s&key=ACC001' % j['name'])[1].decode())
+ self.assertEqual('New Invoices 777/8', answer['subject'])
+ self.assertIn('for a total of \xa3614.65', answer['body'])
+ r, body = self.get('/settings/templates?kind=invoice&docnum=778')
+ self.assertIn(b'Subject: New Invoices 777/8', body)
+ self.assertIn(b'all.numbers', body) # the helper is listed in the editor
+
+ # ---- anything that changes something is a POST, and redirects to a page that is safe to refresh
+
+ def test_sending_an_email_is_a_post_that_redirects(self):
+ from unittest import mock
+ j = self.send_invoice()
+ self.add_contact('ACC001', 'ann@x.com', 'Ann')
+ fields = dict(name=j['name'], key='ACC001', action='send', subject='Hello there', emailbody='The text')
+ with mock.patch.object(main.mailqueue, 'append') as append:
+ # a GET carrying every send parameter only shows the page: it must never send
+ r, body = self.get('/pdf?' + urllib.parse.urlencode(dict(fields, em='ann@x.com')))
+ self.assertEqual(200, r.status)
+ self.assertNotIn(b'Queued the email', body)
+ append.assert_not_called()
+
+ # the POST queues it once and answers with a redirect to the page
+ r, data = self.post('/pdf', em=['ann@x.com'], **fields)
+ self.assertEqual(303, r.status)
+ self.assertEqual('0', r.getheader('Content-Length'))
+ location = r.getheader('Location')
+ self.assertEqual('/pdf?name=%s&key=ACC001&queued=1' % j['name'], location)
+ append.assert_called_once()
+ item = append.call_args[0][0]
+ self.assertEqual((['ann@x.com'], 'Hello there', 'The text'), (item['to'], item['subject'], item['body']))
+ self.assertTrue(item['attachment'].endswith('-ACC001.pdf'), item['attachment'])
+
+ # the page it lands on says so; refreshing it (or following the link again) sends nothing more
+ for _ in range(3):
+ r, body = self.get(location)
+ self.assertEqual(200, r.status)
+ self.assertIn(b'Queued the email to 1 recipient.', body)
+ append.assert_called_once()
+
+ def test_a_refused_send_keeps_what_was_typed_and_who_was_ticked(self):
+ from unittest import mock
+ j = self.send_invoice()
+ self.add_contact('ACC001', 'ann@x.com', 'Ann')
+ self.add_contact('ACC001', 'bob@x.com', 'Bob')
+ with mock.patch.object(main.mailqueue, 'append') as append:
+ r, data = self.post('/pdf', name=j['name'], key='ACC001', action='send', em=['bob@x.com'], subject='x', emailbody='my own words')
+ self.assertEqual(200, r.status) # not a redirect: nothing happened, so say why here
+ page = data.decode('utf-8')
+ self.assertIn('Some fields missing or incomplete', page)
+ self.assertIn('my own words', page)
+ self.assertRegex(page, r'name="subject" placeholder="Subject" value="x"')
+ self.assertRegex(page, r'value="bob@x.com" checked')
+ self.assertNotRegex(page, r'value="ann@x.com" checked')
+ append.assert_not_called()
+ # no recipient at all is refused too
+ r, data = self.post('/pdf', name=j['name'], key='ACC001', action='send', subject='Hello there', emailbody='text')
+ self.assertEqual(200, r.status)
+ append.assert_not_called()
+
+ def test_printing_is_a_post_that_redirects(self):
+ from unittest import mock
+ j = self.send_invoice()
+ with mock.patch.object(main, 'printFile') as printed:
+ r, body = self.get('/print?name=%s&key=ACC001&printer=default' % j['name']) # the old kind of link
+ self.assertEqual(200, r.status)
+ printed.assert_not_called()
+ self.assertIn(b'printed from their', body)
+
+ r, data = self.post('/print', name=j['name'], key='ACC001', printer='default')
+ self.assertEqual(303, r.status)
+ location = r.getheader('Location')
+ self.assertEqual('/pdf?name=%s&key=ACC001&printed=default' % j['name'], location)
+ printed.assert_called_once()
+ self.assertTrue(printed.call_args[0][0].endswith('-ACC001.pdf'))
+ self.assertEqual('default', printed.call_args[0][1])
+ for _ in range(2):
+ self.assertIn(b'Sent the document to printer default.', self.get(location)[1])
+ printed.assert_called_once()
+ # the job page offers printers through a POST form, not links
+ r, body = self.get('/pdf?name=%s&key=ACC001' % j['name'])
+ self.assertIn(b'