]> git.aero2k.de Git - sirius.git/commitdiff
Remember sent messages in a database model and show them on overview.
authorTom Hunger <tehunger@gmail.com>
Tue, 20 Jan 2015 14:25:48 +0000 (14:25 +0000)
committerTom Hunger <tehunger@gmail.com>
Tue, 20 Jan 2015 14:30:39 +0000 (14:30 +0000)
README.md
migrations/versions/d62b07987a2_sirius_models.py [moved from migrations/versions/3be2a0e43b88_sirius_models.py with 73% similarity]
sirius/models/hardware.py
sirius/models/messages.py [new file with mode: 0644]
sirius/web/printer_overview.py
sirius/web/printer_print.py
sirius/web/templates/printer_overview.html

index 649f8db90c9fd9de366bf6112e5f133d07f635b4..7edcc0e388518f622bf6e5f90633bca66cb44bc1 100644 (file)
--- a/README.md
+++ b/README.md
@@ -81,3 +81,10 @@ We are also deriving this hardware xor when a device calls home with
 an "encryption_key_required". In that case we connect the device to
 the claim code via the hardware-xor and send back the correct
 encryption key.
+
+
+## TODO
+
+* Can't read images from the net because we're rendering a local file
+  with phantomjs. The way to fix is probably to run an in-process
+  web-server for the duration of rendering (urg).
similarity index 73%
rename from migrations/versions/3be2a0e43b88_sirius_models.py
rename to migrations/versions/d62b07987a2_sirius_models.py
index 07a645c2d3bad9d1f44df4a8373915ae6006360f..f632efd9007eaf0d81494a9494a6323427da5a41 100644 (file)
@@ -1,13 +1,13 @@
 """Sirius models.
 
-Revision ID: 3be2a0e43b88
+Revision ID: d62b07987a2
 Revises: None
-Create Date: 2015-01-15 15:33:10.629707
+Create Date: 2015-01-20 14:24:56.114106
 
 """
 
 # revision identifiers, used by Alembic.
-revision = '3be2a0e43b88'
+revision = 'd62b07987a2'
 down_revision = None
 
 from alembic import op
@@ -16,17 +16,11 @@ import sqlalchemy as sa
 
 def upgrade():
     ### commands auto generated by Alembic - please adjust! ###
-    op.create_table('user',
-    sa.Column('id', sa.Integer(), nullable=False),
-    sa.Column('created', sa.DateTime(), nullable=True),
-    sa.Column('username', sa.String(), nullable=True),
-    sa.PrimaryKeyConstraint('id')
-    )
     op.create_table('bridge',
     sa.Column('id', sa.Integer(), nullable=False),
     sa.Column('created', sa.DateTime(), nullable=True),
-    sa.Column('bridge_address', sa.String(), nullable=False),
-    sa.PrimaryKeyConstraint('id', 'bridge_address')
+    sa.Column('bridge_address', sa.String(), nullable=True),
+    sa.PrimaryKeyConstraint('id')
     )
     op.create_table('device_log',
     sa.Column('id', sa.Integer(), nullable=False),
@@ -35,6 +29,23 @@ def upgrade():
     sa.Column('entry', sa.String(), nullable=True),
     sa.PrimaryKeyConstraint('id')
     )
+    op.create_table('user',
+    sa.Column('id', sa.Integer(), nullable=False),
+    sa.Column('created', sa.DateTime(), nullable=True),
+    sa.Column('username', sa.String(), nullable=True),
+    sa.PrimaryKeyConstraint('id')
+    )
+    op.create_table('twitter_o_auth',
+    sa.Column('id', sa.Integer(), nullable=False),
+    sa.Column('created', sa.DateTime(), nullable=True),
+    sa.Column('user_id', sa.Integer(), nullable=True),
+    sa.Column('screen_name', sa.String(), nullable=True),
+    sa.Column('token', sa.String(), nullable=True),
+    sa.ForeignKeyConstraint(['user_id'], [u'user.id'], ),
+    sa.PrimaryKeyConstraint('id'),
+    sa.UniqueConstraint('screen_name'),
+    sa.UniqueConstraint('token')
+    )
     op.create_table('printer',
     sa.Column('id', sa.Integer(), nullable=False),
     sa.Column('created', sa.DateTime(), nullable=True),
@@ -56,26 +67,30 @@ def upgrade():
     sa.ForeignKeyConstraint(['by_id'], ['user.id'], ),
     sa.PrimaryKeyConstraint('id')
     )
