def post(self):
        """Used by the host to create the room."""
        user = users.get_current_user()

        if not user:
            #Handle the user not being logged in. TODO
            return
        
        #Setup tokbox tokens.
        tokbox_session_id = opentok_sdk.create_session().session_id
        tokbox_token = opentok_sdk.generate_token(tokbox_session_id)
        sub_tokbox_token = opentok_sdk.generate_token(tokbox_session_id, OpenTokSDK.RoleConstants.SUBSCRIBER)
        
        #Create the room.
        room_key = user.user_id()
        room = Room(key_name = room_key,
                    current_user = user,
                    session_id = tokbox_session_id,
                    pub_token = tokbox_token,
                    sub_token = sub_tokbox_token
                   )
        room.put()
        
        #Create the channel token.
        token = channel.create_channel(room_key)
        
        #Respond with room information.
        room_data = {'token': token,
                     'tokbox_api_key': tokbox_api_key,
                     'tokbox_session_id': tokbox_session_id,
                     'tokbox_token': tokbox_token,
                     'room_key': room_key,
                     'initial_message': RoomUpdater(room).get_room_message_for_room(),
                    }
        self.response.out.write(json.dumps(room_data))
 def get(self):
     user = users.get_current_user()
     
     #Redirect the user if they aren't logged in.
     if not user:
         self.redirect(users.create_login_url(self.request.uri))
         return
     
     #Setup tokbox tokens.
     tokbox_session_id = opentok_sdk.create_session().session_id
     tokbox_token = opentok_sdk.generate_token(tokbox_session_id)
     sub_tokbox_token = opentok_sdk.generate_token(tokbox_session_id, OpenTokSDK.RoleConstants.SUBSCRIBER)
     
     #Create the room.
     room_key = user.user_id()
     room = Room(key_name = room_key,
                     current_user = user,
                     session_id = tokbox_session_id,
                     pub_token = tokbox_token,
                     sub_token = sub_tokbox_token
                    )
     room.put()
     
     #Display the template.
     token = channel.create_channel(room_key)
     template_values = {'token': token,
                        'tokbox_api_key': tokbox_api_key,
                        'tokbox_session_id': tokbox_session_id,
                        'tokbox_token': tokbox_token,
                        'room_key': room_key,
                        'initial_message': RoomUpdater(room).get_room_message_for_room(),
                        }
     template = jinja_environment.get_template('nav-pub-with-playback.html')
     self.response.out.write(template.render(template_values))
Exemple #3
0
def new_room():
    """Show the new room form. On submit, create and go to the new room."""

    # If no one is logged in, show the anon home page.
    if not g.user:
        return render_template("home-anon.html")

    form = NewRoomForm()

    # If conditional will return true when the form submits a response
    if form.validate_on_submit():
        try:
            if form.password.data:
                room = Room.create(form.id.data,
                                   form.password.data,
                                   is_private=True)
            else:
                room = Room.create(form.id.data)
            db.session.commit()
            return redirect(f"/room/{room.id}")

        except IntegrityError:
            flash("Room Name already taken", "danger")
            return render_template("/room/new-room.html", form=form)

        except:
            flash("Something went wrong. Try again!", "danger")
            return render_template("/room/new-room.html", form=form)

    return render_template("/room/new-room.html", form=form)
Exemple #4
0
def post_ad(state="available"):
    is_available = state == "available"
    if is_available:
        form = AvailableAdForm()
    else:
        form = WantedAdForm()
    form.starting.flags.is_date = True
    if request.method == "GET":
        form.email.data = g.user.email
    if form.validate_on_submit():
        room = Room(user=g.user, is_available=is_available)
        if room.is_available:
            form.room_pref.data = product(form.room_pref.data)
        else:
            form.room_type.data = product(form.room_type.data)
        form.populate_obj(room)
        room.urlname = str(uuid4())[:8]
        db.session.add(room)
        db.session.commit()

        # Search for matching rooms
        rooms_distance = Room.search_rooms(room)
        # Send emails to interested users
        for r, distance in rooms_distance:
            if room.is_available:  # ad poster is looking for a person
                send_email_found_room(r.user, room, distance)
            else:  # ad poster is looking for a room.
                send_email_found_person(r.user, room, distance)

        flash("Your ad has been posted!", category="info")
        return render_template("found.html", room=room, rooms_distance=rooms_distance)
    return render_template("autoform.html", form=form, title="Post a new advertisement", submit="Post ad")
Exemple #5
0
def fillup_db():
    DB['rooms'].append(Room(42, 1, 'closed', 1000))
    DB['rooms'].append(Room(7, 1, 'available', 50))
    DB['rooms'].append(Room(69, 7, 'available', 9000))
    DB['rooms'].append(Room(11, 3, 'closed', 10))

    DB['tenants'].append(Tenant('Neo', 'zz0101', 33, 'M',
                                {
                                    "city": "Zeon",
                                    "street": "Street 255"
                                }, 42))
    DB['tenants'].append(Tenant('Janis', 'bb2222', 40, 'W',
                                {
                                    "city": "Los Angeles",
                                    "street": "Beverly Hills, 90210"
                                }, 7))
    DB['tenants'].append(Tenant('Sherlock', 'cc3333', 51, 'M',
                                {
                                    "city": "London",
                                    "street": "Bakerstreet, 221B"
                                }, 11))

    DB['staff'].append(Staff('Taylor', 'aa1111', 'waiter', 100))
    DB['staff'].append(Staff('Hannibal', 'et0000', 'cook', 1000))
    DB['staff'].append(Staff('Hilton', 'ad1234', 'Administrator', 9000))
