class Promoter(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(30), nullable=False, unique=True, index=True) name = db.Column(db.String(100), nullable=False, index=True) description = db.Column(db.String) created_on = db.Column(db.DateTime, nullable=False, default=datetime.now) longitude = db.Column(db.Float(precision=9)) latitude = db.Column(db.Float(precision=9)) email = db.Column(db.String(40)) category_id = db.Column(db.Integer, db.ForeignKey('event_category.id')) category = db.relationship(EventCategory) users = db.relationship('User', secondary='promoter_user', backref=db.backref('promoters')) def __repr__(self): return f'<Promoter: {self.username}>' def get_user_role(self, user: User): promoter_user = PromoterUser.query.filter( PromoterUser.user == user).first() return promoter_user.role
class EventPromoter(db.Model): class Role(IntEnum): COPROMOTER = auto() MAIN = auto() class Status(IntEnum): PENDING = auto() APPROVED = auto() REJECTED = auto() event_id = db.Column(db.Integer, db.ForeignKey('event.id'), primary_key=True) promoter_id = db.Column(db.Integer, db.ForeignKey('promoter.id'), primary_key=True) role = db.Column(db.Integer, default=Role.MAIN.value, nullable=False) status = db.Column(db.Integer, default=Status.PENDING.value, nullable=False) event = db.relationship('Event', backref=db.backref('event_promoters')) promoter = db.relationship('Promoter', backref=db.backref('event_promoters', lazy='dynamic'))
class Replay(db.Model): __tablename__ = 'replay' id = db.Column(db.Integer, primary_key=True, autoincrement=True) guid = db.Column(db.String(128), default=False, nullable=False) version = db.Column(db.Integer, default=False, nullable=False) release = db.Column(db.String(128), default=False, nullable=False) created_at = db.Column(db.DateTime, nullable=False, server_default=func.now()) total_players = db.Column(db.Integer, default=False, nullable=False) elimination_events = db.relationship("Elimination", backref="Replay") stats = db.relationship("ReplayStats", backref="Replay") @hybrid_property def weapon_usage(self): return Counter(i.weapon_type for i in self.elimination_events) def __init__(self, **kwargs): super(Replay, self).__init__(**kwargs) def __json__(self): return ['id', 'guid', 'created_at', 'total_players', 'weapon_usage']
class Dog(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) description = db.Column(db.String) breed_id = db.Column(db.Integer, db.ForeignKey('breed.id')) breed = db.relationship(Breed, backref='dogs') user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship(User, backref='dogs') photo = db.Column(db.Unicode) size = db.Column(db.String) born_date = db.Column(db.Date) location = db.Column(db.String) def __init__(self, name, description=None, size=None, photo=None, born_date=None, breed_id=None, location=None, user_id=None): self.name = name self.description = description self.size = size self.photo = photo self.born_date = born_date self.breed_id = breed_id self.location = location self.user_id = user_id def __repr__(self): return u'<Dog %s>' % self.name
class PromoterUser(db.Model): class Role(IntEnum): SUPPORT = auto() CREATOR = auto() ADMIN = auto() promoter_id = db.Column(db.Integer, db.ForeignKey('promoter.id'), primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) role = db.Column(db.Integer, default=Role.SUPPORT.value, nullable=False) promoter = db.relationship('Promoter', backref=db.backref('roles')) user = db.relationship('User', backref=db.backref('roles')) @classmethod def get_minimum_role_for_event(cls): return cls.Role.CREATOR
class EventCategory(db.Model): __tablename__ = 'event_category' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False, unique=True, index=True) description = db.Column(db.String) default = db.Column(db.Boolean, default=False) parent_id = db.Column(db.Integer, db.ForeignKey('event_category.id'), nullable=True) children = db.relationship('EventCategory') def __repr__(self): return f'<Event category: {self.name}'
class Bilhete(db.Model): __tablename__ = 'bilhete' id = db.Column(db.Integer, primary_key=True) num_bilhete = db.Column(db.String(10)) date_posted = db.Column(db.DateTime, nullable=False) parecer = db.relationship('Parecer', uselist=False, backref='bilhete', lazy='dynamic') def __init__(self, num_bilhete=None, date_posted=None): self.num_bilhete = num_bilhete self.date_posted = datetime.datetime.now()
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) password_hash = db.Column(db.String) pomodoros = db.relationship('Pomodoro', backref='user', lazy='dynamic') @property def password(self, password): raise AttributeError('password: write-only field') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) @staticmethod def get_by_username(username): return User.query.filter_by(username=username).first() def __repr__(self): return "<User {}>".format(self.username)
class Event(db.Model): minumum_duration = relativedelta(minutes=30) id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) longitude = db.Column(db.Float(precision=9)) latitude = db.Column(db.Float(precision=9)) datetime_from = db.Column(db.DateTime, nullable=False, default=datetime.now) datetime_to = db.Column(db.DateTime) capacity = db.Column(db.Integer, default=0) profit = db.Column(db.Boolean, default=False, nullable=False) subcateogries = db.relationship('EventCategory', secondary=event_subcategories) main_category_id = db.Column(db.Integer, db.ForeignKey('event_category.id')) main_category = db.relationship('EventCategory') updates = db.relationship('EventUpdate', backref='event') def __repr__(self): return f'Event: {self.name}' @classmethod def create_event(cls, user: User, main_promoters: list, copromoters: list = [], **kwargs): event = cls(**kwargs) db.session.add(event) db.session.commit() for promoter in main_promoters: event.assign_promoter(promoter=promoter, user=user, main=True) for promoter in copromoters: event.assign_promoter(promoter, user) return event def assign_promoter(self, promoter: Promoter, user: User, main: bool = False): event_promoter = EventPromoter(event=self, promoter=promoter, role=EventPromoter.Role.MAIN.value) user_role = promoter.get_user_role(user) if user_role >= PromoterUser.Role.CREATOR.value: event_promoter.status = EventPromoter.Status.APPROVED db.session.add(event_promoter) db.session.commit() def create_update(self, text: str, tag: int = None, **kwargs): event_update = EventUpdate(tag=tag, text=text) self.updates.append(event_update) db.session.commit() return event_update
class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True, autoincrement=True) firstname = db.Column(db.String(128), nullable=True) lastname = db.Column(db.String(128), nullable=False) email = db.Column(db.String(128), unique=True, nullable=False) password = db.Column(db.String, nullable=False) admin = db.Column(db.Boolean, default=False, nullable=False) email_sent = db.Column(db.Boolean, default=False, nullable=False) confirmed = db.Column(db.Boolean, default=False, nullable=False) accountdetails = db.relationship('Accountdetails', lazy='dynamic', backref=db.backref('users', lazy=True)) def __init__(self, firstname, lastname, email, password): self.firstname = firstname self.lastname = lastname self.email = email self.password = bcrypt.generate_password_hash( password, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode() def to_json(self): return { 'id': self.id, 'firstname': self.firstname, 'lastname': self.lastname, 'email': self.email, 'admin': self.admin, 'email_sent': self.email_sent, 'confirmed': self.confirmed, 'accountdetails': [upload.to_json() for upload in self.accountdetails] } def showCertInfo(self, app): return {'certificate': app.certificate, 'status': app.status} def encode_auth_token(self, user_id): try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta( days=current_app.config.get('TOKEN_EXPIRATION_DAYS'), seconds=current_app.config.get( 'TOKEN_EXPIRATION_SECONDS')), 'iat': datetime.datetime.utcnow(), 'sub': user_id } return jwt.encode(payload, current_app.config.get('SECRET_KEY'), algorithm='HS256') except Exception as e: return e @staticmethod def decode_auth_token(auth_token): # return auth_token try: payload = jwt.decode(auth_token, current_app.config.get('SECRET_KEY')) return payload['sub'] except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again' except jwt.InvalidTokenError: return 'Invalid Token. Please log in again'
class ReplayStats(db.Model): __tablename__ = 'stats' id = db.Column(db.Integer, primary_key=True, autoincrement=True) created_at = db.Column(db.DateTime, nullable=False, server_default=func.now()) replay_id = db.Column(db.Integer, db.ForeignKey('replay.id', ondelete='CASCADE')) username = db.Column(db.String(255), nullable=False) eliminations = db.Column(db.Integer, default=False, nullable=False) accuracy = db.Column(db.Float, default=False, nullable=False) assists = db.Column(db.Integer, default=False, nullable=False) weapon_damage = db.Column(db.Integer, default=False, nullable=False) other_damage = db.Column(db.Integer, default=False, nullable=False) revives = db.Column(db.Integer, default=False, nullable=False) damage_taken = db.Column(db.Integer, default=False, nullable=False) damage_structures = db.Column(db.Integer, default=False, nullable=False) materials_gathered = db.Column(db.Integer, default=False, nullable=False) materials_used = db.Column(db.Integer, default=False, nullable=False) total_traveled = db.Column(db.Integer, default=False, nullable=False) position = db.Column(db.Integer, default=False, nullable=False) replay = db.relationship("Replay", backref="ReplayStats") @hybrid_property def died(self): return any(i for i in self.replay.elimination_events if i.eliminated == self.username and not i.knocked) @hybrid_property def knocks(self): return len([ i for i in self.replay.elimination_events if i.eliminator == self.username and i.knocked ]) @hybrid_property def knocked(self): return len([ i for i in self.replay.elimination_events if i.eliminated == self.username and i.knocked ]) @hybrid_property def winner(self): return self.position == 1 def __init__(self, replay_id, username, stats, team_stats): self.replay_id = replay_id self.username = username self.eliminations = stats['eliminations'] self.accuracy = stats['accuracy'] self.assists = stats['assists'] self.weapon_damage = stats['weapon_damage'] self.other_damage = stats['other_damage'] self.revives = stats['revives'] self.damage_taken = stats['damage_taken'] self.damage_structures = stats['damage_structures'] self.materials_gathered = stats['materials_gathered'] self.materials_used = stats['materials_used'] self.total_traveled = stats['total_traveled'] self.position = team_stats['position'] def __json__(self): return [ 'replay_id', 'username', 'eliminations', 'accuracy', 'assists', 'weapon_damage', 'other_damage', 'revives', 'damage_taken', 'damage_structures', 'materials_gathered', 'materials_used', 'total_traveled', 'position', 'died', 'knocks', 'knocked', 'winner' ]