コード例 #1
0
ファイル: main.py プロジェクト: TDo13/ee_server
def on_connect():
    global terrain
    print('NEW CONNECTION: ', request.sid)

    # Request for the terrain
    if terrain == None:
        seed = datetime.datetime.now()
        seed = seed.hour + 24 * (seed.day + 31 * seed.month) * 4352 + 32454354
        terrain = requests.get(app.config['TERRAIN_URL'] +
           '/get_landscape?width=' + str(BOARD_WIDTH) +
           '&height=' + str(BOARD_HEIGHT) +
           '&seed=' + str(seed)).json()['result']
    
    socketio.emit('landscape', {'terrain': terrain}, room=request.sid)
    # Request for field-objects: Response dealt with above
    requests.get(app.config['OBJECTS_URL'] + '/terrain_objects?width=' + str(BOARD_WIDTH) + '&height=' + str(BOARD_HEIGHT))

    # Spawn all other players into new player's screen (Must happen before initializing current player)
    playersList = requests.get(app.config['DB_URL'] + '/players/get_all').json()
    if playersList != None and len(playersList) > 0: 
        for player in playersList:
            emit('spawn', {'id': player['id'], 'mass': player['mass']}, room=request.sid)
    requests.post(app.config["DB_URL"] + '/users/add', json={'id': request.sid, 'zombies': []})
    requests.post(app.config['DB_URL'] + '/players/add', json={'mass': DEFAULT_PLAYER_MASS, 'id': request.sid})

    add_more_zombies()
コード例 #2
0
ファイル: main.py プロジェクト: TDo13/ee_server
def add_more_zombies():
    global current_zombie_id
    users = requests.get(app.config["DB_URL"] + '/users/get_all').json()
    players = requests.get(app.config["DB_URL"] + '/players/get_all').json()
    if len(users) <= 0:
        return
    # create up to 20 zombies
    for i in range(max(0, MIN_PLAYERS_ZOMBIE_THRESHOLD - len(players))):
        # Choose a random client to add the zombie to
        user_id = random.choice(users)['id']
        zombieMass = DEFAULT_PLAYER_MASS - 2 -(1 + 2 * random.random())
        current_zombie_id += 1
        zombiePositionX = random.random() * (BOARD_WIDTH - 20) + 10
        zombiePositionZ = random.random() * (BOARD_HEIGHT - 20) + 10
        zombieID = 'zombie_' + str(current_zombie_id)
        socketio.emit('initialize_zombie_player',
                      {'id': zombieID, 
                       'mass': zombieMass,
                       'x': zombiePositionX,
                       'z': zombiePositionZ}, room=user_id)
        
        # Store zombie on assigned player 
        requests.post(app.config['DB_URL'] + '/users/add_zombie', json={'id': user_id, 'zombie': zombieID})
        # Store zombie as player
        requests.post(app.config["DB_URL"] + '/players/add', json = {'id': zombieID, 'mass': zombieMass})
        
        emit('spawn', {'id': zombieID, 'mass': zombieMass}, broadcast=True, include_self=False) 
コード例 #3
0
def publish_message():
    if request.method == 'POST':
        data = request.form['data']
        password = request.form['password']
        date = request.form['date']
        sen = request.form['sender']
        conn = holder.getConnectionbypassword(password)
        if conn:
            conn.api.set_available()
            app.logger.info('sending message to' + conn.get_user_name())
            emit('on message', {'data': data, 'sender': sen,
                                'sent_time': date}, room=conn.get_user_name(), namespace='/')
            # save to db
            data_base.write_message({
                'channel': conn.get_user_name(),
                'message': data,
                'sender': sen,
                'destination': 'self',
                'sent_time': date,
                'is_read': False
            })
            conn.api.set_not_available()
        else:
            app.logger.error('invailed password was passed from YowSup' + password)
    return ''
コード例 #4
0
ファイル: server.py プロジェクト: zergov/pythonChatServer
def get_connected_user():
    """
    Return the list of connected users.
    """
    usernames = clients.keys()
    data = json.dumps(usernames)
    emit('on_client_list_received', data)
