Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Printerface is an application that acts as a virtual printer, accepting LPD (Lin

The service is written in Python, with a Javascript web front end using bootstrap JS. It has a rich JSON API and can be used as a centralised interface to legacy system output, whereby documents can be parsed and then consumed by downstream services. We have production instances with over 100k documents a year, 5-6M pages.

Computer systems as old as Windows NT4 can print to LPD printers as standard, so integration even into the most challenging environments is relatively easy compared to modifying legacy systems. Printerface provides a great path forward for customers trapped with old fixed-width, fanfold or pre-printed stationary systems, or struggling to maintain old dot-matrix line printers.
Computer systems as old as Windows NT4 can print to LPD printers as standard, so integration even into the most challenging environments is relatively easy compared to modifying legacy systems. Printerface provides a great path forward for customers trapped with old fixed-width, fanfold or pre-printed stationery systems, or struggling to maintain old dot-matrix line printers.

Often we can de-duplicate or drop entirely sections of the documents that are no longer required in hard copies, to reduce the environmental footprint of legacy print jobs.

Expand All @@ -26,7 +26,7 @@ The following will checkout the source code, build a docker image and start an i
* `httpserver.py` the web server: path handlers and static files on aiohttp, handlers run on the event loop one at a time
* `mailer.py` asynchronous mail queue to Gmail
* `docparser` recognise and parse some plain-text formats from 1990 to JSON
* `stationary.py` format JSON to nice PDF files
* `stationery.py` format JSON to nice PDF files
* `printing.py` printing with CUPS via `lp`. Each document sent is recorded (job, key, printer, CUPS request id or the error) in `~/printerface/printer.pickle`, newest first and trimmed to `[Printing] result_count` (the sent emails and uploads have their own `result_count` under `[Gmail]` and `[Web]`), and listed on the job page. The file is written from the main loop only when something changed
* `derived.py` a cache, `~/printerface/derived.pickle`, of what is slow to work out from a stored job: its parsed pages and the names of its PDFs. At startup a job whose file is unchanged and whose parser is unchanged takes these from the cache (a thousand jobs in under a second, against about eight), and a job that has left the loaded history drops out of the file the next time it is written (at most every three minutes, and at shutdown). The PDFs are not redrawn when the stationery changes: Settings > Stationery counts the documents drawn under older stationery and redraws them on request
* `printstatus.py` read-only CUPS status for the Printers page (one `lpstat -t` in the C locale, cached for 10s), and the check of whether auto-printing can work. lpstat can show a stuck or stopped queue but not that a page was printed
Expand Down Expand Up @@ -54,6 +54,18 @@ Jobs, rendered PDFs, the email address book and `email.cfg` overrides live in `~
`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`).

### Configuration

`defaults.cfg` lists every setting; `~/printerface/email.cfg` overrides what you need to, under the same section names:

* `[Stationery]` how documents are drawn: the company details, terms and logos on the PDFs. Settings > Stationery lists the values in use
* `[Printing]` what is done with documents once drawn: `auto_types` and `auto_printer` for printing on arrival, and `result_count` for the printed history
* `[Web]` the website documents are uploaded to (`base_url`, `api_key`), `auto_types` for uploading on arrival, and `result_count` for the upload history
* `[Gmail]` the mail account and `result_count` for the sent history; `[Main]` ports, time zone and the like; `[History]` how many jobs to load and show

These were `[Printing]` (the company details) and `[Robot]` (auto-printing) before. A file written for those is still read, with a
notice in the log, and `tools/migrate_config.py` rewrites one in place (`--dry-run` shows the result first, and the original is kept).

### Email templates

The text offered when emailing a document comes from a template per document type: `invoice`, `purchase` and
Expand Down
10 changes: 6 additions & 4 deletions defaults.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from=printerface@localhost
to=chris@shucksmith.co.uk

[Printing]
# How documents are drawn: the company details and logos on the stationery
[Stationery]
email=sales@yourdomain.com
website=www.yourdomain.com
vatreg=VAT Reg. GB-123 456 789
Expand All @@ -17,8 +18,6 @@ purch_instruction_fr=Veuillez confirmer reception de cette commande et sa\ndate
purch_instruction_en=Please contact immediately if any problems or\nqueries.
logo=logo.jpg
logo2=
# How many printed documents to remember (newest first) on the Printed Documents page
result_count=200

[Main]
summary_trim=AAAA,BBBBBB
Expand All @@ -37,9 +36,12 @@ auto_types=
# How many uploads to remember (newest first) on the Uploads page
result_count=120

[Robot]
# What is done with documents once drawn: the kinds printed as soon as they arrive, on which CUPS queue, and how
# many printed documents to remember (newest first) on the Printed Documents page
[Printing]
auto_types=Delvnote,Pick lst
auto_printer=HP_TONY
result_count=200

[History]
loadqty=800
Expand Down
6 changes: 3 additions & 3 deletions derived.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
An entry is only trusted if
* the job file is the one it was made from (size and modification time),
* it was parsed by the same parser (`parse_stamp`: docparser.py and textutil.py),
and the PDFs it names are still on disk. How the PDFs were drawn (`render_stamp`: stationary.py, the [Printing]
and the PDFs it names are still on disk. How the PDFs were drawn (`render_stamp`: stationery.py, the [Stationery]
company details and the logos) is recorded with it, but a change does not redraw them by itself: the Stationery
settings page counts the jobs drawn under older stationery and has the button that redraws them.
"""
Expand Down Expand Up @@ -51,9 +51,9 @@ def parse_stamp():


def render_stamp():
parts = [FORMAT, _source('stationary.py'), sorted(config.items('Printing'))]
parts = [FORMAT, _source('stationery.py'), sorted(config.items('Stationery'))]
for key in ('logo', 'logo2'):
path = os.path.expanduser(config.get('Printing', key, fallback=''))
path = os.path.expanduser(config.get('Stationery', key, fallback=''))
try:
st = os.stat(path) if path else None
except OSError:
Expand Down
2 changes: 1 addition & 1 deletion emailtemplates.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def build_context(job, key, names=(), addresses=(), company=None):
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
company company.name, company.email, company.website, from the [Stationery] 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]
Expand Down
38 changes: 28 additions & 10 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import mailer
from mailer import JobMailer
from docparser import DocParser
from stationary import DocFormatter
from stationery import DocFormatter
from printing import getPrinters, printFile
import printing
import printstatus
Expand All @@ -28,6 +28,7 @@
import json
import time
import pytz
import settings
from settings import config, HOME
import emailtemplates
from textutil import split_lines, load_job_pickle, load_user_pickles, PICKLE_PROTOCOL
Expand Down Expand Up @@ -276,8 +277,8 @@ def cleanJob(j, entry=None):

# all done
j['autoprint'] = None
if j['doctype'] in config.get('Robot', 'auto_types').split(','):
j['autoprint'] = config.get('Robot', 'auto_printer')
if j['doctype'] in config.get('Printing', 'auto_types').split(','):
j['autoprint'] = config.get('Printing', 'auto_printer')
return outcome

def register_accounts(j):
Expand Down Expand Up @@ -372,15 +373,15 @@ def job(query_string=dict(), resp=None):
'templ': job.get('templ'),
'doctype': job.get('doctype'),
'autofmt': job.get('autofmt'),
'stationary':
'stationery':
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):
"""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')
auto_types = [t for t in config.get('Printing', 'auto_types').split(',') if t]
auto_printer = config.get('Printing', 'auto_printer')
try:
st = printstatus.status()
error = None
Expand Down Expand Up @@ -427,9 +428,25 @@ def regenerate_stationery():
derivedcache.dirty = True
return len(stale)

STATIONERY_LOGOS = ('logo', 'logo2')

def stationery_details():
"""The [Stationery] settings the documents are drawn with, as the Stationery page lists them: each key with its
value (split on the \\n that stands for a line break), whether email.cfg sets it or it is the default, and for a
logo whether the file is there."""
rows = []
for key in config.options('Stationery'):
value = config.get('Stationery', key)
row = dict(key=key, lines=value.split('\\n') if value else [], set=('Stationery', key) in settings.overridden, logo=None)
if key in STATIONERY_LOGOS and value:
path = os.path.expanduser(value)
row['logo'] = (path, os.path.isfile(path))
rows.append(row)
return rows

def settings_stationery(query_string='', postreq=None, resp=None):
"""How many loaded jobs have PDFs drawn under older stationery (a change to stationary.py, or to the company
details or logos under [Printing]), with the button that draws them again. It blocks the server while it works,
"""How many loaded jobs have PDFs drawn under older stationery (a change to stationery.py, or to the company
details or logos under [Stationery]), with the button that draws them again. It blocks the server while it works,
about a second for every few hundred jobs, so it is an admin action rather than something done on its own."""
if postreq is not None:
n = regenerate_stationery() if 'regenerate' in postreq else 0
Expand All @@ -438,7 +455,8 @@ def settings_stationery(query_string='', postreq=None, resp=None):
redrawn = int(query_string.get('redrawn', [''])[0])
except ValueError:
redrawn = None
return ( template_lookup.get_template("/settings_stationery.html").render(stale=len(derivedcache.stale(jobs)), total=len(jobs), redrawn=redrawn), 'text/html')
return ( template_lookup.get_template("/settings_stationery.html").render(stale=len(derivedcache.stale(jobs)), total=len(jobs), redrawn=redrawn,
details=stationery_details(), config_path=os.path.join(HOME, 'email.cfg')), 'text/html')

def settings_web(query_string='', resp=None):
"""Where documents are uploaded to. Read only: it is set under [Web] in email.cfg. The API key is never shown, only
Expand Down Expand Up @@ -491,7 +509,7 @@ def printfn(query_string='', postreq=None, resp=None):
return doMessage(title='Printing', message='Could not find the document, or a problem printing it! Source: %s sent to printer %s<br>' % (html.escape(str(docf)), html.escape(printer)))

def company_info():
printing = lambda k: config.get('Printing', k, fallback='')
printing = lambda k: config.get('Stationery', 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):
Expand Down
39 changes: 37 additions & 2 deletions settings.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,54 @@
# Locations and configuration shared by main, mailer and stationary.
# Locations and configuration shared by main, mailer and stationery.
#
# 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 io
import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
HOME = os.path.expanduser(os.environ.get('PRINTERFACE_HOME', '~/printerface'))

# [Stationery] is how documents are drawn (company details, logos), [Printing] is what is done with them once drawn
# (auto-print, the printed history). They used to be [Printing] and [Robot]; a file written for that is still read,
# the keys that were in [Printing] going to [Stationery] and those in [Robot] to [Printing]. tools/migrate_config.py
# rewrites a file to the new layout.

# the (section, key) pairs that email.cfg sets, for the settings pages to mark as changed from the defaults
overridden = set()

def translate(user, company_keys):
"""(RawConfigParser in the current layout, whether it was in the old one) for a RawConfigParser read from email.cfg."""
out = configparser.RawConfigParser()
legacy = False
for section in user.sections():
for key, value in user.items(section):
target = section
if section == 'Robot':
target, legacy = 'Printing', True
elif section == 'Printing' and key in company_keys:
target, legacy = 'Stationery', True
if not out.has_section(target):
out.add_section(target)
out.set(target, key, value)
return out, legacy

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'))
user = configparser.RawConfigParser()
user.read(os.path.join(HOME, 'email.cfg'))
user, legacy = translate(user, set(config.options('Stationery')))
if legacy:
print('[config] %s/email.cfg uses the old [Printing] and [Robot] sections; read as [Stationery] and [Printing]. '
'Run tools/migrate_config.py to update it' % HOME)
buf = io.StringIO()
user.write(buf)
config.read_string(buf.getvalue())
overridden.clear()
overridden.update((section, key) for section in user.sections() for key in user.options(section))
return config

config = load_config()
32 changes: 16 additions & 16 deletions stationary.py → stationery.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,27 @@ def headerDetails(c, ctx, doctype="DELIVERY NOTE", terms_key='terms'):

textobject = c.beginText(0*cm, top-1.5*cm)
textobject.setFont("Helvetica", 8)
textobject.textLines(config.get('Printing', 'address').split("\\n"))
textobject.textLines(config.get('Stationery', 'address').split("\\n"))
c.drawText(textobject)

textobject = c.beginText(5.5*cm, top-1.5*cm)
textobject.setFont("Helvetica", 8)
textobject.textLine(config.get('Printing', 'vatreg'))
textobject.textLine(config.get('Printing', 'fax1'))
textobject.textLine(config.get('Printing', 'fax2'))
textobject.textLine(config.get('Printing', 'email'))
textobject.textLine(config.get('Printing', 'website'))
textobject.textLine(config.get('Stationery', 'vatreg'))
textobject.textLine(config.get('Stationery', 'fax1'))
textobject.textLine(config.get('Stationery', 'fax2'))
textobject.textLine(config.get('Stationery', 'email'))
textobject.textLine(config.get('Stationery', 'website'))
c.drawText(textobject)

c.setFont("Helvetica", 18)
c.drawRightString(pagewidth, top, doctype)
c.restoreState()
c.drawImage(os.path.expanduser(config.get('Printing', 'logo')) , 0.0*cm, top-1.1*cm, width=7.0*cm,height=1.8*cm, preserveAspectRatio=True, anchor='sw')
if config.get('Printing', 'logo2'):
c.drawImage(os.path.expanduser(config.get('Printing', 'logo2')), 5.0*cm, top-0.9*cm, width=5.0*cm,height=1.4*cm, preserveAspectRatio=True, anchor='sw')
c.drawImage(os.path.expanduser(config.get('Stationery', 'logo')) , 0.0*cm, top-1.1*cm, width=7.0*cm,height=1.8*cm, preserveAspectRatio=True, anchor='sw')
if config.get('Stationery', 'logo2'):
c.drawImage(os.path.expanduser(config.get('Stationery', 'logo2')), 5.0*cm, top-0.9*cm, width=5.0*cm,height=1.4*cm, preserveAspectRatio=True, anchor='sw')

c.setFont("Helvetica", 10)
c.drawString(0, 0.40*cm, config.get('Printing', terms_key))
c.drawString(0, 0.40*cm, config.get('Stationery', terms_key))

# marker of progress on CLI
sys.stdout.write('.')
Expand Down Expand Up @@ -176,7 +176,7 @@ def deliveryNotePage(c, ctx, mark):
w = pagewidth / 2.0
h = 0.45*cm
topBox(c, 0, y, w=w, h=h, title='SECTION TO BE COMPLETED BY CUSTOMER', content='', align='c')
topBox(c, w, y, w=w, h=h, title=config.get('Printing', 'inv_rhs'), content='', align='c')
topBox(c, w, y, w=w, h=h, title=config.get('Stationery', 'inv_rhs'), content='', align='c')
y = y-h
h = 0.85*cm
leftBox(c, 0, y, w=w, h=h, title='SIGNED', content='')
Expand Down Expand Up @@ -319,7 +319,7 @@ def purchasePage(c, ctx, mark):
(x, y1) = leftBox(c, x, y0-vpad, w=pagewidth-x, title='TOTAL NET', content=price_tot, colfmt='dr')

w = 10.4*cm
(x, y) = topBox(c, 0, y0-vpad, w=w, h=3.7*cm, pad=0.2*cm, title=config.get('Printing', 'purch_instruction_header'), align='c', content=config.get('Printing', 'purch_instruction_en').replace("\\n", '\n'))
(x, y) = topBox(c, 0, y0-vpad, w=w, h=3.7*cm, pad=0.2*cm, title=config.get('Stationery', 'purch_instruction_header'), align='c', content=config.get('Stationery', 'purch_instruction_en').replace("\\n", '\n'))

c.showPage()

Expand All @@ -341,8 +341,8 @@ def statementPage(c, ctx, mark):
textobject.setTextOrigin(divide+vpad, top-vpad)
textobject.setFont("Helvetica", 8)
textobject.textLines('PLEASE DETACH AND RETURN\nWITH YOUR REMITTANCE TO:')
textobject.textLines(config.get('Printing', 'address').replace("\\n", '\n'))
textobject.textLines(config.get('Printing', 'fax1'))
textobject.textLines(config.get('Stationery', 'address').replace("\\n", '\n'))
textobject.textLines(config.get('Stationery', 'fax1'))
c.drawText(textobject)

h = 0.85*cm
Expand Down Expand Up @@ -417,7 +417,7 @@ def genericPage(c, data, title=None, fontsz=7, landsc=False, overlay=None, decor
if title:
c.setFont("Helvetica", 18)
c.drawRightString(pagewidth, top, title)
c.drawImage(os.path.expanduser(config.get('Printing', 'logo')) , 0.0*cm, top-1.1*cm, width=7.0*cm,height=1.8*cm, preserveAspectRatio=True, anchor='sw')
c.drawImage(os.path.expanduser(config.get('Stationery', 'logo')) , 0.0*cm, top-1.1*cm, width=7.0*cm,height=1.8*cm, preserveAspectRatio=True, anchor='sw')
y = y - 2.0*cm

textobject = c.beginText()
Expand Down Expand Up @@ -700,7 +700,7 @@ def getBestPageFormat(self, plaintext):

import unittest
from datetime import datetime
class TestStationary(unittest.TestCase):
class TestStationery(unittest.TestCase):

def setUp(self):
import tempfile
Expand Down
Loading
Loading