-    op.create_table('twitter_o_auth',
+    op.create_table('message',
     sa.Column('id', sa.Integer(), nullable=False),
     sa.Column('created', sa.DateTime(), nullable=True),
-    sa.Column('user_id', sa.Integer(), nullable=True),
-    sa.Column('screen_name', sa.String(), nullable=True),
-    sa.Column('token', sa.String(), nullable=True),
-    sa.ForeignKeyConstraint(['user_id'], [u'user.id'], ),
-    sa.PrimaryKeyConstraint('id'),
-    sa.UniqueConstraint('screen_name'),
-    sa.UniqueConstraint('token')
+    sa.Column('pixels', sa.LargeBinary(), nullable=True),
+    sa.Column('sender_id', sa.Integer(), nullable=True),
+    sa.Column('target_printer_id', sa.Integer(), nullable=True),
+    sa.Column('response_timestamp', sa.DateTime(), nullable=True),
+    sa.Column('failure_message', sa.String(), nullable=True),
+    sa.ForeignKeyConstraint(['sender_id'], ['user.id'], ),
+    sa.ForeignKeyConstraint(['target_printer_id'], ['printer.id'], ),
+    sa.PrimaryKeyConstraint('id')
     )
+    op.create_index(op.f('ix_message_created'), 'message', ['created'], unique=False)
     ### end Alembic commands ###
 
 
 def downgrade():
     ### commands auto generated by Alembic - please adjust! ###
-    op.drop_table('twitter_o_auth')
+    op.drop_index(op.f('ix_message_created'), table_name='message')
+    op.drop_table('message')
     op.drop_table('claim_code')
     op.drop_table('printer')
+    op.drop_table('twitter_o_auth')
+    op.drop_table('user')
     op.drop_table('device_log')
     op.drop_table('bridge')
-    op.drop_table('user')
     ### end Alembic commands ###
index dd1b486ece925251701c0d36b2ab8573b4ab359b..2ba0f04a7bfe2b4e9b007aeae0065dee6f64c594 100644 (file)
@@ -11,7 +11,7 @@ class Bridge(db.Model):
     """
     id = db.Column(db.Integer, primary_key=True)
     created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
-    bridge_address = db.Column(db.String, primary_key=True)
+    bridge_address = db.Column(db.String)
 
 
 class Printer(db.Model):
diff --git a/sirius/models/messages.py b/sirius/models/messages.py
new file mode 100644 (file)
index 0000000..18b4f3e
--- /dev/null
@@ -0,0 +1,54 @@
+import base64
+import datetime
+
+from sirius.models.db import db
+from sirius.models import hardware
+from sirius.models import user
+
+
+TIMEOUT_SECONDS = 60
+
+class Message(db.Model):
+    """Messages are printed by someone on ("sender") to a "target
+    printer".
+    """
+    id = db.Column(db.Integer, primary_key=True)
+    created = db.Column(db.DateTime, default=datetime.datetime.utcnow, index=True)
+    pixels = db.Column(db.LargeBinary)
+
+    sender_id = db.Column(db.Integer, db.ForeignKey('user.id'))
+    sender = db.relationship('User', backref=db.backref('messages', lazy='dynamic'))
+
+    target_printer_id = db.Column(db.Integer, db.ForeignKey('printer.id'))
+    target_printer = db.relationship('Printer', backref=db.backref('messages', lazy='dynamic'))
+
+    # The response is received by the protocol_loop. It's also
+    # possible to not receive a response (e.g. printer got
+    # disconnected) in which case we "time out" after TIMEOUT_SECONDS.
+    response_timestamp = db.Column(db.DateTime, nullable=True)
+    failure_message = db.Column(db.String, nullable=True)
+
+
+    @classmethod
+    def timeout_updates(cls, utcnow=None):
+        """Update all messages that are timed-out with an error message. This
+        is a destructive update. It should also be fairly cheap
+        because of the index on created.
+
+        We're doing these updates "eagerly" on every printer overview
+        page load instead of through a cron job, but there's no reason
+        why we couldn't do that.
+        """
+
+        if utcnow is None:
+            utcnow = datetime.datetime.utcnow()
+        cutoff = utcnow - datetime.timedelta(seconds=TIMEOUT_SECONDS)
+
+        cls.query.filter(cls.created <= cutoff).update(dict(
+            response_timestamp=utcnow,
+            failure_message="Timed out",
+        ))
+
+
+    def base64_pixels(self):
+        return base64.b64encode(self.pixels)
index 5383c31f359882425bf926d180fcd3756d27e5ba..eb557ade0400aa4dffb0b6139d126aa468ce02d7 100644 (file)
@@ -1,7 +1,9 @@
 import flask
 from flask.ext import login
+from sqlalchemy import desc
 
 from sirius.models import hardware
+from sirius.models import messages
 
 blueprint = flask.Blueprint('printer_overview', __name__)
 
@@ -16,7 +18,12 @@ def printer_overview(user_id, username, printer_id):
     if printer is None:
         flask.abort(404)
 
+    messages.Message.timeout_updates()
+    message_list = login.current_user.messages.order_by(desc('created'))
+
+    # TODO - pagination?
     return flask.render_template(
         'printer_overview.html',
         printer=printer,
+        messages=message_list[:10],
     )
index e7e1b4bbfbc8286c39f67b8ec8f92f94cc0f4fba..657e7c0cc8d844d47db01d5f2dd81a023b00f427 100644 (file)
@@ -3,11 +3,14 @@ from flask.ext import login
 import flask_wtf
 import wtforms
 
+from sirius.models.db import db
 from sirius.models import hardware
+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
 
+
 blueprint = flask.Blueprint('printer_print', __name__)
 
 
@@ -50,6 +53,18 @@ def printer_print(user_id, username, printer_id):
             device_address=printer.device_address,
             pixels=pixels,
         )
+
+        # Store the same message in the model.
+        model_message = model_messages.Message(
+            pixels=bytearray(pixels),
+            sender_id=login.current_user.id,
+            target_printer=printer,
+        )
+        db.session.add(model_message)
+
+        # Note that we don't really handle the case of a disconnected
+        # printer yet. It f the printer isn't connected we'll silently
+        # swallow the message.
         protocol_loop.send_message(printer.device_address, hardware_message)
 
         return flask.redirect(flask.url_for(
index dae4ba52717296d345cb222b43319aadb0401caf..631b47b7c8cdb326f034c4639b74330b8398041a 100644 (file)
        Print a thing
 </a>
 <h2>Messages</h2>
+{% for m in messages %}
+<div>
+       <b>From:</b> {{ m.sender.username }}. <b>Printer:</b> {{ m.target_printer.name }}.<br>
+       <b>Sent:</b>
+       {% if m.response_timestamp == None %}
+       .. still sending ..
+       {% elif m.failure_message == None %}
+       {{ m.response_timestamp.strftime('%d/%m/%Y %H:%M') }}
+       {% else %}
+       <b style="color: red;">{{ m.failure_message }}</b> at {{ m.response_timestamp.strftime('%d/%m/%Y %H:%M') }}
+       {% endif %}
+</div>
+<div style="margin-bottom: 30px;">
+       <img src="data:image/png;base64,{{ m.base64_pixels() }}" style="border: 1px solid black;width: 6cm;"><br>
+</div>
+
+{% endfor %}
 {% endblock %}