def rooms_by_address(): print(request.form) if not 'start' in request.form.keys(): return jsonify([{ 'id': i.id, 'name': i.name } for i in Room.select().where(Room.address == request.form['address']) ]) else: data = dict(request.form) print('awdawdawdaw') start = data['start'].split(':') data['start'] = datetime.datetime.now().replace(hour=int(start[0]), minute=int(start[1]), second=0) data['end'] = data['start'] + datetime.timedelta(hours=1, minutes=30) data['start'] = datetime.time(hour=data['start'].hour, minute=data['start'].minute) data['end'] = datetime.time(hour=data['end'].hour, minute=data['end'].minute) data['date'] = datetime.datetime.fromisoformat(data['date'].replace( 'Z', '')).date() qq = Room.select().where((Room.address == data['address']) & Room.id.not_in( Room.select(Room.id).join(Lesson).where( (Lesson.date == data['date']) & (((data['start'] >= Lesson.start) & (data['start'] <= Lesson.end)) | ((data['end'] >= Lesson.start) & (data['end'] <= Lesson.end)))))) print(list(qq)) return jsonify([{'id': i.id, 'name': i.name} for i in qq])
def test_match_direction(): with session() as s: d = Direction.create('testing', opposite_string='the test') s.add(d) s.commit() r = Room.get(rid) assert r.match_direction('t') is d assert r.match_direction('testing') is d assert r.match_direction('fails') is None
def post(self): data = room_parser.parse_args() if not Room.query.filter_by(number=data["number"]).scalar(): try: db.session.add(Room(**data)) db.session.commit() except IntegrityError: db.session.rollback() return {"msg": f"Room {data['number']} was added"} abort(404, message="Room already exist!")
def func(self, character, args, text): z = Zone(builder_id=character.id, name='New Zone #') s.add(z) s.commit() z.name = f'{z.name}{z.id}' character.notify(f'Created zone {z.name}.') r = Room(zone_id=z.id, name='The First Room') s.add(r) s.commit() character.notify(f'Created room {r}.') character.move(r) character.show_location()
def func(self, character, args, text): direction = args.direction title = args.title if not title: self.exit(message='Room titles cannot be blank.') d = character.location.match_direction(direction) if d is None: self.exit(message=f'Invalid exit: {direction}') direction = d.name if Exit.query(name=direction, location_id=character.location_id).count(): self.exit(message='There is already an exit in that direction.') x, y, z = d.coordinates_from(character.location.coordinates) r = Room.query(x=x, y=y, z=z).first() if r is None: r = Room(name=title, x=x, y=y, z=z, zone_id=character.location.zone_id) s.add(r) s.commit() msg = f'Created room {r}.' else: msg = f'Linking to room {r}.' character.notify(msg) x = Exit(name=direction, location_id=character.location_id, target_id=r.id) y = Exit(name=d.opposite.name, location_id=r.id, target_id=character.location.id) s.add_all([x, y]) s.commit() for thing in [x, y]: character.notify(f'Created exit {thing} from {thing.location} to ' f'{thing.target}.')
def create_session(): if not verify_session_token(): return failure_response("Session token expired.") body = json.loads(request.data) num_sessions = body.get("num_sessions") work_length = body.get("work_length") break_length = body.get("break_length") room_length = num_sessions * (work_length + break_length) user = users_dao.get_user_by_username(body.get("username")).first() if user is None: failure_response("User invalid") if num_sessions is None: failure_response("Must enter number of sessions") if work_length is None: failure_response("Must enter length of work periods") if break_length is None: failure_response("Must enter length of break periods") # Create new OpenTok session opentok_id = opentok.create_session().session_id token = opentok.generate_token(opentok_id, expire_time=int(time.time()) + room_length) # Create new Room Object body = json.loads(request.data) new_room = Room(opentok_id=opentok_id, code=body.get('code'), num_sessions=body.get('num_sessions'), work_length=body.get('work_length'), break_length=body.get('break_length')) # Add creator to Room Object new_room.users.append(user) # Push changes to database db.session.add(new_room) db.session.commit() # Give client parameters necessary to connect return success_response( { 'key': api_key, 'opentok_id': opentok_id, 'token': token }, 201)
def handle_message(room_key, user, message): message_obj = json.loads(message) room = Room.by_room_key(room_key) other_user = room.get_other_user(user) if room else None if message_obj['type'] == 'bye': # This would remove the other_user in loopback test too. # So check its availability before forwarding Bye message. delete_saved_messages(make_client_id(room_key, user)) room.remove_user(user) logging.info('User ' + user + ' quit from room ' + room_key) logging.info('Room ' + room_key + ' has state ' + str(room)) if other_user and other_user != user: # channel_send_message( # make_client_id(room, other_user), '{"type":"bye"}') logging.info('Sent BYE to ' + other_user) return 'bye' if other_user or room_key == '1': if message_obj['type'] == 'offer': # Special case the loopback scenario. if other_user == user or room_key == '1': message = make_loopback_answer(message) return message # Workaround Chrome bug. # Insert a=crypto line into offer from FireFox. # TODO(juberti): Remove this call. message = maybe_add_fake_crypto(message) message = message.replace("\"offer\"", "\"answer\"") if room_key == '1': return message if other_user: on_message(room_key, other_user, message) client_id = make_client_id(room_key, user) messages = get_saved_messages(client_id) message = '' for i in messages: message = i.msg logger.debug(message) return message
def post(self): message = self.request.body check = self.get_argument('check', None) room_key = self.get_argument('r') user = self.get_argument('u') logging.info('message is ' + message) logging.info('room_key is ' + room_key) logging.info('user is ' + user) with LOCK: room = Room.by_room_key(room_key) if check: if room_key == '1': status = 'True' else: status = str(room.has_user(user) and room.get_occupancy() == 2) self.write(status) elif room_key: message = handle_message(room_key, user, message) info = 'echo message %s' % message logger.debug(info) self.write(message) else: logging.warning('Unknown room ' + room_key)
def get(self): """Renders the main page. When this page is shown, we create a new channel to push asynchronous updates to the client.""" room_key = sanitize(self.get_argument('r', None)) debug = self.get_argument('debug', None) unittest = self.get_argument('unittest', None) stun_server = self.get_argument('ss', None) turn_server = self.get_argument('ts', None) hd_video = self.get_argument('hd', 'true') ts_pwd = self.get_argument('tp', None) # set compat to true by default. compat = self.get_argument('compat', 'true') if debug == 'loopback': # set compat to false as DTLS does not work for loopback. compat = 'false' # token_timeout for channel creation, default 30min, max 2 days, min 3min. # token_timeout = self.request.get_range('tt', # min_value = 3, # max_value = 3000, # default = 30) if unittest: # Always create a new room for the unit tests. room_key = generate_random(8) if not room_key: room_key = generate_random(8) redirect = '?r=' + room_key redirect = append_url_arguments(self.request, redirect) self.redirect(redirect) logging.info('Redirecting visitor to base URL to ' + redirect) return user = None initiator = 0 with LOCK: # room = None room = Room.by_room_key(room_key) if not room and debug != "full": # New room. user = generate_random(8) if debug == 'loopback': initiator = 1 info = 'user0 %s added to test room %s' % (user, room_key) logger.debug(info) else: initiator = 0 room = Room.new({'room_key': room_key}) room.add_user(user) info = 'user1 %s added to new room %s' % (user, room_key) logger.debug(info) elif room and room.get_occupancy() == 1 and debug != 'full': # 1 occupant. user = generate_random(8) room.add_user(user) info = 'user2 %s added to room %s' % (user, room_key) logger.debug(info) initiator = 1 else: # 2 occupants (full). template = jinja_environment.get_template('full.html') self.write( template.render({'room_key': room_key})) info = 'room %s is full' % (room_key) logger.debug(info) return room_link = 'http://%s/videomeet?r=%s' % (self.request.host, room_key) room_link = append_url_arguments(self.request, room_link) pc_config = make_pc_config(stun_server, turn_server, ts_pwd) pc_constraints = make_pc_constraints(compat) offer_constraints = make_offer_constraints(compat) media_constraints = make_media_constraints(hd_video) template_values = { 'me': user, 'room_key': room_key, 'room_link': room_link, 'initiator': initiator, 'pc_config': json.dumps(pc_config), 'pc_constraints': json.dumps(pc_constraints), 'offer_constraints': json.dumps(offer_constraints), 'media_constraints': json.dumps(media_constraints) } if unittest: target_page = 'test/test_' + unittest + '.html' else: target_page = 'videomeet.html' template = jinja_environment.get_template(target_page) self.write(template.render(template_values))
"""Boring database tests.""" from db import (Room, Character, session, Exit, Object, Guild, GuildSecondary, Direction, Zone) with session() as s: z = Zone(name='Test') s.add(z) s.commit() r = Room(name='Test Room', zone_id=z.id) c = Character(name='Test Player', location=r) s.add_all((c, r)) s.commit() rid = r.id cid = c.id def test_location_ids(): c = Character.get(cid) assert c.location_id == rid def test_stats(): c = Character.get(cid) c.max_hitpoints = 50 assert c.h == c.max_hitpoints c.h = 5 assert c.h == 5 assert c.max_hitpoints == 50 c.h = c.max_hitpoints assert c.hitpoints is None
def new_lesson(): return render_template('lessons/new.html', groups=Group.select(), lecturers=Lecturer.select(), addresses=Room.select(Room.address).group_by( Room.address))
def insert(): rooms = [{ 'name': '1', 'address': 'address1', 'id': 1 }, { 'name': '10', 'address': 'address1', 'id': 2 }, { 'name': '20', 'address': 'address1', 'id': 3 }, { 'name': '30', 'address': 'address1', 'id': 4 }, { 'name': '40', 'address': 'address1', 'id': 5 }, { 'name': '1', 'address': 'address2', 'id': 6 }, { 'name': '5', 'address': 'address2', 'id': 7 }, { 'name': '10', 'address': 'address2', 'id': 8 }, { 'name': '15', 'address': 'address2', 'id': 9 }, { 'name': '20', 'address': 'address2', 'id': 10 }] Room.insert_many(rooms).execute() lecturers = [{ 'name': 'Lecturer One' }, { 'name': 'Lecturer One' }, { 'name': 'Lecturer Two' }, { 'name': 'Lecturer Three' }, { 'name': 'Lecturer Four' }] Lecturer.insert_many(lecturers).execute() groups = [{ 'name': 'stream1', 'id': 1 }, { 'name': 'stream2', 'id': 2 }, { 'name': 'group1', 'parentGroupId': 1, 'id': 3 }, { 'name': 'group2', 'parentGroupId': 1, 'id': 4 }, { 'name': 'group3', 'parentGroupId': 2, 'id': 5 }, { 'name': 'group4', 'parentGroupId': 2, 'id': 6 }, { 'name': 'group5', 'id': 7 }] Group.insert_many(groups).execute() students = [{'id': i, 'name': 'student ' + str(i)} for i in range(1, 41)] Student.insert_many(students).execute() stg = [{'StudentID': i, 'GroupID': 1} for i in range(1, 21)] stg += [{'StudentID': i, 'GroupID': 2} for i in range(21, 41)] stg += [{'StudentID': i, 'GroupID': 3} for i in range(1, 11)] stg += [{'StudentID': i, 'GroupID': 4} for i in range(11, 21)] stg += [{'StudentID': i, 'GroupID': 5} for i in range(21, 31)] stg += [{'StudentID': i, 'GroupID': 6} for i in range(31, 41)] stg += [{'StudentID': i, 'GroupID': 7} for i in range(1, 41, 5)] StudentToGroup.insert_many(stg).execute() dates = [ date(2020, 2, 10), date(2020, 2, 11), date(2020, 2, 12), date(2020, 2, 13) ] times = [(time(9, 30), time(11, 5)), (time(11, 15), time(12, 50)), (time(13, 40), time(15, 15))] lessons = [] for d in dates: (s, e) = times[0] #print(e) lessons.append({ 'group': 1, 'room': 1, 'lecturer': 1, 'name': 'Lecture', 'start': s, 'end': e, 'date': d }) lessons.append({ 'group': 2, 'room': 2, 'lecturer': 2, 'name': 'Lecture', 'start': s, 'end': e, 'date': d }) (s, e) = times[1] lessons.append({ 'group': 3, 'room': 3, 'lecturer': 3, 'name': 'Practice', 'start': s, 'end': e, 'date': d }) lessons.append({ 'group': 4, 'room': 4, 'lecturer': 4, 'name': 'Practice', 'start': s, 'end': e, 'date': d }) lessons.append({ 'group': 5, 'room': 1, 'lecturer': 1, 'name': 'Practice', 'start': s, 'end': e, 'date': d }) lessons.append({ 'group': 6, 'room': 2, 'lecturer': 2, 'name': 'Practice', 'start': s, 'end': e, 'date': d }) (s, e) = times[2] lessons.append({ 'group': 7, 'room': 3, 'lecturer': 3, 'name': 'Elective', 'start': s, 'end': e, 'date': d }) print(lessons) Lesson.insert_many(lessons).execute()
def lineReceived(self, line): """A line was received.""" self.idle_since = datetime.utcnow() line = line.decode(encoding, 'replace') with session() as s: if self.intercept is not None: return self.intercept.feed(line) if self.username is None: self.username = line.lower() if line == config.new_character_command: msg = 'Enter a name for your new character:' else: msg = 'Password:'******'That character name is taken. Please choose ' 'another.') elif not line: self.notify( 'Character names cannot be blank. Goodbye.') return self.transport.loseConnection() else: c = Character(name=line.title()) s.add(c) c.location = Room.first() s.commit() self.object = c self.logger.info('Created character %s.', c) self.notify( f'Your new password is {c.randomise_password()}.') else: c = Character.query( func.lower(Character.name) == self.username).first() if c is None or not c.check_password(line): self.notify('Incorrect password.') self.username = None return self.notify('Username:'******'s tell the # user where they are. return self.object.show_location() if not line: return # Just a blank line. if line[0] in config.command_substitutions: line = config.command_substitutions[line[0]] + line[1:] both = line.split(' ', 1) if len(both) == 1: both.append('') if self.object is not None and self.object.log_commands: self.object.log_command(line) command, rest = both if command in commands_table and commands_table[command].allowed( self.object): try: return commands_table[command].run(self.object, rest) except Exception as e: return self.object.notify( 'Something went wrong with your command.') cmd = RoomCommand.query( name=command, location_id=self.object.location_id).first() if cmd is not None: try: with manage_environment(character=self.object, here=self.object.location, text=rest) as lua: lua.execute(cmd.code) except MatchError as e: self.object.notify(str(e)) except Exception as e: self.notify('There was a problem with your command.') logger.warning('Room command %s caused an error:', cmd) logger.exception(e) return direction = self.object.location.match_direction(line) if direction is None: return self.notify("I don't understand that.") commands_table['go'].run(self.object, direction.name)