Beispiel #1
0
def on_join_jobs(data):
    """
    Somebody joined a room
    """
    room = data['room']
    join_room(room)
    flask.session['room'] = room
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    global names
    room = session.get('name')
    if room == 'EndOfFile':
        contest_names = copy.deepcopy(names)
        winner = random.choice(contest_names.keys())
        contest_names[winner] = True
        for name in contest_names:
            if contest_names[name]:
                emit('message', {'msg': 'You are the winner!'}, room=name)
            else:
                emit('message', {'msg': 'Sorry!  Better luck next time!'}, room=name)
        fh = open('output.txt', 'a')
        fh.write("\n########   WINNER: {}!   ########\n".format(winner))
        fh.close()
    else:
        names[room] = False
        join_room(room)

        fh = open('output.txt', 'w')
        for name in sorted(names):
            fh.write("{}\n".format(name))
        fh.close()
Beispiel #3
0
def search_room(message):
    #need user
    # TODO refact
    user_name = 'Andrew'
    dragon = message['dragon']
    check_key = redis_store.get(user_name)
    session['receive_count'] = session.get('receive_count', 0) + 1
    if not check_key:
        rooms = searching_room(dragon)
        if not rooms:
            room_id = str(uuid.uuid4())
            redis_store.sadd('room:{}'.format(dragon),*[room_id])
            redis_store.set(user_name, dragon +":"+ room_id)
        else :
            room_id = random.choice(list(rooms))
        
        test_filter = filter(lambda room: room != room_id, request.namespace.rooms)
        if request.namespace.rooms:
                data = 'leave old rooms before!'
        else:
            join_room(room_id)
            redis_store.sadd('room:{}'.format(dragon),*[room_id])
            redis_store.set(user_name, dragon +":"+ room_id)
            request.namespace.channel = room_id
            data = 'join_room: ' + ', '.join(request.namespace.rooms)
        emit('my response',
             {'data': data, 'count': session['receive_count']})
        print request.namespace.channel
    else:
        _, room_id = check_key.split(":")
        request.namespace.channel = room_id
        if not request.namespace.rooms:
            join_room(room_id)
        emit('my response',
                 {'data': 'in room: ' + ', '.join(request.namespace.rooms), 'count': session['receive_count']})
Beispiel #4
0
Datei: mobi.py Projekt: m329/mobi
def personal_connect():	
	if current_user.is_authenticated():
		#emit('response', {'data': 'You are now connected.', 'user': '******'})
		join_room(current_user.id)
		
	else:
		disconnect()
Beispiel #5
0
def socketSetName(user):
	session['name'] = user['name']
	session['room'] = findAvailableRoom()
	print "room: " + session['room']
	addUserToRoom(session['name'], session['room'])
	join_room(session['room'])
	gameStart(session['room'])
