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,700 | test_ack_incoming.py | tgalal_yowsup/yowsup/layers/protocol_acks/protocolentities/test_ack_incoming.py | from yowsup.layers.protocol_acks.protocolentities.ack_incoming import IncomingAckProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
import time
entity = IncomingAckProtocolEntity("12345", "message", "sender@s.whatsapp.com", int(time.time()))
class IncomingAckProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = IncomingAckProtocolEntity
self.node = entity.toProtocolTreeNode()
| 486 | Python | .py | 9 | 50.555556 | 97 | 0.825263 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,701 | layer.py | tgalal_yowsup/yowsup/layers/protocol_ib/layer.py | from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer
from .protocolentities import *
import logging
logger = logging.getLogger(__name__)
class YowIbProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"ib": (self.recvIb, self.sendIb),
"iq": (None, self.sendIb)
}
super(YowIbProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Ib Layer"
def sendIb(self, entity):
if entity.__class__ == CleanIqProtocolEntity:
self.toLower(entity.toProtocolTreeNode())
def recvIb(self, node):
if node.getChild("dirty"):
self.toUpper(DirtyIbProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("offline"):
self.toUpper(OfflineIbProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("account"):
self.toUpper(AccountIbProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("edge_routing"):
logger.debug("ignoring edge_routing ib node for now")
elif node.getChild("attestation"):
logger.debug("ignoring attestation ib node for now")
elif node.getChild("fbip"):
logger.debug("ignoring fbip ib node for now")
else:
logger.warning("Unsupported ib node: %s" % node)
| 1,346 | Python | .py | 31 | 34.741935 | 76 | 0.655462 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,702 | dirty_ib.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/dirty_ib.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ib import IbProtocolEntity
class DirtyIbProtocolEntity(IbProtocolEntity):
'''
<ib>
<dirty type="{{groups | ?}}" timestamp="{{ts}}"></dirty>
</ib>
'''
def __init__(self, timestamp, _type):
super(DirtyIbProtocolEntity, self).__init__()
self.setProps(timestamp, _type)
def setProps(self, timestamp, _type):
self.timestamp = int(timestamp)
self._type = _type
def toProtocolTreeNode(self):
node = super(DirtyIbProtocolEntity, self).toProtocolTreeNode()
dirtyNode = ProtocolTreeNode("dirty")
dirtyNode["timestamp"] = str(self.timestamp)
dirtyNode["type"] = self._type
node.addChild(dirtyNode)
return node
def __str__(self):
out = super(DirtyIbProtocolEntity, self).__str__()
out += "Type: %s\n" % self._type
out += "Timestamp: %s\n" % self.timestamp
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = IbProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = DirtyIbProtocolEntity
dirtyChild = node.getChild("dirty")
entity.setProps(dirtyChild["timestamp"], dirtyChild["type"])
return entity
| 1,281 | Python | .py | 33 | 31.484848 | 70 | 0.646489 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,703 | test_clean_iq.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/test_clean_iq.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_ib.protocolentities.clean_iq import CleanIqProtocolEntity
from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
class CleanIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(CleanIqProtocolEntityTest, self).setUp()
self.ProtocolEntity = CleanIqProtocolEntity
cleanNode = ProtocolTreeNode("clean", {"type": "groups"})
self.node.addChild(cleanNode) | 501 | Python | .py | 9 | 50.666667 | 85 | 0.800813 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,704 | account_ib.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/account_ib.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ib import IbProtocolEntity
class AccountIbProtocolEntity(IbProtocolEntity):
'''
<ib from="s.whatsapp.net">
<account status="active | ?" kind="paid" creation="timestamp" expiration="timestamp"></account>
</ib>
'''
STATUS_ACTIVE = "active"
KIND_PAD = "paid"
def __init__(self, status, kind, creation, expiration):
super(AccountIbProtocolEntity, self).__init__()
self.setProps(status, kind, creation, expiration)
def setProps(self, status, kind, creation, expiration):
self.status = status
self.creation = int(creation)
self.kind = kind
self.expiration= int(expiration)
def toProtocolTreeNode(self):
node = super(AccountIbProtocolEntity, self).toProtocolTreeNode()
accountChild = ProtocolTreeNode("account",
{
"status": self.status,
"kind": self.kind,
"creation": int(self.creation),
"expiration": int(self.expiration)
})
node.addChild(accountChild)
return node
def __str__(self):
out = super(AccountIbProtocolEntity, self).__str__()
out += "Status: %s\n" % self.status
out += "Kind: %s\n" % self.kind
out += "Creation: %s\n" % self.creation
out += "Expiration: %s\n" % self.expiration
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = IbProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = AccountIbProtocolEntity
accountNode = node.getChild("account")
entity.setProps(
accountNode["status"],
accountNode["kind"],
accountNode["creation"],
accountNode["expiration"]
) | 1,996 | Python | .py | 47 | 30.06383 | 103 | 0.561566 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,705 | clean_iq.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/clean_iq.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
class CleanIqProtocolEntity(IqProtocolEntity):
'''
<iq id="" type="set" to="self.domain" xmlns="urn:xmpp:whatsapp:dirty">
<clean type="{{dirty_type}}"></clean>
</iq>
'''
def __init__(self, cleanType, to, _id = None):
super(CleanIqProtocolEntity, self).__init__(
"urn:xmpp:whatsapp:dirty",
_id = _id,
_type = "set",
to = to
)
self.setProps(cleanType)
def setProps(self, cleanType):
self.cleanType = cleanType
def __str__(self):
out = super(CleanIqProtocolEntity, self).__str__()
out += "Clean Type: %s\n" % self.cleanType
return out
def toProtocolTreeNode(self):
node = super(CleanIqProtocolEntity, self).toProtocolTreeNode()
cleanNode = ProtocolTreeNode("clean", {"type": self.cleanType})
node.addChild(cleanNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = CleanIqProtocolEntity
entity.setProps(node.getChild("clean").getAttributeValue("type"))
return entity | 1,297 | Python | .py | 33 | 31.666667 | 74 | 0.645519 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,706 | offline_ib.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/offline_ib.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ib import IbProtocolEntity
class OfflineIbProtocolEntity(IbProtocolEntity):
'''
<ib from="s.whatsapp.net">
<offline count="{{X}}"></offline>
</ib>
'''
def __init__(self, count):
super(IbProtocolEntity, self).__init__()
self.setProps(count)
def setProps(self, count):
self.count = int(count)
def toProtocolTreeNode(self):
node = super(OfflineIbProtocolEntity, self).toProtocolTreeNode()
offlineChild = ProtocolTreeNode("offline", {"count": str(self.count)})
node.addChild(offlineChild)
return node
def __str__(self):
out = super(OfflineIbProtocolEntity, self).__str__()
out += "Offline count: %s\n" % self.count
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = IbProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = OfflineIbProtocolEntity
entity.setProps(node.getChild("offline")["count"])
return entity
| 1,064 | Python | .py | 28 | 30.964286 | 78 | 0.663096 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,707 | test_dirty_ib.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/test_dirty_ib.py | from yowsup.layers.protocol_ib.protocolentities.test_ib import IbProtocolEntityTest
from yowsup.layers.protocol_ib.protocolentities.dirty_ib import DirtyIbProtocolEntity
from yowsup.structs import ProtocolTreeNode
class DirtyIbProtocolEntityTest(IbProtocolEntityTest):
def setUp(self):
super(DirtyIbProtocolEntityTest, self).setUp()
self.ProtocolEntity = DirtyIbProtocolEntity
dirtyNode = ProtocolTreeNode("dirty")
dirtyNode["timestamp"] = "123456"
dirtyNode["type"] = "groups"
self.node.addChild(dirtyNode) | 559 | Python | .py | 11 | 45.181818 | 85 | 0.777778 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,708 | test_offline_iq.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/test_offline_iq.py | from yowsup.layers.protocol_ib.protocolentities.test_ib import IbProtocolEntityTest
from yowsup.layers.protocol_ib.protocolentities.offline_ib import OfflineIbProtocolEntity
from yowsup.structs import ProtocolTreeNode
class OfflineIbProtocolEntityTest(IbProtocolEntityTest):
def setUp(self):
super(OfflineIbProtocolEntityTest, self).setUp()
self.ProtocolEntity = OfflineIbProtocolEntity
self.node.addChild(ProtocolTreeNode("offline", {"count": "5"})) | 478 | Python | .py | 8 | 55.375 | 89 | 0.815287 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,709 | test_ib.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/test_ib.py | from yowsup.layers.protocol_ib.protocolentities.ib import IbProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class IbProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = IbProtocolEntity
self.node = ProtocolTreeNode("ib")
| 375 | Python | .py | 8 | 43.25 | 74 | 0.833333 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,710 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/__init__.py | from .clean_iq import CleanIqProtocolEntity
from .dirty_ib import DirtyIbProtocolEntity
from .offline_ib import OfflineIbProtocolEntity
from .account_ib import AccountIbProtocolEntity | 183 | Python | .py | 4 | 45 | 47 | 0.888889 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,711 | ib.py | tgalal_yowsup/yowsup/layers/protocol_ib/protocolentities/ib.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class IbProtocolEntity(ProtocolEntity):
'''
<ib></ib>
'''
def __init__(self):
super(IbProtocolEntity, self).__init__("ib")
def toProtocolTreeNode(self):
return self._createProtocolTreeNode({}, None, None)
def __str__(self):
out = "Ib:\n"
return out
@staticmethod
def fromProtocolTreeNode(node):
return IbProtocolEntity()
| 461 | Python | .py | 15 | 24.466667 | 59 | 0.649203 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,712 | layer.py | tgalal_yowsup/yowsup/layers/logger/layer.py | from yowsup.layers import YowLayer
import logging
logger = logging.getLogger(__name__)
class YowLoggerLayer(YowLayer):
def send(self, data):
ldata = list(data) if type(data) is bytearray else data
logger.debug("tx:\n%s" % ldata)
self.toLower(data)
def receive(self, data):
ldata = list(data) if type(data) is bytearray else data
logger.debug("rx:\n%s" % ldata)
self.toUpper(data)
def __str__(self):
return "Logger Layer" | 491 | Python | .py | 14 | 29.071429 | 63 | 0.652632 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,713 | layer.py | tgalal_yowsup/yowsup/layers/protocol_receipts/layer.py | from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer
from .protocolentities import *
class YowReceiptProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"receipt": (self.recvReceiptNode, self.sendReceiptEntity)
}
super(YowReceiptProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Receipt Layer"
def sendReceiptEntity(self, entity):
self.entityToLower(entity)
def recvReceiptNode(self, node):
self.toUpper(IncomingReceiptProtocolEntity.fromProtocolTreeNode(node))
| 591 | Python | .py | 14 | 35.428571 | 78 | 0.72028 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,714 | receipt_outgoing.py | tgalal_yowsup/yowsup/layers/protocol_receipts/protocolentities/receipt_outgoing.py | import time
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .receipt import ReceiptProtocolEntity
class OutgoingReceiptProtocolEntity(ReceiptProtocolEntity):
'''
delivered:
If we send the following without "to" specified, whatsapp will consider the message delivered,
but will not notify the sender.
<receipt to="xxxxxxxxxxx@s.whatsapp.net" id="1415389947-15"></receipt>
read
<receipt to="xxxxxxxxxxx@s.whatsapp.net" id="1415389947-15" type="read"></receipt>
multiple items:
<receipt type="read" to="xxxxxxxxxxxx@s.whatsapp.net" id="1431364583-191">
<list>
<item id="1431364572-189"></item>
<item id="1431364575-190"></item>
</list>
</receipt>
'''
def __init__(self, messageIds, to, read = False, participant = None, callId = None):
if type(messageIds) in (list, tuple):
if len(messageIds) > 1:
receiptId = self._generateId()
else:
receiptId = messageIds[0]
else:
receiptId = messageIds
messageIds = [messageIds]
super(OutgoingReceiptProtocolEntity, self).__init__(receiptId)
self.setOutgoingData(messageIds, to, read, participant, callId)
def setOutgoingData(self, messageIds, to, read, participant, callId):
self.messageIds = messageIds
self.to = to
self.read = read
self.participant = participant
self.callId = callId
def getMessageIds(self):
return self.messageIds
def toProtocolTreeNode(self):
node = super(OutgoingReceiptProtocolEntity, self).toProtocolTreeNode()
if self.read:
node.setAttribute("type", "read")
if self.participant:
node.setAttribute("participant", self.participant)
if self.callId:
offer = ProtocolTreeNode("offer", {"call-id": self.callId})
node.addChild(offer)
node.setAttribute("to", self.to)
if len(self.messageIds) > 1:
listNode = ProtocolTreeNode("list")
listNode.addChildren([ProtocolTreeNode("item", {"id": mId}) for mId in self.messageIds])
node.addChild(listNode)
return node
def __str__(self):
out = super(OutgoingReceiptProtocolEntity, self).__str__()
out += "To: \n%s" % self.to
if self.read:
out += "Type: \n%s" % "read"
out += "For: \n%s" % self.messageIds
return out
@staticmethod
def fromProtocolTreeNode(node):
listNode = node.getChild("list")
messageIds = []
if listNode:
messageIds = [child["id"] for child in listNode.getChildren()]
else:
messageIds = [node["id"]]
return OutgoingReceiptProtocolEntity(
messageIds,
node["to"],
node["type"] == "read",
node["participant"]
)
| 2,940 | Python | .py | 74 | 30.567568 | 100 | 0.615439 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,715 | test_receipt_outgoing.py | tgalal_yowsup/yowsup/layers/protocol_receipts/protocolentities/test_receipt_outgoing.py | from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class OutgoingReceiptProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = OutgoingReceiptProtocolEntity
self.node = OutgoingReceiptProtocolEntity("123", "target", "read").toProtocolTreeNode() | 425 | Python | .py | 7 | 56.857143 | 95 | 0.839713 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,716 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_receipts/protocolentities/__init__.py | from .receipt import ReceiptProtocolEntity
from .receipt_incoming import IncomingReceiptProtocolEntity
from .receipt_outgoing import OutgoingReceiptProtocolEntity | 162 | Python | .py | 3 | 53.333333 | 59 | 0.9125 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,717 | test_receipt_incoming.py | tgalal_yowsup/yowsup/layers/protocol_receipts/protocolentities/test_receipt_incoming.py | from yowsup.layers.protocol_receipts.protocolentities import IncomingReceiptProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
import time
class IncomingReceiptProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = IncomingReceiptProtocolEntity
self.node = IncomingReceiptProtocolEntity("123", "sender", int(time.time())).toProtocolTreeNode()
| 448 | Python | .py | 8 | 52.375 | 105 | 0.838269 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,718 | receipt_incoming.py | tgalal_yowsup/yowsup/layers/protocol_receipts/protocolentities/receipt_incoming.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .receipt import ReceiptProtocolEntity
from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity
class IncomingReceiptProtocolEntity(ReceiptProtocolEntity):
'''
delivered:
<receipt to="xxxxxxxxxxx@s.whatsapp.net" id="1415389947-15"></receipt>
read
<receipt to="xxxxxxxxxxx@s.whatsapp.net" id="1415389947-15" type="read"></receipt>
delivered to participant in group:
<receipt participant="xxxxxxxxxx@s.whatsapp.net" from="yyyyyyyyyyyyy@g.us" id="1431204051-9" t="1431204094"></receipt>
read by participant in group:
<receipt participant="xxxxxxxxxx@s.whatsapp.net" t="1431204235" from="yyyyyyyyyyyyy@g.us" id="1431204051-9" type="read"></receipt>
multiple items:
<receipt type="read" from="xxxxxxxxxxxx@s.whatsapp.net" id="1431364583-191" t="1431365553">
<list>
<item id="1431364572-189"></item>
<item id="1431364575-190"></item>
</list>
</receipt>
multiple items to group:
<receipt participant="xxxxxxxxxxxx@s.whatsapp.net" t="1431330533" from="yyyyyyyyyyyyyy@g.us" id="1431330385-323" type="read">
<list>
<item id="1431330096-317"></item>
<item id="1431330373-320"></item>
<item id="1431330373-321"></item>
<item id="1431330385-322"></item>
</list>
</receipt>
INCOMING
<receipt offline="0" from="xxxxxxxxxx@s.whatsapp.net" id="1415577964-1" t="1415578027"></receipt>
'''
def __init__(self, _id, _from, timestamp, offline = None, type = None, participant = None, items = None):
super(IncomingReceiptProtocolEntity, self).__init__(_id)
self.setIncomingData(_from, timestamp, offline, type, participant, items)
def getType(self):
return self.type
def getParticipant(self, full=True):
if self.participant:
return self.participant if full else self.participant.split('@')[0]
def getFrom(self, full = True):
return self._from if full else self._from.split('@')[0]
def setIncomingData(self, _from, timestamp, offline, type = None, participant = None, items = None):
self._from = _from
self.timestamp = timestamp
self.type = type
self.participant = participant
if offline is not None:
self.offline = True if offline == "1" else False
else:
self.offline = None
self.items = items
def toProtocolTreeNode(self):
node = super(IncomingReceiptProtocolEntity, self).toProtocolTreeNode()
node.setAttribute("from", self._from)
node.setAttribute("t", str(self.timestamp))
if self.offline is not None:
node.setAttribute("offline", "1" if self.offline else "0")
if self.type is not None:
node.setAttribute("type", self.type)
if self.participant is not None:
node.setAttribute("participant", self.participant)
if self.items is not None:
inodes = []
for item in self.items:
inode = ProtocolTreeNode("item", {"id": item})
inodes.append(inode)
lnode = ProtocolTreeNode("list")
lnode.addChildren(inodes)
node.addChild(lnode)
return node
def __str__(self):
out = super(IncomingReceiptProtocolEntity, self).__str__()
out += "From: %s\n" % self._from
out += "Timestamp: %s\n" % self.timestamp
if self.offline is not None:
out += "Offline: %s\n" % ("1" if self.offline else "0")
if self.type is not None:
out += "Type: %s\n" % (self.type)
if self.participant is not None:
out += "Participant: %s\n" % (self.participant)
if self.items is not None:
out += "Items: %s\n" % " ".join(self.items)
return out
def ack(self):
return OutgoingAckProtocolEntity(self.getId(), "receipt", self.getType(), self.getFrom(), participant = self.participant)
@staticmethod
def fromProtocolTreeNode(node):
items = None
listNode = node.getChild("list")
if listNode is not None:
items = []
for inode in listNode.getAllChildren("item"):
items.append(inode["id"])
return IncomingReceiptProtocolEntity(
node.getAttributeValue("id"),
node.getAttributeValue("from"),
node.getAttributeValue("t"),
node.getAttributeValue("offline"),
node.getAttributeValue("type"),
node.getAttributeValue("participant"),
items
)
| 4,690 | Python | .py | 103 | 36.320388 | 134 | 0.62697 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,719 | receipt.py | tgalal_yowsup/yowsup/layers/protocol_receipts/protocolentities/receipt.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class ReceiptProtocolEntity(ProtocolEntity):
'''
delivered:
<receipt to="xxxxxxxxxxx@s.whatsapp.net" id="1415389947-15"></receipt>
read
<receipt to="xxxxxxxxxxx@s.whatsapp.net" id="1415389947-15" type="read || played"></receipt>
INCOMING
<receipt offline="0" from="4915225256022@s.whatsapp.net" id="1415577964-1" t="1415578027" type="played?"></receipt>
'''
def __init__(self, _id):
super(ReceiptProtocolEntity, self).__init__("receipt")
self._id = _id
def getId(self):
return self._id
def toProtocolTreeNode(self):
attribs = {
"id" : self._id
}
return self._createProtocolTreeNode(attribs, None, data = None)
def __str__(self):
out = "Receipt:\n"
out += "ID: %s\n" % self._id
return out
@staticmethod
def fromProtocolTreeNode(node):
return ReceiptProtocolEntity(
node.getAttributeValue("id")
)
| 1,051 | Python | .py | 29 | 28.862069 | 119 | 0.622398 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,720 | layer.py | tgalal_yowsup/yowsup/layers/protocol_privacy/layer.py | from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer
from .protocolentities import *
class YowPrivacyProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowPrivacyProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Privacy Layer"
def sendIq(self, entity):
if entity.getXmlns() == "jabber:iq:privacy":
self.entityToLower(entity)
def recvIq(self, node):
pass
| 535 | Python | .py | 15 | 28.6 | 67 | 0.653772 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,721 | privacylist_iq.py | tgalal_yowsup/yowsup/layers/protocol_privacy/protocolentities/privacylist_iq.py | from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class PrivacyListIqProtocolEntity(IqProtocolEntity):
def __init__(self, name = "default"):
super(PrivacyListIqProtocolEntity, self).__init__("jabber:iq:privacy", _type="get")
self.setListName(name)
def setListName(self, name):
self.listName = name
def toProtocolTreeNode(self):
node = super(PrivacyListIqProtocolEntity, self).toProtocolTreeNode()
queryNode = ProtocolTreeNode("query")
listNode = ProtocolTreeNode("list", {"name": self.listName})
queryNode.addChild(listNode)
node.addChild(queryNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = PrivacyListIqProtocolEntity
entity.setListName(node.getChild("query").getChild("list")["name"])
return entity
| 983 | Python | .py | 21 | 39.761905 | 91 | 0.719499 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,722 | layer.py | tgalal_yowsup/yowsup/layers/protocol_groups/layer.py | from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer
from yowsup.layers.protocol_iq.protocolentities import ErrorIqProtocolEntity
from yowsup.layers.protocol_iq.protocolentities.iq_result import ResultIqProtocolEntity
from .protocolentities import *
import logging
logger = logging.getLogger(__name__)
class YowGroupsProtocolLayer(YowProtocolLayer):
HANDLE = (
CreateGroupsIqProtocolEntity,
InfoGroupsIqProtocolEntity,
LeaveGroupsIqProtocolEntity,
ListGroupsIqProtocolEntity,
SubjectGroupsIqProtocolEntity,
ParticipantsGroupsIqProtocolEntity,
AddParticipantsIqProtocolEntity,
PromoteParticipantsIqProtocolEntity,
DemoteParticipantsIqProtocolEntity,
RemoveParticipantsIqProtocolEntity
)
def __init__(self):
handleMap = {
"iq": (None, self.sendIq),
"notification": (self.recvNotification, None)
}
super(YowGroupsProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Groups Iq Layer"
def sendIq(self, entity):
if entity.__class__ in self.__class__.HANDLE:
if entity.__class__ == SubjectGroupsIqProtocolEntity:
self._sendIq(entity, self.onSetSubjectSuccess, self.onSetSubjectFailed)
elif entity.__class__ == CreateGroupsIqProtocolEntity:
self._sendIq(entity, self.onCreateGroupSuccess, self.onCreateGroupFailed)
elif entity.__class__ == ParticipantsGroupsIqProtocolEntity:
self._sendIq(entity, self.onGetParticipantsResult)
elif entity.__class__ == AddParticipantsIqProtocolEntity:
self._sendIq(entity, self.onAddParticipantsSuccess, self.onAddParticipantsFailed)
elif entity.__class__ == PromoteParticipantsIqProtocolEntity:
self._sendIq(entity, self.onPromoteParticipantsSuccess, self.onPromoteParticipantsFailed)
elif entity.__class__ == DemoteParticipantsIqProtocolEntity:
self._sendIq(entity, self.onDemoteParticipantsSuccess, self.onDemoteParticipantsFailed)
elif entity.__class__ == RemoveParticipantsIqProtocolEntity:
self._sendIq(entity, self.onRemoveParticipantsSuccess, self.onRemoveParticipantsFailed)
elif entity.__class__ == ListGroupsIqProtocolEntity:
self._sendIq(entity, self.onListGroupsResult)
elif entity.__class__ == LeaveGroupsIqProtocolEntity:
self._sendIq(entity, self.onLeaveGroupSuccess, self.onLeaveGroupFailed)
elif entity.__class__ == InfoGroupsIqProtocolEntity:
self._sendIq(entity, self.onInfoGroupSuccess, self.onInfoGroupFailed)
else:
self.entityToLower(entity)
def onCreateGroupSuccess(self, node, originalIqEntity):
logger.info("Group create success")
self.toUpper(SuccessCreateGroupsIqProtocolEntity.fromProtocolTreeNode(node))
def onCreateGroupFailed(self, node, originalIqEntity):
logger.error("Group create failed")
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
def onSetSubjectSuccess(self, node, originalIqEntity):
logger.info("Group subject change success")
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(node))
def onSetSubjectFailed(self, node, originalIqEntity):
logger.error("Group subject change failed")
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
def onGetParticipantsResult(self, node, originalIqEntity):
self.toUpper(ListParticipantsResultIqProtocolEntity.fromProtocolTreeNode(node))
def onAddParticipantsSuccess(self, node, originalIqEntity):
logger.info("Group add participants success")
self.toUpper(SuccessAddParticipantsIqProtocolEntity.fromProtocolTreeNode(node))
def onRemoveParticipantsFailed(self, node, originalIqEntity):
logger.error("Group remove participants failed")
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
def onRemoveParticipantsSuccess(self, node, originalIqEntity):
logger.info("Group remove participants success")
self.toUpper(SuccessRemoveParticipantsIqProtocolEntity.fromProtocolTreeNode(node))
def onPromoteParticipantsFailed(self, node, originalIqEntity):
logger.error("Group promote participants failed")
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
def onPromoteParticipantsSuccess(self, node, originalIqEntity):
logger.info("Group promote participants success")
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(node))
def onDemoteParticipantsFailed(self, node, originalIqEntity):
logger.error("Group demote participants failed")
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
def onDemoteParticipantsSuccess(self, node, originalIqEntity):
logger.info("Group demote participants success")
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(node))
def onAddParticipantsFailed(self, node, originalIqEntity):
logger.error("Group add participants failed")
self.toUpper(FailureAddParticipantsIqProtocolEntity.fromProtocolTreeNode(node))
def onListGroupsResult(self, node, originalIqEntity):
self.toUpper(ListGroupsResultIqProtocolEntity.fromProtocolTreeNode(node))
def onLeaveGroupSuccess(self, node, originalIqEntity):
logger.info("Group leave success")
self.toUpper(SuccessLeaveGroupsIqProtocolEntity.fromProtocolTreeNode(node))
def onLeaveGroupFailed(self, node, originalIqEntity):
logger.error("Group leave failed")
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
def onInfoGroupSuccess(self, node, originalIqEntity):
logger.info("Group info success")
self.toUpper(InfoGroupsResultIqProtocolEntity.fromProtocolTreeNode(node))
def onInfoGroupFailed(self, node, originalIqEntity):
logger.error("Group info failed")
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
def recvNotification(self, node):
if node["type"] == "w:gp2":
if node.getChild("subject"):
self.toUpper(SubjectGroupsNotificationProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("create"):
self.toUpper(CreateGroupsNotificationProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("remove"):
self.toUpper(RemoveGroupsNotificationProtocolEntity.fromProtocolTreeNode(node))
elif node.getChild("add"):
self.toUpper(AddGroupsNotificationProtocolEntity.fromProtocolTreeNode(node))
| 6,769 | Python | .py | 113 | 50.362832 | 105 | 0.739406 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,723 | group.py | tgalal_yowsup/yowsup/layers/protocol_groups/structs/group.py | class Group(object):
def __init__(self, groupId, creatorJid, subject, subjectOwnerJid, subjectTime, creationTime, participants=None):
self._groupId = groupId
self._creatorJid = creatorJid
self._subject = subject
self._subjectOwnerJid = subjectOwnerJid
self._subjectTime = int(subjectTime)
self._creationTime = int(creationTime)
self._participants = participants or {}
def getId(self):
return self._groupId
def getCreator(self):
return self._creatorJid
def getOwner(self):
return self.getCreator()
def getSubject(self):
return self._subject
def getSubjectOwner(self):
return self._subjectOwnerJid
def getSubjectTime(self):
return self._subjectTime
def getCreationTime(self):
return self._creationTime
def __str__(self):
return "ID: %s, Subject: %s, Creation: %s, Creator: %s, Subject Owner: %s, Subject Time: %s\nParticipants: %s" %\
(self.getId(), self.getSubject(), self.getCreationTime(), self.getCreator(), self.getSubjectOwner(), self.getSubjectTime(), ", ".join(self._participants.keys()))
def getParticipants(self):
return self._participants
| 1,287 | Python | .py | 28 | 38.071429 | 178 | 0.6408 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,724 | iq_groups_subject.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_subject.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups import GroupsIqProtocolEntity
class SubjectGroupsIqProtocolEntity(GroupsIqProtocolEntity):
'''
<iq type="set" id="{{id}}" xmlns="w:g2", to={{group_jid}}">
<subject>
{{NEW_VAL}}
</subject>
</iq>
'''
def __init__(self, jid, subject, _id = None):
super(SubjectGroupsIqProtocolEntity, self).__init__(to = jid, _id = _id, _type = "set")
self.setProps(subject)
def setProps(self, subject):
self.subject = subject
def toProtocolTreeNode(self):
node = super(SubjectGroupsIqProtocolEntity, self).toProtocolTreeNode()
node.addChild(ProtocolTreeNode("subject",{}, None, self.subject))
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(SubjectGroupsIqProtocolEntity, SubjectGroupsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = SubjectGroupsIqProtocolEntity
entity.setProps(node.getChild("subject").getData())
return entity
| 1,076 | Python | .py | 25 | 36.08 | 111 | 0.682252 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,725 | notification_groups.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/notification_groups.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from yowsup.layers.protocol_notifications.protocolentities import NotificationProtocolEntity
class GroupsNotificationProtocolEntity(NotificationProtocolEntity):
'''
<notification notify="WhatsApp" id="{{id}}" t="1420402514" participant="{{participant_jiid}}" from="{{group_jid}}" type="w:gp2">
</notification>
'''
def __init__(self, _id, _from, timestamp, notify, participant, offline):
super(GroupsNotificationProtocolEntity, self).__init__("w:gp2", _id, _from, timestamp, notify, offline)
self.setParticipant(participant)
self.setGroupId(_from)
def setParticipant(self, participant):
self._participant = participant
def getParticipant(self, full = True):
return self._participant if full else self._participant.split('@')[0]
def getGroupId(self):
return self.groupId
def setGroupId(self, groupId):
self.groupId = groupId
def __str__(self):
out = super(GroupsNotificationProtocolEntity, self).__str__()
out += "Participant: %s\n" % self.getParticipant()
return out
def toProtocolTreeNode(self):
node = super(GroupsNotificationProtocolEntity, self).toProtocolTreeNode()
node.setAttribute("participant", self.getParticipant())
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(GroupsNotificationProtocolEntity, GroupsNotificationProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = GroupsNotificationProtocolEntity
entity.setParticipant(node.getAttributeValue("participant"))
entity.setGroupId(node.getAttributeValue("from"))
return entity
| 1,740 | Python | .py | 34 | 44.058824 | 132 | 0.719008 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,726 | iq_groups_info.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_info.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups import GroupsIqProtocolEntity
class InfoGroupsIqProtocolEntity(GroupsIqProtocolEntity):
'''
<iq id="{{id}}"" type="get" to="{{group_jid}}" xmlns="w:g2">
<query request="interactive"></query>
</iq>
'''
def __init__(self, group_jid, _id=None):
super(InfoGroupsIqProtocolEntity, self).__init__(to = group_jid, _id = _id, _type = "get")
self.setProps(group_jid)
def setProps(self, group_jid):
self.group_jid = group_jid
def __str__(self):
out = super(InfoGroupsIqProtocolEntity, self).__str__()
out += "Group JID: %s\n" % self.group_jid
return out
def toProtocolTreeNode(self):
node = super(InfoGroupsIqProtocolEntity, self).toProtocolTreeNode()
node.addChild(ProtocolTreeNode("query", {"request": "interactive"}))
return node
@staticmethod
def fromProtocolTreeNode(node):
assert node.getChild("query") is not None, "Not a groups info iq node %s" % node
entity = super(InfoGroupsIqProtocolEntity, InfoGroupsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = InfoGroupsIqProtocolEntity
entity.setProps(node.getAttributeValue("to"))
return entity
| 1,297 | Python | .py | 28 | 39.357143 | 105 | 0.675119 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,727 | notification_groups_add.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/notification_groups_add.py | from .notification_groups import GroupsNotificationProtocolEntity
from yowsup.structs import ProtocolTreeNode
class AddGroupsNotificationProtocolEntity(GroupsNotificationProtocolEntity):
'''
<notification participant="{{participant_jiid}}" t="{{TIMESTAMP}}" from="{{group_jid}}" type="w:gp2" id="{{id}}" notify="WhatsApp">
<add>
<participant jid="{{JID_1}}">
</participant>
</add>
</notification>
'''
def __init__(self, _id, _from, timestamp, notify, participant, offline, participants):
super(AddGroupsNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, participant, offline)
self.setParticipants(participants)
def setParticipants(self, participants):
assert type(participants) is list, "Must be a list of jids, got %s instead." % type(participants)
self.participants = participants
def getParticipants(self):
return self.participants
def __str__(self):
out = super(AddGroupsNotificationProtocolEntity, self).__str__()
out += "Participants: %s\n" % " ".join(self.getParticipants())
return out
def toProtocolTreeNode(self):
node = super(AddGroupsNotificationProtocolEntity, self).toProtocolTreeNode()
addNode = ProtocolTreeNode("add")
participants = []
for jid in self.getParticipants():
pnode = ProtocolTreeNode("participant", {"jid": jid})
participants.append(pnode)
addNode.addChildren(participants)
node.addChild(addNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
addNode = node.getChild("add")
participants = []
for p in addNode.getAllChildren("participant"):
participants.append(p["jid"])
return AddGroupsNotificationProtocolEntity(
node["id"], node["from"], node["t"], node["notify"], node["participant"], node["offline"],
participants
) | 1,946 | Python | .py | 43 | 38.139535 | 131 | 0.679325 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,728 | iq_groups_participants_remove_success.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_participants_remove_success.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
class SuccessRemoveParticipantsIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" from="{{group_jid}}" id="{{id}}">
<remove type="success" participant="{{jid}}"></remove>
<remove type="success" participant="{{jid}}"></remove>
</iq>
'''
def __init__(self, _id, groupId, participantList):
super(SuccessRemoveParticipantsIqProtocolEntity, self).__init__(_from = groupId, _id = _id)
self.setProps(groupId, participantList)
def setProps(self, groupId, participantList):
self.groupId = groupId
self.participantList = participantList
self.action = 'remove'
def getAction(self):
return self.action
def toProtocolTreeNode(self):
node = super(SuccessRemoveParticipantsIqProtocolEntity, self).toProtocolTreeNode()
participantNodes = [
ProtocolTreeNode("remove", {
"type": "success",
"participant": participant
})
for participant in self.participantList
]
node.addChildren(participantNodes)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(SuccessRemoveParticipantsIqProtocolEntity, SuccessRemoveParticipantsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = SuccessRemoveParticipantsIqProtocolEntity
participantList = []
for participantNode in node.getAllChildren():
if participantNode["type"]=="success":
participantList.append(participantNode["participant"])
entity.setProps(node.getAttributeValue("from"), participantList)
return entity
| 1,821 | Python | .py | 39 | 38.153846 | 135 | 0.676802 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,729 | iq_groups_leave_success.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_leave_success.py | from yowsup.common import YowConstants
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
class SuccessLeaveGroupsIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" from="g.us" id="{{ID}}">
<leave>
<group id="{{GROUP_JID}}"></group>
</leave>
</iq>
'''
def __init__(self, _id, groupId):
super(SuccessLeaveGroupsIqProtocolEntity, self).\
__init__(_from=YowConstants.WHATSAPP_GROUP_SERVER, _id=_id)
self.setProps(groupId)
def setProps(self, groupId):
self.groupId = groupId
def __str__(self):
out = super(SuccessLeaveGroupsIqProtocolEntity, self).__str__()
out += "Group Id: %s\n" % self.groupId
return out
def toProtocolTreeNode(self):
node = super(SuccessLeaveGroupsIqProtocolEntity, self).\
toProtocolTreeNode()
leaveNode = ProtocolTreeNode(
"leave", {}, [ProtocolTreeNode("group", {"id": self.groupId})]
)
node.addChild(leaveNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(SuccessLeaveGroupsIqProtocolEntity, SuccessLeaveGroupsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = SuccessLeaveGroupsIqProtocolEntity
entity.setProps(
node.getChild("leave").getChild("group").getAttributeValue("id")
)
return entity
| 1,491 | Python | .py | 37 | 32.513514 | 121 | 0.664824 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,730 | test_iq_groups_list.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/test_iq_groups_list.py | from yowsup.layers.protocol_groups.protocolentities.iq_groups_list import ListGroupsIqProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
entity = ListGroupsIqProtocolEntity()
class ListGroupsIqProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = ListGroupsIqProtocolEntity
self.node = entity.toProtocolTreeNode()
| 421 | Python | .py | 8 | 48.875 | 100 | 0.846715 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,731 | iq_result_participants_list.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_result_participants_list.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
class ListParticipantsResultIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" from="{{GROUP_ID}}" id="{{IQ_ID}}">
<participant jid="{{PARTICIPANT_JID}}">
</participant>
</iq>
'''
def __init__(self, _from, participantList):
super(ListParticipantsResultIqProtocolEntity, self).__init__(_from = _from)
self.setParticipants(participantList)
def __str__(self):
out = super(ListParticipantsResultIqProtocolEntity, self).__str__()
out += "Participants: %s\n" % " ".join(self.participantList)
return out
def getParticipants(self):
return self.participantList
def setParticipants(self, participants):
self.participantList = participants
def toProtocolTreeNode(self):
node = super(ListParticipantsResultIqProtocolEntity, self).toProtocolTreeNode()
participantNodes = [
ProtocolTreeNode("participant", {
"jid": participant
})
for participant in self.participantList
]
node.addChildren(participantNodes)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(ListParticipantsResultIqProtocolEntity, ListParticipantsResultIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = ListParticipantsResultIqProtocolEntity
entity.setParticipants([ pNode.getAttributeValue("jid") for pNode in node.getAllChildren() ])
return entity
| 1,628 | Python | .py | 36 | 37.333333 | 129 | 0.696338 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,732 | test_iq_groups_create_success.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/test_iq_groups_create_success.py | from yowsup.structs.protocolentity import ProtocolEntityTest
from yowsup.layers.protocol_groups.protocolentities import SuccessCreateGroupsIqProtocolEntity
import unittest
entity = SuccessCreateGroupsIqProtocolEntity("123-456", "431-123")
class SuccessCreateGroupsIqProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = SuccessCreateGroupsIqProtocolEntity
self.node = entity.toProtocolTreeNode()
| 462 | Python | .py | 8 | 54 | 94 | 0.849558 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,733 | notification_groups_create.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/notification_groups_create.py | from .notification_groups import GroupsNotificationProtocolEntity
from yowsup.structs import ProtocolTreeNode
class CreateGroupsNotificationProtocolEntity(GroupsNotificationProtocolEntity):
"""
<notification from="{{owner_username}}-{{group_id}}@g.us" type="w:gp2" id="{{message_id}}" participant="{{participant_jid}}"
t="{{timestamp}}" notify="{{pushname}}">
<create type="new" key="{{owner_username}}-{{key}}@temp">
<group id="{{group_id}}" creator="{{creator_jid}}" creation="{{creation_timestamp}}"
subject="{{group_subject}}" s_t="{{subject_timestamp}}" s_o="{{subject_owner_jid}}">
<participant jid="{{pariticpant_jid}}"/>
<participant jid="{{}}" type="superadmin"/>
</group>
</create>
</notification>
"""
TYPE_CREATE_NEW = "new"
TYPE_PARTICIPANT_ADMIN = "admin"
TYPE_PARTICIPANT_SUPERADMIN = "superadmin"
def __init__(self, _id, _from, timestamp, notify, participant, offline,
createType, key, groupId, creationTimestamp, creatorJid,
subject, subjectTime, subjectOwnerJid,
participants):
super(CreateGroupsNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, participant, offline)
self.setGroupProps(createType, key, groupId, creationTimestamp, creatorJid,
subject, subjectTime, subjectOwnerJid, participants)
def setGroupProps(self, createType, key, groupId, creationTimestamp, creatorJid,
subject, subjectTime, subjectOwnerJid,
participants):
assert type(participants) is dict, "Participants must be a dict {jid => type?}"
self.createType = createType
self.groupId = groupId
self.creationTimestamp = int(creationTimestamp)
self.creatorJid = creatorJid
self.subject = subject
self.subjectTime = int(subjectTime)
self.subjectOwnerJid = subjectOwnerJid
self.participants = participants
self._key = key
@property
def key(self):
return self._key
def getParticipants(self):
return self.participants
def getSubject(self):
return self.subject
def getGroupId(self):
return self.groupId
def getCreationTimestamp(self):
return self.creationTimestamp
def getCreatorJid(self, full = True):
return self.creatorJid if full else self.creatorJid.split('@')[0]
def getSubjectTimestamp(self):
return self.subjectTime
def getSubjectOwnerJid(self, full = True):
return self.subjectOwnerJid if full else self.subjectOwnerJid.split('@')[0]
def getCreatetype(self):
return self.createType
def getGroupSuperAdmin(self, full = True):
for jid, _type in self.participants.items():
if _type == self.__class__.TYPE_PARTICIPANT_SUPERADMIN:
return jid if full else jid.split('@')[0]
def getGroupAdmins(self, full = True):
out = []
for jid, _type in self.participants.items():
if _type == self.__class__.TYPE_PARTICIPANT_ADMIN:
out.append(jid if full else jid.split('@')[0])
return out
def __str__(self):
out = super(CreateGroupsNotificationProtocolEntity, self).__str__()
out += "Creator: %s\n" % self.getCreatorJid()
out += "Create type: %s\n" % self.getCreatetype()
out += "Creation timestamp: %s\n" % self.getCreationTimestamp()
out += "Subject: %s\n" % self.getSubject()
out += "Subject owner: %s\n" % self.getSubjectOwnerJid()
out += "Subject timestamp: %s\n" % self.getSubjectTimestamp()
out += "Participants: %s\n" % self.getParticipants()
out += "Key: %s\n" % self.key
return out
def toProtocolTreeNode(self):
node = super(CreateGroupsNotificationProtocolEntity, self).toProtocolTreeNode()
createNode = ProtocolTreeNode("create", {"type": self.getCreatetype(), "key": self.key})
groupNode = ProtocolTreeNode("group", {
"subject": self.getSubject(),
"creation": str(self.getCreationTimestamp()),
"creator": self.getCreatorJid(),
"s_t": self.getSubjectTimestamp(),
"s_o": self.getSubjectOwnerJid(),
"id": self.getGroupId()
})
participants = []
for jid, _type in self.getParticipants().items():
pnode = ProtocolTreeNode("participant", {"jid": jid})
if _type:
pnode["type"] = _type
participants.append(pnode)
groupNode.addChildren(participants)
createNode.addChild(groupNode)
node.addChild(createNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
createNode = node.getChild("create")
groupNode = createNode.getChild("group")
participants = {}
for p in groupNode.getAllChildren("participant"):
participants[p["jid"]] = p["type"]
return CreateGroupsNotificationProtocolEntity(
node["id"], node["from"], node["t"], node["notify"], node["participant"], node["offline"],
createNode["type"], createNode["key"], groupNode["id"], groupNode["creation"], groupNode["creator"], groupNode["subject"],
groupNode["s_t"], groupNode["s_o"], participants
)
| 5,442 | Python | .py | 111 | 39.135135 | 134 | 0.627591 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,734 | iq_result_groups_list.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_result_groups_list.py | from yowsup.common import YowConstants
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
from ..structs import Group
class ListGroupsResultIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" from="g.us" id="{{IQ_ID}}">
<groups>
<group s_t="{{SUBJECT_TIME}}" creation="{{CREATING_TIME}}" creator="{{OWNER_JID}}" id="{{GROUP_ID}}" s_o="{{SUBJECT_OWNER_JID}}" subject="{{SUBJECT}}">
<participant jid="{{JID}}" type="admin">
</participant>
<participant jid="{{JID}}">
</participant>
</group>
<group s_t="{{SUBJECT_TIME}}" creation="{{CREATING_TIME}}" creator="{{OWNER_JID}}" id="{{GROUP_ID}}" s_o="{{SUBJECT_OWNER_JID}}" subject="{{SUBJECT}}">
<participant jid="{{JID}}" type="admin">
</participant>
</group>
<groups>
</iq>
'''
def __init__(self, groupsList):
super(ListGroupsResultIqProtocolEntity, self).__init__(_from = YowConstants.WHATSAPP_GROUP_SERVER)
self.setProps(groupsList)
def __str__(self):
out = super(ListGroupsResultIqProtocolEntity, self).__str__()
out += "Groups:\n"
for g in self.groupsList:
out += "%s\n" % g
return out
def getGroups(self):
return self.groupsList
def setProps(self, groupsList):
assert type(groupsList) is list and (len(groupsList) == 0 or groupsList[0].__class__ is Group),\
"groupList must be a list of Group instances"
self.groupsList = groupsList
def toProtocolTreeNode(self):
node = super(ListGroupsResultIqProtocolEntity, self).toProtocolTreeNode()
groupsNodes = []
for group in self.groupsList:
groupNode = ProtocolTreeNode("group", {
"id": group.getId(),
"creator": group.getCreator(),
"subject": group.getSubject(),
"s_o": group.getSubjectOwner(),
"s_t": str(group.getSubjectTime()),
"creation": str(group.getCreationTime())
},
)
participants = []
for jid, _type in group.getParticipants().items():
pnode = ProtocolTreeNode("participant", {"jid": jid})
if _type:
pnode["type"] = _type
participants.append(pnode)
groupNode.addChildren(participants)
groupsNodes.append(groupNode)
node.addChild(ProtocolTreeNode("groups", children = groupsNodes))
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(ListGroupsResultIqProtocolEntity, ListGroupsResultIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = ListGroupsResultIqProtocolEntity
groups = []
for groupNode in node.getChild("groups").getAllChildren():
participants = {}
for p in groupNode.getAllChildren("participant"):
participants[p["jid"]] = p["type"]
groups.append(
Group(groupNode["id"], groupNode["creator"], groupNode["subject"], groupNode["s_o"], groupNode["s_t"], groupNode["creation"], participants)
)
entity.setProps(groups)
return entity
| 3,389 | Python | .py | 73 | 35.917808 | 161 | 0.597096 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,735 | iq_groups_list.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_list.py | from yowsup.common import YowConstants
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups import GroupsIqProtocolEntity
class ListGroupsIqProtocolEntity(GroupsIqProtocolEntity):
'''
<iq id="{{id}}"" type="get" to="g.us" xmlns="w:g2">
<"{{participating | owning}}"></"{{participating | owning}}">
</iq>
result (processed in iq_result_groups_list.py):
<iq type="result" from="g.us" id="{{IQ_ID}}">
<groups>
<group s_t="{{SUBJECT_TIME}}" creation="{{CREATING_TIME}}" creator="{{OWNER_JID}}" id="{{GROUP_ID}}" s_o="{{SUBJECT_OWNER_JID}}" subject="{{SUBJECT}}">
<participant jid="{{JID}}" type="admin">
</participant>
<participant jid="{{JID}}">
</participant>
</group>
<group s_t="{{SUBJECT_TIME}}" creation="{{CREATING_TIME}}" creator="{{OWNER_JID}}" id="{{GROUP_ID}}" s_o="{{SUBJECT_OWNER_JID}}" subject="{{SUBJECT}}">
<participant jid="{{JID}}" type="admin">
</participant>
</group>
<groups>
</iq>
'''
GROUP_TYPE_PARTICIPATING = "participating"
GROUP_TYPE_OWNING = "owning"
GROUPS_TYPES = (GROUP_TYPE_PARTICIPATING, GROUP_TYPE_OWNING)
def __init__(self, groupsType = GROUP_TYPE_PARTICIPATING, _id = None):
super(ListGroupsIqProtocolEntity, self).__init__(_id=_id, to = YowConstants.WHATSAPP_GROUP_SERVER, _type = "get")
self.setProps(groupsType)
def setProps(self, groupsType):
assert groupsType in self.__class__.GROUPS_TYPES,\
"Groups type must be %s, not %s" % (" or ".join(self.__class__.GROUPS_TYPES), groupsType)
self.groupsType = groupsType
def toProtocolTreeNode(self):
node = super(ListGroupsIqProtocolEntity, self).toProtocolTreeNode()
node.addChild(ProtocolTreeNode(self.groupsType))
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(ListGroupsIqProtocolEntity, ListGroupsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = ListGroupsIqProtocolEntity
entity.setProps(node.getChild(0).tag)
return entity
| 2,183 | Python | .py | 44 | 41.727273 | 161 | 0.639568 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,736 | iq_groups_participants.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_participants.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups import GroupsIqProtocolEntity
class ParticipantsGroupsIqProtocolEntity(GroupsIqProtocolEntity):
'''
<iq type="get" id="{{id}}" xmlns="w:g2", to={{group_jid}}">
<list></list>
</iq>
'''
modes=["add","promote","remove","demote"]
def __init__(self, jid, participantList, _mode, _id = None):
super(ParticipantsGroupsIqProtocolEntity, self).__init__(to = jid, _id = _id, _type = "set")
self.setProps(group_jid = jid, participantList = participantList, mode = _mode)
def setProps(self, group_jid, participantList, mode):
assert type(participantList) is list, "Must be a list of jids, got %s instead." % type(participantList)
assert mode in self.modes, "Mode should be in: '" + "', '".join(self.modes) + "' but is '" + mode + "'"
self.group_jid = group_jid
self.participantList = participantList
self.mode = mode
def toProtocolTreeNode(self):
node = super(ParticipantsGroupsIqProtocolEntity, self).toProtocolTreeNode()
participantNodes = [
ProtocolTreeNode("participant", {
"jid": participant
})
for participant in self.participantList
]
node.addChild(ProtocolTreeNode(self.mode,{}, participantNodes))
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(ParticipantsGroupsIqProtocolEntity, ParticipantsGroupsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = ParticipantsGroupsIqProtocolEntity
return entity
| 1,641 | Python | .py | 33 | 41.909091 | 121 | 0.668122 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,737 | iq_groups_participants_remove.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_participants_remove.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups_participants import ParticipantsGroupsIqProtocolEntity
class RemoveParticipantsIqProtocolEntity(ParticipantsGroupsIqProtocolEntity):
'''
<iq type="set" id="{{id}}" xmlns="w:g2", to="{{group_jid}}">
<remove>
<participant jid="{{jid}}"></participant>
<participant jid="{{jid}}"></participant>
</remove>
</iq>
'''
def __init__(self, group_jid, participantList, _id = None):
super(RemoveParticipantsIqProtocolEntity, self).__init__(group_jid, participantList, "remove", _id = _id)
@staticmethod
def fromProtocolTreeNode(node):
entity = super(RemoveParticipantsIqProtocolEntity, RemoveParticipantsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = RemoveParticipantsIqProtocolEntity
participantList = []
for participantNode in node.getChild("remove").getAllChildren():
participantList.append(participantNode["jid"])
entity.setProps(node.getAttributeValue("to"), participantList)
return entity
| 1,128 | Python | .py | 22 | 43.409091 | 121 | 0.703941 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,738 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/__init__.py | from .iq_groups_create import CreateGroupsIqProtocolEntity
from .iq_groups_create_success import SuccessCreateGroupsIqProtocolEntity
from .iq_groups_leave import LeaveGroupsIqProtocolEntity
from .iq_groups_leave_success import SuccessLeaveGroupsIqProtocolEntity
from .iq_groups_list import ListGroupsIqProtocolEntity
from .iq_groups_info import InfoGroupsIqProtocolEntity
from .iq_groups_subject import SubjectGroupsIqProtocolEntity
from .iq_groups_participants import ParticipantsGroupsIqProtocolEntity
from .iq_groups_participants_add import AddParticipantsIqProtocolEntity
from .iq_groups_participants_promote import PromoteParticipantsIqProtocolEntity
from .iq_groups_participants_demote import DemoteParticipantsIqProtocolEntity
from .iq_groups_participants_add_success import SuccessAddParticipantsIqProtocolEntity
from .iq_groups_participants_add_failure import FailureAddParticipantsIqProtocolEntity
from .iq_groups_participants_remove import RemoveParticipantsIqProtocolEntity
from .iq_groups_participants_remove_success import SuccessRemoveParticipantsIqProtocolEntity
from .iq_result_groups_list import ListGroupsResultIqProtocolEntity
from .iq_result_participants_list import ListParticipantsResultIqProtocolEntity
from .iq_result_groups_info import InfoGroupsResultIqProtocolEntity
from .notification_groups import GroupsNotificationProtocolEntity
from .notification_groups_subject import SubjectGroupsNotificationProtocolEntity
from .notification_groups_create import CreateGroupsNotificationProtocolEntity
from .notification_groups_add import AddGroupsNotificationProtocolEntity
from .notification_groups_remove import RemoveGroupsNotificationProtocolEntity
| 1,706 | Python | .py | 23 | 73.173913 | 92 | 0.890077 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,739 | iq_groups_create_success.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_create_success.py | from yowsup.common import YowConstants
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
class SuccessCreateGroupsIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" id="{{id}}" from="g.us">
<group id="{group_id}"></group>
</iq>
'''
def __init__(self, _id, groupId):
super(SuccessCreateGroupsIqProtocolEntity, self).__init__(_from = YowConstants.WHATSAPP_GROUP_SERVER, _id = _id)
self.setProps(groupId)
def setProps(self, groupId):
self.groupId = groupId
def toProtocolTreeNode(self):
node = super(SuccessCreateGroupsIqProtocolEntity, self).toProtocolTreeNode()
node.addChild(ProtocolTreeNode("group",{"id": self.groupId}))
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(SuccessCreateGroupsIqProtocolEntity, SuccessCreateGroupsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = SuccessCreateGroupsIqProtocolEntity
entity.setProps(node.getChild("group").getAttributeValue("id"))
return entity
| 1,143 | Python | .py | 24 | 41.291667 | 123 | 0.730045 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,740 | iq_result_groups_info.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_result_groups_info.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
class InfoGroupsResultIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" from="{{GROUP_ID}}" id="{{IQ_ID}}">
<group subject="{{GROUPSUBJ}}" creation="{{GROUP_CREATION_TYIME}}"
creator="{{CREATOR_JID}}" s_t="{{SUBJECT_SET_TIMESTAMP}}" id="{{GROUP_ID}}"
s_o="{{SUBJECT_OWNER_JID}}">
<participant jid="{{PARTICIPANT_JID}}" type="admin"></participant>
<participant jid="{{PARTICIPANT_JID}}"></participant>
<participant jid="{{PARTICIPANT_JID}}"></participant>
</group>
</iq>
'''
TYPE_PARTICIPANT_ADMIN = "admin"
def __init__(self, _id, _from,
groupId, creationTimestamp, creatorJid,
subject, subjectTime, subjectOwnerJid,
participants):
super(InfoGroupsResultIqProtocolEntity, self).__init__(_id = _id, _from = _from)
self.setGroupProps(groupId, creationTimestamp, creatorJid,
subject, subjectTime, subjectOwnerJid, participants)
def setGroupProps(self, groupId, creationTimestamp, creatorJid,
subject, subjectTime, subjectOwnerJid,
participants):
assert type(participants) is dict, "Participants must be a dict {jid => type?}"
self.groupId = groupId
self.creationTimestamp = int(creationTimestamp)
self.creatorJid = creatorJid
self.subject = subject
self.subjectTime = int(subjectTime)
self.subjectOwnerJid = subjectOwnerJid
self.participants = participants
def getParticipants(self):
return self.participants
def getSubject(self):
return self.subject
def getGroupId(self):
return self.groupId
def getCreationTimestamp(self):
return self.creationTimestamp
def getCreatorJid(self, full = True):
return self.creatorJid if full else self.creatorJid.split('@')[0]
def getSubjectTimestamp(self):
return self.subjectTime
def getSubjectOwnerJid(self, full = True):
return self.subjectOwnerJid if full else self.subjectOwnerJid.split('@')[0]
def getGroupAdmins(self, full = True):
admins = []
for jid, _type in self.participants.items():
if _type == self.__class__.TYPE_PARTICIPANT_ADMIN:
admins.append(jid if full else jid.split('@')[0])
return admins
def __str__(self):
out = super(InfoGroupsResultIqProtocolEntity, self).__str__()
out += "Group ID: %s\n" % self.groupId
out += "Created: %s\n" % self.creationTimestamp
out += "Creator JID: %s\n" % self.creatorJid
out += "Subject: %s\n" % self.subject
out += "Subject Timestamp: %s\n" % self.subjectTime
out += "Subject owner JID: %s\n" % self.subjectOwnerJid
out += "Participants: %s\n" % self.participants
return out
def toProtocolTreeNode(self):
node = super(InfoGroupsResultIqProtocolEntity, self).toProtocolTreeNode()
groupNode = ProtocolTreeNode("group", {
"subject": self.getSubject(),
"creation": str(self.getCreationTimestamp()),
"creator": self.getCreatorJid(),
"s_t": self.getSubjectTimestamp(),
"s_o": self.getSubjectOwnerJid(),
"id": self.getGroupId()
})
participants = []
for jid, _type in self.getParticipants().items():
pnode = ProtocolTreeNode("participant", {"jid": jid})
if _type:
pnode["type"] = _type
participants.append(pnode)
groupNode.addChildren(participants)
node.addChild(groupNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
groupNode = node.getChild("group")
participants = {}
for p in groupNode.getAllChildren("participant"):
participants[p["jid"]] = p["type"]
return InfoGroupsResultIqProtocolEntity(
node["id"], node["from"],
groupNode["id"], groupNode["creation"], groupNode["creator"], groupNode["subject"],
groupNode["s_t"], groupNode["s_o"], participants
)
| 4,256 | Python | .py | 93 | 36.462366 | 95 | 0.631363 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,741 | iq_groups_participants_add_failure.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_participants_add_failure.py | from yowsup.layers.protocol_iq.protocolentities import ErrorIqProtocolEntity
class FailureAddParticipantsIqProtocolEntity(ErrorIqProtocolEntity):
'''
<iq type="error" from="{{group_jid}}" id="{{id}}">
<error text="item-not-found" code="404">
</error>
</iq>
'''
def __init__(self, _id, _from, _code, _text, _backoff= 0 ):
super(FailureAddParticipantsIqProtocolEntity, self).__init__(_from = _from,
_id = _id, code = _code,
text = _text, backoff = _backoff)
@staticmethod
def fromProtocolTreeNode(node):
entity = ErrorIqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = FailureAddParticipantsIqProtocolEntity
return entity | 846 | Python | .py | 17 | 36.176471 | 102 | 0.569361 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,742 | iq_groups_participants_add.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_participants_add.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups_participants import ParticipantsGroupsIqProtocolEntity
class AddParticipantsIqProtocolEntity(ParticipantsGroupsIqProtocolEntity):
'''
<iq type="set" id="{{id}}" xmlns="w:g2", to="{{group_jid}}">
<add>
<participant jid="{{jid}}"></participant>
<participant jid="{{jid}}"></participant>
</add>
</iq>
'''
def __init__(self, group_jid, participantList, _id = None):
super(AddParticipantsIqProtocolEntity, self).__init__(group_jid, participantList, "add", _id = _id)
@staticmethod
def fromProtocolTreeNode(node):
entity = super(AddParticipantsIqProtocolEntity, AddParticipantsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = AddParticipantsIqProtocolEntity
participantList = []
for participantNode in node.getChild("add").getAllChildren():
participantList.append(participantNode["jid"])
entity.setProps(node.getAttributeValue("to"), participantList)
return entity
| 1,089 | Python | .py | 22 | 42.181818 | 115 | 0.696429 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,743 | iq_groups_leave.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_leave.py | from yowsup.common import YowConstants
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups import GroupsIqProtocolEntity
class LeaveGroupsIqProtocolEntity(GroupsIqProtocolEntity):
'''
<iq id="{{id}}"" type="set" to="{{group_jid}}" xmlns="w:g2">
<leave action="delete">
<group id="{{JID}}">
<group id="{{JID}}">
</leave>
</iq>
'''
def __init__(self, groupList):
super(LeaveGroupsIqProtocolEntity, self).__init__(to = YowConstants.WHATSAPP_GROUP_SERVER, _type = "set")
self.setProps(groupList if type(groupList) is list else [groupList])
def setProps(self, groupList):
assert type(groupList) is list and len(groupList), "Must specify a list of group jids to leave"
self.groupList = groupList
def toProtocolTreeNode(self):
node = super(LeaveGroupsIqProtocolEntity, self).toProtocolTreeNode()
groupNodes = [
ProtocolTreeNode("group", {
"id": groupid
})
for groupid in self.groupList
]
node.addChild(ProtocolTreeNode("leave", {"action": "delete"}, groupNodes))
return node
@staticmethod
def fromProtocolTreeNode(node):
assert node.getChild("leave") is not None, "Not a group leave iq node %s" % node
assert node.getChild("leave").getAttributeValue("action") == "delete", "Not a group leave action %s" % node
entity = super(LeaveGroupsIqProtocolEntity, LeaveGroupsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = LeaveGroupsIqProtocolEntity
entity.setProps([group.getAttributeValue("id") for group in node.getChild("leave").getAllChildren()] )
return entity
| 1,743 | Python | .py | 36 | 40.583333 | 115 | 0.666471 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,744 | test_iq_groups_create.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/test_iq_groups_create.py | from yowsup.layers.protocol_groups.protocolentities.iq_groups_create import CreateGroupsIqProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
entity = CreateGroupsIqProtocolEntity("group subject")
class CreateGroupsIqProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = CreateGroupsIqProtocolEntity
self.node = entity.toProtocolTreeNode()
| 446 | Python | .py | 8 | 52 | 104 | 0.848624 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,745 | iq_groups.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
class GroupsIqProtocolEntity(IqProtocolEntity):
'''
<iq type="{{get | set?}}" id="{{id}}" xmlns="w:g2", to="{{group_jid}}">
</iq>
'''
def __init__(self, to = None, _from = None, _id = None, _type = None):
super(GroupsIqProtocolEntity, self).__init__("w:g2", _id, _type, to = to, _from = _from)
| 455 | Python | .py | 9 | 46.444444 | 96 | 0.652466 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,746 | iq_groups_participants_promote.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_participants_promote.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups_participants import ParticipantsGroupsIqProtocolEntity
class PromoteParticipantsIqProtocolEntity(ParticipantsGroupsIqProtocolEntity):
'''
<iq type="set" id="{{id}}" xmlns="w:g2", to="{{group_jid}}">
<promote>
<participant jid="{{jid}}"></participant>
<participant jid="{{jid}}"></participant>
</promote>
</iq>
'''
def __init__(self, group_jid, participantList, _id = None):
super(PromoteParticipantsIqProtocolEntity, self).__init__(group_jid, participantList, "promote", _id = _id)
@staticmethod
def fromProtocolTreeNode(node):
entity = super(PromoteParticipantsIqProtocolEntity, PromoteParticipantsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = PromoteParticipantsIqProtocolEntity
participantList = []
for participantNode in node.getChild("promote").getAllChildren():
participantList.append(participantNode["jid"])
entity.setProps(node.getAttributeValue("to"), participantList)
return entity
| 1,130 | Python | .py | 22 | 43.863636 | 123 | 0.705722 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,747 | notification_groups_remove.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/notification_groups_remove.py | from .notification_groups import GroupsNotificationProtocolEntity
from yowsup.structs import ProtocolTreeNode
class RemoveGroupsNotificationProtocolEntity(GroupsNotificationProtocolEntity):
'''
<notification notify="{{NOTIFY_NAME}}" id="{{id}}" t="{{TIMESTAMP}}" participant="{{participant_jiid}}" from="{{group_jid}}" type="w:gp2" mode="none">
<remove subject="{{subject}}">
<participant jid="{{participant_jid}}">
</participant>
</remove>
</notification>
'''
TYPE_PARTICIPANT_ADMIN = "admin"
def __init__(self, _id, _from, timestamp, notify, participant, offline,
subject,
participants):
super(RemoveGroupsNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, participant, offline)
self.setGroupProps(subject, participants)
def setGroupProps(self,
subject,
participants):
assert type(participants) is list, "Must be a list of jids, got %s instead." % type(participants)
self.subject = subject
self.participants = participants
def getParticipants(self):
return self.participants
def getSubject(self):
return self.subject
def toProtocolTreeNode(self):
node = super(RemoveGroupsNotificationProtocolEntity, self).toProtocolTreeNode()
removeNode = ProtocolTreeNode("remove", {"subject": self.subject})
participants = []
for jid in self.getParticipants():
pnode = ProtocolTreeNode("participant", {"jid": jid})
participants.append(pnode)
removeNode.addChildren(participants)
node.addChild(removeNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
removeNode = node.getChild("remove")
participants = []
for p in removeNode.getAllChildren("participant"):
participants.append(p["jid"])
return RemoveGroupsNotificationProtocolEntity(
node["id"], node["from"], node["t"], node["notify"], node["participant"], node["offline"],
removeNode["subject"], participants
)
| 2,126 | Python | .py | 47 | 37 | 150 | 0.667472 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,748 | iq_groups_participants_demote.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_participants_demote.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups_participants import ParticipantsGroupsIqProtocolEntity
class DemoteParticipantsIqProtocolEntity(ParticipantsGroupsIqProtocolEntity):
'''
<iq type="set" id="{{id}}" xmlns="w:g2", to="{{group_jid}}">
<demote>
<participant jid="{{jid}}"></participant>
<participant jid="{{jid}}"></participant>
</demote>
</iq>
'''
def __init__(self, group_jid, participantList, _id = None):
super(DemoteParticipantsIqProtocolEntity, self).__init__(group_jid, participantList, "demote", _id = _id)
@staticmethod
def fromProtocolTreeNode(node):
entity = super(DemoteParticipantsIqProtocolEntity, DemoteParticipantsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = DemoteParticipantsIqProtocolEntity
participantList = []
for participantNode in node.getChild("demote").getAllChildren():
participantList.append(participantNode["jid"])
entity.setProps(node.getAttributeValue("to"), participantList)
return entity
| 1,121 | Python | .py | 22 | 43.454545 | 121 | 0.703297 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,749 | iq_groups_create.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_create.py | from yowsup.common import YowConstants
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups import GroupsIqProtocolEntity
class CreateGroupsIqProtocolEntity(GroupsIqProtocolEntity):
'''
<iq type="set" id="{{id}}" xmlns="w:g2", to="g.us">
<create subject="{{subject}}">
<participant jid="{{jid}}"></participant>
</create>
</iq>
'''
def __init__(self, subject, _id = None, participants = None):
super(CreateGroupsIqProtocolEntity, self).__init__(to = YowConstants.WHATSAPP_GROUP_SERVER, _id = _id, _type = "set")
self.setProps(subject)
self.setParticipants(participants or [])
def setProps(self, subject):
self.subject = subject
def setParticipants(self, participants):
self.participantList = participants
def toProtocolTreeNode(self):
node = super(CreateGroupsIqProtocolEntity, self).toProtocolTreeNode()
cnode = ProtocolTreeNode("create",{ "subject": self.subject})
participantNodes = [
ProtocolTreeNode("participant", {
"jid": participant
})
for participant in self.participantList
]
cnode.addChildren(participantNodes)
node.addChild(cnode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(CreateGroupsIqProtocolEntity,CreateGroupsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = CreateGroupsIqProtocolEntity
entity.setProps(node.getChild("create").getAttributeValue("subject"))
participantList = []
for participantNode in node.getChild("create").getAllChildren():
participantList.append(participantNode["jid"])
entity.setParticipants(participantList)
return entity
| 1,825 | Python | .py | 41 | 36.439024 | 125 | 0.677347 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,750 | notification_groups_subject.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/notification_groups_subject.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from yowsup.layers.protocol_notifications.protocolentities import NotificationProtocolEntity
from .notification_groups import GroupsNotificationProtocolEntity
class SubjectGroupsNotificationProtocolEntity(GroupsNotificationProtocolEntity):
'''
<notification notify="WhatsApp" id="{{id}}" t="{{TIMESTAMP}}" participant="{{PARTICIPANT_JID}}" from="{{GROUP_JID}}" type="w:gp2">
<subject s_t="{{subject_set_timestamp}}" s_o="{{subject_owner_jid}}" subject="{{SUBJECT}}">
</subject>
</notification>
'''
def __init__(self, _type, _id, _from, timestamp, notify, participant, subject):
super(SubjectGroupsNotificationProtocolEntity, self).__init__(_id, _from, timestamp, notify, participant)
self.setSubjectData(subject)
def setSubjectData(self, subject, subjectOwner, subjectTimestamp):
self.subject = subject
self.subjectOwner = subjectOwner
self.subjectTimestamp = int(subjectTimestamp)
def getSubject(self):
return self.subject
def getSubjectOwner(self, full = True):
return self.subjectOwner if full else self.subjectOwner.split('@')[0]
def getSubjectTimestamp(self):
return self.subjectTimestamp
def __str__(self):
out = super(SubjectGroupsNotificationProtocolEntity, self).__str__()
out += "New subject: %s\n" % self.getSubject()
out += "Set by: %s\n" % self.getSubjectOwner()
return out
def toProtocolTreeNode(self):
node = super(SubjectGroupsNotificationProtocolEntity, self).toProtocolTreeNode()
subjectNode = ProtocolTreeNode("subject", {
"s_t": str(self.getSubjectTimestamp()),
"s_o": self.getSubjectOwner(),
"subject": self.getSubject()
})
node.addChild(subjectNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(SubjectGroupsNotificationProtocolEntity, SubjectGroupsNotificationProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = SubjectGroupsNotificationProtocolEntity
subjectNode = node.getChild("subject")
entity.setSubjectData(subjectNode["subject"], subjectNode["s_o"], subjectNode["s_t"])
return entity
| 2,304 | Python | .py | 44 | 44.75 | 134 | 0.703424 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,751 | test_iq_result_groups_list.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/test_iq_result_groups_list.py | from yowsup.layers.protocol_groups.protocolentities.iq_result_groups_list import ListGroupsResultIqProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
from yowsup.layers.protocol_groups.structs import Group
import unittest
import time
entity = ListGroupsResultIqProtocolEntity(
[
Group("1234-456", "owner@s.whatsapp.net", "subject", "sOwnerJid@s.whatsapp.net", int(time.time()), int(time.time())),
Group("4321-456", "owner@s.whatsapp.net", "subject", "sOwnerJid@s.whatsapp.net", int(time.time()), int(time.time()))
]
)
class ListGroupsResultIqProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = ListGroupsResultIqProtocolEntity
self.node = entity.toProtocolTreeNode()
| 784 | Python | .py | 15 | 48.2 | 125 | 0.774446 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,752 | iq_groups_participants_add_success.py | tgalal_yowsup/yowsup/layers/protocol_groups/protocolentities/iq_groups_participants_add_success.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
class SuccessAddParticipantsIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" from="{{group_jid}}" id="{{id}}">
<add type="success" participant="{{jid}}"></add>
<add type="success" participant="{{jid}}"></add>
</iq>
'''
def __init__(self, _id, groupId, participantList):
super(SuccessAddParticipantsIqProtocolEntity, self).__init__(_from = groupId, _id = _id)
self.setProps(groupId, participantList)
def setProps(self, groupId, participantList):
self.groupId = groupId
self.participantList = participantList
self.action = 'add'
def getAction(self):
return self.action
def toProtocolTreeNode(self):
node = super(SuccessAddParticipantsIqProtocolEntity, self).toProtocolTreeNode()
participantNodes = [
ProtocolTreeNode("add", {
"type": "success",
"participant": participant
})
for participant in self.participantList
]
node.addChildren(participantNodes)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(SuccessAddParticipantsIqProtocolEntity, SuccessAddParticipantsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = SuccessAddParticipantsIqProtocolEntity
participantList = []
for participantNode in node.getAllChildren():
if participantNode["type"]=="success":
participantList.append(participantNode["participant"])
entity.setProps(node.getAttributeValue("from"), participantList)
return entity
| 1,785 | Python | .py | 39 | 37.230769 | 129 | 0.670115 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,753 | manager.py | tgalal_yowsup/yowsup/config/manager.py | from yowsup.config.v1.config import Config
from yowsup.config.transforms.dict_keyval import DictKeyValTransform
from yowsup.config.transforms.dict_json import DictJsonTransform
from yowsup.config.v1.serialize import ConfigSerialize
from yowsup.common.tools import StorageTools
import logging
import os
logger = logging.getLogger(__name__)
class ConfigManager(object):
NAME_FILE_CONFIG = "config"
TYPE_KEYVAL = 1
TYPE_JSON = 2
TYPE_NAMES = {
TYPE_KEYVAL: "keyval",
TYPE_JSON: "json"
}
MAP_EXT = {
"yo": TYPE_KEYVAL,
"json": TYPE_JSON,
}
TYPES = {
TYPE_KEYVAL: DictKeyValTransform,
TYPE_JSON: DictJsonTransform
}
def load(self, path_or_profile_name, profile_only=False):
# type: (str, bool) -> Config
"""
Will first try to interpret path_or_profile_name as direct path to a config file and load from there. If
this fails will interpret it as profile name and load from profile dir.
:param path_or_profile_name:
:param profile_only
:return Config instance, or None if no config could be found
"""
logger.debug("load(path_or_profile_name=%s, profile_only=%s)" % (path_or_profile_name, profile_only))
exhausted = []
if not profile_only:
config = self._load_path(path_or_profile_name)
else:
config = None
if config is not None:
return config
else:
logger.debug("path_or_profile_name is not a path, using it as profile name")
if not profile_only:
exhausted.append(path_or_profile_name)
profile_name = path_or_profile_name
config_dir = StorageTools.getStorageForProfile(profile_name)
logger.debug("Detecting config for profile=%s, dir=%s" % (profile_name, config_dir))
for ftype in self.MAP_EXT:
if len(ftype):
fname = (self.NAME_FILE_CONFIG + "." + ftype)
else:
fname = self.NAME_FILE_CONFIG
fpath = os.path.join(config_dir, fname)
logger.debug("Trying %s" % fpath)
if os.path.isfile(fpath):
return self._load_path(fpath)
exhausted.append(fpath)
logger.error("Could not find a config for profile=%s, paths checked: %s" % (profile_name, ":".join(exhausted)))
def _type_to_str(self, type):
"""
:param type:
:type type: int
:return:
:rtype:
"""
for key, val in self.TYPE_NAMES.items():
if key == type:
return val
def _load_path(self, path):
"""
:param path:
:type path:
:return:
:rtype:
"""
logger.debug("_load_path(path=%s)" % path)
if os.path.isfile(path):
configtype = self.guess_type(path)
logger.debug("Detected config type: %s" % self._type_to_str(configtype))
if configtype in self.TYPES:
logger.debug("Opening config for reading")
with open(path, 'r') as f:
data = f.read()
datadict = self.TYPES[configtype]().reverse(data)
return self.load_data(datadict)
else:
raise ValueError("Unsupported config type")
else:
logger.debug("_load_path couldn't find the path: %s" % path)
def load_data(self, datadict):
logger.debug("Loading config")
return ConfigSerialize(Config).deserialize(datadict)
def guess_type(self, config_path):
dissected = os.path.splitext(config_path)
if len(dissected) > 1:
ext = dissected[1][1:].lower()
config_type = self.MAP_EXT[ext] if ext in self.MAP_EXT else None
else:
config_type = None
if config_type is not None:
return config_type
else:
logger.debug("Trying auto detect config type by parsing")
with open(config_path, 'r') as f:
data = f.read()
for config_type, transform in self.TYPES.items():
config_type_str = self.TYPE_NAMES[config_type]
try:
logger.debug("Trying to parse as %s" % config_type_str)
if transform().reverse(data):
logger.debug("Successfully detected %s as config type for %s" % (config_type_str, config_path))
return config_type
except Exception as ex:
logger.debug("%s was not parseable as %s, reason: %s" % (config_path, config_type_str, ex))
def get_str_transform(self, serialize_type):
if serialize_type in self.TYPES:
return self.TYPES[serialize_type]()
def config_to_str(self, config, serialize_type=TYPE_JSON):
transform = self.get_str_transform(serialize_type)
if transform is not None:
return transform.transform(ConfigSerialize(config.__class__).serialize(config))
raise ValueError("unrecognized serialize_type=%d" % serialize_type)
def save(self, profile_name, config, serialize_type=TYPE_JSON, dest=None):
outputdata = self.config_to_str(config, serialize_type)
if dest is None:
StorageTools.writeProfileConfig(profile_name, outputdata)
else:
with open(dest, 'wb') as outputfile:
outputfile.write(outputdata)
| 5,552 | Python | .py | 130 | 31.792308 | 123 | 0.589335 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,754 | config.py | tgalal_yowsup/yowsup/config/v1/config.py | from yowsup.config.base import config
import logging
logger = logging.getLogger(__name__)
class Config(config.Config):
def __init__(
self,
phone=None,
cc=None,
login=None,
password=None,
pushname=None,
id=None,
mcc=None,
mnc=None,
sim_mcc=None,
sim_mnc=None,
client_static_keypair=None,
server_static_public=None,
expid=None,
fdid=None,
edge_routing_info=None,
chat_dns_domain=None
):
super(Config, self).__init__(1)
self._phone = str(phone) if phone is not None else None # type: str
self._cc = cc # type: int
self._login = str(login) if login is not None else None # type: str
self._password = password # type: str
self._pushname = pushname # type: str
self._id = id
self._client_static_keypair = client_static_keypair
self._server_static_public = server_static_public
self._expid = expid
self._fdid = fdid
self._mcc = mcc
self._mnc = mnc
self._sim_mcc = sim_mcc
self._sim_mnc = sim_mnc
self._edge_routing_info = edge_routing_info
self._chat_dns_domain = chat_dns_domain
if self._password is not None:
logger.warn("Setting a password in Config is deprecated and not used anymore. "
"client_static_keypair is used instead")
def __str__(self):
from yowsup.config.v1.serialize import ConfigSerialize
from yowsup.config.transforms.dict_json import DictJsonTransform
return DictJsonTransform().transform(ConfigSerialize(self.__class__).serialize(self))
@property
def phone(self):
return self._phone
@phone.setter
def phone(self, value):
self._phone = str(value) if value is not None else None
@property
def cc(self):
return self._cc
@cc.setter
def cc(self, value):
self._cc = value
@property
def login(self):
return self._login
@login.setter
def login(self, value):
self._login= value
@property
def password(self):
return self._password
@password.setter
def password(self, value):
self._password = value
if value is not None:
logger.warn("Setting a password in Config is deprecated and not used anymore. "
"client_static_keypair is used instead")
@property
def pushname(self):
return self._pushname
@pushname.setter
def pushname(self, value):
self._pushname = value
@property
def mcc(self):
return self._mcc
@mcc.setter
def mcc(self, value):
self._mcc = value
@property
def mnc(self):
return self._mnc
@mnc.setter
def mnc(self, value):
self._mnc = value
@property
def sim_mcc(self):
return self._sim_mcc
@sim_mcc.setter
def sim_mcc(self, value):
self._sim_mcc = value
@property
def sim_mnc(self):
return self._sim_mnc
@sim_mnc.setter
def sim_mnc(self, value):
self._sim_mnc = value
@property
def id(self):
return self._id
@id.setter
def id(self, value):
self._id = value
@property
def client_static_keypair(self):
return self._client_static_keypair
@client_static_keypair.setter
def client_static_keypair(self, value):
self._client_static_keypair = value
@property
def server_static_public(self):
return self._server_static_public
@server_static_public.setter
def server_static_public(self, value):
self._server_static_public = value
@property
def expid(self):
return self._expid
@expid.setter
def expid(self, value):
self._expid = value
@property
def fdid(self):
return self._fdid
@fdid.setter
def fdid(self, value):
self._fdid = value
@property
def edge_routing_info(self):
return self._edge_routing_info
@edge_routing_info.setter
def edge_routing_info(self, value):
self._edge_routing_info = value
@property
def chat_dns_domain(self):
return self._chat_dns_domain
@chat_dns_domain.setter
def chat_dns_domain(self, value):
self._chat_dns_domain = value
| 4,470 | Python | .py | 146 | 22.671233 | 93 | 0.604293 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,755 | serialize.py | tgalal_yowsup/yowsup/config/v1/serialize.py | from yowsup.config.base import serialize
from yowsup.config.transforms.filter import FilterTransform
from yowsup.config.transforms.meta import MetaPropsTransform
from yowsup.config.transforms.map import MapTransform
from yowsup.config.transforms.config_dict import ConfigDictTransform
from yowsup.config.transforms.props import PropsTransform
from consonance.structs.keypair import KeyPair
from consonance.structs.publickey import PublicKey
import base64
class ConfigSerialize(serialize.ConfigSerialize):
def __init__(self, config_class):
super(ConfigSerialize, self).__init__(
transforms=(
ConfigDictTransform(config_class),
FilterTransform(
transform_filter=lambda key, val: val is not None,
reverse_filter=lambda key, val: key != "version"
),
MapTransform(transform_map=lambda key, val: (key[1:], val)),
PropsTransform(
transform_map={
"server_static_public": lambda key, val: (key, base64.b64encode(val.data).decode()),
"client_static_keypair": lambda key, val: (key, base64.b64encode(val.private.data + val.public.data).decode()),
"id": lambda key, val: (key, base64.b64encode(val).decode()),
"expid": lambda key, val: (key, base64.b64encode(val).decode()),
"edge_routing_info": lambda key, val: (key, base64.b64encode(val).decode())
},
reverse_map={
"server_static_public": lambda key, val: (key, PublicKey(base64.b64decode(val))),
"client_static_keypair": lambda key, val: (key, KeyPair.from_bytes(base64.b64decode(val))),
"id": lambda key, val: (key, base64.b64decode(val)),
"expid": lambda key, val: (key, base64.b64decode(val)),
"edge_routing_info": lambda key, val: (key, base64.b64decode(val))
}
),
MetaPropsTransform(meta_props=("version", )),
)
)
| 2,180 | Python | .py | 38 | 42.710526 | 135 | 0.591865 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,756 | meta.py | tgalal_yowsup/yowsup/config/transforms/meta.py | from yowsup.config.base.transform import ConfigTransform
from yowsup.config.transforms.props import PropsTransform
class MetaPropsTransform(ConfigTransform):
META_FORMAT = "__%s__"
def __init__(self, meta_props=None, meta_format=META_FORMAT):
meta_props = meta_props or ()
meta_format = meta_format
transform_map = {}
reverse_map = {}
for prop in meta_props:
formatted = meta_format % prop
transform_map[prop] = lambda key, val, formatted=formatted: (formatted, val)
reverse_map[formatted] = lambda key, val, prop=prop: (prop, val)
self._props_transform = PropsTransform(transform_map=transform_map, reverse_map=reverse_map)
def transform(self, data):
return self._props_transform.transform(data)
def reverse(self, data):
return self._props_transform.reverse(data)
| 887 | Python | .py | 18 | 41.5 | 100 | 0.680185 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,757 | filter.py | tgalal_yowsup/yowsup/config/transforms/filter.py | from yowsup.config.base.transform import ConfigTransform
class FilterTransform(ConfigTransform):
def __init__(self, transform_filter=None, reverse_filter=None):
"""
:param transform_filter:
:type transform_filter: function | None
:param reverse_filter:
:type reverse_filter: function | None
"""
self._transform_filter = transform_filter # type: function | None
self._reverse_filter = reverse_filter # type: function | None
def transform(self, data):
if self._transform_filter is not None:
out = {}
for key, val in data.items():
if self._transform_filter(key, val):
out[key] = val
return out
return data
def reverse(self, data):
if self._reverse_filter is not None:
out = {}
for key, val in data.items():
if self._reverse_filter(key, val):
out[key] = val
return out
return data
| 1,036 | Python | .py | 27 | 27.851852 | 74 | 0.573705 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,758 | dict_keyval.py | tgalal_yowsup/yowsup/config/transforms/dict_keyval.py | from yowsup.config.base.transform import ConfigTransform
class DictKeyValTransform(ConfigTransform):
def transform(self, data):
"""
:param data:
:type data: dict
:return:
:rtype:
"""
out=[]
keys = sorted(data.keys())
for k in keys:
out.append("%s=%s" % (k, data[k]))
return "\n".join(out)
def reverse(self, data):
out = {}
for l in data.split('\n'):
line = l.strip()
if len(line) and line[0] not in ('#',';'):
prep = line.split('#', 1)[0].split(';', 1)[0].split('=', 1)
varname = prep[0].strip()
val = prep[1].strip()
out[varname.replace('-', '_')] = val
return out
| 781 | Python | .py | 24 | 22.583333 | 75 | 0.476127 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,759 | dict_json.py | tgalal_yowsup/yowsup/config/transforms/dict_json.py | from yowsup.config.base.transform import ConfigTransform
import json
class DictJsonTransform(ConfigTransform):
def transform(self, data):
return json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
def reverse(self, data):
return json.loads(data)
| 289 | Python | .py | 7 | 36.285714 | 81 | 0.726619 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,760 | config_dict.py | tgalal_yowsup/yowsup/config/transforms/config_dict.py | from yowsup.config.base.transform import ConfigTransform
class ConfigDictTransform(ConfigTransform):
def __init__(self, cls):
self._cls = cls
def transform(self, config):
"""
:param config:
:type config: dict
:return:
:rtype: yowsup.config.config.Config
"""
out = {}
for prop in vars(config):
out[prop] = getattr(config, prop)
return out
def reverse(self, data):
"""
:param data:
:type data: yowsup,config.config.Config
:return:
:rtype: dict
"""
return self._cls(**data)
| 635 | Python | .py | 23 | 19.478261 | 56 | 0.560855 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,761 | props.py | tgalal_yowsup/yowsup/config/transforms/props.py | from yowsup.config.base.transform import ConfigTransform
import types
class PropsTransform(ConfigTransform):
def __init__(self, transform_map=None, reverse_map=None):
self._transform_map = transform_map or {}
self._reverse_map = reverse_map or {}
def transform(self, data):
"""
:param data:
:type data: dict
:return:
:rtype: dict
"""
out = {}
for key, val in data.items():
if key in self._transform_map:
target = self._transform_map[key]
key, val = target(key, val) if type(target) == types.FunctionType else (key, target)
out[key] = val
return out
def reverse(self, data):
transformed_dict = {}
for key, val in data.items():
if key in self._reverse_map:
target = self._reverse_map[key]
key, val = target(key, val) if type(target) == types.FunctionType else (key, target)
transformed_dict[key] = val
return transformed_dict
| 1,070 | Python | .py | 28 | 28.428571 | 100 | 0.577519 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,762 | serialize.py | tgalal_yowsup/yowsup/config/transforms/serialize.py | from yowsup.config.transforms.props import PropsTransform
class SerializeTransform(PropsTransform):
def __init__(self, serialize_map):
"""
{
"keystore": serializer
}
:param serialize_map:
:type serialize_map:
"""
transform_map = {}
reverse_map = {}
for key, val in serialize_map:
transform_map[key] = lambda key, val: key, serialize_map[key].serialize(val)
reverse_map[key] = lambda key, val: key, serialize_map[key].deserialize(val)
super(SerializeTransform, self).__init__(transform_map=transform_map, reverse_map=reverse_map)
| 654 | Python | .py | 16 | 32.0625 | 102 | 0.625592 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,763 | map.py | tgalal_yowsup/yowsup/config/transforms/map.py | from yowsup.config.base.transform import ConfigTransform
class MapTransform(ConfigTransform):
def __init__(self, transform_map=None, reverse_map=None):
"""
:param transform_map:
:type transform_map: function | None
:param reverse_map:
:type reverse_map: function | None
"""
self._transform_map = transform_map # type: function | None
self._reverse_map = reverse_map # type: function | None
def transform(self, data):
if self._transform_map is not None:
out = {}
for key, val in data.items():
key, val = self._transform_map(key, val)
out[key] = val
return out
return data
def reverse(self, data):
if self._reverse_map is not None:
out = {}
for key, val in data.items():
key, val = self._reverse_map(key, val)
out[key] = val
return out
return data
| 997 | Python | .py | 27 | 26.703704 | 68 | 0.558549 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,764 | config.py | tgalal_yowsup/yowsup/config/base/config.py | class Config(object):
def __init__(self, version):
self._version = version
def __contains__(self, item):
return self[item] is not None
def __getitem__(self, item):
return getattr(self, "_%s" % item)
def __setitem__(self, key, value):
setattr(self, key, value)
def keys(self):
return [var[1:] for var in vars(self)]
@property
def version(self):
return self._version
| 446 | Python | .py | 14 | 25.071429 | 46 | 0.590164 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,765 | transform.py | tgalal_yowsup/yowsup/config/base/transform.py | class ConfigTransform(object):
def transform(self, config):
"""
:param config:
:type config: yowsup.config.base.config.Config
:return: dict
:rtype:
"""
def reverse(self, data):
"""
:param data:
:type data:
:return:
:rtype: yowsup.config.base.config.Config
"""
| 365 | Python | .py | 15 | 16.333333 | 54 | 0.532951 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,766 | serialize.py | tgalal_yowsup/yowsup/config/base/serialize.py | class ConfigSerialize(object):
def __init__(self, transforms):
self._transforms = transforms
def serialize(self, config):
"""
:param config:
:type config: yowsup.config.base.config.Config
:return:
:rtype: bytes
"""
for transform in self._transforms:
config = transform.transform(config)
return config
def deserialize(self, data):
"""
:type cls: type
:param data:
:type data: bytes
:return:
:rtype: yowsup.config.base.config.Config
"""
for transform in self._transforms[::-1]:
data = transform.reverse(data)
return data
| 702 | Python | .py | 24 | 20.625 | 54 | 0.57037 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,767 | protocolentity.py | tgalal_yowsup/yowsup/structs/protocolentity.py | from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = 0
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, attributes, children = None, data = None):
return ProtocolTreeNode(self.getTag(), attributes, children, data)
def _getCurrentTimestamp(self):
return int(time.time())
def _generateId(self, short = False):
ProtocolEntity.__ID_GEN += 1
return str(ProtocolEntity.__ID_GEN) if short else str(int(time.time())) + "-" + str(ProtocolEntity.__ID_GEN)
def toProtocolTreeNode(self):
pass
@staticmethod
def fromProtocolTreeNode(self, protocolTreeNode):
pass
class ProtocolEntityTest(object):
def setUp(self):
self.ProtocolEntity = None
self.node = None
# def assertEqual(self, entity, node):
# raise AssertionError("Should never execute that")
def test_generation(self):
if self.ProtocolEntity is None:
raise ValueError("Test case not setup!")
entity = self.ProtocolEntity.fromProtocolTreeNode(self.node)
try:
self.assertEqual(entity.toProtocolTreeNode(), self.node)
except:
print(entity.toProtocolTreeNode())
print("\nNOTEQ\n")
print(self.node)
raise
| 1,474 | Python | .py | 39 | 30.051282 | 116 | 0.653521 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,768 | protocoltreenode.py | tgalal_yowsup/yowsup/structs/protocoltreenode.py | import binascii
class ProtocolTreeNode(object):
_STR_MAX_LEN_DATA = 500
_STR_INDENT = ' '
def __init__(self, tag, attributes = None, children = None, data = None):
# type: (str, dict, list[ProtocolTreeNode], bytes) -> None
if data is not None:
assert type(data) is bytes, type(data)
self.tag = tag
self.attributes = attributes or {}
self.children = children or []
self.data = data
self._truncate_str_data = True
assert type(self.children) is list, "Children must be a list, got %s" % type(self.children)
def __eq__(self, protocolTreeNode):
"""
:param protocolTreeNode: ProtocolTreeNode
:return: bool
"""
#
if protocolTreeNode.__class__ == ProtocolTreeNode\
and self.tag == protocolTreeNode.tag\
and self.data == protocolTreeNode.data\
and self.attributes == protocolTreeNode.attributes\
and len(self.getAllChildren()) == len(protocolTreeNode.getAllChildren()):
found = False
for c in self.getAllChildren():
for c2 in protocolTreeNode.getAllChildren():
if c == c2:
found = True
break
if not found:
return False
found = False
for c in protocolTreeNode.getAllChildren():
for c2 in self.getAllChildren():
if c == c2:
found = True
break
if not found:
return False
return True
return False
def __hash__(self):
return hash(self.tag) ^ hash(tuple(self.attributes.items())) ^ hash(self.data)
def __str__(self):
out = "<%s" % self.tag
attrs = " ".join((map(lambda item: "%s=\"%s\"" % item, self.attributes.items())))
children = "\n".join(map(str, self.children))
data = self.data or b""
len_data = len(data)
if attrs:
out = "%s %s" % (out, attrs)
if children or data:
out = "%s>" % out
if children:
out = "%s\n%s%s" % (out, self._STR_INDENT, children.replace('\n', '\n' + self._STR_INDENT))
if len_data:
if self._truncate_str_data and len_data > self._STR_MAX_LEN_DATA:
data = data[:self._STR_MAX_LEN_DATA]
postfix = "...[truncated %s bytes]" % (len_data - self._STR_MAX_LEN_DATA)
else:
postfix = ""
data = "0x%s" % binascii.hexlify(data).decode()
out = "%s\n%s%s%s" % (out, self._STR_INDENT, data, postfix)
out = "%s\n</%s>" % (out, self.tag)
else:
out = "%s />" % out
return out
def getData(self):
return self.data
def setData(self, data):
self.data = data
@staticmethod
def tagEquals(node,string):
return node is not None and node.tag is not None and node.tag == string
@staticmethod
def require(node,string):
if not ProtocolTreeNode.tagEquals(node,string):
raise Exception("failed require. string: "+string);
def __getitem__(self, key):
return self.getAttributeValue(key)
def __setitem__(self, key, val):
self.setAttribute(key, val)
def __delitem__(self, key):
self.removeAttribute(key)
def getChild(self,identifier):
if type(identifier) == int:
if len(self.children) > identifier:
return self.children[identifier]
else:
return None
for c in self.children:
if identifier == c.tag:
return c
return None
def hasChildren(self):
return len(self.children) > 0
def addChild(self, childNode):
self.children.append(childNode)
def addChildren(self, children):
for c in children:
self.addChild(c)
def getAttributeValue(self,string):
try:
return self.attributes[string]
except KeyError:
return None
def removeAttribute(self, key):
if key in self.attributes:
del self.attributes[key]
def setAttribute(self, key, value):
self.attributes[key] = value
def getAllChildren(self,tag = None):
ret = []
if tag is None:
return self.children
for c in self.children:
if tag == c.tag:
ret.append(c)
return ret
| 4,704 | Python | .py | 121 | 26.942149 | 107 | 0.53103 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,769 | existsrequest.py | tgalal_yowsup/yowsup/registration/existsrequest.py | from yowsup.common.http.warequest import WARequest
from yowsup.common.http.waresponseparser import JSONResponseParser
from yowsup.env import YowsupEnv
class WAExistsRequest(WARequest):
def __init__(self, config):
"""
:param config:
:type config: yowsup.config.v1.config.Config
"""
super(WAExistsRequest,self).__init__(config)
if config.id is None:
raise ValueError("Config does not contain id")
self.url = "v.whatsapp.net/v2/exist"
self.pvars = ["status", "reason", "sms_length", "voice_length", "result","param", "login", "type",
"chat_dns_domain", "edge_routing_info"
]
self.setParser(JSONResponseParser())
self.addParam("token", YowsupEnv.getCurrent().getToken(self._p_in))
| 821 | Python | .py | 18 | 36.611111 | 106 | 0.638645 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,770 | regrequest.py | tgalal_yowsup/yowsup/registration/regrequest.py | '''
Copyright (c) <2012> Tarek Galal <tare2.galal@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
from yowsup.common.http.warequest import WARequest
from yowsup.common.http.waresponseparser import JSONResponseParser
class WARegRequest(WARequest):
def __init__(self, config, code):
"""
:param config:
:type config: yowsup.config.vx.config.Config
:param code:
:type code: str
"""
super(WARegRequest,self).__init__(config)
if config.id is None:
raise ValueError("config.id is not set.")
self.addParam("code", code)
self.url = "v.whatsapp.net/v2/register"
self.pvars = ["status", "login", "type", "edge_routing_info", "chat_dns_domain"
"reason","retry_after"]
self.setParser(JSONResponseParser())
| 1,827 | Python | .py | 35 | 47.028571 | 87 | 0.737079 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,771 | coderequest.py | tgalal_yowsup/yowsup/registration/coderequest.py | from yowsup.common.http.warequest import WARequest
from yowsup.common.http.waresponseparser import JSONResponseParser
from yowsup.common.tools import WATools
from yowsup.registration.existsrequest import WAExistsRequest
from yowsup.env import YowsupEnv
class WACodeRequest(WARequest):
def __init__(self, method, config):
"""
:type method: str
:param config:
:type config: yowsup.config.v1.config.Config
"""
super(WACodeRequest,self).__init__(config)
self.addParam("mcc", config.mcc.zfill(3))
self.addParam("mnc", config.mnc.zfill(3))
self.addParam("sim_mcc", config.sim_mcc.zfill(3))
self.addParam("sim_mnc", config.sim_mnc.zfill(3))
self.addParam("method", method)
self.addParam("reason", "")
self.addParam("token", YowsupEnv.getCurrent().getToken(self._p_in))
self.addParam("hasav", "1")
self.url = "v.whatsapp.net/v2/code"
self.pvars = ["status","reason","length", "method", "retry_after", "code", "param"] +\
["login", "type", "sms_wait", "voice_wait"]
self.setParser(JSONResponseParser())
def send(self, parser = None, encrypt=True, preview=False):
if self._config.id is not None:
request = WAExistsRequest(self._config)
result = request.send(encrypt=encrypt, preview=preview)
if result:
if result["status"] == "ok":
return result
elif result["status"] == "fail" and "reason" in result and result["reason"] == "blocked":
return result
else:
self._config.id = WATools.generateIdentity()
self.addParam("id", self._config.id)
res = super(WACodeRequest, self).send(parser, encrypt=encrypt, preview=preview)
return res
| 1,856 | Python | .py | 39 | 37.948718 | 105 | 0.623894 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,772 | __init__.py | tgalal_yowsup/yowsup/registration/__init__.py | from .coderequest import WACodeRequest
from .existsrequest import WAExistsRequest
from .regrequest import WARegRequest | 118 | Python | .py | 3 | 38.666667 | 42 | 0.896552 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,773 | factory.py | tgalal_yowsup/yowsup/axolotl/factory.py | from yowsup.axolotl.manager import AxolotlManager
from yowsup.common.tools import StorageTools
from yowsup.axolotl.store.sqlite.liteaxolotlstore import LiteAxolotlStore
import logging
logger = logging.getLogger(__name__)
class AxolotlManagerFactory(object):
DB = "axolotl.db"
def get_manager(self, profile_name, username):
logger.debug("get_manager(profile_name=%s, username=%s)" % (profile_name, username))
dbpath = StorageTools.constructPath(profile_name, self.DB)
store = LiteAxolotlStore(dbpath)
return AxolotlManager(store, username)
| 583 | Python | .py | 12 | 43.916667 | 92 | 0.768959 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,774 | manager.py | tgalal_yowsup/yowsup/axolotl/manager.py | from axolotl.util.keyhelper import KeyHelper
from axolotl.identitykeypair import IdentityKeyPair
from axolotl.groups.senderkeyname import SenderKeyName
from axolotl.axolotladdress import AxolotlAddress
from axolotl.sessioncipher import SessionCipher
from axolotl.groups.groupcipher import GroupCipher
from axolotl.groups.groupsessionbuilder import GroupSessionBuilder
from axolotl.sessionbuilder import SessionBuilder
from axolotl.protocol.prekeywhispermessage import PreKeyWhisperMessage
from axolotl.protocol.whispermessage import WhisperMessage
from axolotl.state.prekeybundle import PreKeyBundle
from axolotl.untrustedidentityexception import UntrustedIdentityException
from axolotl.invalidmessageexception import InvalidMessageException
from axolotl.duplicatemessagexception import DuplicateMessageException
from axolotl.invalidkeyidexception import InvalidKeyIdException
from axolotl.nosessionexception import NoSessionException
from axolotl.protocol.senderkeydistributionmessage import SenderKeyDistributionMessage
from axolotl.state.axolotlstore import AxolotlStore
from yowsup.axolotl.store.sqlite.liteaxolotlstore import LiteAxolotlStore
from yowsup.axolotl import exceptions
import random
import logging
import sys
logger = logging.getLogger(__name__)
class AxolotlManager(object):
COUNT_GEN_PREKEYS = 812
THRESHOLD_REGEN = 10
MAX_SIGNED_PREKEY_ID = 16777215
def __init__(self, store, username):
"""
:param store:
:type store: AxolotlStore
:param username:
:type username: str
"""
self._username = username # type: str
self._store = store # type: LiteAxolotlStore
self._identity = self._store.getIdentityKeyPair() # type: IdentityKeyPair
self._registration_id = self._store.getLocalRegistrationId() # type: int | None
assert self._registration_id is not None
assert self._identity is not None
self._group_session_builder = GroupSessionBuilder(self._store) # type: GroupSessionBuilder
self._session_ciphers = {} # type: dict[str, SessionCipher]
self._group_ciphers = {} # type: dict[str, GroupCipher]
logger.debug("Initialized AxolotlManager [username=%s, db=%s]" % (self._username, store))
@property
def registration_id(self):
return self._registration_id
@property
def identity(self):
return self._identity
def level_prekeys(self, force=False):
logger.debug("level_prekeys(force=%s)" % force)
len_pending_prekeys = len(self._store.loadPreKeys())
logger.debug("len(pending_prekeys) = %d" % len_pending_prekeys)
if force or len_pending_prekeys < self.THRESHOLD_REGEN:
count_gen = self.COUNT_GEN_PREKEYS
max_prekey_id = self._store.preKeyStore.loadMaxPreKeyId()
logger.info("Generating %d prekeys, current max_prekey_id=%d" % (count_gen, max_prekey_id))
prekeys = KeyHelper.generatePreKeys(max_prekey_id + 1, count_gen)
logger.info("Storing %d prekeys" % len(prekeys))
for i in range(0, len(prekeys)):
key = prekeys[i]
if logger.level <= logging.DEBUG:
sys.stdout.write("Storing prekey %d/%d \r" % (i + 1, len(prekeys)))
sys.stdout.flush()
self._store.storePreKey(key.getId(), key)
return prekeys
return []
def load_unsent_prekeys(self):
logger.debug("load_unsent_prekeys")
unsent = self._store.preKeyStore.loadUnsentPendingPreKeys()
if len(unsent) > 0:
logger.info("Loaded %d unsent prekeys" % len(unsent))
return unsent
def set_prekeys_as_sent(self, prekeyIds):
"""
:param prekeyIds:
:type prekeyIds: list
:return:
:rtype:
"""
logger.debug("set_prekeys_as_sent(prekeyIds=[%d prekeyIds])" % len(prekeyIds))
self._store.preKeyStore.setAsSent([prekey.getId() for prekey in prekeyIds])
def generate_signed_prekey(self):
logger.debug("generate_signed_prekey")
latest_signed_prekey = self.load_latest_signed_prekey(generate=False)
if latest_signed_prekey is not None:
if latest_signed_prekey.getId() == self.MAX_SIGNED_PREKEY_ID:
new_signed_prekey_id = (self.MAX_SIGNED_PREKEY_ID / 2) + 1
else:
new_signed_prekey_id = latest_signed_prekey.getId() + 1
else:
new_signed_prekey_id = 0
signed_prekey = KeyHelper.generateSignedPreKey(self._identity, new_signed_prekey_id)
self._store.storeSignedPreKey(signed_prekey.getId(), signed_prekey)
return signed_prekey
def load_latest_signed_prekey(self, generate=False):
logger.debug("load_latest_signed_prekey")
signed_prekeys = self._store.loadSignedPreKeys()
if len(signed_prekeys):
return signed_prekeys[-1]
return self.generate_signed_prekey() if generate else None
def _get_session_cipher(self, recipientid):
logger.debug("get_session_cipher(recipientid=%s)" % recipientid)
if recipientid in self._session_ciphers:
session_cipher = self._session_ciphers[recipientid]
else:
session_cipher= SessionCipher(self._store, self._store, self._store, self._store, recipientid, 1)
self._session_ciphers[recipientid] = session_cipher
return session_cipher
def _get_group_cipher(self, groupid, username):
logger.debug("get_group_cipher(groupid=%s, username=%s)" % (groupid, username))
senderkeyname = SenderKeyName(groupid, AxolotlAddress(username, 0))
if senderkeyname in self._group_ciphers:
group_cipher = self._group_ciphers[senderkeyname]
else:
group_cipher = GroupCipher(self._store.senderKeyStore, senderkeyname)
self._group_ciphers[senderkeyname] = group_cipher
return group_cipher
def _generate_random_padding(self):
logger.debug("generate_random_padding")
num = random.randint(1,255)
return bytes(bytearray([num] * num))
def _unpad(self, data):
padding_byte = data[-1] if type(data[-1]) is int else ord(data[-1]) # bec inconsistent API?
padding = padding_byte & 0xFF
return data[:-padding]
def encrypt(self, recipient_id, message):
# to avoid the hassle of encoding issues and associated unnecessary crashes,
# don't log the message content.
# see https://github.com/tgalal/yowsup/issues/2732
logger.debug("encrypt(recipientid=%s, message=[omitted])" % recipient_id)
"""
:param recipient_id:
:type recipient_id: str
:param data:
:type data: bytes
:return:
:rtype:
"""
cipher = self._get_session_cipher(recipient_id)
return cipher.encrypt(message + self._generate_random_padding())
def decrypt_pkmsg(self, senderid, data, unpad):
logger.debug("decrypt_pkmsg(senderid=%s, data=(omitted), unpad=%s)" % (senderid, unpad))
pkmsg = PreKeyWhisperMessage(serialized=data)
try:
plaintext = self._get_session_cipher(senderid).decryptPkmsg(pkmsg)
return self._unpad(plaintext) if unpad else plaintext
except NoSessionException:
raise exceptions.NoSessionException()
except InvalidKeyIdException:
raise exceptions.InvalidKeyIdException()
except InvalidMessageException:
raise exceptions.InvalidMessageException()
except DuplicateMessageException:
raise exceptions.DuplicateMessageException()
def decrypt_msg(self, senderid, data, unpad):
logger.debug("decrypt_msg(senderid=%s, data=[omitted], unpad=%s)" % (senderid, unpad))
msg = WhisperMessage(serialized=data)
try:
plaintext = self._get_session_cipher(senderid).decryptMsg(msg)
return self._unpad(plaintext) if unpad else plaintext
except NoSessionException:
raise exceptions.NoSessionException()
except InvalidKeyIdException:
raise exceptions.InvalidKeyIdException()
except InvalidMessageException:
raise exceptions.InvalidMessageException()
except DuplicateMessageException:
raise exceptions.DuplicateMessageException()
def group_encrypt(self, groupid, message):
"""
:param groupid:
:type groupid: str
:param message:
:type message: bytes
:return:
:rtype:
"""
# to avoid the hassle of encoding issues and associated unnecessary crashes,
# don't log the message content.
# see https://github.com/tgalal/yowsup/issues/2732
logger.debug("group_encrypt(groupid=%s, message=[omitted])" % groupid)
group_cipher = self._get_group_cipher(groupid, self._username)
return group_cipher.encrypt(message + self._generate_random_padding())
def group_decrypt(self, groupid, participantid, data):
logger.debug("group_decrypt(groupid=%s, participantid=%s, data=[omitted])" % (groupid, participantid))
group_cipher = self._get_group_cipher(groupid, participantid)
try:
plaintext = group_cipher.decrypt(data)
plaintext = self._unpad(plaintext)
return plaintext
except NoSessionException:
raise exceptions.NoSessionException()
except DuplicateMessageException:
raise exceptions.DuplicateMessageException()
except InvalidMessageException:
raise exceptions.InvalidMessageException()
def group_create_skmsg(self, groupid):
logger.debug("group_create_skmsg(groupid=%s)" % groupid)
senderKeyName = SenderKeyName(groupid, AxolotlAddress(self._username, 0))
return self._group_session_builder.create(senderKeyName)
def group_create_session(self, groupid, participantid, skmsgdata):
"""
:param groupid:
:type groupid: str
:param participantid:
:type participantid: str
:param skmsgdata:
:type skmsgdata: bytearray
:return:
:rtype:
"""
logger.debug("group_create_session(groupid=%s, participantid=%s, skmsgdata=[omitted])"
% (groupid, participantid))
senderKeyName = SenderKeyName(groupid, AxolotlAddress(participantid, 0))
senderkeydistributionmessage = SenderKeyDistributionMessage(serialized=skmsgdata)
self._group_session_builder.process(senderKeyName, senderkeydistributionmessage)
def create_session(self, username, prekeybundle, autotrust=False):
"""
:param username:
:type username: str
:param prekeybundle:
:type prekeybundle: PreKeyBundle
:return:
:rtype:
"""
logger.debug("create_session(username=%s, prekeybundle=[omitted], autotrust=%s)" % (username, autotrust))
session_builder = SessionBuilder(self._store, self._store, self._store, self._store, username, 1)
try:
session_builder.processPreKeyBundle(prekeybundle)
except UntrustedIdentityException as ex:
if autotrust:
self.trust_identity(ex.getName(), ex.getIdentityKey())
else:
raise exceptions.UntrustedIdentityException(ex.getName(), ex.getIdentityKey())
def session_exists(self, username):
"""
:param username:
:type username: str
:return:
:rtype:
"""
logger.debug("session_exists(%s)?" % username)
return self._store.containsSession(username, 1)
def load_senderkey(self, groupid):
logger.debug("load_senderkey(groupid=%s)" % groupid)
senderkeyname = SenderKeyName(groupid, AxolotlAddress(self._username, 0))
return self._store.loadSenderKey(senderkeyname)
def trust_identity(self, recipientid, identitykey):
logger.debug("trust_identity(recipientid=%s, identitykey=[omitted])" % recipientid)
self._store.saveIdentity(recipientid, identitykey)
| 12,168 | Python | .py | 253 | 39.217391 | 113 | 0.677354 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,775 | exceptions.py | tgalal_yowsup/yowsup/axolotl/exceptions.py | class NoSessionException(Exception):
pass
class UntrustedIdentityException(Exception):
def __init__(self, name, identity_key):
self._name = name
self._identity_key = identity_key
@property
def name(self):
return self._name
@property
def identity_key(self):
return self._identity_key
class InvalidMessageException(Exception):
pass
class InvalidKeyIdException(Exception):
pass
class DuplicateMessageException(Exception):
pass
| 503 | Python | .py | 18 | 22.555556 | 44 | 0.723629 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,776 | liteprekeystore.py | tgalal_yowsup/yowsup/axolotl/store/sqlite/liteprekeystore.py | from axolotl.state.prekeystore import PreKeyStore
from axolotl.state.prekeyrecord import PreKeyRecord
from yowsup.axolotl.exceptions import InvalidKeyIdException
import sys
class LitePreKeyStore(PreKeyStore):
def __init__(self, dbConn):
"""
:type dbConn: Connection
"""
self.dbConn = dbConn
dbConn.execute("CREATE TABLE IF NOT EXISTS prekeys (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"prekey_id INTEGER UNIQUE, sent_to_server BOOLEAN, record BLOB);")
def loadPreKey(self, preKeyId):
q = "SELECT record FROM prekeys WHERE prekey_id = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (preKeyId,))
result = cursor.fetchone()
if not result:
raise InvalidKeyIdException("No such prekeyrecord!")
return PreKeyRecord(serialized = result[0])
def loadUnsentPendingPreKeys(self):
q = "SELECT record FROM prekeys WHERE sent_to_server is NULL or sent_to_server = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (0,))
result = cursor.fetchall()
return [PreKeyRecord(serialized=result[0]) for result in result]
def setAsSent(self, prekeyIds):
"""
:param preKeyIds:
:type preKeyIds: list
:return:
:rtype:
"""
for prekeyId in prekeyIds:
q = "UPDATE prekeys SET sent_to_server = ? WHERE prekey_id = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (1, prekeyId))
self.dbConn.commit()
def loadPendingPreKeys(self):
q = "SELECT record FROM prekeys"
cursor = self.dbConn.cursor()
cursor.execute(q)
result = cursor.fetchall()
return [PreKeyRecord(serialized=result[0]) for result in result]
def storePreKey(self, preKeyId, preKeyRecord):
#self.removePreKey(preKeyId)
q = "INSERT INTO prekeys (prekey_id, record) VALUES(?,?)"
cursor = self.dbConn.cursor()
serialized = preKeyRecord.serialize()
cursor.execute(q, (preKeyId, buffer(serialized) if sys.version_info < (2,7) else serialized))
self.dbConn.commit()
def containsPreKey(self, preKeyId):
q = "SELECT record FROM prekeys WHERE prekey_id = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (preKeyId,))
return cursor.fetchone() is not None
def removePreKey(self, preKeyId):
q = "DELETE FROM prekeys WHERE prekey_id = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (preKeyId,))
self.dbConn.commit()
def loadMaxPreKeyId(self):
q = "SELECT max(prekey_id) FROM prekeys"
cursor = self.dbConn.cursor()
cursor.execute(q)
result = cursor.fetchone()
return 0 if result[0] is None else result[0]
| 2,838 | Python | .py | 67 | 33.776119 | 101 | 0.64016 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,777 | liteidentitykeystore.py | tgalal_yowsup/yowsup/axolotl/store/sqlite/liteidentitykeystore.py | from axolotl.state.identitykeystore import IdentityKeyStore
from axolotl.identitykey import IdentityKey
from axolotl.identitykeypair import IdentityKeyPair
from axolotl.util.keyhelper import KeyHelper
from axolotl.ecc.djbec import *
import sys
class LiteIdentityKeyStore(IdentityKeyStore):
def __init__(self, dbConn):
"""
:type dbConn: Connection
"""
self.dbConn = dbConn
dbConn.execute("CREATE TABLE IF NOT EXISTS identities (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"recipient_id INTEGER UNIQUE,"
"registration_id INTEGER, public_key BLOB, private_key BLOB,"
"next_prekey_id INTEGER, timestamp INTEGER);")
if self.getLocalRegistrationId() is None or self.getIdentityKeyPair() is None:
identity = KeyHelper.generateIdentityKeyPair()
registration_id = KeyHelper.generateRegistrationId(True)
self._storeLocalData(registration_id, identity)
def getIdentityKeyPair(self):
q = "SELECT public_key, private_key FROM identities WHERE recipient_id = -1"
c = self.dbConn.cursor()
c.execute(q)
result = c.fetchone()
if result:
publicKey, privateKey = result
return IdentityKeyPair(IdentityKey(DjbECPublicKey(publicKey[1:])), DjbECPrivateKey(privateKey))
return None
def getLocalRegistrationId(self):
q = "SELECT registration_id FROM identities WHERE recipient_id = -1"
c = self.dbConn.cursor()
c.execute(q)
result = c.fetchone()
return result[0] if result else None
def _storeLocalData(self, registrationId, identityKeyPair):
q = "INSERT INTO identities(recipient_id, registration_id, public_key, private_key) VALUES(-1, ?, ?, ?)"
c = self.dbConn.cursor()
pubKey = identityKeyPair.getPublicKey().getPublicKey().serialize()
privKey = identityKeyPair.getPrivateKey().serialize()
if sys.version_info < (2,7):
pubKey = buffer(pubKey)
privKey = buffer(privKey)
c.execute(q, (registrationId,
pubKey,
privKey))
self.dbConn.commit()
def saveIdentity(self, recipientId, identityKey):
q = "DELETE FROM identities WHERE recipient_id=?"
self.dbConn.cursor().execute(q, (recipientId,))
self.dbConn.commit()
q = "INSERT INTO identities (recipient_id, public_key) VALUES(?, ?)"
c = self.dbConn.cursor()
pubKey = identityKey.getPublicKey().serialize()
c.execute(q, (recipientId, buffer(pubKey) if sys.version_info < (2,7) else pubKey))
self.dbConn.commit()
def isTrustedIdentity(self, recipientId, identityKey):
q = "SELECT public_key from identities WHERE recipient_id = ?"
c = self.dbConn.cursor()
c.execute(q, (recipientId,))
result = c.fetchone()
if not result:
return True
pubKey = identityKey.getPublicKey().serialize()
if sys.version_info < (2, 7):
pubKey = buffer(pubKey)
return result[0] == pubKey | 3,163 | Python | .py | 67 | 37.507463 | 112 | 0.647173 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,778 | liteaxolotlstore.py | tgalal_yowsup/yowsup/axolotl/store/sqlite/liteaxolotlstore.py | from axolotl.state.axolotlstore import AxolotlStore
from .liteidentitykeystore import LiteIdentityKeyStore
from .liteprekeystore import LitePreKeyStore
from .litesessionstore import LiteSessionStore
from .litesignedprekeystore import LiteSignedPreKeyStore
from .litesenderkeystore import LiteSenderKeyStore
import sqlite3
class LiteAxolotlStore(AxolotlStore):
def __init__(self, db):
conn = sqlite3.connect(db, check_same_thread=False)
conn.text_factory = bytes
self._db = db
self.identityKeyStore = LiteIdentityKeyStore(conn)
self.preKeyStore = LitePreKeyStore(conn)
self.signedPreKeyStore = LiteSignedPreKeyStore(conn)
self.sessionStore = LiteSessionStore(conn)
self.senderKeyStore = LiteSenderKeyStore(conn)
def __str__(self):
return self._db
def getIdentityKeyPair(self):
return self.identityKeyStore.getIdentityKeyPair()
def getLocalRegistrationId(self):
return self.identityKeyStore.getLocalRegistrationId()
def saveIdentity(self, recepientId, identityKey):
self.identityKeyStore.saveIdentity(recepientId, identityKey)
def isTrustedIdentity(self, recepientId, identityKey):
return self.identityKeyStore.isTrustedIdentity(recepientId, identityKey)
def loadPreKey(self, preKeyId):
return self.preKeyStore.loadPreKey(preKeyId)
def loadPreKeys(self):
return self.preKeyStore.loadPendingPreKeys()
def storePreKey(self, preKeyId, preKeyRecord):
self.preKeyStore.storePreKey(preKeyId, preKeyRecord)
def containsPreKey(self, preKeyId):
return self.preKeyStore.containsPreKey(preKeyId)
def removePreKey(self, preKeyId):
self.preKeyStore.removePreKey(preKeyId)
def loadSession(self, recepientId, deviceId):
return self.sessionStore.loadSession(recepientId, deviceId)
def getSubDeviceSessions(self, recepientId):
return self.sessionStore.getSubDeviceSessions(recepientId)
def storeSession(self, recepientId, deviceId, sessionRecord):
self.sessionStore.storeSession(recepientId, deviceId, sessionRecord)
def containsSession(self, recepientId, deviceId):
return self.sessionStore.containsSession(recepientId, deviceId)
def deleteSession(self, recepientId, deviceId):
self.sessionStore.deleteSession(recepientId, deviceId)
def deleteAllSessions(self, recepientId):
self.sessionStore.deleteAllSessions(recepientId)
def loadSignedPreKey(self, signedPreKeyId):
return self.signedPreKeyStore.loadSignedPreKey(signedPreKeyId)
def loadSignedPreKeys(self):
return self.signedPreKeyStore.loadSignedPreKeys()
def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):
self.signedPreKeyStore.storeSignedPreKey(signedPreKeyId, signedPreKeyRecord)
def containsSignedPreKey(self, signedPreKeyId):
return self.signedPreKeyStore.containsSignedPreKey(signedPreKeyId)
def removeSignedPreKey(self, signedPreKeyId):
self.signedPreKeyStore.removeSignedPreKey(signedPreKeyId)
def loadSenderKey(self, senderKeyName):
return self.senderKeyStore.loadSenderKey(senderKeyName)
def storeSenderKey(self, senderKeyName, senderKeyRecord):
self.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord)
| 3,343 | Python | .py | 63 | 46.206349 | 84 | 0.781567 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,779 | litesessionstore.py | tgalal_yowsup/yowsup/axolotl/store/sqlite/litesessionstore.py | from axolotl.state.sessionstore import SessionStore
from axolotl.state.sessionrecord import SessionRecord
import sys
class LiteSessionStore(SessionStore):
def __init__(self, dbConn):
"""
:type dbConn: Connection
"""
self.dbConn = dbConn
dbConn.execute("CREATE TABLE IF NOT EXISTS sessions (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"recipient_id INTEGER UNIQUE, device_id INTEGER, record BLOB, timestamp INTEGER);")
def loadSession(self, recipientId, deviceId):
q = "SELECT record FROM sessions WHERE recipient_id = ? AND device_id = ?"
c = self.dbConn.cursor()
c.execute(q, (recipientId, deviceId))
result = c.fetchone()
if result:
return SessionRecord(serialized=result[0])
else:
return SessionRecord()
def getSubDeviceSessions(self, recipientId):
q = "SELECT device_id from sessions WHERE recipient_id = ?"
c = self.dbConn.cursor()
c.execute(q, (recipientId,))
result = c.fetchall()
deviceIds = [r[0] for r in result]
return deviceIds
def storeSession(self, recipientId, deviceId, sessionRecord):
self.deleteSession(recipientId, deviceId)
q = "INSERT INTO sessions(recipient_id, device_id, record) VALUES(?,?,?)"
c = self.dbConn.cursor()
serialized = sessionRecord.serialize()
c.execute(q, (recipientId, deviceId, buffer(serialized) if sys.version_info < (2,7) else serialized))
self.dbConn.commit()
def containsSession(self, recipientId, deviceId):
q = "SELECT record FROM sessions WHERE recipient_id = ? AND device_id = ?"
c = self.dbConn.cursor()
c.execute(q, (recipientId, deviceId))
result = c.fetchone()
return result is not None
def deleteSession(self, recipientId, deviceId):
q = "DELETE FROM sessions WHERE recipient_id = ? AND device_id = ?"
self.dbConn.cursor().execute(q, (recipientId, deviceId))
self.dbConn.commit()
def deleteAllSessions(self, recipientId):
q = "DELETE FROM sessions WHERE recipient_id = ?"
self.dbConn.cursor().execute(q, (recipientId,))
self.dbConn.commit()
| 2,250 | Python | .py | 48 | 38.416667 | 109 | 0.654039 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,780 | litesignedprekeystore.py | tgalal_yowsup/yowsup/axolotl/store/sqlite/litesignedprekeystore.py | from axolotl.state.signedprekeystore import SignedPreKeyStore
from axolotl.state.signedprekeyrecord import SignedPreKeyRecord
from axolotl.invalidkeyidexception import InvalidKeyIdException
import sys
class LiteSignedPreKeyStore(SignedPreKeyStore):
def __init__(self, dbConn):
"""
:type dbConn: Connection
"""
self.dbConn = dbConn
dbConn.execute("CREATE TABLE IF NOT EXISTS signed_prekeys (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"prekey_id INTEGER UNIQUE, timestamp INTEGER, record BLOB);")
def loadSignedPreKey(self, signedPreKeyId):
q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (signedPreKeyId,))
result = cursor.fetchone()
if not result:
raise InvalidKeyIdException("No such signedprekeyrecord! %s " % signedPreKeyId)
return SignedPreKeyRecord(serialized=result[0])
def loadSignedPreKeys(self):
q = "SELECT record FROM signed_prekeys"
cursor = self.dbConn.cursor()
cursor.execute(q,)
result = cursor.fetchall()
results = []
for row in result:
results.append(SignedPreKeyRecord(serialized=row[0]))
return results
def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):
#q = "DELETE FROM signed_prekeys WHERE prekey_id = ?"
#self.dbConn.cursor().execute(q, (signedPreKeyId,))
#self.dbConn.commit()
q = "INSERT INTO signed_prekeys (prekey_id, record) VALUES(?,?)"
cursor = self.dbConn.cursor()
record = signedPreKeyRecord.serialize()
cursor.execute(q, (signedPreKeyId, buffer(record) if sys.version_info < (2,7) else record))
self.dbConn.commit()
def containsSignedPreKey(self, signedPreKeyId):
q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (signedPreKeyId,))
return cursor.fetchone() is not None
def removeSignedPreKey(self, signedPreKeyId):
q = "DELETE FROM signed_prekeys WHERE prekey_id = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (signedPreKeyId,))
self.dbConn.commit()
| 2,274 | Python | .py | 48 | 38.979167 | 106 | 0.6757 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,781 | litesenderkeystore.py | tgalal_yowsup/yowsup/axolotl/store/sqlite/litesenderkeystore.py | from axolotl.groups.state.senderkeystore import SenderKeyStore
from axolotl.groups.state.senderkeyrecord import SenderKeyRecord
import sqlite3
import sys
class LiteSenderKeyStore(SenderKeyStore):
def __init__(self, dbConn):
"""
:type dbConn: Connection
"""
self.dbConn = dbConn
dbConn.execute("CREATE TABLE IF NOT EXISTS sender_keys (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"group_id TEXT NOT NULL,"
"sender_id INTEGER NOT NULL, record BLOB);")
dbConn.execute("CREATE UNIQUE INDEX IF NOT EXISTS sender_keys_idx ON sender_keys (group_id, sender_id);")
def storeSenderKey(self, senderKeyName, senderKeyRecord):
"""
:type senderKeyName: SenderKeName
:type senderKeyRecord: SenderKeyRecord
"""
q = "INSERT OR REPLACE INTO sender_keys (group_id, sender_id, record) VALUES(?,?, ?)"
cursor = self.dbConn.cursor()
serialized = senderKeyRecord.serialize()
if sys.version_info < (2,7):
serialized = buffer(serialized)
try:
cursor.execute(q, (senderKeyName.getGroupId(), senderKeyName.getSender().getName(), serialized))
self.dbConn.commit()
except sqlite3.IntegrityError as e:
q = "UPDATE sender_keys set record = ? WHERE group_id = ? and sender_id = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (serialized, senderKeyName.getGroupId(), senderKeyName.getSender().getName()))
self.dbConn.commit()
def loadSenderKey(self, senderKeyName):
"""
:type senderKeyName: SenderKeyName
"""
q = "SELECT record FROM sender_keys WHERE group_id = ? and sender_id = ?"
cursor = self.dbConn.cursor()
cursor.execute(q, (senderKeyName.getGroupId(), senderKeyName.getSender().getName()))
result = cursor.fetchone()
if not result:
return SenderKeyRecord()
return SenderKeyRecord(serialized = result[0])
| 2,036 | Python | .py | 43 | 38.023256 | 113 | 0.644545 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,782 | profile.py | tgalal_yowsup/yowsup/profile/profile.py | from yowsup.config.manager import ConfigManager
from yowsup.config.v1.config import Config
from yowsup.axolotl.manager import AxolotlManager
from yowsup.axolotl.factory import AxolotlManagerFactory
import logging
logger = logging.getLogger(__name__)
class YowProfile(object):
def __init__(self, profile_name, config=None):
# type: (str, Config) -> None
"""
:param profile_name: profile name
:param config: A supplied config will disable loading configs using the Config manager and provide that config
instead
"""
logger.debug("Constructed Profile(profile_name=%s)" % profile_name)
self._profile_name = profile_name
self._config = config
self._config_manager = ConfigManager()
self._axolotl_manager = None
def __str__(self):
return "YowProfile(profile_name=%s)" % self._profile_name
def _load_config(self):
# type: () -> Config
logger.debug("load_config for %s" % self._profile_name)
return self._config_manager.load(self._profile_name)
def _load_axolotl_manager(self):
# type: () -> AxolotlManager
return AxolotlManagerFactory().get_manager(self._profile_name, self.username)
def write_config(self, config):
# type: (Config) -> None
logger.debug("write_config for %s" % self._profile_name)
self._config_manager.save(self._profile_name, config)
@property
def config(self):
if self._config is None:
self._config = self._load_config()
return self._config
@property
def axolotl_manager(self):
if self._axolotl_manager is None:
self._axolotl_manager = self._load_axolotl_manager()
return self._axolotl_manager
@property
def username(self):
config = self.config
return config.login or config.phone or self._profile_name
| 1,902 | Python | .py | 46 | 34.130435 | 118 | 0.665222 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,783 | stack.py | tgalal_yowsup/yowsup/demos/contacts/stack.py | from .layer import SyncLayer
from yowsup.stacks import YowStackBuilder
from yowsup.layers import YowLayerEvent
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.network import YowNetworkLayer
class YowsupSyncStack(object):
def __init__(self, profile, contacts):
"""
:param profile:
:param contacts: list of [jid ]
:return:
"""
stackBuilder = YowStackBuilder()
self._stack = stackBuilder \
.pushDefaultLayers() \
.push(SyncLayer) \
.build()
self._stack.setProp(SyncLayer.PROP_CONTACTS, contacts)
self._stack.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True)
self._stack.setProfile(profile)
def set_prop(self, key, val):
self._stack.setProp(key, val)
def start(self):
self._stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
self._stack.loop()
| 964 | Python | .py | 25 | 31.2 | 86 | 0.684549 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,784 | layer.py | tgalal_yowsup/yowsup/demos/contacts/layer.py | from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_contacts.protocolentities import GetSyncIqProtocolEntity, ResultSyncIqProtocolEntity
from yowsup.layers.protocol_iq.protocolentities import ErrorIqProtocolEntity
import threading
import logging
logger = logging.getLogger(__name__)
class SyncLayer(YowInterfaceLayer):
PROP_CONTACTS = "org.openwhatsapp.yowsup.prop.syncdemo.contacts"
def __init__(self):
super(SyncLayer, self).__init__()
#call back function when there is a successful connection to whatsapp server
@ProtocolEntityCallback("success")
def onSuccess(self, successProtocolEntity):
contacts= self.getProp(self.__class__.PROP_CONTACTS, [])
contactEntity = GetSyncIqProtocolEntity(contacts)
self._sendIq(contactEntity, self.onGetSyncResult, self.onGetSyncError)
def onGetSyncResult(self, resultSyncIqProtocolEntity, originalIqProtocolEntity):
print(resultSyncIqProtocolEntity)
raise KeyboardInterrupt()
def onGetSyncError(self, errorSyncIqProtocolEntity, originalIqProtocolEntity):
print(errorSyncIqProtocolEntity)
raise KeyboardInterrupt()
| 1,230 | Python | .py | 22 | 50.454545 | 113 | 0.777038 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,785 | sink_worker.py | tgalal_yowsup/yowsup/demos/common/sink_worker.py | from yowsup.layers.protocol_media.mediacipher import MediaCipher
from yowsup.layers.protocol_media.protocolentities \
import ImageDownloadableMediaMessageProtocolEntity, AudioDownloadableMediaMessageProtocolEntity,\
VideoDownloadableMediaMessageProtocolEntity, DocumentDownloadableMediaMessageProtocolEntity, \
ContactMediaMessageProtocolEntity, DownloadableMediaMessageProtocolEntity, \
StickerDownloadableMediaMessageProtocolEntity
import threading
from tqdm import tqdm
import requests
import logging
import math
import sys
import os
import base64
if sys.version_info >= (3, 0):
from queue import Queue
else:
from Queue import Queue
logger = logging.getLogger(__name__)
class SinkWorker(threading.Thread):
def __init__(self, storage_dir):
super(SinkWorker, self).__init__()
self.daemon = True
self._storage_dir = storage_dir
self._jobs = Queue()
self._media_cipher = MediaCipher()
def enqueue(self, media_message_protocolentity):
self._jobs.put(media_message_protocolentity)
def _create_progress_iterator(self, iterable, niterations, desc):
return tqdm(
iterable, total=niterations, unit='KB', dynamic_ncols=True,
unit_scale=True, leave=True, desc=desc, ascii=True)
def _download(self, url):
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
logger.debug("%s total size is %s, downloading" % (url, total_size))
block_size = 1024
wrote = 0
enc_data = b""
for data in self._create_progress_iterator(
response.iter_content(block_size), math.ceil(total_size // block_size) + 1, "Download ",
):
wrote = wrote + len(data)
enc_data = enc_data + data
if total_size != 0 and wrote != total_size:
logger.error("Something went wrong")
return None
return enc_data
def _decrypt(self, ciphertext, ref_key, media_info):
length_kb = int(math.ceil(len(ciphertext) / 1024))
progress = self._create_progress_iterator(range(length_kb), length_kb, "Decrypt ")
try:
plaintext = self._media_cipher.decrypt(ciphertext, ref_key, media_info)
progress.update(length_kb)
return plaintext
except Exception as e:
progress.set_description("Decrypt Error ")
logger.error(e)
return None
def _write(self, data, filename):
length_kb = int(math.ceil(len(data) / 1024))
progress = self._create_progress_iterator(range(length_kb), length_kb, "Write ")
try:
with open(filename, 'wb') as f:
f.write(data)
progress.update(length_kb)
return filename
except Exception as e:
progress.set_description("Write error ")
logger.error(e)
return None
def _create_unique_filepath(self, filepath):
file_dir = os.path.dirname(filepath)
filename = os.path.basename(filepath)
result_filename = filename
dissected = os.path.splitext(filename)
count = 0
while os.path.exists(os.path.join(file_dir, result_filename)):
count += 1
result_filename = "%s_%d%s" % (dissected[0], count, dissected[1])
return os.path.join(file_dir, result_filename)
def run(self):
logger.debug(
"SinkWorker started, storage_dir=%s" % self._storage_dir
)
while True:
media_message_protocolentity = self._jobs.get()
if media_message_protocolentity is None:
sys.exit(0)
if isinstance(media_message_protocolentity, DownloadableMediaMessageProtocolEntity):
logger.info(
"Processing [url=%s, media_key=%s]" %
(media_message_protocolentity.url, base64.b64encode(media_message_protocolentity.media_key))
)
else:
logger.info("Processing %s" % media_message_protocolentity.media_type)
filedata = None
fileext = None
if isinstance(media_message_protocolentity, ImageDownloadableMediaMessageProtocolEntity):
media_info = MediaCipher.INFO_IMAGE
filename = "image"
elif isinstance(media_message_protocolentity, AudioDownloadableMediaMessageProtocolEntity):
media_info = MediaCipher.INFO_AUDIO
filename = "ptt" if media_message_protocolentity.ptt else "audio"
elif isinstance(media_message_protocolentity, VideoDownloadableMediaMessageProtocolEntity):
media_info = MediaCipher.INFO_VIDEO
filename = "video"
elif isinstance(media_message_protocolentity, DocumentDownloadableMediaMessageProtocolEntity):
media_info = MediaCipher.INFO_DOCUM
filename = media_message_protocolentity.file_name
elif isinstance(media_message_protocolentity, ContactMediaMessageProtocolEntity):
filename = media_message_protocolentity.display_name
filedata = media_message_protocolentity.vcard
fileext = "vcard"
elif isinstance(media_message_protocolentity, StickerDownloadableMediaMessageProtocolEntity):
media_info = MediaCipher.INFO_IMAGE
filename = "sticker"
else:
logger.error("Unsupported Media type: %s" % media_message_protocolentity.__class__)
sys.exit(1)
if filedata is None:
enc_data = self._download(media_message_protocolentity.url)
if enc_data is None:
logger.error("Download failed")
sys.exit(1)
filedata = self._decrypt(enc_data, media_message_protocolentity.media_key, media_info)
if filedata is None:
logger.error("Decrypt failed")
sys.exit(1)
if not isinstance(media_message_protocolentity, DocumentDownloadableMediaMessageProtocolEntity):
if fileext is None:
fileext = media_message_protocolentity.mimetype.split('/')[1].split(';')[0]
filename_full = "%s.%s" % (filename, fileext)
else:
filename_full = filename
filepath = self._create_unique_filepath(os.path.join(self._storage_dir, filename_full))
if self._write(filedata, filepath):
logger.info("Wrote %s" % filepath)
else:
sys.exit(1)
| 6,733 | Python | .py | 140 | 36.621429 | 112 | 0.62715 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,786 | stack.py | tgalal_yowsup/yowsup/demos/echoclient/stack.py | from yowsup.stacks import YowStackBuilder
from .layer import EchoLayer
from yowsup.layers import YowLayerEvent
from yowsup.layers.network import YowNetworkLayer
class YowsupEchoStack(object):
def __init__(self, profile):
stackBuilder = YowStackBuilder()
self._stack = stackBuilder\
.pushDefaultLayers()\
.push(EchoLayer)\
.build()
self._stack.setProfile(profile)
def set_prop(self, key, val):
self._stack.setProp(key, val)
def start(self):
self._stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
self._stack.loop()
| 641 | Python | .py | 17 | 30.705882 | 86 | 0.692557 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,787 | layer.py | tgalal_yowsup/yowsup/demos/echoclient/layer.py | from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
class EchoLayer(YowInterfaceLayer):
@ProtocolEntityCallback("message")
def onMessage(self, messageProtocolEntity):
if messageProtocolEntity.getType() == 'text':
self.onTextMessage(messageProtocolEntity)
elif messageProtocolEntity.getType() == 'media':
self.onMediaMessage(messageProtocolEntity)
self.toLower(messageProtocolEntity.forward(messageProtocolEntity.getFrom()))
self.toLower(messageProtocolEntity.ack())
self.toLower(messageProtocolEntity.ack(True))
@ProtocolEntityCallback("receipt")
def onReceipt(self, entity):
self.toLower(entity.ack())
def onTextMessage(self,messageProtocolEntity):
# just print info
print("Echoing %s to %s" % (messageProtocolEntity.getBody(), messageProtocolEntity.getFrom(False)))
def onMediaMessage(self, messageProtocolEntity):
# just print info
if messageProtocolEntity.media_type == "image":
print("Echoing image %s to %s" % (messageProtocolEntity.url, messageProtocolEntity.getFrom(False)))
elif messageProtocolEntity.media_type == "location":
print("Echoing location (%s, %s) to %s" % (messageProtocolEntity.getLatitude(), messageProtocolEntity.getLongitude(), messageProtocolEntity.getFrom(False)))
elif messageProtocolEntity.media_type == "contact":
print("Echoing contact (%s, %s) to %s" % (messageProtocolEntity.getName(), messageProtocolEntity.getCardData(), messageProtocolEntity.getFrom(False)))
| 1,638 | Python | .py | 25 | 56.92 | 168 | 0.718029 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,788 | stack.py | tgalal_yowsup/yowsup/demos/sendclient/stack.py | from yowsup.stacks import YowStackBuilder
from .layer import SendLayer
from yowsup.layers import YowLayerEvent
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.network import YowNetworkLayer
class YowsupSendStack(object):
def __init__(self, profile, messages):
"""
:param profile:
:param messages: list of (jid, message) tuples
:return:
"""
stackBuilder = YowStackBuilder()
self._stack = stackBuilder\
.pushDefaultLayers()\
.push(SendLayer)\
.build()
self._stack.setProp(SendLayer.PROP_MESSAGES, messages)
self._stack.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True)
self._stack.setProfile(profile)
def set_prop(self, key, val):
self._stack.setProp(key, val)
def start(self):
self._stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
self._stack.loop()
| 975 | Python | .py | 25 | 31.68 | 86 | 0.689619 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,789 | layer.py | tgalal_yowsup/yowsup/demos/sendclient/layer.py | from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
from yowsup.common.tools import Jid
import threading
import logging
logger = logging.getLogger(__name__)
class SendLayer(YowInterfaceLayer):
#This message is going to be replaced by the @param message in YowsupSendStack construction
#i.e. list of (jid, message) tuples
PROP_MESSAGES = "org.openwhatsapp.yowsup.prop.sendclient.queue"
def __init__(self):
super(SendLayer, self).__init__()
self.ackQueue = []
self.lock = threading.Condition()
#call back function when there is a successful connection to whatsapp server
@ProtocolEntityCallback("success")
def onSuccess(self, successProtocolEntity):
self.lock.acquire()
for target in self.getProp(self.__class__.PROP_MESSAGES, []):
#getProp() is trying to retreive the list of (jid, message) tuples, if none exist, use the default []
phone, message = target
messageEntity = TextMessageProtocolEntity(message, to = Jid.normalize(phone))
#append the id of message to ackQueue list
#which the id of message will be deleted when ack is received.
self.ackQueue.append(messageEntity.getId())
self.toLower(messageEntity)
self.lock.release()
#after receiving the message from the target number, target number will send a ack to sender(us)
@ProtocolEntityCallback("ack")
def onAck(self, entity):
self.lock.acquire()
#if the id match the id in ackQueue, then pop the id of the message out
if entity.getId() in self.ackQueue:
self.ackQueue.pop(self.ackQueue.index(entity.getId()))
if not len(self.ackQueue):
self.lock.release()
logger.info("Message sent")
raise KeyboardInterrupt()
self.lock.release()
| 2,017 | Python | .py | 39 | 43.333333 | 113 | 0.687692 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,790 | stack.py | tgalal_yowsup/yowsup/demos/cli/stack.py | from yowsup.stacks import YowStackBuilder
from .layer import YowsupCliLayer
from yowsup.layers import YowLayerEvent
from yowsup.layers.axolotl.props import PROP_IDENTITY_AUTOTRUST
import sys
class YowsupCliStack(object):
def __init__(self, profile):
stackBuilder = YowStackBuilder()
self._stack = stackBuilder\
.pushDefaultLayers()\
.push(YowsupCliLayer)\
.build()
self._stack.setProfile(profile)
self._stack.setProp(PROP_IDENTITY_AUTOTRUST, True)
def set_prop(self, prop, val):
self._stack.setProp(prop, val)
def start(self):
print("Yowsup Cli client\n==================\nType /help for available commands\n")
self._stack.broadcastEvent(YowLayerEvent(YowsupCliLayer.EVENT_START))
try:
self._stack.loop()
except KeyboardInterrupt:
print("\nYowsdown")
sys.exit(0)
| 927 | Python | .py | 24 | 30.833333 | 91 | 0.659598 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,791 | layer.py | tgalal_yowsup/yowsup/demos/cli/layer.py | from .cli import Cli, clicmd
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers import YowLayerEvent, EventCallback
from yowsup.layers.network import YowNetworkLayer
import sys
from yowsup.common import YowConstants
import datetime
import time
import os
import logging
import threading
import base64
from yowsup.layers.protocol_groups.protocolentities import *
from yowsup.layers.protocol_presence.protocolentities import *
from yowsup.layers.protocol_messages.protocolentities import *
from yowsup.layers.protocol_ib.protocolentities import *
from yowsup.layers.protocol_iq.protocolentities import *
from yowsup.layers.protocol_contacts.protocolentities import *
from yowsup.layers.protocol_chatstate.protocolentities import *
from yowsup.layers.protocol_privacy.protocolentities import *
from yowsup.layers.protocol_media.protocolentities import *
from yowsup.layers.protocol_media.mediauploader import MediaUploader
from yowsup.layers.protocol_profiles.protocolentities import *
from yowsup.common.tools import Jid
from yowsup.common.optionalmodules import PILOptionalModule
from yowsup.layers.axolotl.protocolentities.iq_key_get import GetKeysIqProtocolEntity
logger = logging.getLogger(__name__)
class YowsupCliLayer(Cli, YowInterfaceLayer):
PROP_RECEIPT_AUTO = "org.openwhatsapp.yowsup.prop.cli.autoreceipt"
PROP_RECEIPT_KEEPALIVE = "org.openwhatsapp.yowsup.prop.cli.keepalive"
PROP_CONTACT_JID = "org.openwhatsapp.yowsup.prop.cli.contact.jid"
EVENT_LOGIN = "org.openwhatsapp.yowsup.event.cli.login"
EVENT_START = "org.openwhatsapp.yowsup.event.cli.start"
EVENT_SENDANDEXIT = "org.openwhatsapp.yowsup.event.cli.sendandexit"
MESSAGE_FORMAT = "[%s(%s)]:[%s]\t %s"
FAIL_OPT_PILLOW = "No PIL library installed, try install pillow"
FAIL_OPT_AXOLOTL = "axolotl is not installed, try install python-axolotl"
DISCONNECT_ACTION_PROMPT = 0
DISCONNECT_ACTION_EXIT = 1
ACCOUNT_DEL_WARNINGS = 4
def __init__(self):
super(YowsupCliLayer, self).__init__()
YowInterfaceLayer.__init__(self)
self.accountDelWarnings = 0
self.connected = False
self.username = None
self.sendReceipts = True
self.sendRead = True
self.disconnectAction = self.__class__.DISCONNECT_ACTION_PROMPT
#add aliases to make it user to use commands. for example you can then do:
# /message send foobar "HI"
# and then it will get automaticlaly mapped to foobar's jid
self.jidAliases = {
# "NAME": "PHONE@s.whatsapp.net"
}
def aliasToJid(self, calias):
for alias, ajid in self.jidAliases.items():
if calias.lower() == alias.lower():
return Jid.normalize(ajid)
return Jid.normalize(calias)
def jidToAlias(self, jid):
for alias, ajid in self.jidAliases.items():
if ajid == jid:
return alias
return jid
@EventCallback(EVENT_START)
def onStart(self, layerEvent):
self.startInput()
return True
@EventCallback(YowNetworkLayer.EVENT_STATE_DISCONNECTED)
def onStateDisconnected(self,layerEvent):
self.output("Disconnected: %s" % layerEvent.getArg("reason"))
if self.disconnectAction == self.__class__.DISCONNECT_ACTION_PROMPT:
self.connected = False
self.notifyInputThread()
else:
os._exit(os.EX_OK)
def assertConnected(self):
if self.connected:
return True
else:
self.output("Not connected", tag = "Error", prompt = False)
return False
########## PRESENCE ###############
@clicmd("Set presence name")
def presence_name(self, name):
if self.assertConnected():
entity = PresenceProtocolEntity(name = name)
self.toLower(entity)
@clicmd("Set presence as available")
def presence_available(self):
if self.assertConnected():
entity = AvailablePresenceProtocolEntity()
self.toLower(entity)
@clicmd("Set presence as unavailable")
def presence_unavailable(self):
if self.assertConnected():
entity = UnavailablePresenceProtocolEntity()
self.toLower(entity)
@clicmd("Unsubscribe from contact's presence updates")
def presence_unsubscribe(self, contact):
if self.assertConnected():
entity = UnsubscribePresenceProtocolEntity(self.aliasToJid(contact))
self.toLower(entity)
@clicmd("Subscribe to contact's presence updates")
def presence_subscribe(self, contact):
if self.assertConnected():
entity = SubscribePresenceProtocolEntity(self.aliasToJid(contact))
self.toLower(entity)
########### END PRESENCE #############
########### ib #######################
@clicmd("Send clean dirty")
def ib_clean(self, dirtyType):
if self.assertConnected():
entity = CleanIqProtocolEntity("groups", YowConstants.DOMAIN)
self.toLower(entity)
@clicmd("Ping server")
def ping(self):
if self.assertConnected():
entity = PingIqProtocolEntity(to = YowConstants.DOMAIN)
self.toLower(entity)
######################################
####### contacts/ profiles ####################
@clicmd("Set status text")
def profile_setStatus(self, text):
if self.assertConnected():
def onSuccess(resultIqEntity, originalIqEntity):
self.output("Status updated successfully")
def onError(errorIqEntity, originalIqEntity):
logger.error("Error updating status")
entity = SetStatusIqProtocolEntity(text)
self._sendIq(entity, onSuccess, onError)
@clicmd("Get profile picture for contact")
def contact_picture(self, jid):
if self.assertConnected():
entity = GetPictureIqProtocolEntity(self.aliasToJid(jid), preview=False)
self._sendIq(entity, self.onGetContactPictureResult)
@clicmd("Get profile picture preview for contact")
def contact_picturePreview(self, jid):
if self.assertConnected():
entity = GetPictureIqProtocolEntity(self.aliasToJid(jid), preview=True)
self._sendIq(entity, self.onGetContactPictureResult)
@clicmd("Get lastseen for contact")
def contact_lastseen(self, jid):
if self.assertConnected():
def onSuccess(resultIqEntity, originalIqEntity):
self.output("%s lastseen %s seconds ago" % (resultIqEntity.getFrom(), resultIqEntity.getSeconds()))
def onError(errorIqEntity, originalIqEntity):
logger.error("Error getting lastseen information for %s" % originalIqEntity.getTo())
entity = LastseenIqProtocolEntity(self.aliasToJid(jid))
self._sendIq(entity, onSuccess, onError)
@clicmd("Set profile picture")
def profile_setPicture(self, path):
if self.assertConnected():
with PILOptionalModule(failMessage = "No PIL library installed, try install pillow") as imp:
Image = imp("Image")
def onSuccess(resultIqEntity, originalIqEntity):
self.output("Profile picture updated successfully")
def onError(errorIqEntity, originalIqEntity):
logger.error("Error updating profile picture")
#example by @aesedepece in https://github.com/tgalal/yowsup/pull/781
#modified to support python3
src = Image.open(path)
pictureData = src.resize((640, 640)).tobytes("jpeg", "RGB")
picturePreview = src.resize((96, 96)).tobytes("jpeg", "RGB")
iq = SetPictureIqProtocolEntity(self.getOwnJid(), picturePreview, pictureData)
self._sendIq(iq, onSuccess, onError)
@clicmd("Get profile privacy")
def profile_getPrivacy(self):
if self.assertConnected():
def onSuccess(resultIqEntity, originalIqEntity):
self.output("Profile privacy is: %s" %(resultIqEntity))
def onError(errorIqEntity, originalIqEntity):
logger.error("Error getting profile privacy")
iq = GetPrivacyIqProtocolEntity()
self._sendIq(iq, onSuccess, onError)
@clicmd("Profile privacy. value=all|contacts|none names=profile|status|last. Names are comma separated, defaults to all.")
def profile_setPrivacy(self, value="all", names=None):
if self.assertConnected():
def onSuccess(resultIqEntity, originalIqEntity):
self.output("Profile privacy set to: %s" %(resultIqEntity))
def onError(errorIqEntity, originalIqEntity):
logger.error("Error setting profile privacy")
try:
names = [name for name in names.split(',')] if names else None
iq = SetPrivacyIqProtocolEntity(value, names)
self._sendIq(iq, onSuccess, onError)
except Exception as inst:
self.output(inst.message)
return self.print_usage()
########### groups
@clicmd("List all groups you belong to", 5)
def groups_list(self):
if self.assertConnected():
entity = ListGroupsIqProtocolEntity()
self.toLower(entity)
@clicmd("Leave a group you belong to", 4)
def group_leave(self, group_jid):
if self.assertConnected():
entity = LeaveGroupsIqProtocolEntity([self.aliasToJid(group_jid)])
self.toLower(entity)
@clicmd("Create a new group with the specified subject and participants. Jids are a comma separated list but optional.", 3)
def groups_create(self, subject, jids = None):
if self.assertConnected():
jids = [self.aliasToJid(jid) for jid in jids.split(',')] if jids else []
entity = CreateGroupsIqProtocolEntity(subject, participants=jids)
self.toLower(entity)
@clicmd("Invite to group. Jids are a comma separated list")
def group_invite(self, group_jid, jids):
if self.assertConnected():
jids = [self.aliasToJid(jid) for jid in jids.split(',')]
entity = AddParticipantsIqProtocolEntity(self.aliasToJid(group_jid), jids)
self.toLower(entity)
@clicmd("Promote admin of a group. Jids are a comma separated list")
def group_promote(self, group_jid, jids):
if self.assertConnected():
jids = [self.aliasToJid(jid) for jid in jids.split(',')]
entity = PromoteParticipantsIqProtocolEntity(self.aliasToJid(group_jid), jids)
self.toLower(entity)
@clicmd("Remove admin of a group. Jids are a comma separated list")
def group_demote(self, group_jid, jids):
if self.assertConnected():
jids = [self.aliasToJid(jid) for jid in jids.split(',')]
entity = DemoteParticipantsIqProtocolEntity(self.aliasToJid(group_jid), jids)
self.toLower(entity)
@clicmd("Kick from group. Jids are a comma separated list")
def group_kick(self, group_jid, jids):
if self.assertConnected():
jids = [self.aliasToJid(jid) for jid in jids.split(',')]
entity = RemoveParticipantsIqProtocolEntity(self.aliasToJid(group_jid), jids)
self.toLower(entity)
@clicmd("Change group subject")
def group_setSubject(self, group_jid, subject):
if self.assertConnected():
entity = SubjectGroupsIqProtocolEntity(self.aliasToJid(group_jid), subject)
self.toLower(entity)
@clicmd("Set group picture")
def group_picture(self, group_jid, path):
if self.assertConnected():
with PILOptionalModule(failMessage = self.__class__.FAIL_OPT_PILLOW) as imp:
Image = imp("Image")
def onSuccess(resultIqEntity, originalIqEntity):
self.output("Group picture updated successfully")
def onError(errorIqEntity, originalIqEntity):
logger.error("Error updating Group picture")
#example by @aesedepece in https://github.com/tgalal/yowsup/pull/781
#modified to support python3
src = Image.open(path)
pictureData = src.resize((640, 640)).tobytes("jpeg", "RGB")
picturePreview = src.resize((96, 96)).tobytes("jpeg", "RGB")
iq = SetPictureIqProtocolEntity(self.aliasToJid(group_jid), picturePreview, pictureData)
self._sendIq(iq, onSuccess, onError)
@clicmd("Get group info")
def group_info(self, group_jid):
if self.assertConnected():
entity = InfoGroupsIqProtocolEntity(self.aliasToJid(group_jid))
self.toLower(entity)
@clicmd("Get shared keys")
def keys_get(self, jids):
if self.assertConnected():
jids = [self.aliasToJid(jid) for jid in jids.split(',')]
entity = GetKeysIqProtocolEntity(jids)
self.toLower(entity)
@clicmd("Send init seq")
def seq(self):
priv = PrivacyListIqProtocolEntity()
self.toLower(priv)
push = PushIqProtocolEntity()
self.toLower(push)
props = PropsIqProtocolEntity()
self.toLower(props)
crypto = CryptoIqProtocolEntity()
self.toLower(crypto)
@clicmd("Delete your account")
def account_delete(self):
if self.assertConnected():
if self.accountDelWarnings < self.__class__.ACCOUNT_DEL_WARNINGS:
self.accountDelWarnings += 1
remaining = self.__class__.ACCOUNT_DEL_WARNINGS - self.accountDelWarnings
self.output("Repeat delete command another %s times to send the delete request" % remaining, tag="Account delete Warning !!", prompt = False)
else:
entity = UnregisterIqProtocolEntity()
self.toLower(entity)
@clicmd("Send message to a friend")
def message_send(self, number, content):
if self.assertConnected():
outgoingMessage = TextMessageProtocolEntity(content, to=self.aliasToJid(number))
self.toLower(outgoingMessage)
@clicmd("Broadcast message. numbers should comma separated phone numbers")
def message_broadcast(self, numbers, content):
if self.assertConnected():
jids = [self.aliasToJid(number) for number in numbers.split(',')]
outgoingMessage = BroadcastTextMessage(jids, content)
self.toLower(outgoingMessage)
#@clicmd("Send read receipt")
def message_read(self, message_id):
pass
#@clicmd("Send delivered receipt")
def message_delivered(self, message_id):
pass
@clicmd("Send a video with optional caption")
def video_send(self, number, path, caption = None):
self.media_send(number, path, RequestUploadIqProtocolEntity.MEDIA_TYPE_VIDEO)
@clicmd("Send an image with optional caption")
def image_send(self, number, path, caption = None):
self.media_send(number, path, RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE)
@clicmd("Send audio file")
def audio_send(self, number, path):
self.media_send(number, path, RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO)
def media_send(self, number, path, mediaType, caption = None):
if self.assertConnected():
jid = self.aliasToJid(number)
entity = RequestUploadIqProtocolEntity(mediaType, filePath=path)
successFn = lambda successEntity, originalEntity: self.onRequestUploadResult(jid, mediaType, path, successEntity, originalEntity, caption)
errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError(jid, path, errorEntity, originalEntity)
self._sendIq(entity, successFn, errorFn)
@clicmd("Send typing state")
def state_typing(self, jid):
if self.assertConnected():
entity = OutgoingChatstateProtocolEntity(ChatstateProtocolEntity.STATE_TYPING, self.aliasToJid(jid))
self.toLower(entity)
@clicmd("Request contacts statuses")
def statuses_get(self, contacts):
def on_success(entity, original_iq_entity):
# type: (ResultStatusesIqProtocolEntity, GetStatusesIqProtocolEntity) -> None
status_outs = []
for jid, status_info in entity.statuses.items():
status_outs.append("[user=%s status=%s last_updated=%s]" % (jid, status_info[0], status_info[1]))
self.output("\n".join(status_outs), tag="statuses_get result")
def on_error(entity, original_iq):
# type: (ResultStatusesIqProtocolEntity, GetStatusesIqProtocolEntity) -> None
logger.error("Failed to get statuses")
if self.assertConnected():
entity = GetStatusesIqProtocolEntity([self.aliasToJid(c) for c in contacts.split(',')])
self._sendIq(entity, on_success, on_error)
@clicmd("Send paused state")
def state_paused(self, jid):
if self.assertConnected():
entity = OutgoingChatstateProtocolEntity(ChatstateProtocolEntity.STATE_PAUSED, self.aliasToJid(jid))
self.toLower(entity)
@clicmd("Sync contacts, contacts should be comma separated phone numbers, with no spaces")
def contacts_sync(self, contacts):
if self.assertConnected():
entity = GetSyncIqProtocolEntity(contacts.split(','))
self.toLower(entity)
@clicmd("Disconnect")
def disconnect(self):
if self.assertConnected():
self.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
@clicmd("Quick login")
def L(self):
if self.connected:
return self.output("Already connected, disconnect first")
threading.Thread(target=lambda: self.getLayerInterface(YowNetworkLayer).connect()).start()
return True
######## receive #########
@ProtocolEntityCallback("presence")
def onPresenceChange(self, entity):
status="offline"
if entity.getType() is None:
status="online"
##raw fix for iphone lastseen deny output
lastseen = entity.getLast()
if status is "offline" and lastseen is "deny":
lastseen = time.time()
##
self.output("%s %s %s lastseen at: %s" % (entity.getFrom(), entity.getTag(), status, lastseen))
@ProtocolEntityCallback("chatstate")
def onChatstate(self, entity):
print(entity)
@ProtocolEntityCallback("iq")
def onIq(self, entity):
if not isinstance(entity, ResultStatusesIqProtocolEntity): # already printed somewhere else
print(entity)
@ProtocolEntityCallback("receipt")
def onReceipt(self, entity):
self.toLower(entity.ack())
@ProtocolEntityCallback("ack")
def onAck(self, entity):
#formattedDate = datetime.datetime.fromtimestamp(self.sentCache[entity.getId()][0]).strftime('%d-%m-%Y %H:%M')
#print("%s [%s]:%s"%(self.username, formattedDate, self.sentCache[entity.getId()][1]))
if entity.getClass() == "message":
self.output(entity.getId(), tag = "Sent")
#self.notifyInputThread()
@ProtocolEntityCallback("success")
def onSuccess(self, entity):
self.connected = True
self.output("Logged in!", "Auth", prompt = False)
self.notifyInputThread()
@ProtocolEntityCallback("failure")
def onFailure(self, entity):
self.connected = False
self.output("Login Failed, reason: %s" % entity.getReason(), prompt = False)
@ProtocolEntityCallback("notification")
def onNotification(self, notification):
notificationData = notification.__str__()
if notificationData:
self.output(notificationData, tag = "Notification")
else:
self.output("From :%s, Type: %s" % (self.jidToAlias(notification.getFrom()), notification.getType()), tag = "Notification")
@ProtocolEntityCallback("message")
def onMessage(self, message):
messageOut = ""
if message.getType() == "text":
#self.output(message.getBody(), tag = "%s [%s]"%(message.getFrom(), formattedDate))
messageOut = self.getTextMessageBody(message)
elif message.getType() == "media":
messageOut = self.getMediaMessageBody(message)
else:
messageOut = "Unknown message type %s " % message.getType()
print(messageOut.toProtocolTreeNode())
formattedDate = datetime.datetime.fromtimestamp(message.getTimestamp()).strftime('%d-%m-%Y %H:%M')
sender = message.getFrom() if not message.isGroupMessage() else "%s/%s" % (message.getParticipant(False), message.getFrom())
output = self.__class__.MESSAGE_FORMAT % (sender, formattedDate, message.getId(), messageOut)
self.output(output, tag = None, prompt = not self.sendReceipts)
if self.sendReceipts:
self.toLower(message.ack(self.sendRead))
self.output("Sent delivered receipt"+" and Read" if self.sendRead else "", tag = "Message %s" % message.getId())
def getTextMessageBody(self, message):
if isinstance(message, TextMessageProtocolEntity):
return message.conversation
elif isinstance(message, ExtendedTextMessageProtocolEntity):
return str(message.message_attributes.extended_text)
else:
raise NotImplementedError()
def getMediaMessageBody(self, message):
# type: (DownloadableMediaMessageProtocolEntity) -> str
return str(message.message_attributes)
def getDownloadableMediaMessageBody(self, message):
return "[media_type={media_type}, length={media_size}, url={media_url}, key={media_key}]".format(
media_type=message.media_type,
media_size=message.file_length,
media_url=message.url,
media_key=base64.b64encode(message.media_key)
)
def doSendMedia(self, mediaType, filePath, url, to, ip = None, caption = None):
if mediaType == RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE:
entity = ImageDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to, caption = caption)
elif mediaType == RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO:
entity = AudioDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to)
elif mediaType == RequestUploadIqProtocolEntity.MEDIA_TYPE_VIDEO:
entity = VideoDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to, caption = caption)
self.toLower(entity)
def __str__(self):
return "CLI Interface Layer"
########### callbacks ############
def onRequestUploadResult(self, jid, mediaType, filePath, resultRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity, caption = None):
if resultRequestUploadIqProtocolEntity.isDuplicate():
self.doSendMedia(mediaType, filePath, resultRequestUploadIqProtocolEntity.getUrl(), jid,
resultRequestUploadIqProtocolEntity.getIp(), caption)
else:
successFn = lambda filePath, jid, url: self.doSendMedia(mediaType, filePath, url, jid, resultRequestUploadIqProtocolEntity.getIp(), caption)
mediaUploader = MediaUploader(jid, self.getOwnJid(), filePath,
resultRequestUploadIqProtocolEntity.getUrl(),
resultRequestUploadIqProtocolEntity.getResumeOffset(),
successFn, self.onUploadError, self.onUploadProgress, asynchronous=False)
mediaUploader.start()
def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity):
logger.error("Request upload for file %s for %s failed" % (path, jid))
def onUploadError(self, filePath, jid, url):
logger.error("Upload file %s to %s for %s failed!" % (filePath, url, jid))
def onUploadProgress(self, filePath, jid, url, progress):
sys.stdout.write("%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress))
sys.stdout.flush()
def onGetContactPictureResult(self, resultGetPictureIqProtocolEntiy, getPictureIqProtocolEntity):
# do here whatever you want
# write to a file
# or open
# or do nothing
# write to file example:
#resultGetPictureIqProtocolEntiy.writeToFile("/tmp/yowpics/%s_%s.jpg" % (getPictureIqProtocolEntity.getTo(), "preview" if resultGetPictureIqProtocolEntiy.isPreview() else "full"))
pass
@clicmd("Print this message")
def help(self):
self.print_usage()
| 24,951 | Python | .py | 475 | 42.850526 | 187 | 0.660906 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,792 | cli.py | tgalal_yowsup/yowsup/demos/cli/cli.py | import threading, inspect, shlex
try:
import Queue
except ImportError:
import queue as Queue
try:
import readline
except ImportError:
import pyreadline as readline
class clicmd(object):
def __init__(self, desc, order = 0):
self.desc = desc
self.order = order
def __call__(self, fn):
fn.clidesc = self.desc
fn.cliorder = self.order
return fn
class Cli(object):
def __init__(self):
self.sentCache = {}
self.commands = {}
self.acceptingInput = False
self.lastPrompt = True
self.blockingQueue = Queue.Queue()
self._queuedCmds = []
readline.set_completer(self.complete)
readline.parse_and_bind('tab: complete')
members = inspect.getmembers(self, predicate = inspect.ismethod)
for m in members:
if hasattr(m[1], "clidesc"):
fname = m[0]
fn = m[1]
try:
cmd, subcommand = fname.split('_')
except ValueError:
cmd = fname
subcommand = "_"
if not cmd in self.commands:
self.commands[cmd] = {}
self.commands[cmd][subcommand] = {
"args": inspect.getargspec(fn)[0][1:],
"optional": len(inspect.getargspec(fn)[3]) if inspect.getargspec(fn)[3] else 0,
"desc": fn.clidesc,
"fn": fn,
"order": fn.cliorder
}
#self.cv = threading.Condition()
self.inputThread = threading.Thread(target = self.startInputThread)
self.inputThread.daemon = True
def queueCmd(self, cmd):
self._queuedCmds.append(cmd)
def startInput(self):
self.inputThread.start()
################### cmd input parsing ####################
def print_usage(self):
line_width = 100
outArr = []
def addToOut(ind, cmd):
if ind >= len(outArr):
outArr.extend([None] * (ind - len(outArr) + 1))
if outArr[ind] != None:
for i in range(len(outArr) - 1, 0, -1):
if outArr[i] is None:
outArr[i] = outArr[ind]
outArr[ind] = cmd
return
outArr.append(cmd)
else:
outArr[ind] = cmd
for cmd, subcommands in self.commands.items():
for subcmd, subcmdDetails in subcommands.items():
out = ""
out += ("/%s " % cmd).ljust(15)
out += ("%s " % subcmd if subcmd != "_" else "").ljust(15)
args = ("%s " % " ".join(["<%s>" % c for c in subcmdDetails["args"][0:len(subcmdDetails["args"])-subcmdDetails["optional"]]]))
args += ("%s " % " ".join(["[%s]" % c for c in subcmdDetails["args"][len(subcmdDetails["args"])-subcmdDetails["optional"]:]]))
out += args.ljust(30)
out += subcmdDetails["desc"].ljust(20)
addToOut(subcmdDetails["order"], out)
print("----------------------------------------------")
print("\n" . join(outArr))
print("----------------------------------------------")
def execCmd(self, cmdInput):
cmdInput = cmdInput.rstrip()
if not len(cmdInput) > 1:
return
if cmdInput.startswith("/"):
cmdInput = cmdInput[1:]
else:
self.print_usage()
return
cmdInputDissect = [c for c in shlex.split(cmdInput) if c]
cmd = cmdInputDissect[0]
if not cmd in self.commands:
return self.print_usage()
cmdData = self.commands[cmd]
if len(cmdData) == 1 and "_" in cmdData:
subcmdData = cmdData["_"]
args = cmdInputDissect[1:] if len(cmdInputDissect) > 1 else []
else:
args = cmdInputDissect[2:] if len(cmdInputDissect) > 2 else []
subcmd = cmdInputDissect[1] if len(cmdInputDissect) > 1 else ""
if subcmd not in cmdData:
return self.print_usage()
subcmdData = cmdData[subcmd]
targetFn = subcmdData["fn"]
if len(subcmdData["args"]) < len(args) or len(subcmdData["args"]) - subcmdData["optional"] > len(args):
return self.print_usage()
return self.doExecCmd(lambda :targetFn(*args))
def doExecCmd(self, fn):
return fn()
def startInputThread(self):
#cv.acquire()
# Fix Python 2.x.
global input
try: input = raw_input
except NameError: pass
while(True):
cmd = self._queuedCmds.pop(0) if len(self._queuedCmds) else input(self.getPrompt()).strip()
wait = self.execCmd(cmd)
if wait:
self.acceptingInput = False
self.blockingQueue.get(True)
#cv.wait()
#self.inputThread.wait()
self.acceptingInput = True
#cv.release()
def getPrompt(self):
return "[%s]:" % ("connected" if self.connected else "offline")
def printPrompt(self):
#return "Enter Message or command: (/%s)" % ", /".join(self.commandMappings)
print(self.getPrompt())
def output(self, message, tag = "general", prompt = True):
if self.acceptingInput == True and self.lastPrompt is True:
print("")
self.lastPrompt = prompt
if tag is not None:
print("%s: %s" % (tag, message))
else:
print(message)
if prompt:
self.printPrompt()
def complete(self, text, state):
if state == 0:
for cmd in self.commands:
if cmd.startswith(text) and cmd != text:
return cmd
def notifyInputThread(self):
self.blockingQueue.put(1)
if __name__ == "__main__":
c = Cli()
c.print_usage()
| 6,023 | Python | .py | 152 | 28.059211 | 142 | 0.518398 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,793 | stack.py | tgalal_yowsup/yowsup/demos/mediasink/stack.py | from yowsup.stacks import YowStackBuilder
from .layer import MediaSinkLayer
from yowsup.layers import YowLayerEvent
from yowsup.layers.network import YowNetworkLayer
class MediaSinkStack(object):
def __init__(self, profile, storage_dir=None):
stackBuilder = YowStackBuilder()
self._stack = stackBuilder\
.pushDefaultLayers()\
.push(MediaSinkLayer)\
.build()
self._stack.setProp(MediaSinkLayer.PROP_STORAGE_DIR, storage_dir)
self._stack.setProfile(profile)
def set_prop(self, key, val):
self._stack.setProp(key, val)
def start(self):
self._stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
self._stack.loop()
| 741 | Python | .py | 18 | 34.111111 | 86 | 0.703343 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,794 | layer.py | tgalal_yowsup/yowsup/demos/mediasink/layer.py | from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_media.protocolentities import *
from yowsup.layers.network.layer import YowNetworkLayer
from yowsup.layers import EventCallback
import sys
try:
from tqdm import tqdm
import requests
except ImportError:
print("This demo requires the python packages 'tqdm' and 'requests' to be installed, exiting.")
sys.exit(1)
from ..common.sink_worker import SinkWorker
import tempfile
import logging
import os
logger = logging.getLogger(__name__)
class MediaSinkLayer(YowInterfaceLayer):
PROP_STORAGE_DIR = "org.openwhatsapp.yowsup.prop.demos.mediasink.storage_dir"
def __init__(self):
super(MediaSinkLayer, self).__init__()
self._sink_worker = None
@EventCallback(YowNetworkLayer.EVENT_STATE_CONNECTED)
def on_connected(self, event):
logger.info("Connected, starting SinkWorker")
storage_dir = self.getProp(self.PROP_STORAGE_DIR)
if storage_dir is None:
logger.debug("No storage dir specified, creating tempdir")
storage_dir = tempfile.mkdtemp("yowsup_mediasink")
if not os.path.exists(storage_dir):
logger.debug("%s does not exist, creating" % storage_dir)
os.makedirs(storage_dir)
logger.info("Storing incoming media to %s" % storage_dir)
self._sink_worker = SinkWorker(storage_dir)
self._sink_worker.start()
@ProtocolEntityCallback("message")
def on_message(self, message_protocolentity):
self.toLower(message_protocolentity.ack())
self.toLower(message_protocolentity.ack(True))
if isinstance(message_protocolentity, MediaMessageProtocolEntity):
self.on_media_message(message_protocolentity)
@ProtocolEntityCallback("receipt")
def on_receipt(self, entity):
self.toLower(entity.ack())
def on_media_message(self, media_message_protocolentity):
self._sink_worker.enqueue(media_message_protocolentity)
| 2,031 | Python | .py | 45 | 38.844444 | 99 | 0.729209 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,795 | yowstack.py | tgalal_yowsup/yowsup/stacks/yowstack.py | from yowsup.layers import YowParallelLayer
import time, logging, random
from yowsup.layers import YowLayer
from yowsup.layers.noise.layer import YowNoiseLayer
from yowsup.layers.noise.layer_noise_segments import YowNoiseSegmentsLayer
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.coder import YowCoderLayer
from yowsup.layers.logger import YowLoggerLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.protocol_messages import YowMessagesProtocolLayer
from yowsup.layers.protocol_media import YowMediaProtocolLayer
from yowsup.layers.protocol_acks import YowAckProtocolLayer
from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer
from yowsup.layers.protocol_groups import YowGroupsProtocolLayer
from yowsup.layers.protocol_presence import YowPresenceProtocolLayer
from yowsup.layers.protocol_ib import YowIbProtocolLayer
from yowsup.layers.protocol_notifications import YowNotificationsProtocolLayer
from yowsup.layers.protocol_iq import YowIqProtocolLayer
from yowsup.layers.protocol_contacts import YowContactsIqProtocolLayer
from yowsup.layers.protocol_chatstate import YowChatstateProtocolLayer
from yowsup.layers.protocol_privacy import YowPrivacyProtocolLayer
from yowsup.layers.protocol_profiles import YowProfilesProtocolLayer
from yowsup.layers.protocol_calls import YowCallsProtocolLayer
from yowsup.common.constants import YowConstants
from yowsup.layers.axolotl import AxolotlSendLayer, AxolotlControlLayer, AxolotlReceivelayer
from yowsup.profile.profile import YowProfile
import inspect
try:
import Queue
except ImportError:
import queue as Queue
logger = logging.getLogger(__name__)
YOWSUP_PROTOCOL_LAYERS_BASIC = (
YowAuthenticationProtocolLayer, YowMessagesProtocolLayer,
YowReceiptProtocolLayer, YowAckProtocolLayer, YowPresenceProtocolLayer,
YowIbProtocolLayer, YowIqProtocolLayer, YowNotificationsProtocolLayer,
YowContactsIqProtocolLayer, YowChatstateProtocolLayer, YowCallsProtocolLayer
)
class YowStackBuilder(object):
def __init__(self):
self.layers = ()
self._props = {}
def setProp(self, key, value):
self._props[key] = value
return self
def pushDefaultLayers(self):
defaultLayers = YowStackBuilder.getDefaultLayers()
self.layers += defaultLayers
return self
def push(self, yowLayer):
self.layers += (yowLayer,)
return self
def pop(self):
self.layers = self.layers[:-1]
return self
def build(self):
return YowStack(self.layers, reversed = False, props = self._props)
@staticmethod
def getDefaultLayers(groups = True, media = True, privacy = True, profiles = True):
coreLayers = YowStackBuilder.getCoreLayers()
protocolLayers = YowStackBuilder.getProtocolLayers(groups = groups, media=media, privacy=privacy, profiles=profiles)
allLayers = coreLayers
allLayers += (AxolotlControlLayer,)
allLayers += (YowParallelLayer((AxolotlSendLayer, AxolotlReceivelayer)),)
allLayers += (YowParallelLayer(protocolLayers),)
return allLayers
@staticmethod
def getDefaultStack(layer = None, axolotl = False, groups = True, media = True, privacy = True, profiles = True):
"""
:param layer: An optional layer to put on top of default stack
:param axolotl: E2E encryption enabled/ disabled
:return: YowStack
"""
allLayers = YowStackBuilder.getDefaultLayers(axolotl, groups = groups, media=media,privacy=privacy, profiles=profiles)
if layer:
allLayers = allLayers + (layer,)
return YowStack(allLayers, reversed = False)
@staticmethod
def getCoreLayers():
return (
YowLoggerLayer,
YowCoderLayer,
YowNoiseLayer,
YowNoiseSegmentsLayer,
YowNetworkLayer
)[::-1]
@staticmethod
def getProtocolLayers(groups = True, media = True, privacy = True, profiles = True):
layers = YOWSUP_PROTOCOL_LAYERS_BASIC
if groups:
layers += (YowGroupsProtocolLayer,)
if media:
layers += (YowMediaProtocolLayer, )
if privacy:
layers += (YowPrivacyProtocolLayer, )
if profiles:
layers += (YowProfilesProtocolLayer, )
return layers
class YowStack(object):
__stack = []
__stackInstances = []
__detachedQueue = Queue.Queue()
def __init__(self, stackClassesArr = None, reversed = True, props = None):
stackClassesArr = stackClassesArr or ()
self.__stack = stackClassesArr[::-1] if reversed else stackClassesArr
self.__stackInstances = []
self._props = props or {}
self.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[random.randint(0,len(YowConstants.ENDPOINTS)-1)])
self._construct()
def getLayerInterface(self, YowLayerClass):
for inst in self.__stackInstances:
if inst.__class__ == YowLayerClass:
return inst.getLayerInterface()
elif inst.__class__ == YowParallelLayer:
res = inst.getLayerInterface(YowLayerClass)
if res:
return res
def send(self, data):
self.__stackInstances[-1].send(data)
def receive(self, data):
self.__stackInstances[0].receive(data)
def setCredentials(self, credentials):
logger.warning("setCredentials is deprecated and any passed-in keypair is ignored, "
"use setProfile(YowProfile) instead")
profile_name, keypair = credentials
self.setProfile(YowProfile(profile_name))
def setProfile(self, profile):
# type: (str | YowProfile) -> None
"""
:param profile: profile to use.
:return:
"""
logger.debug("setProfile(%s)" % profile)
self.setProp("profile", profile if isinstance(profile, YowProfile) else YowProfile(profile))
def addLayer(self, layerClass):
self.__stack.push(layerClass)
def addPostConstructLayer(self, layer):
self.__stackInstances[-1].setLayers(layer, self.__stackInstances[-2])
layer.setLayers(None, self.__stackInstances[-1])
self.__stackInstances.append(layer)
def setProp(self, key, value):
self._props[key] = value
def getProp(self, key, default = None):
return self._props[key] if key in self._props else default
def emitEvent(self, yowLayerEvent):
if not self.__stackInstances[0].onEvent(yowLayerEvent):
self.__stackInstances[0].emitEvent(yowLayerEvent)
def broadcastEvent(self, yowLayerEvent):
if not self.__stackInstances[-1].onEvent(yowLayerEvent):
self.__stackInstances[-1].broadcastEvent(yowLayerEvent)
def execDetached(self, fn):
self.__class__.__detachedQueue.put(fn)
def loop(self, *args, **kwargs):
while True:
try:
callback = self.__class__.__detachedQueue.get(False) #doesn't block
callback()
except Queue.Empty:
pass
time.sleep(0.1)
def _construct(self):
logger.debug("Initializing stack")
for s in self.__stack:
if type(s) is tuple:
logger.warn("Implicit declaration of parallel layers in a tuple is deprecated, pass a YowParallelLayer instead")
inst = YowParallelLayer(s)
else:
if inspect.isclass(s):
if issubclass(s, YowLayer):
inst = s()
else:
raise ValueError("Stack must contain only subclasses of YowLayer")
elif issubclass(s.__class__, YowLayer):
inst = s
else:
raise ValueError("Stack must contain only subclasses of YowLayer")
#inst = s()
logger.debug("Constructed %s" % inst)
inst.setStack(self)
self.__stackInstances.append(inst)
for i in range(0, len(self.__stackInstances)):
upperLayer = self.__stackInstances[i + 1] if (i + 1) < len(self.__stackInstances) else None
lowerLayer = self.__stackInstances[i - 1] if i > 0 else None
self.__stackInstances[i].setLayers(upperLayer, lowerLayer)
def getLayer(self, layerIndex):
return self.__stackInstances[layerIndex]
| 8,733 | Python | .tac | 186 | 38.370968 | 128 | 0.663217 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,796 | attributes_contact.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_contact.py | class ContactAttributes(object):
def __init__(self, display_name, vcard, context_info=None):
self._display_name = display_name
self._vcard = vcard
self._context_info = context_info
def __str__(self):
attrs = []
if self.display_name is not None:
attrs.append(("display_name", self.display_name))
if self.vcard is not None:
attrs.append(("vcard", "[binary data]"))
if self.context_info is not None:
attrs.append(("context_info", self.context_info))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def display_name(self):
return self._display_name
@display_name.setter
def display_name(self, value):
self._display_name = value
@property
def vcard(self):
return self._vcard
@vcard.setter
def vcard(self, value):
self._vcard = value
@property
def context_info(self):
return self._context_info
@context_info.setter
def context_info(self, value):
self.context_info = value
| 1,108 | Python | .tac | 32 | 27 | 75 | 0.607678 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,797 | message_media_contact.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media_contact.py | from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from .message_media import MediaMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_contact import ContactAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class ContactMediaMessageProtocolEntity(MediaMessageProtocolEntity):
def __init__(self, contact_attrs, message_meta_attrs):
# type: (ContactAttributes, MessageMetaAttributes) -> None
super(ContactMediaMessageProtocolEntity, self).__init__(
"contact", MessageAttributes(contact=contact_attrs), message_meta_attrs
)
@property
def media_specific_attributes(self):
return self.message_attributes.contact
@property
def display_name(self):
return self.media_specific_attributes.display_name
@display_name.setter
def display_name(self, value):
self.media_specific_attributes.display_name = value
@property
def vcard(self):
return self.media_specific_attributes.vcard
@vcard.setter
def vcard(self, value):
self.media_specific_attributes.vcard = value
| 1,260 | Python | .tac | 25 | 44.32 | 117 | 0.775244 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,798 | test_message_media_contact.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/test_message_media_contact.py | from yowsup.layers.protocol_media.protocolentities.test_message_media import MediaMessageProtocolEntityTest
from yowsup.layers.protocol_media.protocolentities import ContactMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
class ContactMediaMessageProtocolEntityTest(MediaMessageProtocolEntityTest):
def setUp(self):
super(ContactMediaMessageProtocolEntityTest, self).setUp()
self.ProtocolEntity = ContactMediaMessageProtocolEntity
m = Message()
contact_message = Message.ContactMessage()
contact_message.display_name = "abc"
contact_message.vcard = b"VCARD_DATA"
m.contact_message.MergeFrom(contact_message)
proto_node = self.node.getChild("proto")
proto_node["mediatype"] = "contact"
proto_node.setData(m.SerializeToString())
| 857 | Python | .tac | 15 | 50.4 | 107 | 0.77381 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,799 | 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 | .tac | 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) |