コード例 #5
0
def cleanHum(data):
	print("clean the hum data in the hum table", data)
	cur.execute("use TempHumTable")
	cur.execute("delete from hum")
	con.commit()
	print("Restart Humidity Detection successfully!")
	emit('cleanHum', data)
コード例 #6
0
def set_nick_name(data):
    conn = holder.getConnectionbyuser(session['room'])
    if conn is not None:
        conn.api.set_nick_name(str(data[u'nickname']))
        emit('server log', {'data': 'nick name has been set'})
    else:
        emit('server log', {'data': 'not existing user'})
コード例 #7
0
ファイル: SpyPartyDraft.py プロジェクト: sgnurf/SpyPartyDraft
def first_option_form(message):
    choice = message['choice']
    room = room_map[message['room_id']]
    room.touch()
    print "got choice {}".format(choice)
    if choice == "pickfirst":
        room.draft.start_player = room.draft.coin_flip_winner
        room.post_event("{} has opted to pick first".format(room.draft.coin_flip_winner))
        ask_spy_order(room, "You opponent has opted to pick first")
    elif choice == "picksecond":
        room.draft.start_player = room.draft.coin_flip_loser()
        room.post_event("{} has opted to pick second".format(room.draft.coin_flip_winner))
        ask_spy_order(room, "Your opponent has opted to pick second")
    elif choice == "spyfirst":
        room.draft.first_spy = room.draft.coin_flip_winner
        room.post_event("{} has opted to spy first".format(room.draft.coin_flip_winner))
        ask_pick_order(room, "Your opponent has opted to spy first")
    elif choice == "spysecond":
        room.draft.first_spy = room.draft.coin_flip_loser()
        room.post_event("{} has opted to spy second".format(room.draft.coin_flip_winner))
        ask_pick_order(room, "Your opponent has opted to spy second")
    elif choice == "defer":
        # we're going to pretend the other player won the flip, but
        # don't let them defer
        room.post_event("{} has opted to defer".format(room.draft.coin_flip_winner))
        room.draft.coin_flip_winner = room.draft.coin_flip_loser()
        emit('winner_deferred', {
            'room_id': room.id,
            'picker': room.draft.coin_flip_winner
        }, room=room.id)
コード例 #8
0
def cleanTemp(data):
	print("clean the temp data in the temp table", data)
	cur.execute("use TempHumTable")
	cur.execute("delete from temp")
	con.commit()
	print("Restart Temperature Detection successfully!")
	emit('cleanTemp', data)
コード例 #9
0
ファイル: flowcontroller.py プロジェクト: jmccormack200/SDR
def set_freq(freq):
    print("PRINT")
    print(str(int(freq)))
    tb.set_tx_freq(int(freq))
    tb.set_rx_freq(int(freq))
    print(tb.get_tx_freq())
    emit("confirm tx freq", {"txfreq": tb.get_tx_freq()}, broadcast=True)
コード例 #10
0
ファイル: SpyPartyDraft.py プロジェクト: sgnurf/SpyPartyDraft
def broadcast_to_room(room_id, msg):
    print 'broadcasting: ' + msg
    emit('room_broadcast',
         {'msg': msg,
          'room': room_id
         },
         room=room_id)
コード例 #11
0
ファイル: flowcontroller.py プロジェクト: jmccormack200/SDR
def dec_freq():
    newFreq = txfreqtable.decrease_freq()
    os.system("echo " + "'" + str(newFreq) + "%" + str(time()) + "'" + " | sudo alfred -s 65")
    sleep(7)
    tb.set_tx_freq(int(newFreq))
    tb.set_rx_freq(int(newFreq))
    emit("confirm tx freq", {"txfreq": newFreq}, broadcast=True)
