]> git.aero2k.de Git - sirius.git/commitdiff
Refactor 'print' function onto model object and prepare for key API
authorJoe Rickerby <joerick@mac.com>
Wed, 10 Jan 2018 16:59:08 +0000 (16:59 +0000)
committerJoe Rickerby <joerick@mac.com>
Wed, 10 Jan 2018 16:59:08 +0000 (16:59 +0000)
'Sender' of the message models changes to sender_name, since users of
the printkey api won't have accounts here

migrations/versions/18ec55ca3e22_sender_name.py [new file with mode: 0644]
sirius/models/hardware.py
sirius/models/messages.py
sirius/web/printer_print.py
sirius/web/templates/printer_overview.html

diff --git a/migrations/versions/18ec55ca3e22_sender_name.py b/migrations/versions/18ec55ca3e22_sender_name.py
new file mode 100644 (file)
index 0000000..714e773
--- /dev/null
@@ -0,0 +1,24 @@
+"""empty message
+
+Revision ID: 18ec55ca3e22
+Revises: 36ba0c7b9fbc
+Create Date: 2018-01-10 16:50:07.468905
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '18ec55ca3e22'
+down_revision = '36ba0c7b9fbc'
+
+from alembic import op
+import sqlalchemy as sa
+
+
+def upgrade():
+    op.add_column('message', sa.Column('sender_name', sa.String(), nullable=True))
+    op.drop_column('message', 'sender_id')
+
+
+def downgrade():
+    op.add_column('message', sa.Column('sender_id', sa.INTEGER(), autoincrement=False, nullable=True))
+    op.drop_column('message', 'sender_name')
index ad112a4fe5049999939996c252d67a8445966b79..4d41a26b457e27eb0fb7e1b2836036482440ff9d 100644 (file)
@@ -1,4 +1,4 @@
-import datetime
+import datetime, io
 from sqlalchemy import desc
 
 from sirius.coding import bitshuffle
@@ -94,6 +94,64 @@ class Printer(db.Model):
         from sirius.protocol import protocol_loop
         return protocol_loop.device_is_online(self.device_address)
 
+    class OfflineError(Exception):
+        pass
+
+    def print_html(self, html, from_name, face='default'):
+        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
+        from sirius.models import messages as model_messages
+
+        pixels = image_encoding.default_pipeline(
+            templating.default_template(html, from_name=from_name)
+        )
+
+        hardware_message = None
+        if face == "noface":
+            hardware_message = messages.SetDeliveryAndPrintNoFace(
+                device_address=self.device_address,
+                pixels=pixels,
+            )
+        else:
+            hardware_message = messages.SetDeliveryAndPrint(
+                device_address=self.device_address,
+                pixels=pixels,
+            )
+
+        # If a printer is "offline" then we won't find the printer
+        # connected and success will be false.
+        success, next_print_id = protocol_loop.send_message(
+            self.device_address,
+            hardware_message
+        )
+
+        if success:
+            stats.inc('printer.print.ok')
+        else:
+            stats.inc('printer.print.offline')
+
+        # Store the same message in the database.
+        png = io.BytesIO()
+        pixels.save(png, "PNG")
+        model_message = model_messages.Message(
+            print_id=next_print_id,
+            pixels=bytearray(png.getvalue()),
+            sender_name=from_name,
+            target_printer=self,
+        )
+
+        # We know immediately if the printer wasn't online.
+        if not success:
+            model_message.failure_message = 'Printer offline'
+            model_message.response_timestamp = datetime.datetime.utcnow()
+        db.session.add(model_message)
+
+        if not success:
+            raise OfflineError()
+
 
 class ClaimCode(db.Model):
     """Printer and claim codes are joined over the hardware xor. Claim
index 1697ea0670e9b62db452ffa1aa16acefff70e6b9..2778726bb12c8c1ba0825d9cbbe511f328997c58 100644 (file)
@@ -21,8 +21,7 @@ class Message(db.Model):
 
     print_id = db.Column(db.Integer, unique=True)
 
-    sender_id = db.Column(db.Integer, db.ForeignKey('user.id'))
-    sender = db.relationship('User', backref=db.backref('messages', lazy='dynamic'))
+    sender_name = db.Column(db.String)
 
     target_printer_id = db.Column(db.Integer, db.ForeignKey('printer.id'))
     target_printer = db.relationship('Printer', backref=db.backref('messages', lazy='dynamic'))
index a768cad789ab0e51cd8b027ce5657e26eb8727e7..8f47a2fd3edc0fc70182fe9c5c6c723baa07280b 100644 (file)
@@ -73,52 +73,17 @@ def printer_print(printer_id):
         form.face.data = "default"
 
     if form.validate_on_submit():
-        # TODO: move image encoding into a pthread.
-        # TODO: use templating to avoid injection attacks
-        pixels = image_encoding.default_pipeline(
-            templating.default_template(form.message.data, from_name=login.current_user.username))
-
-        hardware_message = None
-        if form.face.data == "noface":
-            hardware_message = messages.SetDeliveryAndPrintNoFace(
-                device_address=printer.device_address,
-                pixels=pixels,
+        try:
+            printer.print_html(
+                html=form.message.data, 
+                from_name='@'+login.current_user.username
             )
-        else:
-            hardware_message = messages.SetDeliveryAndPrint(
-                device_address=printer.device_address,
-                pixels=pixels,
-            )
-
-        # If a printer is "offline" then we won't find the printer
-        # connected and success will be false.
-        success, next_print_id = protocol_loop.send_message(
-            printer.device_address, hardware_message)
-
-        if success:
             flask.flash('Sent your message to the printer!')
-            stats.inc('printer.print.ok')
-        else:
-            flask.flash(("Could not send message because the "
-                         "printer {} is offline.").format(printer.name),
-                        'error')
-            stats.inc('printer.print.offline')
-
-        # Store the same message in the database.
-        png = io.BytesIO()
-        pixels.save(png, "PNG")
-        model_message = model_messages.Message(
-            print_id=next_print_id,
-            pixels=bytearray(png.getvalue()),
-            sender_id=login.current_user.id,
-            target_printer=printer,
-        )
-
-        # We know immediately if the printer wasn't online.
-        if not success:
-            model_message.failure_message = 'Printer offline'
-            model_message.response_timestamp = datetime.datetime.utcnow()
-        db.session.add(model_message)
+        except hardware.Printer.OfflineError:
+            flask.flash(
+                "Could not send message because the printer {} is offline.".format(printer.name),
+                'error'
+            )
 
         return flask.redirect(flask.url_for(
             'printer_overview.printer_overview',
index 53dc297d280f5c98c405d6d332cd082917881397..55d51ae732d8a283c12c361bfff83e3ba3f22598 100644 (file)
@@ -32,7 +32,7 @@
                        <img src="data:image/png;base64,{{ m.base64_pixels() }}" style="border: 1px solid #ccc; width: 100%;">
                        <div class="caption">
                        <p>
-                       From @{{ m.sender.username }} at
+                       From {{ m.sender_name }} at
                        {% if m.response_timestamp == None %}
                        <span class="bg-info">(still sending)</span>
                        {% else %}