id int64 0 458k | file_name stringlengths 4 119 | file_path stringlengths 14 227 | content stringlengths 24 9.96M | size int64 24 9.96M | language stringclasses 1 value | extension stringclasses 14 values | total_lines int64 1 219k | avg_line_length float64 2.52 4.63M | max_line_length int64 5 9.91M | alphanum_fraction float64 0 1 | repo_name stringlengths 7 101 | repo_stars int64 100 139k | repo_forks int64 0 26.4k | repo_open_issues int64 0 2.27k | repo_license stringclasses 12 values | repo_extraction_date stringclasses 433 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21,600 | layer.py | tgalal_yowsup/yowsup/layers/protocol_presence/layer.py | from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer
from .protocolentities import *
from yowsup.layers.protocol_iq.protocolentities import ErrorIqProtocolEntity
class YowPresenceProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"presence": (self.recvPresence, self.sendPresence),
"iq": (None, self.sendIq)
}
super(YowPresenceProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Presence Layer"
def sendPresence(self, entity):
self.entityToLower(entity)
def recvPresence(self, node):
self.toUpper(PresenceProtocolEntity.fromProtocolTreeNode(node))
def sendIq(self, entity):
if entity.getXmlns() == LastseenIqProtocolEntity.XMLNS:
self._sendIq(entity, self.onLastSeenSuccess, self.onLastSeenError)
def onLastSeenSuccess(self, protocolTreeNode, lastSeenEntity):
self.toUpper(ResultLastseenIqProtocolEntity.fromProtocolTreeNode(protocolTreeNode))
def onLastSeenError(self, protocolTreeNode, lastSeenEntity):
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(protocolTreeNode))
| 1,175 | Python | .py | 23 | 43.913043 | 91 | 0.740838 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,601 | presence_unavailable.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/presence_unavailable.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .presence import PresenceProtocolEntity
class UnavailablePresenceProtocolEntity(PresenceProtocolEntity):
'''
<presence type="unavailable"></presence>
response:
<presence type="unavailable" from="self.jid">
</presence>
'''
def __init__(self):
super(UnavailablePresenceProtocolEntity, self).__init__("unavailable") | 413 | Python | .py | 11 | 33.363636 | 78 | 0.74938 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,602 | presence_subscribe.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/presence_subscribe.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .presence import PresenceProtocolEntity
class SubscribePresenceProtocolEntity(PresenceProtocolEntity):
'''
<presence type="subscribe" to="jid"></presence>
'''
def __init__(self, jid):
super(SubscribePresenceProtocolEntity, self).__init__("subscribe")
self.setProps(jid)
def setProps(self, jid):
self.jid = jid
def toProtocolTreeNode(self):
node = super(SubscribePresenceProtocolEntity, self).toProtocolTreeNode()
node.setAttribute("to", self.jid)
return node
def __str__(self):
out = super(SubscribePresenceProtocolEntity, self).__str__()
out += "To: %s\n" % self.jid
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = PresenceProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = SubscribePresenceProtocolEntity
entity.setProps(
node.getAttributeValue("to")
)
return entity
| 1,033 | Python | .py | 27 | 30.962963 | 80 | 0.680723 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,603 | iq_lastseen_result.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/iq_lastseen_result.py | from yowsup.layers.protocol_iq.protocolentities.iq_result import ResultIqProtocolEntity
from yowsup.structs.protocoltreenode import ProtocolTreeNode
class ResultLastseenIqProtocolEntity(ResultIqProtocolEntity):
def __init__(self, jid, seconds, _id = None):
super(ResultLastseenIqProtocolEntity, self).__init__(_from=jid, _id=_id)
self.setSeconds(seconds)
def setSeconds(self, seconds):
self.seconds = int(seconds)
def getSeconds(self):
return self.seconds
def __str__(self):
out = super(ResultIqProtocolEntity, self).__str__()
out += "Seconds: %s\n" % self.seconds
return out
def toProtocolTreeNode(self):
node = super(ResultLastseenIqProtocolEntity, self).toProtocolTreeNode()
node.addChild(ProtocolTreeNode("query", {"seconds": str(self.seconds)}))
return node
@staticmethod
def fromProtocolTreeNode(node):
return ResultLastseenIqProtocolEntity(node["from"], node.getChild("query")["seconds"], node["id"]) | 1,028 | Python | .py | 21 | 42.238095 | 106 | 0.710867 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,604 | test_presence_subscribe.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/test_presence_subscribe.py | from yowsup.layers.protocol_presence.protocolentities.presence_subscribe import SubscribePresenceProtocolEntity
from yowsup.layers.protocol_presence.protocolentities.test_presence import PresenceProtocolEntityTest
class SubscribePresenceProtocolEntityTest(PresenceProtocolEntityTest):
def setUp(self):
super(SubscribePresenceProtocolEntityTest, self).setUp()
self.ProtocolEntity = SubscribePresenceProtocolEntity
self.node.setAttribute("type", "subscribe")
self.node.setAttribute("to", "subscribe_jid") | 539 | Python | .py | 8 | 61.875 | 111 | 0.822976 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,605 | presence_available.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/presence_available.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .presence import PresenceProtocolEntity
class AvailablePresenceProtocolEntity(PresenceProtocolEntity):
'''
<presence type="available"></presence>
response:
<presence from="self.jid">
</presence>
'''
def __init__(self):
super(AvailablePresenceProtocolEntity, self).__init__("available") | 387 | Python | .py | 11 | 30.909091 | 74 | 0.742021 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,606 | iq_lastseen.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/iq_lastseen.py | from yowsup.layers.protocol_iq.protocolentities.iq import IqProtocolEntity
from yowsup.structs.protocoltreenode import ProtocolTreeNode
class LastseenIqProtocolEntity(IqProtocolEntity):
XMLNS = "jabber:iq:last"
def __init__(self, jid, _id = None):
super(LastseenIqProtocolEntity, self).__init__(self.__class__.XMLNS, _type = "get", to = jid, _id = _id)
@staticmethod
def fromProtocolTreeNode(node):
return LastseenIqProtocolEntity(node["to"])
def toProtocolTreeNode(self):
node = super(LastseenIqProtocolEntity, self).toProtocolTreeNode()
node.setAttribute("xmlns", self.__class__.XMLNS)
node.addChild(ProtocolTreeNode("query"))
return node
| 711 | Python | .py | 14 | 44.785714 | 112 | 0.723741 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,607 | test_presence_unavailable.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/test_presence_unavailable.py | from yowsup.layers.protocol_presence.protocolentities.presence_unavailable import UnavailablePresenceProtocolEntity
from yowsup.layers.protocol_presence.protocolentities.test_presence import PresenceProtocolEntityTest
class UnavailablePresenceProtocolEntityTest(PresenceProtocolEntityTest):
def setUp(self):
super(UnavailablePresenceProtocolEntityTest, self).setUp()
self.ProtocolEntity = UnavailablePresenceProtocolEntity
self.node.setAttribute("type", "unavailable")
| 498 | Python | .py | 7 | 66 | 115 | 0.846939 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,608 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/__init__.py | from .presence import PresenceProtocolEntity
from .presence_available import AvailablePresenceProtocolEntity
from .presence_unavailable import UnavailablePresenceProtocolEntity
from .presence_subscribe import SubscribePresenceProtocolEntity
from .presence_unsubscribe import UnsubscribePresenceProtocolEntity
from .iq_lastseen import LastseenIqProtocolEntity
from .iq_lastseen_result import ResultLastseenIqProtocolEntity
| 456 | Python | .py | 7 | 64.142857 | 68 | 0.846325 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,609 | presence_unsubscribe.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/presence_unsubscribe.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .presence import PresenceProtocolEntity
class UnsubscribePresenceProtocolEntity(PresenceProtocolEntity):
'''
<presence type="unsubscribe" to="jid"></presence>
'''
def __init__(self, jid):
super(UnsubscribePresenceProtocolEntity, self).__init__("unsubscribe")
self.setProps(jid)
def setProps(self, jid):
self.jid = jid
def toProtocolTreeNode(self):
node = super(UnsubscribePresenceProtocolEntity, self).toProtocolTreeNode()
node.setAttribute("to", self.jid)
return node
def __str__(self):
out = super(UnsubscribePresenceProtocolEntity, self).__str__()
out += "To: %s\n" % self.jid
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = PresenceProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = UnsubscribePresenceProtocolEntity
entity.setProps(
node.getAttributeValue("to")
)
return entity
| 1,047 | Python | .py | 27 | 31.481481 | 82 | 0.685149 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,610 | test_presence_unsubscribe.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/test_presence_unsubscribe.py | from yowsup.layers.protocol_presence.protocolentities.presence_unsubscribe import UnsubscribePresenceProtocolEntity
from yowsup.layers.protocol_presence.protocolentities.test_presence import PresenceProtocolEntityTest
class UnsubscribePresenceProtocolEntityTest(PresenceProtocolEntityTest):
def setUp(self):
super(UnsubscribePresenceProtocolEntityTest, self).setUp()
self.ProtocolEntity = UnsubscribePresenceProtocolEntity
self.node.setAttribute("type", "unsubscribe")
self.node.setAttribute("to", "some_jid") | 546 | Python | .py | 8 | 62.75 | 115 | 0.825279 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,611 | presence.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/presence.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class PresenceProtocolEntity(ProtocolEntity):
'''
<presence type="{{type}} name={{push_name}}"></presence>
Should normally be either type or name
when contact goes offline:
<presence type="unavailable" from="{{contact_jid}}" last="deny | ?">
</presence>
when contact goes online:
<presence from="contact_jid">
</presence>
'''
def __init__(self, _type = None, name = None, _from = None, last = None):
super(PresenceProtocolEntity, self).__init__("presence")
self._type = _type
self.name = name
self._from = _from
self.last = last
def getType(self):
return self._type
def getName(self):
return self.name
def getFrom(self, full = True):
return self._from if full else self._from.split('@')[0]
def getLast(self):
return self.last
def toProtocolTreeNode(self):
attribs = {}
if self._type:
attribs["type"] = self._type
if self.name:
attribs["name"] = self.name
if self._from:
attribs["from"] = self._from
if self.last:
attribs["last"] = self.last
return self._createProtocolTreeNode(attribs, None, None)
def __str__(self):
out = "Presence:\n"
if self._type:
out += "Type: %s\n" % self._type
if self.name:
out += "Name: %s\n" % self.name
if self._from:
out += "From: %s\n" % self._from
if self.last:
out += "Last seen: %s\n" % self.last
return out
@staticmethod
def fromProtocolTreeNode(node):
return PresenceProtocolEntity(
node.getAttributeValue("type"),
node.getAttributeValue("name"),
node.getAttributeValue("from"),
node.getAttributeValue("last")
)
| 1,929 | Python | .py | 56 | 25.928571 | 77 | 0.575806 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,612 | test_presence.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/test_presence.py | from yowsup.layers.protocol_presence.protocolentities.presence import PresenceProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class PresenceProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = PresenceProtocolEntity
self.node = ProtocolTreeNode("presence", {"type": "presence_type", "name": "presence_name"}, None, None)
| 475 | Python | .py | 8 | 55.75 | 112 | 0.817597 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,613 | test_presence_available.py | tgalal_yowsup/yowsup/layers/protocol_presence/protocolentities/test_presence_available.py | from yowsup.layers.protocol_presence.protocolentities.presence_available import AvailablePresenceProtocolEntity
from yowsup.layers.protocol_presence.protocolentities.test_presence import PresenceProtocolEntityTest
class AvailablePresenceProtocolEntityTest(PresenceProtocolEntityTest):
def setUp(self):
super(AvailablePresenceProtocolEntityTest, self).setUp()
self.ProtocolEntity = AvailablePresenceProtocolEntity
self.node.setAttribute("type", "available")
| 486 | Python | .py | 7 | 64.285714 | 111 | 0.843096 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,614 | layer.py | tgalal_yowsup/yowsup/layers/network/layer.py | from yowsup.layers import YowLayer, YowLayerEvent, EventCallback
from yowsup.layers.network.layer_interface import YowNetworkLayerInterface
from yowsup.layers.network.dispatcher.dispatcher import ConnectionCallbacks
from yowsup.layers.network.dispatcher.dispatcher import YowConnectionDispatcher
from yowsup.layers.network.dispatcher.dispatcher_socket import SocketConnectionDispatcher
from yowsup.layers.network.dispatcher.dispatcher_asyncore import AsyncoreConnectionDispatcher
import logging
logger = logging.getLogger(__name__)
class YowNetworkLayer(YowLayer, ConnectionCallbacks):
"""This layer wraps a connection dispatcher that provides connection and a communication channel
to remote endpoints. Unless explicitly configured, applications should not make assumption about
the dispatcher being used as the default dispatcher could be changed across versions"""
EVENT_STATE_CONNECT = "org.openwhatsapp.yowsup.event.network.connect"
EVENT_STATE_DISCONNECT = "org.openwhatsapp.yowsup.event.network.disconnect"
EVENT_STATE_CONNECTED = "org.openwhatsapp.yowsup.event.network.connected"
EVENT_STATE_DISCONNECTED = "org.openwhatsapp.yowsup.event.network.disconnected"
PROP_ENDPOINT = "org.openwhatsapp.yowsup.prop.endpoint"
PROP_NET_READSIZE = "org.openwhatsapp.yowsup.prop.net.readSize"
PROP_DISPATCHER = "org.openwhatsapp.yowsup.prop.net.dispatcher"
STATE_DISCONNECTED = 0
STATE_CONNECTING = 1
STATE_CONNECTED = 2
STATE_DISCONNECTING = 3
DISPATCHER_SOCKET = 0
DISPATCHER_ASYNCORE = 1
DISPATCHER_DEFAULT = DISPATCHER_ASYNCORE
def __init__(self):
self.state = self.__class__.STATE_DISCONNECTED
YowLayer.__init__(self)
ConnectionCallbacks.__init__(self)
self.interface = YowNetworkLayerInterface(self)
self.connected = False
self._dispatcher = None # type: YowConnectionDispatcher
self._disconnect_reason = None
def __create_dispatcher(self, dispatcher_type):
if dispatcher_type == self.DISPATCHER_ASYNCORE:
logger.debug("Created asyncore dispatcher")
return AsyncoreConnectionDispatcher(self)
else:
logger.debug("Created socket dispatcher")
return SocketConnectionDispatcher(self)
def onConnected(self):
logger.debug("Connected")
self.state = self.__class__.STATE_CONNECTED
self.connected = True
self.emitEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECTED))
def onDisconnected(self):
if self.state != self.__class__.STATE_DISCONNECTED:
self.state = self.__class__.STATE_DISCONNECTED
self.connected = False
logger.debug("Disconnected")
self.emitEvent(
YowLayerEvent(
self.__class__.EVENT_STATE_DISCONNECTED, reason=self._disconnect_reason or "", detached=True
)
)
def onConnecting(self):
pass
def onConnectionError(self, error):
self.onDisconnected()
@EventCallback(EVENT_STATE_CONNECT)
def onConnectLayerEvent(self, ev):
if not self.connected:
self.createConnection()
else:
logger.warn("Received connect event while already connected")
return True
@EventCallback(EVENT_STATE_DISCONNECT)
def onDisconnectLayerEvent(self, ev):
self.destroyConnection(ev.getArg("reason"))
return True
def createConnection(self):
self._disconnect_reason = None
self._dispatcher = self.__create_dispatcher(self.getProp(self.PROP_DISPATCHER, self.DISPATCHER_DEFAULT))
self.state = self.__class__.STATE_CONNECTING
endpoint = self.getProp(self.__class__.PROP_ENDPOINT)
logger.info("Connecting to %s:%s" % endpoint)
self._dispatcher.connect(endpoint)
def destroyConnection(self, reason=None):
self._disconnect_reason = reason
self.state = self.__class__.STATE_DISCONNECTING
self._dispatcher.disconnect()
def getStatus(self):
return self.connected
def send(self, data):
if self.connected:
self._dispatcher.sendData(data)
def onRecvData(self, data):
self.receive(data)
def receive(self, data):
self.toUpper(data)
def __str__(self):
return "Network Layer"
| 4,465 | Python | .py | 93 | 40.215054 | 112 | 0.693244 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,615 | layer_interface.py | tgalal_yowsup/yowsup/layers/network/layer_interface.py | from yowsup.layers import YowLayerInterface
class YowNetworkLayerInterface(YowLayerInterface):
def connect(self):
self._layer.createConnection()
def disconnect(self):
self._layer.destroyConnection()
def getStatus(self):
return self._layer.getStatus() | 288 | Python | .py | 8 | 30.375 | 50 | 0.741935 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,616 | dispatcher_socket.py | tgalal_yowsup/yowsup/layers/network/dispatcher/dispatcher_socket.py | from yowsup.layers.network.dispatcher.dispatcher import YowConnectionDispatcher
import socket
import logging
logger = logging.getLogger(__name__)
class SocketConnectionDispatcher(YowConnectionDispatcher):
def __init__(self, connectionCallbacks):
super(SocketConnectionDispatcher, self).__init__(connectionCallbacks)
self.socket = None
def connect(self, host):
if not self.socket:
self.socket = socket.socket()
self.connectAndLoop(host)
else:
logger.error("Already connected?")
def disconnect(self):
if self.socket:
try:
self.socket.shutdown(socket.SHUT_WR)
self.socket.close()
except socket.error as e:
logger.error(e)
self.socket = None
self.connectionCallbacks.onDisconnected()
else:
logger.error("Not connected?")
def connectAndLoop(self, host):
socket = self.socket
self.connectionCallbacks.onConnecting()
try:
socket.connect(host)
self.connectionCallbacks.onConnected()
while True:
data = socket.recv(1024)
if len(data):
self.connectionCallbacks.onRecvData(data)
else:
break
self.connectionCallbacks.onDisconnected()
except Exception as e:
logger.error(e)
self.connectionCallbacks.onConnectionError(e)
finally:
self.socket = None
socket.close()
def sendData(self, data):
try:
self.socket.send(data)
except socket.error as e:
logger.error(e)
self.disconnect()
| 1,767 | Python | .py | 50 | 24.28 | 79 | 0.591813 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,617 | dispatcher_asyncore.py | tgalal_yowsup/yowsup/layers/network/dispatcher/dispatcher_asyncore.py | from yowsup.layers.network.dispatcher.dispatcher import YowConnectionDispatcher
import asyncore
import logging
import socket
import traceback
logger = logging.getLogger(__name__)
class AsyncoreConnectionDispatcher(YowConnectionDispatcher, asyncore.dispatcher_with_send):
def __init__(self, connectionCallbacks):
super(AsyncoreConnectionDispatcher, self).__init__(connectionCallbacks)
asyncore.dispatcher_with_send.__init__(self)
self._connected = False
def sendData(self, data):
if self._connected:
self.out_buffer = self.out_buffer + data
self.initiate_send()
else:
logger.warn("Attempted to send %d bytes while still not connected" % len(data))
def connect(self, host):
logger.debug("connect(%s)" % str(host))
self.connectionCallbacks.onConnecting()
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
asyncore.dispatcher_with_send.connect(self, host)
asyncore.loop(timeout=1)
def handle_connect(self):
logger.debug("handle_connect")
if not self._connected:
self._connected = True
self.connectionCallbacks.onConnected()
def handle_close(self):
logger.debug("handle_close")
self.close()
self._connected = False
self.connectionCallbacks.onDisconnected()
def handle_error(self):
logger.error(traceback.format_exc())
self.handle_close()
def handle_read(self):
data = self.recv(1024)
self.connectionCallbacks.onRecvData(data)
def disconnect(self):
logger.debug("disconnect")
self.handle_close()
| 1,673 | Python | .py | 42 | 32.214286 | 91 | 0.682295 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,618 | dispatcher.py | tgalal_yowsup/yowsup/layers/network/dispatcher/dispatcher.py | class ConnectionCallbacks(object):
def onConnected(self):
pass
def onDisconnected(self):
pass
def onRecvData(self, data):
pass
def onConnecting(self):
pass
def onConnectionError(self, error):
pass
class YowConnectionDispatcher(object):
def __init__(self, connectionCallbacks):
assert isinstance(connectionCallbacks, ConnectionCallbacks)
self.connectionCallbacks = connectionCallbacks
def connect(self, host):
pass
def disconnect(self):
pass
def sendData(self, data):
pass | 596 | Python | .py | 21 | 21.47619 | 67 | 0.677249 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,619 | layer.py | tgalal_yowsup/yowsup/layers/protocol_notifications/layer.py | from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer
from .protocolentities import *
from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity
import logging
logger = logging.getLogger(__name__)
class YowNotificationsProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"notification": (self.recvNotification, self.sendNotification)
}
super(YowNotificationsProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "notification Ib Layer"
def sendNotification(self, entity):
if entity.getTag() == "notification":
self.toLower(entity.toProtocolTreeNode())
def recvNotification(self, node):
if node["type"] == "picture":
if node.getChild("set"):
self.toUpper(SetPictureNotificationProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("delete"):
self.toUpper(DeletePictureNotificationProtocolEntity.fromProtocolTreeNode(node))
else:
self.raiseErrorForNode(node)
elif node["type"] == "status":
self.toUpper(StatusNotificationProtocolEntity.fromProtocolTreeNode(node))
elif node["type"] in ["contacts", "subject", "w:gp2"]:
# Implemented in respectively the protocol_contacts and protocol_groups layer
pass
else:
logger.warning("Unsupported notification type: %s " % node["type"])
logger.debug("Unsupported notification node: %s" % node)
ack = OutgoingAckProtocolEntity(node["id"], "notification", node["type"], node["from"], participant=node["participant"])
self.toLower(ack.toProtocolTreeNode())
| 1,752 | Python | .py | 34 | 42.088235 | 128 | 0.679977 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,620 | notification.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/notification.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
class NotificationProtocolEntity(ProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="{{NOTIFICATION_TYPE}}"
t="{{TIMESTAMP}}" from="{{SENDER_JID}}">
</notification>
'''
def __init__(self, _type, _id, _from, timestamp, notify, offline):
super(NotificationProtocolEntity, self).__init__("notification")
self._type = _type
self._id = _id
self._from =_from
self.timestamp = int(timestamp)
self.notify = notify
self.offline = offline == "1"
def __str__(self):
out = "Notification\n"
out += "From: %s\n" % self.getFrom()
out += "Type: %s\n" % self.getType()
return out
def getFrom(self, full = True):
return self._from if full else self._from.split('@')[0]
def getType(self):
return self._type
def getId(self):
return self._id
def getTimestamp(self):
return self.timestamp
def toProtocolTreeNode(self):
attribs = {
"t" : str(self.timestamp),
"from" : self._from,
"offline" : "1" if self.offline else "0",
"type" : self._type,
"id" : self._id,
"notify" : self.notify
}
return self._createProtocolTreeNode(attribs, children = None, data = None)
@staticmethod
def fromProtocolTreeNode(node):
return NotificationProtocolEntity(
node.getAttributeValue("type"),
node.getAttributeValue("id"),
node.getAttributeValue("from"),
node.getAttributeValue("t"),
node.getAttributeValue("notify"),
node.getAttributeValue("offline")
)
| 1,969 | Python | .py | 49 | 31.020408 | 109 | 0.581837 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,621 | test_notification.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/test_notification.py | from yowsup.layers.protocol_notifications.protocolentities.notification import NotificationProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class NotificationProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = NotificationProtocolEntity
attribs = {
"t": "12345",
"from": "from_jid",
"offline": "0",
"type": "notif_type",
"id": "message-id",
"notify": "notify_name"
}
self.node = ProtocolTreeNode("notification", attribs) | 662 | Python | .py | 16 | 33.625 | 105 | 0.688854 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,622 | test_notification_picture_set.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/test_notification_picture_set.py | from yowsup.layers.protocol_notifications.protocolentities.notification_picture_set import SetPictureNotificationProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_notifications.protocolentities.test_notification_picture import PictureNotificationProtocolEntityTest
class SetPictureNotificationProtocolEntityTest(PictureNotificationProtocolEntityTest):
def setUp(self):
super(SetPictureNotificationProtocolEntityTest, self).setUp()
self.ProtocolEntity = SetPictureNotificationProtocolEntity
setNode = ProtocolTreeNode("set", {"jid": "SET_JID", "id": "123"}, None, None)
self.node.addChild(setNode)
| 671 | Python | .py | 9 | 69.444444 | 129 | 0.829047 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,623 | test_notification_status.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/test_notification_status.py | from yowsup.layers.protocol_notifications.protocolentities.notification_status import StatusNotificationProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_notifications.protocolentities.test_notification import NotificationProtocolEntityTest
class StatusNotificationProtocolEntityTest(NotificationProtocolEntityTest):
def setUp(self):
super(StatusNotificationProtocolEntityTest, self).setUp()
self.ProtocolEntity = StatusNotificationProtocolEntity
setNode = ProtocolTreeNode("set", {}, [], b"status_data")
self.node.addChild(setNode)
| 607 | Python | .py | 9 | 62.333333 | 118 | 0.830821 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,624 | test_notification_picture_delete.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/test_notification_picture_delete.py | from yowsup.layers.protocol_notifications.protocolentities.notification_picture_delete import DeletePictureNotificationProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_notifications.protocolentities.test_notification_picture import PictureNotificationProtocolEntityTest
class DeletePictureNotificationProtocolEntityTest(PictureNotificationProtocolEntityTest):
def setUp(self):
super(DeletePictureNotificationProtocolEntityTest, self).setUp()
self.ProtocolEntity = DeletePictureNotificationProtocolEntity
deleteNode = ProtocolTreeNode("delete", {"jid": "DELETE_JID"}, None, None)
self.node.addChild(deleteNode)
| 685 | Python | .py | 9 | 71 | 133 | 0.844444 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,625 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/__init__.py | from .notification import NotificationProtocolEntity
from .notification_picture import PictureNotificationProtocolEntity
from .notification_picture_set import SetPictureNotificationProtocolEntity
from .notification_picture_delete import DeletePictureNotificationProtocolEntity
from .notification_status import StatusNotificationProtocolEntity
| 389 | Python | .py | 5 | 76.8 | 85 | 0.8125 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,626 | notification_picture_delete.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/notification_picture_delete.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .notification_picture import PictureNotificationProtocolEntity
class DeletePictureNotificationProtocolEntity(PictureNotificationProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="picture"
t="{{TIMESTAMP}}" from="{{SENDER_JID}}">
<delete jid="{{DELETE_JID}}">
</delete>
</notification>
'''
def __init__(self, _id, _from, status, timestamp, notify, offline, deleteJid):
super(DeletePictureNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline)
self.setData(deleteJid)
def setData(self, deleteJid):
self.deleteJid = deleteJid
def __str__(self):
out = super(DeletePictureNotificationProtocolEntity, self).__str__()
out += "Type: Delete"
return out
def toProtocolTreeNode(self):
node = super(DeletePictureNotificationProtocolEntity, self).toProtocolTreeNode()
deleteNode = ProtocolTreeNode("delete", {"jid": self.deleteJid}, None, None)
node.addChild(deleteNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = PictureNotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = DeletePictureNotificationProtocolEntity
deleteNode = node.getChild("delete")
entity.setData(deleteNode.getAttributeValue("jid"))
return entity
| 1,494 | Python | .py | 31 | 40.806452 | 109 | 0.69945 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,627 | notification_picture.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/notification_picture.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .notification import NotificationProtocolEntity
class PictureNotificationProtocolEntity(NotificationProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="picture"
t="{{TIMESTAMP}}" from="{{SENDER_JID}}">
</notification>
'''
def __init__(self, _id, _from, status, timestamp, notify, offline, setJid, setId):
super(PictureNotificationProtocolEntity, self).__init__("picture", _id, _from, timestamp, notify, offline)
self.setData(setJid, setId)
@staticmethod
def fromProtocolTreeNode(node):
entity = NotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = PictureNotificationProtocolEntity
return entity | 815 | Python | .py | 16 | 44.8125 | 114 | 0.718045 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,628 | test_notification_picture.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/test_notification_picture.py | from yowsup.layers.protocol_notifications.protocolentities.notification_picture import PictureNotificationProtocolEntity
from yowsup.layers.protocol_notifications.protocolentities.test_notification import NotificationProtocolEntityTest
class PictureNotificationProtocolEntityTest(NotificationProtocolEntityTest):
def setUp(self):
super(PictureNotificationProtocolEntityTest, self).setUp()
self.ProtocolEntity = PictureNotificationProtocolEntity
| 466 | Python | .py | 6 | 73.166667 | 120 | 0.875817 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,629 | notification_status.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/notification_status.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .notification import NotificationProtocolEntity
class StatusNotificationProtocolEntity(NotificationProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="status"
t="{{TIMESTAMP}}" from="{{SENDER_JID}}">
<set>
{{STATUS}}
</set>
</notification>
'''
def __init__(self, _type, _id, _from, status, timestamp, notify, offline = False):
super(StatusNotificationProtocolEntity, self).__init__("status", _id, _from, timestamp, notify, offline)
self.setStatus(status)
def setStatus(self, status):
self.status = status
def toProtocolTreeNode(self):
node = super(StatusNotificationProtocolEntity, self).toProtocolTreeNode()
setNode = ProtocolTreeNode("set", {}, None, self.status)
node.addChild(setNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = NotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = StatusNotificationProtocolEntity
entity.setStatus(node.getChild("set").getData())
return entity | 1,219 | Python | .py | 27 | 37.592593 | 112 | 0.683898 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,630 | notification_picture_set.py | tgalal_yowsup/yowsup/layers/protocol_notifications/protocolentities/notification_picture_set.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .notification_picture import PictureNotificationProtocolEntity
class SetPictureNotificationProtocolEntity(PictureNotificationProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="picture"
t="{{TIMESTAMP}}" from="{{SENDER_JID}}">
<set jid="{{SET_JID}}" id="{{SET_ID}}">
</set>
</notification>
'''
def __init__(self, _id, _from, status, timestamp, notify, offline, setJid, setId):
super(SetPictureNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline)
self.setData(setJid, setId)
def setData(self, setJid, setId):
self.setId = setId
self.setJid = setJid
def toProtocolTreeNode(self):
node = super(SetPictureNotificationProtocolEntity, self).toProtocolTreeNode()
setNode = ProtocolTreeNode("set", {"jid": self.setJid, "id": self.setId}, None, None)
node.addChild(setNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = PictureNotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = SetPictureNotificationProtocolEntity
setNode = node.getChild("set")
entity.setData(setNode.getAttributeValue("jid"), setNode.getAttributeValue("id"))
return entity | 1,405 | Python | .py | 28 | 42.892857 | 106 | 0.691241 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,631 | layer.py | tgalal_yowsup/yowsup/layers/protocol_iq/layer.py | import time
import logging
from threading import Thread, Lock
from yowsup.layers import YowProtocolLayer, YowLayerEvent, EventCallback
from yowsup.common import YowConstants
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
PROP_PING_INTERVAL = "org.openwhatsapp.yowsup.prop.pinginterval"
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
self._pingThread = None
self._pingQueue = {}
self._pingQueueLock = Lock()
self.__logger = logging.getLogger(__name__)
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def onPong(self, protocolTreeNode, pingEntity):
self.gotPong(pingEntity.getId())
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(protocolTreeNode))
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self._sendIq(entity, self.onPong)
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
def gotPong(self, pingId):
self._pingQueueLock.acquire()
if pingId in self._pingQueue:
self._pingQueue = {}
self._pingQueueLock.release()
def waitPong(self, id):
self._pingQueueLock.acquire()
self._pingQueue[id] = None
pingQueueSize = len(self._pingQueue)
self._pingQueueLock.release()
self.__logger.debug("ping queue size: %d" % pingQueueSize)
if pingQueueSize >= 2:
self.getStack().broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT, reason = "Ping Timeout"))
@EventCallback(YowAuthenticationProtocolLayer.EVENT_AUTHED)
def onAuthed(self, event):
interval = self.getProp(self.__class__.PROP_PING_INTERVAL, 50)
if not self._pingThread and interval > 0:
self._pingQueue = {}
self._pingThread = YowPingThread(self, interval)
self.__logger.debug("starting ping thread.")
self._pingThread.start()
def stop_thread(self):
if self._pingThread:
self.__logger.debug("stopping ping thread")
if self._pingThread:
self._pingThread.stop()
self._pingThread = None
self._pingQueue = {}
@EventCallback(YowNetworkLayer.EVENT_STATE_DISCONNECT)
def onDisconnect(self, event):
self.stop_thread()
@EventCallback(YowNetworkLayer.EVENT_STATE_DISCONNECTED)
def onDisconnected(self, event):
self.stop_thread()
class YowPingThread(Thread):
def __init__(self, layer, interval):
assert type(layer) is YowIqProtocolLayer, "layer must be a YowIqProtocolLayer, got %s instead." % type(layer)
self._layer = layer
self._interval = interval
self._stop = False
self.__logger = logging.getLogger(__name__)
super(YowPingThread, self).__init__()
self.daemon = True
self.name = "YowPing%s" % self.name
def run(self):
while not self._stop:
for i in range(0, self._interval):
time.sleep(1)
if self._stop:
self.__logger.debug("%s - ping thread stopped" % self.name)
return
ping = PingIqProtocolEntity()
self._layer.waitPong(ping.getId())
if not self._stop:
self._layer.sendIq(ping)
def stop(self):
self._stop = True
| 3,932 | Python | .py | 90 | 34.222222 | 122 | 0.636892 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,632 | iq_error.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/iq_error.py | from yowsup.structs import ProtocolTreeNode
from .iq import IqProtocolEntity
class ErrorIqProtocolEntity(IqProtocolEntity):
'''<iq id="1417113419-0" from="{{jid}}" type="error">
<error text="not-acceptable" code="406" backoff="3600">
</error>
</iq>
'''
def __init__(self, _id, _from, code, text, backoff= 0 ):
super(ErrorIqProtocolEntity, self).__init__(xmlns = None, _id = _id, _type = "error", _from = _from)
self.setErrorProps(code, text, backoff)
def setErrorProps(self, code, text, backoff):
self.code = code
self.text = text
self.backoff = int(backoff) if backoff else 0
def toProtocolTreeNode(self):
node = super(ErrorIqProtocolEntity, self).toProtocolTreeNode()
errorNode = ProtocolTreeNode("error", {"text": self.text, "code": self.code})
if self.backoff:
errorNode.setAttribute("backoff", str(self.backoff))
node.addChild(errorNode)
return node
def __str__(self):
out = super(ErrorIqProtocolEntity, self).__str__()
out += "Code: %s\n" % self.code
out += "Text: %s\n" % self.text
out += "Backoff: %s\n" % self.backoff
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = ErrorIqProtocolEntity
errorNode = node.getChild("error")
entity.setErrorProps(errorNode.getAttributeValue("code"),
errorNode.getAttributeValue("text"),
errorNode.getAttributeValue("backoff"))
return entity
| 1,645 | Python | .py | 37 | 35.837838 | 108 | 0.62875 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,633 | iq_result.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/iq_result.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq import IqProtocolEntity
class ResultIqProtocolEntity(IqProtocolEntity):
'''
<iq type="result" id="{{id}}" from="{{FROM}}">
</iq>
'''
def __init__(self, xmlns = None, _id = None, to = None, _from = None):
super(ResultIqProtocolEntity, self).__init__(xmlns = xmlns, _id = _id, _type = "result", to = to, _from = _from)
| 417 | Python | .py | 9 | 41.888889 | 120 | 0.644444 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,634 | iq_push.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/iq_push.py | from .iq import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class PushIqProtocolEntity(IqProtocolEntity):
def __init__(self):
super(PushIqProtocolEntity, self).__init__("urn:xmpp:whatsapp:push", _type="get")
def toProtocolTreeNode(self):
node = super(PushIqProtocolEntity, self).toProtocolTreeNode()
node.addChild(ProtocolTreeNode("config"))
return node | 411 | Python | .py | 9 | 40.222222 | 89 | 0.741294 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,635 | test_iq_result.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/test_iq_result.py | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
class ResultIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(ResultIqProtocolEntityTest, self).setUp()
self.node.setAttribute("type", "result") | 265 | Python | .py | 5 | 48.2 | 83 | 0.793103 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,636 | test_iq_error.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/test_iq_error.py | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
from yowsup.layers.protocol_iq.protocolentities import ErrorIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class ErrorIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(ErrorIqProtocolEntityTest, self).setUp()
self.ProtocolEntity = ErrorIqProtocolEntity
errorNode = ProtocolTreeNode("error", {"code": "123", "text": "abc"})
self.node.addChild(errorNode)
| 505 | Python | .py | 9 | 51 | 83 | 0.789899 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,637 | iq_ping.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/iq_ping.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq import IqProtocolEntity
class PingIqProtocolEntity(IqProtocolEntity):
'''
Receive
<iq type="get" xmlns="urn:xmpp:ping" from="s.whatsapp.net" id="1416174955-ping">
</iq>
Send
<iq type="get" xmlns="w:p" to="s.whatsapp.net" id="1416174955-ping">
</iq>
'''
def __init__(self, _from = None, to = None, _id = None):
super(PingIqProtocolEntity, self).__init__("urn:xmpp:ping" if _from else "w:p", _id = _id, _type = "get", _from = _from, to = to)
| 555 | Python | .py | 13 | 38.153846 | 137 | 0.648148 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,638 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/__init__.py | from .iq import IqProtocolEntity
from .iq_result import ResultIqProtocolEntity
from .iq_ping import PingIqProtocolEntity
from .iq_result_pong import PongResultIqProtocolEntity
from .iq_error import ErrorIqProtocolEntity
from .iq_push import PushIqProtocolEntity
from .iq_props import PropsIqProtocolEntity
from .iq_crypto import CryptoIqProtocolEntity
| 352 | Python | .py | 8 | 43 | 54 | 0.883721 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,639 | test_iq.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/test_iq.py | from yowsup.layers.protocol_iq.protocolentities.iq import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class IqProtocolEntityTest(unittest.TestCase, ProtocolEntityTest):
def setUp(self):
self.ProtocolEntity = IqProtocolEntity
self.node = ProtocolTreeNode("iq", {"id": "test_id", "type": "get", "xmlns": "iq_xmlns"}, None, None) | 441 | Python | .py | 8 | 51.625 | 109 | 0.785219 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,640 | iq_result_pong.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/iq_result_pong.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_result import ResultIqProtocolEntity
class PongResultIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" xmlns="w:p" to="self.domain" id="1416174955-ping">
</iq>
'''
def __init__(self, to, _id = None):
super(PongResultIqProtocolEntity, self).__init__("w:p", _id = _id, to = to)
| 388 | Python | .py | 9 | 38.888889 | 83 | 0.695767 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,641 | iq_crypto.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/iq_crypto.py | from .iq import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class CryptoIqProtocolEntity(IqProtocolEntity):
def __init__(self):
super(CryptoIqProtocolEntity, self).__init__("urn:xmpp:whatsapp:account", _type="get")
def toProtocolTreeNode(self):
node = super(CryptoIqProtocolEntity, self).toProtocolTreeNode()
cryptoNode = ProtocolTreeNode("crypto", {"action": "create"})
googleNode = ProtocolTreeNode("google", data = "fe5cf90c511fb899781bbed754577098e460d048312c8b36c11c91ca4b49ca34".decode('hex'))
cryptoNode.addChild(googleNode)
node.addChild(cryptoNode)
return node | 651 | Python | .py | 12 | 47.916667 | 136 | 0.744914 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,642 | iq.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/iq.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class IqProtocolEntity(ProtocolEntity):
'''
<iq type="{{get | set}}" id="{{id}}" xmlns="{{xmlns}}" to="{{TO}}" from="{{FROM}}">
</iq>
'''
TYPE_SET = "set"
TYPE_GET = "get"
TYPE_ERROR = "error"
TYPE_RESULT = "result"
TYPES = (TYPE_SET, TYPE_GET, TYPE_RESULT, TYPE_ERROR)
def __init__(self, xmlns = None, _id = None, _type = None, to = None, _from = None):
super(IqProtocolEntity, self).__init__("iq")
assert _type in self.__class__.TYPES, "Iq of type %s is not implemented, can accept only (%s)" % (_type," | ".join(self.__class__.TYPES))
assert not to or not _from, "Can't set from and to at the same time"
self._id = self._generateId(True) if _id is None else _id
self._from = _from
self._type = _type
self.xmlns = xmlns
self.to = to
def getId(self):
return self._id
def getType(self):
return self._type
def getXmlns(self):
return self.xmlns
def getFrom(self, full = True):
return self._from if full else self._from.split('@')[0]
def getTo(self):
return self.to
def toProtocolTreeNode(self):
attribs = {
"id" : self._id,
"type" : self._type
}
if self.xmlns:
attribs["xmlns"] = self.xmlns
if self.to:
attribs["to"] = self.to
elif self._from:
attribs["from"] = self._from
return self._createProtocolTreeNode(attribs, None, data = None)
def __str__(self):
out = "Iq:\n"
out += "ID: %s\n" % self._id
out += "Type: %s\n" % self._type
if self.xmlns:
out += "xmlns: %s\n" % self.xmlns
if self.to:
out += "to: %s\n" % self.to
elif self._from:
out += "from: %s\n" % self._from
return out
@staticmethod
def fromProtocolTreeNode(node):
return IqProtocolEntity(
node.getAttributeValue("xmlns"),
node.getAttributeValue("id"),
node.getAttributeValue("type"),
node.getAttributeValue("to"),
node.getAttributeValue("from")
)
| 2,265 | Python | .py | 62 | 27.806452 | 145 | 0.544872 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,643 | iq_props.py | tgalal_yowsup/yowsup/layers/protocol_iq/protocolentities/iq_props.py | from .iq import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class PropsIqProtocolEntity(IqProtocolEntity):
def __init__(self):
super(PropsIqProtocolEntity, self).__init__("w", _type="get")
def toProtocolTreeNode(self):
node = super(PropsIqProtocolEntity, self).toProtocolTreeNode()
node.addChild(ProtocolTreeNode("props"))
return node | 392 | Python | .py | 9 | 38.111111 | 70 | 0.736292 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,644 | layer_send.py | tgalal_yowsup/yowsup/layers/axolotl/layer_send.py | from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
from yowsup.layers.axolotl.protocolentities import *
from yowsup.layers.auth.layer_authentication import YowAuthenticationProtocolLayer
from yowsup.layers.protocol_groups.protocolentities import InfoGroupsIqProtocolEntity, InfoGroupsResultIqProtocolEntity
from axolotl.protocol.whispermessage import WhisperMessage
from yowsup.layers.protocol_messages.protocolentities.message import MessageMetaAttributes
from yowsup.layers.axolotl.protocolentities.iq_keys_get_result import MissingParametersException
from yowsup.axolotl import exceptions
from .layer_base import AxolotlBaseLayer
import logging
logger = logging.getLogger(__name__)
class AxolotlSendLayer(AxolotlBaseLayer):
MAX_SENT_QUEUE = 100
def __init__(self):
super(AxolotlSendLayer, self).__init__()
self.sessionCiphers = {}
self.groupCiphers = {}
'''
Sent messages will be put in Queue until we receive a receipt for them.
This is for handling retry receipts which requires re-encrypting and resend of the original message
As the receipt for a sent message might arrive at a different yowsup instance,
ideally the original message should be fetched from a persistent storage.
Therefore, if the original message is not in sentQueue for any reason, we will
notify the upper layers and let them handle it.
'''
self.sentQueue = []
def __str__(self):
return "Axolotl Layer"
def send(self, node):
if node.tag == "message" and node["to"] not in self.skipEncJids:
self.processPlaintextNodeAndSend(node)
else:
self.toLower(node)
def receive(self, protocolTreeNode):
def on_get_keys_success(node, retry_entity, success_jids, errors):
if len(errors):
self.on_get_keys_process_errors(errors)
elif len(success_jids) == 1:
self.processPlaintextNodeAndSend(node, retry_entity)
else:
raise NotImplementedError()
if not self.processIqRegistry(protocolTreeNode):
if protocolTreeNode.tag == "receipt":
'''
Going to keep all group message enqueued, as we get receipts from each participant
So can't just remove it on first receipt. Therefore, the MAX queue length mechanism should better be working
'''
messageNode = self.getEnqueuedMessageNode(protocolTreeNode["id"], protocolTreeNode["participant"] is not None)
if not messageNode:
logger.debug("Axolotl layer does not have the message, bubbling it upwards")
self.toUpper(protocolTreeNode)
elif protocolTreeNode["type"] == "retry":
logger.info("Got retry to for message %s, and Axolotl layer has the message" % protocolTreeNode["id"])
retryReceiptEntity = RetryIncomingReceiptProtocolEntity.fromProtocolTreeNode(protocolTreeNode)
self.toLower(retryReceiptEntity.ack().toProtocolTreeNode())
self.getKeysFor(
[protocolTreeNode["participant"] or protocolTreeNode["from"]],
lambda successJids, errors: on_get_keys_success(messageNode, retryReceiptEntity, successJids, errors)
)
else:
#not interested in any non retry receipts, bubble upwards
self.toUpper(protocolTreeNode)
def on_get_keys_process_errors(self, errors):
# type: (dict) -> None
for jid, error in errors.items():
if isinstance(error, MissingParametersException):
logger.error("Failed to create prekeybundle for %s, user had missing parameters: %s, "
"is that a valid user?" % (jid, error.parameters))
elif isinstance(error, exceptions.UntrustedIdentityException):
logger.error("Failed to create session for %s as user's identity is not trusted. " % jid)
else:
logger.error("Failed to process keys for %s, is that a valid user? Exception: %s" % error)
def processPlaintextNodeAndSend(self, node, retryReceiptEntity = None):
recipient_id = node["to"].split('@')[0]
isGroup = "-" in recipient_id
def on_get_keys_error(error_node, getkeys_entity, plaintext_node):
logger.error("Failed to fetch keys for %s, is that a valid user? "
"Server response: [code=%s, text=%s], aborting send." % (
plaintext_node["to"], error_node.children[0]["code"], error_node.children[0]["text"]
))
def on_get_keys_success(node, success_jids, errors):
if len(errors):
self.on_get_keys_process_errors(errors)
elif len(success_jids) == 1:
self.sendToContact(node)
else:
raise NotImplementedError()
if isGroup:
self.sendToGroup(node, retryReceiptEntity)
elif self.manager.session_exists(recipient_id):
self.sendToContact(node)
else:
self.getKeysFor(
[node["to"]],
lambda successJids, errors: on_get_keys_success(node, successJids, errors),
lambda error_node, entity: on_get_keys_error(error_node, entity, node)
)
def enqueueSent(self, node):
logger.debug("enqueueSent(node=[omitted])")
if len(self.sentQueue) >= self.__class__.MAX_SENT_QUEUE:
logger.warn("Discarding queued node without receipt")
self.sentQueue.pop(0)
self.sentQueue.append(node)
def getEnqueuedMessageNode(self, messageId, keepEnqueued = False):
for i in range(0, len(self.sentQueue)):
if self.sentQueue[i]["id"] == messageId:
if keepEnqueued:
return self.sentQueue[i]
return self.sentQueue.pop(i)
def sendEncEntities(self, node, encEntities, participant=None):
logger.debug("sendEncEntities(node=[omitted], encEntities=[omitted], participant=%s)" % participant)
message_attrs = MessageMetaAttributes.from_message_protocoltreenode(node)
message_attrs.participant = participant
messageEntity = EncryptedMessageProtocolEntity(
encEntities,
node["type"],
message_attrs
)
# if participant is set, this message is directed to that specific participant as a result of a retry, therefore
# we already have the original group message and there is no need to store it again.
if participant is None:
self.enqueueSent(node)
self.toLower(messageEntity.toProtocolTreeNode())
def sendToContact(self, node):
recipient_id = node["to"].split('@')[0]
protoNode = node.getChild("proto")
messageData = protoNode.getData()
ciphertext = self.manager.encrypt(
recipient_id,
messageData
)
mediaType = protoNode["mediatype"]
return self.sendEncEntities(node, [EncProtocolEntity(EncProtocolEntity.TYPE_MSG if ciphertext.__class__ == WhisperMessage else EncProtocolEntity.TYPE_PKMSG, 2, ciphertext.serialize(), mediaType)])
def sendToGroupWithSessions(self, node, jidsNeedSenderKey = None, retryCount=0):
"""
For each jid in jidsNeedSenderKey will create a pkmsg enc node with the associated jid.
If retryCount > 0 and we have only one jidsNeedSenderKey, this is a retry requested by a specific participant
and this message is to be directed at specific at that participant indicated by jidsNeedSenderKey[0]. In this
case the participant's jid would go in the parent's EncryptedMessage and not into the enc node.
"""
logger.debug(
"sendToGroupWithSessions(node=[omitted], jidsNeedSenderKey=%s, retryCount=%d)" % (jidsNeedSenderKey, retryCount)
)
jidsNeedSenderKey = jidsNeedSenderKey or []
groupJid = node["to"]
protoNode = node.getChild("proto")
encEntities = []
participant = jidsNeedSenderKey[0] if len(jidsNeedSenderKey) == 1 and retryCount > 0 else None
if len(jidsNeedSenderKey):
senderKeyDistributionMessage = self.manager.group_create_skmsg(groupJid)
for jid in jidsNeedSenderKey:
message = self.serializeSenderKeyDistributionMessageToProtobuf(node["to"], senderKeyDistributionMessage)
if retryCount > 0:
message.MergeFromString(protoNode.getData())
ciphertext = self.manager.encrypt(jid.split('@')[0], message.SerializeToString())
encEntities.append(
EncProtocolEntity(
EncProtocolEntity.TYPE_MSG if ciphertext.__class__ == WhisperMessage else EncProtocolEntity.TYPE_PKMSG
, 2, ciphertext.serialize(), protoNode["mediatype"], jid=None if participant else jid
)
)
if not retryCount:
messageData = protoNode.getData()
ciphertext = self.manager.group_encrypt(groupJid, messageData)
mediaType = protoNode["mediatype"]
encEntities.append(EncProtocolEntity(EncProtocolEntity.TYPE_SKMSG, 2, ciphertext, mediaType))
self.sendEncEntities(node, encEntities, participant)
def ensureSessionsAndSendToGroup(self, node, jids):
logger.debug("ensureSessionsAndSendToGroup(node=[omitted], jids=%s)" % jids)
jidsNoSession = []
for jid in jids:
if not self.manager.session_exists(jid.split('@')[0]):
jidsNoSession.append(jid)
def on_get_keys_success(node, success_jids, errors):
if len(errors):
self.on_get_keys_process_errors(errors)
self.sendToGroupWithSessions(node, success_jids)
if len(jidsNoSession):
self.getKeysFor(jidsNoSession, lambda successJids, errors: on_get_keys_success(node, successJids, errors))
else:
self.sendToGroupWithSessions(node, jids)
def sendToGroup(self, node, retryReceiptEntity = None):
"""
Group send sequence:
check if senderkeyrecord exists
no: - create,
- get group jids from info request
- for each jid without a session, get keys to create the session
- send message with dist key for all participants
yes:
- send skmsg without any dist key
received retry for a participant
- request participants keys
- send message with dist key only + conversation, only for this participat
"""
logger.debug("sendToGroup(node=[omitted], retryReceiptEntity=[%s])" %
("[retry_count=%s, retry_jid=%s]" % (
retryReceiptEntity.getRetryCount(), retryReceiptEntity.getRetryJid())
) if retryReceiptEntity is not None else None)
groupJid = node["to"]
ownJid = self.getLayerInterface(YowAuthenticationProtocolLayer).getUsername(True)
senderKeyRecord = self.manager.load_senderkey(node["to"])
def sendToGroup(resultNode, requestEntity):
groupInfo = InfoGroupsResultIqProtocolEntity.fromProtocolTreeNode(resultNode)
jids = list(groupInfo.getParticipants().keys()) #keys in py3 returns dict_keys
if ownJid in jids:
jids.remove(ownJid)
return self.ensureSessionsAndSendToGroup(node, jids)
if senderKeyRecord.isEmpty():
logger.debug("senderKeyRecord is empty, requesting group info")
groupInfoIq = InfoGroupsIqProtocolEntity(groupJid)
self._sendIq(groupInfoIq, sendToGroup)
else:
logger.debug("We have a senderKeyRecord")
retryCount = 0
jidsNeedSenderKey = []
if retryReceiptEntity is not None:
retryCount = retryReceiptEntity.getRetryCount()
jidsNeedSenderKey.append(retryReceiptEntity.getRetryJid())
self.sendToGroupWithSessions(node, jidsNeedSenderKey, retryCount)
def serializeSenderKeyDistributionMessageToProtobuf(self, groupId, senderKeyDistributionMessage, message = None):
m = message or Message()
m.sender_key_distribution_message.group_id = groupId
m.sender_key_distribution_message.axolotl_sender_key_distribution_message = senderKeyDistributionMessage.serialize()
m.sender_key_distribution_message.axolotl_sender_key_distribution_message = senderKeyDistributionMessage.serialize()
# m.conversation = text
return m
| 12,897 | Python | .py | 227 | 44.612335 | 204 | 0.651073 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,645 | layer_receive.py | tgalal_yowsup/yowsup/layers/axolotl/layer_receive.py | from .layer_base import AxolotlBaseLayer
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_messages.proto.e2e_pb2 import *
from yowsup.layers.axolotl.protocolentities import *
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_messages.protocolentities.proto import ProtoProtocolEntity
from yowsup.layers.axolotl.props import PROP_IDENTITY_AUTOTRUST
from yowsup.axolotl import exceptions
from axolotl.untrustedidentityexception import UntrustedIdentityException
import logging
logger = logging.getLogger(__name__)
class AxolotlReceivelayer(AxolotlBaseLayer):
def __init__(self):
super(AxolotlReceivelayer, self).__init__()
self.v2Jids = [] #people we're going to send v2 enc messages
self.sessionCiphers = {}
self.groupCiphers = {}
self.pendingIncomingMessages = {} #(jid, participantJid?) => message
self._retries = {}
def receive(self, protocolTreeNode):
"""
:type protocolTreeNode: ProtocolTreeNode
"""
if not self.processIqRegistry(protocolTreeNode):
if protocolTreeNode.tag == "message":
self.onMessage(protocolTreeNode)
elif not protocolTreeNode.tag == "receipt":
#receipts will be handled by send layer
self.toUpper(protocolTreeNode)
def processPendingIncomingMessages(self, jid, participantJid = None):
conversationIdentifier = (jid, participantJid)
if conversationIdentifier in self.pendingIncomingMessages:
for messageNode in self.pendingIncomingMessages[conversationIdentifier]:
self.onMessage(messageNode)
del self.pendingIncomingMessages[conversationIdentifier]
def onMessage(self, protocolTreeNode):
encNode = protocolTreeNode.getChild("enc")
if encNode:
self.handleEncMessage(protocolTreeNode)
else:
self.toUpper(protocolTreeNode)
def handleEncMessage(self, node):
encMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(node)
isGroup = node["participant"] is not None
senderJid = node["participant"] if isGroup else node["from"]
if node.getChild("enc")["v"] == "2" and node["from"] not in self.v2Jids:
self.v2Jids.append(node["from"])
try:
if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_PKMSG):
self.handlePreKeyWhisperMessage(node)
elif encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_MSG):
self.handleWhisperMessage(node)
if encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_SKMSG):
self.handleSenderKeyMessage(node)
self.reset_retries(node["id"])
except exceptions.InvalidKeyIdException:
logger.warning("Invalid KeyId for %s, going to send a retry", encMessageProtocolEntity.getAuthor(False))
self.send_retry(node, self.manager.registration_id)
except exceptions.InvalidMessageException:
logger.warning("InvalidMessage for %s, going to send a retry", encMessageProtocolEntity.getAuthor(False))
self.send_retry(node, self.manager.registration_id)
except exceptions.NoSessionException:
logger.warning("No session for %s, getting their keys now", encMessageProtocolEntity.getAuthor(False))
conversationIdentifier = (node["from"], node["participant"])
if conversationIdentifier not in self.pendingIncomingMessages:
self.pendingIncomingMessages[conversationIdentifier] = []
self.pendingIncomingMessages[conversationIdentifier].append(node)
successFn = lambda successJids, b: self.processPendingIncomingMessages(*conversationIdentifier) if len(successJids) else None
self.getKeysFor([senderJid], successFn)
except exceptions.DuplicateMessageException:
logger.warning("Received a message that we've previously decrypted, "
"going to send the delivery receipt myself")
self.toLower(OutgoingReceiptProtocolEntity(node["id"], node["from"], participant=node["participant"]).toProtocolTreeNode())
except UntrustedIdentityException as e:
if self.getProp(PROP_IDENTITY_AUTOTRUST, False):
logger.warning("Autotrusting identity for %s", e.getName())
self.manager.trust_identity(e.getName(), e.getIdentityKey())
return self.handleEncMessage(node)
else:
logger.error("Ignoring message with untrusted identity")
def handlePreKeyWhisperMessage(self, node):
pkMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(node)
enc = pkMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_PKMSG)
plaintext = self.manager.decrypt_pkmsg(pkMessageProtocolEntity.getAuthor(False), enc.getData(),
enc.getVersion() == 2)
if enc.getVersion() == 2:
self.parseAndHandleMessageProto(pkMessageProtocolEntity, plaintext)
node = pkMessageProtocolEntity.toProtocolTreeNode()
node.addChild((ProtoProtocolEntity(plaintext, enc.getMediaType())).toProtocolTreeNode())
self.toUpper(node)
def handleWhisperMessage(self, node):
encMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(node)
enc = encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_MSG)
plaintext = self.manager.decrypt_msg(encMessageProtocolEntity.getAuthor(False), enc.getData(),
enc.getVersion() == 2)
if enc.getVersion() == 2:
self.parseAndHandleMessageProto(encMessageProtocolEntity, plaintext)
node = encMessageProtocolEntity.toProtocolTreeNode()
node.addChild((ProtoProtocolEntity(plaintext, enc.getMediaType())).toProtocolTreeNode())
self.toUpper(node)
def handleSenderKeyMessage(self, node):
encMessageProtocolEntity = EncryptedMessageProtocolEntity.fromProtocolTreeNode(node)
enc = encMessageProtocolEntity.getEnc(EncProtocolEntity.TYPE_SKMSG)
try:
plaintext = self.manager.group_decrypt (
groupid=encMessageProtocolEntity.getFrom(True),
participantid=encMessageProtocolEntity.getParticipant(False),
data=enc.getData()
)
self.parseAndHandleMessageProto(encMessageProtocolEntity, plaintext)
node = encMessageProtocolEntity.toProtocolTreeNode()
node.addChild((ProtoProtocolEntity(plaintext, enc.getMediaType())).toProtocolTreeNode())
self.toUpper(node)
except exceptions.NoSessionException:
logger.warning("No session for %s, going to send a retry", encMessageProtocolEntity.getAuthor(False))
self.send_retry(node, self.manager.registration_id)
def parseAndHandleMessageProto(self, encMessageProtocolEntity, serializedData):
m = Message()
try:
m.ParseFromString(serializedData)
except:
print("DUMP:")
print(serializedData)
print([s for s in serializedData])
raise
if not m or not serializedData:
raise exceptions.InvalidMessageException()
if m.HasField("sender_key_distribution_message"):
self.handleSenderKeyDistributionMessage(
m.sender_key_distribution_message,
encMessageProtocolEntity.getParticipant(False)
)
def handleSenderKeyDistributionMessage(self, senderKeyDistributionMessage, participantId):
groupId = senderKeyDistributionMessage.group_id
self.manager.group_create_session(
groupid=groupId,
participantid=participantId,
skmsgdata=senderKeyDistributionMessage.axolotl_sender_key_distribution_message
)
def send_retry(self, message_node, registration_id):
message_id = message_node["id"]
if message_id in self._retries:
count = self._retries[message_id]
count += 1
else:
count = 1
self._retries[message_id] = count
retry = RetryOutgoingReceiptProtocolEntity.fromMessageNode(message_node, registration_id)
retry.count = count
self.toLower(retry.toProtocolTreeNode())
def reset_retries(self, message_id):
if message_id in self._retries:
del self._retries[message_id]
| 8,650 | Python | .py | 153 | 45.431373 | 137 | 0.694753 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,646 | __init__.py | tgalal_yowsup/yowsup/layers/axolotl/__init__.py | from .layer_send import AxolotlSendLayer
from .layer_control import AxolotlControlLayer
from .layer_receive import AxolotlReceivelayer
| 135 | Python | .py | 3 | 44 | 46 | 0.886364 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,647 | layer_base.py | tgalal_yowsup/yowsup/layers/axolotl/layer_base.py | from yowsup.layers import YowProtocolLayer
from yowsup.layers.axolotl.protocolentities import *
from yowsup.layers.network.layer import YowNetworkLayer
from yowsup.layers import EventCallback
from yowsup.profile.profile import YowProfile
from yowsup.axolotl import exceptions
from yowsup.layers.axolotl.props import PROP_IDENTITY_AUTOTRUST
import logging
logger = logging.getLogger(__name__)
class AxolotlBaseLayer(YowProtocolLayer):
def __init__(self):
super(AxolotlBaseLayer, self).__init__()
self._manager = None # type: AxolotlManager | None
self.skipEncJids = []
def send(self, node):
pass
def receive(self, node):
self.processIqRegistry(node)
@property
def manager(self):
"""
:return:
:rtype: AxolotlManager
"""
return self._manager
@EventCallback(YowNetworkLayer.EVENT_STATE_CONNECTED)
def on_connected(self, yowLayerEvent):
profile = self.getProp("profile") # type: YowProfile
self._manager = profile.axolotl_manager
@EventCallback(YowNetworkLayer.EVENT_STATE_DISCONNECTED)
def on_disconnected(self, yowLayerEvent):
self._manager = None
def getKeysFor(self, jids, resultClbk, errorClbk = None, reason=None):
logger.debug("getKeysFor(jids=%s, resultClbk=[omitted], errorClbk=[omitted], reason=%s)" % (jids, reason))
def onSuccess(resultNode, getKeysEntity):
entity = ResultGetKeysIqProtocolEntity.fromProtocolTreeNode(resultNode)
resultJids = entity.getJids()
successJids = []
errorJids = entity.getErrors() #jid -> exception
for jid in getKeysEntity.jids:
if jid not in resultJids:
self.skipEncJids.append(jid)
continue
recipient_id = jid.split('@')[0]
preKeyBundle = entity.getPreKeyBundleFor(jid)
try:
self.manager.create_session(recipient_id, preKeyBundle,
autotrust=self.getProp(PROP_IDENTITY_AUTOTRUST, False))
successJids.append(jid)
except exceptions.UntrustedIdentityException as e:
errorJids[jid] = e
logger.error(e)
logger.warning("Ignoring message with untrusted identity")
resultClbk(successJids, errorJids)
def onError(errorNode, getKeysEntity):
if errorClbk:
errorClbk(errorNode, getKeysEntity)
entity = GetKeysIqProtocolEntity(jids, reason=reason)
self._sendIq(entity, onSuccess, onError=onError)
| 2,702 | Python | .py | 59 | 34.966102 | 114 | 0.645603 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,648 | layer_control.py | tgalal_yowsup/yowsup/layers/axolotl/layer_control.py | from .layer_base import AxolotlBaseLayer
from yowsup.layers import YowLayerEvent, EventCallback
from yowsup.layers.network.layer import YowNetworkLayer
from yowsup.layers.axolotl.protocolentities import *
from yowsup.layers.auth.layer_authentication import YowAuthenticationProtocolLayer
from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity
from axolotl.util.hexutil import HexUtil
from axolotl.ecc.curve import Curve
import logging
import binascii
logger = logging.getLogger(__name__)
class AxolotlControlLayer(AxolotlBaseLayer):
def __init__(self):
super(AxolotlControlLayer, self).__init__()
self._unsent_prekeys = []
self._reboot_connection = False
def send(self, node):
self.toLower(node)
def receive(self, protocolTreeNode):
"""
:type protocolTreeNode: ProtocolTreeNode
"""
if not self.processIqRegistry(protocolTreeNode):
if protocolTreeNode.tag == "notification" and protocolTreeNode["type"] == "encrypt":
if protocolTreeNode.getChild("count") is not None:
return self.onRequestKeysEncryptNotification(protocolTreeNode)
elif protocolTreeNode.getChild("identity") is not None:
return self.onIdentityChangeEncryptNotification(protocolTreeNode)
self.toUpper(protocolTreeNode)
def onIdentityChangeEncryptNotification(self, protocoltreenode):
entity = IdentityChangeEncryptNotification.fromProtocolTreeNode(protocoltreenode)
ack = OutgoingAckProtocolEntity(
protocoltreenode["id"], "notification", protocoltreenode["type"], protocoltreenode["from"]
)
self.toLower(ack.toProtocolTreeNode())
self.getKeysFor([entity.getFrom(True)], resultClbk=lambda _,__: None, reason="identity")
def onRequestKeysEncryptNotification(self, protocolTreeNode):
entity = RequestKeysEncryptNotification.fromProtocolTreeNode(protocolTreeNode)
ack = OutgoingAckProtocolEntity(protocolTreeNode["id"], "notification", protocolTreeNode["type"], protocolTreeNode["from"])
self.toLower(ack.toProtocolTreeNode())
self.flush_keys(
self.manager.generate_signed_prekey(),
self.manager.level_prekeys(force=True)
)
@EventCallback(YowNetworkLayer.EVENT_STATE_CONNECTED)
def on_connected(self, yowLayerEvent):
super(AxolotlControlLayer, self).on_connected(yowLayerEvent)
self.manager.level_prekeys()
self._unsent_prekeys.extend(self.manager.load_unsent_prekeys())
if len(self._unsent_prekeys):
self.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True)
@EventCallback(YowAuthenticationProtocolLayer.EVENT_AUTHED)
def onAuthed(self, yowLayerEvent):
if yowLayerEvent.getArg("passive") and len(self._unsent_prekeys):
logger.debug("SHOULD FLUSH KEYS %d NOW!!" % len(self._unsent_prekeys))
self.flush_keys(
self.manager.load_latest_signed_prekey(generate=True),
self._unsent_prekeys[:], reboot_connection=True
)
self._unsent_prekeys = []
@EventCallback(YowNetworkLayer.EVENT_STATE_DISCONNECTED)
def on_disconnected(self, yowLayerEvent):
super(AxolotlControlLayer, self).on_disconnected(yowLayerEvent)
logger.debug(("Disconnected, reboot_connect? = %s" % self._reboot_connection))
if self._reboot_connection:
self._reboot_connection = False
#we requested this disconnect in this layer to switch off passive
#no need to traverse it to upper layers?
self.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, False)
self.getLayerInterface(YowNetworkLayer).connect()
def flush_keys(self, signed_prekey, prekeys, reboot_connection=False):
"""
sends prekeys
:return:
:rtype:
"""
preKeysDict = {}
for prekey in prekeys:
keyPair = prekey.getKeyPair()
preKeysDict[self.adjustId(prekey.getId())] = self.adjustArray(keyPair.getPublicKey().serialize()[1:])
signedKeyTuple = (self.adjustId(signed_prekey.getId()),
self.adjustArray(signed_prekey.getKeyPair().getPublicKey().serialize()[1:]),
self.adjustArray(signed_prekey.getSignature()))
setKeysIq = SetKeysIqProtocolEntity(
self.adjustArray(
self.manager.identity.getPublicKey().serialize()[1:]
),
signedKeyTuple,
preKeysDict,
Curve.DJB_TYPE,
self.adjustId(self.manager.registration_id)
)
onResult = lambda _, __: self.on_keys_flushed(prekeys, reboot_connection=reboot_connection)
self._sendIq(setKeysIq, onResult, self.onSentKeysError)
def on_keys_flushed(self, prekeys, reboot_connection):
self.manager.set_prekeys_as_sent(prekeys)
if reboot_connection:
self._reboot_connection = True
self.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
def onSentKeysError(self, errorNode, keysEntity):
raise Exception("Sent keys were not accepted")
def adjustArray(self, arr):
return HexUtil.decodeHex(binascii.hexlify(arr))
def adjustId(self, _id):
_id = format(_id, 'x')
zfiller = len(_id) if len(_id) % 2 == 0 else len(_id) + 1
_id = _id.zfill(zfiller if zfiller > 6 else 6)
# if len(_id) % 2:
# _id = "0" + _id
return binascii.unhexlify(_id)
| 5,633 | Python | .py | 110 | 41.672727 | 131 | 0.680959 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,649 | iq_key_get.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/iq_key_get.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class GetKeysIqProtocolEntity(IqProtocolEntity):
def __init__(self, jids, reason=None):
super(GetKeysIqProtocolEntity, self).__init__("encrypt", _type="get", to=YowConstants.WHATSAPP_SERVER)
self.jids = jids
self.reason = reason
@property
def reason(self):
# type: () -> str
return self._reason
@reason.setter
def reason(self, value):
# type: (str) -> None
self._reason = value
@property
def jids(self):
# type: () -> list[str]
return self._jids
@jids.setter
def jids(self, value):
# type: (list[str]) -> None
assert type(value) is list, "expected list of jids, got %s" % type(value)
self._jids = value
def toProtocolTreeNode(self):
node = super(GetKeysIqProtocolEntity, self).toProtocolTreeNode()
keyNode = ProtocolTreeNode("key")
for jid in self.jids:
attrs = { "jid": jid }
if self.reason is not None:
attrs["reason"] = self.reason
userNode = ProtocolTreeNode("user", attrs)
keyNode.addChild(userNode)
node.addChild(keyNode)
return node
| 1,343 | Python | .py | 36 | 29.416667 | 110 | 0.632025 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,650 | message_encrypted.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/message_encrypted.py | from yowsup.layers.protocol_messages.protocolentities import MessageProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.axolotl.protocolentities.enc import EncProtocolEntity
class EncryptedMessageProtocolEntity(MessageProtocolEntity):
'''
<message retry="1" from="49xxxxxxxx@s.whatsapp.net" t="1418906418" offline="1" type="text" id="1418906377-1" notify="Tarek Galal">
<enc type="{{type}}" mediatype="image|audio|location|document|contact" v="{{1 || 2}}">
HEX:33089eb3c90312210510e0196be72fe65913c6a84e75a54f40a3ee290574d6a23f408df990e718da761a210521f1a3f3d5cb87fde19fadf618d3001b64941715efd3e0f36bba48c23b08c82f2242330a21059b0ce2c4720ec79719ba862ee3cda6d6332746d05689af13aabf43ea1c8d747f100018002210d31cd6ebea79e441c4935f72398c772e2ee21447eb675cfa28b99de8d2013000</enc>
</message>
'''
def __init__(self, encEntities, _type, messageAttributes):
super(EncryptedMessageProtocolEntity, self).__init__(_type, messageAttributes)
self.setEncEntities(encEntities)
def setEncEntities(self, encEntities = None):
assert type(encEntities) is list and len(encEntities) \
, "Must have at least a list of minumum 1 enc entity"
self.encEntities = encEntities
def getEnc(self, encType):
for enc in self.encEntities:
if enc.type == encType:
return enc
def getEncEntities(self):
return self.encEntities
def toProtocolTreeNode(self):
node = super(EncryptedMessageProtocolEntity, self).toProtocolTreeNode()
participantsNode = ProtocolTreeNode("participants")
for enc in self.encEntities:
encNode = enc.toProtocolTreeNode()
if encNode.tag == "to":
participantsNode.addChild(encNode)
else:
node.addChild(encNode)
if len(participantsNode.getAllChildren()):
node.addChild(participantsNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = MessageProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = EncryptedMessageProtocolEntity
entity.setEncEntities(
[EncProtocolEntity.fromProtocolTreeNode(encNode) for encNode in node.getAllChildren("enc")]
)
return entity
| 2,299 | Python | .py | 43 | 45.27907 | 314 | 0.736983 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,651 | iq_keys_get_result.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/iq_keys_get_result.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
from axolotl.state.prekeybundle import PreKeyBundle
from axolotl.identitykey import IdentityKey
from axolotl.ecc.curve import Curve
from axolotl.ecc.djbec import DjbECPublicKey
import binascii
import sys
class ResultGetKeysIqProtocolEntity(ResultIqProtocolEntity):
"""
<iq type="result" from="s.whatsapp.net" id="3">
<list>
<user jid="79049347231@s.whatsapp.net">
<registration>
HEX:7a9cec4b</registration>
<type>
HEX:05</type>
<identity>
HEX:eeb668c8d062c99b43560c811acfe6e492798b496767eb060d99e011d3862369</identity>
<skey>
<id>
HEX:000000</id>
<value>
HEX:a1b5216ce4678143fb20aaaa2711a8c2b647230164b79414f0550b4e611ccd6c</value>
<signature>
HEX:94c231327fcd664b34603838b5e9ba926718d71c206e92b2b400f5cf4ae7bf17d83557bf328c1be6d51efdbd731a26d000adb8f38f140b1ea2a5fd3df2688085</signature>
</skey>
<key>
<id>
HEX:36b545</id>
<value>
HEX:c20826f622bec24b349ced38f1854bdec89ba098ef4c06b2402800d33e9aff61</value>
</key>
</user>
</list>
</iq>
"""
def __init__(self, _id, preKeyBundleMap = None):
super(ResultGetKeysIqProtocolEntity, self).__init__(_from = YowConstants.WHATSAPP_SERVER, _id=_id)
self.setPreKeyBundleMap(preKeyBundleMap)
self._errors = {}
def getJids(self):
return self.preKeyBundleMap.keys()
def getErrors(self):
return self._errors.copy()
def setErrorFor(self, jid, exception):
self._errors[jid] = exception
def setPreKeyBundleMap(self, preKeyBundleMap = None):
self.preKeyBundleMap = preKeyBundleMap or {}
def setPreKeyBundleFor(self, jid, preKeyBundle):
self.preKeyBundleMap[jid] = preKeyBundle
def getPreKeyBundleFor(self, jid):
if jid in self.preKeyBundleMap:
return self.preKeyBundleMap[jid]
@staticmethod
def _intToBytes(val):
return binascii.unhexlify(format(val, 'x').zfill(8).encode())
@staticmethod
def _bytesToInt(val):
if sys.version_info >= (3,0):
valEnc = val.encode('latin-1') if type(val) is str else val
else:
valEnc = val
return int(binascii.hexlify(valEnc), 16)
@staticmethod
def encStr(string):
if sys.version_info >= (3,0) and type(string) is str:
return string.encode('latin-1')
return string
@staticmethod
def fromProtocolTreeNode(node):
entity = ResultGetKeysIqProtocolEntity(node["id"])
userNodes = node.getChild("list").getAllChildren()
for userNode in userNodes:
missing_params = []
preKeyNode = userNode.getChild("key")
signedPreKeyNode = userNode.getChild("skey")
registrationNode = userNode.getChild("registration")
identityNode = userNode.getChild("identity")
if preKeyNode is None:
missing_params.append(MissingParametersException.PARAM_KEY)
if signedPreKeyNode is None:
missing_params.append(MissingParametersException.PARAM_SKEY)
if registrationNode is None:
missing_params.append(MissingParametersException.PARAM_REGISTRATION)
if identityNode is None:
missing_params.append(MissingParametersException.PARAM_IDENTITY)
if len(missing_params):
entity.setErrorFor(userNode["jid"], MissingParametersException(userNode["jid"], missing_params))
else:
registrationId = ResultGetKeysIqProtocolEntity._bytesToInt(registrationNode.getData())
identityKey = IdentityKey(DjbECPublicKey(ResultGetKeysIqProtocolEntity.encStr(identityNode.getData())))
preKeyId = ResultGetKeysIqProtocolEntity._bytesToInt(preKeyNode.getChild("id").getData())
preKeyPublic = DjbECPublicKey(ResultGetKeysIqProtocolEntity.encStr(preKeyNode.getChild("value").getData()))
signedPreKeyId = ResultGetKeysIqProtocolEntity._bytesToInt(signedPreKeyNode.getChild("id").getData())
signedPreKeySig = ResultGetKeysIqProtocolEntity.encStr(signedPreKeyNode.getChild("signature").getData())
signedPreKeyPub = DjbECPublicKey(ResultGetKeysIqProtocolEntity.encStr(signedPreKeyNode.getChild("value").getData()))
preKeyBundle = PreKeyBundle(registrationId, 1, preKeyId, preKeyPublic,
signedPreKeyId, signedPreKeyPub, signedPreKeySig, identityKey)
entity.setPreKeyBundleFor(userNode["jid"], preKeyBundle)
return entity
def toProtocolTreeNode(self):
node = super(ResultGetKeysIqProtocolEntity, self).toProtocolTreeNode()
listNode = ProtocolTreeNode("list")
node.addChild(listNode)
for jid, preKeyBundle in self.preKeyBundleMap.items():
userNode = ProtocolTreeNode("user", {"jid": jid})
registrationNode = ProtocolTreeNode("registration", data = self.__class__._intToBytes(preKeyBundle.getRegistrationId()))
typeNode = ProtocolTreeNode("type", data = self.__class__._intToBytes(Curve.DJB_TYPE))
identityNode = ProtocolTreeNode("identity", data = preKeyBundle.getIdentityKey().getPublicKey().getPublicKey())
skeyNode = ProtocolTreeNode("skey")
skeyNode_idNode = ProtocolTreeNode("id", data=self.__class__._intToBytes(preKeyBundle.getSignedPreKeyId()))
skeyNode_valueNode = ProtocolTreeNode("value", data=preKeyBundle.getSignedPreKey().getPublicKey())
skeyNode_signatureNode = ProtocolTreeNode("signature", data=preKeyBundle.getSignedPreKeySignature())
skeyNode.addChildren([skeyNode_idNode, skeyNode_valueNode, skeyNode_signatureNode])
preKeyNode = ProtocolTreeNode("key")
preKeyNode_idNode = ProtocolTreeNode("id", data = self.__class__._intToBytes(preKeyBundle.getPreKeyId()))
preKeyNode_valueNode = ProtocolTreeNode("value", data= preKeyBundle.getPreKey().getPublicKey())
preKeyNode.addChildren([preKeyNode_idNode, preKeyNode_valueNode])
userNode.addChildren([
registrationNode,
typeNode,
identityNode,
skeyNode,
preKeyNode
])
listNode.addChild(userNode)
return node
class MissingParametersException(Exception):
PARAM_KEY = "key"
PARAM_IDENTITY = "identity"
PARAM_SKEY = "skey"
PARAM_REGISTRATION = "registration"
__PARAMS = (PARAM_KEY, PARAM_IDENTITY, PARAM_SKEY, PARAM_REGISTRATION)
def __init__(self, jid, parameters):
# type: (str, list | str) -> None
self._jid = jid
assert type(parameters) in (list, str)
if type(parameters) is str:
parameters = list(parameters)
assert len(parameters) > 0
for p in parameters:
assert p in self.__PARAMS, "%s is unrecognized param" % p
self._parameters = parameters
@property
def jid(self):
return self._jid
@property
def parameters(self):
return self._parameters
| 7,327 | Python | .py | 151 | 39.092715 | 148 | 0.682066 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,652 | test_iq_keys_set.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/test_iq_keys_set.py | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
from yowsup.layers.axolotl.protocolentities import SetKeysIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class SetKeysIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(SetKeysIqProtocolEntityTest, self).setUp()
# self.ProtocolEntity = SetKeysIqProtocolEntity
#
# regNode = ProtocolTreeNode("registration", data = "abcd")
# idNode = ProtocolTreeNode("identity", data = "efgh")
# typeNode = ProtocolTreeNode("type", data = "ijkl")
# listNode = ProtocolTreeNode("list")
# for i in range(0, 2):
# keyNode = ProtocolTreeNode("key", children=[
# ProtocolTreeNode("id", data = "id_%s" % i),
# ProtocolTreeNode("value", data = "val_%s" % i)
# ])
# listNode.addChild(keyNode)
#
# self.node.addChildren([regNode, idNode, typeNode, listNode])
| 999 | Python | .py | 20 | 42.75 | 83 | 0.659857 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,653 | test_notification_encrypt_requestkeys.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/test_notification_encrypt_requestkeys.py | from yowsup.layers.protocol_notifications.protocolentities.test_notification import NotificationProtocolEntityTest
from yowsup.layers.axolotl.protocolentities import RequestKeysEncryptNotification
from yowsup.structs import ProtocolTreeNode
class TestRequestKeysEncryptNotification(NotificationProtocolEntityTest):
def setUp(self):
super(TestRequestKeysEncryptNotification, self).setUp()
self.ProtocolEntity = RequestKeysEncryptNotification
self.node.addChild(ProtocolTreeNode("count", {"value": "9"})) | 532 | Python | .py | 8 | 61.875 | 114 | 0.839388 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,654 | notification_encrypt_identitychange.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/notification_encrypt_identitychange.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_notifications.protocolentities import NotificationProtocolEntity
from yowsup.structs import ProtocolTreeNode
class IdentityChangeEncryptNotification(NotificationProtocolEntity):
"""
<notification t="1419824928" id="2451228097" from="s.whatsapp.net" type="encrypt">
<identity />
</notification>
"""
def __init__(self, timestamp, _id = None, notify = None, offline = None):
super(IdentityChangeEncryptNotification, self).__init__(
"encrypt", _id, YowConstants.WHATSAPP_SERVER, timestamp, notify, offline
)
def toProtocolTreeNode(self):
node = super(IdentityChangeEncryptNotification, self).toProtocolTreeNode()
node.addChild(ProtocolTreeNode("identity"))
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = NotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = IdentityChangeEncryptNotification
return entity
| 1,028 | Python | .py | 22 | 40.272727 | 92 | 0.738523 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,655 | notification_encrypt_requestkeys.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/notification_encrypt_requestkeys.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_notifications.protocolentities import NotificationProtocolEntity
from yowsup.structs import ProtocolTreeNode
class RequestKeysEncryptNotification(NotificationProtocolEntity):
"""
<notification t="1419824928" id="2451228097" from="s.whatsapp.net" type="encrypt">
<count value="9">
</count>
</notification>
"""
def __init__(self, count, timestamp, _id = None, notify = None, offline = None):
super(RequestKeysEncryptNotification, self).__init__(
"encrypt", _id, YowConstants.WHATSAPP_SERVER, timestamp, notify, offline
)
self._count = count
@property
def count(self):
return self._count
@count.setter
def count(self, value):
self._count = value
def toProtocolTreeNode(self):
node = super(RequestKeysEncryptNotification, self).toProtocolTreeNode()
count_node = ProtocolTreeNode("count", {"value": str(self.count)})
node.addChild(count_node)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = NotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = RequestKeysEncryptNotification
entity.count = node.getChild("count")["value"]
return entity
| 1,323 | Python | .py | 32 | 34.53125 | 92 | 0.698054 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,656 | test_iq_keys_get_result.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/test_iq_keys_get_result.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities.test_iq_result import ResultIqProtocolEntityTest
from yowsup.layers.axolotl.protocolentities import ResultGetKeysIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
from axolotl.util.keyhelper import KeyHelper
from axolotl.ecc.curve import Curve
class ResultGetKeysIqProtocolEntityTest(ResultIqProtocolEntityTest):
def setUp(self):
super(ResultGetKeysIqProtocolEntityTest, self).setUp()
self.ProtocolEntity = ResultGetKeysIqProtocolEntity
listNode = ProtocolTreeNode("list")
self.node.addChild(listNode)
self.node["from"] = "s.whatsapp.net"
del self.node.attributes["xmlns"]
for i in range(0, 1):
userNode = ProtocolTreeNode("user", {"jid": "user_%s@%s" % (i, YowConstants.WHATSAPP_SERVER)})
listNode.addChild(userNode)
registrationNode = ProtocolTreeNode("registration",
data = ResultGetKeysIqProtocolEntity._intToBytes(
KeyHelper.generateRegistrationId()))
typeNode = ProtocolTreeNode("type", data = ResultGetKeysIqProtocolEntity._intToBytes(Curve.DJB_TYPE))
identityKeyPair = KeyHelper.generateIdentityKeyPair()
identityNode = ProtocolTreeNode("identity", data=identityKeyPair.getPublicKey().getPublicKey().getPublicKey())
signedPreKey = KeyHelper.generateSignedPreKey(identityKeyPair, i)
signedPreKeyNode = ProtocolTreeNode("skey")
signedPreKeyNode_idNode = ProtocolTreeNode("id",
data = ResultGetKeysIqProtocolEntity._intToBytes(
signedPreKey.getId()))
signedPreKeyNode_valueNode = ProtocolTreeNode("value",
data = signedPreKey.getKeyPair().getPublicKey().getPublicKey())
signedPreKeyNode_sigNode = ProtocolTreeNode("signature",
data = signedPreKey.getSignature())
signedPreKeyNode.addChildren([signedPreKeyNode_idNode, signedPreKeyNode_valueNode, signedPreKeyNode_sigNode])
preKey = KeyHelper.generatePreKeys(i * 10, 1)[0]
preKeyNode = ProtocolTreeNode("key")
preKeyNode_idNode = ProtocolTreeNode("id", data = ResultGetKeysIqProtocolEntity._intToBytes(preKey.getId()))
preKeyNode_valNode = ProtocolTreeNode("value", data = preKey.getKeyPair().getPublicKey().getPublicKey())
preKeyNode.addChildren([preKeyNode_idNode, preKeyNode_valNode])
userNode.addChildren([
registrationNode,
typeNode,
identityNode,
signedPreKeyNode,
preKeyNode
])
| 2,946 | Python | .py | 45 | 48.711111 | 122 | 0.63885 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,657 | __init__.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/__init__.py | from .iq_key_get import GetKeysIqProtocolEntity
from .iq_keys_set import SetKeysIqProtocolEntity
from .iq_keys_get_result import ResultGetKeysIqProtocolEntity
from .message_encrypted import EncryptedMessageProtocolEntity
from .enc import EncProtocolEntity
from .receipt_outgoing_retry import RetryOutgoingReceiptProtocolEntity
from .receipt_incoming_retry import RetryIncomingReceiptProtocolEntity
from .notification_encrypt_identitychange import IdentityChangeEncryptNotification
from .notification_encrypt_requestkeys import RequestKeysEncryptNotification
| 558 | Python | .py | 9 | 61 | 82 | 0.905282 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,658 | receipt_incoming_retry.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/receipt_incoming_retry.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_receipts.protocolentities import IncomingReceiptProtocolEntity
from yowsup.layers.axolotl.protocolentities.iq_keys_get_result import ResultGetKeysIqProtocolEntity
class RetryIncomingReceiptProtocolEntity(IncomingReceiptProtocolEntity):
'''
<receipt type="retry" from="xxxxxxxxxxx@s.whatsapp.net" participant="" id="1415389947-12" t="1432833777">
<retry count="1" t="1432833266" id="1415389947-12" v="1">
</retry>
<registration>
HEX:xxxxxxxxx
</registration>
</receipt>
'''
def __init__(self, _id, jid, remoteRegistrationId, receiptTimestamp, retryTimestamp, v = 1, count = 1, participant = None, offline = None):
super(RetryIncomingReceiptProtocolEntity, self).__init__(_id, jid, receiptTimestamp, offline=offline, type="retry", participant=participant)
self.setRetryData(remoteRegistrationId, v,count, retryTimestamp)
def setRetryData(self, remoteRegistrationId, v, count, retryTimestamp):
self.remoteRegistrationId = remoteRegistrationId
self.v = int(v)
self.count = int(count)
self.retryTimestamp = int(retryTimestamp)
def toProtocolTreeNode(self):
node = super(RetryIncomingReceiptProtocolEntity, self).toProtocolTreeNode()
retry = ProtocolTreeNode("retry", {
"count": str(self.count),
"id": self.getId(),
"v": str(self.v),
"t": str(self.retryTimestamp)
})
node.addChild(retry)
registration = ProtocolTreeNode("registration", data=ResultGetKeysIqProtocolEntity._intToBytes(self.remoteRegistrationId))
node.addChild(registration)
return node
def getRetryCount(self):
return self.count
def getRetryJid(self):
return self.getParticipant() or self.getFrom()
def __str__(self):
out = super(RetryIncomingReceiptProtocolEntity, self).__str__()
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = IncomingReceiptProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = RetryIncomingReceiptProtocolEntity
retryNode = node.getChild("retry")
entity.setRetryData(ResultGetKeysIqProtocolEntity._bytesToInt(node.getChild("registration").data), retryNode["v"], retryNode["count"], retryNode["t"])
return entity
| 2,417 | Python | .py | 47 | 43.489362 | 158 | 0.70678 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,659 | iq_keys_set.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/iq_keys_set.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
import os, struct
class SetKeysIqProtocolEntity(IqProtocolEntity):
def __init__(self, identityKey, signedPreKey, preKeys, djbType, registrationId = None):
super(SetKeysIqProtocolEntity, self).__init__("encrypt", _type = "set", to = YowConstants.WHATSAPP_SERVER)
self.setProps(identityKey, signedPreKey, preKeys, djbType, registrationId)
def setProps(self, identityKey, signedPreKey, preKeys, djbType, registrationId = None):
assert type(preKeys) is dict, "Expected keys to be a dict key_id -> public_key"
assert type(signedPreKey) is tuple, "Exception signed pre key to be tuple id,key,signature"
self.preKeys = preKeys
self.identityKey = identityKey
self.registration = registrationId or os.urandom(4)
self.djbType = int(djbType)
self.signedPreKey = signedPreKey
@staticmethod
def fromProtocolTreeNode(node):
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = SetKeysIqProtocolEntity
regVal = node.getChild("registration").data
typeVal = node.getChild("type").data
idVal = node.getChild("identity").data
preKeys = {}
for keyNode in node.getChild("list").getAllChildren():
preKeys[keyNode.getChild("id").data] = keyNode.getChild("value").data
skeyNode = node.getChild("skey")
entity.setProps(idVal, (skeyNode.getChild("id").data, skeyNode.getChild("value").data,
skeyNode.getChild("signature").data), preKeys, typeVal, regVal)
return entity
def toProtocolTreeNode(self):
node = super(SetKeysIqProtocolEntity, self).toProtocolTreeNode()
identityNode = ProtocolTreeNode("identity", data = self.identityKey)
listNode = ProtocolTreeNode("list")
keyNodes = []
for keyId, pk in self.preKeys.items():
keyNode = ProtocolTreeNode("key")
keyNode.addChild(ProtocolTreeNode("id", data = keyId))
keyNode.addChild(ProtocolTreeNode("value", data = pk))
keyNodes.append(keyNode)
listNode.addChildren(keyNodes)
regNode = ProtocolTreeNode("registration", data = self.registration)
typeNode = ProtocolTreeNode("type", data = struct.pack('<B', self.djbType))
_id, val, signature = self.signedPreKey
skeyNode = ProtocolTreeNode("skey", children = [
ProtocolTreeNode("id", data = _id),
ProtocolTreeNode("value", data = val),
ProtocolTreeNode("signature", data = signature)
])
node.addChildren([
listNode,
identityNode,
regNode,
typeNode,
skeyNode
])
return node
| 2,901 | Python | .py | 57 | 41.403509 | 114 | 0.666667 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,660 | enc.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/enc.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
import sys
class EncProtocolEntity(ProtocolEntity):
TYPE_PKMSG = "pkmsg"
TYPE_MSG = "msg"
TYPE_SKMSG = "skmsg"
TYPES = (TYPE_PKMSG, TYPE_MSG, TYPE_SKMSG)
def __init__(self, type, version, data, mediaType = None, jid = None):
assert type in self.__class__.TYPES, "Unknown message enc type %s" % type
super(EncProtocolEntity, self).__init__("enc")
self.type = type
self.version = int(version)
self.data = data
self.mediaType = mediaType
self.jid = jid
def getType(self):
return self.type
def getVersion(self):
return self.version
def getData(self):
return self.data
def getMediaType(self):
return self.mediaType
def getJid(self):
return self.jid
def toProtocolTreeNode(self):
attribs = {"type": self.type, "v": str(self.version)}
if self.mediaType:
attribs["mediatype"] = self.mediaType
encNode = ProtocolTreeNode("enc", attribs, data = self.data)
if self.jid:
return ProtocolTreeNode("to", {"jid": self.jid}, [encNode])
return encNode
@staticmethod
def fromProtocolTreeNode(node):
return EncProtocolEntity(node["type"], node["v"], node.data, node["mediatype"])
| 1,354 | Python | .py | 36 | 30.277778 | 87 | 0.637405 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,661 | receipt_outgoing_retry.py | tgalal_yowsup/yowsup/layers/axolotl/protocolentities/receipt_outgoing_retry.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.axolotl.protocolentities.iq_keys_get_result import ResultGetKeysIqProtocolEntity
class RetryOutgoingReceiptProtocolEntity(OutgoingReceiptProtocolEntity):
'''
<receipt type="retry" to="xxxxxxxxxxx@s.whatsapp.net" participant="" id="1415389947-12" t="1432833777">
<retry count="1" t="1432833266" id="1415389947-12" v="1">
</retry>
<registration>
HEX:xxxxxxxxx
</registration>
</receipt>
'''
def __init__(self, _id, jid, local_registration_id, retry_timestamp, v=1, count=1, participant=None):
super(RetryOutgoingReceiptProtocolEntity, self).__init__(_id, jid, participant=participant)
'''
Note to self: Android clients won't retry sending if the retry node didn't contain the message timestamp
'''
self.local_registration_id = local_registration_id
self.v = v
self.retry_timestamp = retry_timestamp
self.count = count
@property
def local_registration_id(self):
return self._local_registration_id
@local_registration_id.setter
def local_registration_id(self, value):
self._local_registration_id = value
@property
def v(self):
return self._v
@v.setter
def v(self, value):
self._v = value
@property
def retry_timestamp(self):
return self._retry_timestamp
@retry_timestamp.setter
def retry_timestamp(self, value):
self._retry_timestamp = value
@property
def count(self):
return self._count
@count.setter
def count(self, value):
self._count = value
def toProtocolTreeNode(self):
node = super(RetryOutgoingReceiptProtocolEntity, self).toProtocolTreeNode()
node.setAttribute("type", "retry")
retry_attrs = {
"count": str(self.count),
"id":self.getId(),
"v":str(self.v),
"t": str(self.retry_timestamp)
}
retry = ProtocolTreeNode("retry", retry_attrs)
node.addChild(retry)
registration = ProtocolTreeNode(
"registration",
data=ResultGetKeysIqProtocolEntity._intToBytes(self.local_registration_id)
)
node.addChild(registration)
return node
def __str__(self):
out = super(RetryOutgoingReceiptProtocolEntity, self).__str__()
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = OutgoingReceiptProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = RetryOutgoingReceiptProtocolEntity
retry_node = node.getChild("retry")
entity.setRetryData(
ResultGetKeysIqProtocolEntity._bytesToInt(
node.getChild("registration").data
),
retry_node["v"], retry_node["count"], retry_node["t"]
)
return entity
@staticmethod
def fromMessageNode(message_node, local_registration_id):
return RetryOutgoingReceiptProtocolEntity(
message_node.getAttributeValue("id"),
message_node.getAttributeValue("from"),
local_registration_id,
message_node.getAttributeValue("t"),
participant=message_node.getAttributeValue("participant")
)
| 3,411 | Python | .py | 87 | 30.770115 | 116 | 0.658094 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,662 | layer.py | tgalal_yowsup/yowsup/layers/protocol_contacts/layer.py | from yowsup.layers import YowProtocolLayer
from .protocolentities import *
import logging
logger = logging.getLogger(__name__)
class YowContactsIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq),
"notification": (self.recvNotification, None)
}
super(YowContactsIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Contact Iq Layer"
def recvNotification(self, node):
if node["type"] == "contacts":
if node.getChild("remove"):
self.toUpper(RemoveContactNotificationProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("add"):
self.toUpper(AddContactNotificationProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("update"):
self.toUpper(UpdateContactNotificationProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("sync"):
self.toUpper(ContactsSyncNotificationProtocolEntity.fromProtocolTreeNode(node))
else:
logger.warning("Unsupported notification type: %s " % node["type"])
logger.debug("Unsupported notification node: %s" % node)
def recvIq(self, node):
if node["type"] == "result" and node.getChild("sync"):
self.toUpper(ResultSyncIqProtocolEntity.fromProtocolTreeNode(node))
def sendIq(self, entity):
if entity.getXmlns() == "urn:xmpp:whatsapp:sync":
self.toLower(entity.toProtocolTreeNode())
| 1,581 | Python | .py | 32 | 39.4375 | 96 | 0.662776 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,663 | test_layer.py | tgalal_yowsup/yowsup/layers/protocol_contacts/test_layer.py | from yowsup.layers import YowProtocolLayerTest
from yowsup.layers.protocol_contacts import YowContactsIqProtocolLayer
from yowsup.layers.protocol_contacts.protocolentities.test_notification_contact_add import entity as addEntity
from yowsup.layers.protocol_contacts.protocolentities.test_notification_contact_update import entity as updateEntity
from yowsup.layers.protocol_contacts.protocolentities.test_notification_contact_remove import entity as removeEntity
from yowsup.layers.protocol_contacts.protocolentities.test_iq_sync_result import entity as syncResultEntity
from yowsup.layers.protocol_contacts.protocolentities.test_iq_sync_get import entity as syncGetEntity
class YowContactsIqProtocolLayerTest(YowProtocolLayerTest, YowContactsIqProtocolLayer):
def setUp(self):
YowContactsIqProtocolLayer.__init__(self)
def test_sync(self):
self.assertSent(syncGetEntity)
def test_syncResult(self):
self.assertReceived(syncResultEntity)
def test_notificationAdd(self):
self.assertReceived(addEntity)
def test_notificationUpdate(self):
self.assertReceived(updateEntity)
def test_notificationRemove(self):
self.assertReceived(removeEntity)
| 1,216 | Python | .py | 20 | 55.9 | 116 | 0.828571 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,664 | test_notification_contact_add.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/test_notification_contact_add.py | from yowsup.layers.protocol_contacts.protocolentities import AddContactNotificationProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import time
import unittest
entity = AddContactNotificationProtocolEntity("1234", "jid@s.whatsapp.net", int(time.time()), "notify", False,
"sender@s.whatsapp.net")
class AddContactNotificationProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
super(AddContactNotificationProtocolEntityTest, self).setUp()
self.ProtocolEntity = AddContactNotificationProtocolEntity
self.node = entity.toProtocolTreeNode()
| 672 | Python | .py | 11 | 52.454545 | 110 | 0.760243 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,665 | test_iq_sync_result.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/test_iq_sync_result.py | from yowsup.layers.protocol_contacts.protocolentities.iq_sync_result import ResultSyncIqProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
entity = ResultSyncIqProtocolEntity("123", "1.30615237617e+17", 0,
True, "123456", {"12345678": "12345678@s.whatsapp.net"},
{"12345678": "12345678@s.whatsapp.net"}, ["1234"])
class ResultSyncIqProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = ResultSyncIqProtocolEntity
self.node = entity.toProtocolTreeNode()
def test_delta_result(self):
del self.node.getChild("sync")["wait"]
self.test_generation()
| 760 | Python | .py | 13 | 47.384615 | 102 | 0.680108 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,666 | notification_contact_add.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notification_contact_add.py | from yowsup.structs import ProtocolTreeNode
from .notification_contact import ContactNotificationProtocolEntity
class AddContactNotificationProtocolEntity(ContactNotificationProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="contacts"
t="{{TIMESTAMP}}" from="{{SENDER_JID}}">
<add jid="{{SET_JID}}"> </add>
</notification>
'''
def __init__(self, _id, _from, timestamp, notify, offline, contactJid):
super(AddContactNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline)
self.setData(contactJid)
def setData(self, jid):
self.contactJid = jid
def toProtocolTreeNode(self):
node = super(AddContactNotificationProtocolEntity, self).toProtocolTreeNode()
removeNode = ProtocolTreeNode("add", {"jid": self.contactJid}, None, None)
node.addChild(removeNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = ContactNotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = AddContactNotificationProtocolEntity
removeNode = node.getChild("add")
entity.setData(removeNode.getAttributeValue("jid"))
return entity | 1,271 | Python | .py | 26 | 41.884615 | 106 | 0.706119 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,667 | notification_contact_remove.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notification_contact_remove.py | from yowsup.structs import ProtocolTreeNode
from .notification_contact import ContactNotificationProtocolEntity
class RemoveContactNotificationProtocolEntity(ContactNotificationProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="contacts"
t="{{TIMESTAMP}}" from="{{SENDER_JID}}">
<remove jid="{{SET_JID}}"> </remove>
</notification>
'''
def __init__(self, _id, _from, timestamp, notify, offline, contactJid):
super(RemoveContactNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline)
self.setData(contactJid)
def setData(self, jid):
self.contactJid = jid
def toProtocolTreeNode(self):
node = super(RemoveContactNotificationProtocolEntity, self).toProtocolTreeNode()
removeNode = ProtocolTreeNode("remove", {"jid": self.contactJid}, None, None)
node.addChild(removeNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = ContactNotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = RemoveContactNotificationProtocolEntity
removeNode = node.getChild("remove")
entity.setData(removeNode.getAttributeValue("jid"))
return entity | 1,295 | Python | .py | 26 | 42.807692 | 109 | 0.71169 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,668 | iq_sync_get.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/iq_sync_get.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from .iq_sync import SyncIqProtocolEntity
class GetSyncIqProtocolEntity(SyncIqProtocolEntity):
MODE_FULL = "full"
MODE_DELTA = "delta"
CONTEXT_REGISTRATION = "registration"
CONTEXT_INTERACTIVE = "interactive"
CONTEXTS = (CONTEXT_REGISTRATION, CONTEXT_INTERACTIVE)
MODES = (MODE_FULL, MODE_DELTA)
'''
<iq type="get" id="{{id}}" xmlns="urn:xmpp:whatsapp:sync">
<sync mode="{{full | ?}}"
context="{{registration | ?}}"
sid="{{str((int(time.time()) + 11644477200) * 10000000)}}"
index="{{0 | ?}}"
last="{{true | false?}}"
>
<user>
{{num1}}
</user>
<user>
{{num2}}
</user>
</sync>
</iq>
'''
def __init__(self, numbers, mode = MODE_FULL, context = CONTEXT_INTERACTIVE, sid = None, index = 0, last = True):
super(GetSyncIqProtocolEntity, self).__init__("get", sid = sid, index = index, last = last)
self.setGetSyncProps(numbers, mode, context)
def setGetSyncProps(self, numbers, mode, context):
assert type(numbers) is list, "numbers must be a list"
assert mode in self.__class__.MODES, "mode must be in %s" % self.__class__.MODES
assert context in self.__class__.CONTEXTS, "context must be in %s" % self.__class__.CONTEXTS
self.numbers = numbers
self.mode = mode
self.context = context
def __str__(self):
out = super(GetSyncIqProtocolEntity, self).__str__()
out += "Mode: %s\n" % self.mode
out += "Context: %s\n" % self.context
out += "numbers: %s\n" % (",".join(self.numbers))
return out
def toProtocolTreeNode(self):
users = [ProtocolTreeNode("user", {}, None, number.encode()) for number in self.numbers]
node = super(GetSyncIqProtocolEntity, self).toProtocolTreeNode()
syncNode = node.getChild("sync")
syncNode.setAttribute("mode", self.mode)
syncNode.setAttribute("context", self.context)
syncNode.addChildren(users)
return node
@staticmethod
def fromProtocolTreeNode(node):
syncNode = node.getChild("sync")
userNodes = syncNode.getAllChildren()
numbers = [userNode.data.decode() for userNode in userNodes]
entity = SyncIqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = GetSyncIqProtocolEntity
entity.setGetSyncProps(numbers,
syncNode.getAttributeValue("mode"),
syncNode.getAttributeValue("context"),
)
return entity
| 2,766 | Python | .py | 63 | 35.206349 | 117 | 0.609084 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,669 | test_notification_contact_update.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/test_notification_contact_update.py | from yowsup.layers.protocol_contacts.protocolentities import UpdateContactNotificationProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import time
import unittest
entity = UpdateContactNotificationProtocolEntity("1234", "jid@s.whatsapp.net",
int(time.time()), "notify", False,"contactjid@s.whatsapp.net")
class UpdateContactNotificationProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = UpdateContactNotificationProtocolEntity
self.node = entity.toProtocolTreeNode()
| 612 | Python | .py | 10 | 53.1 | 111 | 0.771667 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,670 | notification_contact.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notification_contact.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from yowsup.layers.protocol_notifications.protocolentities import NotificationProtocolEntity
class ContactNotificationProtocolEntity(NotificationProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="contacts"
t="{{TIMESTAMP}}" from="{{SENDER_JID}}">
</notification>
'''
def __init__(self, _id, _from, timestamp, notify, offline = False):
super(ContactNotificationProtocolEntity, self).__init__("contacts", _id, _from, timestamp, notify, offline)
@staticmethod
def fromProtocolTreeNode(node):
entity = NotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = ContactNotificationProtocolEntity
return entity | 812 | Python | .py | 15 | 47.8 | 115 | 0.731646 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,671 | iq_sync.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/iq_sync.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
import time
class SyncIqProtocolEntity(IqProtocolEntity):
'''
<iq type="get" id="{{id}}" xmlns="urn:xmpp:whatsapp:sync">
<sync
sid="{{str((int(time.time()) + 11644477200) * 10000000)}}"
index="{{0 | ?}}"
last="{{true | false?}}"
>
</sync>
</iq>
'''
def __init__(self, _type, _id = None, sid = None, index = 0, last = True):
super(SyncIqProtocolEntity, self).__init__("urn:xmpp:whatsapp:sync", _id = _id, _type = _type)
self.setSyncProps(sid, index, last)
def setSyncProps(self, sid, index, last):
self.sid = sid if sid else str((int(time.time()) + 11644477200) * 10000000)
self.index = int(index)
self.last = last
def __str__(self):
out = super(SyncIqProtocolEntity, self).__str__()
out += "sid: %s\n" % self.sid
out += "index: %s\n" % self.index
out += "last: %s\n" % self.last
return out
def toProtocolTreeNode(self):
syncNodeAttrs = {
"sid": self.sid,
"index": str(self.index),
"last": "true" if self.last else "false"
}
syncNode = ProtocolTreeNode("sync", syncNodeAttrs)
node = super(SyncIqProtocolEntity, self).toProtocolTreeNode()
node.addChild(syncNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
syncNode = node.getChild("sync")
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = SyncIqProtocolEntity
entity.setSyncProps(
syncNode.getAttributeValue("sid"),
syncNode.getAttributeValue("index"),
syncNode.getAttributeValue("last")
)
return entity
| 1,903 | Python | .py | 48 | 31 | 102 | 0.58587 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,672 | test_notification_contact_remove.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/test_notification_contact_remove.py | from yowsup.layers.protocol_contacts.protocolentities import RemoveContactNotificationProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import time
import unittest
entity = RemoveContactNotificationProtocolEntity("1234", "jid@s.whatsapp.net",
int(time.time()), "notify", False, "contactjid@s.whatsapp.net")
class RemoveContactNotificationProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = RemoveContactNotificationProtocolEntity
self.node = entity.toProtocolTreeNode()
| 613 | Python | .py | 10 | 53.2 | 112 | 0.770383 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,673 | notification_contact_update.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notification_contact_update.py | from yowsup.structs import ProtocolTreeNode
from .notification_contact import ContactNotificationProtocolEntity
class UpdateContactNotificationProtocolEntity(ContactNotificationProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="contacts"
t="{{TIMESTAMP}}" from="{{SENDER_JID}}">
<update jid="{{SET_JID}}"> </update>
</notification>
'''
def __init__(self, _id, _from, timestamp, notify, offline, contactJid):
super(UpdateContactNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline)
self.setData(contactJid)
def setData(self, jid):
self.contactJid = jid
def toProtocolTreeNode(self):
node = super(UpdateContactNotificationProtocolEntity, self).toProtocolTreeNode()
removeNode = ProtocolTreeNode("update", {"jid": self.contactJid}, None, None)
node.addChild(removeNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = ContactNotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = UpdateContactNotificationProtocolEntity
removeNode = node.getChild("update")
entity.setData(removeNode.getAttributeValue("jid"))
return entity | 1,295 | Python | .py | 26 | 42.807692 | 109 | 0.71169 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,674 | notificiation_contacts_sync.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/notificiation_contacts_sync.py | from yowsup.structs import ProtocolTreeNode
from .notification_contact import ContactNotificationProtocolEntity
class ContactsSyncNotificationProtocolEntity(ContactNotificationProtocolEntity):
'''
<notification from="4917667738517@s.whatsapp.net" t="1437251557" offline="0" type="contacts" id="4174521704">
<sync after="1437251557"></sync>
</notification>
'''
def __init__(self, _id, _from, timestamp, notify, offline, after):
super(ContactsSyncNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, offline)
self.setData(after)
def setData(self, after):
self.after = int(after)
def toProtocolTreeNode(self):
node = super(ContactsSyncNotificationProtocolEntity, self).toProtocolTreeNode()
syncNode = ProtocolTreeNode("sync", {"after": str(self.after)}, None, None)
node.addChild(syncNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = ContactNotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = ContactsSyncNotificationProtocolEntity
syncNode = node.getChild("sync")
entity.setData(syncNode.getAttributeValue("after"))
return entity | 1,237 | Python | .py | 25 | 42.76 | 113 | 0.72622 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,675 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/__init__.py | from .iq_sync import SyncIqProtocolEntity
from .iq_sync_get import GetSyncIqProtocolEntity
from .iq_sync_result import ResultSyncIqProtocolEntity
from .notification_contact_add import AddContactNotificationProtocolEntity
from .notification_contact_remove import RemoveContactNotificationProtocolEntity
from .notification_contact_update import UpdateContactNotificationProtocolEntity
from .notificiation_contacts_sync import ContactsSyncNotificationProtocolEntity
| 463 | Python | .py | 7 | 65.142857 | 80 | 0.910088 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,676 | test_iq_sync_get.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/test_iq_sync_get.py | from yowsup.layers.protocol_contacts.protocolentities.iq_sync_get import GetSyncIqProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
entity = GetSyncIqProtocolEntity(["12345678", "8764543121"])
class GetSyncIqProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = GetSyncIqProtocolEntity
self.node = entity.toProtocolTreeNode() | 433 | Python | .py | 8 | 50.5 | 96 | 0.832547 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,677 | iq_sync_result.py | tgalal_yowsup/yowsup/layers/protocol_contacts/protocolentities/iq_sync_result.py | from yowsup.structs import ProtocolTreeNode
from .iq_sync import SyncIqProtocolEntity
class ResultSyncIqProtocolEntity(SyncIqProtocolEntity):
'''
<iq type="result" from="491632092557@s.whatsapp.net" id="1417046561-4">
<sync index="0" wait="166952" last="true" version="1417046548593182" sid="1.30615237617e+17">
<in>
<user jid="{{jid}}>{{number}}</user>
</in>
<out>
<user jid="{{jid}}">
{{number}}
</user>
</out>
<invalid>
<user>
abcdefgh
</user>
</invalid>
</sync>
</iq>
'''
def __init__(self,_id, sid, index, last, version, inNumbers, outNumbers, invalidNumbers, wait = None):
super(ResultSyncIqProtocolEntity, self).__init__("result", _id, sid, index, last)
self.setResultSyncProps(version, inNumbers, outNumbers, invalidNumbers, wait)
def setResultSyncProps(self, version, inNumbers, outNumbers, invalidNumbers, wait = None):
assert type(inNumbers) is dict, "in numbers must be a dict {number -> jid}"
assert type(outNumbers) is dict, "out numbers must be a dict {number -> jid}"
assert type(invalidNumbers) is list, "invalid numbers must be a list"
self.inNumbers = inNumbers
self.outNumbers = outNumbers
self.invalidNumbers = invalidNumbers
self.wait = int(wait) if wait is not None else None
self.version = version
def __str__(self):
out = super(SyncIqProtocolEntity, self).__str__()
if self.wait is not None:
out += "Wait: %s\n" % self.wait
out += "Version: %s\n" % self.version
out += "In Numbers: %s\n" % (",".join(self.inNumbers))
out += "Out Numbers: %s\n" % (",".join(self.outNumbers))
out += "Invalid Numbers: %s\n" % (",".join(self.invalidNumbers))
return out
def toProtocolTreeNode(self):
outUsers = [ProtocolTreeNode("user", {"jid": jid}, None, number.encode()) for number, jid in self.outNumbers.items()]
inUsers = [ProtocolTreeNode("user", {"jid": jid}, None, number.encode()) for number, jid in self.inNumbers.items()]
invalidUsers = [ProtocolTreeNode("user", {}, None, number.encode()) for number in self.invalidNumbers]
node = super(ResultSyncIqProtocolEntity, self).toProtocolTreeNode()
syncNode = node.getChild("sync")
syncNode.setAttribute("version", self.version)
if self.wait is not None:
syncNode.setAttribute("wait", str(self.wait))
if len(outUsers):
syncNode.addChild(ProtocolTreeNode("out", children = outUsers))
if len(inUsers):
syncNode.addChild(ProtocolTreeNode("in", children = inUsers))
if len(invalidUsers):
syncNode.addChildren([ProtocolTreeNode("invalid", children = invalidUsers)])
return node
@staticmethod
def fromProtocolTreeNode(node):
syncNode = node.getChild("sync")
outNode = syncNode.getChild("out")
inNode = syncNode.getChild("in")
invalidNode = syncNode.getChild("invalid")
outUsers = outNode.getAllChildren() if outNode else []
inUsers = inNode.getAllChildren() if inNode else []
invalidUsers = [inode.data.decode() for inode in invalidNode.getAllChildren()] if invalidNode else []
outUsersDict = {}
for u in outUsers:
outUsersDict[u.data.decode()] = u.getAttributeValue("jid")
inUsersDict = {}
for u in inUsers:
inUsersDict[u.data.decode()] = u.getAttributeValue("jid")
entity = SyncIqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = ResultSyncIqProtocolEntity
entity.setResultSyncProps(syncNode.getAttributeValue("version"),
inUsersDict,
outUsersDict,
invalidUsers,
syncNode.getAttributeValue("wait")
)
return entity
| 4,048 | Python | .py | 83 | 39.325301 | 125 | 0.620041 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,678 | layer.py | tgalal_yowsup/yowsup/layers/protocol_calls/layer.py | from yowsup.layers import YowProtocolLayer
from .protocolentities import *
from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
class YowCallsProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"call": (self.recvCall, self.sendCall)
}
super(YowCallsProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "call Layer"
def sendCall(self, entity):
if entity.getTag() == "call":
self.toLower(entity.toProtocolTreeNode())
def recvCall(self, node):
entity = CallProtocolEntity.fromProtocolTreeNode(node)
if entity.getType() == "offer":
receipt = OutgoingReceiptProtocolEntity(node["id"], node["from"], callId = entity.getCallId())
self.toLower(receipt.toProtocolTreeNode())
else:
ack = OutgoingAckProtocolEntity(node["id"], "call", None, node["from"])
self.toLower(ack.toProtocolTreeNode())
self.toUpper(entity)
| 1,119 | Python | .py | 24 | 38.75 | 106 | 0.688991 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,679 | test_call.py | tgalal_yowsup/yowsup/layers/protocol_calls/protocolentities/test_call.py | from yowsup.layers.protocol_calls.protocolentities.call import CallProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class CallProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = CallProtocolEntity
children = [ProtocolTreeNode("offer", {"call-id": "call_id"})]
attribs = {
"t": "12345",
"from": "from_jid",
"offline": "0",
"id": "message_id",
"notify": "notify_name"
}
self.node = ProtocolTreeNode("call", attribs, children)
| 662 | Python | .py | 16 | 33.8125 | 81 | 0.671318 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,680 | call.py | tgalal_yowsup/yowsup/layers/protocol_calls/protocolentities/call.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class CallProtocolEntity(ProtocolEntity):
'''
<call offline="0" from="{{CALLER_JID}}" id="{{ID}}" t="{{TIMESTAMP}}" notify="{{CALLER_PUSHNAME}}" retry="{{RETRY}}" e="{{?}}">
</call>
'''
def __init__(self, _id, _type, timestamp, notify = None, offline = None, retry = None, e = None, callId = None, _from = None, _to = None):
super(CallProtocolEntity, self).__init__("call")
self._id = _id or self._generateId()
self._type = _type
self._from = _from
self._to = _to
self.timestamp = int(timestamp)
self.notify = notify
self.offline = offline == "1"
self.retry = retry
self.e = e
self.callId = callId
def __str__(self):
out = "Call\n"
if self.getFrom() is not None:
out += "From: %s\n" % self.getFrom()
if self.getTo() is not None:
out += "To: %s\n" % self.getTo()
if self.getType() is not None:
out += "Type: %s\n" % self.getType()
if self.getCallId() is not None:
out += "Call ID: %s\n" % self.getCallId()
return out
def getFrom(self, full = True):
return self._from if full else self._from.split('@')[0]
def getTo(self):
return self._to
def getId(self):
return self._id
def getType(self):
return self._type
def getCallId(self):
return self.callId
def getTimestamp(self):
return self.timestamp
def toProtocolTreeNode(self):
children = []
attribs = {
"t" : str(self.timestamp),
"offline" : "1" if self.offline else "0",
"id" : self._id,
}
if self._from is not None:
attribs["from"] = self._from
if self._to is not None:
attribs["to"] = self._to
if self.retry is not None:
attribs["retry"] = self.retry
if self.e is not None:
attribs["e"] = self.e
if self.notify is not None:
attribs["notify"] = self.notify
if self._type in ["offer", "transport", "relaylatency", "reject", "terminate"]:
child = ProtocolTreeNode(self._type, {"call-id": self.callId})
children.append(child)
return self._createProtocolTreeNode(attribs, children = children, data = None)
@staticmethod
def fromProtocolTreeNode(node):
(_type, callId) = [None] * 2
offer = node.getChild("offer")
transport = node.getChild("transport")
relaylatency = node.getChild("relaylatency")
reject = node.getChild("reject")
terminate = node.getChild("terminate")
if offer:
_type = "offer"
callId = offer.getAttributeValue("call-id")
elif transport:
_type = "transport"
callId = transport.getAttributeValue("call-id")
elif relaylatency:
_type = "relaylatency"
callId = relaylatency.getAttributeValue("call-id")
elif reject:
_type = "reject"
callId = reject.getAttributeValue("call-id")
elif terminate:
_type = "terminate"
callId = terminate.getAttributeValue("call-id")
return CallProtocolEntity(
node.getAttributeValue("id"),
_type,
node.getAttributeValue("t"),
node.getAttributeValue("notify"),
node.getAttributeValue("offline"),
node.getAttributeValue("retry"),
node.getAttributeValue("e"),
callId,
node.getAttributeValue("from"),
node.getAttributeValue("to")
)
| 3,829 | Python | .py | 97 | 29.42268 | 142 | 0.547916 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,681 | layer_interface_authentication.py | tgalal_yowsup/yowsup/layers/auth/layer_interface_authentication.py | from yowsup.layers import YowLayerInterface
class YowAuthenticationProtocolLayerInterface(YowLayerInterface):
def setCredentials(self, phone, keypair):
self._layer.setCredentials((phone, keypair))
def getUsername(self, full = False):
return self._layer.getUsername(full)
| 297 | Python | .py | 6 | 44.166667 | 65 | 0.778547 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,682 | layer_authentication.py | tgalal_yowsup/yowsup/layers/auth/layer_authentication.py | from yowsup.common import YowConstants
from yowsup.layers import YowLayerEvent, YowProtocolLayer, EventCallback
from yowsup.layers.network import YowNetworkLayer
from .protocolentities import *
from .layer_interface_authentication import YowAuthenticationProtocolLayerInterface
from .protocolentities import StreamErrorProtocolEntity
import logging
logger = logging.getLogger(__name__)
class YowAuthenticationProtocolLayer(YowProtocolLayer):
EVENT_AUTHED = "org.openwhatsapp.yowsup.event.auth.authed"
EVENT_AUTH = "org.openwhatsapp.yowsup.event.auth"
PROP_CREDENTIALS = "org.openwhatsapp.yowsup.prop.auth.credentials"
PROP_PASSIVE = "org.openwhatsapp.yowsup.prop.auth.passive"
def __init__(self):
handleMap = {
"stream:features": (self.handleStreamFeatures, None),
"failure": (self.handleFailure, None),
"success": (self.handleSuccess, None),
"stream:error": (self.handleStreamError, None),
}
super(YowAuthenticationProtocolLayer, self).__init__(handleMap)
self.interface = YowAuthenticationProtocolLayerInterface(self)
def __str__(self):
return "Authentication Layer"
@EventCallback(YowNetworkLayer.EVENT_STATE_CONNECTED)
def on_connected(self, event):
self.broadcastEvent(
YowLayerEvent(
self.EVENT_AUTH,
passive=self.getProp(self.PROP_PASSIVE, False)
)
)
def setCredentials(self, credentials):
logger.warning("setCredentials is deprecated and has no effect, user stack.setProfile instead")
def getUsername(self, full = False):
username = self.getProp("profile").username
return username if not full else ("%s@%s" % (username, YowConstants.WHATSAPP_SERVER))
def handleStreamFeatures(self, node):
nodeEntity = StreamFeaturesProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(nodeEntity)
def handleSuccess(self, node):
successEvent = YowLayerEvent(self.__class__.EVENT_AUTHED, passive = self.getProp(self.__class__.PROP_PASSIVE))
self.broadcastEvent(successEvent)
nodeEntity = SuccessProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(nodeEntity)
def handleFailure(self, node):
nodeEntity = FailureProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(nodeEntity)
self.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT, reason = "Authentication Failure"))
def handleStreamError(self, node):
nodeEntity = StreamErrorProtocolEntity.fromProtocolTreeNode(node)
errorType = nodeEntity.getErrorType()
if not errorType:
raise NotImplementedError("Unhandled stream:error node:\n%s" % node)
self.toUpper(nodeEntity)
| 2,805 | Python | .py | 55 | 43.272727 | 118 | 0.725512 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,683 | response.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/response.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class ResponseProtocolEntity(ProtocolEntity):
def __init__(self, data, xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"):
super(ResponseProtocolEntity, self).__init__("response")
self.xmlns = xmlns
self.data = data
def toProtocolTreeNode(self):
return self._createProtocolTreeNode({"xmlns": self.xmlns}, children = None, data = self.data)
@staticmethod
def fromProtocolTreeNode(node):
return ResponseProtocolEntity(node.getData(), node.getAttributeValue("xmlns")) | 579 | Python | .py | 11 | 46.090909 | 101 | 0.724689 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,684 | test_success.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/test_success.py | from yowsup.layers.auth.protocolentities.success import SuccessProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class SuccessProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = SuccessProtocolEntity
attribs = {
"creation": "1234",
"location": "atn",
"props": "2",
"t": "1415470561"
}
self.node = ProtocolTreeNode("success", attribs)
| 552 | Python | .py | 14 | 32.285714 | 77 | 0.705224 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,685 | success.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/success.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class SuccessProtocolEntity(ProtocolEntity):
def __init__(self, creation, props, t, location):
super(SuccessProtocolEntity, self).__init__("success")
self.location = location
self.creation = int(creation)
self.props = props
self.t = int(t) ##whatever that is !
def __str__(self):
out = "Account:\n"
out += "Location: %s\n" % self.location
out += "Creation: %s\n" % self.creation
out += "Props: %s\n" % self.props
out += "t: %s\n" % self.t
return out
def toProtocolTreeNode(self):
attributes = {
"location" : self.location,
"creation" : str(self.creation),
"props" : self.props,
"t" : str(self.t)
}
return self._createProtocolTreeNode(attributes)
@staticmethod
def fromProtocolTreeNode(node):
return SuccessProtocolEntity(
node.getAttributeValue("creation"),
node.getAttributeValue("props"),
node.getAttributeValue("t"),
node.getAttributeValue("location")
) | 1,202 | Python | .py | 31 | 29.709677 | 62 | 0.57485 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,686 | challenge.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/challenge.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class ChallengeProtocolEntity(ProtocolEntity):
def __init__(self, nonce):
super(ChallengeProtocolEntity, self).__init__("challenge")
self.nonce = nonce
def getNonce(self):
return self.nonce
def toProtocolTreeNode(self):
#return self._createProtocolTreeNode({}, children = None, data = self.nonce)
return self._createProtocolTreeNode({}, children = [], data = "".join(map(chr, self.nonce)))
def __str__(self):
out = "Challenge\n"
out += "Nonce: %s\n" % self.nonce
return out
@staticmethod
def fromProtocolTreeNode(node):
nonce = list(map(ord,node.getData()))
entity = ChallengeProtocolEntity(bytearray(nonce))
return entity
| 803 | Python | .py | 19 | 34.947368 | 100 | 0.664948 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,687 | stream_features.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/stream_features.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class StreamFeaturesProtocolEntity(ProtocolEntity):
def __init__(self, features = None):
super(StreamFeaturesProtocolEntity, self).__init__("stream:features")
self.setFeatures(features)
def setFeatures(self, features = None):
self.features = features or []
def toProtocolTreeNode(self):
featureNodes = [ProtocolTreeNode(feature) for feature in self.features]
return self._createProtocolTreeNode({}, children = featureNodes, data = None)
@staticmethod
def fromProtocolTreeNode(node):
return StreamFeaturesProtocolEntity([fnode.tag for fnode in node.getAllChildren()]) | 699 | Python | .py | 13 | 47.307692 | 91 | 0.740849 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,688 | auth.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/auth.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class AuthProtocolEntity(ProtocolEntity):
def __init__(self, user, mechanism = "WAUTH-2", passive = False, nonce = None):
super(AuthProtocolEntity, self).__init__("auth")
self.user = user
self.mechanism = mechanism
self.passive = passive
self.nonce = nonce
def toProtocolTreeNode(self):
attributes = {
"user" : self.user,
"mechanism" : self.mechanism,
"passive" : "true" if self.passive else "false"
}
return self._createProtocolTreeNode(attributes, children = None, data = self.nonce)
@staticmethod
def fromProtocolTreeNode(node):
return AuthProtocolEntity(
node.getAttributeValue("user"),
node.getAttributeValue("mechanism"),
node.getAttributeValue("passive") != "false",
node.getData()
) | 956 | Python | .py | 23 | 32.347826 | 91 | 0.617457 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,689 | failure.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/failure.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class FailureProtocolEntity(ProtocolEntity):
def __init__(self, reason):
super(FailureProtocolEntity, self).__init__("failure")
self.reason = reason
def __str__(self):
out = "Failure:\n"
out += "Reason: %s\n" % self.reason
return out
def getReason(self):
return self.reason
def toProtocolTreeNode(self):
return self._createProtocolTreeNode({"reason": self.reason})
@staticmethod
def fromProtocolTreeNode(node):
return FailureProtocolEntity( node["reason"] )
| 612 | Python | .py | 16 | 31.4375 | 68 | 0.675127 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,690 | __init__.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/__init__.py | from .auth import AuthProtocolEntity
from .challenge import ChallengeProtocolEntity
from .response import ResponseProtocolEntity
from .stream_features import StreamFeaturesProtocolEntity
from .success import SuccessProtocolEntity
from .failure import FailureProtocolEntity
from .stream_error import StreamErrorProtocolEntity
| 325 | Python | .py | 7 | 45.428571 | 57 | 0.90566 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,691 | test_failure.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/test_failure.py | from yowsup.layers.auth.protocolentities.failure import FailureProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class FailureProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = FailureProtocolEntity
self.node = ProtocolTreeNode("failure", {"reason": "not-authorized"})
| 424 | Python | .py | 8 | 49.25 | 77 | 0.828502 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,692 | stream_error.py | tgalal_yowsup/yowsup/layers/auth/protocolentities/stream_error.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class StreamErrorProtocolEntity(ProtocolEntity):
TYPE_CONFLICT = "conflict"
'''
<stream:error>
<conflict></conflict>
<text>Replaced by new connection</text>
</stream:error>
'''
TYPE_ACK = "ack"
'''
<stream:error>
<ack></ack>
</stream:error>
'''
TYPE_XML_NOT_WELL_FORMED = "xml-not-well-formed"
'''
<stream:error>
<xml-not-well-formed>
</xml-not-well-formed>
</stream:error>
'''
TYPES = (TYPE_CONFLICT, TYPE_ACK, TYPE_XML_NOT_WELL_FORMED)
def __init__(self, data = None):
super(StreamErrorProtocolEntity, self).__init__("stream:error")
data = data or {}
self.setErrorData(data)
def setErrorData(self, data):
self.data = data
def getErrorData(self):
return self.data
def getErrorType(self):
for k in self.data.keys():
if k in self.__class__.TYPES:
return k
def __str__(self):
out = "Stream Error type: %s\n" % self.getErrorType()
out += "%s" % self.getErrorData()
out += "\n"
return out
def toProtocolTreeNode(self):
node = super(StreamErrorProtocolEntity, self).toProtocolTreeNode()
type = self.getErrorType()
node.addChild(ProtocolTreeNode(type))
if type == self.__class__.TYPE_CONFLICT and "text" in self.data:
node.addChild(ProtocolTreeNode("text", data=self.data["text"]))
return node
@staticmethod
def fromProtocolTreeNode(protocolTreeNode):
data = {}
for child in protocolTreeNode.getAllChildren():
data[child.tag] = child.data
return StreamErrorProtocolEntity(data)
| 1,782 | Python | .py | 53 | 26.037736 | 75 | 0.613054 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,693 | layer.py | tgalal_yowsup/yowsup/layers/protocol_acks/layer.py | from yowsup.layers import YowProtocolLayer
from .protocolentities import *
class YowAckProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"ack": (self.recvAckNode, self.sendAckEntity)
}
super(YowAckProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Ack Layer"
def sendAckEntity(self, entity):
self.entityToLower(entity)
def recvAckNode(self, node):
self.toUpper(IncomingAckProtocolEntity.fromProtocolTreeNode(node))
| 529 | Python | .py | 14 | 31.071429 | 74 | 0.693359 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,694 | test_layer.py | tgalal_yowsup/yowsup/layers/protocol_acks/test_layer.py | from yowsup.layers import YowProtocolLayerTest
from yowsup.layers.protocol_acks import YowAckProtocolLayer
from yowsup.layers.protocol_acks.protocolentities.test_ack_incoming import entity as incomingAckEntity
from yowsup.layers.protocol_acks.protocolentities.test_ack_outgoing import entity as outgoingAckEntity
class YowAckProtocolLayerTest(YowProtocolLayerTest, YowAckProtocolLayer):
def setUp(self):
YowAckProtocolLayer.__init__(self)
def test_receive(self):
self.assertReceived(incomingAckEntity)
def test_send(self):
self.assertSent(outgoingAckEntity)
| 596 | Python | .py | 11 | 49.727273 | 102 | 0.823328 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,695 | ack_outgoing.py | tgalal_yowsup/yowsup/layers/protocol_acks/protocolentities/ack_outgoing.py | from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):
'''
<ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
</ack>
<ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}">
</ack>
'''
def __init__(self, _id, _class, _type, to, participant = None):
super(OutgoingAckProtocolEntity, self).__init__(_id, _class)
self.setOutgoingData(_type, to, participant)
def setOutgoingData(self, _type, _to, _participant):
self._type = _type
self._to = _to
self._participant = _participant
def toProtocolTreeNode(self):
node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode()
if self._type:
node.setAttribute("type", self._type)
node.setAttribute("to", self._to)
if self._participant:
node.setAttribute("participant", self._participant)
return node
def __str__(self):
out = super(OutgoingAckProtocolEntity, self).__str__()
out += "Type: %s\n" % self._type
out += "To: %s\n" % self._to
if self._participant:
out += "Participant: %s\n" % self._participant
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = AckProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = OutgoingAckProtocolEntity
entity.setOutgoingData(
node.getAttributeValue("type"),
node.getAttributeValue("to"),
node.getAttributeValue("participant")
)
return entity
| 1,662 | Python | .py | 40 | 33.35 | 105 | 0.610905 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,696 | ack_incoming.py | tgalal_yowsup/yowsup/layers/protocol_acks/protocolentities/ack_incoming.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ack import AckProtocolEntity
class IncomingAckProtocolEntity(AckProtocolEntity):
'''
<ack t="{{TIMESTAMP}}" from="{{FROM_JID}}" id="{{MESSAGE_ID}}" class="{{message | receipt | ?}}">
</ack>
'''
def __init__(self, _id, _class, _from, timestamp):
super(IncomingAckProtocolEntity, self).__init__(_id, _class)
self.setIncomingData(_from, timestamp)
def setIncomingData(self, _from, timestamp):
self._from = _from
self.timestamp = timestamp
def toProtocolTreeNode(self):
node = super(IncomingAckProtocolEntity, self).toProtocolTreeNode()
node.setAttribute("from", self._from)
node.setAttribute("t", self.timestamp)
return node
def __str__(self):
out = super(IncomingAckProtocolEntity, self).__str__()
out += "From: %s\n" % self._from
out += "timestamp: %s\n" % self.timestamp
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = AckProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = IncomingAckProtocolEntity
entity.setIncomingData(
node.getAttributeValue("from"),
node.getAttributeValue("t")
)
return entity
| 1,304 | Python | .py | 32 | 33.1875 | 101 | 0.648177 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,697 | ack.py | tgalal_yowsup/yowsup/layers/protocol_acks/protocolentities/ack.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class AckProtocolEntity(ProtocolEntity):
'''
<ack class="{{receipt | message | ?}}" id="{{message_id}}">
</ack>
'''
def __init__(self, _id, _class):
super(AckProtocolEntity, self).__init__("ack")
self._id = _id
self._class = _class
def getId(self):
return self._id
def getClass(self):
return self._class
def toProtocolTreeNode(self):
attribs = {
"id" : self._id,
"class" : self._class,
}
return self._createProtocolTreeNode(attribs, None, data = None)
def __str__(self):
out = "ACK:\n"
out += "ID: %s\n" % self._id
out += "Class: %s\n" % self._class
return out
@staticmethod
def fromProtocolTreeNode(node):
return AckProtocolEntity(
node.getAttributeValue("id"),
node.getAttributeValue("class")
)
| 995 | Python | .py | 31 | 24 | 71 | 0.552521 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,698 | test_ack_outgoing.py | tgalal_yowsup/yowsup/layers/protocol_acks/protocolentities/test_ack_outgoing.py | from yowsup.layers.protocol_acks.protocolentities.ack_outgoing import OutgoingAckProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
entity = OutgoingAckProtocolEntity("12345", "receipt", "delivery", "to_jid")
class OutgoingAckProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = OutgoingAckProtocolEntity
self.node = entity.toProtocolTreeNode()
| 453 | Python | .py | 8 | 52.875 | 95 | 0.826185 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,699 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_acks/protocolentities/__init__.py | from .ack import AckProtocolEntity
from .ack_incoming import IncomingAckProtocolEntity
from .ack_outgoing import OutgoingAckProtocolEntity | 138 | Python | .py | 3 | 45.333333 | 51 | 0.897059 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |