You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

128 lines
5.1 KiB

from secrets import token_hex
from datetime import datetime, timedelta
from flask_login import UserMixin
from sqlalchemy.ext.associationproxy import association_proxy
from werkzeug.security import generate_password_hash, check_password_hash
from app import db, login
from app.models import GamePlayer, Role
class User(UserMixin, db.Model):
""" !Always call set_auth_hash() after creating new instance! """
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True, nullable=False)
auth_hash = db.Column(db.String(32), unique=True, nullable=True)
password_hash = db.Column(db.String(128))
last_login = db.Column(db.DateTime)
user_games = db.relationship(
'GamePlayer',
back_populates='user',
cascade='save-update, merge, delete, delete-orphan')
games = association_proxy('user_games', 'game',
creator=lambda game: GamePlayer(game=game))
locations = db.relationship(
'Location',
lazy='select',
backref=db.backref('user', lazy='joined'),
cascade="save-update, merge, delete, delete-orphan")
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def set_auth_hash(self):
self.auth_hash = token_hex(16)
def check_password(self, password):
if not password or not self.password_hash:
return False
return check_password_hash(self.password_hash, password)
def locations_during_game(self, game, offset=None):
'''
Returns users locations during game.
Parameters:
game (Game): If specified, only locations within start- and endtime of game wil be returned
offset (int): Offset in minutes. Only locations older than this amount of minutes will be returned.
'''
# pylint: disable=not-an-iterable
if offset is None or offset == '':
offset = 0
if not self.locations:
return None
if game is None:
if offset == 0:
return self.locations
return [location for location in self.locations
if datetime.utcnow() - location.timestamp > timedelta(minutes=offset)]
game_start = game.start_time or datetime.min
game_end = game.end_time or datetime.max
if offset == 0:
return [location for location in self.locations
if location.timestamp > game_start and location.timestamp < game_end]
return [location for location in self.locations
if location.timestamp > game_start and location.timestamp < game_end
and datetime.utcnow() - location.timestamp > timedelta(minutes=offset)]
def last_location(self, game=None, offset=None):
'''
Returns users last recorded location.
Parameters:
game (Game): If specified, only locations within start- and endtime of game wil be returned
offset (int): Offset in minutes. Only locations older than this amount of minutes will be returned.
'''
# pylint: disable=[not-an-iterable, unsubscriptable-object]
if offset is None or offset == '':
offset = 0
if not self.locations:
return None
if game is None:
locations = self.locations_during_game(game=None, offset=offset)
return locations[-1] if locations else None
locations_during_game = self.locations_during_game(game, offset=offset)
return locations_during_game[-1] if locations_during_game else None
def role_in_game(self, game):
'''Returns the role as Role enum of player in given game. Returns None if player does not participate in game'''
gameplayer = self.player_in(game)
if not gameplayer:
return None
return gameplayer.role
def owns_game_played_by(self, user):
'''Self is an owner of a game the user participates in'''
return self in [gameplayer.user for gameplayers in
[game.players for game in user.games]
for gameplayer in gameplayers if gameplayer.role == Role.owner]
def owned_game_played_by(self, user):
'''Return first game owned by self that the user participates in'''
return next(iter([gameplayer.game for gameplayers in
[game.players for game in user.games]
for gameplayer in gameplayers
if gameplayer.role == Role.owner and gameplayer.user == self]),
None)
def player_in(self, game):
# pylint: disable=not-an-iterable
'''Returns GamePlayer object for given game, or None if user does not participate in given game'''
gameplayers = [gameplayer for gameplayer in self.user_games if gameplayer.game == game]
if not gameplayers:
return None
return gameplayers[0]
@staticmethod
def delete_orphans():
User.query.filter(~User.user_games.any()).delete()
db.session.commit()
@login.user_loader
def load_user(id):
return User.query.get(int(id))