예제 #1
0
	def test_reallocate_existing_staff_to_office(self):
		office = Office('My9994')
		Office.add(office)
		staff = Staff("Ugeg", "Insdnis", "073437")
		office.allocate_to(staff)
		with self.assertRaises(ValueError):
			Room.reallocate(staff, office)
예제 #2
0
	def serverStatus(self,message):
		# ip is the server name
		ip,port = self.transport.socket.getpeername()
		# Find the server named ip in the RoomServer room
		server = None
		for s in self.factory.rooms["RoomServer"].players:
			if s.name == ip:
				server = s

		# Build a local representation of its open rooms
		# Used to determine which server the player should connect to
		server.rooms = []
		server.openRoomCount = 0

		if server != None:
			server.playerCount = message.readInt()
			print "PCount " + str(server.playerCount)
			server.openRoomCount = message.readInt()
			for i in range(0,server.openRoomCount):
				room = Room(message.readString())								
				room.playerCount = message.readInt()
				server.rooms.append(room)

			print str(server.rooms)
		else:
			print "No server with name " + ip + " found in " + str(self.factory.rooms)

		print "***Server Status***"
		print server.name
		print "Players: " + str(server.playerCount)
		print "Rooms: ("+str(server.openRoomCount)+")"
		for r in server.rooms:
			print r.roomID + " " + str(r.playerCount)
예제 #3
0
    def post(self):
        logging.error("form: room_name = %s" % self.request.POST["name"])

        try:
            room = Room.get_by_key_name(self.request.POST["name"])

            if room and self.request.POST.get(
                    "action") == "switch_active_status":
                if room.is_active:
                    room.is_active = False
                else:
                    room.is_active = True
                room.put()
                self.set_message("activation switched")
            elif room and self.request.POST.get("action") == "chpass":
                room.password = hashlib.sha1(
                    self.SECRET + self.request.POST["password"]).hexdigest()
                room.put()
                self.set_message("password changed")
            elif not room:
                r = Room(key_name=self.request.POST["name"],
                         name=self.request.POST["name"],
                         password=hashlib.sha1(
                             self.SECRET +
                             self.request.POST["password"]).hexdigest())
                r.put()
                self.set_message("success")
            else:
                self.set_error("room '%s' already exists" % room.name)
        except:
            logging.error(traceback.format_exc())
            self.set_error("error")
        time.sleep(1)
        self.redirect("/admin/")
예제 #4
0
 def test_allocations_load_state(self):
     path = "db/"
     file_name = "mydb"
     file_ = file_name + ".db"
     #clean up to avoid conflict between tests
     os.remove(path + file_)
     self.clear_stores()
     #memory
     livingspace = LivingSpace('hwan')
     LivingSpace.add(livingspace)
     fellow = Fellow("onon", "ekek", "000009", "Y")
     fellow.register()
     livingspace.allocate_to(fellow)
     prev_allocations = Room.all_allocations().copy()
     Allocation.save_state(file_name)
     #clear memory stores
     self.clear_stores()
     empty_allocations = Room.all_allocations().copy()
     #db
     Allocation.load_state(file_name)
     loaded_allocations = Room.all_allocations().copy()
     #compare
     expected_output = ["HWAN", "LIVINGSPACE", "000009"]
     output = [
         prev_allocations[0], empty_allocations, loaded_allocations[0]
     ]
     self.assertEqual(output, [expected_output, [], expected_output])
예제 #5
0
    def post(self, user_name):
        print('ROOM CREATOR POST querry from', self.request.remote_ip)

        if self.current_user:
            table = self.get_argument('game_table')

            new_room = Room(None, None, table)
            new_room.add_player(
                str(self.current_user), self.get_cookie('nick'))

            player = {'color': new_room.get_color_by_player(self.current_user),
                      'nick': self.get_cookie('nick')}

            db = self.application.db
            obj_id = db.rooms.insert({
                'table': table,
                'players_num': new_room.players_num,
                'current_color': new_room.current_color,
                'players': {str(self.current_user): player}
            })

            new_room.objectid = str(obj_id)
            self.application.rooms_manager.add_room(new_room)

            # db room id to Cookies
            self.set_cookie("room_id", str(obj_id))
            self.redirect('/room/')
        else:
            self.redirect('/')
