Then claim the printer in the web UI with a claim code: reset the printer with a
paperclip, then press its button.
+## Share from your phone
+
+sirius can be installed as an app from Chrome on Android, and then shows up as
+"Little Printer" when you share something from another app. Photos open as a
+Dithergram, xkcd links as the comic, and other text and links as a Poster.
+Nothing prints until you press **Print now**.
+
+Chrome only installs apps from HTTPS addresses, and the Pi serves plain HTTP.
+To allow it anyway, on the phone:
+
+1. Open `chrome://flags`, search for **Insecure origins treated as secure**,
+ enter `http://<pi address>:8016`, enable it and restart Chrome.
+2. Open `http://<pi address>:8016/`, sign in, and choose **Install app** (or
+ **Add to home screen**) in Chrome's menu.
+
## Everyday use
```bash
db.session.rollback()
db.session.remove()
db.drop_all()
+ # Every test creates its own app and with it an engine, whose
+ # connections would otherwise stay open until Postgres runs out.
+ db.get_engine(self.app).dispose()
def autologin(self):
# Most disgusting hack but I see no other way to log in users:
+import base64
+import io
+import re
+
import flask
import flask_login as login
import flask_wtf
import flask_wtf.file
from PIL import Image
+from PIL import ImageOps
import wtforms
from sirius.models import hardware
# row can invert the whole print, see the comment in that template.
PADDING_TOP = 1
PADDING_BOTTOM = 80
+# Shared photos are scaled down before they go into the page. Dithergram
+# scales them to the printer's width anyway, this leaves room to spare.
+SHARED_IMAGE_WIDTH = 3 * printer_personality.PRINTER_WIDTH
+SHARED_IMAGE_MAX_HEIGHT = SHARED_IMAGE_WIDTH * 30
+XKCD_LINK = re.compile(r"https?://(?:www\.|m\.)?xkcd\.com/\d+/?")
def validate_print_image(form, field):
flask.url_for("printer_overview.printer_overview", printer_id=printer.id)
)
+ return render_compose(printer, [printer], form)
+
+
+def render_compose(printer, printers, form, shared=None):
return flask.render_template(
"printer_compose.html",
printer=printer,
+ printers=printers,
form=form,
padding=PADDING_TOP + PADDING_BOTTOM,
max_height=MAX_HEIGHT,
+ shared=shared,
+ )
+
+
+def shared_text(title, text, url):
+ """What a share from another app says, as one string.
+
+ Apps fill these differently: browsers often put the link into text and
+ leave url empty, and title can be the same as text or a page title.
+ """
+ title, text, url = title.strip(), text.strip(), url.strip()
+ result = text or title
+ if url and url not in result:
+ result = (result + " " + url).strip()
+ return result
+
+
+def shared_image(upload):
+ """A shared image as a data URL for the page, or None if it's unreadable.
+
+ Phone photos are often rotated only by their EXIF orientation, which a
+ canvas doesn't apply everywhere, so it's applied here.
+ """
+ try:
+ image = Image.open(upload)
+ image.load()
+ except (IOError, ValueError, Image.DecompressionBombError):
+ return None
+
+ try:
+ image = ImageOps.exif_transpose(image)
+ except Exception: # pylint: disable=broad-except
+ # Broken EXIF data is common, the unrotated image is still usable.
+ pass
+
+ image = image.convert("RGBA")
+ background = Image.new("RGBA", image.size, (255, 255, 255, 255))
+ background.paste(image, mask=image)
+ image = background.convert("RGB")
+ image.thumbnail((SHARED_IMAGE_WIDTH, SHARED_IMAGE_MAX_HEIGHT), Image.LANCZOS)
+
+ data = io.BytesIO()
+ image.save(data, "JPEG", quality=90)
+ return "data:image/jpeg;base64," + base64.b64encode(data.getvalue()).decode("ascii")
+
+
+@blueprint.route("/share", methods=["GET", "POST"])
+@login.login_required
+def share():
+ """Where Android sends things shared to the installed web app.
+
+ It doesn't print anything by itself: it opens the compose page with the
+ shared photo, link or text filled in, and printing is still a button
+ press there. That also keeps it harmless when another site posts to it.
+ """
+ printers = (
+ hardware.Printer.query.filter_by(owner_id=login.current_user.id)
+ .order_by(hardware.Printer.id)
+ .all()
+ )
+ if not printers:
+ flask.flash("Claim a printer first, then you can share things to it.")
+ return flask.redirect(flask.url_for("landing.landing"))
+
+ values = flask.request.values
+ text = shared_text(
+ values.get("title", ""), values.get("text", ""), values.get("url", "")
)
+ shared = {"tab": "poster", "text": text}
+
+ # Checked by content: an empty file field still arrives as an upload, and
+ # a sender may leave out the filename of a real one.
+ upload = flask.request.files.get("image")
+ upload_data = upload.read() if upload is not None else b""
+ xkcd_link = XKCD_LINK.search(text)
+ if upload_data:
+ image = shared_image(io.BytesIO(upload_data))
+ if image is None:
+ flask.flash("That's not an image I can read.", "error")
+ else:
+ # A caption is only useful if it isn't just a link.
+ caption = "" if "://" in text else text
+ shared = {"tab": "dithergram", "image": image, "caption": caption}
+ elif xkcd_link:
+ shared = {"tab": "xkcd", "xkcd": xkcd_link.group(0)}
+
+ return render_compose(printers[0], printers, ComposeForm(), shared)
@blueprint.route("/printer/<int:printer_id>/compose/xkcd")
--- /dev/null
+"""Makes sirius installable as a web app, so it can receive shares.
+
+Once installed from Chrome on Android, "Little Printer" shows up in the
+share menu of other apps, and what is shared opens on the compose page (see
+printer_compose.share). Chrome only offers to install over HTTPS, or on an
+address that chrome://flags lists under "Insecure origins treated as
+secure".
+"""
+import json
+
+import flask
+
+
+blueprint = flask.Blueprint("pwa", __name__)
+
+
+@blueprint.route("/manifest.webmanifest")
+def manifest():
+ # Not behind the login: browsers fetch it without cookies.
+ icon = lambda name: flask.url_for("static", filename=name)
+ data = {
+ "name": "Little Printer",
+ "short_name": "Little Printer",
+ "start_url": flask.url_for("landing.landing"),
+ "scope": "/",
+ "display": "standalone",
+ "background_color": "#ffffff",
+ "theme_color": "#222222",
+ "icons": [
+ {"src": icon("icon-192.png"), "sizes": "192x192", "type": "image/png"},
+ {"src": icon("icon-512.png"), "sizes": "512x512", "type": "image/png"},
+ {
+ "src": icon("icon-maskable-512.png"),
+ "sizes": "512x512",
+ "type": "image/png",
+ "purpose": "maskable",
+ },
+ ],
+ "share_target": {
+ "action": flask.url_for("printer_compose.share"),
+ "method": "POST",
+ "enctype": "multipart/form-data",
+ "params": {
+ "title": "title",
+ "text": "text",
+ "url": "url",
+ "files": [{"name": "image", "accept": ["image/*"]}],
+ },
+ },
+ }
+ return flask.Response(json.dumps(data), mimetype="application/manifest+json")
dithergramChanged();
});
dithergramFile.addEventListener("change", function () {
+ if (dithergramFile.files.length) {
+ loadDithergram(URL.createObjectURL(dithergramFile.files[0]));
+ } else {
+ loadDithergram(null);
+ }
+ });
+
+ function loadDithergram(src) {
dithergramImage = null;
resetDithergramAdjustments();
enableDithergramAdjustments(false);
dithergramChanged();
- if (!dithergramFile.files.length) return;
+ if (!src) return;
var loading = new Image();
loading.onload = function () {
loading.onerror = function () {
showError("That's not an image I can read.");
};
- loading.src = URL.createObjectURL(dithergramFile.files[0]);
- });
+ loading.src = src;
+ }
penButton.addEventListener("click", function () {
selectTool(PEN);
$('a[data-toggle="tab"]').on("shown.bs.tab", update);
+ var printerSelect = document.getElementById("compose-printer");
+ if (printerSelect) {
+ printerSelect.addEventListener("change", function () {
+ var option = printerSelect.options[printerSelect.selectedIndex];
+ form.action = option.dataset.composeUrl;
+ form.dataset.xkcdUrl = option.dataset.xkcdUrl;
+ form.dataset.printerUrl = option.dataset.printerUrl;
+ });
+ }
+
+ // Something shared from another app, see printer_compose.share.
+ var sharedData = document.getElementById("compose-shared");
+ if (sharedData) {
+ var shared = JSON.parse(sharedData.textContent);
+ $('a[href="#' + shared.tab + '"]').tab("show");
+ if (shared.tab === "dithergram") {
+ dithergramCaption.value = shared.caption || "";
+ loadDithergram(shared.image);
+ } else if (shared.tab === "xkcd") {
+ xkcdComicInput.value = shared.xkcd;
+ loadXkcd();
+ } else {
+ posterText.value = shared.text || "";
+ renderPoster();
+ update();
+ }
+ }
+
form.addEventListener("submit", function (event) {
event.preventDefault();
send.disabled = true;
{{super()}}
<link rel="stylesheet" href="{{url_for('static', filename='bootstrap-theme.min.css')}}">
<link rel="stylesheet" href="{{url_for('static', filename='site.css')}}">
+<link rel="manifest" href="{{ url_for('pwa.manifest') }}">
+<meta name="theme-color" content="#222222">
+<link rel="apple-touch-icon" href="{{ url_for('static', filename='icon-192.png') }}">
{% endblock %}
{% block title %}Little Printer{% endblock %}
</div>
</div>
+{% if printers|length > 1 %}
+<div class="form-group">
+ <label for="compose-printer">Printer</label>
+ <select class="form-control" id="compose-printer">
+ {% for choice in printers %}
+ <option value="{{ choice.id }}"{% if choice.id == printer.id %} selected{% endif %}
+ data-compose-url="{{ url_for('printer_compose.printer_compose', printer_id=choice.id) }}"
+ data-xkcd-url="{{ url_for('printer_compose.printer_compose_xkcd', printer_id=choice.id) }}"
+ data-printer-url="{{ url_for('printer_overview.printer_overview', printer_id=choice.id) }}">{{ choice.name }}</option>
+ {% endfor %}
+ </select>
+</div>
+{% endif %}
+
+{# The action is written out because shared things open this page at /share. #}
<form method="POST" id="compose-form" data-padding="{{ padding }}" data-max-height="{{ max_height }}"
+ action="{{ url_for('printer_compose.printer_compose', printer_id=printer.id) }}"
data-xkcd-url="{{ url_for('printer_compose.printer_compose_xkcd', printer_id=printer.id) }}"
data-printer-url="{{ url_for('printer_overview.printer_overview', printer_id=printer.id) }}">
{{ form.csrf_token }}
{% block scripts %}
{{ super() }}
+{% if shared %}
+<script type="application/json" id="compose-shared">{{ shared|tojson }}</script>
+{% endif %}
<script src="{{ url_for('static', filename='compose.js') }}"></script>
{% endblock scripts %}
+import base64
import io
+import json
from unittest import mock
import flask
from sirius.models import messages as model_messages
from sirius.models.db import db
from sirius.testing import base
+from sirius.web import printer_compose
def png(width=384, height=20, color=(0, 0, 0, 255)):
db.session.commit()
self.assert404(self.post(png()))
send_message.assert_not_called()
+
+
+def jpeg_rotated(width=40, height=20):
+ """A JPEG that is stored landscape but tagged to be shown portrait."""
+ image = Image.new("RGB", (width, height), (0, 0, 0))
+ exif = image.getexif()
+ exif[0x0112] = 6 # Orientation: rotate 90 degrees to display.
+ data = io.BytesIO()
+ image.save(data, "JPEG", exif=exif.tobytes())
+ data.seek(0)
+ return data
+
+
+# pylint: disable=no-member
+class TestShare(base.Base):
+ def setUp(self):
+ base.Base.setUp(self)
+ self.autologin()
+ hardware.Printer.phone_home("000d6f000273ce0b")
+ self.testuser.claim_printer("n5ry-p6x6-kth7-7hc4", "my test printer")
+ db.session.commit()
+ self.url = flask.url_for("printer_compose.share")
+
+ def shared(self, response):
+ """The data the compose page was given for its script."""
+ self.assert200(response)
+ page = response.get_data(as_text=True)
+ start = page.index('id="compose-shared">') + len('id="compose-shared">')
+ return json.loads(page[start:page.index("</script>", start)])
+
+ def share(self, **data):
+ return self.client.post(self.url, data=data, content_type="multipart/form-data")
+
+ def test_text_goes_to_the_poster(self):
+ shared = self.shared(self.share(title="Title", text="Hello there"))
+ self.assertEqual(shared, {"tab": "poster", "text": "Hello there"})
+
+ def test_link_is_added_to_the_text(self):
+ shared = self.shared(self.share(text="Look", url="https://example.com/"))
+ self.assertEqual(shared["text"], "Look https://example.com/")
+
+ def test_link_already_in_the_text_is_not_repeated(self):
+ shared = self.shared(
+ self.share(text="Look https://example.com/", url="https://example.com/")
+ )
+ self.assertEqual(shared["text"], "Look https://example.com/")
+
+ def test_title_is_used_without_text(self):
+ self.assertEqual(self.shared(self.share(title="Only a title"))["text"], "Only a title")
+
+ def test_xkcd_link_goes_to_the_xkcd_tab(self):
+ shared = self.shared(self.share(text="Ha! https://xkcd.com/327/"))
+ self.assertEqual(shared, {"tab": "xkcd", "xkcd": "https://xkcd.com/327/"})
+
+ def test_image_goes_to_the_dithergram(self):
+ shared = self.shared(self.share(image=(png(), "photo.png"), text="Our cat"))
+ self.assertEqual(shared["tab"], "dithergram")
+ self.assertEqual(shared["caption"], "Our cat")
+ self.assertTrue(shared["image"].startswith("data:image/jpeg;base64,"))
+
+ def test_link_is_not_used_as_caption(self):
+ shared = self.shared(
+ self.share(image=(png(), "photo.png"), text="https://example.com/photo")
+ )
+ self.assertEqual(shared["caption"], "")
+
+ def test_image_is_rotated_and_scaled_down(self):
+ image = printer_compose.shared_image(jpeg_rotated(4000, 2000))
+ decoded = Image.open(io.BytesIO(base64.b64decode(image.split(",", 1)[1])))
+ self.assertEqual(decoded.size, (printer_compose.SHARED_IMAGE_WIDTH, 2304))
+
+ def test_transparency_becomes_white(self):
+ image = printer_compose.shared_image(png(color=(0, 0, 0, 0)))
+ decoded = Image.open(io.BytesIO(base64.b64decode(image.split(",", 1)[1])))
+ self.assertGreater(decoded.convert("L").getpixel((0, 0)), 250)
+
+ def test_unreadable_image_falls_back_to_the_text(self):
+ response = self.share(image=(io.BytesIO(b"not an image"), "x.png"), text="Hi")
+ self.assertEqual(self.shared(response), {"tab": "poster", "text": "Hi"})
+ self.assertIn("not an image I can read", response.get_data(as_text=True))
+
+ def test_empty_file_field_is_ignored(self):
+ response = self.share(image=(io.BytesIO(b""), ""), text="Hi")
+ self.assertEqual(self.shared(response), {"tab": "poster", "text": "Hi"})
+ self.assertNotIn("not an image", response.get_data(as_text=True))
+
+ def test_get_works_too(self):
+ response = self.client.get(self.url + "?text=Hello")
+ self.assertEqual(self.shared(response)["text"], "Hello")
+
+ def test_form_prints_to_the_users_printer(self):
+ page = self.share(text="Hi").get_data(as_text=True)
+ self.assertIn('action="/printer/1/compose"', page)
+ self.assertNotIn('id="compose-printer"', page)
+
+ def test_several_printers_can_be_chosen(self):
+ hardware.Printer.phone_home("000d6f000273ce0c")
+ second = hardware.Printer.query.filter_by(device_address="000d6f000273ce0c").one()
+ second.owner_id = self.testuser.id
+ second.name = "second printer"
+ db.session.commit()
+ page = self.share(text="Hi").get_data(as_text=True)
+ self.assertIn('id="compose-printer"', page)
+ self.assertIn("second printer", page)
+
+ def test_without_printer_goes_to_the_landing_page(self):
+ hardware.Printer.query.first().owner_id = None
+ db.session.commit()
+ self.assertRedirects(self.share(text="Hi"), "/")
+
+ def test_other_users_printers_are_not_offered(self):
+ printer = hardware.Printer.query.first()
+ printer.owner_id = None
+ db.session.commit()
+ self.assertNotIn(b"my test printer", self.share(text="Hi").get_data())
+
+ def test_needs_login(self):
+ self.client.get("/login/twitter/logout")
+ response = self.share(text="Hi")
+ self.assertEqual(response.status_code, 302)
+ self.assertNotIn("compose-shared", response.get_data(as_text=True))
--- /dev/null
+import json
+
+from sirius.testing import base
+
+
+class TestManifest(base.Base):
+ def test_manifest_is_public_and_points_to_share(self):
+ response = self.client.get("/manifest.webmanifest")
+ self.assert200(response)
+ self.assertEqual(response.mimetype, "application/manifest+json")
+ manifest = json.loads(response.get_data(as_text=True))
+ self.assertEqual(manifest["share_target"]["action"], "/share")
+ self.assertEqual(manifest["share_target"]["method"], "POST")
+ for icon in manifest["icons"]:
+ self.assert200(self.client.get(icon["src"]))
+
+ def test_pages_link_the_manifest(self):
+ page = self.client.get("/").get_data(as_text=True)
+ self.assertIn('rel="manifest" href="/manifest.webmanifest"', page)
from sirius.web import local_login
from sirius.web import printer_compose
from sirius.web import printer_personality
+from sirius.web import pwa
from sirius.web import twitter
from sirius.web import login
from sirius.web import admin
app.register_blueprint(print_key_api.blueprint)
app.register_blueprint(printer_personality.blueprint)
app.register_blueprint(printer_compose.blueprint)
+ app.register_blueprint(pwa.blueprint)
# Live interactions.
gevent.spawn(protocol_loop.mark_dead_loop)
--- /dev/null
+const { test, expect } = require("@playwright/test");
+const { canvasRows, png, printedRows, signIn } = require("./helpers");
+
+const PADDING_TOP = 1;
+const PADDING_BOTTOM = 80;
+
+// Posts to /share the way Android does for an installed web app: a
+// multipart form, with the page navigating to the answer.
+async function share(page, fields, file) {
+ await page.goto("/printer/1");
+ await page.evaluate((fields) => {
+ const form = document.createElement("form");
+ form.method = "POST";
+ form.action = "/share";
+ form.enctype = "multipart/form-data";
+ form.id = "share-test";
+ for (const [name, value] of Object.entries(fields)) {
+ const input = document.createElement("input");
+ input.name = name;
+ input.value = value;
+ form.appendChild(input);
+ }
+ const image = document.createElement("input");
+ image.type = "file";
+ image.name = "image";
+ form.appendChild(image);
+ document.body.appendChild(form);
+ }, fields);
+ if (file) await page.setInputFiles('#share-test [name="image"]', file);
+ await Promise.all([page.waitForURL("/share"), page.evaluate(() => document.getElementById("share-test").submit())]);
+ await page.evaluate(() => document.fonts.ready);
+}
+
+async function expectPrintedAsShown(page, shown) {
+ await page.click("#compose-send");
+ await expect(page).toHaveURL("/printer/1");
+ await expect(page.locator(".alert")).toContainText("Sent your message");
+ const blank = "1".repeat(384);
+ expect((await printedRows(page)).rows).toEqual([
+ ...Array(PADDING_TOP).fill(blank),
+ ...shown.rows,
+ ...Array(PADDING_BOTTOM).fill(blank),
+ ]);
+}
+
+test.beforeEach(async ({ page, request }) => {
+ await request.post("/test/reset");
+ await signIn(page);
+});
+
+test("the manifest offers sharing to /share", async ({ request }) => {
+ const manifest = await (await request.get("/manifest.webmanifest")).json();
+ expect(manifest.share_target.action).toBe("/share");
+});
+
+test("shared text becomes a poster, and prints", async ({ page }) => {
+ await share(page, { title: "", text: "hello from my phone", url: "" });
+ await expect(page.locator("#poster")).toHaveClass(/active/);
+ await expect(page.locator("#poster-text")).toHaveValue("hello from my phone");
+ await expect(page.locator("#compose-send")).toBeEnabled();
+ const shown = await canvasRows(page, "#poster-canvas");
+ expect(shown.rows.some((row) => row.includes("0"))).toBe(true);
+ await expectPrintedAsShown(page, shown);
+});
+
+test("a shared photo becomes a dithergram with its caption, and prints", async ({ page }) => {
+ const photo = await png(page, 800, 400, { color: "#777" });
+ await share(page, { text: "our cat" }, { ...photo, name: "cat.png" });
+ await expect(page.locator("#dithergram")).toHaveClass(/active/);
+ await expect(page.locator("#dithergram-caption")).toHaveValue("our cat");
+ await expect(page.locator("#compose-send")).toBeEnabled();
+ await expect(page.locator("#dithergram-brightness")).toBeEnabled();
+ const shown = await canvasRows(page, "#dithergram-canvas");
+ expect(shown.width).toBe(384);
+ // 800x400 scaled to 384 wide is 192 rows, the caption goes below.
+ expect(shown.rows.length).toBeGreaterThan(192);
+ await expectPrintedAsShown(page, shown);
+});
+
+test("a shared xkcd link loads the comic", async ({ page }) => {
+ await share(page, { text: "ha https://xkcd.com/100/" });
+ await expect(page.locator("#xkcd")).toHaveClass(/active/);
+ await expect(page.locator("#xkcd-comic")).toHaveValue("https://xkcd.com/100/");
+ await expect(page.locator("#compose-send")).toBeEnabled();
+ await expectPrintedAsShown(page, await canvasRows(page, "#xkcd-canvas"));
+});
+
+test("a shared file that isn't an image falls back to the text", async ({ page }) => {
+ const file = { name: "x.png", mimeType: "image/png", buffer: Buffer.from("not an image") };
+ await share(page, { text: "still here" }, file);
+ await expect(page.locator(".alert-warning")).toContainText("not an image I can read");
+ await expect(page.locator("#poster-text")).toHaveValue("still here");
+});