Exemple #6
0
def create_house(home_id):
    # create master bed
    session.add(Room(home_id=home_id, name="Master"))

    # create kid bed
    session.add(Room(home_id=home_id, name="Guest Bed"))

    # create kid bed
    session.add(Room(home_id=home_id, name="Kids"))

    # create 16 windows
    for _n in range(16):
        session.add(
            EntryPoint(home_id=home_id,
                       name=f'Window{_n}',
                       type='window',
                       is_open=False))

    # create 3 doors
    for _n in range(3):
        session.add(
            EntryPoint(home_id=home_id,
                       name=f'Door{_n}',
                       type='door',
                       is_open=False))

    session.commit()
Exemple #7
0
def add_care_home():
    form = CareHomeForm(request.form)

    if request.method == 'POST':
        operator = Operator(name=form.operator_name.data,
                            phone=form.phone.data,
                            certification=form.certification.data,
                            license_expiration=form.license_expiration.data)
        address = Address(street=form.address_street.data,
                          city=form.address_city.data,
                          region=form.address_region.data,
                          state='HI',
                          zip=form.address_zip.data,
                          email=form.email.data,
                          operator=operator)
        carehome = CareHome(
            name=form.carehome_name.data,
            type=form.type.data,
            open_rooms=form.open_rooms.data,
            max_rooms=form.private_rooms.data + form.shared_rooms.data,
            patient_gender=form.patient_gender.data,
            patient_max_age=form.patient_age.data,
            private_patients=form.patient_private.data,
            medicaid_patients=form.patient_medicaid.data,
            ssi_patients=form.patient_ssi.data,
            assistive_walking_devices=str(
                form.patient_walking_device.data).replace('[', '').replace(
                    ']', '').replace('\'', ''),
            behavioral_issues_patient=form.patient_behavioral.data,
            dialysis_patient=form.patient_dialysis.data,
            hospice_patient=form.patient_hospice.data,
            insulin_patient=form.patient_insulin.data,
            tube_feed_patient=form.patient_tube_feed.data,
            wounded_patient=form.patient_wounds.data,
            max_weight_patient=form.patient_weight.data,
            case_management_company=form.case_management_company.data,
            previous_experience=form.previous_experience.data,
            subs=form.subs.data,
            open_year=form.carehome_open_year.data,
            notes=form.notes.data,
            operator=operator)
        private_rooms = Room(min_price=form.min_price_private.data,
                             max_price=form.max_price_private.data,
                             amount=form.private_rooms.data,
                             type=Room.Type.PRIVATE,
                             carehome=carehome)
        shared_rooms = Room(min_price=form.min_price_shared.data,
                            max_price=form.max_price_shared.data,
                            amount=form.shared_rooms.data,
                            type=Room.Type.SHARED,
                            carehome=carehome)
        db.session.add(operator)
        db.session.add(address)
        db.session.add(carehome)
        db.session.add(private_rooms)
        db.session.add(shared_rooms)
        db.session.commit()
        flash('Care Home added', 'success')
        return redirect(url_for('care_homes'))
    return render_template('addcarehome.html', form=form)
 def get(self, room_id):
     room = Room(room_id)
     if not room.exists():
         self.redirect('/')
     self.render("views/room.html", video_key=room.get_video_id(),
         user_email=create_signed_value(APPLICATION['cookie_secret'], 'user_email', self.current_user.email),
         user_token=create_signed_value(APPLICATION['cookie_secret'], 'user_token', self.current_user.token))
Exemple #9
0
def createCode(request, roomid):
    newRoom = Room(code=roomid)
    if isExists(roomid):
        return HttpResponse("Error: Room exists")
    else:
        newRoom.save()
        return HttpResponse("Room created")
Exemple #10
0
def room_create(tokenData):
    values = request.get_json()
    user = User.query.filter_by(id=tokenData['userId']).first()
    if user:
        room = Room(name=values['name'],
                    description=values['description'],
                    user_set=str(tokenData['userId']),
                    owner=user.id,
                    avatar_image='')
        db.session.add(room)
        db.session.flush()
        room.room_hash_id = hashlib.md5(
            f'{room.id}{time.time()}'.encode('utf-8')).hexdigest()
        room.user_set = f'{room.user_set},{user.id}' if room.user_set else user.id
        if values['avatarImage']:
            avatartImageList = values['avatarImage'].split(',')
            suffix = avatartImageList[0].split('/')[1].split(';')[0]
            filename = f'room_avatar/{room.room_hash_id}.{suffix}'
            print(filename)
            with open(f'media/{filename}', 'wb') as f:
                f.write(base64.b64decode(avatartImageList[1]))
            room.avatar_image = filename
        user.room_id_set = f'{user.room_id_set},{room.id}' if user.room_id_set else room.id
        db.session.commit()
        return jsonify({
            'data': {
                'room': JSONHelper.model_to_json(room)
            },
            'message': '成功',
            'status': 200
        })
    return jsonify({'data': '', 'message': '失败失败', 'status': 500})
Exemple #11
0
async def create(request: web.Request):
    user: User = await check_authorized(request)
    data = await request.json()
    roomname = data["name"]
    logo = data["logo"]
    if not roomname:
        return web.HTTPBadRequest()
    else:

        if Room.get_or_none(name=roomname, creator=user):
            return web.HTTPConflict()

        with db.atomic():
            default_options = LocationOptions.create()
            room = Room.create(
                name=roomname,
                creator=user,
                default_options=default_options,
            )

            if logo >= 0:
                room.logo_id = logo

            loc = Location.create(room=room, name="start", index=1)
            loc.create_floor()
            PlayerRoom.create(player=user, room=room, role=Role.DM, active_location=loc)
            room.save()
        return web.HTTPOk()