예제 #6
0
def user_leave_room(room_id):
    member = RoomMember.select('room_members.id','room_members.user_id', 'r.user_id as owner_id') \
        .join('rooms as r', 'r.id', '=', 'room_members.room_id') \
        .where('room_members.room_id', room_id) \
        .where('room_members.user_id', g.user['id']) \
        .first()

    if not member:
        return jsonify({'message': "Unknown Room"}), 400

    if member.user_id == member.owner_id:
        Room.where('id', room_id).delete()
        socketio.emit('close_room', {'room_id': room_id}, room='room-%s' % room_id)
        close_room(room='room-%s' % room_id, namespace='/')

    else:
        member.delete()

        clients = _.where(connected_users, {'id': member.user_id})
        if clients and _.isList(clients):
            for item in clients:
                leave_room('room-%s' % room_id, sid=item['sid'], namespace='/')

        socketio.emit('update_members', {'room_id': room_id, 'detach': []}, room='room-%s' % room_id)

    return jsonify({'message': 'Success'}), 200
예제 #7
0
    def post(self):
        logging.error("form: room_name = %s" % self.request.POST["name"])

        try:
            room = Room.get_by_key_name(self.request.POST["name"])

            if room and self.request.POST.get("action") == "switch_active_status":
                if room.is_active:
                    room.is_active = False
                else:
                    room.is_active = True
                room.put()
                self.set_message("activation switched")
            elif room and self.request.POST.get("action") == "chpass":
                room.password = hashlib.sha1(self.SECRET+self.request.POST["password"]).hexdigest()
                room.put()
                self.set_message("password changed")
            elif not room:
                r = Room(key_name=self.request.POST["name"],
                         name=self.request.POST["name"],
                         password=hashlib.sha1(self.SECRET+self.request.POST["password"]).hexdigest())
                r.put()
                self.set_message("success")
            else:
                self.set_error("room '%s' already exists" % room.name)
        except:
            logging.error(traceback.format_exc())
            self.set_error("error")
        time.sleep(1)
        self.redirect("/admin/")
예제 #8
0
 def test_compute_identity(self):
     from models.room import Room
     u1 = MagicMock(id=1)
     u2 = MagicMock(id=2)
     u3 = MagicMock(id=3)
     assert (Room.compute_identity([u1, u2, u3]) == Room.compute_identity(
         [u3, u2, u1]))
예제 #9
0
def print_room(room_name):
    try:
        room = Room(room_name)
        allocations = room.allocations()
        print_pretty(" Allocations to room: " + room.name)
        print_pretty(Room.members(allocations))
    except Exception as e:
        print_pretty(str(e))
예제 #10
0
	def test_reallocate_staff_to_livingspace(self):
		office = Office('M777848')
		Office.add(office)
		staff = Staff("jjjkkdsj", "liidsls", "0799034987")
		office.allocate_to(staff)
		livingspace1 = LivingSpace('U988934')
		LivingSpace.add(livingspace1)
		with self.assertRaises(Exception):
			Room.reallocate(staff, livingspace1)
예제 #11
0
def createRoom(name, info):
    try:
        room = Room(name, info)
        db.session.add(room)
        db.session.commit()
        return room.to_json(), 201
    except SQLAlchemyError as err:
        print(err)
        return "", 400
예제 #12
0
	def test_reallocate_staff_to_office(self):
		office = Office('Myok848')
		Office.add(office)
		staff = Staff("UNidng", "Inignis", "07089797537")
		office.allocate_to(staff)
		office1 = Office('M949438')
		Office.add(office1)
		Room.reallocate(staff, office1)
		self.assertEqual([office1.has_allocation(staff), office.has_allocation(staff)], 
						 [True, False])
예제 #13
0
	def test_reallocate_fellow_to_office(self):
		office = Office('000848')
		Office.add(office)
		fellow = Fellow("UNlsldg", "Ilslnis", "070555597537", "N")
		office.allocate_to(fellow)
		office1 = Office('M9498987')
		Office.add(office1)
		Room.reallocate(fellow, office1)
		self.assertEqual([office1.has_allocation(fellow), office.has_allocation(fellow)], 
						 [True, False])
예제 #14
0
	def test_reallocate_fellow_to_livingspace(self):
		livingspace  = LivingSpace('My9990')
		LivingSpace.add(livingspace)
		fellow = Fellow("jjjsj", "lksls", "07009987", "Y")
		livingspace.allocate_to(fellow)
		livingspace1  = LivingSpace('My9991')
		LivingSpace.add(livingspace1)
		Room.reallocate(fellow, livingspace1)
		self.assertEqual([livingspace1.has_allocation(fellow), livingspace.has_allocation(fellow)],
						 [True, False])
