the twitter api is becoming prohibitive to use so removing friends reduces dependency
BREAKING CHANGE:
These can be set in the `.env` file, and an example is available in `.env.sample` in your checkout.
-### Creating fake printers and friends
+### Creating fake printers
Resetting the actual hardware all the time gets a bit tiresome so
there's a fake command that creates unclaimed fake little printers:
Functionally there is no difference between resetting and creating a new printer so we don't distinguish between the two.
-To create a fake friend from twitter who signed up do this:
-
-```console
-$ ./manage.py fake user stephenfry
-```
-
-You can also claim a printer in somebody else's name:
-
-```console
-$ ./manage.py fake claim b7235a2b432585eb quentinsf 342f-eyh0-korc-msej testprinter
-```
-
## Sirius Architecture
### Layers
--- /dev/null
+"""Remove friends
+
+Revision ID: 89a031bd9657
+Revises: 44c4368c2db1
+Create Date: 2023-07-04 18:44:13.041005
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = "89a031bd9657"
+down_revision = "44c4368c2db1"
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+
+def upgrade():
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.create_unique_constraint(None, "claim_code", ["claim_code"])
+ op.create_foreign_key(None, "print_key", "print_key", ["parent_id"], ["id"])
+ op.create_unique_constraint(None, "printer", ["used_claim_code"])
+ op.drop_column("twitter_o_auth", "last_friend_refresh")
+ op.drop_column("twitter_o_auth", "friends")
+ # ### end Alembic commands ###
+
+
+def downgrade():
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.add_column(
+ "twitter_o_auth",
+ sa.Column("friends", postgresql.BYTEA(), autoincrement=False, nullable=True),
+ )
+ op.add_column(
+ "twitter_o_auth",
+ sa.Column(
+ "last_friend_refresh",
+ postgresql.TIMESTAMP(),
+ autoincrement=False,
+ nullable=True,
+ ),
+ )
+ op.drop_constraint(None, "printer", type_="unique")
+ op.drop_constraint(None, "print_key", type_="foreignkey")
+ op.drop_constraint(None, "claim_code", type_="unique")
+ # ### end Alembic commands ###
from sirius.models import hardware
-class CannotChangeOwner(Exception): pass
-class ClaimCodeInUse(Exception): pass
+class CannotChangeOwner(Exception):
+ pass
+
+
+class ClaimCodeInUse(Exception):
+ pass
class User(db.Model):
# providers. For now we just copy the twitter handle.
username = db.Column(db.String)
twitter_oauth = db.relationship(
- 'TwitterOAuth', uselist=False, backref=db.backref('user'))
+ "TwitterOAuth", uselist=False, backref=db.backref("user")
+ )
def __repr__(self):
- return 'User {}'.format(self.username)
+ return "User {}".format(self.username)
# Flask-login interface:
@property
return self.id
def generate_api_key(self):
- self.api_key = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(32))
+ self.api_key = "".join(
+ random.choice(string.ascii_letters + string.digits) for _ in range(32)
+ )
def claim_printer(self, claim_code, name):
"""Claiming can happen before the printer "calls home" for the first
if hcc is not None and hcc.by != self:
raise ClaimCodeInUse(
- "Claim code {} already claimed by {}".format(
- claim_code, hcc.by))
+ "Claim code {} already claimed by {}".format(claim_code, hcc.by)
+ )
if hcc is None:
hcc = hardware.ClaimCode(
# Check whether we've seen this printer and if so: connect it
# to claim code and make it "owned" but *only* if it does not
# have an owner yet.
- printer_query = hardware.Printer.query.filter_by(
- hardware_xor=hardware_xor)
+ printer_query = hardware.Printer.query.filter_by(hardware_xor=hardware_xor)
printer = printer_query.first()
if printer is None:
return
if printer.owner is not None and printer.owner != self:
raise CannotChangeOwner(
"Printer {} already owned by {}. Cannot claim for {}.".format(
- printer, printer.owner, self))
+ printer, printer.owner, self
+ )
+ )
- assert printer_query.count() == 1, \
- "hardware xor collision: {}".format(hardware_xor)
+ assert printer_query.count() == 1, "hardware xor collision: {}".format(
+ hardware_xor
+ )
printer.used_claim_code = claim_code
printer.hardware_xor = hardware_xor
db.session.add(printer)
return printer
- def signed_up_friends(self):
- """
- A "friend" is someone this user follows on twitter.
-
- :returns: 2-tuple of (all friends, list of people who can print on
- this user's printer)
- """
- friends = self.twitter_oauth.friends
- if not friends:
- return [], []
- return friends, User.query.filter(
- User.username.in_(x.screen_name for x in friends))
-
- def friends_printers(self):
- """
- :returns: List of printers this user can print on.
- """
- # TODO(tom): Querying the full database is O(N) and will not
- # scale. Replace the model with a N:M relationship.
- sn = self.twitter_oauth.screen_name
- reverse_friend_ids = [
- x.user_id for x in TwitterOAuth.query.all()
- for y in (x.friends or [])
- if sn == y.screen_name]
-
- # Avoid expensive sql by checking for list.
- if not reverse_friend_ids:
- return []
-
- return hardware.Printer.query.filter(
- hardware.Printer.owner_id.in_(reverse_friend_ids))
-
-
-Friend = collections.namedtuple('Friend', 'screen_name name profile_image_url')
class TwitterOAuth(db.Model):
id = db.Column(db.Integer, primary_key=True)
token = db.Column(db.String)
token_secret = db.Column(db.String)
-
- # Twitter comes with a 15 requests / 15 minutes rate. To avoid
- # people DOS'ing our service we allow only one refresh per hour.
- last_friend_refresh = db.Column(db.DateTime)
-
- # List of Friend objects (see named tuple above this class)
- friends = db.Column(db.PickleType())
-
- def seconds_to_next_refresh(self, utcnow=None):
- if utcnow is None:
- utcnow = datetime.datetime.utcnow()
-
- if self.last_friend_refresh is None:
- return 0
-
- seconds_since_refresh = (
- utcnow - self.last_friend_refresh
- ).total_seconds() - 3600
-
- return abs(min(seconds_since_refresh, 0))
# pylint: disable=no-member
class Base(testing.TestCase):
- """Common base class for tests that require database interactions.
- """
+ """Common base class for tests that require database interactions."""
def create_app(self):
- app = webapp.create_app('test')
+ app = webapp.create_app("test")
return app
def setUp(self):
self.testuser = user.User(
username="testuser",
twitter_oauth=user.TwitterOAuth(
- screen_name='testuser',
- friends=[],
+ screen_name="testuser",
token="token",
token_secret="token_secret",
- )
+ ),
)
db.session.add(self.testuser)
db.session.flush()
# Flask session doesn't pick up the cookies if I call just
# login_user. The login_user call needs to be embedded in a
# request.
- @self.app.route('/autologin')
+ @self.app.route("/autologin")
def autologin():
login.login_user(self.testuser)
- return ''
+ return ""
- self.client.get('/autologin')
+ self.client.get("/autologin")
import io
import datetime
+import json
+
import flask
import flask_login as login
from flask import request
-import flask_wtf
-import wtforms
-import base64
-import json
from sirius.models.db import db
from sirius.models import hardware
from sirius.protocol import messages
from sirius.coding import image_encoding
from sirius.coding import templating
-from sirius import stats
-blueprint = flask.Blueprint('external_api', __name__)
+blueprint = flask.Blueprint("external_api", __name__)
+
# TODO : need a refactor as this is code duplication from printer_print
-@blueprint.route('/ext_api/v1/printer/<int:printer_id>/print_html', methods=['POST'])
+@blueprint.route("/ext_api/v1/printer/<int:printer_id>/print_html", methods=["POST"])
@login.login_required
def print_html(printer_id):
printer = hardware.Printer.query.get(printer_id)
flask.abort(404)
# PERMISSIONS
- # the printer must either belong to this user, or be
- # owned by a friend
+ # the printer must either belong to this user
if printer.owner.id == login.current_user.id:
# fine
pass
- elif printer.id in [p.id for p in login.current_user.friends_printers()]:
- # fine
- pass
else:
flask.abort(404)
request.get_data()
task = json.loads(request.data)
- if not task['message'] or not task['face']:
+ if not task["message"] or not task["face"]:
flask.abort(500)
pixels = image_encoding.default_pipeline(
templating.default_template(
- task['message'],
- from_name=login.current_user.username
+ task["message"], from_name=login.current_user.username
)
)
hardware_message = None
- if task['face'] == "noface":
+ if task["face"] == "noface":
hardware_message = messages.SetDeliveryAndPrintNoFace(
device_address=printer.device_address,
pixels=pixels,
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)
+ printer.device_address, hardware_message
+ )
# Store the same message in the database.
png = io.BytesIO()
# We know immediately if the printer wasn't online.
if not success:
- model_message.failure_message = 'Printer offline'
+ model_message.failure_message = "Printer offline"
model_message.response_timestamp = datetime.datetime.utcnow()
db.session.add(model_message)
response = {}
if success:
- response['status'] = 'Sent your message to the printer!'
+ response["status"] = "Sent your message to the printer!"
else:
- response['status'] = ("Could not send message because the "
- "printer {} is offline.").format(printer.name)
+ response["status"] = (
+ "Could not send message because the " "printer {} is offline."
+ ).format(printer.name)
return json.dumps(response)
import flask_wtf
import wtforms
import flask_login as login
-import datetime
from sirius.coding import claiming
-from sirius.web import twitter
-blueprint = flask.Blueprint('landing', __name__)
+blueprint = flask.Blueprint("landing", __name__)
class ClaimForm(flask_wtf.FlaskForm):
claim_code = wtforms.StringField(
- 'Claim code',
+ "Claim code",
validators=[wtforms.validators.DataRequired()],
)
printer_name = wtforms.StringField(
- 'Name your printer',
+ "Name your printer",
validators=[wtforms.validators.DataRequired()],
)
)
-class TwitterRefreshFriendsForm(flask_wtf.FlaskForm):
- "CSRF-only form."
-
-@blueprint.route('/about')
+@blueprint.route("/about")
def about():
- return flask.render_template('about.html')
+ return flask.render_template("about.html")
+
-@blueprint.route('/')
+@blueprint.route("/")
def landing():
if not login.current_user.is_authenticated:
- return flask.render_template('landing.html')
+ return flask.render_template("landing.html")
return overview()
user = login.current_user
my_printers = user.printers.all()
- friends, signed_up_friends = user.signed_up_friends()
- form = TwitterRefreshFriendsForm()
+ return flask.render_template("overview.html", my_printers=my_printers)
- friends_printers = user.friends_printers()
-
- return flask.render_template(
- 'overview.html',
- form=form,
- my_printers=my_printers,
- signed_up_friends=list(signed_up_friends),
- friends=friends,
- friends_printers=list(friends_printers),
- seconds_to_next_refresh=user.twitter_oauth.seconds_to_next_refresh(),
- last_friend_refresh=user.twitter_oauth.last_friend_refresh,
- )
-
-@blueprint.route('/<int:user_id>/<username>/claim', methods=['GET', 'POST'])
+@blueprint.route("/<int:user_id>/<username>/claim", methods=["GET", "POST"])
@login.login_required
def claim(user_id, username):
user = login.current_user
form = ClaimForm()
if form.validate_on_submit():
- user.claim_printer(
- form.claim_code.data,
- form.printer_name.data)
- return flask.redirect(flask.url_for('.landing'))
-
- return flask.render_template(
- 'claim.html',
- form=form,
- )
+ user.claim_printer(form.claim_code.data, form.printer_name.data)
+ return flask.redirect(flask.url_for(".landing"))
+
+ return flask.render_template("claim.html", form=form)
-@blueprint.route('/<int:user_id>/<username>/generate_api_key', methods=['POST'])
+
+@blueprint.route("/<int:user_id>/<username>/generate_api_key", methods=["POST"])
@login.login_required
def generate_api_key(user_id, username):
user = login.current_user
assert username == user.username
user.generate_api_key()
- return flask.redirect(flask.url_for('.landing'))
-
-@blueprint.route('/<int:user_id>/<username>/twitter-friend-refresh', methods=['POST'])
-@login.login_required
-def twitter_friend_refresh(user_id, username):
- user = login.current_user
- assert user_id == login.current_user.get_id()
- assert username == login.current_user.username
-
- assert user.twitter_oauth.seconds_to_next_refresh() == 0
-
- # TODO error handling when hitting twitter rate limit ...
- login.current_user.twitter_oauth.friends = twitter.get_friends(login.current_user)
- login.current_user.twitter_oauth.last_friend_refresh = datetime.datetime.utcnow()
-
- return flask.redirect(flask.url_for('.landing'))
+ return flask.redirect(flask.url_for(".landing"))
import io
-import datetime
+import base64
+
import flask
import flask_login as login
import flask_wtf
import wtforms
-import base64
-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
from sirius.coding import templating
from sirius import stats
-blueprint = flask.Blueprint('printer_print', __name__)
+blueprint = flask.Blueprint("printer_print", __name__)
class PrintForm(flask_wtf.FlaskForm):
target_printer = wtforms.SelectField(
- 'Printer',
+ "Printer",
coerce=int,
validators=[wtforms.validators.DataRequired()],
)
face = wtforms.SelectField(
- 'Face',
+ "Face",
coerce=str,
validators=[wtforms.validators.DataRequired()],
)
message = wtforms.TextAreaField(
- 'Message',
+ "Message",
validators=[wtforms.validators.DataRequired()],
)
@login.login_required
-@blueprint.route('/printer/<int:printer_id>/print', methods=['GET', 'POST'])
+@blueprint.route("/printer/<int:printer_id>/print", methods=["GET", "POST"])
def printer_print(printer_id):
printer = hardware.Printer.query.get(printer_id)
if printer is None:
flask.abort(404)
# PERMISSIONS
- # the printer must either belong to this user, or be
- # owned by a friend
+ # the printer must either belong to this user
if printer.owner.id == login.current_user.id:
# fine
pass
- elif printer.id in [p.id for p in login.current_user.friends_printers()]:
- # fine
- pass
else:
flask.abort(404)
form = PrintForm()
# Note that the form enforces access permissions: People can't
- # submit a valid printer-id that's not owned by the user or one of
- # the user's friends.
- choices = [
- (x.id, x.name) for x in login.current_user.printers
- ] + [
- (x.id, x.name) for x in login.current_user.friends_printers()
- ]
+ # submit a valid printer-id that's not owned by the user.
+ choices = [(x.id, x.name) for x in login.current_user.printers]
form.target_printer.choices = choices
form.face.choices = [("default", "Default face"), ("noface", "No face")]
# Set default printer on get
- if flask.request.method != 'POST':
+ if flask.request.method != "POST":
form.target_printer.data = printer.id
form.face.data = "default"
if form.validate_on_submit():
try:
printer.print_html(
- html=form.message.data,
- from_name='@'+login.current_user.username
+ html=form.message.data,
+ from_name="@" + login.current_user.username,
)
- flask.flash('Sent your message to the printer!')
+ flask.flash("Sent your message to the printer!")
except hardware.Printer.OfflineError:
flask.flash(
- "Could not send message because the printer {} is offline.".format(printer.name),
- 'error'
+ "Could not send message because the printer {} is offline.".format(
+ printer.name
+ ),
+ "error",
)
- return flask.redirect(flask.url_for(
- 'printer_overview.printer_overview',
- printer_id=printer.id))
+ return flask.redirect(
+ flask.url_for("printer_overview.printer_overview", printer_id=printer.id)
+ )
return flask.render_template(
- 'printer_print.html',
+ "printer_print.html",
printer=printer,
form=form,
)
-@blueprint.route('/<int:user_id>/<username>/printer/<int:printer_id>/preview', methods=['POST'])
+@blueprint.route(
+ "/<int:user_id>/<username>/printer/<int:printer_id>/preview", methods=["POST"]
+)
@login.login_required
def preview(user_id, username, printer_id):
assert user_id == login.current_user.id
assert username == login.current_user.username
- message = flask.request.data.decode('utf-8')
+ message = flask.request.data.decode("utf-8")
pixels = image_encoding.default_pipeline(
- templating.default_template(message, from_name=login.current_user.username))
+ templating.default_template(message, from_name=login.current_user.username)
+ )
png = io.BytesIO()
pixels.save(png, "PNG")
- stats.inc('printer.preview')
+ stats.inc("printer.preview")
- return '<img style="width: 100%;" src="data:image/png;base64,{}">'.format(base64.b64encode(png.getvalue()).decode('utf-8'))
+ return '<img style="width: 100%;" src="data:image/png;base64,{}">'.format(
+ base64.b64encode(png.getvalue()).decode("utf-8")
+ )
+++ /dev/null
-from sirius.models.db import db
-from sirius.models import user
-from sirius.models import hardware
-from sirius.testing import base
-
-
-# pylint: disable=no-member
-class TestFriends(base.Base):
-
- def setUp(self):
- base.Base.setUp(self)
- db.create_all()
- u0 = user.User(username='u0')
- u1 = user.User(username='u1')
- oa0 = user.TwitterOAuth(
- user=u0,
- screen_name='twitter0',
- token='token',
- token_secret='token_secret',
- friends=[user.Friend('twitter1', 't1', ''), user.Friend('twitter2', 't2', '')],
- )
- oa1 = user.TwitterOAuth(
- user=u1,
- screen_name='twitter1',
- token='token',
- token_secret='token_secret',
- friends=[user.Friend('twitter2', 't2', '')],
- )
- db.session.add_all([u0, u1, oa0, oa1])
- db.session.commit()
- self.u0 = u0
- self.u1 = u1
-
- # Register a printer for user so we can test friends printers
- u0.claim_printer('vcty-8s95-40hq-6k1z', 'u0 printer')
- hardware.Printer.phone_home('dd5ebbcce362f584')
-
- u1.claim_printer('pmo0-bjf1-ste8-51c1', 'u1 printer')
- hardware.Printer.phone_home('35fef3793dce4692')
-
-
- def tearDown(self):
- db.session.remove()
- db.drop_all()
-
-
- def test_signed_up_friends(self):
- f0, _ = self.u0.signed_up_friends()
- f1, _ = self.u1.signed_up_friends()
-
- self.assertCountEqual(f0, [
- user.Friend('twitter1', 't1', ''),
- user.Friend('twitter2', 't2', '')])
-
- self.assertCountEqual(f1, [
- user.Friend('twitter2', 't2', '')])
-
-
- def test_friends_printers(self):
- fp0 = list(self.u0.friends_printers())
- fp1 = list(self.u1.friends_printers())
- # u0 follows u1 but the reverse is not true. That means u1
- # should be able to print on u0's printer but u0 should not be
- # able to print on u1's printer
- self.assertEqual(len(fp0), 0)
- self.assertEqual(len(fp1), 1)
-
- self.assertEqual(fp1[0].name, 'u0 printer')
from sirius.web import twitter
-# Mock network-accessing function:
-twitter.get_friends = lambda x: []
-
-
# pylint: disable=no-member
class TestOAuthFlow(testing.TestCase):
def setUp(self):
db.drop_all()
def create_app(self):
- app = webapp.create_app('test')
+ app = webapp.create_app("test")
return app
def test_oauth_authorized(self):
self.assertEqual(login.current_user.is_authenticated, False)
twitter.process_authorization(
- 'token',
- 'secret_token',
- 'test_screen_name',
- '/next_url',
+ "token",
+ "/next_url",
)
- self.assertEqual(login.current_user.username, 'test_screen_name')
+ self.assertEqual(login.current_user.username, "test_screen_name")
self.assertEqual(login.current_user.is_authenticated, True)