From 0b1b9100f2c2e0631fe137f3a69ffb357290ca1f Mon Sep 17 00:00:00 2001 From: Joe Rickerby Date: Wed, 10 Jan 2018 19:19:58 +0000 Subject: [PATCH] Add print keys, an API for using and a docs page for them --- migrations/versions/15dd8689e7fe_print_key.py | 30 +++++ sirius/models/print_keys.py | 19 ++++ sirius/web/print_key_api.py | 81 +++++++++++++ sirius/web/templates/print_key.html | 106 ++++++++++++++++++ sirius/web/templates/printer_print.html | 2 +- sirius/web/webapp.py | 2 + 6 files changed, 239 insertions(+), 1 deletion(-) create mode 100644 migrations/versions/15dd8689e7fe_print_key.py create mode 100644 sirius/models/print_keys.py create mode 100644 sirius/web/print_key_api.py create mode 100644 sirius/web/templates/print_key.html diff --git a/migrations/versions/15dd8689e7fe_print_key.py b/migrations/versions/15dd8689e7fe_print_key.py new file mode 100644 index 0000000..b2aaa26 --- /dev/null +++ b/migrations/versions/15dd8689e7fe_print_key.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: 15dd8689e7fe +Revises: 18ec55ca3e22 +Create Date: 2018-01-10 17:21:00.034598 + +""" + +# revision identifiers, used by Alembic. +revision = '15dd8689e7fe' +down_revision = '18ec55ca3e22' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + op.create_table('print_key', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('secret', sa.String(), nullable=True), + sa.Column('created', sa.DateTime(), nullable=True), + sa.Column('printer_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['printer_id'], ['printer.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('secret') + ) + + +def downgrade(): + op.drop_table('print_key') diff --git a/sirius/models/print_keys.py b/sirius/models/print_keys.py new file mode 100644 index 0000000..8a4ff83 --- /dev/null +++ b/sirius/models/print_keys.py @@ -0,0 +1,19 @@ +import datetime, random, string +from sirius.models.db import db + + +def generate_secret(): + return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(20)) + + +class PrintKey(db.Model): + """ + Keys uniquely identify a printer and include a secret so you can print to a + little printer by just embedding a secret in an URL. + """ + id = db.Column(db.Integer, primary_key=True) + secret = db.Column(db.String, default=generate_secret, unique=True) + created = db.Column(db.DateTime, default=datetime.datetime.utcnow) + + printer_id = db.Column(db.Integer, db.ForeignKey('printer.id')) + printer = db.relationship('Printer', backref=db.backref('print_keys', lazy='dynamic')) diff --git a/sirius/web/print_key_api.py b/sirius/web/print_key_api.py new file mode 100644 index 0000000..1f59010 --- /dev/null +++ b/sirius/web/print_key_api.py @@ -0,0 +1,81 @@ +import io +import datetime +import flask +from flask.ext import login +from flask import request +import flask_wtf +import wtforms +import base64 +import json +import cgi + +from sirius.models.db import db +from sirius.models import hardware +from sirius.models.print_keys import PrintKey +from sirius.models import messages as model_messages +from sirius.protocol import protocol_loop +from sirius.protocol import messages +from sirius.coding import image_encoding +from sirius.coding import templating +from sirius import stats + +blueprint = flask.Blueprint('print_key_api', __name__) + + +@blueprint.route('/printkey/', methods=['GET', 'POST']) +def print_with_print_key(print_key_secret): + print_key = PrintKey.query.filter(PrintKey.secret == print_key_secret).first() + if print_key is None: + flask.abort(404) + + printer = print_key.printer + if printer is None: + flask.abort(404) + + if request.method == 'GET': + printer_info = { + "name": printer.name, + "owner": printer.owner.username, + "status": 'online' if printer.is_online else 'offline' + } + + print request.accept_mimetypes + html_preference_score = request.accept_mimetypes.quality('text/html') + json_preference_score = request.accept_mimetypes.quality('application/json') + + if html_preference_score > json_preference_score: + return flask.render_template( + 'print_key.html', + printer=printer, + printer_info=printer_info, + print_key=print_key, + ) + else: + return json.dumps(printer_info), 200, {'content-type': 'application/json'} + else: + from_name = request.args.get('from') or 'Key ' + print_key_secret[0:4] + + + + if request.content_type == 'text/html': + html = request.get_data(as_text=True) + elif request.content_type.startswith('image/'): + data_uri = 'data:{type};base64,{data}'.format( + type=request.content_type, + data=base64.b64encode(request.data) + ) + html = '' + elif request.content_type.startswith('text/'): + # fallback for sending any text format + html = '
{text}
'.format( + text=cgi.escape(request.get_data(as_text=True)) + ) + else: + flask.abort(415) + + try: + printer.print_html(html, from_name=from_name) + except hardware.Printer.OfflineError: + return json.dumps({'status': 'failed-offline'}), 503, {'content-type': 'application/json'} + + return json.dumps({'status': 'sent'}), 200, {'content-type': 'application/json'} diff --git a/sirius/web/templates/print_key.html b/sirius/web/templates/print_key.html new file mode 100644 index 0000000..970e32c --- /dev/null +++ b/sirius/web/templates/print_key.html @@ -0,0 +1,106 @@ +{% extends "base.html" %} + +{% block title %}Print key | {{ printer.name }} | Little Printer{% endblock %} + +{% block page_content %} + +
+
+

🔑 You got a Print Key!

+ +

+ You can use this Print Key to print to {{ printer.owner.username }}'s Little Printer. +

+ + + + + + + + + + + + + + + + + + + + +
Printer{{ printer.name }}
Owned by{{ printer.owner.username }}
Status + {% if printer.is_online %} + Online + {% else %} + Offline + {% endif %} +
Print key{{print_key.secret}}
+
+
+ + + +

How do I actually use this?!

+ +

The easy way

+ +

+ Download our iOS app and paste the code ({{print_key.secret}}) in there. You'll be rattling selfies off in no time! +

+ +

The nerdy way

+ +

+ This URL also works as an API. You can POST data to it and it'll send it to the printer. +

+

+ You could do this from IFTTT, a Glitch app, your web app, or the command line. For example: +

+
curl '{{request.url}}?from=example' \
+    -H 'content-type: text/plain' \
+    -d 'boop beep boop'
+ +

HTML

+

+ Content-Type: text/html +

+

Renders and prints HTML. Surprisingly powerful! Supports HTML elements, CSS styling, and embedded images.

+
curl '{{request.url}}?from=htmlexample' \
+    -H 'content-type: text/html' \
+    -d "<h1>Yep, you can do this</h1><small>or this</small>"
+ +

+ Take care to set the Content-Type of the request. Supported types below: +

+ +

Images

+

+ Content-Type: image/png, + Content-Type: image/gif, + Content-Type: image/jpeg +

+

Prints out the image data from the request body, in a lovely dithered style.

+
cat mindblown.gif | curl {{request.url}}?from=image-example \
+    -X POST \
+    -H 'content-type: image/gif' \
+    --data-binary @-
+ +

Text

+

+ Content-Type: text/plain +

+

Prints out plain text.

+
curl '{{request.url}}?from=text-example' \
+    -H 'content-type: text/plain' \
+    -d "I'm a little teapot"
+{% endblock %} + +{% block scripts %} +{{ super() }} + + +{% endblock scripts %} diff --git a/sirius/web/templates/printer_print.html b/sirius/web/templates/printer_print.html index 2ea0687..2e08e05 100644 --- a/sirius/web/templates/printer_print.html +++ b/sirius/web/templates/printer_print.html @@ -1,6 +1,6 @@ {% extends "base.html" %} -{% block title %}Print{% endblock %} +{% block title %}Print | {{ printer.name }} | Little Printer{% endblock %} {% block page_content %}
diff --git a/sirius/web/webapp.py b/sirius/web/webapp.py index ae2beea..93d89bc 100644 --- a/sirius/web/webapp.py +++ b/sirius/web/webapp.py @@ -29,6 +29,7 @@ from sirius.web import admin from sirius.web import printer_print from sirius.web import printer_overview from sirius.web import external_api +from sirius.web import print_key_api logger = logging.getLogger(__name__) @@ -56,6 +57,7 @@ def create_app(config_name): app.register_blueprint(printer_print.blueprint) app.register_blueprint(external_api.blueprint) app.register_blueprint(admin.blueprint) + app.register_blueprint(print_key_api.blueprint) # Live interactions. gevent.spawn(protocol_loop.mark_dead_loop) -- 2.47.3