def request(self, message, sock): super(LoginHandler, self).request(message, sock) uobj = json.loads(message.data) if uobj: try: uobj['name'] = uobj['name'].strip() uobj['passwd'] = "" # 先检查当前用户是否已经登录 """ if self.check_islogin_in_other_client(uobj['name']): return self.send_message(msg.Message(protocol.ERR_LOGIN_FAIL.TID, echo='当前用户已经在其它客户端登录')) """ if uobj['name'] == '': return self.send_message(msg.Message(protocol.ERR_LOGIN_FAIL.TID, echo='用户名为空')) exist_user = user.User.find_user_by_name(uobj['name']) if not exist_user: ouser = user.User(**uobj) ouser.save() else: return self.send_message(msg.Message(protocol.ERR_LOGIN_FAIL.TID, echo="用户已经存在") ouser.sid = sock.sid sock.set_data('login_user', ouser) self.record_loginuser(ouser) return self.send_message(self._obtain_s2c_msg(message.TID, data=None, echo=json.dumps({"id" : ouser.id, "name" : ouser.name, "score" : ouser.score}))) except Exception, oe: print(oe) return self.send_message(msg.Message(protocol.ERR_LOGIN_FAIL.TID, echo=str(oe))) return self.send_message(msg.Message(protocol.ERR_LOGIN_FAIL.TID, echo=str(uobj) + ",注册失败")) # 发送登录错误 def finalize(self, sock_data): pass # loguser = sock_data.get_data('login_user') # if loguser.name in self._server.app_dict['login_users']: # print("Finalize socket login data") # del self._server.app_dict['login_users'][loguser.name]
def listen_loop(socket): try: msg_data = socket.recv(DATA_SIZE) while RUNNING and msg_data: #msg = message.Message(data=message.unpack(data)) #msg.print() msg_recv = message.Message(data=message.unpack(msg_data)) if msg_recv.get_type() != 'ping': print(msg_recv) msg_data = socket.recv(DATA_SIZE) except Exception as e: print(e) print('Connection to server lost!!!')
def parse_message(self): raw_data = self.getmsg() if self.moredata: self.assemble_data(raw_data) else: self.msg = None #clear data before assign new data self.msg = message.Message() self.msg.parse_fromstr(raw_data) if len(self.msg._body) == self.msg.get_body_length(): self.moredata = False self.update_app() else: self.moredata = True
def GatherInput(self): while True: IP = '127.0.0.1' port = input("Target IP? ") msg = raw_input("Message? ") send = message.Message(msg, type='test', keepAlive='1', MLen=1024, port=self.home) self.ToSend.put(((IP, port), send))
def start(self): conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn.connect((self.host, self.port)) self.conn = connection.Connection(conn) msg = self.conn.get_message() print msg.decoded msg = message.Message() msg.encode({'username': '******'}) self.conn.send_message(msg) self.running = True
def loadData(self): fileName = self.dataDir + "/" + str(self.fileLoadNo) + ".data" if os.path.exists(fileName): with open(fileName) as fLoad: for line in fLoad: msgStr = line.strip() msg = message.Message() msg.buildMessage(msgStr) self.messageQueue.pushBack(msg) self.fileLoadNo += 1 else: time.sleep(self.interval)
def handle_updates(self, updates): """Hanles the update set and responses accordingly""" for update in updates: message_body = self.strip_update(update) if not message_body: break message = msg.Message(message_body) command = self.get_command(message) if command: self.execute_command(command, message) else: response = self.get_response(message) if response: self.send_message(message.get_chat_id(), response)
def __init__(self, **kwargs): """Constructor. Builds a ChRIS_authenticate object. This object acts as a functor that calls into a ChRIS object after checking the authentication of the caller. Args: achris_instance (ChRIS): the chris instance to authenticate against aself_name (string): this object's string name """ self._log = message.Message() self._log._b_syslog = True self.__name = "ChRIS_authenticate" self._name = 'auth' self.chris = None for key, val in kwargs.iteritems(): if key == 'chris': self.chris = val if key == 'name': self._name = val self.debug = message.Message(logTo='./debug.log') self.debug._b_syslog = True
def logout(self, uname): if uname in self.__authenticated_users.keys(): del self.__authenticated_users[uname] self.__logger.debug("We have removed " + uname + " from auth_users.") if uname in self.__timers.keys(): self.__timers[uname].die() del self.__timers[uname] self.__logger.debug("We have removed " + uname + " from timers.") self.__logger.info("User " + uname + " logged out.") if uname.startswith('demo_'): self.__db.delete_user(uname) self.__logger.debug("We have deleted demouser " + uname + ".") return m.Message(m.T_ACK, {}, "Bye.")
def dealMsg(recvMsg, recvConn, recvChannel, recvAck_tag, sender, queue, log): messageList = ast.literal_eval(recvMsg) postType = messageList['post_type'] user_id = messageList['user_id'] if postType == '' or user_id == '': recvConn.add_callback_threadsafe(recvChannel.basic_ack, recvAck_tag) log.error("loss of information attribute, message: %s" % recvMsg) else: if postType == 'request': # TODO: 测试 import requestMsg rMsg = requestMsg.RequestMsg( messageList['comment'], messageList['flag']) replyMessage = rMsg.accept() elif postType == 'message': msgType = messageList['msg_body_type'] if msgType == 'Shared': import messageShared msgShared = messageShared.SharedMessage(messageList['user_id'],messageList['message']) replyMessage = msgShared.sendMessage() elif msgType == 'Document': pass elif msgType == 'Image': pass elif msgType == 'Record': pass elif msgType == 'Face': pass elif msgType == 'Shake': pass elif msgType == 'Location': pass elif msgType == 'Contact': pass elif msgType == 'Show': pass elif msgType == 'Text': # TODO: 待测试 import message if messageList['message'] == '': messageList['message'] = '你没有发送内容' msgText = message.Message( messageList['user_id'], messageList['message']) replyMessage = msgText.sendMessage() elif postType == 'notice': pass log.info( "deal message success, the message is: %s, will send to queue..." % replyMessage) SendMsg(replyMessage, recvConn, recvChannel, recvAck_tag, sender, queue, log)
def send_request(isack, pro, ts_ack): if not isack: message_ts = str(pro.ts) + str(pro.pid) message_ts = int(message_ts) print("TS da mensagem enviada: ", message_ts) for process in p: tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp.connect((host, process.port)) m1 = message.Message(message_ts, isack) m_dumped = pickle.dumps(m1) x = tcp.send(m_dumped) tcp.close() pro.ts += 1 else: for process in p: tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp.connect((host, process.port)) m1 = message.Message(ts_ack, isack) m_dumped = pickle.dumps(m1) x = tcp.send(m_dumped) tcp.close()
def _send_objects(self): if self.vectors_to_send: if len(self.vectors_to_send) > 16: to_send = random.sample(self.vectors_to_send, 16) self.vectors_to_send.difference_update(to_send) else: to_send = self.vectors_to_send.copy() self.vectors_to_send.clear() with shared.objects_lock: for vector in to_send: obj = shared.objects.get(vector, None) if obj: self.send_queue.put( message.Message(b'object', obj.to_bytes()))
def __request(self, request): try: #print "sending:", request.type, request.args r = requests.post('https://suonto.com/', headers=hdrs, data=request.toJson()) if r.status_code == 502: return m.Message(m.T_ERR, {m.K_REASON: m.R_SERV_ERR}, "Server error.") #print "we got back:\nStatus Code:", str(r.status_code), "\n", r.text #print "request history:", r.history msg = m.construct_message(r.text) #print msg, msg.args if msg: return msg else: return m.Message(m.T_ERR, { m.K_REASON: m.R_SERV_ERR, m.K_STATUS_CODE: r.status_code }, "invalid message from server.") except ValueError, e: return m.Message(m.T_ERR, {m.K_REASON: m.R_SERV_ERR}, "Error. Invalid message from server.")
def start(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((self.host, self.port)) self.server_socket.listen(1) conn, self.addr = self.server_socket.accept() self.conn = connection.Connection(conn) msg = message.Message() msg.encode({'type': 'start', 'param':{'turnLimit':200}}) self.conn.send_message(msg) msg = self.conn.get_message() print msg.decoded
def test_processMessage(self): # discover message Message discover_msg: msg.Message = msg.Message(TEAM_NAME, DISCOVER, None, None, None, None) res = self.server_side.process_message(discover_msg) res_message: msg.Message = self.encoder_decoder.decode(res) self.assertEqual(res_message.type, OFFER) #request, with ack request_msg: msg.Message = msg.Message( TEAM_NAME, REQUEST, "12abf551138756adc2a88edc23cb77b1832b7ab8", '3', 'aaa', 'ccc') res = self.server_side.process_message(request_msg) res_message: msg.Message = self.encoder_decoder.decode(res) self.assertEqual(res_message.type, ACK) #request with nack request_msg: msg.Message = msg.Message( TEAM_NAME, REQUEST, "12abf551138756adc2a88edc23cb77b1832b7ab8", '3', 'aad', 'ccc') res = self.server_side.process_message(request_msg) res_message: msg.Message = self.encoder_decoder.decode(res) self.assertEqual(res_message.type, NACK)
def __init__(self, screen): self.screen = screen self.wm = screen.wm self.message = message.Message( screen, self.window_font, self.window_draw, self.window_foreground, self.window_background, self.window_bordercolor, self.window_borderwidth, 0) # no timeouts self.clients = None
def validate_str(self, data_str): '''验证收到的消息所包含的信息''' print(data_str[:2]) if data_str[:2] == '21': str_json = data_str[3:len(data_str) - 7] dump = json.loads(str_json) if dump['SendMsgType'] == 0: nick_name = dump['IMNickName'] content = dump['Content'] m = message.Message() m.send_message(content, nick_name) elif dump['SendMsgType'] == 1: group_name = dump['GroupName'] content = dump['Content'] m = message.Message() m.send_chatroom_mseeage(content, group_name) elif data_str[:2] == '22': str_json = data_str[3:len(data_str) - 7] dump = json.loads(str_json) gname = dump['GroupName'] m = message.Message() m.obtain_chatroom_member(gname)
def request(self, message, sock): super(LoginHandler, self).request(message, sock) uobj = json.loads(message.data) if uobj: try: uobj['name'] = uobj['name'].strip() uobj['passwd'] = uobj['passwd'].strip() # 先检查当前用户是否已经登录 if self.check_islogin_in_other_client(uobj['name']): return self.send_message( msg.Message(protocol.ERR_LOGIN_FAIL.TID, echo='当前用户已经在其它客户端登录')) if uobj['name'] == '' or uobj['passwd'] == '': return self.send_message( msg.Message(protocol.ERR_LOGIN_FAIL.TID, echo='用户名或密码为空')) ouser = user.User.find_user_by_name(uobj['name']) if ouser.passwd != uobj['passwd']: return self.send_message( msg.Message(protocol.ERR_LOGIN_FAIL.TID, echo='密码错误')) if not ouser: ouser = user.User(**uobj) ouser.save() ouser.sid = sock.sid sock.set_data('login_user', ouser) self.record_loginuser(ouser) return self.send_message( self._obtain_s2c_msg(message.TID, data=None, echo=uobj['name'])) except Exception, oe: return self.send_message( msg.Message(protocol.ERR_LOGIN_FAIL.TID, echo=str(oe)))
def register(self, uname, h, token): if not self.__check_credentials(uname, h): return m.Message(m.T_ERR, {m.K_REASON: m.R_BLACKLIST}, "Welcome to blacklist.") self.__logger.info("We are registering " + uname + ".") creds = self.__db.get_user_credentials() if uname in creds: self.__logger.info("Registration for " + uname + " failed. Username already in use.") return m.Message(m.T_FAIL, {m.K_REASON: m.R_UNAME_TAKEN}, "Username already in use.") f = open(REG_TOKENS, "r") tokens = f.read() write_back = "" success = False result = m.Message(m.T_FAIL, {m.K_REASON: m.R_INVALID_TOKEN}, "Invalid token.") for t in tokens.split('\n'): if t == token and len(t) == 32: self.__db.store_user_credentials(uname, h) result = m.Message( m.T_ACK, {}, "User " + uname + " registered successfully.") success = True self.__logger.info("Registration for " + uname + " successful.") elif len(t) == 32: write_back += t + '\n' else: pass f.close() if success == False: self.__logger.info("Registration for " + uname + " failed. Invalid token.") else: f = open(REG_TOKENS, "w") f.write(write_back) return result
def handle_user_command(client, msg): # break the text into components of the command cmds = msg.get_text().split() ## NAME COMMAND if cmds[0] == '/name': prev_name = client.name_color + client.name client.name = '' client.get_name() # this code tells the chat room that a user changed their name # by popular demand this was removed # msg_name_change = message.Message() # msg_name_change.set_time(get_time()) # msg_name_change.set_type('text') # msg_name_change.set_text('{} changed their name to {}'.format(prev_name, client.name)) # broadcast(message.pack(msg_name_change)) return True ## NAME COLOR COMMAND elif cmds[0] == '/color': if len(cmds) > 1: if cmds[1] in USER_COLORS: #print('set {} color to red'.format(client.name)) client.name_color = cmds[1] else: client.name_color = None else: client.name_color = None return True ## CLAN COMMAND elif cmds[0] == '/clan': if len(cmds) > 1: if cmds[1] == 'leave': client.clan = None return True elif len(cmds[1]) <= 4: client.clan = cmds[1] return True return False ## HELP COMMAND elif cmds[0] == '/help': msg_help = message.Message() msg_help.set_type('text') msg_help.set_text('\n\t/help - show help\n\t/name <new name> - change your name\n\t/color [red, green, yellow, blue, purple, cyan] - change name color WIP\n\t/clan leave/<4 characters> - leave or join a clan') client.send(message.pack(msg_help)) return True return False
def __init__(self, **kwargs): # This class contains a reference back to the chris parent object that # contains this DB self._str_apiCall = "" self.debug = message.Message(logTo='./debug.log') self.debug._b_syslog = True self._log = message.Message() self._log._b_syslog = True self.__name = "ChRIS_SMUserDB" self.str_DBpath = '/tmp' self.str_VERB = "" self.str_APIcall = "" self.chris = None self.b_createNewDB = 0 self.b_ignorePersistentDB = False self.b_readDB = False self.DB = C_snode.C_stree() self.userTree = None for key, value in kwargs.iteritems(): if key == "chris": self.chris = value if key == 'ignorePersistentDB': self.b_ignorePersistentDB = value if key == 'DB': self.str_DBpath = value if key == 'createNewDB': self.b_createNewDB = value if key == 'VERB': self.str_VERB = value if key == 'APIcall': self.str_APIcall = value self.debug = message.Message(logTo="./debug.log") self.debug._b_syslog = True self._md5 = hashlib # The entire DataBase is represented here as a tree self.DB_build()
def onboarding_message(self, team_id, user_id): """ Crea y manda un mensaje de bienvenida a un nuevo usuario. ---------- team_id: [str] id del equipo de Slack asociado al evento user_id: [str] id del usuario de Slack asociado al evento """ if self.messages.get(team_id): self.messages[team_id].update({user_id: message.Message()}) else: self.messages[team_id] = {user_id: message.Message()} message_obj = self.messages[team_id][user_id] message_obj.channel = self.open_dm(user_id) message_obj.create_attachments() post_message = self.client.api_call( 'chat.postMessage', channel=message_obj.channel, username=self.name, icon_emoji=self.emoji, text=message_obj.text, attachments=message_obj.attachments) timestamp = post_message['ts'] message_obj.timestamp = timestamp
def part_two(args, input_lines): "Process part two of the puzzle" # 1. Create the puzzle solver solver = message.Message(part2=True, text=input_lines) # 2. Determine the solution for part two solution = solver.part_two(verbose=args.verbose, limit=args.limit) if solution is None: print("There is no solution") else: print("The solution for part two is %s" % (solution)) # 3. Return result return solution is not None
def run(self, message_obj): conn = self.get_connection(message_obj.from_client_key) lobby_id = message_obj["lobby_id"] joined = self.database.join_lobby(conn.client_key, lobby_id) if joined: message_obj.message = message_obj.new_message( SERVER_NAME, lobby_id, "192.0.0.1", "8223") conn = message_obj else: err_msg = msg.Message(message_obj.from_client_key, "s") err_msg.message = err_msg.new_message(Action_status.TYPE_LOBBY, False, "Lobby Unavailable")
def login(self): #msg = m.Message(m.T_LOGIN, {m.K_USER : self.__uname, m.K_HASH : self.hex_hash(self.__pp)}, "User "+self.__uname+" requesting authentication.") msg = m.Message(m.T_LOGIN, { m.K_USER: self.__uname, m.K_HASH: self.hex_hash(self.__pp) }, "User " + self.__uname + " requesting authentication.") response = self.__request(msg) if response.type == m.T_RESPONSE: self.__priv = self.import_rsa() self.__pkcs1 = PKCS1_OAEP.new(self.__priv) self.__sid = response.args[m.K_SID] self.__state = S_AUTH else: self.__sid = None self.__state = S_NOT_AUTH return response
def test_text_init(self): "Test the Message object creation from text" # 1. Create Message object from text myobj = message.Message(text=aoc_06.from_text(EXAMPLE_TEXT)) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(len(myobj.text), 16) self.assertEqual(len(myobj.columns), 6) self.assertEqual(myobj.columns[0].most_common()[0][0], 'e') self.assertEqual(myobj.columns[1].most_common()[0][0], 'a') # 3. Check methods self.assertEqual(myobj.most_common(), 'easter') self.assertEqual(myobj.least_common(), 'advent')
def respond(self, event): msg = message.Message(event) response = msg.get_response() if response == "do nothing": pass elif response == "random message": self.random_message(msg) elif response == "say hi": self.say_hi(msg) elif response == "say meow": self.say_meow(msg)
def __init__(self, **kwargs): ''' Constructor ''' self.__name = 'unnamed pipeline' self._log = message.Message() self._pipeline = [] self._verbosity = 0 self._b_poststdout = False self._b_poststderr = False for key, value in kwargs.iteritems(): if key == 'name': self.name(value) if key == 'fatalConditions': self.fatalConditions(value) if key == 'syslog': self.log().syslog(value) if key == 'verbosity': self.verbosity(value) if key == 'logTo': self.log().to(value) if key == 'logTee': self.log().tee(value)
def parse(self): list_of_messages = [] set_of_senders = set() for l in self.raw_messages: content = l["message"].encode("utf-8") sender = l["from"].encode("utf-8") datetime_str = l["datetime"].encode("utf-8") date, time = datetime_str.split("T") time = time.replace("+0000", "") msg_date = date + " " + time datetime_obj = datetime.strptime(msg_date, "%Y-%m-%d %H:%M:%S") set_of_senders.add(sender) list_of_messages.append( message.Message(sender, content, date, time, datetime_obj)) return list(set_of_senders), list_of_messages
def main(): # create a database connection conn = create_connection(database) # create a new message req_data1 = open('./data.json', 'r') req_data1 = req_data1.read() print(req_data1) req_data = json.loads(req_data1) application_id = req_data['application_id'] session_id = req_data['session_id'] message_id = req_data['message_id'] participants = req_data['participants'] participantss = json.dumps(req_data['participants']) content = req_data['content'] newMessage = message.Message(application_id, session_id, message_id, participantss, content) # create new message as json print('################ insert_new_message ########################') x = insert_new_message(conn, req_data) print(x) # create new message as object print('################ insert_new_message ########################') x = create_message(conn, newMessage) print(x) # selected message by applicatin id print( '################ selected message by application id ########################' ) x = select_massages_by_applicationId(conn, 5) print_results(x) # selected message by session id print( '################ selected message by session id ########################' ) x = select_massages_by_session_id(conn, "dd") print_results(x) # selected message by message id print( '################ selected message by message id ########################' ) x = select_massages_by_message_id(conn, "y") print_results(x)