class ToolForTribulationDTO(db.Model): __tablename__ = 'tool_for_tribulation' tribulation_id = db.Column(db.Integer, db.ForeignKey('tribulation.tribulation_id'), primary_key=True) tool_id = db.Column(db.Integer, db.ForeignKey('tool.tool_id'), primary_key=True) time_start = db.Column(db.DateTime, default=datetime.utcnow) time_end = db.Column(db.DateTime, default=datetime.utcnow) quantity = db.Column(db.Integer, default=0) def serialize(self): return { "tribulation_id": self.tribulation_id, "tool_id": self.tool_id, "time_start": self.time_start, "time_end": self.time_end, "quantity": self.quantity } def merge(self, newdata): for key, value in newdata.items(): if value: setattr(self, key, value)
class Reservation(db.Model): id = db.Column(db.Integer, primary_key=True) res_date = db.Column(db.DateTime, nullable=False) res_moment = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) is_started = db.Column(db.Boolean(), nullable=False, default=False) owner_id = db.Column(db.Integer, db.ForeignKey('setup.id'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) def se(self): # se:Student Enviroment Starter start_time = self.res_date duration = Setup.query.filter_by( id=self.owner_id).first().period_of_res token = User.query.filter_by(id=self.user_id).first().password_sha1 setup = Setup.query.filter_by(id=self.owner_id).first() port = self.owner_id + 8800 self.bash_file(token, setup.id, port) duration = int(duration) end_time = start_time + timedelta(minutes=duration) left = end_time - datetime.now() proc = subprocess.Popen([ 'gnome-terminal', '--disable-factory', '--', 'bash', 'setup{}.sh'.format(setup.id) ], preexec_fn=os.setpgrp) o_e_id = Setup.query.filter_by(id=self.owner_id).first().owner_id self.cp_materials(o_e_id, setup.id) print(f'New student enviroment ready for {setup.name}!') time.sleep(int(left.seconds) - 10) print(f'{setup.name} is closing') os.killpg(proc.pid, signal.SIGINT) os.remove(f'setup{setup.id}.sh') print(f'{setup.name} has closed') @staticmethod def bash_file(token, setup_id, port): ip_adress = ip_find() text = [] text.append('#!/bin/bash\n') text.append('\n') text.append('sudo su - setup{} <<EOF\n'.format(setup_id)) text.append('rm -rf *\n') text.append( "jupyter notebook --no-browser --NotebookApp.token='' --NotebookApp.password={0} --ip {1} --port {2} --NotebookApp.terminals_enabled=False\n" .format(token, ip_adress, port)) text.append('EOF\n') with open('setup{}.sh'.format(setup_id), 'w') as f: f.writelines(text) @staticmethod def cp_materials(o_e_id, setup_id): time.sleep(3) #If no delay put, materials delete in the subprocess mtrls = Experiment.query.filter_by(id=o_e_id).first().materials.all() for m in mtrls: os.system(f'sudo cp uploads/{m.name} /home/setup{setup_id}/') return def __repr__(self): return f"Reservation('{self.res_date}','{self.owner_id}','{self.user_id}')"
class Material(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) owner_id = db.Column(db.Integer, db.ForeignKey('experiment.id'), nullable=False) def __repr__(self): return f"Material('{self.name}','{self.owner_id}')"
class Post(db.Model): id = db.Column(db.Integer, primary_key=True) url = db.Column(db.String(140)) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey("user.id")) def __repr__(self): return "<Post {}>".format(self.url)
class Experiment(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) owner_id = db.Column(db.Integer, db.ForeignKey('course.id'), nullable=False) setups = db.relationship('Setup', backref='owner', lazy='dynamic') materials = db.relationship('Material', backref='owner', lazy='dynamic') def __repr__(self): return f"Experiment('{self.name}','{self.owner_id}')"
class Post(db.Model): id = db.Column(db.Integer, primary_key=True) plays = db.Column(db.Integer, default=0) url = db.Column(db.String(140)) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey("user.id")) def __repr__(self): return "\n{} - https://www.youtube.com/watch?v={}\n".format( self.body, self.url) def get_plays(self): return self.plays def increment_play_count(self): self.plays += 1 return def delete_all(): posts = Post.get_posts() for post in posts: db.session.delete(post) db.session.commit() return redirect(url_for("index")) def delete(id): post = Post.get_post(id) db.session.delete(post) db.session.commit() return def create(url, body): post = Post(user_id=current_user.id, url=url, body=body) db.session.add(post) db.session.commit() return def update(id, url, body): post = Post.get_post(id) post.url = url post.body = body db.session.add(post) db.session.commit() return def get_post(id): return Post.query.get_or_404(id) def get_posts(): return Post.query.order_by(Post.id).all()
class LogDTO(db.Model): __tablename__ = 'log' user_id = db.Column(db.Integer, db.ForeignKey('actor.actor_id'), primary_key = True) date_create = db.Column(db.DateTime,default = datetime.utcnow, primary_key = True) action = db.Column(db.String(100), nullable = True) user = db.relationship(ActorDTO) def serialize(self): return { "user_id": self.user_id, "user_name": self.user.name, "date_create": self.date_create, "action": self.action, }
class Setup(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) period_of_res = db.Column(db.Integer, nullable=False) max_res_for_week = db.Column(db.Integer, nullable=False) #Currently not in use is_virtual = db.Column(db.Boolean(), nullable=False, default=False) product_id = db.Column(db.String(150), nullable=False) product_serial = db.Column(db.String(150), unique=True, nullable=False) owner_id = db.Column(db.Integer, db.ForeignKey('experiment.id'), nullable=False) reservations = db.relationship('Reservation', backref='owner', lazy='dynamic') def setup_user_creator(self): os.system( f'sudo useradd -m -d /home/setup{self.id} -s /bin/bash setup{self.id}' ) os.system(f'sudo chown -R setup{self.id} /home/setup{self.id}') os.system(f'sudo chmod -R 750 /home/setup{self.id}') if self.is_virtual: os.system(f'sudo usermod -a -G dialout setup{self.id}') return self.rule_file(self.product_id, self.product_serial, self.id) os.system(f'sudo cp 99-setup{self.id}.rules /etc/udev/rules.d/') os.system(f'sudo udevadm control --reload-rules && udevadm trigger') os.remove(f'99-setup{self.id}.rules') def setup_user_delete(self): if not self.is_virtual: os.system(f'sudo rm /etc/udev/rules.d/99-setup{self.id}.rules') os.system(f'sudo userdel -r setup{self.id}') @staticmethod def rule_file(product_id, product_serial, setup_id): text = [] text.append( f'SUBSYSTEM=="tty", ATTRS{{idProduct}}=="{product_id}", ATTRS{{serial}}=="{product_serial}", ACTION=="add", RUN+="/bin/setfacl -m u:setup{setup_id}:rw- /dev/$name"' ) with open(f'99-setup{setup_id}.rules', 'w') as f: f.writelines(text) def __repr__(self): return f"Setup('{self.name}','{self.period_of_res}','{self.max_res_for_week}','{self.owner_id}')"
class Recording(db.Model): id = db.Column(db.Integer, primary_key=True) score = db.Column(db.Float) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) scale = db.Column(db.String(64), index=False, unique=False) key = db.Column(db.String(64), index=False, unique=False) def get_score(self): return self.score def __repr__(self): return '<recording {}>'.format(self.score) def info(self): return (str(self.timestamp), str(self.score)) def get_scale(self): return str(scale) def get_key(self): return str(key)
from datetime import datetime, timedelta from flask_server import db, login_manager from flask_server.functions import ip_find from flask_login import UserMixin import os import signal import subprocess import time subs = db.Table( 'subs', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('course_id', db.Integer, db.ForeignKey('course.id')), ) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(30), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(120), nullable=False) password_sha1 = db.Column(db.String(120), nullable=False) is_admin = db.Column(db.Boolean(), nullable=False, default=False) reservations = db.relationship('Reservation', backref='owner_student', lazy='dynamic')
from datetime import datetime, timedelta from flask_server import flask_server, db, login, mail from flask_login import UserMixin, current_user from werkzeug.security import generate_password_hash, check_password_hash from hashlib import md5 from flask import flash, redirect, url_for, request, render_template from flask_mail import Mail, Message import random import string followers = db.Table( "followers", db.Column("follower_id", db.Integer, db.ForeignKey("user.id")), db.Column("followed_id", db.Integer, db.ForeignKey("user.id")), ) class User(UserMixin, db.Model): """ The User database object model. The Flask-Login extension expects that the class used to represent users implements the following properties and methods: a. is_authenticated - This property should return True if the user is authenticated, i.e. they have provided valid credentials. (Only authenticated users will fulfill the criteria of login_required.) b. is_active - This property should return True if this is an active user - in addition to being authenticated, they also have activated their account, not been suspended, or any condition your application has for rejecting an account. Inactive accounts may not log in (without being forced of course). c. is_anonymous - This property should return True if this is an anonymous user. (Actual users should return False instead.) d. get_id() - This method must return a unicode that uniquely identifies this user, and can be used to load the user from the user_loader callback. Note that this must be a unicode - if the ID is natively an int or some other type, you will need to convert it to unicode. e. These are inherited from the [`UserMixin`](https://flask-login.readthedocs.io/en/latest/#flask_login.UserMixin) class. f. [`db.Model`](https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#models) q
class CharacterDTO(db.Model): __tablename__ = 'character' character_name = db.Column(db.String(80), nullable = False) actor_id = db.Column(db.Integer, db.ForeignKey('actor.actor_id'), primary_key = True) tribulation_id = db.Column(db.Integer, db.ForeignKey('tribulation.tribulation_id'), primary_key = True)