コード例 #12
0
ファイル: views.py プロジェクト: AkelaInc/OpenVNA-Web-Demo
def config_change(data):

	if not isinstance(data, dict):
		raise ValueError("Wat?")

	if not 'src-guid' in data:
		error_response("That doesn't work without a source GUID!")
		return

	if not app.config['LOGIN_ARBITER'].check_auth(request.sid):
		error_response("You have to be authenticated to do that. Nice try, though!")
		return

	# Re-broadcast change so all clients can pick it up.
	# emit('config update', data, broadcast=True)
	emit('config', data, broadcast=True, namespace='/vna_interface')

	# def set_num_points(self, npts):
	# def set_start_stop_freq(self, start, stop):
	# def set_experiment(self, experiment_num):

	if 'no-points' in data:
		print("Point number:", data['no-points'])

		app.config['ARBITER'].set_num_points(data['no-points'])

	if 'start-stop' in data:
		app.config['ARBITER'].set_start_stop_freq(*data['start-stop'])

	if 'switch-matrix' in data:
		app.config['ARBITER'].set_experiment(data['switch-matrix'])


	emit('change_applied', "config change OK", namespace='/vna_interface')
コード例 #13
0
ファイル: views.py プロジェクト: AkelaInc/OpenVNA-Web-Demo
def event_connect():
	log.info("event_connect() -> %s", request.sid)
	log_request(request, "websocket connect")

	active = app.config['LOGIN_ARBITER'].add_non_auth(request.sid)
	if active[0]:
		emit('active', list(active), broadcast=True, namespace='/vna_interface')
コード例 #14
0
ファイル: server.py プロジェクト: percyliang/sempre
def emit_top_builders():
    top_5_builders = []
    for uid in os.listdir(CITATION_FOLDER):
        subdir = os.path.join(CITATION_FOLDER, uid)
        if not os.path.isdir(subdir):
            continue

        top_5_builders = sorted(
            top_5_builders, key=lambda b: b[1], reverse=True)

        (citations, citation_score) = compute_citations(subdir)

        top_5_builders = sorted(
            top_5_builders, key=lambda b: b[1], reverse=True)
        if len(top_5_builders) < 10 or citation_score > top_5_builders[9][1]:
            # If there are more than 5 citations with cites, only return those
            citations = sorted(
                citations, key=lambda c: c["cite"] + c["self"], reverse=True)[:10]
            # if len(citations_with_cites) >= 6:
            #     citations = citations_with_cites

            # Sort them by score and return the top 7.
            citations = sorted(
                citations, key=lambda c: c["cite"] + c["self"], reverse=True)[:10]

            struct = (uid, citation_score, citations)
            if len(top_5_builders) < 10:
                top_5_builders.append(struct)
            else:
                top_5_builders[9] = struct

    emit("top_builders", {"top_builders": top_5_builders},
         broadcast=True, room="community")
コード例 #15
0
ファイル: server.py プロジェクト: percyliang/sempre
def handle_share(data):
    """Users can share structs. We save this struct in STRUCTS_FOLDER/UID/SCORE_ID.json

    where UID is the uid of the user who submitted the struct, SCORE is the
    current score of the struct and ID is the unique index (auto-incremented) of
    this particular struct.."""

    user = current_user(data['token'])
    if not user:
        return

    uid = user['id']

    user_structs_folder = os.path.join(STRUCTS_FOLDER, uid)
    if not is_safe_path(STRUCTS_FOLDER, user_structs_folder):
        return
    make_dir_if_necessary(user_structs_folder)
    new_struct_path = os.path.join(user_structs_folder, data["id"] + ".json")
    if not is_safe_path(user_structs_folder, new_struct_path):
        return

    submission_time = current_unix_time()
    score = score_struct(submission_time, 0)

    with open(new_struct_path, 'w') as f:
        f.write("[]\n")  # it starts with no upvoters
        f.write(str(submission_time) + "\n")  # timestamp of submission
        f.write(json.dumps(data["struct"]) + "\n")  # the actual struct
        f.write(data["image"])  # the png of the struct

    # Broadcast addition to the "community" room
    message = {"uid": uid, "id": data["id"], "score": score, "upvotes": [
    ], "struct": data["struct"], "image": data["image"]}
    emit("struct", message, broadcast=True, room="community")
