def submit_message(self, data, original=None): corpus = self.get_corpus() corpus.set_writable() if not original: (msg, labels) = message.create_message(corpus, data) else: doc = corpus.get_doc(original) (msg, labels) = message.create_message(corpus, data, doc.get_msg(0)) corpus.mark_deleted(original) # Get labels. # We silently ignore unknown labels, # because we shouldn't throw any exception. def get_labels(labels): for name in labels: try: c = config.str2label(name) yield c except config.UnknownLabel: pass return labels = set(get_labels(labels)) # Resolve addresses. # We silently ignore unresolved addresses. def resolve1((user, addr)): if user: return formataddr((user, addr)) if addr in config.ADDRESS_ALIASES: return config.ADDRESS_ALIASES[addr] r = self.resolve_address(addr) if not r: return addr (n, x) = r[0] threshold = int(len(r) * config.RESOLVE_ADDRESS_RATIO + 0.5) if n <= threshold: return addr return x alt_headers = [] for (k, v) in msg.items(): if k.lower() in ('to', 'cc', 'bcc'): v = ', '.join(resolve1(addr) for addr in unicode_getaddrs(v)) alt_headers.append((k, v)) for (k, _) in alt_headers: del msg[k] for (k, v) in alt_headers: msg[k] = v loc = corpus.add_message(msg_repr(msg), labels) corpus.flush(self.notice_indexing) # show the edited message. self.select_tmp('edit', corpus, [loc]) return loc
def submit_message(self, data, original=None): corpus = self.get_corpus() corpus.set_writable() if not original: (msg, labels) = message.create_message(corpus, data) else: doc = corpus.get_doc(original) (msg, labels) = message.create_message(corpus, data, doc.get_msg(0)) corpus.mark_deleted(original) # Get labels. # We silently ignore unknown labels, # because we shouldn't throw any exception. def get_labels(labels): for name in labels: try: c = config.str2label(name) yield c except config.UnknownLabel: pass return labels = set(get_labels(labels)) # Resolve addresses. # We silently ignore unresolved addresses. def resolve1((user,addr)): if user: return formataddr((user, addr)) if addr in config.ADDRESS_ALIASES: return config.ADDRESS_ALIASES[addr] r = self.resolve_address(addr) if not r: return addr (n, x) = r[0] threshold = int(len(r)*config.RESOLVE_ADDRESS_RATIO + 0.5) if n <= threshold: return addr return x alt_headers = [] for (k,v) in msg.items(): if k.lower() in ('to', 'cc', 'bcc'): v = ', '.join( resolve1(addr) for addr in unicode_getaddrs(v) ) alt_headers.append((k,v)) for (k,_) in alt_headers: del msg[k] for (k,v) in alt_headers: msg[k] = v loc = corpus.add_message(msg_repr(msg), labels) corpus.flush(self.notice_indexing) # show the edited message. self.select_tmp('edit', corpus, [loc]) return loc
def concat_fragments(self, fragments): frame = fragments[0] for f in fragments[1:]: frame.payload += f.payload frame.final = True frame = self.sock.apply_recv_hooks(frame, True) return create_message(frame.opcode, frame.payload)
def main(): try: spend = slack.sum_spend(util.yesterday()) if spend > 0: damage_message = message.create_message(spend) slack_api.post_message(damage_message) except Exception as e: print(e) raise e
def on_receive(self, connection_handler, message): """ on event of receiving a message from an existing connection """ if message.payload_descriptor == GnutellaBodyId.PING: # check if we saw this ping before. If not, then process forward_key = (message.message_id, GnutellaBodyId.PONG) now = time.time() not_seen_or_expire = forward_key not in self.forwarding_table or (self.forwarding_table[forward_key][1] < now) not_ignore_or_expire = message.message_id not in self.ignore or (self.ignore[message.message_id] < now) if not_seen_or_expire and not_ignore_or_expire: # send Ping to any neighbor that not the one servent recceived the Ping from self.flood(connection_handler, message) # add ping to forwarding table to forward PONG self.put_into_forwarding_table(message, connection_handler) # reply with Pong (the return trip's ttl should be equals to hops) pong_message = create_message(GnutellaBodyId.PONG, message.message_id, message.hops+1, ip = self.reactor.ip, port = self.reactor.port, num_of_files = self.num_files, num_of_kb = self.num_kilobytes) self.log("Sending replied pong %s", pong_message) self.send_message(pong_message, connection_handler) elif message.payload_descriptor == GnutellaBodyId.PONG: # forwarding pong self.forward(message) elif message.payload_descriptor == GnutellaBodyId.QUERY: # check if we saw this query before. If not, then process forward_key = (message.message_id, GnutellaBodyId.QUERYHIT) now = time.time() not_seen_or_expire = forward_key not in self.forwarding_table or (self.forwarding_table[forward_key][1] < now) not_ignore_or_expire = message.message_id not in self.ignore or (self.ignore[message.message_id] < now) if not_seen_or_expire and not_ignore_or_expire: # add to forwarding table to forward QUERYHIT self.put_into_forwarding_table(message, connection_handler) # forward query packet to neighbor servent self.flood(connection_handler, message) elif message.payload_descriptor == GnutellaBodyId.QUERYHIT: # don't route query hit if it is meant for this node if not message.body.servent_id == self.id: # forwarding query hit if self.forward(message): # add to forwarding table to forward PUSH self.put_into_forwarding_table(message, connection_handler) elif message.payload_descriptor == GnutellaBodyId.PUSH: # don't route push if it is meant for this node if not message.body.servent_id == self.id: # forward push self.forward(message) else: raise ValueError('message type is not one of PING, PONG, QUERY, QUERYHIT, PUSH')
def create_out_buffer(self, socket): if socket.isJson: socket.inBuffer.decode() socket.request_body = json.loads(socket.inBuffer) command = socket.request_body["command"] #if the command on the request is a supported command, we will generate a response according to the command #callback, otherwise we return an error to the client response = self.actions[command]( socket) if command in self.actions else { 'error': "no such command" } socket.inBuffer = b'' socket.outBuffer = message.create_message(response)
def send_messages(service, users, mes, subject, attachments=None): print(users) for k, v in users: f = m.format_message(k, mes) s = m.format_message(k, subject) if attachments: formed_message = m.create_message_with_attachment(v, s, f, attachments) print("sending to: " + k) m.send_message(service, "me", formed_message) else: formed_message = m.create_message(v, s, f) print("sending to: " + k) m.send_message(service, "me", formed_message)
def handle(self, data, address): message = create_message(data) if (address[0] in settings.OWN_IP_ADDRESSES): return elif message is None: # discard message print "Datagram with unknown message received" elif isinstance(message, HiMessage): self.handle_hi_message(message, address[0]) elif isinstance(message, YoMessage): self.handle_yo_message(message, address[0]) elif isinstance(message, ByeMessage): self.handle_bye_message(message, address[0]) elif isinstance(message, FileMessage): self.handle_file_message(message, address[0])
t.add_row(dic.values()) print(t) return s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost', 50000)) greeting = read_message(s) path = greeting["path"] print(greeting["message"]) while True: inputStr = input(path + ">") if inputStr == "exit": break request = create_request(inputStr) s.send(message.create_message(request)) response = read_message(s) if type(response) is dict and "error" in response: print(response["error"]) continue command = request["command"] if command == 'cd': path = response['path'] elif command == 'dirlist': print("Path: " + path) print("Files:") print_table(response['files']) elif command == "download": f = open(request["arg"], "wb") f.write(response)
def listen(self): self.server_socket.listen(5) inputs = [self.server_socket] outputs = [] sockets = {} while True: readable, writable, exceptional = select.select( inputs, outputs, inputs) for s in readable: if s is self.server_socket: newSocket = s.accept()[0] newSocket.setblocking(0) inputs.append(newSocket) sockets[newSocket] = socketData.SocketData() sockets[newSocket].set_path(self.filesDir) greeting = { "message": "Welcome to the server", "path": str(PurePath(sockets[newSocket].path)) } sockets[newSocket].outBuffer = message.create_message( greeting) outputs.append(newSocket) else: try: data = s.recv(CHUNK) except: data = b'' if data: if sockets[s].inSize == 0: sockets[s].inSize = int( data[:HEADER_SIZE].decode()) sockets[s].isJson = True if int( data[HEADER_SIZE:HEADER_SIZE + 1].decode()) else False data = data[HEADER_SIZE + 1:] sockets[s].inBuffer += data sockets[s].inSize -= len(data) if sockets[s].inSize == 0: #if were done receiving a request from a socket, #we are now ready to generate a response and it send back. self.create_out_buffer(sockets[s]) outputs.append(s) else: if s in outputs: outputs.remove(s) inputs.remove(s) s.close() del sockets[s] for s in writable: nextPiece = sockets[s].outBuffer[:CHUNK] sockets[s].outBuffer = sockets[s].outBuffer[CHUNK:] try: s.send(nextPiece) except: outputs.remove(s) continue if not sockets[s].outBuffer: outputs.remove(s) for s in exceptional: inputs.remove(s) if s in outputs: outputs.remove(s) s.close() del sockets[s]