--- /dev/null
+"""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')
--- /dev/null
+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'))
--- /dev/null
+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/<print_key_secret>', 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 = '<img src="{uri}" style="width: 100%">'
+ elif request.content_type.startswith('text/'):
+ # fallback for sending any text format
+ html = '<div style="white-space: pre-wrap">{text}</div>'.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'}
--- /dev/null
+{% extends "base.html" %}
+
+{% block title %}Print key | {{ printer.name }} | Little Printer{% endblock %}
+
+{% block page_content %}
+<div class="hidden-xs" style="height: 3em"></div>
+<div class="row">
+ <div class="col-md-8">
+ <h1>🔑 You got a Print Key!</h1>
+
+ <p>
+ You can use this Print Key to print to {{ printer.owner.username }}'s Little Printer.
+ </p>
+
+ <table class="table">
+ <tbody>
+ <tr>
+ <td>Printer</td>
+ <td>{{ printer.name }}</td>
+ </tr>
+ <tr>
+ <td>Owned by</td>
+ <td>{{ printer.owner.username }}</td>
+ </tr>
+ <tr>
+ <td>Status</td>
+ <td>
+ {% if printer.is_online %}
+ <span class="label label-success">Online</span>
+ {% else %}
+ <span class="label label-default">Offline</span>
+ {% endif %}
+ </td>
+ </tr>
+ <tr>
+ <td>Print key</td>
+ <td><a href="{{request.url}}"><tt>{{print_key.secret}}</tt></a></td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+</div>
+
+<div class="hidden-xs" style="height: 2em"></div>
+
+<h2>How do I actually use this?!</h2>
+
+<h3>The easy way</h3>
+
+<p>
+ <a href="#">Download our iOS app</a> and paste the code (<tt>{{print_key.secret}}</tt>) in there. You'll be rattling selfies off in no time!
+</p>
+
+<h3>The nerdy way</h3>
+
+<p>
+ This URL also works as an API. You can POST data to it and it'll send it to the printer.
+</p>
+<p>
+ You could do this from IFTTT, a Glitch app, your web app, or the command line. For example:
+</p>
+<pre><code>curl '{{request.url}}?from=example' \
+ -H 'content-type: text/plain' \
+ -d 'boop beep boop'</code></pre>
+
+<h4>HTML</h4>
+<p>
+ <code>Content-Type: text/html</code>
+</p>
+<p>Renders and prints HTML. Surprisingly powerful! Supports HTML elements, CSS styling, and embedded images.</p>
+<pre><code>curl '{{request.url}}?from=htmlexample' \
+ -H 'content-type: text/html' \
+ -d "<h1>Yep, you can do this</h1><small>or this</small>"</code></pre>
+
+<p>
+ Take care to set the Content-Type of the request. Supported types below:
+</p>
+
+<h4>Images</h4>
+<p>
+ <code>Content-Type: image/png</code>,
+ <code>Content-Type: image/gif</code>,
+ <code>Content-Type: image/jpeg</code>
+</p>
+<p>Prints out the image data from the request body, in a lovely dithered style.</p>
+<pre><code>cat mindblown.gif | curl {{request.url}}?from=image-example \
+ -X POST \
+ -H 'content-type: image/gif' \
+ --data-binary @-</code></pre>
+
+<h4>Text</h4>
+<p>
+ <code>Content-Type: text/plain</code>
+</p>
+<p>Prints out plain text.</p>
+<pre><code>curl '{{request.url}}?from=text-example' \
+ -H 'content-type: text/plain' \
+ -d "I'm a little teapot"</code></pre>
+{% endblock %}
+
+{% block scripts %}
+{{ super() }}
+
+<script>
+</script>
+{% endblock scripts %}
{% extends "base.html" %}
-{% block title %}Print{% endblock %}
+{% block title %}Print | {{ printer.name }} | Little Printer{% endblock %}
{% block page_content %}
<div class="row">
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__)
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)