Exemple #12
0
async def patch(request: web.Request):
    user: User = await check_authorized(request)
    data = await request.json()

    creator = request.match_info["creator"]
    roomname = request.match_info["roomname"]

    if creator != user.name:
        return web.HTTPUnauthorized()

    new_name = data.get("name")
    new_logo = data.get("logo")

    if not any([new_name, new_logo]):
        return web.HTTPBadRequest()

    room = Room.get_or_none(name=roomname, creator=user)
    if room is None:
        return web.HTTPBadRequest()

    if new_name:
        if Room.filter(name=new_name, creator=user).count() > 0:
            return web.HTTPBadRequest()

        room.name = new_name

    if new_logo:
        room.logo_id = new_logo

    room.save()
    return web.HTTPOk()
Exemple #13
0
 def register(self, password):
     room = Room()
     room.password = password
     try:
         room.save()
     except:
         return None, False
     return room.id, True
def create_room():
    if request.form:
        r = Room(language=request.form.get('room_language'),room_name=request.form.get('room_name'),invite_only=request.form.get('invite_only','')=='on')
        r.owner_id = current_user.id
        db.session.add(r)
        db.session.commit()
        return redirect("/r/%s"%r.room_name)
    return render_template("admin-pages/create_room.html")
Exemple #15
0
 def add_rooms(self, item):
     rooms = []
     if item['room_kinds']:
         for room_item in item['room_kinds']:
             room = Room(**room_item)
             room.conditions = self.add_conditions(room_item)
             rooms.append(room)
     return rooms
Exemple #16
0
def handlefbrequestcallback(request):
    fp = open( 'tmp.3.log', 'w' ) 
    print >> fp, request
    request_str   = ( request.GET.get('request') )
    request_to    = ( request.GET.get('to') )
    #request_from  = ( request.GET.get('from') )
    request_id    = ( request.GET.get('id') )
    request_from  = request.session['fb_id']
 
    #if request_to:
    #   request_to = int(request_to.encode('ascii'))

    #if request_from:
    #   request_from = int(request_from.encode('ascii'))

    #if request_id:
    #   request_id = int(request_id.encode('ascii'))

    print >> fp, "request id", request_id
    print >> fp, "request string", request_str
    print >> fp, "request to", request_to
    print >> fp, "request from", request_from
    print >> fp, "request fb id", request.session['fb_id']

    try:
    	m_to   = Member.objects.get(fb_id=request_to)
    except: 
	# need to make member    	
        m_to   = Member(fb_id=request_to)
  
    try: 
        m_from = Member.objects.get(fb_id=request_from)
    except:
	# need to make member    	
        m_from = Member(fb_id=request_from)

    # name is set
    gamename = "%s_%s_%s" % ( request_from, request_to, time.asctime(time.gmtime()) ) 
    r = Room(name=gamename)
    r.fb_request_id = request_id
    r.save()

    g = Game(room=r)
    # game name and room name duplicated 
    g.name = gamename
    g.save()

    p = Player(game=g,turn=0)
    p.member = m_from
    p.save()

    # TODO assumes two player game - generalize
    p = Player(game=g,turn=1)
    p.member = m_to
    p.save()

    #return HttpResponseRedirect('requestpage.html')
    return HttpResponseRedirect( reverse('lupalo.views.lupalo') ) # Redirect after POST
 def get(self, room_id):
     room = Room(room_id)
     if not room.exists():
         room.create()
     self.render("views/room.html",
                 video_url='',
                 room_id=room_id,
                 user_email=self.current_user.email,
                 user_token=self.current_user.token)
Exemple #18
0
def rooms():
    if request.method == 'POST':
        room_data = Room(**get_request_data(request))
        if not room_data.validate():
            return json_response({"message": "Room form is invalid"}, 400)

        return room_data.create(db.rooms)
    else:
        return list_all(db.rooms, arguments=request.args)
Exemple #19
0
 def get(self, room_id):
     room = Room(room_id)
     if not room.exists():
         room.create()
     self.render("views/room.html",
                 video_url='',
                 room_id=room_id,
                 user_email=self.current_user.email,
                 user_token=self.current_user.token)
Exemple #20
0
def create_room(request):
    if request.method == "POST":
        form = RoomModelForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            room_inst = Room(**data)
            room_inst.save()

    form = RoomModelForm()
    return render(request, "app1/create_room.html", {"form": form})
Exemple #21
0
def createRoom(request):
	if request.method == "POST":
		req = json.loads(request.body)
		master = Trainer.objects.get(name=req['trainer'])
		new_room = Room(master=master)
		new_room.save()
		response_data = {}
		response_data['msg'] = 'success'
		response_data['channel'] = new_room.id
		return HttpResponse(json.dumps(response_data), content_type="application/json")
