diff --git a/README.md b/README.md index 74b3b60..7a56506 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/defaults.cfg b/defaults.cfg index 0217c60..8b0f650 100644 --- a/defaults.cfg +++ b/defaults.cfg @@ -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 diff --git a/httpserver.py b/httpserver.py index 50b7d12..e4c5d21 100644 --- a/httpserver.py +++ b/httpserver.py @@ -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 @@ -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 @@ -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') diff --git a/main.py b/main.py index 2049566..17c8963 100755 --- a/main.py +++ b/main.py @@ -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 @@ -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, @@ -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 } diff --git a/test_integration.py b/test_integration.py index 7352c8e..a745b80 100644 --- a/test_integration.py +++ b/test_integration.py @@ -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', body) # a loaded job links to its page - self.assertIn(b'st1 / ACC002', body) + self.assertIn(('>%s / ACC001' % j['name']).encode(), body) # job / key, as on the other history pages; a loaded job links to its page + self.assertIn(b'invoice 777', body) # what was uploaded is in the next column + self.assertIn(b'statement st1', body) + self.assertIn(b'job-19990101-000000 / ACC001', body) # not loaded: not linked self.assertNotIn(b'job-19990101-000000&', body) self.assertIn(b'HTTP 400 bad', body) @@ -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 @@ -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'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)') @@ -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'(.*?)', body).group(1), re.search(r'(.*?)', body, re.S).group(1)) + self.assertEqual('Printerface', brand_and_title()[0]) # the default + self.assertTrue(self.get('/home')[1].startswith(b'')) # 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 <&>', brand, path) # escaped + self.assertTrue(title.startswith('Printertest <&>'), 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]) diff --git a/test_servers.py b/test_servers.py index b3c602e..0ea0ba2 100644 --- a/test_servers.py +++ b/test_servers.py @@ -8,7 +8,7 @@ import threading import unittest -from httpserver import HttpServer, Redirect +from httpserver import HttpServer, NotFound, Redirect from lpdserver import LpdServer @@ -166,12 +166,15 @@ def echo(query_string=None, resp=None, postreq=None): def broken(query_string=None, resp=None, postreq=None): raise RuntimeError('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): @@ -217,6 +220,11 @@ def test_a_failing_handler_is_a_500_and_the_server_carries_on(self): 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) diff --git a/web/bootstrap.html b/web/bootstrap.html index 390d571..2875c34 100644 --- a/web/bootstrap.html +++ b/web/bootstrap.html @@ -1,8 +1,9 @@ +<%! from settings import config %>\ - Printerface <%block name="title"/> + ${config.get('Main', 'brand', fallback='Printerface') | h} <%block name="title"/> @@ -32,7 +33,7 @@