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()
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)
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 ''
def get_connected_user(): """ Return the list of connected users. """ usernames = clients.keys() data = json.dumps(usernames) emit('on_client_list_received', data)
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)
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'})
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)
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)
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)
def broadcast_to_room(room_id, msg): print 'broadcasting: ' + msg emit('room_broadcast', {'msg': msg, 'room': room_id }, room=room_id)
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)
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')
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')
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")
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")
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"
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)))})
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"
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'
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")
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()
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)
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)
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)
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")
def leave_room(message): room = message['room'] del rooms[room][current_user.username] print() print(rooms) print() emit("infogroom",{"rooms":rooms},broadcast = True)
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()
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"
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)
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)
def send_next(): print('Broadcast Next Round.\n') emit('next-round', broadcast=True)
def restart(): app.g = Game() print('\nStart a new game.') emit('next-round', broadcast=True)