Exemple #22
0
def create_room(request, extra_context={}):
	"""
	View for creating a room. Uses a clever combination of PollForm, RoomForm and ChoiceFormSet to achieve
	3-way model creation:
		- PollForm allows the user to specify the question
		- ChoiceFormSet allows the user to specify an arbitrary number of "choices" to go with the question
			(each one represented by its own DB object)
		- RoomForm gives more advanced "tweaks" for the room, for example:
			- period length (how long each period lasts, default is 30)
			- join threshold (the amount of time that a room is in lock mode before a poll begins)
	"""
	if request.method == "POST":
		# if the user has submitted the form, get the data from all three
		poll_form = PollForm(request.POST, request.FILES)
		choice_formset = ChoiceFormSet(request.POST, request.FILES)
		room_form = RoomForm(request.POST, request.FILES)
		
		if poll_form.is_valid() and choice_formset.is_valid() and room_form.is_valid():
			# if all 3 forms are valid, create a new question object and save it
			q = Question(text=poll_form.cleaned_data['question'])
			q.save()
			
			# create a new poll object that points to the question, and save it
			p = Poll(question=q)
			p.save()
			
			# for every choice the user has inputted
			for form in choice_formset.forms:
				# create a new choice object, and point it at the question created earlier
				c = Choice(question=q, text=form.cleaned_data['choice'])
				c.save()
			
			# finally, create the room itself, pointing to the question object, with the creator of the
			# currently logged in user, and the period length & join threshold as specified in the form
			# data.
			r = Room(question=q, opened_by=request.user, controller=request.user,
				period_length=room_form.cleaned_data['period_length'],
				join_threshold=room_form.cleaned_data['join_threshold'])
			r.save()
			
			# redirect the user to their newly created room
			return HttpResponseRedirect(r.get_absolute_url())
	else:
		# if the user has not submitted the form (i.e. wishes to fill the form in)
		# then initialise the 3 forms with no data
		poll_form = PollForm()
		choice_formset = ChoiceFormSet()
		room_form = RoomForm()
	
	# put the forms into a context dictionary (and update that with any extra context we have been given)
	data = {'poll_form': poll_form, 'choice_formset': choice_formset, 'room_form': room_form}
	data.update(extra_context)
	
	# render the page
	return render_to_response('rooms/room_form.html', data, context_instance=RequestContext(request))
Exemple #23
0
def submitRoom(request):
    if request.method == "POST":
        f = RoomForm(request.POST)
        if f.is_valid():
            newRoom = Room(name=request.POST['name'], info=request.POST['info'])
            newRoom.save()
            return HttpResponseRedirect(reverse('juakstore:roomDetail', args=(newRoom.id,)))
        else:
            return render(request, 'juakstore/room_add.html', {'form' : f})
    else:
        return HttpResponseRedirect(reverse('juakstore:roomCreate'))
Exemple #24
0
    def get(self):
        user = users.get_current_user()

        if user:
            room_key = self.request.get('g')
            if not room_key:
                room_key = user.user_id()
                room = Room(key_name = room_key,
                            current_user = user)
                room.put()
            else:
                if room_key == "vr":
                    self.redirect("/vr-room")
                    return
                if room_key == "demo":
                    self.redirect("/demo")
                    return
                room = Room.get_by_key_name(room_key)

            if room:
                #Check if the crowdee already exists for this user and room.
                crowdeeQuery = Crowdee.all()
                crowdeeQuery.filter("user ="******"room =", room_key)
                crowdee = crowdeeQuery.get()
                #If the crowdee doesn't exist...
                if not crowdee:
                    #Create the crowdee for the user and room.
                    crowdee = Crowdee(user = user,
                                      room = room_key,
                                      channel = room_key + "_" + user.user_id(),
                                      direction = "None",
                                      weight = 1)
                    crowdee.put()
                
                token = channel.create_channel(room_key + "_" + user.user_id())
                template_values = {'token': token,
                                   'current_user_id': user.user_id(),
                                   'room_key': room_key,
                                   'weight': 1,
                                   'initial_message': RoomUpdater(room).get_room_message()
                                   }
                #Add tokbox tokens if they exist.
                if room.session_id:
                    template_values.update({'tokbox_api_key': tokbox_api_key,
                                            'tokbox_session_id': room.session_id,
                                            'tokbox_token': room.sub_token
                                           })
                template = jinja_environment.get_template('nav-room-base.html')
                self.response.out.write(template.render(template_values))
            else:
                self.response.out.write('No such room')
        else:
            self.redirect(users.create_login_url(self.request.uri))
Exemple #25
0
def add_new_room(user_id):  
    body = request.get_json()
    if body is None:
        raise APIException("You need to specify the request body as a json object", status_code=400)
    if 'name_room' not in body:
        raise APIException('You need to specify the name room', status_code=400)

    new_room = Room(name_room=body['name_room'], id_user= user_id)
    new_room.create()

    return jsonify({'status': 'OK', 'message': 'Room Added succesfully'}), 201
Exemple #26
0
def create_room(db: SessionClass, user_name, room_name):
    with session_manager(db) as session:
        room = Room(name=room_name)
        session.add(room)
        session.commit()
        user = User(name=user_name, room_id=room.id)
        session.add(user)
        session.commit()
        room.host_user_id = user.id
        session.commit()
        return {'user': user, 'room': room}
Exemple #27
0
def create_room():
    rc = generate_room_code()
    host = str(request.json["name"])
    gameState = 0
    data = [rc, host]
    new_room = Room(id=rc, host=host)
    new_player = Player(id=rc, name=host)

    db.session.add(new_player)
    db.session.add(new_room)
    db.session.commit()
    return jsonify(new_room.serialize())
Exemple #28
0
    def run(self):
        from setup import db, db_session, engine, app
        from models import Room, User

        models.PSABase.metadata.create_all(engine)
        db.create_all()
        db_session.commit()

        db_session.add(Room(name='Glass Room 1', reservable=True))
        db_session.add(Room(name='Glass Room 2', reservable=False))
        db_session.add(User(id=app.config['SUDO_USERID'], admin=True))
        db_session.commit()
Exemple #29
0
	def post(self):

		user = users.get_current_user()

		if user is None:
			login_url = users.create_login_url('/home')

			template_data = {}
			template_data['login_url'] = login_url

			template = JINJA_ENVIRONMENT.get_template('login.html')
			self.response.write(template.render(template_data))
			return

		residence = Residence.get_residence_by_user(user)

		category = self.request.get('category')
		name = self.request.get('name')
		price = self.request.get('price')


		room_name = self.request.get("room")

		if name.strip() == '' or category.strip() == '':
			if room_name == "miscellaneous":
				self.redirect("home")
			else:
				self.redirect("/room-tour?room=" + urllib.quote(room_name))
			return

		price = float(price)

		inventory = Inventory.get_inventory_by_user(user)
		item = Item(category=category, name=name, price=price, parent=inventory.key)
		item.put()


		residence = Residence.get_residence_by_user(user)
		room = Room.query(ancestor=residence.key).filter(Room.name==room_name).get()
		if room is None:
			room = Room(name=room_name, parent=residence.key)
			room.put()
		
		relation = ItemRoomRelation(item=item.key, room=room.key, parent=inventory.key)
		relation.put()

		if room_name == "miscellaneous":
			self.redirect("/home")
			return



		self.redirect("/room-tour?room=" + urllib.quote(room_name))