コード例 #16
0
ファイル: flaskAuthServer80.py プロジェクト: eb96706/Spirals
def addComment(etype):
    print "addComment", etype
    req = {}
    args = request.args
    print "args:", args
    if request.data:
        req = json.loads(request.data)
    for key in args:
        #req[key] = args[key][0]
        req[key] = args[key]
    print "req:", req
    parentId = req['parent']
    comment = req['comment']
    print "parentId:", parentId
    print "comment:", comment
    note = getNote(parentId)
    print "note:", note
    comments = note.get("comments", [])
    comments.append(comment)
    print "comments:", comments
    note['comments'] = comments
    #q = rdb.table("notes").filter({"id":id})
    #q = q.update({"comments": comments})
    #q.run(conn)
    jObj = json.dumps(note)
    print "etype:", etype
    print "jObj:", jObj
    if socketio:
        print "send to socketio"
        emit(etype, jObj, broadcast=True, namespace='/')
    print "**** addToDB"
    replaceObjToDB(note, etype)
    print
    return "OK"
コード例 #17
0
ファイル: houseSock.py プロジェクト: Chan9390/house
def doEnv():
    with open('./scripts/enum/env.js') as f:
        house_global.script_to_load = f.read()
    try:
        load_script()
    except Exception as e:
        emit('update_env_info',{'error': cgi.escape("[!]load_script Exception: {}".format(str(e)))})
コード例 #18
0
ファイル: flaskAuthServer80.py プロジェクト: eb96706/Spirals
def reg():
    print "reg path:", request.path
    print "reg args", request.args
    t = time.time()
    name = request.args.get('name')
    tagStr = request.args.get('tagStr')
    clientType = request.args.get('clientType')
    lon = float(request.args.get('longitude'))
    lat = float(request.args.get('latitude'))
    room = request.args.get('room')
    numUsers = int(request.args.get('numUsers'))
    sessionId = request.args.get('sessionId')
    sessionId = sessionId.replace(':', '_')
    sessionId = sessionId.replace('-', '_')
    obj = {'t': t, 'name': name, 'tagStr': tagStr,
           'lon': lon, 'lat': lat, 'room': room,
           'sessionId': sessionId,
           'numUsers': numUsers, 'clientType': clientType}
    print obj
    jstr = json.dumps(obj)
    print "jstr:", jstr
    if socketio:
        print "send to socketio"
        emit('sharecam', jstr, broadcast=True, namespace='/')
    return "Ok"
コード例 #19
0
def doAction(data):
    from_player = data['from']
    raw_player_action = data['action']
    action = None

    print data

    for stuff in Action:
        if (stuff.name == raw_player_action):
            action = stuff
            break;

    if (isinstance(action, Action)):
        if game.handleAction(from_player, action, data) is True:
            print "action success!"
            game.increaseTurns()
            if (game.getTurns() / (2*len(player_names))) is 1:
                game.setTurns(0)
                game.updateEventAndGetUpcomingEvents()
                print 'update events'

            jsonResponse = game.getJsonResponse()
            if jsonResponse is not None:
                print jsonResponse
                emit('playersBroadcast', jsonResponse, room=room)

        else: 
            print "Do action failed due to invalid parameters."
    else:
        print 'Error, invalid action'
コード例 #20
0
ファイル: houseSock.py プロジェクト: Chan9390/house
def gen_script(message):
    house_global.hooks_list = message.get('hooks_list')
    update_conf()
    house_global.script_to_load = ''
    house_global.hooks_list = house_global.hook_conf.get('hooks_list')
    build_hook_script()
    emit("update_hooks")
コード例 #21
0
ファイル: main.py プロジェクト: TCCinTaiwan/TcTube
def socketio_connect():
    realIP = getRealIP(request)
    connectTime = datetime.utcnow()
    print("Connect: ", realIP)
    sqlAlchemy.session.commit()
    if realIP not in connection:
        connection[realIP] = {}
    connection[realIP][request.sid] = {
        "ip": realIP
    }

    if (current_user.is_authenticated):
        current_user.connect_time = connectTime
        connection[realIP][request.sid].update(
            {
                "login_ip": current_user.login_ip,
                "login_time": dates(current_user.login_time, isUTC = True),
                "name": current_user.name,
                "account": current_user.account,
                "connect_time": dates(current_user.connect_time, isUTC = True)
            }
        )
    emit('connect success', connection[realIP][request.sid])
    emit('user online', connection[realIP][request.sid], broadcast = True)
    socketio_server_ping_client()