예제 #15
0
def test_update_room_fails(mocker):
    room = setUp(mocker)
    room2 = Room("x-Wing", "yeah")
    mocker.patch.object(roomService, 'getRoomById')
    roomService.getRoomById.return_value = room
    form = dict(name="x-Wing", info="yeah", c**k="balls")
    responseText, statusCode = roomService.updateRoom(1, form)
    assert room2.to_json() == responseText
    assert 200 == statusCode
    db.session.add.assert_called_with(room)
    db.session.commit.assert_called()
예제 #16
0
	def test_print_existing_allocations_to_screen(self):
		self.clear_stores()
		office = Office("NDO2")
		Dojo.add_room(office)
		fellow = Fellow("Xone2", "Ndobile2", "0856443324", "y")
		fellow.register()
		office.allocate_to(fellow)
		allocations_ = Room.all_allocations()
		output = Room.members(allocations_, room_tag=True)
		expected_output = " NDO2-OFFICE, 0856443324, NDOBILE2, XONE2, FELLOW\n"
		self.assertEqual(output, expected_output)
예제 #17
0
def test_room_variable_capacity():
    name = fake.name()
    room = Room(name=name)

    cap = random.randint(10, 50)

    assert room.capacity >= 10

    room.capacity = cap

    assert room.capacity == cap
예제 #18
0
 def setUp(self):
     self.guest_1 = Guest("Simon Elsmie")
     self.guest_2 = Guest("Rick Sanchez")
     self.room_1 = Room(1)
     self.room_2 = Room(2)
     self.date_1 = '2021-04-06'
     self.date_2 = '2021-04-07'
     self.reservation_1 = Reservation(self.guest_1, self.room_2,
                                      self.date_1, self.date_2, "Arrival")
     self.reservation_2 = Reservation(self.guest_2, self.room_1,
                                      self.date_1, self.date_2, "Arrival")
예제 #19
0
def test_room_unique_identifier():
    name = fake.name()
    room1 = Room(name=name)
    room2 = Room(name=name)

    room_manager = RoomManager()
    room_manager.save(room1)

    assert len(room_manager.rooms) == 1

    with pytest.raises(ValueError):
        room_manager.save(room2)

    assert len(room_manager.rooms) == 1
예제 #20
0
	def test_print_existing_allocations_to_default_file(self):
		self.clear_stores()
		office = Office("ND2")
		Dojo.add_room(office)
		fellow = Fellow("Xne2", "Ndoile2", "0868443324", "y")
		fellow.register()
		office.allocate_to(fellow)
		allocations_ = Room.all_allocations()
		expected_output = Room.members(allocations_, room_tag=True)
		Room.to_file(expected_output)
		path = "output/"
		f = open(path+"File.txt", "r")
		output = f.read() #"NDO2-Office, 0856443324, NDOBILE2, XONE2, FELLOW"
		f.close()
		self.assertEqual(expected_output, output)
예제 #21
0
def edit_room(id):
    name = request.form['name']
    capacity = request.form['capacity']
    description = request.form['description']
    room = Room(name, capacity, description, id)
    room_repository.update(room)
    return redirect('/rooms')
예제 #22
0
파일: room.py 프로젝트: gfreezy/pushpin
def rooms_create():
    user_ids = request.form.get('user_ids', '').split(',')
    users = User.get_list(user_ids)
    if g.me in users:
        users.append(g.me)
    room = Room.create(users)
    return jsonify(room)
예제 #23
0
 def setUp(self):
     self.engine = create_engine('sqlite:///:memory:')
     self.session = sessionmaker(self.engine)()
     Base.metadata.create_all(self.engine)
     self.room = Room(name='room1', theme='This is an example theme.')
     self.session.add(self.room)
     self.session.commit()
예제 #24
0
 def test_allocations_save_state(self):
     path = "db/"
     file_name = "mydb"
     file_ = file_name + ".db"
     #clean up to avoid conflict between tests
     os.remove(path + file_)
     self.clear_stores()
     #memory
     livingspace = LivingSpace('hwan')
     LivingSpace.add(livingspace)
     fellow = Fellow("onon", "ekek", "000009", "Y")
     fellow.register()
     livingspace.allocate_to(fellow)
     Allocation.save_state(file_name)
     #db
     engine = create_engine("sqlite:///" + path + file_, echo=False)
     Session = sessionmaker(bind=engine)
     session = Session()
     db_allocation = session.query(Allocation).first()
     #compare
     db_output = [
         db_allocation.roomname, db_allocation.roomtype,
         db_allocation.phonenumber
     ]
     self.assertEqual(Room.all_allocations()[0], db_output)
     session.close()
