def getMessageNode(self, fmsg, child): requestNode = None serverNode = ProtocolTreeNode("server", None) xNode = ProtocolTreeNode("x", {"xmlns": "jabber:x:event"}, [serverNode]) childCount = (0 if requestNode is None else 1) + 2 messageChildren = [None] * childCount i = 0 if requestNode is not None: messageChildren[i] = requestNode i += 1 #System.currentTimeMillis() / 1000L + "-"+1 messageChildren[i] = xNode i += 1 messageChildren[i] = child i += 1 key = eval(fmsg.key) messageNode = ProtocolTreeNode("message", { "to": key.remote_jid, "type": "chat", "id": key.id }, messageChildren) return messageNode
def sendPaused(self, jid): composing = ProtocolTreeNode( 'paused', {'xmlns': 'http://jabber.org/protocol/chatstates'}) message = ProtocolTreeNode('message', { 'to': jid, 'type': 'chat' }, [composing]) self.out.write(message)
def getServerProperties(self): node = ProtocolTreeNode('list', {'xmlns': 'w:g', 'type': 'props'}) node_out = ProtocolTreeNode('iq', { 'id': str(int(time.time())) + '-0', 'type': 'get', 'to': 'g.us' }, [node]) self.out.write(node_out)
def handleLastOnline(self, node, jid=None): firstChild = node.getChild(0) ProtocolTreeNode.require(firstChild, 'query') seconds = firstChild.getAttributeValue('seconds') status = None status = firstChild.data if seconds is not None and jid is not None: self.connection.event.lastSeenUpdated.emit(int(seconds), jid)
def sendTyping(self, jid): print "SEND TYPING TO JID" composing = ProtocolTreeNode( "composing", {"xmlns": "http://jabber.org/protocol/chatstates"}) message = ProtocolTreeNode("message", { "to": jid, "type": "chat" }, [composing]) self.out.write(message)
def sendPaused(self, jid): print "SEND PAUSED TO JID" composing = ProtocolTreeNode( "paused", {"xmlns": "http://jabber.org/protocol/chatstates"}) message = ProtocolTreeNode("message", { "to": jid, "type": "chat" }, [composing]) self.out.write(message)
def sendGetGroups(self, group_type): node = ProtocolTreeNode('list', {'xmlns': 'w:g', 'type': group_type}) node_out = ProtocolTreeNode('iq', { 'id': str(int(time.time())) + '-0', 'type': 'get', 'to': 'g.us' }, [node]) self.out.write(node_out)
def sendMessageReceived(self, fmsg): receivedNode = ProtocolTreeNode("received", {"xmlns": "urn:xmpp:receipts"}) messageNode = ProtocolTreeNode("message", { "to": fmsg.key.remote_jid, "type": "chat", "id": fmsg.key.id }, [receivedNode]) self.out.write(messageNode)
def getParticipants(self, group): node = ProtocolTreeNode('list', {'xmlns': 'w:g'}) node_out = ProtocolTreeNode('iq', { 'id': str(int(time.time())) + '-0', 'type': 'get', 'to': group }, [node]) self.out.write(node_out)
def setGroupSubject(self, group, subject): node = ProtocolTreeNode('subject', {'xmlns': 'w:g', 'value': subject}) node_out = ProtocolTreeNode('iq', { 'id': str(int(time.time())) + '-0', 'type': 'set', 'to': group }, [node]) self.out.write(node_out)
def sendMessageReceived(self, fmsg): receivedNode = ProtocolTreeNode('received', {'xmlns': 'urn:xmpp:receipts'}) messageNode = ProtocolTreeNode('message', { 'to': fmsg.remote, 'type': 'chat', 'id': fmsg.id }, [receivedNode]) self.out.write(messageNode)
def handleGroupInfo(self,node,jid): groupNode = node.getChild(0) ProtocolTreeNode.require(groupNode,"group") gid = groupNode.getAttributeValue("id") owner = groupNode.getAttributeValue("owner") subject = groupNode.getAttributeValue("subject") subjectT = groupNode.getAttributeValue("s_t") subjectOwner = groupNode.getAttributeValue("s_o") creation = groupNode.getAttributeValue("creation") self.eventHandler.onGroupInfo(jid,owner,subject,subjectOwner,int(subjectT),int(creation))
def leaveGroup(self, group): group_nodes = [ProtocolTreeNode('group', {'id': group})] node = ProtocolTreeNode('leave', {'xmlns': 'w:g'}, group_nodes) node_out = ProtocolTreeNode('iq', { 'id': str(int(time.time())) + '-0', 'type': 'set', 'to': 'g.us' }, [node]) self.out.write(node_out)
def getReceiptAck(self, to, msg_id, receiptType): ackNode = ProtocolTreeNode("ack", { "xmlns": "urn:xmpp:receipts", "type": receiptType }) messageNode = ProtocolTreeNode("message", { "to": to, "type": "chat", "id": msg_id }, [ackNode]) return messageNode
def handleLastOnline(self,node,jid=None): firstChild = node.getChild(0); ProtocolTreeNode.require(firstChild,"query"); seconds = firstChild.getAttributeValue("seconds"); status = None status = firstChild.data try: if seconds is not None and jid is not None: self.eventHandler.onLastSeen(jid,int(seconds),status); except: self._d("Ignored exception in handleLastOnline "+ sys.exc_info()[1])
def sendPing(self): idx = self.makeId("ping_") self.stanzaReader.requests[idx] = self.stanzaReader.handlePingResponse pingNode = ProtocolTreeNode("ping", {"xmlns": "w:p"}) iqNode = ProtocolTreeNode("iq", { "id": idx, "type": "get", "to": self.domain }, [pingNode]) self.out.write(iqNode)
def handleLastOnline(self, node, jid=None): firstChild = node.getChild(0) ProtocolTreeNode.require(firstChild, "query") seconds = firstChild.getAttributeValue("seconds") status = None status = firstChild.data try: if seconds is not None and jid is not None: self.eventHandler.onLastSeen(jid, int(seconds), status) except: print "Ignored exception in handleLastOnline " + sys.exc_info()[1]
def sendPing(self): idx = self.makeId('ping_') self.stanzaReader.requests[idx] = \ self.stanzaReader.handlePingResponse pingNode = ProtocolTreeNode('ping', {'xmlns': 'w:p'}) iqNode = ProtocolTreeNode('iq', { 'id': idx, 'type': 'get', 'to': self.domain }, [pingNode]) self.out.write(iqNode)
def sendVerbParticipants(self, group, participants, verb): participant_nodes = map( lambda p: ProtocolTreeNode('participants', {'jid': p}), participants) node = ProtocolTreeNode(verb, {'xmlns': 'w:g'}, participant_nodes) node_out = ProtocolTreeNode('iq', { 'id': str(int(time.time())) + '-0', 'type': 'set', 'to': group }, [node]) self.out.write(node_out)
def sendIq(self): node = ProtocolTreeNode('iq', { 'to': 'g.us', 'type': 'get', 'id': str(int(time.time())) + '-0' }, None, 'expired') self.out.write(node) node = ProtocolTreeNode( 'iq', { 'to': 's.whatsapp.net', 'type': 'set', 'id': str(int(time.time())) + '-1' }, None, 'expired') self.out.write(node)
def sendIq(self): node = ProtocolTreeNode("iq", { "to": "g.us", "type": "get", "id": str(int(time.time())) + "-0" }, None, 'expired') self.out.write(node) node = ProtocolTreeNode( "iq", { "to": "s.whatsapp.net", "type": "set", "id": str(int(time.time())) + "-1" }, None, 'expired') self.out.write(node)
def sendSubscribe(self, to): presenceNode = ProtocolTreeNode('presence', { 'type': 'subscribe', 'to': to }) self.out.write(presenceNode)
def sendPong(self, idx): iqNode = ProtocolTreeNode("iq", { "type": "result", "to": self.domain, "id": idx }) self.out.write(iqNode)
def sendPong(self, idx): iqNode = ProtocolTreeNode('iq', { 'type': 'result', 'to': self.domain, 'id': idx }) self.out.write(iqNode)
def getReceiptAck( self, to, msg_id, receiptType, ): ackNode = ProtocolTreeNode('ack', { 'xmlns': 'urn:xmpp:receipts', 'type': receiptType }) messageNode = ProtocolTreeNode('message', { 'to': to, 'type': 'chat', 'id': msg_id }, [ackNode]) return messageNode
def sendAuth(self): node = ProtocolTreeNode( "auth", { "xmlns": "urn:ietf:params:xml:ns:xmpp-sasl", "mechanism": "DIGEST-MD5-1" }) self.out.write(node)
def sendMessageWithBody(self, fmsg): #bodyNode = ProtocolTreeNode("body",None,message.data); #self.out.write(self.getMessageNode(message,bodyNode)); bodyNode = ProtocolTreeNode("body", None, None, fmsg.content) self.out.write(self.getMessageNode(fmsg, bodyNode)) self.msg_id += 1
def sendSubscribe(self, to): presenceNode = ProtocolTreeNode("presence", { "type": "subscribe", "to": to }) self.out.write(presenceNode)
def readSuccess(self): node = self.inn.nextTree(); self._d("Login Status: %s"%(node.tag)); if ProtocolTreeNode.tagEquals(node,"failure"): self.loginFailed.emit() raise Exception("Login Failure"); ProtocolTreeNode.require(node,"success"); expiration = node.getAttributeValue("expiration"); if expiration is not None: self._d("Expires: "+str(expiration)); self.connection.expire_date = expiration; kind = node.getAttributeValue("kind"); self._d("Account type: %s"%(kind)) if kind == "paid": self.connection.account_kind = 1; elif kind == "free": self.connection.account_kind = 0; else: self.connection.account_kind = -1; status = node.getAttributeValue("status"); self._d("Account status: %s"%(status)); if status == "expired": self.loginFailed.emit() raise Exception("Account expired on "+str(self.connection.expire_date)); if status == "active": if expiration is None: #raise Exception ("active account with no expiration"); '''@@TODO expiration changed to creation''' else: self.connection.account_kind = 1; self.inn.inn.buf = []; self.loginSuccess.emit()
def sendClientConfig(self, sound, pushID, preview, platform): idx = self.makeId("config_") configNode = ProtocolTreeNode( "config", { "xmlns": "urn:xmpp:whatsapp:push", "sound": sound, "id": pushID, "preview": "1" if preview else "0", "platform": platform }) iqNode = ProtocolTreeNode("iq", { "id": idx, "type": "set", "to": self.domain }, [configNode]) self.out.write(iqNode)
def getSubjectMessage(self, to, msg_id, child): messageNode = ProtocolTreeNode("message", { "to": to, "type": "subject", "id": msg_id }, [child]) return messageNode
def getLastOnline(self, jid): if len(jid.split('-')) == 2: #SUPER CANCEL SUBSCRIBE TO GROUP return self.sendSubscribe(jid) print "presence request Initiated for %s" % (jid) idx = self.makeId("last_") self.stanzaReader.requests[idx] = self.stanzaReader.handleLastOnline query = ProtocolTreeNode("query", {"xmlns": "jabber:iq:last"}) iqNode = ProtocolTreeNode("iq", { "id": idx, "type": "get", "to": jid }, [query]) self.out.write(iqNode)
def getLastOnline(self, jid): if len(jid.split('-')) == 2: return self.sendSubscribe(jid) idx = self.makeId('last_') self.stanzaReader.requests[idx] = \ self.stanzaReader.handleLastOnline query = ProtocolTreeNode('query', {'xmlns': 'jabber:iq:last'}) iqNode = ProtocolTreeNode('iq', { 'id': idx, 'type': 'get', 'to': jid }, [query]) self.out.write(iqNode)
def parseCategories(self,dirtyNode): categories = {} if dirtyNode.children is not None: for childNode in dirtyNode.getAllChildren(): if ProtocolTreeNode.tagEquals(childNode,"category"): cname = childNode.getAttributeValue("name"); timestamp = childNode.getAttributeValue("timestamp") categories[cname] = timestamp return categories
def readSuccess(self): node = self.inn.nextTree() Utilities.debug("Login Status: " + node.tag) if ProtocolTreeNode.tagEquals(node, "failure"): self.loginFailed.emit() raise Exception("Login Failure") ProtocolTreeNode.require(node, "success") expiration = node.getAttributeValue("expiration") if expiration is not None: Utilities.debug("Expires: " + str(expiration)) self.connection.expire_date = expiration kind = node.getAttributeValue("kind") Utilities.debug("Account type: " + kind) if kind == "paid": self.connection.account_kind = 1 elif kind == "free": self.connection.account_kind = 0 else: self.connection.account_kind = -1 status = node.getAttributeValue("status") Utilities.debug("Account status: " + status) if status == "expired": self.loginFailed.emit() raise Exception("Account expired on " + str(self.connection.expire_date)) if status == "active": if expiration is None: # raise Exception ("active account with no expiration"); """@@TODO expiration changed to creation""" else: self.connection.account_kind = 1 self.inn.inn.buf = [] self.loginSuccess.emit()
def readFeaturesAndChallenge(self): server_supports_receipt_acks = True; root = self.inn.nextTree(); while root is not None: if ProtocolTreeNode.tagEquals(root,"stream:features"): #self._d("GOT FEATURES !!!!"); server_supports_receipt_acks = root.getChild("receipt_acks") is not None; root = self.inn.nextTree(); continue; if ProtocolTreeNode.tagEquals(root,"challenge"): #self._d("GOT CHALLENGE !!!!"); self.connection.supports_receipt_acks = self.connection.supports_receipt_acks and server_supports_receipt_acks; #String data = new String(Base64.decode(root.data.getBytes())); data = base64.b64decode(root.data); return data; raise Exception("fell out of loop in readFeaturesAndChallenge");
def readFeaturesAndChallenge(self): server_supports_receipt_acks = True root = self.inn.nextTree() while root is not None: if ProtocolTreeNode.tagEquals(root, 'stream:features'): server_supports_receipt_acks = \ root.getChild('receipt_acks') is not None root = self.inn.nextTree() continue if ProtocolTreeNode.tagEquals(root, 'challenge'): self.connection.supports_receipt_acks = \ self.connection.supports_receipt_acks \ and server_supports_receipt_acks # String data = new String(Base64.decode(root.data.getBytes())) data = base64.b64decode(root.data) return data raise Exception('fell out of loop in readFeaturesAndChallenge')
def readSuccess(self): node = self.inn.nextTree() if ProtocolTreeNode.tagEquals(node, 'failure'): self.connection.event.loginFailed.emit() raise LoginException('Login Failure') ProtocolTreeNode.require(node, 'success') expiration = node.getAttributeValue('expiration') if expiration is not None: self.connection.expire_date = expiration kind = node.getAttributeValue('kind') if kind == 'paid': self.connection.account_kind = 1 elif kind == 'free': self.connection.account_kind = 0 else: self.connection.account_kind = -1 status = node.getAttributeValue('status') if status == 'expired': self.connection.event.loginFailed.emit() raise LoginException('Account expired on ' + str(self.connection.expire_date)) if status == 'active': if expiration is None: pass else: self.connection.account_kind = 1 self.inn.inn.buf = [] self.connection.event.loginSuccess.emit()
def parseMessage(self,messageNode): #if messageNode.getChild("media") is not None: # return fromAttribute = messageNode.getAttributeValue("from"); author = messageNode.getAttributeValue("author"); fmsg = WAXMPP.message_store.createMessage(fromAttribute) fmsg.wantsReceipt = False conversation = WAXMPP.message_store.getOrCreateConversationByJid(fromAttribute); fmsg.conversation_id = conversation fmsg.Conversation = conversation msg_id = messageNode.getAttributeValue("id"); attribute_t = messageNode.getAttributeValue("t"); typeAttribute = messageNode.getAttributeValue("type"); if typeAttribute == "error": errorCode = 0; errorNodes = messageNode.getAllChildren("error"); for errorNode in errorNodes: codeString = errorNode.getAttributeValue("code") try: errorCode = int(codeString); except ValueError: '''catch value error''' message = None; if fromAttribute is not None and msg_id is not None: key = Key(fromAttribute,True,msg_id); message = message_store.get(key); if message is not None: message.status = 7 self.eventHandler.message_error(message,errorCode); elif typeAttribute == "subject": receiptRequested = False; requestNodes = messageNode.getAllChildren("request"); for requestNode in requestNodes: if requestNode.getAttributeValue("xmlns") == "urn:xmpp:receipts": receiptRequested = True; bodyNode = messageNode.getChild("body"); newSubject = None if bodyNode is None else bodyNode.data; if newSubject is not None and self.groupEventHandler is not None: self.groupEventHandler.group_new_subject(fromAttribute,author,newSubject,int(attribute_t)); if receiptRequested and self.eventHandler is not None: self.eventHandler.subjectReceiptRequested(fromAttribute,msg_id); elif typeAttribute == "chat": duplicate = False; wantsReceipt = False; messageChildren = [] if messageNode.children is None else messageNode.children for childNode in messageChildren: if ProtocolTreeNode.tagEquals(childNode,"composing"): if self.eventHandler is not None: self.eventHandler.typing_received(fromAttribute); elif ProtocolTreeNode.tagEquals(childNode,"paused"): if self.eventHandler is not None: self.eventHandler.paused_received(fromAttribute); elif ProtocolTreeNode.tagEquals(childNode,"media") and msg_id is not None: self._d("MULTIMEDIA MESSAGE!"); mediaItem = WAXMPP.message_store.store.Media.create() mediaItem.remote_url = messageNode.getChild("media").getAttributeValue("url"); mediaType = messageNode.getChild("media").getAttributeValue("type") msgdata = mediaType preview = None try: index = fromAttribute.index('-') #group conv contact = WAXMPP.message_store.store.Contact.getOrCreateContactByJid(author) fmsg.contact_id = contact.id fmsg.contact = contact except ValueError: #single conv pass if mediaType == "image": mediaItem.mediatype_id = WAConstants.MEDIA_TYPE_IMAGE mediaItem.preview = messageNode.getChild("media").data elif mediaType == "audio": mediaItem.mediatype_id = WAConstants.MEDIA_TYPE_AUDIO elif mediaType == "video": mediaItem.mediatype_id = WAConstants.MEDIA_TYPE_VIDEO elif mediaType == "location": mlatitude = messageNode.getChild("media").getAttributeValue("latitude") mlongitude = messageNode.getChild("media").getAttributeValue("longitude") mediaItem.mediatype_id = WAConstants.MEDIA_TYPE_LOCATION mediaItem.remote_url = None mediaItem.preview = messageNode.getChild("media").data mediaItem.local_path ="%s,%s"%(mlatitude,mlongitude) mediaItem.transfer_status = 2 elif mediaType =="vcard": return mediaItem.preview = messageNode.getChild("media").data else: self._d("Unknown media type") return fmsg.Media = mediaItem #if ProtocolTreeNode.tagEquals(childNode,"body"): This suposses handle MEDIA + TEXT # msgdata = msgdata + " " + childNode.data; But it's not supported in whatsapp? key = Key(fromAttribute,False,msg_id); fmsg.setData({"status":0,"key":key.toString(),"content":msgdata,"type":WAXMPP.message_store.store.Message.TYPE_RECEIVED}); elif ProtocolTreeNode.tagEquals(childNode,"body") and msg_id is not None: msgdata = childNode.data; #mediaItem = WAXMPP.message_store.store.Media.create() #mediaItem.mediatype_id = WAConstants.MEDIA_TYPE_TEXT #fmsg.Media = mediaItem fmsg.Media = None key = Key(fromAttribute,False,msg_id); fmsg.setData({"status":0,"key":key.toString(),"content":msgdata,"type":WAXMPP.message_store.store.Message.TYPE_RECEIVED}); elif not (ProtocolTreeNode.tagEquals(childNode,"active")): if ProtocolTreeNode.tagEquals(childNode,"request"): fmsg.wantsReceipt = True; elif ProtocolTreeNode.tagEquals(childNode,"notify"): fmsg.notify_name = childNode.getAttributeValue("name"); elif ProtocolTreeNode.tagEquals(childNode,"delay"): xmlns = childNode.getAttributeValue("xmlns"); if "urn:xmpp:delay" == xmlns: stamp_str = childNode.getAttributeValue("stamp"); if stamp_str is not None: stamp = stamp_str fmsg.timestamp = self.parseOfflineMessageStamp(stamp)*1000; fmsg.offline = True; elif ProtocolTreeNode.tagEquals(childNode,"x"): xmlns = childNode.getAttributeValue("xmlns"); if "jabber:x:event" == xmlns and msg_id is not None: key = Key(fromAttribute,True,msg_id); message = WAXMPP.message_store.get(key) if message is not None: WAXMPP.message_store.updateStatus(message,WAXMPP.message_store.store.Message.STATUS_SENT) if self.eventHandler is not None: self.eventHandler.message_status_update(message); elif "jabber:x:delay" == xmlns: continue; #TODO FORCED CONTINUE, WHAT SHOULD I DO HERE? #wtf? stamp_str = childNode.getAttributeValue("stamp"); if stamp_str is not None: stamp = stamp_str fmsg.timestamp = stamp; fmsg.offline = True; else: if ProtocolTreeNode.tagEquals(childNode,"delay") or not ProtocolTreeNode.tagEquals(childNode,"received") or msg_id is None: continue; key = Key(fromAttribute,True,msg_id); message = WAXMPP.message_store.get(key); if message is not None: WAXMPP.message_store.updateStatus(message,WAXMPP.message_store.store.Message.STATUS_DELIVERED) if self.eventHandler is not None: self.eventHandler.message_status_update(message); self._d(self.connection.supports_receipt_acks) if self.connection.supports_receipt_acks: receipt_type = childNode.getAttributeValue("type"); if receipt_type is None or receipt_type == "delivered": self.connection.sendDeliveredReceiptAck(fromAttribute,msg_id); elif receipt_type == "visible": self.connection.sendVisibleReceiptAck(fromAttribute,msg_id); if fmsg.timestamp is None: fmsg.timestamp = time.time()*1000; fmsg.offline = False; print fmsg.getModelData(); if self.eventHandler is not None: signal = True if fmsg.content: try: index = fromAttribute.index('-') #group conv contact = WAXMPP.message_store.store.Contact.getOrCreateContactByJid(author) fmsg.contact_id = contact.id fmsg.contact = contact except ValueError: #single conv pass if conversation.type == "group": if conversation.subject is None: signal = False self._d("GETTING GROUP INFO") self.connection.sendGetGroupInfo(fromAttribute) ret = WAXMPP.message_store.get(key); if ret is None: conversation.incrementNew(); WAXMPP.message_store.pushMessage(fromAttribute,fmsg) fmsg.key = key else: fmsg.key = eval(ret.key) duplicate = True; if signal: self.eventHandler.message_received(fmsg,duplicate);
def parseMessage(self,messageNode): #throw media in the garbage if messageNode.getChild("media") is not None: return fmsg = WAXMPP.message_store.store.Message.create() fmsg.wantsReceipt = False msg_id = messageNode.getAttributeValue("id"); attribute_t = messageNode.getAttributeValue("t"); fromAttribute = messageNode.getAttributeValue("from"); author = messageNode.getAttributeValue("author"); typeAttribute = messageNode.getAttributeValue("type"); if typeAttribute == "error": errorCode = 0; errorNodes = messageNode.getAllChildren("error"); for errorNode in errorNodes: codeString = errorNode.getAttributeValue("code") try: errorCode = int(codeString); except ValueError: '''catch value error''' message = None; if fromAttribute is not None and msg_id is not None: key = Key(fromAttribute,True,msg_id); message = message_store.get(key.toString()); if message is not None: message.status = 7 self.eventHandler.message_error(message,errorCode); elif typeAttribute == "subject": receiptRequested = False; requestNodes = messageNode.getAllChildren("request"); for requestNode in requestNodes: if requestNode.getAttributeValue("xmlns") == "urn:xmpp:receipts": receiptRequested = True; bodyNode = messageNode.getChild("body"); newSubject = None if bodyNode is None else bodyNode.data; if newSubject is not None and self.groupEventHandler is not None: self.groupEventHandler.group_new_subject(fromAttribute,author,newSubject,int(attribute_t)); if receiptRequested and self.eventHandler is not None: self.eventHandler.subjectReceiptRequested(fromAttribute,msg_id); elif typeAttribute == "chat": duplicate = False; wantsReceipt = False; messageChildren = [] if messageNode.children is None else messageNode.children for childNode in messageChildren: if ProtocolTreeNode.tagEquals(childNode,"composing"): if self.eventHandler is not None: self.eventHandler.typing_received(fromAttribute); elif ProtocolTreeNode.tagEquals(childNode,"paused"): if self.eventHandler is not None: self.eventHandler.paused_received(fromAttribute); elif ProtocolTreeNode.tagEquals(childNode,"body") and msg_id is not None: msgdata = childNode.data; key = Key(fromAttribute,False,msg_id); ret = WAXMPP.message_store.get(key.toString()); if ret is None: conversation = WAXMPP.message_store.getOrCreateConversationByJid(fromAttribute); fmsg.setData({"status":0,"key":key.toString(),"content":msgdata,"conversation_id":conversation.id,"type":WAXMPP.message_store.store.Message.TYPE_RECEIVED}); WAXMPP.message_store.pushMessage(fmsg) fmsg.key = key #if self.eventHandler is not None: #self.eventHandler.message_received(fmsg); else: fmsg.key = eval(ret.key) duplicate = True; elif not (ProtocolTreeNode.tagEquals(childNode,"active")): if ProtocolTreeNode.tagEquals(childNode,"request"): fmsg.wantsReceipt = True; elif ProtocolTreeNode.tagEquals(childNode,"notify"): fmsg.notify_name = childNode.getAttributeValue("name"); elif ProtocolTreeNode.tagEquals(childNode,"x"): xmlns = childNode.getAttributeValue("xmlns"); if "jabber:x:event" == xmlns and msg_id is not None: key = Key(fromAttribute,True,msg_id); message = WAXMPP.message_store.get(key.toString()); if message is not None: WAXMPP.message_store.updateStatus(message,WAXMPP.message_store.store.Message.STATUS_SENT) if self.eventHandler is not None: self.eventHandler.message_status_update(message); elif "jabber:x:delay" == xmlns: continue; #TODO FORCED CONTINUE, WHAT SHOULD I DO HERE? #wtf? stamp_str = childNode.getAttributeValue("stamp"); if stamp_str is not None: stamp = stamp_str fmsg.timestamp = stamp; fmsg.offline = True; else: if ProtocolTreeNode.tagEquals(childNode,"delay") or not ProtocolTreeNode.tagEquals(childNode,"received") or msg_id is None: continue; key = Key(fromAttribute,True,msg_id); message = WAXMPP.message_store.get(key.toString()); if message is not None: WAXMPP.message_store.updateStatus(message,WAXMPP.message_store.store.Message.STATUS_DELIVERED) if self.eventHandler is not None: self.eventHandler.message_status_update(message); print self.connection.supports_receipt_acks if self.connection.supports_receipt_acks: receipt_type = childNode.getAttributeValue("type"); if receipt_type is None or receipt_type == "delivered": self.connection.sendDeliveredReceiptAck(fromAttribute,msg_id); elif receipt_type == "visible": self.connection.sendVisibleReceiptAck(fromAttribute,msg_id); if fmsg.timestamp is None: fmsg.timestamp = time.time()*1000; fmsg.offline = False; if self.eventHandler is not None: self.eventHandler.message_received(fmsg,duplicate);
def run(self): flag = True; self._d("Read thread started"); while flag == True: self._d("waiting"); ready = select.select([self.inn.rawIn], [], []) if ready[0]: try: node = self.inn.nextTree(); except ConnectionClosedException: self._d("Socket closed, got 0 bytes") if self.eventHandler.connMonitor.isOnline(): self.eventHandler.connMonitor.connected.emit() return except: self._d("Unhandled error: %s .restarting connection " % sys.exc_info()[1]) if self.eventHandler.connMonitor.isOnline(): self.eventHandler.connMonitor.connected.emit() else: self._d("Not online, aborting restart") return self.lastTreeRead = int(time.time())*1000; if node is not None: if ProtocolTreeNode.tagEquals(node,"iq"): iqType = node.getAttributeValue("type") idx = node.getAttributeValue("id") jid = node.getAttributeValue("from"); if iqType is None: raise Exception("iq doesn't have type") if iqType == "result": if self.requests.has_key(idx): self.requests[idx](node,jid) del self.requests[idx] elif idx.startswith(self.connection.user): accountNode = node.getChild(0) ProtocolTreeNode.require(accountNode,"account") kind = accountNode.getAttributeValue("kind") if kind == "paid": self.connection.account_kind = 1 elif kind == "free": self.connection.account_kind = 0 else: self.connection.account_kind = -1 expiration = accountNode.getAttributeValue("expiration") if expiration is None: raise Exception("no expiration") try: self.connection.expire_date = long(expiration) except ValueError: raise IOError("invalid expire date %s"%(expiration)) self.eventHandler.onAccountChanged(self.connection.account_kind,self.connection.expire_date) elif iqType == "error": if self.requests.has_key(idx): self.requests[idx](node) del self.requests[idx] elif iqType == "get": childNode = node.getChild(0) if ProtocolTreeNode.tagEquals(childNode,"ping"): self.eventHandler.onPing(idx) elif ProtocolTreeNode.tagEquals(childNode,"query") and jid is not None and "http://jabber.org/protocol/disco#info" == childNode.getAttributeValue("xmlns"): pin = childNode.getAttributeValue("pin"); timeoutString = childNode.getAttributeValue("timeout"); try: timeoutSeconds = int(timeoutString) if timoutString is not None else None except ValueError: raise Exception("relay-iq exception parsing timeout %s "%(timeoutString)) if pin is not None: self.eventHandler.onRelayRequest(pin,timeoutSeconds,idx) elif iqType == "set": childNode = node.getChild(0) if ProtocolTreeNode.tagEquals(childNode,"query"): xmlns = childNode.getAttributeValue("xmlns") if xmlns == "jabber:iq:roster": itemNodes = childNode.getAllChildren("item"); ask = "" for itemNode in itemNodes: jid = itemNode.getAttributeValue("jid") subscription = itemNode.getAttributeValue("subscription") ask = itemNode.getAttributeValue("ask") else: raise Exception("Unkown iq type %s"%(iqType)) elif ProtocolTreeNode.tagEquals(node,"presence"): xmlns = node.getAttributeValue("xmlns") jid = node.getAttributeValue("from") if (xmlns is None or xmlns == "urn:xmpp") and jid is not None: presenceType = node.getAttributeValue("type") if presenceType == "unavailable": self.eventHandler.presence_unavailable_received(jid); elif presenceType is None or presenceType == "available": self.eventHandler.presence_available_received(jid); elif xmlns == "w" and jid is not None: add = node.getAttributeValue("add"); remove = node.getAttributeValue("remove") status = node.getAttributeValue("status") if add is not None: self._d("GROUP EVENT ADD") elif remove is not None: self._d("GROUP EVENT REMOVE") elif status == "dirty": categories = self.parseCategories(node); self.eventHandler.onDirty(categories); elif ProtocolTreeNode.tagEquals(node,"message"): self.parseMessage(node) '''
def parseMessage(self, messageNode): fmsg = Message() msg_id = messageNode.getAttributeValue('id') attribute_t = messageNode.getAttributeValue('t') fromAttribute = messageNode.getAttributeValue('from') author = messageNode.getAttributeValue('author') typeAttribute = messageNode.getAttributeValue('type') if fromAttribute is not None and msg_id is not None: fmsg.id = msg_id fmsg.remote = fromAttribute if typeAttribute == 'error': message = None errorCode = 0 errorNodes = messageNode.getAllChildren('error') for errorNode in errorNodes: codeString = errorNode.getAttributeValue('code') try: errorCode = int(codeString) except ValueError: message = None if message is not None: message.status = 7 self.connection.event.message_error(message, errorCode) elif typeAttribute == 'subject': receiptRequested = False requestNodes = messageNode.getAllChildren('request') for requestNode in requestNodes: if requestNode.getAttributeValue('xmlns') == 'urn:xmpp:receipts': receiptRequested = True bodyNode = messageNode.getChild('body') subject = (None if bodyNode is None else bodyNode.data) if subject is not None: self.connection.event.newGroupSubject.emit(group=fromAttribute, author=author, subject=subject) if receiptRequested: self.connection.event.subjectReceiptRequested(fromAttribute, msg_id) elif typeAttribute == 'chat': wants_receipt = False messageChildren = ([] if messageNode.children is None else messageNode.children) if author: fmsg.author = author for childNode in messageChildren: if ProtocolTreeNode.tagEquals(childNode, 'composing'): if self.connection.event is not None: self.connection.event.typing_received(fromAttribute) elif ProtocolTreeNode.tagEquals(childNode, 'paused'): if self.connection.event is not None: self.connection.event.paused_received(fromAttribute) elif ProtocolTreeNode.tagEquals(childNode,"media") and msg_id is not None: fmsg.type = "media" url = messageNode.getChild("media").getAttributeValue("url"); fmsg.media_type = media_type = messageNode.getChild("media").getAttributeValue("type") data = {} if media_type == "image": data['preview'] = messageNode.getChild("media").data data['url'] = url elif media_type == "audio": data['url'] = url elif media_type == "video": data['url'] = url elif media_type == "location": data['latitude'] = messageNode.getChild("media").getAttributeValue("latitude") data['longitude'] = messageNode.getChild("media").getAttributeValue("longitude") data['preview'] = messageNode.getChild("media").data elif media_type == "vcard": data['contact'] = messageNode.getChild("media").data else: continue fmsg.data = data elif ProtocolTreeNode.tagEquals(childNode, 'body') and msg_id is not None: fmsg.type = "chat" fmsg.data = childNode.data elif not ProtocolTreeNode.tagEquals(childNode, 'active'): if ProtocolTreeNode.tagEquals(childNode, 'request'): fmsg.wants_receipt = True elif ProtocolTreeNode.tagEquals(childNode, 'notify'): fmsg.notify_name = childNode.getAttributeValue('name') elif ProtocolTreeNode.tagEquals(childNode, 'x'): xmlns = childNode.getAttributeValue('xmlns') if 'jabber:x:delay' == xmlns: continue stamp_str = \ childNode.getAttributeValue('stamp') if stamp_str is not None: stamp = stamp_str fmsg.timestamp = stamp fmsg.offline = True else: if ProtocolTreeNode.tagEquals(childNode, 'delay') \ or not ProtocolTreeNode.tagEquals(childNode, 'received') or msg_id is None: continue if self.connection.supports_receipt_acks: receipt_type = \ childNode.getAttributeValue('type') if receipt_type is None or receipt_type \ == 'delivered': self.connection.sendDeliveredReceiptAck(fromAttribute, msg_id) elif receipt_type == 'visible': self.connection.sendVisibleReceiptAck(fromAttribute, msg_id) if fmsg.timestamp is None: fmsg.timestamp = time.time() * 1000 fmsg.offline = False self.connection.event.message_received(fmsg)
def run(self): while True: if self.connection.disconnectRequested: self.connection.conn.close() break ready = select.select([self.inn.rawIn], [], []) if ready[0]: try: node = self.inn.nextTree() except Exception, e: self.connection.event.reconnecting.emit() self.connection.login() return self.lastTreeRead = int(time.time()) * 1000 if node is not None: # print node.toString() if ProtocolTreeNode.tagEquals(node, 'iq'): iqType = node.getAttributeValue('type') idx = node.getAttributeValue('id') jid = node.getAttributeValue('from') if iqType is None: raise Exception("iq doesn't have type") if iqType == 'result': if self.requests.has_key(idx): self.requests[idx](node, jid) del self.requests[idx] elif jid == 'g.us': children = node.getAllChildren() if len(children) > 0: # List of groups received if ProtocolTreeNode.tagEquals(children[0], 'group'): self.connection.event.groupsReceived(map(lambda c: { 'subject': c.getAttributeValue('subject'), 'owner': c.getAttributeValue('owner'), 'id': c.getAttributeValue('id') }, children)) elif idx.startswith(self.connection.user): accountNode = node.getChild(0) ProtocolTreeNode.require(accountNode, 'account') kind = accountNode.getAttributeValue('kind') if kind == 'paid': self.connection.account_kind = 1 elif kind == 'free': self.connection.account_kind = 0 else: self.connection.account_kind = -1 expiration = accountNode.getAttributeValue('expiration') if expiration is None: raise Exception('no expiration') try: self.connection.expire_date = long(expiration) except ValueError: raise IOError('invalid expire date %s'% expiration) self.connection.event.onAccountChanged(self.connection.account_kind, self.connection.expire_date) elif iqType == 'error': if self.requests.has_key(idx): self.requests[idx](node) del self.requests[idx] elif iqType == 'get': childNode = node.getChild(0) if ProtocolTreeNode.tagEquals(childNode, 'ping'): self.connection.event.onPing(idx) elif ProtocolTreeNode.tagEquals(childNode, 'query') and jid is not None \ and 'http://jabber.org/protocol/disco#info' \ == childNode.getAttributeValue('xmlns'): pin = childNode.getAttributeValue('pin') timeoutString = childNode.getAttributeValue('timeout') try: timeoutSeconds = (int(timeoutString) if timoutString is not None else None) except ValueError: raise Exception('relay-iq exception parsing timeout %s ' % timeoutString) if pin is not None: self.connection.event.onRelayRequest(pin, timeoutSeconds, idx) elif iqType == 'set': childNode = node.getChild(0) if ProtocolTreeNode.tagEquals(childNode, 'query'): xmlns = childNode.getAttributeValue('xmlns') if xmlns == 'jabber:iq:roster': itemNodes = childNode.getAllChildren('item') ask = '' for itemNode in itemNodes: jid = itemNode.getAttributeValue('jid') subscription = itemNode.getAttributeValue('subscription') ask = itemNode.getAttributeValue('ask') else: raise Exception('Unkown iq type %s' % iqType) elif ProtocolTreeNode.tagEquals(node, 'presence'): xmlns = node.getAttributeValue('xmlns') jid = node.getAttributeValue('from') if (xmlns is None or xmlns == 'urn:xmpp') and jid is not None: presenceType = node.getAttributeValue('type') if presenceType == 'unavailable': self.connection.event.presence_unavailable_received(jid) elif presenceType is None or presenceType \ == 'available': self.connection.event.presence_available_received(jid) elif xmlns == 'w' and jid is not None: add = node.getAttributeValue('add') remove = node.getAttributeValue('remove') status = node.getAttributeValue('status') if add is not None: self.connection.event.groupAdd(jid.split('-')[-1], add) elif remove is not None: self.connection.event.groupRemove(jid.split('-')[-1], remove) elif status == 'dirty': categories = self.parseCategories(node) self.connection.event.onDirty(categories) elif ProtocolTreeNode.tagEquals(node, 'message'): self.parseMessage(node)