Skip to content
Open
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ against a copy of the data on other ports (`lpd_port` and `http_port` in `defaul
* `[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
* `[Main]` also has `brand`, the name at the left of the menu bar and in page titles (default `Printerface`), which is a way to tell instances apart
* `[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
Expand Down
2 changes: 2 additions & 0 deletions defaults.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ logo=logo.jpg
logo2=

[Main]
# The name at the left of the menu bar and in the page titles; set it to tell instances apart
brand=Printerface
summary_trim=AAAA,BBBBBB
lpd_port=1515
http_port=8081
Expand Down
8 changes: 7 additions & 1 deletion httpserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
Pages are plain functions registered by path (`pathhandlers`), the same ones the asyncore server called:
`handler(query_string=..., resp=...)` for GET and HEAD and `handler(query_string=..., postreq=...)` for POST,
where the query string and the form fields arrive as {name: [values]}. A handler returns `(body, content type)`,
with body a str, bytes or binary file object, or a `Redirect`. Anything else is served as a file from the
with body a str, bytes or binary file object, or a `Redirect`; raising `NotFound` answers 404. Anything else is served as a file from the
web root.

Handlers run on the event loop, one at a time, exactly as before: they and the LPD receiver share one thread, so
Expand Down Expand Up @@ -32,6 +32,10 @@
MAX_REQUEST_BYTES = 16 * 1024 * 1024


class NotFound(Exception):
"""A path handler raises this to answer 404, for a thing that is not there (a file it was asked for by name)."""


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
Expand Down Expand Up @@ -148,6 +152,8 @@ def run_handler(self, request, handler, kwargs, gatherer=None):
body = f.read()
f.close()
return self.reply(request, 200, body, headers)
except NotFound:
return self.error(request, 404, 'Not Found')
except Exception:
print(traceback.format_exc())
return self.error(request, 500, 'Internal Server Error')
Expand Down
14 changes: 13 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import asyncio, os, re, signal
from datetime import datetime
from lpdserver import LpdServer
from httpserver import HttpServer, Redirect
from httpserver import HttpServer, Redirect, NotFound, guess_type
import mailer
from mailer import JobMailer
from docparser import DocParser
Expand Down Expand Up @@ -444,6 +444,17 @@ def stationery_details():
rows.append(row)
return rows

def stationery_logo(query_string='', resp=None):
"""The logo file that [Stationery] names under `key` (logo or logo2), for the Stationery page to show. Only
those two settings are served, never a path from the request."""
key = query_string.get('key', [''])[0]
value = config.get('Stationery', key, fallback='') if key in STATIONERY_LOGOS else ''
path = os.path.expanduser(value) if value else ''
if not path or not os.path.isfile(path):
raise NotFound()
with open(path, 'rb') as f:
return f.read(), guess_type(path)

def settings_stationery(query_string='', postreq=None, resp=None):
"""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,
Expand Down Expand Up @@ -805,6 +816,7 @@ def htmlcol(rgb):
'/settings/templates':settings_templates,
'/settings/web':settings_web,
'/settings/stationery':settings_stationery,
'/settings/stationery_logo':stationery_logo,
'/email_body':email_body
}

Expand Down
37 changes: 34 additions & 3 deletions test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,8 +795,10 @@ def test_web_uploads_settings_and_uploads_pages(self):
main.uploadqueue.log.add(dict(job=j['name'], key='ACC001', kind='invoice', account='ACC001', docnum='777', added=datetime.now(), outcome='created', status=201, error=None))
main.uploadqueue.log.add(dict(job='job-19990101-000000', key='ACC001', kind='statement', account='ACC002', docnum='st1', added=datetime.now(), outcome='failed', status=400, error='HTTP 400 bad'))
body = self.get('/uploads')[1]
self.assertIn(b'>777 / ACC001</a>', body) # a loaded job links to its page
self.assertIn(b'st1 / ACC002', body)
self.assertIn(('>%s / ACC001</a>' % j['name']).encode(), body) # job / key, as on the other history pages; a loaded job links to its page
self.assertIn(b'<td>invoice 777</td>', body) # what was uploaded is in the next column
self.assertIn(b'<td>statement st1</td>', body)
self.assertIn(b'job-19990101-000000 / ACC001</span>', body) # not loaded: not linked
self.assertNotIn(b'job-19990101-000000&', body)
self.assertIn(b'HTTP 400 bad', body)

Expand All @@ -820,6 +822,9 @@ def arrive(**kw):
j = arrive(doc_num='6001')
wait_for(1)
self.assertEqual(['6001'], [i['docnum'] for i in sent])
deadline = time.time() + 10
while not main.uploadqueue.log.for_job(j['name']) and time.time() < deadline: # recorded just after the transport returns
time.sleep(0.05)
self.assertEqual('created', main.uploadqueue.log.for_job(j['name'])[0]['outcome'])
self.send_invoice(jtype='Delvnote') # not a listed kind
arrive(doc_num='6002', jtype='Cr-note') # a credit note: not listed either
Expand Down Expand Up @@ -893,9 +898,20 @@ def test_stationery_page_redraws_jobs_drawn_under_older_stationery(self):
self.assertIn(b'SOME BUSINESS PARK', body)
self.assertNotIn(b'\\nSOME', body)
self.assertNotIn(b'label-important">missing', body) # logo.jpg is found, logo2 is blank
self.assertIn(b'<img src="/settings/stationery_logo?key=logo"', body) # shown, for the logo that is there
self.assertNotIn(b'stationery_logo?key=logo2', body)
r, image = self.get('/settings/stationery_logo?key=logo')
self.assertEqual(('image/jpeg', open('logo.jpg', 'rb').read()), (r.getheader('Content-Type'), image))
self.assertEqual(404, self.get('/settings/stationery_logo?key=logo2')[0].status) # blank
self.assertEqual(404, self.get('/settings/stationery_logo?key=terms')[0].status) # only the logos are served
self.assertEqual(404, self.get('/settings/stationery_logo?key=../email.cfg')[0].status)
self.assertEqual(404, self.get('/settings/stationery_logo')[0].status)
main.config.set('Stationery', 'logo2', '/no/such/logo.jpg')
self.addCleanup(main.config.set, 'Stationery', 'logo2', '')
self.assertIn(b'label-important">missing', self.get('/settings/stationery')[1])
body = self.get('/settings/stationery')[1]
self.assertIn(b'label-important">missing', body)
self.assertNotIn(b'stationery_logo?key=logo2', body) # no image for a file that is not there
self.assertEqual(404, self.get('/settings/stationery_logo?key=logo2')[0].status)
main.config.set('Stationery', 'logo2', '')
old = config_terms = main.config.get('Stationery', 'terms')
main.config.set('Stationery', 'terms', old + ' (changed)')
Expand Down Expand Up @@ -1011,6 +1027,21 @@ def test_a_file_older_than_a_full_history_is_ignored(self):
self.assertNotIn(name, [j['name'] for j in main.jobs])
self.assertEqual(printed, self.printed.call_count) # nothing printed for a file that old

def test_the_brand_in_the_menu_bar_and_titles_comes_from_the_config(self):
def brand_and_title(path='/home'):
body = self.get(path)[1].decode('utf-8')
return (re.search(r'<a class="brand" href="/home">(.*?)</a>', body).group(1), re.search(r'<title>(.*?)</title>', body, re.S).group(1))
self.assertEqual('Printerface', brand_and_title()[0]) # the default
self.assertTrue(self.get('/home')[1].startswith(b'<!DOCTYPE html>')) # the template's own code adds nothing before the doctype
self.assertTrue(brand_and_title('/printed')[1].startswith('Printerface - Printed'))
old = main.config.get('Main', 'brand')
self.addCleanup(main.config.set, 'Main', 'brand', old)
main.config.set('Main', 'brand', 'Printertest <&>')
for path in ('/home', '/recent', '/printers', '/settings/web'):
brand, title = brand_and_title(path)
self.assertEqual('Printertest &lt;&amp;&gt;', brand, path) # escaped
self.assertTrue(title.startswith('Printertest &lt;&amp;&gt;'), path)

def test_print_history_is_listed_on_the_job_page(self):
j = self.send_invoice()
self.assertNotIn(b'Printed from this job', self.get('/pdf?name=%s&key=ACC001' % j['name'])[1])
Expand Down
12 changes: 10 additions & 2 deletions test_servers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import threading
import unittest

from httpserver import HttpServer, Redirect
from httpserver import HttpServer, NotFound, Redirect
from lpdserver import LpdServer


Expand Down Expand Up @@ -164,14 +164,17 @@
return ('caf\xe9 %s' % query_string, 'text/plain')

def broken(query_string=None, resp=None, postreq=None):
raise RuntimeError('boom')

Check failure on line 167 in test_servers.py

View workflow job for this annotation

GitHub Actions / test

boom

Check failure on line 167 in test_servers.py

View workflow job for this annotation

GitHub Actions / test

boom

def missing(query_string=None, resp=None, postreq=None):
raise NotFound()

def blob(query_string=None, resp=None):
import io
return (io.BytesIO(b'%PDF-1.4 data'), 'application/pdf')

cls.loop = LoopThread()
cls.server = cls.loop.call(HttpServer({'/echo': echo, '/broken': broken, '/blob': blob}, cls.webroot, ip='127.0.0.1', port=0).start())
cls.server = cls.loop.call(HttpServer({'/echo': echo, '/broken': broken, '/blob': blob, '/missing': missing}, cls.webroot, ip='127.0.0.1', port=0).start())

@classmethod
def tearDownClass(cls):
Expand Down Expand Up @@ -217,6 +220,11 @@
self.assertEqual(500, self.request('POST', '/broken', 'a=1')[0].status)
self.assertEqual(200, self.request('GET', '/echo')[0].status)

def test_a_handler_can_answer_404(self):
self.assertEqual(404, self.request('GET', '/missing')[0].status)
self.assertEqual(404, self.request('POST', '/missing', 'a=1')[0].status)
self.assertEqual(200, self.request('GET', '/echo')[0].status)

def test_unknown_paths_and_methods(self):
self.assertEqual(404, self.request('GET', '/nothing')[0].status)
self.assertEqual(404, self.request('POST', '/nothing', 'a=1')[0].status)
Expand Down
5 changes: 3 additions & 2 deletions web/bootstrap.html
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<%! from settings import config %>\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Printerface <%block name="title"/></title>
<title>${config.get('Main', 'brand', fallback='Printerface') | h} <%block name="title"/></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
Expand Down Expand Up @@ -32,7 +33,7 @@
<div class="navbar navbar-inverse navbar-fixed-top hidden-print">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="/home">Printerface</a>
<a class="brand" href="/home">${config.get('Main', 'brand', fallback='Printerface') | h}</a>
<div class="">
<ul class="nav">
<li ><a href="/recent">Recent Documents</a></li>
Expand Down
1 change: 1 addition & 0 deletions web/settings_stationery.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ <h4>Settings the documents are drawn with</h4>
% if d['logo']:
<br/>
% if d['logo'][1]:
<img src="/settings/stationery_logo?key=${d['key'] | u}" alt="${d['key'] | h}" style="max-width: 265px; max-height: 70px; margin: 4px 0; background: #fff; border: 1px solid #ddd; padding: 2px;"><br/>
<span class="muted">${d['logo'][0] | h}</span>
% else:
<span class="label label-important">missing</span> <span class="muted">${d['logo'][0] | h}</span>
Expand Down
8 changes: 4 additions & 4 deletions web/uploads.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ <h3>Uploads</h3>
<a href="/settings/web">Web Uploads settings</a></p>
% else:
<table class="table table-striped table-condensed" style="font-size: 11px; line-height: 15px;">
<tr><th>Document</th><th>Type</th><th>Result</th><th>Problems?</th></tr>
<tr><th>Document</th><th>Uploaded</th><th>Result</th><th>Problems?</th></tr>
% for row in rows:
<% u = row['u'] %>
% if u['error']:
Expand All @@ -26,12 +26,12 @@ <h3>Uploads</h3>
% endif
<td style="white-space: nowrap;" title="${u['added'].strftime('%d %b %Y %H:%M:%S') | h}">
% if row['loaded']:
<a href="/pdf?name=${u['job'] | u}&amp;key=${u['key'] | u}" title="Open the job this was uploaded from">${u['docnum'] | h} / ${u['account'] | h}</a>
<a href="/pdf?name=${u['job'] | u}&amp;key=${u['key'] | u}" title="Open the job this was uploaded from">${u['job'] | h} / ${u['key'] | h}</a>
% else:
<span class="muted" title="This job is no longer loaded">${u['docnum'] | h} / ${u['account'] | h}</span>
<span class="muted" title="This job is no longer loaded">${u['job'] | h} / ${u['key'] | h}</span>
% endif
</td>
<td>${u['kind'] | h}</td><td>${u['outcome'] | h}</td><td>${u['error'] or '' | h}</td>
<td>${u['kind'] | h} ${u['docnum'] | h}</td><td>${u['outcome'] | h}</td><td>${u['error'] or '' | h}</td>
</tr>
% endfor
</table>
Expand Down
Loading