Exemple #30
0
	def get(self):

		user = users.get_current_user()

		if user is None:
			login_url = users.create_login_url('/welcome')
			self.response.write('<html><body>{}</body></html>'.format('<a href="' + login_url + '">Sign in</a>'))
			return

		residence = Residence.get_residence_by_user(user)
		inventory = Inventory.get_inventory_by_user(user)

		other_homes = Residence.query(Residence.own==residence.own).fetch()

		logging.error(other_homes)

		rooms = []
		for home in other_homes:
			rooms += Room.query(ancestor=home.key).filter(Room.name!="miscellaneous").fetch()

		room_count = {}
		for room in rooms:
			name = room.name
			if name in room_count:
				room_count[name] += 1
				continue
			room_count[name] = 1

		room_count_final = {}
		for room in room_count:
			my_count = Room.query(ancestor=residence.key).filter(Room.name==room).count()

			if my_count == 0:
				room_count_final[str(room)] = ("", room_count[room] / max(len(other_homes), 1))
			else:
				up_count = str(my_count + 1)
				my_tail = ""
				if up_count[-1:] in ["0", "4", "5", "6", "7", "8", "9"]:
					my_tail = "th"
				elif up_count[-1:] in ["2"]:
					my_tail = "nd"
				elif up_count[-1:] in ["1"]:
					my_tail = "st"
				elif up_count[-1:] in ["3"]:
					my_tail = "rd"
				room_count_final[str(room)] = (" (" + up_count + my_tail + ")", room_count[room] / max(len(other_homes), 1) - 2 * my_count)
		
		room_count_final = sorted(room_count_final.items(), key=lambda x: x[1][1], reverse=True)

		template = JINJA_ENVIRONMENT.get_template('tourRoomPage.html')
		template_data = {'rooms': room_count_final}

		self.response.write(template.render(template_data))
Exemple #31
0
 def get(self, room_id):
     room = Room(room_id)
     if not room.exists():
         self.redirect('/')
     self.render(
         "views/room.html",
         video_key=room.get_video_id(),
         user_email=create_signed_value(APPLICATION['cookie_secret'],
                                        'user_email',
                                        self.current_user.email),
         user_token=create_signed_value(APPLICATION['cookie_secret'],
                                        'user_token',
                                        self.current_user.token))
Exemple #32
0
def makerobogame(request):
  
    fb_id = ROBOT1
    request.session['fb_id'] = fb_id
 
    # make robot player 1
    try:
        m_from = Member.objects.get( fb_id=ROBOT1 )
    except Member.DoesNotExist:
        m_from   = Member(fb_id=ROBOT1)
        m_from.user_name     =  'Robo1'
        m_from.fb_first_name =  'Robo1'
        m_from.fb_last_name  =  'Robo1'
        m_from.save()
    # make robot player 2
    try:
        m_to = Member.objects.get( fb_id=ROBOT2 )
    except Member.DoesNotExist:
        m_to   = Member(fb_id=ROBOT2)
        m_to.user_name     =  'Robo2'
        m_to.fb_first_name =  'Robo2'
        m_to.fb_last_name  =  'Robo2'
        m_to.save()

    # name is set
    request_from = 'Robo1'
    request_to   = 'Robo2'
    gamename = "%s_%s_%s" % ( request_from, request_to, time.asctime(time.gmtime()) ) 
    r = Room(name=gamename)
    r.fb_request_id = ROBOREQUEST
    r.save()

    g = Game(room=r)
    # game name and room name duplicated 
    g.name = gamename
    g.save()

    p = Player(member=m_from)  # player in game, link to member 
    p.game=g		       # game 
    p.turn=0                   # static order of player in game
    p.save()

    request.session['player_id'] = p.turn

    # TODO assumes two player game - generalize
    p = Player( member = m_to )
    p.game=g
    p.turn=1
    p.save()

    return HttpResponse( simplejson.dumps( { "gamename": gamename } ), mimetype='application/javascript' )
def optionnal_room(sender, **kwargs):
    reservation = kwargs.pop('instance')

    if not isinstance(reservation, Reservation):
        return True
    if not reservation.room:
        try:
            room = Room._default_manager.get(name='default')
        except Room.DoesNotExist:
            room = Room(name='default', slug='default')
            room.save()

        reservation.room = room
    return True
def optionnal_room(sender, **kwargs):
    reservation = kwargs.pop('instance')
        
    if not isinstance(reservation, Reservation):
        return True
    if not reservation.room:
        try:
            room = Room._default_manager.get(name='default')
        except Room.DoesNotExist:
            room = Room(name='default', slug='default')
            room.save()

        reservation.room = room
    return True
