def emit(self, tup, stream=None, anchors=[], direct_task=None): """Emit a new tuple to a stream. :param tup: a ``list`` representing the tuple to send to Storm, should contain only JSON-serializable data. :param stream: a ``str`` indicating the ID of the stream to emit this tuple to. Specify ``None`` to emit to default stream. :param anchors: a ``list`` of IDs of the tuples tuple should be anchored to. :param direct_task: an ``int`` which indicates the task to send the tuple to. """ if not isinstance(tup, list): raise TypeError('All tuples must be lists, received {!r} instead' .format(type(tup))) if _ANCHOR_TUPLE is not None: anchors = [_ANCHOR_TUPLE] msg = {'command': 'emit', 'tuple': tup} if stream is not None: msg['stream'] = stream msg['anchors'] = [x.id for x in anchors] if direct_task is not None: msg['task'] = direct_task send_message(msg)
def list_all(self, client_connection): chunk = b'' util.send_message(self.data_nodes[0].socket, 'list', self.chunk_size) chunk = util.get_instructions(self.data_nodes[0].socket, self.chunk_size) if chunk == '-1': util.send_message(client_connection, util.stop_phrase.decode("utf-8"), self.chunk_size) return False while chunk.find(util.stop_phrase.decode("utf-8")) == -1: util.send_message(client_connection, chunk, self.chunk_size) self.directory.append(chunk) chunk = util.get_instructions(self.data_nodes[0].socket, self.chunk_size) if chunk == '-1': util.send_message(client_connection, util.stop_phrase.decode("utf-8"), self.chunk_size) return False util.send_message(client_connection, util.stop_phrase.decode("utf-8"), self.chunk_size) return True
def to_servers(self, client_connection, filename): # TODO: after fixing padding broke upload ''' * downloads file to the middleware folder * uses distribute data to split and xor items into chunks for storage * makes sure that the file contains a number of chunks divisible by 4 * sends files to the storage nodes ''' os.makedirs('middle', exist_ok=True) got_chunks_to_middle = util.receive_file(client_connection, f'middle/{filename}', self.chunk_size) print(f'downloaded chunks: {got_chunks_to_middle}') for node in self.data_nodes: util.send_message(node.socket, f'{UPLOAD} {filename}', self.chunk_size) # login, run, foxy, download ch11.txt with open(f'middle/{filename}', 'rb') as f: buffer = f.read(4 * self.chunk_size) last_buffer = f.read(4 * self.chunk_size) while last_buffer: self.distribute_data(buffer) buffer = last_buffer last_buffer = f.read(4 * self.chunk_size) self.distribute_data(buffer, final_chunk=True) terminating_sequence = (util.stop_phrase).decode('utf-8') terminating_chunk = f'0{terminating_sequence}' for node in self.data_nodes: util.send_message(node.socket, terminating_chunk, self.chunk_size) return True
def on_connect_to_existing_request(**kwargs): with sqlite3.connect(DB_STRING) as con: con.row_factory = sqlite3.Row cursor = con.execute('SELECT * FROM rooms WHERE id=?', (kwargs['room_id'], )) row = cursor.fetchone() if row is None: result = '{} {} {}'.format(2, 0, 0) else: for i in range(1, 4): if row['player{}'.format(i)] is None: res = con.execute( 'UPDATE rooms SET player{}=? WHERE id=?'.format(i), ( kwargs['id'], kwargs['room_id'], )) res = con.execute( 'UPDATE players SET room_id=?, own_number=? WHERE id=?', (kwargs['room_id'], i, kwargs['id'])) result = '{} {} {}'.format(0, kwargs['room_id'], i) break print(row['player{}'.format(i)]) else: print('HERE') result = '{} {} {}'.format(1, 0, 0) print(result) send_message(id_to_regid[kwargs['id']], result, 'ROOMS_ACTIVITY', 'ROOMS_CONNECTION_RESULT')
def start_dialog(conn): while True: recv = receive_message(conn) send_message(conn, recv) if not recv: print('Connection broke') break
def handle_request(self, conn, code, data): try: code, ret = self.process(code, data) if isinstance(ret, dict): ret = json.dumps(ret) send_message(conn, ret, code) except Exception as e: self._send_error(conn, traceback.format_exc(), e)
def request(self, msg): if isinstance(msg, dict): msg = json.dumps(msg) sock = self.connect() send_message(sock, msg) code, response = recv_message(sock) sock.close() return (code, response)
def on_keep_alive_notification(**kwargs): message = time.time() try: reg_id = kwargs['reg_id'] if 'reg_id' in kwargs.keys() else \ get_player_row(kwargs['id'], kwargs['password'])['reg_id'] send_message(reg_id, message, 'KEEP_ALIVE', 0) except Exception as e: print(e)
def name(self): util.send_message(self.socket, IDENTITY, self.chunk_size) self.server_id = util.get_instructions(self.socket, self.chunk_size) #throwaway = util.get_instructions(self.socket, self.chunk_size) #logger.debug(f'throwaway chunk = {throwaway}') return self.server_id
def handle_request_all(self, conn, code, data): try: for code, ret in self.process_all(code, data): if isinstance(ret, dict): ret = json.dumps(ret) send_message(conn, ret, code) send_message(conn, "EOF", ReturnCode.EOF) except Exception as e: self._send_error(conn, traceback.format_exc(), e)
def on_my_money_request(**kwargs): if not authentificate_user(**kwargs): return with sqlite3.connect(DB_STRING) as con: con.row_factory = sqlite3.Row result = con.execute("SELECT coins FROM players WHERE id=?", (kwargs['id'], )) coins = result.fetchone()['coins'] send_message(id_to_regid[kwargs['id']], coins, 'NEW_ROOM_ACTIVITY', 'NEW_ROOM_MONEY')
def _send_error(self, conn, tb, e): strmsg = str(e) if strmsg == 'None': strmsg = e.__class__.__name__ msg = { 'exception': e.__class__.__name__, 'msg': strmsg, 'traceback': tb } send_message(conn, json.dumps(msg), ReturnCode.ERROR)
def request_all(self, msg): if isinstance(msg, dict): msg = json.dumps(msg) sock = self.connect() send_message(sock, msg, ReturnCode.YIELD) code = ReturnCode.OK while code == ReturnCode.OK: code, response = recv_message(sock) if code != ReturnCode.EOF: yield code, response sock.close()
def threaded_client(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as my_socket: my_socket.bind(('0.0.0.0', PORT)) my_socket.listen(0) connection = accepting_connection(my_socket) with connection as conn: while True: user_input = input() if len(user_input) > 0: send_message(conn, user_input) response = receive_message(conn) print(response)
def main(): driver = webdriver.Chrome(CHROME_DRIVER, chrome_options=webdriver.ChromeOptions()) whatsapp_service = WhatsApp(driver) message_service = Messages() for user in message_service.get_users(): whatsapp_service.open_chat(user) time.sleep(SLEEP_TIME) messages = message_service.get_messages(user) for message in messages: send_message(whatsapp_service, message) whatsapp_service.close()
def on_create_new_room_request(**kwargs): with sqlite3.connect(DB_STRING) as con: cursor = con.execute( "INSERT INTO rooms (name, password, whist_cost, bullet, " "rasp_exit, rasp_progression, without_three, no_whist_raspasy_exit," "stalingrad, ten_whist, game_type, player1) VALUES(?, ?, ?, ?, ?," "?, ?, ?, ?, ?, ?, ?)", ("room1", "", kwargs['whist_cost'], kwargs['bullet'], "6 7 7", "2 2 2", 1, 1, kwargs['stalingrad'], 1, kwargs['game_type'], kwargs['id'])) data = '{} {}'.format(0, cursor.lastrowid) send_message(id_to_regid[kwargs['id']], data, 'NEW_ROOM_ACTIVITY', 'ROOMS_NEW_ROOM_CREATION_RESULT')
def _login(self): username = input('username >> ') password = getpass('password >> ') util.send_message(self.socket, f'{username} {password}', self.chunk_size) instructions = util.get_instructions(self.socket, self.chunk_size) logger.debug(f'command received by client is {instructions}') if instructions == 'welcome': return True else: return False
def create_account(self, client_connection, command): username, password = (util.get_instructions(client_connection, self.chunk_size, False)).split() #util.send_message(connection, 'welcome', self.chunk_size) logged_in = 0 for node in self.data_nodes: data = f"{command} {username}-{password}" logger.debug("Data: " + data) util.send_message(node.socket, data, self.chunk_size) response = util.get_instructions(node.socket, self.chunk_size) print( f'\n\n response is {response} len of resp is {len(response)}') if response == '1': #util.send_message(connection, 'welcome', self.chunk_size) logged_in += 1 elif response == '2': #util.send_message(connection, 'error: account already exists, try a different username or login', self.chunk_size) continue elif response == '-1': util.send_message(client_connection, 'something went wrong', self.chunk_size) if logged_in == len(self.data_nodes): util.send_message(client_connection, 'welcome', self.chunk_size) else: util.send_message(client_connection, 'not welcome', self.chunk_size) return logged_in == len(self.data_nodes)
def __init_cppn(curr_cppn: CPPN = None): if websocket: send_message(websocket, 'Initializing CPPN ...') if target_image is not None and init: cppn = init_cppn_from_img(target_image, color=color) else: if curr_cppn is None: cppn = CPPN(color=color, img_size=image_size) else: cppn = curr_cppn cppn.reset() if websocket: send_message(websocket, '\tDone') send_numpy_array_as_image(websocket, cppn.render_image(), final=False) return cppn
def run(self): # 线程执行函数 log.print("开始执行脚本") execution_times = 0 while self.is_running: reg_info = engine.reg_info video_info = engine.video_info scene = reg_info[Common.KEY_REG_SCENE] width = video_info[Common.KEY_VIDEO_WIDTH] height = video_info[Common.KEY_VIDEO_HEIGHT] find_result = reg_info[Common.KEY_REG_FIND] if scene == Scene.HOMEPAGE: if ImageKey.KEY_EXPLORE not in find_result.keys(): self.left_drag(width, height) log.print("主页左移") else: self.normal_click(ImageKey.KEY_EXPLORE, find_result) if scene == Scene.EXPLORE: self.normal_click(ImageKey.KEY_MITAMA, find_result) log.print("点击御魂按钮") if scene == Scene.MITAMA: self.normal_click(ImageKey.KEY_EIGHT_SNAKE, find_result) log.print("点击八岐大蛇") if scene == Scene.MITAMA_DETAIL: self.normal_click(ImageKey.KEY_CHALLENGE, find_result) log.print("点击挑战") if scene == Scene.BATTLE: self.random_move(width, height) log.print("战斗中,随机位移") if scene == Scene.BATTLE_END1: self.shift_y_click(ImageKey.KEY_BATTLE_END1_THREE, find_result, 40) log.print("点击战斗结束1") if scene == Scene.BATTLE_END2: self.normal_click(ImageKey.KEY_BLESS_BAG, find_result) execution_times += 1 if execution_times >= config.EXECUTION_TIMES: self.stop() log.print("到达执行次数") log.print("点击战斗结束2,福袋") log.print("执行次数:" + str(execution_times)) sleep_time = random.randint(1000, config.ACTION_INTERVAL_TIME) log.print("当前场景:{0};脚本防检测,随机暂停{1}毫秒".format(scene, sleep_time)) self.msleep(sleep_time) send_message("御魂脚本运行结束", "御魂战斗次数:" + str(execution_times)) log.print("脚本运行结束")
def on_existing_rooms_request(**kwargs): ret_val = [] with sqlite3.connect(DB_STRING) as con: con.row_factory = sqlite3.Row result = con.execute("SELECT * FROM rooms") for row in result: id = row['id'] players = con.execute("SELECT * FROM players WHERE room_id=?", (id, )) players_number = 0 for p in players: players_number += 1 ret_val.append(RoomInfo(row, players_number)) data = json.dumps(ret_val, cls=MyEncoder) print(data) send_message(id_to_regid[kwargs['id']], data, 'ROOMS_ACTIVITY', 'ROOMS_EXISTING_ROOMS')
def on_signin_request(**kwargs): with sqlite3.connect(DB_STRING) as con: con.row_factory = sqlite3.Row result = con.execute( "SELECT * FROM players WHERE name=? AND password=?", (kwargs['login'], kwargs['password'])) try: row = result.fetchone() data = '{} {} {}'.format(row['id'], kwargs['login'], kwargs['password']) id_to_regid[row['id']] = kwargs['reg_id'] send_message(kwargs['reg_id'], data, 'ENTRY_ACTIVITY', 'ENTRY_LOGIN_RESULT') con.execute( "UPDATE players SET online=1, reg_id=? WHERE name=? AND password=?", (kwargs['reg_id'], kwargs['login'], kwargs['password'])) except TypeError: send_message(kwargs['reg_id'], "User not found!", 'ENTRY_ACTIVITY', 'ENTRY_LOGIN_RESULT')
def on_register_request(**kwargs): name = kwargs['login'] password = kwargs['password'] reg_id = kwargs['reg_id'] if not re.match('^[a-zA-Z][a-zA-Z_0-9]*$', name): send_message(kwargs['reg_id'], "Name should start with latin letter", 'ENTRY_ACTIVITY', 'ENTRY_REGISTRATION_RESULT') return if len(name) < 3: send_message(kwargs['reg_id'], "Name should be at least 3 characters long", 'ENTRY_ACTIVITY', 'ENTRY_REGISTRATION_RESULT') return if len(password) < MIN_PASSWORD_LENGTH: send_message( kwargs['reg_id'], "Password should be at least " "{} characters long".format(MIN_PASSWORD_LENGTH), 'ENTRY_ACTIVITY', 'ENTRY_REGISTRATION_RESULT') return with sqlite3.connect(DB_STRING) as con: result = con.execute("SELECT * FROM players WHERE name=?", (name, )) for row in result: send_message(kwargs['reg_id'], "Name already exists", 'ENTRY_ACTIVITY', 'ENTRY_REGISTRATION_RESULT') return cursor = con.execute( "INSERT INTO players (name, password, coins, online, reg_id) VALUES(?, ?, ?, ?, ?)", (name, password, START_COINS, True, reg_id)) data = '{} {} {}'.format(cursor.lastrowid, name, password) id_to_regid[cursor.lastrowid] = reg_id send_message(reg_id, data, 'ENTRY_ACTIVITY', 'ENTRY_REGISTRATION_RESULT') cherrypy.log("Registered player with name={} and password={}".format( name, password))
def login(self, client_connection): credentials = util.get_instructions(client_connection, self.chunk_size) #print(f'got credentials {credentials}') try: username, password = credentials.split() except: username = -1 password = -1 if username == -1: return False logged_in = 0 for node in self.data_nodes: util.send_message(node.socket, f'login {username}-{password}', self.chunk_size) result = util.get_instructions(node.socket, self.chunk_size) logger.debug( f'answer from server {node.host} is {result} type of result is {type(result)}' ) if result == '1': logged_in += 1 if logged_in == len(self.data_nodes): util.send_message(client_connection, 'welcome', self.chunk_size) return True else: util.send_message(client_connection, 'failed to log in', self.chunk_size) return False
def schedule_recurring_polls(team): channel_messages = {} all_recurring_polls = db_table.query( IndexName=DATABASE_INDEX_NAME, KeyConditionExpression=Key("team").eq(f"{team}:poll-recurring"), ScanIndexForward=False, ) for recurring_poll in all_recurring_polls["Items"]: print("recurring_poll", recurring_poll) channel = recurring_poll["channel"] if channel not in channel_messages: channel_messages[channel] = {} for scheduled_post in get_all_scheduled_posts(channel): msg_id = get_message_id(scheduled_post) channel_messages[channel][msg_id] = scheduled_post scheduled_messages = channel_messages[channel] for i in get_next_event_timestamps(recurring_poll["recurring"]): in_msg_id = i * 1000 + random.randint(0, 1000) to_schedule_message_id = f"{recurring_poll['uuid']}:{in_msg_id}" if to_schedule_message_id in scheduled_messages: del scheduled_messages[to_schedule_message_id] else: blocks, votes = get_blocks_for_polls( title=recurring_poll.get("title", "SORRY"), anonymous=recurring_poll["anonymous"], limit_votes=recurring_poll["limit_votes"], texts=recurring_poll["options"], created_by=recurring_poll["created_by"], scheduled=True, top_id=to_schedule_message_id, ) msg_id = send_message(channel, blocks=blocks, text="Recurring poll", post_at=i) db_table.put_item( Item={ "team": f"{team}:poll", "timestamp": in_msg_id, "created_by": recurring_poll["created_by"], "anonymous": recurring_poll["anonymous"], "votes": votes, "limit_votes": recurring_poll["limit_votes"], "scheduled_message_id": msg_id, }) print("deleting scheduled messages") for scheduled_messages in channel_messages.values(): for k, v in scheduled_messages.items(): delete_scheduled_message(channel, v["id"])
def listener(self): self.logger.info("listen") self.socket.listen(1) while True: self.logger.debug('waiting for a connection') conn, addr = self.socket.accept() self.logger.debug('accepted') try: code, data = recv_message(conn) self.logger.debug('recvall %s', data) if self.active: if code == ReturnCode.YIELD: self.handle_request_all(conn, code, data) else: self.handle_request(conn, code, data) else: msg = 'Server stopped' send_message(conn, msg, ReturnCode.STOPPED) except Exception as e: self._send_error(conn, traceback.format_exc(), e) finally: conn.close()
def on_all_data_about_room_request(**kwargs): with sqlite3.connect(DB_STRING) as con: con.row_factory = sqlite3.Row cursor = con.execute('SELECT * FROM rooms WHERE id=?', (kwargs['room_id'], )) row_room = cursor.fetchone() for k in row_room: print('{}'.format(k)) players_number = 0 players = [] player_names = [] for i in range(1, 4): k = 'player{}'.format(i) if row_room[k] is not None: players.append(row_room[k]) players_number += 1 cursor = con.execute('SELECT * FROM players WHERE id=?', (row_room[k], )) row_player = cursor.fetchone() player_names.append(row_player['name']) else: player_names.append('null') players.append('null') data = '{} {} {} {} {} {} {}'.format( row_room['name'], players_number, players[0], players[1], players[2], player_names[0], player_names[1], player_names[2], row_room['game_type'], ) send_message(id_to_regid[kwargs['id']], data, 'GAME_ACTIVITY', 'GAME_ROOM_INFO')
def create_account(self): counter = 0 password2, password, username = '', '', '' while counter <= 5: while counter <= 5 and (len(username) < 2 or username.find(' ') > -1): print('username must be at least 2 characters. no spaces') username = input('username\n>> ') counter += 1 continue while counter <= 5 and (len(password) < 4 or password.find(' ') > -1): print('password must be at least 4 characters, no spaces') password = getpass('password:\n>> ') counter += 1 continue while password != password2: password2 = getpass('repeat password:\n>> ') if password != password2: print('passwords don\'t match') util.send_message(self.socket, f'{username} {password}', self.chunk_size) instructions = util.get_instructions(self.socket, self.chunk_size) if instructions == 'welcome': return True else: counter += 1 if counter > 5: print('error getting credentials for new account') return False
def list_acc(self): dir_list = os.listdir(self.current_path) stringy_dir_list = '\n'.join(dir_list) logger.info(f'{stringy_dir_list}') dir_list = util.cut_chunks(stringy_dir_list) for item in dir_list: util.send_message(self.middleware_socket, item, self.chunk_size) util.send_message(self.middleware_socket, item, self.chunk_size) print('---sent all directory---') util.send_message(self.middleware_socket, (util.stop_phrase).decode('utf-8'), self.chunk_size)
def ack(self, tup): """Indicate that processing of a tuple has succeeded. :param tup: a :class:`base.Tuple` object. """ send_message({'command': 'ack', 'id': tup.id})
def send_game_state(self, game_state, active_player): players = {} with sqlite3.connect(DB_STRING) as con: con.row_factory = sqlite3.Row cur = con.execute("SELECT * FROM players WHERE room_id = ?", self.room_id); for row in cur: players[row['my_number']] = row message = '' if game_state == 1: message = "1 {} {} {} {} {}".format(active_player, self.room_row['current_trade_bet'], players[0]["current_trade_bet"], players[1]["current_trade_bet"], players[2]["current_trade_bet"]) if game_state == 2: talon_сards = self.room_row["talon"].split(' ') card = -1 if len(talon_сards) > 0: card = talon_сards[0] suit = get_suit(talon_сards[0]) with sqlite3.connect(DB_STRING) as con: con.execute("UPDATE rooms SET current_suit = ? WHERE id = ?", (suit, self.room_id)) if len(talon_сards) > 1: con.execute("UPDATE rooms SET talon = ? WHERE id = ?", (talon_сards[1], self.room_id)) message = "2 {} {}".format(active_player, card) if game_state == 3: message = "3 {} {} {} {} {}".format(active_player, self.room_row['talon'], players[0]['current_trade_bet'], players[1]['current_trade_bet'], players[2]['current_trade_bet']) if game_state == 4: message = "4 {} {}".format(active_player, self.room_row["current_trade_bet"]) if game_state == 5: message = "5 ".format(active_player, players[0]['my_current_role'], players[1]['my_current_role'], players[2]['my_current_role']) if game_state == 6 or game_state == 11: message = "{} {} {} {} {} {} {} " \ "{} {} {} {} {} {} {}".format(game_state, active_player, players[0]['my_mountain'], players[0]['my_bullet'], players[0]['my_whists_left'], players[0]['my_whists_right'], players[1]['my_mountain'], players[1]['my_bullet'], players[1]['my_whists_left'], players[1]['my_whists_right'], players[2]['my_mountain'], players[2]['my_bullet'], players[2]['my_whists_left'], players[2]['my_whists_right']) if game_state == 7: message = '7 {}'.format(active_player) if game_state == 8: message = '8 {} {}'.format(active_player, self.room_row['open_game']) if active_player != self.room_row['trade_winner'] and self.room_row['open_game'] == 1: self.send_passers_and_whisters_cards() if game_state == 9: message = '9 {} {} {} {} {} {}'.format(active_player, self.room_row['current_suit'], players[0]["last_card_move"], players[1]["last_card_move"], players[2]["last_card_move"], self.room_row["cards_on_table"]) if active_player != self.room_row['trade_winner'] and self.room_row['open_game'] == 1 and \ self.room_row["passers_cards_are_sent"] == 0: self.send_passers_and_whisters_cards() if game_state == 10: message = '10 {} {} {} {}'.format(active_player, players[0]['my_current_role'], players[1]['my_current_role'], players[2]['my_current_role']) for i in range(3): reg_id = id_to_regid[players[i][id]] send_message(reg_id, message, 'GAME_ACTIVITY', 'GAME_GAME_STATE_INFO')
def send_cards(self, cards, player): reg_id = id_to_regid[player] send_message(reg_id, cards, 'GAME_ACTIVITY', 'GAME_CARDS_ARE_SENT')
def fail(self, tup): """Indicate that processing of a tuple has failed. :param tup: a :class:`base.Tuple` object. """ send_message({'command': 'fail', 'id': tup.id})