예제 #25
0
def room():

    room_data = {"name": fake.name()}
    room = Room.create(**room_data)

    yield room.serialize()
    room.delete()
예제 #26
0
def connect():
    db = get_db()
    user = User(db).get_user_by_username(session['username'])
    user_rooms = Room(db).get_user_rooms(user['user_id'])

    join_room(user['room'])

    for room in user_rooms:
        join_room(room['room_name'])
        response = {'user_id': user['user_id'], 'emit': True}

        if room['first_user_id'] == user['user_id']:
            friend = User(db).get_user(room['second_user_id'])
        else:
            friend = User(db).get_user(room['first_user_id'])

        emit('friend connect', response, room=friend['room'])

    awaiting_friend_request = FriendRequest(db).get_waiting_request(
        user['user_id'])

    if awaiting_friend_request is not None:
        sender = User(db).get_user(awaiting_friend_request['sender_id'])
        emit_friend_request(sender, user['room'],
                            awaiting_friend_request['request_id'])
예제 #27
0
 def post(self, group_id, room_id):
     form = RoomForm(self.request.arguments)
     if form.validate():
         room = Room.get(room_id)
         room.update(**form.data)
         room.save()
     self.redirect(self.reverse_url('rooms', group_id))
예제 #28
0
파일: chat.py 프로젝트: leeccong/code
def delete_room(request):
    room_name = request.get_form_var('room_name', '')
    if Room.delete(room_name):
        get_room_message(room_name).delete_by_key()
        return {'r': 1, 'msg': '删除成功'}

    return {'r': 0, 'msg': '删除失败, 可能该room已被删除'}
예제 #29
0
def create_room(room_type, *room_name_arguments):
    output = ''
    if room_name_arguments and isinstance(room_name_arguments[0], tuple):
        room_name_arguments = room_name_arguments[0]
    if room_name_arguments and room_type:
        for room_name in room_name_arguments:
            if room_name not in the_dojo.rooms.keys():
                new_room = Room(room_type, room_name)
                if room_type.lower() == 'office':
                    new_room = Office(room_name, {})
                elif room_type.replace(' ', '').lower() == 'livingspace':
                    new_room = LivingSpace(room_name, {})
                if len(
                        the_dojo.rooms
                ) <= total_number_of_rooms and room_name not in the_dojo.rooms.keys(
                ) and (isinstance(new_room, Office)
                       or isinstance(new_room, LivingSpace)):
                    the_dojo.rooms[room_name] = new_room
                    if room_name in the_dojo.rooms.keys():
                        prefix = 'A'
                        if room_type.lower() == 'office':
                            prefix = 'An'
                        output += prefix + ' ' + room_type.lower(
                        ) + ' called ' + room_name + " has been successfully created! \n"

    return output
예제 #30
0
	def setup(self):
		database_create(k_database)
		database.connect(k_database)

		system = User(0)
		self.room_id = Room.create("Test Room", system)
		self.room_controller = RoomController(self.room_id)
예제 #31
0
    async def wrapper(msg: Message) -> None:
        if msg.room:  # (1)
            msg.parametrized_room = msg.room
        else:  # (2)
            # User didn't supply any parameters
            if not msg.arg:
                await msg.user.send("Specifica il nome della room")
                return

            # Check if user supplied a non-empty roomid
            target_roomid = utils.to_room_id(msg.args[0], fallback=RoomId(""))
            msg.args = msg.args[1:]
            if not target_roomid:
                await msg.user.send("Specifica il nome della room")
                return
            msg.parametrized_room = Room.get(msg.conn, target_roomid)

            # Check if the room is valid
            if (
                target_roomid not in msg.conn.rooms  # bot in room
                or msg.user not in msg.parametrized_room  # user in room
            ):
                # Send the same message for both errors to avoid leaking private rooms
                await msg.user.send("Sei nella room?")
                return

        # Every check passed: wrap the original function
        await func(msg)
예제 #32
0
def createSeatAndRoom():
    room = Room("name", "info")
    db.session.add(room)
    seat = Seat("D1", room, "info")
    db.session.add(seat)
    db.session.commit()
    return room, seat
예제 #33
0
    def __check_if_room_exist(self, id):
        """
        check if room exist.
        """

        if not Room.find(id):
            raise ValidationError("The room id not found.")
예제 #34
0
 def add_rooms(self, room_inputs: List[RoomInput]):
     for room_input in room_inputs:
         room = Room(self.hotel_id, room_input[0], room_input[1],
                     room_input[2])
         self.rooms.append(room)
         # update capacity while adding rooms
         self.capacity[room_input[1]] += 1
