def chat(msg, methods=["POST"]): # print("here") try: message = DirectMessage( body=msg["body"], message_read=msg["message_read"], sender_id=msg["sender_id"], recipient_id=msg["recipient_id"], created_at=msg["time"], ) # msg['created_at'] = time logger.info(msg["recipient_id"]) socketio.emit(msg["recipient_id"], json.loads(message.to_json())) except Exception as e: # msg="Invalid parameter provided" logger.info(e) return create_response(status=500, message="Failed to send message") try: message.save() msg = "successfully sent message" except: msg = "Error in meessage" logger.info(msg) return create_response(status=500, message="Failed to send message") return create_response(status=200, message="successfully sent message")
def invite(msg, methods=["POST"]): print("inisdede new created inivte cintrlloererer") try: # msg['created_at'] = time logger.info(msg["recipient_id"]) inviteObject = { "inviteeId": msg["sender_id"], "allowBooking": "true", } socketio.emit(msg["recipient_id"], inviteObject) except Exception as e: # msg="Invalid parameter provided" logger.info(e) return create_response(status=500, message="Failed to send invite") try: mentee = MenteeProfile.objects.get(id=msg["recipient_id"]) if msg["sender_id"] not in mentee.favorite_mentors_ids: mentee.favorite_mentors_ids.append(msg["sender_id"]) mentee.save() except Exception as e: msg = "Failed to saved mentor as favorite" logger.info(e) return create_response(status=422, message=msg) return create_response(status=200, message="successfully sent invite")
def insert(): """Insert a visit""" form = VisitForm() if not form.validate(): return jsonify(errors=form.errors), 400 # Get location based on token hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() visit = Visit(request.form.get('start_time'), request.form.get('end_time'), location.id) db.session.add(visit) socketio.emit('visit', {'data': loads(dumps(visit.serialize()))}, broadcast=True) # Recalculate average location.calculate_average() db.session.commit() return jsonify(), 201, {'Location': '/visits/' + str(visit.id)}
def create_message(): data = request.get_json() try: message = DirectMessage( body=data["message"], message_read=False, sender_id=data["user_id"], recipient_id=data["recipient_id"], created_at=data.get("time"), ) except Exception as e: msg = "Invalid parameter provided" logger.info(e) return create_response(status=422, message=msg) try: message.save() except: msg = "Failed to save message" logger.info(msg) return create_response(status=422, message=msg) socketio.emit(data["recipient_id"], json.loads(message.to_json())) return create_response( status=201, message=f"Successfully saved message", )
def end_signaling(section_id): print('end-signalling') socketio.emit('signalling-message', { 'sender': 'Signalling server', 'message': 'Ended signalling with id %s' % str(request.sid) }, room=section_id) leave_room(section_id)
def emit_timer(self, seconds): count = 0 while count != seconds: socketio.emit('timer', seconds, namespace='/timer') seconds -= 1 time.sleep(1) time.sleep(1) socketio.emit('timer', "", namespace='/timer')
def kafkaproducer(message): producer = KafkaProducer(bootstrap_servers=BOOTSTRAP_SERVERS) producer.send(TOPIC_NAME, value=bytes(str(message), encoding='utf-8'), key=bytes(str(uuid.uuid4()), encoding='utf-8')) socketio.emit('logs', {'data': 'Added ' + message + ' to topic'}) socketio.emit('kafkaproducer', {'data': message}) producer.close() kafkaconsumer(message)
def sendWeightToClient(): while not scale_stop_event.isSet(): weight = get_hx_weight() socketio.emit('scale_update', weight, namespace='/scale') hx.power_down() hx.power_up() socketio.sleep(.5)
def contact_mentor(mentor_id): data = request.get_json() if "mentee_id" not in data: return create_response(status=422, message="missing mentee_id") mentee_id = data["mentee_id"] try: mentor = MentorProfile.objects.get(id=mentor_id) mentee = MenteeProfile.objects.get(id=mentee_id) except: msg = "Could not find mentor or mentee for given ids" return create_response(status=422, message=msg) res, res_msg = send_email( mentor.email, data={ "response_email": mentee.email, "interest_areas": data.get("interest_areas", ""), "communication_method": data.get("communication_method", ""), "message": data.get("message", ""), "name": mentee.name, }, template_id=MENTOR_CONTACT_ME, ) if not res: msg = "Failed to send mentee email " + res_msg logger.info(msg) return create_response(status=500, message="Failed to send message") try: message = DirectMessage( body=data.get("message", "Hello"), message_read=False, sender_id=mentee_id, recipient_id=mentor_id, created_at=datetime.today().isoformat(), ) socketio.emit(mentor_id, json.loads(message.to_json())) except Exception as e: msg = "Invalid parameter provided" logger.info(e) return create_response(status=422, message=msg) try: message.save() except: msg = "Failed to save message" logger.info(msg) return create_response(status=422, message=msg) return create_response(status=200, message="successfully sent email message")
def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', {'data': loads(dumps(location.serialize()))}, broadcast=True) return jsonify(), 204
def kafkaconsumer(message): consumer = KafkaConsumer(group_id='group-a', bootstrap_servers=BOOTSTRAP_SERVERS) tp = TopicPartition(TOPIC_NAME, 0) # register to the topic consumer.assign([tp]) # obtain the last offset value consumer.seek_to_end(tp) lastOffset = consumer.position(tp) consumer.seek_to_beginning(tp) socketio.emit('kafkaconsumer1', {'data': ''}) for message in consumer: socketio.emit('kafkaconsumer', {'data': message.value.decode('utf-8')}) if message.offset == lastOffset - 1: break consumer.close()
def realtime_request(data): if sections.get(data['section']): socketio.emit('data-request', { 'sender': str(request.sid), 'message': data['message'], 'sensor': data['sensor'] }, room=sections[data['section']]) else: socketio.emit( 'application-alert', { 'type': 'danger', 'message': 'Section %s alternative not reachable' % data['section'] }, room=str(request.sid)) print('Section not reachable')
def post(self): """ On a post request on the /form endpoint we add the consent form to the database :return: If the request is valid, a 200 status code, otherwise a 400 code """ validators = { 'parent': valid.validate_person_data, 'children': valid.validate_children_data, 'signature': valid.validate_signature, 'email': valid.validate_email } data = valid.validate(valid.read_form_data(request), validators) if not data: return ANSWERS[400], 400 parent = data['parent'] signature = data['signature'] if not current_app.config['TESTING']: upload_result = upload(signature, folder="signatures") signature = upload_result["secure_url"] cons = Consent.create_consent(parent_first_name=parent['firstName'], parent_last_name=parent['lastName'], signature=signature, email=data['email']) for child in data['children']: participant = Participant(first_name=child['firstName'], last_name=child['lastName'], consent_id=cons.id) add_to_db(participant) obj = { "firstName": participant.first_name, "lastName": participant.last_name, "id": participant.id } red.rpush("queue", str(obj)) socketio.emit("free-laptops") return ANSWERS[200], 200
def connect(): if request.args.get('token') is not None: user = User.verify_auth_token(request.args.get('token')) if user is not None: print('User %s connected with id: %s' % (user.username, str(request.sid))) users[user.username] = request.sid socketio.emit('application-message', 'Connected with id: %s' % str(request.sid), room=str(request.sid)) else: print('Expired token') # return False TODO: it needs to be changed elif request.args.get('section_id') is not None: section = Section.query.get(request.args.get('section_id')) if section is not None: print('Section %s from garden %s connected with id: %s' % (section.id, section.garden, str(request.sid))) sections[section.id] = request.sid socketio.emit('application-message', 'Connected with id: %s' % str(request.sid), room=str(request.sid)) join_room(section.id) # connect to a room to receive calls else: print('Section not found') return False elif request.args.get('section_id_alt') is not None: section_alt = Section.query.get(request.args.get('section_id_alt')) if section_alt is not None: print( 'Section %s alternative from garden %s connected with id: %s' % (section_alt.id, section_alt.garden, str(request.sid))) sections[str(section_alt.id) + '+'] = request.sid socketio.emit('application-message', 'Connected with id: %s' % str(request.sid)) else: print('Section not found') return False else: print('Connection rejected') return False
def start_signaling(section_id): if sections.get(section_id): print('Calling to section %s' % section_id) join_room( section_id) #join to room with section to exchange signaling data socketio.emit('application-alert', { 'type': 'success', 'message': 'Room with section %s opened' % section_id }, room=str(request.sid)) socketio.emit('signalling-message', { 'sender': 'Signalling server', 'message': 'Call exchange channel opened' }, room=section_id) else: socketio.emit('application-alert', { 'type': 'danger', 'message': 'Section %s not reachable' % section_id }, room=str(request.sid)) print('Section not reachable')
def emit_pour_data(self): while not self.event.isSet(): data = self.update_pour_data() socketio.emit('pour_update', data, namespace='/pour') socketio.sleep(.2)
def sendPourDataToClient(): while not pour_stop_event.isSet(): socketio.emit('pour_update', data, namespace='/pour') socketio.sleep(.5)
def sendTempToClient(): while not scale_stop_event.isSet(): temp = get_tempsensor() socketio.emit('temp_update', temp, namespace='/temp') socketio.sleep(.5)
def realtime_response(data): socketio.emit('data-response', { 'sender': data['sender'], 'message': data['message'] }, room=data['receiver'])
def test_connect(): socketio.emit('logs', {'data': 'Connection established'})
def signalling(data): socketio.emit('signalling-message', { 'sender': str(request.sid), 'message': data['message'] }, room=data['room'])