def on_join(data):
    log.info("JOIN:%s - %s" % (data, request.sid))
    try:
        user = User.query.filter_by(id=current_user.id).first()
    except:
        user = None

    username = data['username']
    room_name = data['room']
    if not user:
        active_room_users = []
        room = Room(room_name=room_name)
    else:
        room = Room.query.filter_by(room_name=room_name).first()
        if not room:
            disconnect()
        # if hasattr(current_user,'id') and isinstance(current_user._get_current_object(),User):
        current_user.sid = request.sid
        #     User.query.filter_by(id=current_user.id).update(dict(sid = request.sid))
        #     db.session.commit()
        if room.invite_only:
            if current_user.is_anonymous:
                disconnect()
            username = current_user.nickname
            try:
                user = User.query.filter_by(id=current_user.id).first()
            except:
                user = None
            if not user:
                invite = Invites.get_my_invitation()
                user = invite.to_user()
            user.sid = request.sid
            db.session.commit()
            if room.invite_only and not room.verify_allowed():
                print("User %s is not invited to room %s" %
                      (current_user, room))
                disconnect()
        active_room_users = ActiveUsers.get_room_users(room.room_name)

    join_room(room.room_name)
    # print("C:",current_user)
    if not user or current_user.is_anonymous:
        ActiveUsers.join_room(
            room_name
        )  #,{'username':username,'id':random.choice(string.ascii_uppercase),"sid":request.sid,"is_AFK":False})

    else:
        ActiveUsers.join_room(room_name)  #,current_user.to_dict())
    request_sync({'room_details': data})
    emit2('user_joined', {'username': username}, room=room_name)
Exemple #36
0
def assign_room(request):
    if request.POST:
        user = request.POST['user']
        rn = request.POST['rno']
        sd = request.POST['sd']
        ed = request.POST['ed']
        r = Room(user_id=user,
                 r_id=uuid.uuid4(),
                 room_no=rn,
                 start_date=sd,
                 end_date=ed,
                 available=False)
        r.save()
        return render_to_response('roomcreatesuccess.html')
Exemple #37
0
    def get(self, obj_id=None):
        """
        Gets room(s).
        Returns all rooms if no obj_id is passed
        ---
        tags:
          - rooms
        parameters:
          - in: path
            name: obj_id
        definitions:
          - schema:
              id: Room
              required:
                - number
              optional:
                - is_booked
              properties:
                number:
                  type: string
                  description: the room's number
        responses:
          200:
            description: Returns the specified room or a list of rooms
            $ref: '#/definitions/Room'
        """
        if not obj_id:
            query = Room.query().fetch()
            output = self.output_fields
            output.update(self.resource_fields)

            resp = {
                'results': marshal(query, output),
                'count': len(query)
            }

            return resp, 200

        try:
            room = Room.get_by_id(int(obj_id))

            if not room:
                abort(404, message="Room with key ({}) not found".format(obj_id))

            output = self.output_fields
            output.update(self.resource_fields)
            return marshal(room, output), 200
        except Exception:
            abort(404, message="Room with key ({}) not found".format(obj_id))
Exemple #38
0
def _save_room(cd):
    room = Room()
    room.id = cd['id'] or None
    room.number = cd['number']
    room.description = cd['description']
    room.syndic = cd['syndic']
    room.save()
    return room
Exemple #39
0
def table_ins():
    requestJson = request.get_json(force=True)
    #if ('roomtype' in list(requestJson.keys()) and requestJson['roomtype'] is not None):
        #roomType = RoomType.query.filter_by(id=requestJson['roomtype'])
        #if (roomType is not None):
            #for key in Room.__table__.columns.keys():
                #if (key not in list(requestJson.keys()) and key != "guid"):
                    #requestJson[key] = roomType[key]
    if ('pricechd' not in list(requestJson.keys())):
        requestJson['pricechd'] = requestJson['price']
    item = Room(**requestJson)
    item.guid = item.guid or uuid.uuid4()
    db.session.add(item)
    db.session.commit()
    return dataResultSuccess(item.to_dict(), code=201, spuriousParameters=list(request.args.to_dict().keys()))
Exemple #40
0
 def post(self):
     channel_token = self.request.get('from')
     user_crowd = Crowdee.all().filter("channel =", channel_token)
     #Although there should only be one user, it will still be received as a list.
     for user_crowdee in user_crowd:
         room = Room.get_by_key_name(user_crowdee.room)
         user_id = user_crowdee.user.user_id()
         user_crowdee.delete()
         if room:
             RoomUpdater(room).delete_move(user_id)
     room_list = Room.all()
     for room in room_list:
         if room.key().name() == channel_token:
             room.active = False
             room.put()