예제 #35
0
 def post(self, group_id, room_id):
     form = RoomForm(self.request.arguments)
     if form.validate():
         room = Room.get(room_id)
         room.update(**form.data)
         room.save()
     self.redirect(self.reverse_url('rooms', group_id))
예제 #36
0
	def test_print_existing_allocations_to_specific_file(self):
		self.clear_stores()
		office = Office("ND88")
		Dojo.add_room(office)
		fellow = Fellow("Xne88", "Ndoile88", "086800000", "y")
		fellow.register()
		office.allocate_to(fellow)
		allocations_ = Room.all_allocations()
		expected_output = Room.members(allocations_, room_tag=True)
		file_name = office.name+"-Allocations"
		Room.to_file(expected_output, file_name)
		path = "output/"
		f = open(path+file_name+".txt", "r")
		output = f.read() 
		f.close()
		self.assertEqual(expected_output, output)
예제 #37
0
	def create_internal(self, name, owner):
		room_id = Room.create(name, owner)

		recreated_room = Room(room_id)
		assert_equals(room_id, recreated_room.room_id)
		assert_equals(name, recreated_room.name)
		assert_equals(owner, recreated_room.owner)

		return recreated_room
예제 #38
0
파일: chat.py 프로젝트: leeccong/code
def _q_lookup(request, room_name):
    if request.method == "POST":
        content = request.get_form_var('message')
        author = request.user.username
        date = datetime.now()
        message_data = {
            "content": content,
            "author": author,
            "date": date
        }
        room_message = get_room_message(room_name)
        room_message.add_message(message_data)
        return {'r': 1}
    if request.method == "GET":
        if room_name != 'lobby' and not Room.exists(room_name):
            return {'r': 0, 'msg': 'room not exists'}
        room_message = get_room_message(room_name)
        messages = room_message.get_messages()
        render_messages = [render_message(m) for m in messages]
        return {'r': 1, 'msg': render_messages}
예제 #39
0
	def test_reordering(self):
		default_room = Room(0)
		video1 = default_room.add_video(
			"youtube"
			, "http://www.youtube.com/watch?v=Qqd9S06lvH0"
			, "screaming creepers"
			, 28
			, 0)
		video2 = default_room.add_video(
			"youtube"
			, "http://www.youtube.com/watch?v=Wl8AK5Ht65Y"
			, "Oh Bother..."
			, 5
			, 0)

		assert_equal(default_room.video_queue(), [video1, video2])
		video1.update_rank(video2.rank + 1.0)
		assert_equal(default_room.video_queue(), [video2, video1])
		video2.update_rank(0.0)
		assert_equal(default_room.video_queue(), [video2, video1])
		video1.update_rank(-1.0)
		assert_equal(default_room.video_queue(), [video1, video2])
예제 #40
0
	def test_queue(self):
		default_room = Room(0)
		assert_equal(default_room.video_queue(), [])

		video1 = default_room.add_video(
			"youtube"
			, "http://www.youtube.com/watch?v=Qqd9S06lvH0"
			, "screaming creepers"
			, 28
			, 0)
		video2 = default_room.add_video(
			"youtube"
			, "http://www.youtube.com/watch?v=Wl8AK5Ht65Y"
			, "Oh Bother..."
			, 5
			, 0)

		assert_equal(default_room.video_queue(), [video1, video2])
		video1.remove()
		assert_equal(default_room.video_queue(), [video2])
		video2.remove()
		assert_equal(default_room.video_queue(), [])
예제 #41
0
 def post(self, group_id, room_id):
     Room.get(room_id).delete()
     self.redirect(self.reverse_url('rooms', group_id))
예제 #42
0
 def get(self, group_id, room_id):
     room = Room.get(room_id)
     self.render('room/brainstorming.html', room=room)
예제 #43
0
 def get(self, group_id):
     room_name = self.get_argument('room_name', '')
     rooms = Room.search_name(room_name)
     rooms = [room for room in rooms if room.belongs_to_group(group_id)]
     self.render('room/rooms.html', rooms=rooms, group_id=group_id)
예제 #44
0
 def test_compute_identity(self):
     from models.room import Room
     u1 = MagicMock(id=1)
     u2 = MagicMock(id=2)
     u3 = MagicMock(id=3)
     assert(Room.compute_identity([u1, u2, u3]) == Room.compute_identity([u3, u2, u1]))
예제 #45
0
 def get(self, group_id, room_id):
     room = Room.get(room_id)
     self.render('room/room.html', room=room)