Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
ef6d9c1
Normalise mixed tab/space indentation (py2 tab=8 semantics preserved)
shuckc Nov 18, 2026
25cb4a7
Port to python 3.11
shuckc Nov 18, 2026
2070dd5
Add end to end tests: RFC1179 client -> LPD -> parse -> PDF -> HTTP
shuckc Nov 18, 2026
2f59f6a
Packaging for python 3.11: requirements, Dockerfile, CI, README
shuckc Nov 18, 2026
a03b7e0
Add corpus comparison and LPD replay tools
shuckc Nov 19, 2026
11e1681
Add compare_http.py: diff the read-only API of two instances
shuckc Nov 19, 2026
df88920
init.d: run main.py with an explicit python 3.11 interpreter
shuckc Nov 19, 2026
7ad28b8
Fix /plaintext: loop over a list, mako's loop.last needs len()
shuckc Nov 19, 2026
a78c98b
Bump template copyright footer to 2026
shuckc Nov 19, 2026
a00297d
Fix /recent json: report each job's own ts
shuckc Nov 19, 2026
98dbbb3
Per document type email templates, with a web editor and preview
shuckc Nov 19, 2026
b25a8fd
Drop the comment lines from the shipped email templates
shuckc Nov 19, 2026
2832e2d
Ignore .venv
shuckc Nov 19, 2026
d79c454
Fold the default email text into templates/default.mako: one editor
shuckc Nov 19, 2026
d98718f
Compose form: re-render the email text when contacts are ticked or un…
shuckc Nov 19, 2026
0afb179
Email templates: the first rendered line is the subject, the rest is …
shuckc Nov 19, 2026
0906bef
Default email template: make company.* available
shuckc Nov 19, 2026
5de667c
Template editor: show just 'Template <file>' above the text
shuckc Nov 19, 2026
ce71c24
Sent Items: show only the latest 100 emails
shuckc Nov 19, 2026
08892f4
Link sent items to their job, and list a job's sent emails on its page
shuckc Nov 19, 2026
88986b3
Sent Items: Document first as one 'job / key' link, and a smaller table
shuckc Nov 19, 2026
2980be6
Email templates: an 'all' helper for several documents, and use the d…
shuckc Nov 19, 2026
5cec337
Shipped email templates: greeting comma, signature, and the document …
shuckc Nov 19, 2026
16c4940
Actions that change something are POSTs that redirect, so a refresh n…
shuckc Nov 19, 2026
8f52def
Remove the dead PDF Tool send form from the plain text page
shuckc Nov 19, 2026
0a79b03
A printing failure no longer loses a job, and the tests never print
shuckc Nov 19, 2026
6d6a0f5
Printers page shows the CUPS state and whether auto-printing can work
shuckc Nov 19, 2026
2a416de
Printing uses lp and records the CUPS request id against the job and …
shuckc Nov 19, 2026
dee9d35
Printed Items page, listing what was sent to a printer like Sent Item…
shuckc Nov 20, 2026
9c2db18
Name the pages for what they hold: Recent Documents, Sent Emails, Pri…
shuckc Nov 20, 2026
8bffabb
Parsing an lpstat date with a zone name no longer depends on the mach…
shuckc Nov 20, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/docker-image.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
18 changes: 18 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
*.py[cod]
venv
.venv
7 changes: 0 additions & 7 deletions .travis.yml

This file was deleted.

11 changes: 3 additions & 8 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
Expand All @@ -21,4 +17,3 @@ COPY . /app/

WORKDIR /app
RUN python -m unittest discover --pattern=*.py
# RUN ls -la /app/
76 changes: 69 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# printerface
[![Build Status](https://travis-ci.org/shuckc/printerface.svg?branch=master)](https://travis-ci.org/shuckc/printerface) [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)
[![Tests](https://github.com/shuckc/printerface/actions/workflows/tests.yml/badge.svg)](https://github.com/shuckc/printerface/actions/workflows/tests.yml) [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](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.

Expand Down Expand Up @@ -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/<type>.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.<field>}` (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.
Expand Down Expand Up @@ -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.
37 changes: 18 additions & 19 deletions datamine.py
Original file line number Diff line number Diff line change
@@ -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 = []

Expand All @@ -29,16 +28,16 @@ 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']))
cleanJob(s, 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):

Expand Down Expand Up @@ -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
Expand All @@ -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):
Expand All @@ -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'],
Expand Down Expand Up @@ -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')
38 changes: 22 additions & 16 deletions docparser.py
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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 = []
Expand Down Expand Up @@ -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 = []
Expand Down Expand Up @@ -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 = []
Expand Down Expand Up @@ -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 = []
Expand Down Expand Up @@ -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 = []
Expand All @@ -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)

Expand Down
Loading
Loading