Exemple #41
0
    def test_get_messages(self, *args, **kwargs):
        username, password = self.username, self.userpwd

        # login user
        client = Client()
        client.login(username=username, password=password)

        # creates a room
        room = Room()
        room.save()

        # message queue empty: check last_message_id
        response = client.get('/chat/get_latest_msg_id/?room_id=%d' % room.id)
        json_response = json.loads(response.content)
        last_msg_id = json_response['id']
        self.assertEquals(last_msg_id, -1)

        # posts a message
        post_response = client.post('/chat/send_message/', {
            'room_id': room.pk,
            'message': 'ABCD'
        },
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEquals(post_response.status_code, 200)
        json_response = json.loads(post_response.content)
        timestamp = json_response['timestamp']

        # gets list of messages
        response = client.get(
            '/chat/get_messages/?room_id=%d&latest_message_id=%d' %
            (room.id, last_msg_id),
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEquals(response.status_code, 200)
        json_response = json.loads(response.content)

        expected_json = [{
            u'message_id': 1,
            u'username': u'john',
            u'date': timestamp,
            u'content': u'ABCD',
        }]
        self.assertEquals(expected_json, json_response)

        # check last_message_id
        response = client.get('/chat/get_latest_msg_id/?room_id=%d' % room.id)
        json_response = json.loads(response.content)
        last_msg_id = json_response['id']
        self.assertEquals(last_msg_id, 1)
Exemple #42
0
def start_game(room_code):
    sessid = request.cookies.get("sessid")
    room = Room.select(Room).join(Player, on=Room.owner).where(Player.sessid == sessid, Room.code == room_code).get()
    init_game(room)
    message_data = {"url": "/game/%s" % room_code}
    post_message([Msg("start", message_data)], room=room)
    return redirect("/game/%s" % room_code)
Exemple #43
0
	def get(self):

		items = Item.query().fetch()
		rooms = Room.query().fetch()
		relations = ItemRoomRelation.query().fetch()

		item_dicts = []
		for item in items:
			item_data = {}
			item_data["name"] = item.name
			item_data["category"] = item.category
			item_data["price"] = item.price
			item_data["encoded"] = urllib.quote(item.name)
			item_dicts.append(item_data)

		room_dicts = []
		for room in rooms:
			room_data = {}
			room_data["name"] = room.name
			room_dicts.append(room_data)

		template_data = {}
		template_data['items'] = item_dicts
		template_data['rooms'] = room_dicts
		template_data['relations'] = relations


		template = JINJA_ENVIRONMENT.get_template('admin.html')
		self.response.write(template.render(template_data))
 def get(self):
     tenant_key = self.request.get('tenant_key')
     tenant = Tenant.get(tenant_key)
     room = Room()
     vacantRooms=room.getVacantRooms()
     if vacantRooms:            
         tenant_data_list = tenant.getTenantProfile()
         rooms_data_list = room.getRoomsProfile(vacantRooms)
         data_list = []
         data_list.append({'tenantProfile': tenant_data_list, 'roomsProfile': rooms_data_list})
         output_json = json.dumps(data_list) 
         self.response.out.write(output_json)                              
     else:
         noVacancyResponse = {'noVacancyResponse':'Sorry, All rooms are occupied!'}
         noVacancyResponse_json = simplejson.dumps(noVacancyResponse)
         return self.response.out.write(noVacancyResponse_json) 
 def post(self, request, *args, **kwargs):
     '''
     Create room
     '''
     user = fetch_user(request)
     room = Room.create_by(user).save()
     return OKResponse(room.to_dict())
Exemple #46
0
async def clone_location(sid: str, data: LocationCloneData):
    pr: PlayerRoom = game_state.get(sid)
    if pr.role != Role.DM:
        logger.warning(f"{pr.player.name} attempted to clone locations.")
        return
    try:
        room = Room.select().where((Room.name == data["room"])
                                   & (Room.creator == pr.player))[0]
    except IndexError:
        logger.warning(f"Destination room {data['room']} not found.")
        return

    src_location = Location.get_by_id(data["location"])
    new_location = Location.create(room=room,
                                   name=src_location.name,
                                   index=room.locations.count())

    new_groups = {}

    for prev_floor in src_location.floors.order_by(Floor.index):
        new_floor = new_location.create_floor(prev_floor.name)
        for prev_layer in prev_floor.layers:
            new_layer = new_floor.layers.where(
                Layer.name == prev_layer.name).get()
            for src_shape in prev_layer.shapes:
                new_group = None
                if src_shape.group:
                    group_id = src_shape.group.uuid
                    if group_id not in new_groups:
                        new_groups[group_id] = src_shape.group.make_copy()
                    new_group = new_groups[group_id]

                src_shape.make_copy(new_layer, new_group)
Exemple #47
0
def query_rooms():
    '''returns each room and its availability status'''
    response = []

    # loop through the rooms
    rooms = Room.get_all()

    if rooms:
        for r in rooms:
            # get current day/time stuff
            current_day = datetime.datetime.now().strftime('%A').lower()
            current_time = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M')

            # get room use times
            room_times = Timetable.get_by_room_id(r.room_id)

            # determine usage
            use_flag = True
            for t in room_times:
                if t.day == current_day:
                    if (current_time >= t.start_time) and (current_time <= t.end_time):
                        use_flag = False
            response.append({"room_id": r.room_id, "room_number": r.room_number, "available": use_flag})
    else:
        response.append({})
    return response
 def put(self, request, roomId, memberId, *args, **kwargs):
     user = fetch_user(request)
     if memberId != user.strId:
         return errors.PERMISSION_DENIED
     room = Room.find_by_id(str(roomId)).raise_if_cannot_join(user)
     user.enter_room(room).save()
     return OKResponse()
Exemple #49
0
 def post(self):
     channel_token = self.request.get('from')
     room_list = Room.all()
     for room in room_list:
         if room.current_user.user_id() == channel_token:
             room.active = True
             room.put()
Exemple #50
0
async def claim_invite(request):
    user = await check_authorized(request)
    data = await request.json()
    room = Room.get_or_none(invitation_code=data["code"])
    if room is None:
        return web.HTTPNotFound()
    else:
        if user != room.creator and not PlayerRoom.get_or_none(player=user,
                                                               room=room):
            query = PlayerRoom.select().where(PlayerRoom.room == room)
            try:
                loc = query.where(
                    PlayerRoom.role == Role.PLAYER)[0].active_location
            except IndexError:
                loc = query.where(
                    PlayerRoom.role == Role.DM)[0].active_location
            PlayerRoom.create(player=user,
                              room=room,
                              role=Role.PLAYER,
                              active_location=loc)

            for csid in game_state.get_sids(player=room.creator, room=room):
                await sio.emit(
                    "Room.Info.Players.Add",
                    {
                        "id": user.id,
                        "name": user.name
                    },
                    room=csid,
                    namespace="/planarally",
                )
        return web.json_response({
            "sessionUrl":
            f"/game/{urllib.parse.quote(room.creator.name, safe='')}/{urllib.parse.quote(room.name, safe='')}"
        })
Exemple #51
0
 def __init__(self, request):
     user = users.get_current_user()
     room_key = request.get('room_id')
     if not room_key:
         room_key = request.get('g') #TODO - Remove with old page
     if user and room_key:
         self.room = Room.get_by_key_name(room_key)
Exemple #52
0
def Adm_room_POST(rev_json):
    """
    处理Adm_room的POST请求
    :param rev_json: 接收到的json数据
    :return: 需要发送给前端的数据
    """
    # 获取参数
    building = rev_json.get('building')
    floor = rev_json.get('floor')
    org = rev_json.get('org')
    room_name = rev_json.get('room_name')
    picture = rev_json.get('picture')
    max_num = rev_json.get('max_num')
    description = rev_json.get('description')
    permissible = True if rev_json.get('permission') != 0 else False
    # 验证必需参数
    if None in (building, floor, room_name, max_num, permissible):
        return jsonify(code=-101, data={'tip': '缺少必要参数'})

    newRoom = Room(building=building,
                   floor=floor,
                   org=org,
                   room_name=room_name,
                   picture=picture,
                   max_num=max_num,
                   description=description,
                   permissible=permissible)
    db.session.add(newRoom)
    try:
        db.session.commit()
    except:
        db.session.rollback()
    return jsonify(data={'tip': '教室添加成功'})
Exemple #53
0
def index():
    form = SearchForm()

    if form.validate_on_submit():
        room = Room()
        form.populate_obj(room)

        # Change room_pref and room_type if they are None
        if not room.room_pref:
            room.room_pref = 0 if room.is_available else 1
        if not room.room_type:
            room.room_type = 1 if room.is_available else 0

        # Search for matching rooms
        rooms_distance = Room.search_rooms(room)
        return render_template("found.html", rooms_distance=rooms_distance)
    return render_template("autoform.html", form=form, title="Search Acco.", submit="Search ad")
Exemple #54
0
 def get(self):
     #self.response.out.write("400")
     room = Room.all()
     direction = "None"
     for s in room:
         if(s.direction):
             direction = s.direction
     self.response.out.write(direction)
 def get(self):
     room_key = self.request.get('room_key')
     room = Room.get(room_key)
     data_list = []
     #data_list = room.getRoomProfile()
     data_list.append({'roomNumber':room.roomNumber,'area':room.area,'rentSingle':room.rentSingle,'rentDouble':room.rentDouble})
     output_json = json.dumps(data_list)
     self.response.out.write(output_json) 
 def post(self, request, *args, **kwargs):
     """
     Create room
     """
     user = fetch_user(request)
     room = Room.create_by(user).save()
     user.enter_room(room).save()
     return OKResponse(room.to_dict())
 def delete(self, request, roomId, memberId, *args, **kwargs):
     user = fetch_user(request)
     if memberId != user.strId:
         return errors.PERMISSION_DENIED
     room = Room.find_by_id(str(roomId))
     user.exit_room(room).save()
     room.destroy_if_created_by(user)
     return OKResponse()
Exemple #58
0
    def test_anonymous_access(self):
        anon_room = Room(
                        allow_anonymous_access=True,
                        name="Anonymous Room",
                        slug="anonymous-room")
        login_req_room = Room(
                        allow_anonymous_access=False,
                        name="Login required room",
                        slug="login-required-room")
        anon_room.save()
        login_req_room.save()

        client = Client()

        response = client.get(login_req_room.get_absolute_url())
        # a login view may not have been implemented, so assertRedirects fails
        self.assertEquals(response.status_code, 302)
        url = response['Location']
        expected_url = get_login_url(login_req_room.get_absolute_url())
        e_scheme, e_netloc, e_path, e_query, e_fragment = urlparse.urlsplit(
                                                                expected_url)
        if not (e_scheme or e_netloc):
            expected_url = urlparse.urlunsplit(('http', 'testserver', e_path,
                e_query, e_fragment))
        self.assertEquals(url, expected_url)

        response = client.get(
            anon_room.get_absolute_url(),
            follow=True)

        # assert redirect
        self.assertRedirects(
            response,
            'http://testserver/chat/setguestname/?room_slug=anonymous-room')

        # post guestname
        guestname_posted = client.post(
            response.redirect_chain[0][0],
            {'guest_name': 'guest',
             'room_slug': 'anonymous-room'},
            follow=True)
        self.assertRedirects(
            guestname_posted,
            anon_room.get_absolute_url()
        )
Exemple #59
0
    def test_get_messages(self, *args, **kwargs):
        username, password = self.username, self.userpwd

        # login user
        client = Client()
        client.login(username=username, password=password)

        # creates a room
        room = Room()
        room.save()

        # message queue empty: check last_message_id
        response = client.get('/chat/get_latest_msg_id/?room_id=%d' % room.id)
        json_response = json.loads(response.content)
        last_msg_id = json_response['id']
        self.assertEquals(last_msg_id, -1)

        # posts a message
        post_response = client.post('/chat/send_message/',
                                {'room_id': room.pk,
                                 'message': 'ABCD'},
                HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEquals(post_response.status_code, 200)
        json_response = json.loads(post_response.content)
        timestamp = json_response['timestamp']

        # gets list of messages
        response = client.get(
            '/chat/get_messages/?room_id=%d&latest_message_id=%d' % (
                                                room.id, last_msg_id),
                HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEquals(response.status_code, 200)
        json_response = json.loads(response.content)

        expected_json = [{u'message_id': 1,
                          u'username': u'john',
                          u'date': timestamp,
                          u'content': u'ABCD', }]
        self.assertEquals(expected_json, json_response)

        # check last_message_id
        response = client.get('/chat/get_latest_msg_id/?room_id=%d' % room.id)
        json_response = json.loads(response.content)
        last_msg_id = json_response['id']
        self.assertEquals(last_msg_id, 1)