def get_delta(sock): print 'GET DELTA' message = protocol_pb2.Message() message.id = 7 message.type = protocol_pb2.Message.GET_DELTA message.get_delta.from_generation = 11 message.get_delta.share = '2867b9fd-5cac-4d01-9c72-be2f769b7429' message.get_delta.from_scratch = False send_protobuf(sock, message) listing = True files = [] while listing: rep = recv_message(sock) if rep.type == protocol_pb2.Message.DELTA_END: print 'delta end' listing = False elif rep.type == protocol_pb2.Message.DELTA_INFO: print 'rep type:', msg_type(rep), 'number', rep.id print 'generation:', rep.delta_info.generation, 'is_live:', rep.delta_info.is_live, 'type:', rep.delta_info.type print 'file infos:' print 'type:', rep.delta_info.file_info.type, 'parent:', rep.delta_info.file_info.parent, 'share:', rep.delta_info.file_info.share, 'node:', rep.delta_info.file_info.node, 'name:', rep.delta_info.file_info.name, 'is_public:', rep.delta_info.file_info.is_public, 'content hash:', rep.delta_info.file_info.content_hash, 'crc32:', rep.delta_info.file_info.crc32, 'size:', rep.delta_info.file_info.size, 'last modified:', rep.delta_info.file_info.last_modified files.append(rep.delta_info.file_info.name) else: print 'error', rep.error.type, rep.error.comment listing = False print '(', len(files), 'files )', files print ''
def run(self): while 1: """Приём собщений""" try: incoming_thread = protocol_pb2.Message() incoming_thread.ParseFromString(incoming_data(self.__stream)) # client_name = incoming_thread.client_name msg = incoming_thread.msg # if msg == 'chart_list': # for name in self.connected_clients.dict: # for name in self.connected_clients.dict: # self.connected_clients.dict[name].send_data( # self.connected_clients.string_of_online_clients() # ) for name in self.__connected_clients.dict: self.__connected_clients.dict[name].send_data(msg) except: print('Клиет {} вышел из чата'.format(self.__client_ip)) self.__connected_clients.remove_from_online_clients( self.__client_name) self.__stream.close() for name in self.__connected_clients.dict: self.__connected_clients.dict[name].send_data( self.__connected_clients.string_of_online_clients()) self.__connected_clients.dict[name].send_data( 'polzovatel2017:::Пользователь {} ' 'покинул чат'.format(self.__client_name)) break
def process_message(self, data): """Function called when a message is received""" msg = protocol_pb2.Message() msg.ParseFromString(data) # print 'Servent sent message id', msg.id, 'type', msg.type, 'msg:', msg if msg.id % 2 != 0: # Odd = it's a response to one of our requests try: self.requests[msg.id].process(msg) except KeyError as ke: # should not happen because it always should be in response to one of our previous requests print 'Server error on message : {} ({})'.format(msg, ke), # TODO: what to do ? self.io_loop.stop() except U1Requests.RequestException as re: # The request couldn't handle the response print 'Request exception: {}'.format(re) self.io_loop.stop() except Exception as e: # whatever happened print 'Unhandled exception: {}'.format(e) self.io_loop.stop() else: # Even : it's an unsolicited message from the server # call the function handling this kind of messages req_name = U1Requests.msg_type(msg) handler = getattr(self, "handle_" + req_name, None) if handler is not None: handler(msg) else: # Not supposed to happen (obsolete protocol ?) raise Exception("Cant handle message '{}' {}".format(U1Requests.msg_type(msg), str(message).replace("\n", " "))) self.receive_message() # wait for a new message
def run(self): while 1: try: incoming_thread = protocol_pb2.Message() a = self.__client.receive_data() incoming_thread.ParseFromString(a) msg = incoming_thread.msg command_key = msg.split(':::') if command_key[0] == 'polzovatel2017': client_update_status = ' '.join(command_key[1:]) self.client_update_status(client_update_status) continue if command_key[0] == 'spisok2017': # clients_list = ' '.join(command_key[1:]) clients_list = (command_key[1]).split(';') self.__client.add_clients_list(clients_list) self.update_chart_list(clients_list) continue if msg == 'Авторизация не удалась': os._exit(0) self.handle_msg(msg) except: print('Сервер разорвал соединение') self.__client.close_conn() os._exit(0)
def query(sock): print 'QUERY' message = protocol_pb2.Message() message.id = 9 message.type = protocol_pb2.Message.QUERY query = message.query.add() query.share = '2867b9fd-5cac-4d01-9c72-be2f769b7429' query.node = '372abcb4-5d19-43ba-aa17-005a6aec9714' query.hash = 'sha1:6b163fa3bad47a62474afcb81fb9f27bcb549d82' send_protobuf(sock, message) print 'sent' rep = recv_message(sock) print 'rep type:', msg_type(rep) print ''
def recv_message(sock): """sad and ugly way to receive a message, and nothing more (temporary !!)""" received = 0 data = '' sizeLen = struct.calcsize("!I") while received < sizeLen: data += sock.read(sizeLen - received) received += len(data) msgLength = struct.unpack("!I", data[:sizeLen])[0] data = data[sizeLen:] received -= sizeLen while received < msgLength: data += sock.read(msgLength - received) received += len(data) rep = protocol_pb2.Message() rep.ParseFromString(data) return rep
def __init__(self, handler, kwargs): self.handler = handler # the u1 requests handler self.handler.requests[self.handler.msg_id] = self # Setting a function to call when the request is complete. try: self.callback = kwargs['callback'] except KeyError: # No callback given: do nothing self.callback = None # If the request has been created from an unsolicited server message, take it if 'unsolicited' in kwargs: self.message = kwargs['server_msg'] # the server message else: # Otherwise, initialize a new protobuf message self.message = protocol_pb2.Message() self.message.id = self.handler.msg_id self.handler.msg_id += 2 # to stay odd ! self.responses = [] self.states = {} # Dict of message type -> function to call self.counter = 0 # Response counter
def run(self): count = 0 maxcount = 3 while count < maxcount: my_message = input() if not my_message: print('Введена пустая строка') count += 1 continue if my_message == 'chart_list': print(self.__client.get_clients_list()) continue message = protocol_pb2.Message() message.msg = my_message message.client_name = self.__client.client_name self.__client.send_data(message.SerializeToString()) print('Перезапустите клиент') self.__client.close_conn() os._exit(0)
def send_message(sock, id, type, oauth_creds=None): message = protocol_pb2.Message() message.id = id message.type = type # Signs the message with oauth (only at authentication time) if oauth_creds is not None: client = oauthlib.oauth1.Client(oauth_creds["consumer_key"], oauth_creds["consumer_secret"], oauth_creds["token"], oauth_creds["token_secret"], signature_method=SIGNATURE_PLAINTEXT, signature_type=SIGNATURE_TYPE_QUERY) url, headers, body = client.sign('http://server') # Parse out the authentication parameters from the query string. auth_parameters = dict( (name, value) for name, value in parse_qsl(urlparse(url).query) if name.startswith('oauth_')) # add the authentication informations for key, value in auth_parameters.items(): param = message.auth_parameters.add() param.name = key param.value = value send_protobuf(sock, message)
def send_msg(self, msg): message = protocol_pb2.Message() message.msg = msg # message.client_name = self.client.client_name self.__client.send_data(message.SerializeToString())
def send_msg(in_conn, msg): message = protocol_pb2.Message() message.msg = msg message = message.SerializeToString() packed_len = struct.pack('>L', len(message)) write_volume(in_conn, packed_len + message)
def run(self): count = 0 maxcount = 3 try: while count < maxcount: """Аутефикация пользователя""" send_msg( self.__stream, 'Существующий пользователь - введите 1. Если хотите зарегистрироваться - введите 0' ) incoming_thread = protocol_pb2.Message() incoming_thread.ParseFromString(incoming_data(self.__stream)) msg = incoming_thread.msg if msg != '1' and msg != '0': send_msg(self.__stream, 'Введите либо 0 либо 1') count += 1 continue """Аутефикация существующего пользователя""" if msg == '1': send_msg(self.__stream, 'Введите имя пользователя') incoming_thread = protocol_pb2.Message() incoming_thread.ParseFromString( incoming_data(self.__stream)) client_name = incoming_thread.msg if client_name != database.read_name_by_name( client_name ) or self.__connected_clients.find_by_name(client_name): count += 1 send_msg( self.__stream, 'Имя пользователя не существует или пользователь онлайн,' ' попробуйте снова.' 'Осталось {} попыток'.format(maxcount - count)) continue send_msg(self.__stream, 'Введите пароль') incoming_thread = protocol_pb2.Message() incoming_thread.ParseFromString( incoming_data(self.__stream)) msg = incoming_thread.msg if msg != database.read_pass_by_name(client_name): count += 1 send_msg( self.__stream, 'Пароль введён неверно, попробуйте снова. ' 'Осталось {} попыток'.format(maxcount - count)) continue """Создаём поток для общения авторизованного клиента""" send_msg(self.__stream, 'Добро пожаловать в общий чат') data_thread = DataThread(self.__stream, self.__client_ip, self.__connected_clients, client_name) self.__connected_clients.add_online_clients( client_name, data_thread) for name in self.__connected_clients.dict: self.__connected_clients.dict[name].send_data( self.__connected_clients.string_of_online_clients( )) for name in self.__connected_clients.dict: self.__connected_clients.dict[name].send_data( 'polzovatel2017:::Пользователь {} ' 'присоединился к чату'.format(client_name)) data_thread.start() break """Аутефикация нового пользователя""" if msg == '0': send_msg( self.__stream, 'Введите имя пользователя. Только латинские буквы и цифры' ) incoming_thread = protocol_pb2.Message() incoming_thread.ParseFromString( incoming_data(self.__stream)) client_name = incoming_thread.msg if not client_name or validators.name_validator( client_name) == False: count += 1 send_msg( self.__stream, 'Неверный ввод, осталось {} попыток'.format( maxcount - count)) continue if client_name == database.read_name_by_name(client_name): count += 1 send_msg( self.__stream, 'Пользователь с таким именем существует, попробуйте снова.' 'Осталось {} попыток'.format(maxcount - count)) continue send_msg(self.__stream, 'Введите пароль') incoming_thread = protocol_pb2.Message() incoming_thread.ParseFromString( incoming_data(self.__stream)) client_pass = incoming_thread.msg if not client_pass or validators.name_validator( client_name) == False: count += 1 send_msg( self.__stream, 'Неверный ввод, осталось {} попыток'.format( maxcount - count)) continue send_msg( self.__stream, 'Пользователь {} добавлен, пройдите ' 'авторизацию для существующего пользователя'.format( client_name)) database.add_to_base(client_name, client_pass) count = 0 if count == maxcount: send_msg(self.__stream, 'Авторизация не удалась') except: print('Клиет {} вышел из чата'.format(self.__client_ip)) self.__stream.close()
def Send(self,datatype,data): res=protobuf.Message() res.messagetype=datatype res.data=data self.SendToUDP(res.SerializeToString())