Beispiel #6
0
def enterGame(msg, db, gameMsg):
    gameId = msg['gameId']
    name = msg['name']

    sameNameExists = False
    players = [parsePlayer(i) for i in db.fetchall('SELECT name, handJSON FROM players WHERE gameId = %d; ' % gameId)]

    for player in players:
        if player['name'] == name:
            sameNameExists = True
            send({
                'error': {
                    'event': 'enterGame',
                    'reason': 'same name exists'
                    }
                }, json=True)
            break
    if not sameNameExists:
        db.execute("INSERT INTO players (gameId, name, handJSON, joined) VALUES (%d, '%s', '%s', 0)" % (gameId, name, '[]'))
        game = getGame(db, gameId)
        gameMsg.buildEnterGame()
        send({
            'event': 'enterGame',
            'message' : gameMsg.message,
            'game': game
            }, json=True, room=gameId)
        join_room(gameId)
        messages = [parseMessage(i) for i in db.fetchall("SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId)]
        gameMsg.message['elements']['messages'] = messages
        send({
            'event': 'enterGame',
            'message' : gameMsg.message,
            'game': game
            }, json=True)
Beispiel #7
0
def join(message):
    """joins and adds clients to global var rooms"""
    global rooms
    if rooms.get(message["room"]) == None:
        rooms[message["room"]] = []

    if len(rooms.get(message['room'], [])) < 2:

        if message['start'] == 1:
            join_room(message['room'])
            rooms[message['room']].append(session['login'])
            
            emit('invite_to_join',
                 {'room_name': message['room']},
                 broadcast=True)

        elif message['start']==2:
            join_room(message['room'])
            rooms[message['room']].append(session['login'])
            starter = rooms[message['room']][0]
            joiner = rooms[message['room']][1]

            emit('start_game', {'room_name': message['room'], 'starter': starter, 'joiner': joiner})
            # emit('full_room', {}, broadcast=True)   
    else:
        print "full room"
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    di={}
    room = session.get('room')
    #u=url+room+"/_search"
    join_room(room)
    emit('status', {'msg':"<span style='font-size:18px;color:#ff6600;text-align:center; margin-bottom:10px; border-bottom:1px solid black'>" + session.get('name') + ' has entered the room.'}, room=room)
    coll=db[room]
    chat=coll.find()
    l=[]
    for c in chat:
        try:
            emit('message',{'msg': "<div style='word-wrap:break-word; margin-right:5px;margin-top:3px;min-height:10px'>"+"<span id='names' style='float:left;max-width:10%;width:100%;margin-left:10px; color:#1234df'>"+c['name']+"</span>" + '<span style= "float:left;max-width:85%;width:100%;text-align:justify; margin-left:10px">'+ c['message']+"</span></div>"})
        except:
            l=c['trending']
            print l
            di={i:l.count(i) for i in l}
            #emit('notify',{'msg':'<div>Trending Now: <b>'+c['trend']+'</b></div>'})    
    print di
    da=[]
    for i in di.keys():
        da.append({"label":i,"value":di[i]})
    print da
    emit("draw",{'msg':str(da)})
    #print l
    #print di
    for i in di.keys():
        emit('notify',{'msg':'<div style="width:70%;bottom-border:1px solid #ff6600"><b>'+i+'</b></div>'})
    '''
Beispiel #9
0
def join_into_room(id):

    data = False
    if id is not None:
        join_room(id)
        data = True
    return data
Beispiel #10
0
def makeConnection():
    db = connectToDB()
    cur = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
    global messages
    
    messages = [] #reset the message array on a reconnect
    rooms = []
    
    messages = [{'text': 'Booting system', 'name': 'Bot'}, {'text': 'ISS Chat now live!', 'name': 'Bot'}]
    
    session['uuid'] = uuid.uuid1()
    session['username'] = '******'
    print('connected')
    users[session['uuid']] = {'username': '******', 'room': 'General'}
    
    join_room(users[session['uuid']]['room'])
    emit('joinedGeneral')
    print users[session['uuid']]['username'] + ' joined room ' + users[session['uuid']]['room']

    cur.execute("SELECT roomname FROM rooms;")
    roomList = cur.fetchall()
    for room in roomList:
        rooms.append(room)
        emit('createRoom', room)
    
    cur.execute("select * from issmessages where room = %s;", (users[session['uuid']]['room'],))
    results = cur.fetchall()
    if(len(results) > 0):
        for result in results:
            tmp = {'text': result[2], 'name': result[1]}
            messages.append(tmp)
    
    for message in messages:
        print(message)
        emit('message', message)
Beispiel #11
0
def joined(message):
   """Sent by clients when they enter a room.
   A status message is broadcast to all people in the room."""
   room = session.get('room')
   join_room(room)
   print "joined"
   emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room,namespace='/chat')
Beispiel #12
0
def on_join(room):
    db = connectToDB()
    cur = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
    global messages
    
    subbedRooms = []
    cur.execute("SELECT rooms.roomname FROM rooms JOIN subscriptions ON rooms.id = subscriptions.room_id JOIN users ON subscriptions.user_id = users.id WHERE users.username = %s;", (users[session['uuid']]['username'],))
    subbedRooms = cur.fetchall()
    print subbedRooms
    if room in subbedRooms:
        leave_room(users[session['uuid']]['room'])
        print 'Leaving room ' + users[session['uuid']]['room']
        for message in messages:
            emit('refreshMessages')
        
        messages = []
        
        users[session['uuid']]['room'] = room[0]
        join_room(users[session['uuid']]['room'])
        print users[session['uuid']]['username'] + ' joined room ' + users[session['uuid']]['room']
        cur.execute("select * from issmessages where room = %s;", (users[session['uuid']]['room'],))
        results = cur.fetchall()
        if(len(results) > 0):
            for result in results:
                tmp = {'text': result[2], 'name': result[1]}
                messages.append(tmp)
                emit('message', tmp, room=users[session['uuid']]['room'])
        emit('joined', users[session['uuid']]['room'])
        
    else:
        print 'You are not subscribed to that chatroom'
Beispiel #13
0
def join_into_room(id):

    data = False
    if id is not None:
        join_room(id)
        data = True
    return data
Beispiel #14
0
def on_join_jobs(data):
    """
    Somebody joined a room
    """
    room = data['room']
    join_room(room)
    flask.session['room'] = room
Beispiel #15
0
def join(message):
    """joins and adds clients to global var rooms"""
    global rooms
    if rooms.get(message["room"]) == None:
        rooms[message["room"]] = []

    if len(rooms.get(message['room'], [])) < 2:

        if message['start'] == 1:
            join_room(message['room'])
            rooms[message['room']].append(session['login'])

            emit('invite_to_join', {'room_name': message['room']},
                 broadcast=True)

        elif message['start'] == 2:
            join_room(message['room'])
            rooms[message['room']].append(session['login'])
            starter = rooms[message['room']][0]
            joiner = rooms[message['room']][1]

            emit('start_game', {
                'room_name': message['room'],
                'starter': starter,
                'joiner': joiner
            })
            # emit('full_room', {}, broadcast=True)
    else:
        print "full room"
Beispiel #16
0
def handle_join(data):
    """User joins the room."""
    username = data['username']
    room = 'room'
    join_room(room)
    USERS.add(username)
    emit('users', {'users': sorted(USERS)}, room=room)
Beispiel #17
0
def state_connect():
    game_id = STATE['game_id']
    player_id = session['player_id']
    join_room(game_id)
    emit('join', {'player_id': player_id, 'player_name': PLAYER.get(player_id)},
        room=game_id)
    print('Client [%s] connected to game [%s]' % (player_id, game_id))
Beispiel #18
0
def joined(message):
	'''A new user has entered the room, status message sent to everybody in the room.
	Also, the list of active users is updated and setn to everybody in the room'''
	room = session.get('room')
	join_room(room)
	emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)
	emit('active', {'msg': 	'\n'.join(list(active_users[room])) }, room=room)
Beispiel #19
0
def add_monitor(data):
    pvname = data['pv']

    monitors = session.get('monitors', defaultdict(int))
    monitors[pvname] += 1
    session['monitors'] = monitors
    session.modified = True

    if monitors[pvname] > 1:
        # Client was already monitoring this PV so no need to create a
        # monitor or join room.
        return

    if pvname in pv_lookup:
        # A monitor has already been set up for this PV so we can just
        # join the room.
        join_room(pvname)
        return

    try:
        pv_lookup[pvname] = PV(pvname, callback=pv_changed)
    except CASeverityException:
        session['monitors'][pvname] -= 1
    else:
        join_room(pvname)
Beispiel #20
0
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    room = session.get('room')
    join_room(room)
    print "session1", session
    emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)
Beispiel #21
0
def test_connect():
    print("in connect")
    conn = connectToDB()
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    join_room('general')
    session['uuid'] = uuid.uuid1()
    query = ("SELECT name1, message, room FROM messages WHERE room='general';")
    cur.execute(query)
    results = cur.fetchall()
    message = {}
    room = {}

    for result in results:
        message['name'] = result['name1']
        message['text'] = result['message']
        message['room'] = result['room']
        emit('sendMessages', message)
        print(message)

    query = "SELECT room1 FROM rooms;"
    cur.execute(query)
    results = cur.fetchall()

    for result in results:
        room['room'] = result['room1']
        emit('sendRooms', room)
        print(result)
    print 'connected'
Beispiel #22
0
def chat_window_open(message):
    """Sent by clients when they leave a room.
    A status message is broadcast to all people in the room."""
    room = int(message["sender_id"][0:4]) + int(message["sender_id"][5:9])
    room = room + int(message["receiver_id"][0:4]) + int(message["receiver_id"][5:9])
    join_room(room)
    emit('status', {"status":"open"}, room = room)
def answer_student(data):
    """
    Needs to make a socket call to shift student and TA to a specific room. There will be an another function which
    catches a signal that is emitted back (Python code will add both users to a room on this signal) and will return
    a href to redirect the users {unique roomID} and will be redirected using window's href in the javascript code
    :param data: data from socketio call
    """

    join_room(data['ta']) # Joined ta's room
    new_data = {'room' : data['net_id'], 'student': data['net_id'], 'ta': data['ta']}

    path = os.path.abspath("VOH/codeshare.py")
    print path

    link = subprocess.check_output(["python", path])

    # emit('answer_info', new_data, namespace='/queue', broadcast=True)

    # Adding a new collection for particular student, ta pair. Collection name is the ta's netID
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    client, db = open_db_connection()
    db['chat_log'][data['ta']].insert(
        dict(room=data['ta'].encode("utf-8"), message="Started Conversation", time=st.encode("utf-8")))
    close_db_connection(client)
    emit('student_join_emit', {"student" : data['net_id'], "ta" : data['ta'], "link":link}, broadcast = True )
Beispiel #24
0
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    room = session.get('room')
    with_bot = False
    if room in bot_rooms.keys():
        with_bot = True
        # Store previous ID
        bot_room = room
        room = str(uuid.uuid4())  # Create private room
        session["room"] = room  # Update session
    join_room(room)
    emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)
    if with_bot:
        # Reverse name for CopyCat bot
        if bot_room == "60":
            bot_name = session.get('name')[::-1]
        # Keep instance of bot
        else:
            bot_name = bot_rooms[bot_room]
        b = Bot(bot_name)
        b.setup()
        active_bots[room] = b
        # Greet user
        emit('status', {'msg': b.name() + ' [BOT] has entered the room.'}, room=room)
        emit('message', {'msg':  b.name() + ': ' + b.greet()}, room=room)
Beispiel #25
0
def joined(data):
    user_2 = data.get('id')
    if user_2 is None:
        return emit('status', {'flag': False, 'msg': 'id is empty'})
    try:
        user_2 = int(user_2)
    except ValueError:
        return emit('status', {'flag': False, 'msg': 'ValueError : id is not int'})
    except TypeError:
        return emit('status', {'flag': False, 'msg': 'TypeError'})

    user_1 = session.get('user_id')
    extra = compare(user_1, user_2)
    room_id = '%d|%d' % extra

    session.setdefault('rooms', [])

    if room_id not in session['rooms']:
        join_room(room_id)
        session['rooms'].append(room_id)
        emit('unique_wire', {'flag': True, 'id': user_2, 'user': user_1}, room=user_2)
        save_room(room_id, user_1, user_2)

    chat = take_message(room_id, extra, number=0)
    context = {
        'flag': True,
        'room': room_id,
        'history': chat,
        'id': user_2,
    }

    emit('status', context)
Beispiel #26
0
def select(message):
    user = User.getUser(session['username'])
    user.joinRoom(message['room'])
    join_room(message['room'])

    room = Room.getRoom(message['room'], user)
    emit('selected', {'room': message['room'], 'messages':room.getMessages()})
Beispiel #27
0
def join_all_rooms(data):
    rooms = data.get('rooms')
    if rooms is not None:
        for x in rooms:
            if x:
                join_room(x)
                print('USER id :', session.get('user_id'), 'joining room : ' + x)
Beispiel #28
0
def join(message):
    new_game = False
    play_computer = message['data']['play_computer']
    if not message['room']:
        new_game = True
    if new_game:
        game_room = 'game' + str(random.randint(1, 10000))
        marker = 'X'
    else:
        game_room = message['room']
        marker = 'O'
    join_room(game_room)
    session['receive_count'] = session.get('receive_count', 0) + 1
    response_data = {}
    response_data['marker'] = marker
    response_data['room'] = game_room
    response_data['start'] = False
    response_data['count'] = session['receive_count']
    emit('set-room', {'data': response_data})
    # Now broadcast to other player in the room that game can start
    if new_game and not play_computer:
        response_data['start'] = False
        response_data['message'] = 'Waiting for Opponent to Join'
    else:
        response_data['start'] = True
        response_data['move_marker'] = 'X'
    emit('game-start', {'data': response_data}, room=response_data['room'])
Beispiel #29
0
def create_or_join(room):
	print 'Received request from clientid' + request.namespace.socket.sessid + ' to create or join room ' + str(room)
	if str(room) in clients:
		clients[str(room)].append(request.namespace.socket.sessid)
		print 'Dictionary being updated'
	else:
		clients.update({ str(room): [request.namespace.socket.sessid]})
		print 'Dictionary entry being created'

	numClients = len(clients[str(room)])
	print numClients
	if numClients <= 1:
		join_room(str(room))
		logger('Client ID ' + request.namespace.socket.sessid + ' created room ' + str(room))
		print 'Client ID ' + request.namespace.socket.sessid + ' created room ' + str(room)
		emit('created', room, request.namespace.socket.sessid)
	elif numClients <= 2:
		logger('Client ID ' + request.namespace.socket.sessid + ' joined room ' + str(room))
		print 'Client ID ' + request.namespace.socket.sessid + ' joined room ' + str(room)
		join_room(str(room))
		emit('joined', room, request.namespace.socket.sessid)
		emit('nowready', room=room) #This sends it to all the clients FROM the server since the socketio
	else:#Max 2 clients
		print "Room is full"
		emit('full', room)
Beispiel #30
0
def resumeGame(msg, db, gameMsg):
    gameId = msg['gameId']
    name = msg['name']

    players = db.fetchall("SELECT name FROM players WHERE gameId = %d AND name='%s'" % (gameId, name))
    
    if len(players) != 0:
        game = getGame(db, gameId)
        gameMsg.buildResumeGame()
        send({
            'event': 'resumeGame',
            'message' : gameMsg.message,
            'game': game
            }, json=True, room=gameId)
        join_room(gameId)
        messages = [parseMessage(i) for i in db.fetchall("SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId)]
        gameMsg.message['elements']['messages'] = messages
        send({
            'event': 'resumeGame',
            'message' : gameMsg.message,
            'game': game
            }, json=True)
    else:
        send({
            'error': {
                'event': 'resumeGame',
                'reason': 'no player with name exists'
                }
            }, json=True)
Beispiel #31
0
    def api_call(self, msg_str):
        msgJson = json.loads(msg_str);
        sessionJson = msgJson.values()[0]['session']
        print 'session[id]:', 'id' in session
        if 'id' in session:
            print 'session[id]:', session['id']
        print "sessionJson['uuid']", sessionJson['uuid']
        if 'id' in session:
            print session['id'] == sessionJson['uuid']
        if 'id' not in session or session['id'] != sessionJson['uuid']:
            print 'Join Room: ', sessionJson['uuid'], '  ...............................'
            join_room(sessionJson['uuid'])
            session['id'] = sessionJson['uuid']

        # receipt = self.Receipt()
        def cb(evt):
            # receipt.status = receipt.DONE
            # receipt.rsp = evt
            evt.values()[0]['session'] = sessionJson
            socketio.emit('call_ret', {'msg': json.dumps(evt)}, room=sessionJson['uuid'])

        # self.api_tasks[receipt.id] = receipt
        try:
            self.bus.send(msg_str, cb)
            # return receipt.to_json()
        except Exception as e:
            del self.api_tasks[receipt.id]
            log.debug(utils.get_exception_stacktrace())
Beispiel #32
0
def on_join(room):
    db = connectToDB()
    cur = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
    global messages

    subbedRooms = []
    cur.execute(
        "SELECT rooms.roomname FROM rooms JOIN subscriptions ON rooms.id = subscriptions.room_id JOIN users ON subscriptions.user_id = users.id WHERE users.username = %s;",
        (users[session['uuid']]['username'], ))
    subbedRooms = cur.fetchall()
    print subbedRooms
    if room in subbedRooms:
        leave_room(users[session['uuid']]['room'])
        print 'Leaving room ' + users[session['uuid']]['room']
        for message in messages:
            emit('refreshMessages')

        messages = []

        users[session['uuid']]['room'] = room[0]
        join_room(users[session['uuid']]['room'])
        print users[session['uuid']]['username'] + ' joined room ' + users[
            session['uuid']]['room']
        cur.execute("select * from issmessages where room = %s;",
                    (users[session['uuid']]['room'], ))
        results = cur.fetchall()
        if (len(results) > 0):
            for result in results:
                tmp = {'text': result[2], 'name': result[1]}
                messages.append(tmp)
                emit('message', tmp, room=users[session['uuid']]['room'])
        emit('joined', users[session['uuid']]['room'])

    else:
        print 'You are not subscribed to that chatroom'
Beispiel #33
0
def test_getroom(message):
    print "join room"
    print message
    join_room(message['room'])
    emit('set room', {
        'room': list(request.namespace.rooms)[0],
        'sender': message['u_id']
    })
Beispiel #34
0
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    C = chat_session()
    start_chat(C.room_id)
    join_room(C.room_id)
    app.logger.debug("Testing logger: User {} has entered room {}.".format(C.my_id, C.room))
    emit_message_to_userid("Your partner has entered the room.", C.partner_id, status_message=True)
Beispiel #35
0
def joined(message):
    '''A new user has entered the room, status message sent to everybody in the room.
	Also, the list of active users is updated and setn to everybody in the room'''
    room = session.get('room')
    join_room(room)
    emit('status', {'msg': session.get('name') + ' has entered the room.'},
         room=room)
    emit('active', {'msg': '\n'.join(list(active_users[room]))}, room=room)
Beispiel #36
0
def handle_ping(data):
    if not keyword_test(data['keyword']):
        return
    join_room(data['keyword'])
    result = keywordsmanager.ping_keyword(data['keyword'])

    if result:
        emit('keywords_synced', {'synced': True})
Beispiel #37
0
def on_join(data):
    room = data['room']
    socketio.join_room(room)
    message = {}
    insert_user_info(message)
    join_room(data['room'], message['user_id'])
    socketio.emit('userJoin', message, namespace='/chat', room=room)
    socketio.emit('users', {'users': rooms[room]['users']}, namespace='/chat', room=room)
Beispiel #38
0
def handle_open_stream(data):
    track = translate_track(data['track'])
    if 'rooms' in session:
        session['rooms'][track] = True
    else:
        session['rooms'] = {track: True}
    join_room(track)
    open_stream(socketio, track)
Beispiel #39
0
def join(message):
    join_room(message['room'])
    console = Console.query.filter_by(name=message['room']).first()
    for button in console.buttons:
        if button.is_running():
            if 'serving-{}'.format(button.id) not in greenlets.keys():
                greenlets['serving-{}'.format(button.id)] = gevent.spawn(serve_log,
                        button.log_file, button.id, console.name)
Beispiel #40
0
def loginChat():
  print('Trying to pass username to socketio')
  if 'username' in session:
    emit('loginChat', session['username'])
    join_room('public')
    session['roomname'] = 'public'
  else:
    emit('login', '')
Beispiel #41
0
def join(message):
    join_room(message['room'])
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit(
        'my response', {
            'data': 'In rooms: ' + ', '.join(request.namespace.rooms),
            'count': session['receive_count']
        })
Beispiel #42
0
def request_random(message):
    print (message)
    room = random.choice(foods)
    join_room(room)
    if room not in peers:
        peers[room] = []
    peers[room].append(message['peer'])
    emit('join confirm', {'room': room, 'peers': peers[room]})
Beispiel #43
0
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    room = message.get('room')
    user = message.get('user')
    join_room(room)
    app.logger.info('User %s joined %s room' % (user, room))
    emit('status', {'msg': user + ' has entered the room.', 'username': user}, room=room)
Beispiel #44
0
def join(data):
    """
    Function is called when a TA and Student need to join a particular room so that they can be
    directed to a unique URL to start their chat
    :param data: Data Containing information about the room
    """
    join_room(data['id'])
    emit('join_room_ta', {'msg': "hi, you are in room " + data['id']},
         room=data['id'])  # Emits signal to a particular chat conversation
Beispiel #45
0
def on_join(data):
    """
        Sent by clients when they enter a room.
    """
    username = session["login"][0]
    room = find_room(data["bookgroup_id"], data.get("chapter_number"))
    join_room(room)

    emit('joined_status', {'msg': username + " has entered room " + str(room)}, room=room)
Beispiel #46
0
def join(message):
    room = session.get('room')
    join_room(room)
    if not room in rooms:
        rooms[room] = set()
    rooms[room].add(session.get('user'))

    msg = '<' + session.get('user') + ' joined the chat>'
    emit('message', {'msg': msg}, room=room)
Beispiel #47
0
def socketio_full_image(message):
    # print('full image', message)
    bid = message['data']['board_id']
    key = message['data']['key']
    board = whiteboards[bid]
    if board.may_view(key):
        socketio.join_room(bid)
        data = {'data': {'board_id': bid, 'actions': board.full_image()}}
        socketio.emit('paint', data)
Beispiel #48
0
def join(message):
    room = message['room']
    join_room(room)
    session['room'] = room
    player_id = session['user_id']
    game = games[room]
    game.join(player_id)
    update(game, room)
    request.namespace.emit('userId', session['user_id'])
Beispiel #49
0
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    username = session.get("name")
    room = session.get('room')

    join_room(room)
    app.logger.debug("Testing logger: User {} has entered room {}.".format(
        username, room))
    emit('status', {'msg': username + ' has entered the room.'}, room=room)
Beispiel #50
0
def state_connect():
    game_id = STATE['game_id']
    player_id = session['player_id']
    join_room(game_id)
    emit('join', {
        'player_id': player_id,
        'player_name': PLAYER.get(player_id)
    },
         room=game_id)
    print('Client [%s] connected to game [%s]' % (player_id, game_id))
Beispiel #51
0
def tutor_ready():
	for i in session['subjects'].split(','):
		if unifiedQueue.can_service(i):
			tuteeName, tuteeLocation = unifiedQueue.service(i, session['name'], session['location'])
			emit('found_tutee', {'tuteeName' : tuteeName, 'tuteeLocation' : tuteeLocation})
			return
	room = unifiedQueue.offer(session['subjects'].split(','), session['name'], session['location'])
	join_room(room)
	print('Joined room since no tutees')
	emit('no_tutees', {'data' : room}, room=room)
Beispiel #52
0
def on_connect():
    join_room(current_user.email)
    try:
        connected_clients[current_user.email].append(request.namespace)
    except KeyError:
        connected_clients[current_user.email] = [request.namespace]
    emit('connected', {
        'user': current_user.email,
        "count": len(connected_clients[current_user.email])
    },
         room=current_user.email)
Beispiel #53
0
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    room = session.get('room')
    join_room(room)
    msg = find_links_in_message(
        u'<i> has entered the <strong>${}</strong> room.</i>'.format(room),
        session.get('name'),
        session.get('avatar')
    )
    emit('status', {'msg': msg}, room=room)
Beispiel #54
0
def success_connect(msg):
    #print(msg['room'])
    #print(msg['user'])
    users_obj = Room.query.filter_by(name=msg['room']).first().users
    join_room(msg['room'])
    emit('success join room', {
        'log': '[' + msg['user'] + '] : Joined room => ' + msg['room'],
        'users': [u.name for u in users_obj],
        'points': [u.point for u in users_obj]
    },
         room=msg['room'])
Beispiel #55
0
        def handle_join(raw_data, data=None, user=None, error=None):
            if error:
                return emit('error', error)

            requested_room = data.get('room')
            if requested_room != 'default':
                # we will only restrict the room for the MVP
                error = "Sorry, but only the 'default' room is available"
                return emit('error', error)

            join_room(requested_room)
            emit('joined', {'room': requested_room})
Beispiel #56
0
def socketio_full_image(message):
	bid = message['board_id'].upper()
	key = message['key']
	board = whiteboards[bid]
	# Ensure the user may see this board
	if board.may_view(key):
		socketio.join_room(bid)
		data = {
			'board_id': bid,
			'actions': board.full_image()
		}
		socketio.emit('paint', data)
Beispiel #57
0
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    room = session.get('room')
    u=url+room+"/_search"
    join_room(room)
    emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)
    coll=db[room]
    chat=coll.find()
    for c in chat:
        emit('message',{'msg':c['name']+": "+c['message']})
    '''
Beispiel #58
0
def joined(message):
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    room = message.get('room')
    user = message.get('user')
    join_room(room)
    app.logger.info('User %s joined %s room' % (user, room))
    emit('status', {
        'msg': user + ' has entered the room.',
        'username': user
    },
         room=room)
Beispiel #59
0
def on_join(data):
    story_id = data['story_id']
    current_segment = Segment.last(story_id=story_id)
    if current_segment is None:
        current_segment = Segment.create(story_id=story_id)
    join_room(story_id)
    emit('welcome', {
        'current_segment_id': current_segment.id
        }, room=story_id)
    emit('user_joined', {
        'user': current_user.name,
        }, broadcast=True, room=story_id)