コード例 #22
0
ファイル: app.py プロジェクト: pbabik/kay
def handle_user_move(data):
    x = data['x']
    y = data['y']
    color = data['color']
    nick = data['nick']
    mapid = data['map']
    emit('usermove',{'x':x,'y':y,'nick':nick,'color':color},room=mapid)
コード例 #23
0
ファイル: views.py プロジェクト: tcitworld/Quizz
def finish_quizz(msg):
	room = msg['room']
	rooms[room][current_user.username][1] = msg['score']
	if min([rooms[room][user][1] for user in rooms[room]]) < 0:
		emit("attente-fin",{"room":room},room=room)
	else:
		emit("score",{"room":room,"score":rooms[room]},room=room)
コード例 #24
0
ファイル: socket.py プロジェクト: boothandrewd/scrumtious
def newNote(payload):
    # Make new data fields in memory
    boardId = payload['boardId']
    nid = mem.newNote(boardId, payload['xr'], payload['yr'])

    # Send new note signal to board users
    emit('tc_NEW_NOTE', mem.getNote(boardId, nid), room=boardId)
コード例 #25
0
ファイル: app_socketio.py プロジェクト: ucl-team-8/service
def onconnect():
    emit('locations', get_locations())
    dispatcher.subscribe('time', request.sid)
    dispatcher.subscribe('matchings', request.sid)
    dispatcher.dispatch('time', date_to_iso(env.now))
    dispatcher.dispatch('matchings', serialize_matchings(get_matchings()))
    print("Client connected")
コード例 #26
0
ファイル: views.py プロジェクト: tcitworld/Quizz
def leave_room(message):
	room = message['room']
	del rooms[room][current_user.username]
	print()
	print(rooms)
	print()
	emit("infogroom",{"rooms":rooms},broadcast = True)
コード例 #27
0
ファイル: main.py プロジェクト: RiverOfVomit/ggj2016
def handle_tile_requested_event(data):
    print "event: choose tile", str(data['tile'])
    result = gamecontroller.request_tile(data['tile'], request.sid)
    result_json = jsonpickle.encode(result,unpicklable=False)
    emit("choose tile result", result_json)
    update_board_event('tile update',result_json)
    update_tile_event()
コード例 #28
0
def reg():
    print "reg path:", request.path
    print "reg args", request.args
    t = time.time()
    name = request.args.get("name")
    tagStr = request.args.get("tagStr")
    clientType = request.args.get("clientType")
    lon = float(request.args.get("longitude"))
    lat = float(request.args.get("latitude"))
    room = request.args.get("room")
    numUsers = int(request.args.get("numUsers"))
    sessionId = request.args.get("sessionId")
    sessionId = sessionId.replace(":", "_")
    sessionId = sessionId.replace("-", "_")
    obj = {
        "t": t,
        "name": name,
        "tagStr": tagStr,
        "lon": lon,
        "lat": lat,
        "room": room,
        "sessionId": sessionId,
        "numUsers": numUsers,
        "clientType": clientType,
    }
    print obj
    jstr = json.dumps(obj)
    print "jstr:", jstr
    if socketio:
        print "send to socketio"
        emit("sharecam", jstr, broadcast=True, namespace="/")
    return "Ok"
コード例 #29
0
ファイル: main.py プロジェクト: leehopkins/socket-poker
def vote(points):
    uid, sid = session.get('user_id'), session.get('poker_session_id')
    if r.hget(uid, 'role') != 'player':
        return;

    r.hset(uid, 'vote', points)
    emit('vote', { 'points': points, 'user': r.hget(uid, 'username'), 'id': uid }, room=sid)
コード例 #30
0
ファイル: main.py プロジェクト: leehopkins/socket-poker
def set_topic(topic):
    uid, sid = session.get('user_id'), session.get('poker_session_id')
    if r.hget(uid, 'role') != 'admin':
        return;

    r.hset('session:' + sid, 'topic', topic)
    emit('set-topic', topic, room=sid)
コード例 #31
0
ファイル: app.py プロジェクト: liuslouis/jj-game
def send_next():
    print('Broadcast Next Round.\n')
    emit('next-round', broadcast=True)
コード例 #32
0
ファイル: app.py プロジェクト: liuslouis/jj-game
def restart():
    app.g = Game()
    print('\nStart a new game.')
    emit('next-round', broadcast=True)