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,500 | httpproxy.py | tgalal_yowsup/yowsup/common/http/httpproxy.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.
'''
import os, base64
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
class HttpProxy:
def __init__(self, address, username = None, password = None):
self.address = address
self.username = username
self.password = password
def __repr__(self):
return repr(self.address)
def handler(self):
return HttpProxyHandler(self)
@staticmethod
def getFromEnviron():
url = None
for key in ('http_proxy', 'https_proxy'):
url = os.environ.get(key)
if url: break
if not url:
return None
dat = urlparse(url)
port = 80 if dat.scheme == 'http' else 443
if dat.port != None: port = int(dat.port)
host = dat.hostname
return HttpProxy((host, port), dat.username, dat.password)
class HttpProxyHandler:
def __init__(self, proxy):
self.state = 'init'
self.proxy = proxy
def onConnect(self):
pass
def connect(self, socket, pair):
proxy = self.proxy
authHeader = None
if proxy.username and proxy.password:
key = bytes(proxy.username, 'ascii') + b':' + bytes(proxy.password, 'ascii') if (bytes != str) else bytes(proxy.username) + b':' + proxy.password
auth = base64.b64encode(key)
authHeader = b'Proxy-Authorization: Basic ' + auth + b'\r\n'
data = bytearray('CONNECT %s:%d HTTP/1.1\r\nHost: %s:%d\r\n' % (2 * pair), 'ascii')
if authHeader:
data += authHeader
data += b'\r\n'
self.state = 'connect'
self.data = data
socket.connect(proxy.address)
def send(self, socket):
if self.state == 'connect':
socket.send(self.data)
self.state = 'sent'
def recv(self, socket, size):
if self.state == 'sent':
data = socket.recv(size)
data = data.decode('ascii')
status = data.split(' ', 2)
if status[1] != '200':
raise Exception('%s' % (data[:data.index('\r\n')]))
self.state = 'end'
self.onConnect()
return data | 3,283 | Python | .py | 78 | 34.846154 | 157 | 0.649843 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,501 | 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 | .py | 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,502 | __init__.py | tgalal_yowsup/yowsup/stacks/__init__.py | from .yowstack import YowStack, YowStackBuilder
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.layers.noise.layer import YowNoiseLayer
from yowsup.layers.noise.layer_noise_segments import YowNoiseSegmentsLayer
YOWSUP_CORE_LAYERS = (
YowLoggerLayer,
YowCoderLayer,
YowNoiseLayer,
YowNoiseSegmentsLayer,
YowNetworkLayer
)
YOWSUP_PROTOCOL_LAYERS_BASIC = (
YowAuthenticationProtocolLayer, YowMessagesProtocolLayer,
YowReceiptProtocolLayer, YowAckProtocolLayer, YowPresenceProtocolLayer,
YowIbProtocolLayer, YowIqProtocolLayer, YowNotificationsProtocolLayer,
YowContactsIqProtocolLayer, YowChatstateProtocolLayer
)
YOWSUP_PROTOCOL_LAYERS_GROUPS = (YowGroupsProtocolLayer,) + YOWSUP_PROTOCOL_LAYERS_BASIC
YOWSUP_PROTOCOL_LAYERS_MEDIA = (YowMediaProtocolLayer,) + YOWSUP_PROTOCOL_LAYERS_BASIC
YOWSUP_PROTOCOL_LAYERS_PROFILES = (YowProfilesProtocolLayer,) + YOWSUP_PROTOCOL_LAYERS_BASIC
YOWSUP_PROTOCOL_LAYERS_CALLS = (YowCallsProtocolLayer,) + YOWSUP_PROTOCOL_LAYERS_BASIC
YOWSUP_PROTOCOL_LAYERS_FULL = (YowGroupsProtocolLayer, YowMediaProtocolLayer, YowPrivacyProtocolLayer, YowProfilesProtocolLayer, YowCallsProtocolLayer)\
+ YOWSUP_PROTOCOL_LAYERS_BASIC
YOWSUP_FULL_STACK = (YOWSUP_PROTOCOL_LAYERS_FULL,) +\
YOWSUP_CORE_LAYERS
| 2,684 | Python | .py | 42 | 60.595238 | 152 | 0.768997 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,503 | env_android.py | tgalal_yowsup/yowsup/env/env_android.py | from .env import YowsupEnv
import base64
import hashlib
class AndroidYowsupEnv(YowsupEnv):
_SIGNATURE = "MIIDMjCCAvCgAwIBAgIETCU2pDALBgcqhkjOOAQDBQAwfDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFDASBgNV" \
"BAcTC1NhbnRhIENsYXJhMRYwFAYDVQQKEw1XaGF0c0FwcCBJbmMuMRQwEgYDVQQLEwtFbmdpbmVlcmluZzEUMBIGA1UEAxMLQnJ" \
"pYW4gQWN0b24wHhcNMTAwNjI1MjMwNzE2WhcNNDQwMjE1MjMwNzE2WjB8MQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5" \
"pYTEUMBIGA1UEBxMLU2FudGEgQ2xhcmExFjAUBgNVBAoTDVdoYXRzQXBwIEluYy4xFDASBgNVBAsTC0VuZ2luZWVyaW5nMRQwEg" \
"YDVQQDEwtCcmlhbiBBY3RvbjCCAbgwggEsBgcqhkjOOAQBMIIBHwKBgQD9f1OBHXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEm" \
"aUVdQCJR+1k9jVj6v8X1ujD2y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb+DtX58aophUPBPuD9tPFHsMCN" \
"VQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdgUI8VIwvMspK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jr" \
"qgvlXTAs9B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCjrh4rs6Z1kW6jfwv6ITVi8ftiegEkO" \
"8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQBTDv+z0kqA4GFAAKBgQDRGYtLgWh7zyRtQainJfCpiaUbzjJuhMgo4fVWZIvXHaS" \
"HBU1t5w//S0lDK2hiqkj8KpMWGywVov9eZxZy37V26dEqr/c2m5qZ0E+ynSu7sqUD7kGx/zeIcGT0H+KAVgkGNQCo5Uc0koLRW" \
"YHNtYoIvt5R3X6YZylbPftF/8ayWTALBgcqhkjOOAQDBQADLwAwLAIUAKYCp0d6z4QQdyN74JDfQ2WCyi8CFDUM4CaNB+ceVXd" \
"KtOrNTQcc0e+t"
_MD5_CLASSES = "WuFH18yXKRVezywQm+S24A=="
_KEY = "eQV5aq/Cg63Gsq1sshN9T3gh+UUp0wIw0xgHYT1bnCjEqOJQKCRrWxdAe2yvsDeCJL+Y4G3PRD2HUF7oUgiGo8vGlNJOaux26k+A2F3hj8A="
_VERSION = "2.21.21.18" # 2.20.206.24
_OS_NAME = "Android"
_OS_VERSION = "8.0.0"
_DEVICE_NAME = "star2lte"
_MANUFACTURER = "samsung"
_BUILD_VERSION = "star2ltexx-user 8.0.0 R16NW G965FXXU1ARCC release-keys"
_AXOLOTL = True
def getVersion(self):
return self.__class__._VERSION
def getOSName(self):
return self.__class__._OS_NAME
def getOSVersion(self):
return self.__class__._OS_VERSION
def getDeviceName(self):
return self.__class__._DEVICE_NAME
def getBuildVersion(self):
return self.__class__._BUILD_VERSION
def getManufacturer(self):
return self.__class__._MANUFACTURER
def isAxolotlEnabled(self):
return self.__class__._AXOLOTL
def getToken(self, phoneNumber):
keyDecoded = bytearray(base64.b64decode(self.__class__._KEY))
sigDecoded = base64.b64decode(self.__class__._SIGNATURE)
clsDecoded = base64.b64decode(self.__class__._MD5_CLASSES)
data = sigDecoded + clsDecoded + phoneNumber.encode()
opad = bytearray()
ipad = bytearray()
for i in range(0, 64):
opad.append(0x5C ^ keyDecoded[i])
ipad.append(0x36 ^ keyDecoded[i])
hash = hashlib.sha1()
subHash = hashlib.sha1()
try:
subHash.update(ipad + data)
hash.update(opad + subHash.digest())
except TypeError:
subHash.update(bytes(ipad + data))
hash.update(bytes(opad + subHash.digest()))
result = base64.b64encode(hash.digest())
return result
| 3,118 | Python | .py | 59 | 44.983051 | 121 | 0.737689 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,504 | env.py | tgalal_yowsup/yowsup/env/env.py | import abc
import logging
from six import with_metaclass
logger = logging.getLogger(__name__)
DEFAULT = "android"
class YowsupEnvType(abc.ABCMeta):
def __init__(cls, name, bases, dct):
if name != "YowsupEnv":
YowsupEnv.registerEnv(cls)
super(YowsupEnvType, cls).__init__(name, bases, dct)
class YowsupEnv(with_metaclass(YowsupEnvType, object)):
__metaclass__ = YowsupEnvType
__ENVS = {}
__CURR = None
_USERAGENT_STRING = "WhatsApp/{WHATSAPP_VERSION} {OS_NAME}/{OS_VERSION} Device/{MANUFACTURER}-{DEVICE_NAME}"
@classmethod
def registerEnv(cls, envCls):
envName = envCls.__name__.lower().replace("yowsupenv", "")
cls.__ENVS[envName] = envCls
logger.debug("registered env %s => %s" % (envName, envCls))
@classmethod
def setEnv(cls, envName):
if not envName in cls.__ENVS:
raise ValueError("%s env does not exist" % envName)
logger.debug("Current env changed to %s " % envName)
cls.__CURR = cls.__ENVS[envName]()
@classmethod
def getEnv(cls, envName):
if not envName in cls.__ENVS:
raise ValueError("%s env does not exist" % envName)
return cls.__ENVS[envName]()
@classmethod
def getRegisteredEnvs(cls):
return list(cls.__ENVS.keys())
@classmethod
def getCurrent(cls):
"""
:rtype: YowsupEnv
"""
if cls.__CURR is None:
env = DEFAULT
envs = cls.getRegisteredEnvs()
if env not in envs:
env = envs[0]
logger.debug("Env not set, setting it to %s" % env)
cls.setEnv(env)
return cls.__CURR
@abc.abstractmethod
def getToken(self, phoneNumber):
pass
@abc.abstractmethod
def getVersion(self):
pass
@abc.abstractmethod
def getOSVersion(self):
pass
@abc.abstractmethod
def getOSName(self):
pass
@abc.abstractmethod
def getDeviceName(self):
pass
@abc.abstractmethod
def getManufacturer(self):
pass
def getBuildVersion(self):
pass
def getUserAgent(self):
return self.__class__._USERAGENT_STRING.format(
WHATSAPP_VERSION=self.getVersion(),
OS_NAME=self.getOSName(),
OS_VERSION=self.getOSVersion(),
MANUFACTURER=self.getManufacturer(),
DEVICE_NAME=self.getDeviceName()
)
| 2,461 | Python | .py | 75 | 25.026667 | 112 | 0.611839 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,505 | __init__.py | tgalal_yowsup/yowsup/layers/__init__.py | import unittest
import inspect
import threading
try:
import Queue
except ImportError:
import queue as Queue
class YowLayerEvent:
def __init__(self, name, **kwargs):
self.name = name
self.detached = False
if "detached" in kwargs:
del kwargs["detached"]
self.detached = True
self.args = kwargs
def isDetached(self):
return self.detached
def getName(self):
return self.name
def getArg(self, name):
return self.args[name] if name in self.args else None
class EventCallback(object):
def __init__(self, eventName):
self.eventName = eventName
def __call__(self, fn):
fn.event_callback = self.eventName
return fn
class YowLayer(object):
__upper = None
__lower = None
_props = {}
__detachedQueue = Queue.Queue()
# def __init__(self, upperLayer, lowerLayer):
# self.setLayers(upperLayer, lowerLayer)
def __init__(self):
self.setLayers(None, None)
self.interface = None
self.event_callbacks = {}
self.__stack = None
self.lock = threading.Lock()
members = inspect.getmembers(self, predicate=inspect.ismethod)
for m in members:
if hasattr(m[1], "event_callback"):
fname = m[0]
fn = m[1]
self.event_callbacks[fn.event_callback] = getattr(self, fname)
def getLayerInterface(self, YowLayerClass = None):
return self.interface if YowLayerClass is None else self.__stack.getLayerInterface(YowLayerClass)
def setStack(self, stack):
self.__stack = stack
def getStack(self):
return self.__stack
def setLayers(self, upper, lower):
self.__upper = upper
self.__lower = lower
def send(self, data):
self.toLower(data)
def receive(self, data):
self.toUpper(data)
def toUpper(self, data):
if self.__upper:
self.__upper.receive(data)
def toLower(self, data):
self.lock.acquire()
if self.__lower:
self.__lower.send(data)
self.lock.release()
def emitEvent(self, yowLayerEvent):
if self.__upper and not self.__upper.onEvent(yowLayerEvent):
if yowLayerEvent.isDetached():
yowLayerEvent.detached = False
self.getStack().execDetached(lambda : self.__upper.emitEvent(yowLayerEvent))
else:
self.__upper.emitEvent(yowLayerEvent)
def broadcastEvent(self, yowLayerEvent):
if self.__lower and not self.__lower.onEvent(yowLayerEvent):
if yowLayerEvent.isDetached():
yowLayerEvent.detached = False
self.getStack().execDetached(lambda:self.__lower.broadcastEvent(yowLayerEvent))
else:
self.__lower.broadcastEvent(yowLayerEvent)
'''return true to stop propagating the event'''
def onEvent(self, yowLayerEvent):
eventName = yowLayerEvent.getName()
if eventName in self.event_callbacks:
return self.event_callbacks[eventName](yowLayerEvent)
return False
def getProp(self, key, default = None):
return self.getStack().getProp(key, default)
def setProp(self, key, val):
return self.getStack().setProp(key, val)
class YowProtocolLayer(YowLayer):
def __init__(self, handleMap = None):
super(YowProtocolLayer, self).__init__()
self.handleMap = handleMap or {}
self.iqRegistry = {}
def receive(self, node):
if not self.processIqRegistry(node):
if node.tag in self.handleMap:
recv, _ = self.handleMap[node.tag]
if recv:
recv(node)
def send(self, entity):
if entity.getTag() in self.handleMap:
_, send = self.handleMap[entity.getTag()]
if send:
send(entity)
def entityToLower(self, entity):
#super(YowProtocolLayer, self).toLower(entity.toProtocolTreeNode())
self.toLower(entity.toProtocolTreeNode())
def isGroupJid(self, jid):
return "-" in jid
def raiseErrorForNode(self, node):
raise ValueError("Unimplemented notification type %s " % node)
def _sendIq(self, iqEntity, onSuccess = None, onError = None):
self.iqRegistry[iqEntity.getId()] = (iqEntity, onSuccess, onError)
self.toLower(iqEntity.toProtocolTreeNode())
def processIqRegistry(self, protocolTreeNode):
if protocolTreeNode.tag == "iq":
iq_id = protocolTreeNode["id"]
if iq_id in self.iqRegistry:
originalIq, successClbk, errorClbk = self.iqRegistry[iq_id]
del self.iqRegistry[iq_id]
if protocolTreeNode["type"] == "result" and successClbk:
successClbk(protocolTreeNode, originalIq)
elif protocolTreeNode["type"] == "error" and errorClbk:
errorClbk(protocolTreeNode, originalIq)
return True
return False
class YowParallelLayer(YowLayer):
def __init__(self, sublayers = None):
super(YowParallelLayer, self).__init__()
self.sublayers = sublayers or []
self.sublayers = tuple([sublayer() for sublayer in sublayers])
for s in self.sublayers:
#s.setLayers(self, self)
s.toLower = self.toLower
s.toUpper = self.toUpper
s.broadcastEvent = self.subBroadcastEvent
s.emitEvent = self.subEmitEvent
def getLayerInterface(self, YowLayerClass):
for s in self.sublayers:
if s.__class__ == YowLayerClass:
return s.getLayerInterface()
def setStack(self, stack):
super(YowParallelLayer, self).setStack(stack)
for s in self.sublayers:
s.setStack(self.getStack())
def receive(self, data):
for s in self.sublayers:
s.receive(data)
def send(self, data):
for s in self.sublayers:
s.send(data)
def subBroadcastEvent(self, yowLayerEvent):
self.onEvent(yowLayerEvent)
self.broadcastEvent(yowLayerEvent)
def subEmitEvent(self, yowLayerEvent):
self.onEvent(yowLayerEvent)
self.emitEvent(yowLayerEvent)
def onEvent(self, yowLayerEvent):
stopEvent = False
for s in self.sublayers:
stopEvent = stopEvent or s.onEvent(yowLayerEvent)
return stopEvent
def __str__(self):
return " - ".join([l.__str__() for l in self.sublayers])
class YowLayerInterface(object):
def __init__(self, layer):
self._layer = layer
class YowLayerTest(unittest.TestCase):
def __init__(self, *args):
super(YowLayerTest, self).__init__(*args)
self.upperSink = []
self.lowerSink = []
self.toUpper = self.receiveOverrider
self.toLower = self.sendOverrider
self.upperEventSink = []
self.lowerEventSink = []
self.emitEvent = self.emitEventOverrider
self.broadcastEvent = self.broadcastEventOverrider
def receiveOverrider(self, data):
self.upperSink.append(data)
def sendOverrider(self, data):
self.lowerSink.append(data)
def emitEventOverrider(self, event):
self.upperEventSink.append(event)
def broadcastEventOverrider(self, event):
self.lowerEventSink.append(event)
def assert_emitEvent(self, event):
self.emitEvent(event)
try:
self.assertEqual(event, self.upperEventSink.pop())
except IndexError:
raise AssertionError("Event '%s' was not emited through this layer" % (event.getName()))
def assert_broadcastEvent(self, event):
self.broadcastEvent(event)
try:
self.assertEqual(event, self.lowerEventSink.pop())
except IndexError:
raise AssertionError("Event '%s' was not broadcasted through this layer" % (event.getName()))
class YowProtocolLayerTest(YowLayerTest):
def assertSent(self, entity):
self.send(entity)
try:
self.assertEqual(entity.toProtocolTreeNode(), self.lowerSink.pop())
except IndexError:
raise AssertionError("Entity '%s' was not sent through this layer" % (entity.getTag()))
def assertReceived(self, entity):
node = entity.toProtocolTreeNode()
self.receive(node)
try:
self.assertEqual(node, self.upperSink.pop().toProtocolTreeNode())
except IndexError:
raise AssertionError("'%s' was not received through this layer" % (entity.getTag()))
| 8,701 | Python | .py | 215 | 31.111628 | 105 | 0.630883 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,506 | layer.py | tgalal_yowsup/yowsup/layers/noise/layer.py | from yowsup.layers.noise.workers.handshake import WANoiseProtocolHandshakeWorker
from yowsup.layers import YowLayer, EventCallback
from yowsup.layers.auth.layer_authentication import YowAuthenticationProtocolLayer
from yowsup.layers.network.layer import YowNetworkLayer
from yowsup.layers.noise.layer_noise_segments import YowNoiseSegmentsLayer
from yowsup.config.manager import ConfigManager
from yowsup.env.env import YowsupEnv
from yowsup.layers import YowLayerEvent
from yowsup.structs.protocoltreenode import ProtocolTreeNode
from yowsup.layers.coder.encoder import WriteEncoder
from yowsup.layers.coder.tokendictionary import TokenDictionary
from consonance.protocol import WANoiseProtocol
from consonance.config.client import ClientConfig
from consonance.config.useragent import UserAgentConfig
from consonance.streams.segmented.blockingqueue import BlockingQueueSegmentedStream
from consonance.structs.keypair import KeyPair
import threading
import logging
logger = logging.getLogger(__name__)
try:
import Queue
except ImportError:
import queue as Queue
class YowNoiseLayer(YowLayer):
DEFAULT_PUSHNAME = "yowsup"
HEADER = b'WA\x04\x00'
EDGE_HEADER = b'ED\x00\x01'
EVENT_HANDSHAKE_FAILED = "org.whatsapp.yowsup.layer.noise.event.handshake_failed"
def __init__(self):
super(YowNoiseLayer, self).__init__()
self._wa_noiseprotocol = WANoiseProtocol(
4, 0, protocol_state_callbacks=self._on_protocol_state_changed
) # type: WANoiseProtocol
self._handshake_worker = None
self._stream = BlockingQueueSegmentedStream() # type: BlockingQueueSegmentedStream
self._read_buffer = bytearray()
self._flush_lock = threading.Lock()
self._incoming_segments_queue = Queue.Queue()
self._profile = None
self._rs = None
def __str__(self):
return "Noise Layer"
@EventCallback(YowNetworkLayer.EVENT_STATE_DISCONNECTED)
def on_disconnected(self, event):
self._wa_noiseprotocol.reset()
@EventCallback(YowAuthenticationProtocolLayer.EVENT_AUTH)
def on_auth(self, event):
logger.debug("Received auth event")
self._profile = self.getProp("profile")
config = self._profile.config # type: yowsup.config.v1.config.Config
# event's keypair will override config's keypair
local_static = config.client_static_keypair
username = int(self._profile.username)
if local_static is None:
logger.error("client_static_keypair is not defined in specified config, disconnecting")
self.broadcastEvent(
YowLayerEvent(
YowNetworkLayer.EVENT_STATE_DISCONNECT,
reason="client_static_keypair is not defined in specified config"
)
)
else:
if type(local_static) is bytes:
local_static = KeyPair.from_bytes(local_static)
assert type(local_static) is KeyPair, type(local_static)
passive = event.getArg('passive')
self.setProp(YowNoiseSegmentsLayer.PROP_ENABLED, False)
if config.edge_routing_info:
self.toLower(self.EDGE_HEADER)
self.setProp(YowNoiseSegmentsLayer.PROP_ENABLED, True)
self.toLower(config.edge_routing_info)
self.setProp(YowNoiseSegmentsLayer.PROP_ENABLED, False)
self.toLower(self.HEADER)
self.setProp(YowNoiseSegmentsLayer.PROP_ENABLED, True)
remote_static = config.server_static_public
self._rs = remote_static
yowsupenv = YowsupEnv.getCurrent()
client_config = ClientConfig(
username=username,
passive=passive,
useragent=UserAgentConfig(
platform=0,
app_version=yowsupenv.getVersion(),
mcc=config.mcc or "000",
mnc=config.mnc or "000",
os_version=yowsupenv.getOSVersion(),
manufacturer=yowsupenv.getManufacturer(),
device=yowsupenv.getDeviceName(),
os_build_number=yowsupenv.getOSVersion(),
phone_id=config.fdid or "",
locale_lang="en",
locale_country="US"
),
pushname=config.pushname or self.DEFAULT_PUSHNAME,
short_connect=True
)
if not self._in_handshake():
logger.debug("Performing handshake [username= %d, passive=%s]" % (username, passive) )
self._handshake_worker = WANoiseProtocolHandshakeWorker(
self._wa_noiseprotocol, self._stream, client_config, local_static, remote_static,
self.on_handshake_finished
)
logger.debug("Starting handshake worker")
self._stream.set_events_callback(self._handle_stream_event)
self._handshake_worker.start()
def on_handshake_finished(self, e=None):
# type: (Exception) -> None
if e is not None:
self.emitEvent(YowLayerEvent(self.EVENT_HANDSHAKE_FAILED, reason=e))
data=WriteEncoder(TokenDictionary()).protocolTreeNodeToBytes(
ProtocolTreeNode("failure", {"reason": str(e)})
)
self.toUpper(data)
logger.error("An error occurred during handshake, try login again.")
def _in_handshake(self):
"""
:return:
:rtype: bool
"""
return self._wa_noiseprotocol.state == WANoiseProtocol.STATE_HANDSHAKE
def _on_protocol_state_changed(self, state):
if state == WANoiseProtocol.STATE_TRANSPORT:
if self._rs != self._wa_noiseprotocol.rs:
config = self._profile.config
config.server_static_public = self._wa_noiseprotocol.rs
self._profile.write_config(config)
self._rs = self._wa_noiseprotocol.rs
self._flush_incoming_buffer()
def _handle_stream_event(self, event):
if event == BlockingQueueSegmentedStream.EVENT_WRITE:
self.toLower(self._stream.get_write_segment())
elif event == BlockingQueueSegmentedStream.EVENT_READ:
self._stream.put_read_segment(self._incoming_segments_queue.get(block=True))
def send(self, data):
"""
:param data:
:type data: bytearray | bytes
:return:
:rtype:
"""
data = bytes(data) if type(data) is not bytes else data
self._wa_noiseprotocol.send(data)
def _flush_incoming_buffer(self):
self._flush_lock.acquire()
while self._incoming_segments_queue.qsize():
self.toUpper(self._wa_noiseprotocol.receive())
self._flush_lock.release()
def receive(self, data):
"""
:param data:
:type data: bytes
:return:
:rtype:
"""
self._incoming_segments_queue.put(data)
if not self._in_handshake():
self._flush_incoming_buffer()
| 7,150 | Python | .py | 157 | 34.910828 | 102 | 0.641986 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,507 | layer_noise_segments.py | tgalal_yowsup/yowsup/layers/noise/layer_noise_segments.py | from yowsup.layers import YowLayer
import logging
import struct
logger = logging.getLogger(__name__)
class YowNoiseSegmentsLayer(YowLayer):
PROP_ENABLED = "org.openwhatsapp.yowsup.prop.noise.segmented_enabled"
def __init__(self):
super(YowNoiseSegmentsLayer, self).__init__()
self._read_buffer = bytearray()
def __str__(self):
return "Noise Segments Layer"
def send(self, data):
if len(data) >= 16777216:
raise ValueError("data too large to write; length=%d" % len(data))
if self.getProp(self.PROP_ENABLED, False):
self.toLower(struct.pack('>I', len(data))[1:])
self.toLower(data)
def receive(self, data):
if self.getProp(self.PROP_ENABLED, False):
self._read_buffer.extend(data)
while len(self._read_buffer) > 3:
read_size = struct.unpack('>I', b"\x00" + self._read_buffer[:3])[0] # type: int
if len(self._read_buffer) >= (3 + read_size):
data = self._read_buffer[3:read_size+3]
self._read_buffer = self._read_buffer[3 + read_size:]
self.toUpper(bytes(data))
else:
break
else:
self.toUpper(data)
| 1,282 | Python | .py | 30 | 32.233333 | 95 | 0.580307 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,508 | handshake.py | tgalal_yowsup/yowsup/layers/noise/workers/handshake.py | from consonance.protocol import WANoiseProtocol
from consonance.streams.segmented.segmented import SegmentedStream
from consonance.exceptions.handshake_failed_exception import HandshakeFailedException
from consonance.config.client import ClientConfig
from consonance.structs.keypair import KeyPair
from consonance.structs.publickey import PublicKey
import threading
import logging
logger = logging.getLogger(__name__)
class WANoiseProtocolHandshakeWorker(threading.Thread):
def __init__(self, wanoiseprotocol, stream, client_config, s, rs=None, finish_callback=None):
"""
:param wanoiseprotocol:
:type wanoiseprotocol: WANoiseProtocol
:param stream:
:type stream: SegmentedStream
:param client_config:
:type client_config: ClientConfig
:param s:
:type s: KeyPair
:param rs:
:type rs: PublicKey | None
"""
super(WANoiseProtocolHandshakeWorker, self).__init__()
self.daemon = True
self._protocol = wanoiseprotocol # type: WANoiseProtocol
self._stream = stream # type: SegmentedStream
self._client_config = client_config # type: ClientConfig
self._s = s # type: KeyPair
self._rs = rs # type: PublicKey
self._finish_callback = finish_callback
def run(self):
self._protocol.reset()
error = None
try:
self._protocol.start(self._stream, self._client_config, self._s, self._rs)
except HandshakeFailedException as e:
error = e
if self._finish_callback is not None:
self._finish_callback(error)
| 1,636 | Python | .py | 40 | 33.625 | 97 | 0.69163 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,509 | layer.py | tgalal_yowsup/yowsup/layers/protocol_profiles/layer.py | from yowsup.layers import YowProtocolLayer
from .protocolentities import *
from yowsup.layers.protocol_iq.protocolentities import ErrorIqProtocolEntity, ResultIqProtocolEntity
class YowProfilesProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowProfilesProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Profiles Layer"
def sendIq(self, entity):
if entity.getXmlns() == "w:profile:picture":
if entity.getType() == "get":
self._sendIq(entity, self.onGetPictureResult, self.onGetPictureError)
elif entity.getType() == "set":
self._sendIq(entity, self.onSetPictureResult, self.onSetPictureError)
elif entity.getType() == "delete":
self._sendIq(entity, self.onDeletePictureResult, self.onDeletePictureError)
elif entity.getXmlns() == "privacy":
self._sendIq(entity, self.onPrivacyResult, self.onPrivacyError)
elif isinstance(entity, GetStatusesIqProtocolEntity):
self._sendIq(entity, self.onGetStatusesResult, self.onGetStatusesError)
elif isinstance(entity, SetStatusIqProtocolEntity):
self._sendIq(entity, self.onSetStatusResult, self.onSetStatusError)
def recvIq(self, node):
pass
def onPrivacyResult(self, resultNode, originIqRequestEntity):
self.toUpper(ResultPrivacyIqProtocolEntity.fromProtocolTreeNode(resultNode))
def onPrivacyError(self, errorNode, originalIqRequestEntity):
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(errorNode))
def onGetStatusesResult(self, resultNode, originIqRequestEntity):
self.toUpper(ResultStatusesIqProtocolEntity.fromProtocolTreeNode(resultNode))
def onGetStatusesError(self, errorNode, originalIqRequestEntity):
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(errorNode))
def onSetStatusResult(self, resultNode, originIqRequestEntity):
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(resultNode))
def onSetStatusError(self, errorNode, originalIqRequestEntity):
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(errorNode))
def onGetPictureResult(self, resultNode, originalIqRequestEntity):
self.toUpper(ResultGetPictureIqProtocolEntity.fromProtocolTreeNode(resultNode))
def onGetPictureError(self, errorNode, originalIqRequestEntity):
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(errorNode))
def onSetPictureResult(self, resultNode, originalIqRequestEntity):
self.toUpper(ResultGetPictureIqProtocolEntity.fromProtocolTreeNode(resultNode))
def onSetPictureError(self, errorNode, originalIqRequestEntity):
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(errorNode))
def onDeletePictureResult(self, resultNode, originalIqRequestEntity):
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(resultNode))
def onDeletePictureError(self, errorNode, originalIqRequestEntity):
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(errorNode))
| 3,186 | Python | .py | 51 | 54.019608 | 100 | 0.762103 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,510 | iq_pictures_list.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_pictures_list.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_picture import PictureIqProtocolEntity
class ListPicturesIqProtocolEntity(PictureIqProtocolEntity):
'''
<iq type="get" id="{{id}}" xmlns="w:profile:picture", to="self.jid">
<list>
<user jid="{{user_jid}}"></user>
<user jid="{{user_jid}}"></user>
</list>
</iq>
'''
def __init__(self, selfJid, jids):
super(ListPicturesIqProtocolEntity, self).__init__(jid = selfJid, type = "get")
self.setProps(jids)
def setProps(self, jids):
assert type(jids) is list and len(jids), "Must specify a list of jids to get the pictures for"
self.jids = jids
def toProtocolTreeNode(self):
node = super(ListPicturesIqProtocolEntity, self).toProtocolTreeNode()
userNodes = [ProtocolTreeNode("user", {"jid": jid}) for jid in self.jids]
listNode = ProtocolTreeNode("list", {}, userNodes)
node.addChild(listNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = PictureIqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = ListPicturesIqProtocolEntity
jids = [userNode.getAttributeValue("jid") for userNode in node.getChild("list").getAllChildren()]
entity.setProps(jids)
return entity | 1,346 | Python | .py | 30 | 37.5 | 105 | 0.666413 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,511 | test_iq_status_set.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/test_iq_status_set.py | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
from yowsup.layers.protocol_profiles.protocolentities import SetStatusIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class SetStatusIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(SetStatusIqProtocolEntityTest, self).setUp()
self.ProtocolEntity = SetStatusIqProtocolEntity
statusNode = ProtocolTreeNode("status", {}, [], b"Hey there, I'm using WhatsApp")
self.node.addChild(statusNode)
| 540 | Python | .py | 9 | 54.888889 | 89 | 0.803774 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,512 | iq_unregister.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_unregister.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class UnregisterIqProtocolEntity(IqProtocolEntity):
XMLNS = "urn:xmpp:whatsapp:account"
def __init__(self):
super(UnregisterIqProtocolEntity, self).__init__(_type = "get", to = YowConstants.WHATSAPP_SERVER)
def toProtocolTreeNode(self):
node = super(UnregisterIqProtocolEntity, self).toProtocolTreeNode()
rmNode = ProtocolTreeNode("remove", {"xmlns": self.__class__.XMLNS})
node.addChild(rmNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = UnregisterIqProtocolEntity
removeNode = node.getChild("remove")
assert removeNode["xmlns"] == UnregisterIqProtocolEntity.XMLNS, "Not an account delete xmlns, got %s" % removeNode["xmlns"]
return entity | 988 | Python | .py | 19 | 45.473684 | 131 | 0.735477 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,513 | iq_statuses_get.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_statuses_get.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class GetStatusesIqProtocolEntity(IqProtocolEntity):
XMLNS = "status"
def __init__(self, jids, _id = None):
"""
Request the statuses of users. Should be sent once after login.
Args:
- jids: A list of jids representing the users whose statuses you are
trying to get.
"""
super(GetStatusesIqProtocolEntity, self).__init__(self.__class__.XMLNS, _id, _type = "get", to = YowConstants.WHATSAPP_SERVER)
self.setGetStatusesProps(jids)
def setGetStatusesProps(self, jids):
assert type(jids) is list, "jids must be a list of jids"
self.jids = jids
def __str__(self):
out = super(GetStatusesIqProtocolEntity, self).__str__()
out += "Numbers: %s\n" % (",".join(self.numbers))
return out
def toProtocolTreeNode(self):
users = [ProtocolTreeNode("user", {'jid': jid}) for jid in self.jids]
node = super(GetStatusesIqProtocolEntity, self).toProtocolTreeNode()
statusNode = ProtocolTreeNode("status", None, users)
node.addChild(statusNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = GetStatusesIqProtocolEntity
statusNode = node.getChild("status")
userNodes = statusNode.getAllChildren()
jids = [user['jid'] for user in userNodes]
entity.setGetStatusesProps(jids)
return entity
| 1,655 | Python | .py | 36 | 38 | 134 | 0.673507 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,514 | test_iq_privacy_result.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/test_iq_privacy_result.py | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
from yowsup.layers.protocol_profiles.protocolentities import ResultPrivacyIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
entity = ResultPrivacyIqProtocolEntity({"profile":"all","last":"none","status":"contacts"})
class ResultPrivacyIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(ResultPrivacyIqProtocolEntityTest, self).setUp()
self.ProtocolEntity = ResultPrivacyIqProtocolEntity
self.node = entity.toProtocolTreeNode()
| 568 | Python | .py | 9 | 58.777778 | 91 | 0.824057 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,515 | iq_privacy_set.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_privacy_set.py | from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
'''
<iq xmlns="privacy" type="set" id="{{IQ_ID}}">
<privacy>
<category name="status" value="none">
<category name="profile" value="none">
<category name="last" value="none">
</category>
</privacy>
</iq>
'''
class SetPrivacyIqProtocolEntity(IqProtocolEntity):
NAMES = ["status", "profile", "last"]
VALUES = ["all", "contacts", "none"]
XMLNS = "privacy"
def __init__(self, value="all", names = None):
# names can be a string with some element in VALUES or an array with strings with elements in VALUES
# by default, all names are used
super(SetPrivacyIqProtocolEntity, self).__init__(self.__class__.XMLNS, _type="set")
self.setNames(names)
self.setValue(value)
@staticmethod
def checkValidNames(names):
names = names if names else SetPrivacyIqProtocolEntity.NAMES
if not type(names) is list:
names = [names]
for name in names:
if not name in SetPrivacyIqProtocolEntity.NAMES:
raise Exception("Name should be in: '" + "', '".join(SetPrivacyIqProtocolEntity.NAMES) + "' but is '" + name + "'")
return names
@staticmethod
def checkValidValue(value):
if not value in SetPrivacyIqProtocolEntity.VALUES:
raise Exception("Value should be in: '" + "', '".join(SetPrivacyIqProtocolEntity.VALUES) + "' but is '" + value + "'")
return value
def setNames(self, names):
self.names = SetPrivacyIqProtocolEntity.checkValidNames(names)
def setValue(self, value):
self.value = SetPrivacyIqProtocolEntity.checkValidValue(value)
def toProtocolTreeNode(self):
node = super(SetPrivacyIqProtocolEntity, self).toProtocolTreeNode()
queryNode = ProtocolTreeNode(self.__class__.XMLNS)
for name in self.names:
listNode = ProtocolTreeNode("category", {"name": name, "value": self.value})
queryNode.addChild(listNode)
node.addChild(queryNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = SetPrivacyIqProtocolEntity
privacyNode = node.getChild(SetPrivacyIqProtocolEntity.XMLNS)
names = []
for categoryNode in privacyNode.getAllChildren():
names.append(categoryNode["name"])
entity.setNames(names)
entity.setValue("all")
return entity
| 2,562 | Python | .py | 59 | 36.338983 | 131 | 0.673887 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,516 | iq_privacy_result.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_privacy_result.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
'''
<iq type="result" from="{{JID}}@s.whatsapp.net" id="{{IQ:ID}}">
<privacy>
<category name="last" value="all">
</category>
<category name="status" value="all">
</category>
<category name="profile" value="all">
</category>
</privacy>
</iq>
'''
class ResultPrivacyIqProtocolEntity(ResultIqProtocolEntity):
NODE_PRIVACY="privacy"
def __init__(self, privacy):
super(ResultPrivacyIqProtocolEntity, self).__init__()
self.setProps(privacy)
def setProps(self, privacy):
assert type(privacy) is dict, "Privacy must be a dict {name => value}"
self.privacy = privacy
def __str__(self):
out = super(ResultPrivacyIqProtocolEntity, self).__str__()
out += "Privacy settings\n"
for name, value in self.privacy.items():
out += "Category %s --> %s\n" % (name, value)
return out
def toProtocolTreeNode(self):
node = super(ResultPrivacyIqProtocolEntity, self).toProtocolTreeNode()
queryNode = ProtocolTreeNode(self.__class__.NODE_PRIVACY)
node.addChild(queryNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(ResultPrivacyIqProtocolEntity, ResultPrivacyIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = ResultPrivacyIqProtocolEntity
privacyNode = node.getChild(ResultPrivacyIqProtocolEntity.NODE_PRIVACY)
privacy = {}
for categoryNode in privacyNode.getAllChildren():
privacy[categoryNode["name"]] = categoryNode["value"]
entity.setProps(privacy)
return entity
| 1,719 | Python | .py | 43 | 34.069767 | 111 | 0.694428 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,517 | iq_status_set.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_status_set.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
import logging
logger = logging.getLogger(__name__)
class SetStatusIqProtocolEntity(IqProtocolEntity):
'''
<iq to="s.whatsapp.net" xmlns="status" type="set" id="{{IQ_ID}}">
<status>{{MSG}}</status>
</notification>
'''
XMLNS = "status"
def __init__(self, text = None, _id = None):
if type(text) is not bytes:
logger.warning("Passing text as str is deprecated, pass bytes instead")
text = bytes(text, "latin-1")
super(SetStatusIqProtocolEntity, self).__init__(self.__class__.XMLNS, _id, _type = "set", to = YowConstants.WHATSAPP_SERVER)
self.setData(text)
def setData(self, text):
self.text = text
def toProtocolTreeNode(self):
node = super(SetStatusIqProtocolEntity, self).toProtocolTreeNode()
statusNode = ProtocolTreeNode("status", {}, [], self.text)
node.addChild(statusNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = SetStatusIqProtocolEntity
statusNode = node.getChild("status")
entity.setData(statusNode.getData())
return entity
| 1,359 | Python | .py | 32 | 35.78125 | 132 | 0.680545 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,518 | test_iq_privacy_get.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/test_iq_privacy_get.py | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
from yowsup.layers.protocol_profiles.protocolentities import GetPrivacyIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
entity = GetPrivacyIqProtocolEntity()
class GetPrivacyIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(GetPrivacyIqProtocolEntityTest, self).setUp()
self.ProtocolEntity = GetPrivacyIqProtocolEntity
self.node = entity.toProtocolTreeNode()
| 502 | Python | .py | 9 | 51.444444 | 87 | 0.839104 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,519 | iq_picture.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_picture.py | from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
class PictureIqProtocolEntity(IqProtocolEntity):
'''
When receiving a profile picture:
<iq type="result" from="{{jid}}" id="{{id}}">
<picture type="image" id="{{another_id}}">
{{Binary bytes of the picture.}}
</picture>
</iq>
'''
XMLNS = "w:profile:picture"
def __init__(self, jid, _id = None, type = "get"):
super(PictureIqProtocolEntity, self).__init__(self.__class__.XMLNS, _id = _id, _type=type, to = jid) | 542 | Python | .py | 13 | 36.076923 | 108 | 0.627599 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,520 | test_iq_unregister.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/test_iq_unregister.py | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
from yowsup.layers.protocol_profiles.protocolentities import UnregisterIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class UnregisterIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(UnregisterIqProtocolEntityTest, self).setUp()
self.ProtocolEntity = UnregisterIqProtocolEntity
self.node.addChild(ProtocolTreeNode("remove", {"xmlns": "urn:xmpp:whatsapp:account"})) | 509 | Python | .py | 8 | 59.125 | 94 | 0.824351 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,521 | iq_picture_get.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_picture_get.py | from .iq_picture import PictureIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class GetPictureIqProtocolEntity(PictureIqProtocolEntity):
'''
<iq type="get" id="{{id}}" xmlns="w:profile:picture", to={{jid}}">
<picture type="image | preview">
</picture>
</iq>'''
def __init__(self, jid, preview = True, _id = None):
super(GetPictureIqProtocolEntity, self).__init__(jid, _id, "get")
self.setGetPictureProps(preview)
def setGetPictureProps(self, preview = True):
self.preview = preview
def isPreview(self):
return self.preview
def toProtocolTreeNode(self):
node = super(GetPictureIqProtocolEntity, self).toProtocolTreeNode()
pictureNode = ProtocolTreeNode("picture", {"type": "preview" if self.isPreview() else "image" })
node.addChild(pictureNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = PictureIqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = GetPictureIqProtocolEntity
entity.setGetPictureProps(node.getChild("picture").getAttributeValue("type"))
return entity | 1,166 | Python | .py | 26 | 38.038462 | 104 | 0.693052 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,522 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/__init__.py | from .iq_unregister import UnregisterIqProtocolEntity
from .iq_status_set import SetStatusIqProtocolEntity
from .iq_statuses_get import GetStatusesIqProtocolEntity
from .iq_statuses_result import ResultStatusesIqProtocolEntity
from .iq_picture_get import GetPictureIqProtocolEntity
from .iq_picture_get_result import ResultGetPictureIqProtocolEntity
from .iq_pictures_list import ListPicturesIqProtocolEntity
from .iq_picture_set import SetPictureIqProtocolEntity
from .iq_privacy_set import SetPrivacyIqProtocolEntity
from .iq_privacy_get import GetPrivacyIqProtocolEntity
from .iq_privacy_result import ResultPrivacyIqProtocolEntity
| 635 | Python | .py | 11 | 56.727273 | 67 | 0.894231 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,523 | iq_privacy_get.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_privacy_get.py | from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
'''
<iq xmlns="privacy" type="get" id="{{IQ_ID}}">
<privacy>
</privacy>
</iq>
'''
class GetPrivacyIqProtocolEntity(IqProtocolEntity):
XMLNS = "privacy"
def __init__(self):
super(GetPrivacyIqProtocolEntity, self).__init__(self.__class__.XMLNS, _type="get")
def toProtocolTreeNode(self):
node = super(GetPrivacyIqProtocolEntity, self).toProtocolTreeNode()
queryNode = ProtocolTreeNode(self.__class__.XMLNS)
node.addChild(queryNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
assert node.getChild(GetPrivacyIqProtocolEntity.XMLNS) is not None, "Not a get privacy iq node %s" % node
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = GetPrivacyIqProtocolEntity
return entity
| 919 | Python | .py | 23 | 34.782609 | 113 | 0.723094 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,524 | test_iq_privacy_set.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/test_iq_privacy_set.py | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
from yowsup.layers.protocol_profiles.protocolentities import SetPrivacyIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
entity = SetPrivacyIqProtocolEntity("all", ["profile","last","status"])
class SetPrivacyIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(SetPrivacyIqProtocolEntityTest, self).setUp()
self.ProtocolEntity = SetPrivacyIqProtocolEntity
self.node = entity.toProtocolTreeNode()
| 536 | Python | .py | 9 | 55.222222 | 87 | 0.822857 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,525 | iq_statuses_result.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_statuses_result.py | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
class ResultStatusesIqProtocolEntity(IqProtocolEntity):
'''
<iq type="result" from="s.whatsapp.net" id="1">
<status>
<user jid="{number}@s.whatsapp.net" t="1330555420">
{status message}
HEX:{status message in hex}
</user>
<user jid="{number}@s.whatsapp.net" t="1420813055">
{status message}
HEX:{status message in hex}
</user>
</status>
</iq>
'''
XMLNS = 'status'
def __init__(self, _id, _from, statuses):
super(ResultStatusesIqProtocolEntity, self).__init__(self.__class__.XMLNS, _id, 'result', _from=_from)
self.setResultStatusesProps(statuses)
def setResultStatusesProps(self, statuses):
assert type(statuses) is dict, "statuses must be dict"
self.statuses = statuses
def __str__(self):
out = super(ResultStatusesIqProtocolEntity, self).__str__()
out += "Statuses: %s\n" % ','.join(jid + '(' + str(v) + ')' for jid, v in self.statuses.items())
return out
def toProtocolTreeNode(self):
node = super(ResultStatusesIqProtocolEntity, self).toProtocolTreeNode()
users = [ProtocolTreeNode('user', {'jid': jid, 't': t}, None, status) for jid, (status, t) in self.statuses.items()]
statusNode = ProtocolTreeNode('status', None, users)
node.addChild(statusNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
statusNode = node.getChild('status')
users = statusNode.getAllChildren()
statuses = dict()
for user in users:
statuses[user['jid']] = (user.getData(), user['t'])
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = ResultStatusesIqProtocolEntity
entity.setResultStatusesProps(statuses)
return entity
| 1,999 | Python | .py | 45 | 35.644444 | 124 | 0.62885 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,526 | iq_picture_get_result.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_picture_get_result.py | from .iq_picture import PictureIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class ResultGetPictureIqProtocolEntity(PictureIqProtocolEntity):
'''
<iq type="result" from="{{jid}}" id="{{id}}">
<picture type="image | preview" id="{{another_id}}">
{{Binary bytes of the picture.}}
</picture>
</iq>
'''
def __init__(self, jid, pictureData, pictureId, preview = True, _id = None):
super(ResultGetPictureIqProtocolEntity, self).__init__(jid, _id, "result")
self.setResultPictureProps(pictureData, pictureId, preview)
def setResultPictureProps(self, pictureData, pictureId, preview = True):
self.preview = preview
self.pictureData = pictureData
self.pictureId = pictureId
def isPreview(self):
return self.preview
def getPictureData(self):
return self.pictureData
def getPictureId(self):
return self.pictureId
def writeToFile(self, path):
with open(path, "wb") as outFile:
outFile.write(self.getPictureData())
def toProtocolTreeNode(self):
node = super(ResultGetPictureIqProtocolEntity, self).toProtocolTreeNode()
pictureNode = ProtocolTreeNode({"type": "preview" if self.isPreview() else "image" }, data = self.getPictureData())
node.addChild(pictureNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = PictureIqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = ResultGetPictureIqProtocolEntity
pictureNode = node.getChild("picture")
entity.setResultPictureProps(pictureNode.getData(), pictureNode.getAttributeValue("id"), pictureNode.getAttributeValue("type") == "preview")
return entity | 1,766 | Python | .py | 38 | 39.210526 | 148 | 0.695703 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,527 | iq_picture_set.py | tgalal_yowsup/yowsup/layers/protocol_profiles/protocolentities/iq_picture_set.py | from .iq_picture import PictureIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
import time
class SetPictureIqProtocolEntity(PictureIqProtocolEntity):
'''
<iq type="set" id="{{id}}" xmlns="w:profile:picture", to={{jid}}">
<picture type="image" id="{{another_id}}">
{{Binary bytes of the picture when type is set.}}
</picture>
</iq>
'''
def __init__(self, jid, previewData, pictureData, pictureId = None, _id = None):
super(SetPictureIqProtocolEntity, self).__init__(jid, _id, "set")
self.setSetPictureProps(previewData, pictureData, pictureId)
def setSetPictureProps(self, previewData, pictureData, pictureId = None):
self.setPictureData(pictureData)
self.setPictureId(pictureId or str(int(time.time())))
self.setPreviewData(previewData)
def setPictureData(self, pictureData):
self.pictureData = pictureData
def getPictureData(self):
return self.pictureData
def setPreviewData(self, previewData):
self.previewData = previewData
def getPreviewData(self):
return self.previewData
def setPictureId(self, pictureId):
self.pictureId = pictureId
def getPictureId(self):
return self.pictureId
def toProtocolTreeNode(self):
node = super(PictureIqProtocolEntity, self).toProtocolTreeNode()
attribs = {"type": "image", "id": self.pictureId}
pictureNode = ProtocolTreeNode("picture", attribs, None, self.getPictureData())
previewNode = ProtocolTreeNode("picture", {"type": "preview"}, None, self.getPreviewData())
node.addChild(pictureNode)
node.addChild(previewNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = PictureIqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = SetPictureIqProtocolEntity
pictureNode = None
previewNode = None
for child in node.getAllChildren("picture"):
nodeType = child.getAttributeValue("type")
if nodeType == "image":
pictureNode = child
elif nodeType == "preview":
previewNode = child
entity.setSetPictureProps(previewNode.getData(), pictureNode.getData(), pictureNode.getAttributeValue("id"))
return entity | 2,336 | Python | .py | 52 | 36.961538 | 116 | 0.682379 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,528 | decoder.py | tgalal_yowsup/yowsup/layers/coder/decoder.py | from yowsup.structs import ProtocolTreeNode
import math
import binascii
import sys
import zlib
class ReadDecoder:
def __init__(self, tokenDictionary):
self.tokenDictionary = tokenDictionary
def getProtocolTreeNode(self, data):
if type(data) is list:
data = bytearray(data)
if data[0] & self.tokenDictionary.FLAG_DEFLATE != 0:
data = bytearray(b'\x00' + zlib.decompress(bytes(data[1:])))
if data[0] & self.tokenDictionary.FLAG_SEGMENTED != 0:
raise ValueError("server to client stanza fragmentation not supported")
return self.nextTreeInternal(data[1:])
def getToken(self, index, data):
token = self.tokenDictionary.getToken(index)
if not token:
index = self.readInt8(data)
token = self.tokenDictionary.getToken(index, True)
if not token:
raise ValueError("Invalid token %s" % token)
return token
def getTokenDouble(self, n, n2):
pos = n2 + n * 256
token = self.tokenDictionary.getToken(pos, True)
if not token:
raise ValueError("Invalid token %s" % pos)
return token
def streamStart(self, data):
self.streamStarted = True
tag = data.pop(0)
size = self.readListSize(tag, data)
tag = data.pop(0)
if tag != 1:
if tag == 236:
tag = data.pop(0) + 237
token = self.getToken(tag, data)#self.tokenDictionary.getToken(tag)
raise Exception("expecting STREAM_START in streamStart, instead got token: %s" % token)
attribCount = (size - 2 + size % 2) / 2
self.readAttributes(attribCount, data)
def readNibble(self, data):
_byte = self.readInt8(data)
ignoreLastNibble = bool(_byte & 0x80)
size = (_byte & 0x7f)
nrOfNibbles = size * 2 - int(ignoreLastNibble)
dataArr = self.readArray(size, data)
string = ''
for i in range(0, nrOfNibbles):
_byte = dataArr[int(math.floor(i/2))]
_shift = 4 * (1 - i % 2)
dec = (_byte & (15 << _shift)) >> _shift
if dec in (0,1,2,3,4,5,6,7,8,9):
string += str(dec)
elif dec in (10, 11):
string += chr(dec - 10 + 45)
else:
raise Exception("Bad nibble %s" % dec)
return string
def readPacked8(self, n, data):
size = self.readInt8(data)
remove = 0
if (size & 0x80) != 0 and n == 251:
remove = 1
size = size & 0x7F
text = bytearray(self.readArray(size, data))
hexData = binascii.hexlify(str(text) if sys.version_info < (2,7) else text).upper()
dataSize = len(hexData)
out = []
if remove == 0:
for i in range(0, dataSize):
char = chr(hexData[i]) if type(hexData[i]) is int else hexData[i] #python2/3 compat
val = ord(binascii.unhexlify("0%s" % char))
if i == (dataSize - 1) and val > 11 and n != 251: continue
out.append(self.unpackByte(n, val))
else:
out = map(ord, list(hexData[0: -remove])) if sys.version_info < (3,0) else list(hexData[0: -remove])
return out
def unpackByte(self, n, n2):
if n == 251:
return self.unpackHex(n2)
if n == 255:
return self.unpackNibble(n2)
raise ValueError("bad packed type %s" % n)
def unpackHex(self, n):
if n in range(0, 10):
return n + 48
if n in range(10, 16):
return 65 + (n - 10)
raise ValueError("bad hex %s" % n)
def unpackNibble(self, n):
if n in range(0, 10):
return n + 48
if n in (10, 11):
return 45 + (n - 10)
raise ValueError("bad nibble %s" % n)
def readHeader(self, data, offset = 0):
ret = 0
if len(data) >= (3 + offset):
b0 = data[offset]
b1 = data[offset + 1]
b2 = data[offset + 2]
ret = b0 + (b1 << 16) + (b2 << 8)
return ret
def readInt8(self, data):
return data.pop(0);
def readInt16(self, data):
intTop = data.pop(0)
intBot = data.pop(0)
value = (intTop << 8) + intBot
if value is not None:
return value
else:
return ""
def readInt20(self, data):
int1 = data.pop(0)
int2 = data.pop(0)
int3 = data.pop(0)
return ((int1 & 0xF) << 16) | (int2 << 8) | int3
def readInt24(self, data):
int1 = data.pop(0)
int2 = data.pop(0)
int3 = data.pop(0)
value = (int1 << 16) + (int2 << 8) + (int3 << 0)
return value
def readInt31(self, data):
data.pop(0)
int1 = data.pop(0)
int2 = data.pop(0)
int3 = data.pop(0)
return (int1 << 24) | (int1 << 16) | int2 << 8 | int3
def readListSize(self,token, data):
size = 0
if token == 0:
size = 0
else:
if token == 248:
size = self.readInt8(data)
else:
if token == 249:
size = self.readInt16(data)
else:
raise Exception("invalid list size in readListSize: token " + str(token))
return size
def readAttributes(self, attribCount, data):
attribs = {}
for i in range(0, int(attribCount)):
key = self.readString(self.readInt8(data), data)
value = self.readString(self.readInt8(data), data)
attribs[key]=value
return attribs
def readString(self,token, data):
if token == -1:
raise Exception("-1 token in readString")
if 2 < token < 236:
return self.getToken(token, data)
if token == 0:
return None
if token in (236, 237, 238, 239):
return self.getTokenDouble(token - 236, self.readInt8(data))
if token == 250:
user = self.readString(data.pop(0), data)
server = self.readString(data.pop(0), data)
if user is not None and server is not None:
return user + "@" + server
if server is not None:
return server
raise Exception("readString couldn't reconstruct jid")
if token in (251, 255):
return "".join(map(chr, self.readPacked8(token, data)))
if token == 252:
size8 = self.readInt8(data)
buf8 = self.readArray(size8, data)
return "".join(map(chr, buf8))
if token == 253:
size20 = self.readInt20(data)
buf20 = self.readArray(size20, data)
return "".join(map(chr, buf20))
if token == 254:
size31 = self.readInt31()
buf31 = self.readArray(size31, data)
return "".join(map(chr, buf31))
raise Exception("readString couldn't match token "+str(token))
def readArray(self, length, data):
out = data[:length]
del data[:length]
return out
def nextTreeInternal(self, data):
size = self.readListSize(self.readInt8(data), data)
token = self.readInt8(data)
if token == 1:
token = self.readInt8(data)
if token == 2:
return None
tag = self.readString(token, data)
if size == 0 or tag is None:
raise ValueError("nextTree sees 0 list or null tag")
attribCount = (size - 2 + size % 2)/2
attribs = self.readAttributes(attribCount, data)
if size % 2 ==1:
return ProtocolTreeNode(tag, attribs)
read2 = self.readInt8(data)
nodeData = None
nodeChildren = None
if self.isListTag(read2):
nodeChildren = self.readList(read2, data)
elif read2 == 252:
size = self.readInt8(data)
nodeData = bytes(self.readArray(size, data))
elif read2 == 253:
size = self.readInt20(data)
nodeData = bytes(self.readArray(size, data))
elif read2 == 254:
size = self.readInt31(data)
nodeData = bytes(self.readArray(size, data))
elif read2 in (255, 251):
nodeData = self.readPacked8(read2, data)
else:
nodeData = self.readString(read2, data)
return ProtocolTreeNode(tag, attribs, nodeChildren, nodeData)
def readList(self,token, data):
size = self.readListSize(token, data)
listx = []
for i in range(0,size):
listx.append(self.nextTreeInternal(data))
return listx;
def isListTag(self, b):
return b in (248, 0, 249)
| 8,808 | Python | .py | 229 | 28.021834 | 113 | 0.547661 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,529 | test_tokendictionary.py | tgalal_yowsup/yowsup/layers/coder/test_tokendictionary.py | from yowsup.layers.coder.tokendictionary import TokenDictionary
import unittest
class TokenDictionaryTest(unittest.TestCase):
def setUp(self):
self.tokenDictionary = TokenDictionary()
def test_getToken(self):
self.assertEqual(self.tokenDictionary.getToken(10), "iq")
def test_getIndex(self):
self.assertEqual(self.tokenDictionary.getIndex("iq"), (10, False))
def test_getSecondaryToken(self):
self.assertEqual(self.tokenDictionary.getToken(238), "lc")
def test_getSecondaryTokenExplicit(self):
self.assertEqual(self.tokenDictionary.getToken(11, True), "reject")
def test_getSecondaryIndex(self):
self.assertEqual(self.tokenDictionary.getIndex("reject"), (11, True)) | 742 | Python | .py | 15 | 43.4 | 77 | 0.745505 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,530 | test_decoder.py | tgalal_yowsup/yowsup/layers/coder/test_decoder.py | import unittest
from yowsup.layers.coder.decoder import ReadDecoder
from yowsup.layers.coder.tokendictionary import TokenDictionary
from yowsup.structs import ProtocolTreeNode
class DecoderTest(unittest.TestCase):
def setUp(self):
self.decoder = ReadDecoder(TokenDictionary())
self.decoder.streamStarted = True
def test_decode(self):
data = bytearray([0, 248, 6, 9, 11, 252, 3, 120, 121, 122, 5, 252, 3, 97, 98, 99, 248, 1, 248, 4, 50, 238, 86, 255, 130, 18, 63,
252, 6, 49, 50, 51, 52, 53, 54])
node = self.decoder.getProtocolTreeNode(data)
targetNode = ProtocolTreeNode("message", {"from": "abc", "to":"xyz"}, [ProtocolTreeNode("media", {"width" : "123"}, data=b"123456")])
self.assertEqual(node, targetNode)
| 781 | Python | .py | 14 | 49.785714 | 141 | 0.677546 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,531 | test_encoder.py | tgalal_yowsup/yowsup/layers/coder/test_encoder.py | import unittest
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.coder.encoder import WriteEncoder
from yowsup.layers.coder.tokendictionary import TokenDictionary
class EncoderTest(unittest.TestCase):
def setUp(self):
self.res = []
self.encoder = WriteEncoder(TokenDictionary())
def test_encode(self):
node = ProtocolTreeNode("message", {"from": "abc", "to":"xyz"}, [ProtocolTreeNode("media", {"width" : "123"}, data=b"123456")])
result = self.encoder.protocolTreeNodeToBytes(node)
self.assertTrue(result in (
[0, 248, 6, 9, 11, 252, 3, 120, 121, 122, 5, 252, 3, 97, 98, 99, 248, 1, 248, 4, 50, 238, 86, 255, 130, 18, 63,
252, 6, 49, 50, 51, 52, 53, 54],
[0, 248, 6, 9, 5, 252, 3, 97, 98, 99, 11, 252, 3, 120, 121, 122, 248, 1, 248, 4, 50, 238, 86, 255, 130, 18, 63,
252, 6, 49, 50, 51, 52, 53, 54]
)
)
| 939 | Python | .py | 18 | 44.388889 | 135 | 0.603053 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,532 | tokendictionary.py | tgalal_yowsup/yowsup/layers/coder/tokendictionary.py | class TokenDictionary:
FLAG_SEGMENTED = 0x1
FLAG_DEFLATE = 0x2
def __init__(self):
self.dictionary = [
'',
'xmlstreamstart',
'xmlstreamend',
'type',
'id',
'from',
'receipt',
't',
's.whatsapp.net',
'message',
'iq',
'to',
'participant',
'ack',
'enc',
'plaintext_size',
'compressed_size',
'class',
'v',
'user',
'jid',
'notify',
'host',
'off_cnt',
'value',
'1',
'xmlns',
'result',
'media_conn',
'read',
'offline',
'mediatype',
'presence',
'edit',
'notification',
'get',
'item',
'phash',
'skmsg',
'text',
'status',
'broadcast',
'g.us',
'hostname',
'contact',
'image',
'set',
'participants',
'0',
'chatstate',
'media',
'success',
'ib',
'subject',
'picture',
'seen',
'ping',
'w',
'retry',
'unavailable',
'config',
'msg',
'ip6',
'ip4',
'video',
'ttl',
'auth_ttl',
'max_buckets',
'count',
'composing',
'call',
'w:p',
'auth',
'call-creator',
'props',
'last',
'creation',
'location',
'hash',
'bits',
'list',
'gcm',
'deny',
'call-id',
'pop',
'subscribe',
'te',
'preview',
'multicast',
'gif',
'code',
'relaylatency',
'download',
'primary',
'pkmsg',
'action',
'order',
'add',
'delivery',
'routing_info',
'edge_routing',
'dns_domain',
'w:m',
'available',
'mmg.whatsapp.net',
'contacts',
'fallback',
'download_buckets',
'name',
'audio',
'in',
'played',
'fail',
'platform',
'urn:xmpp:ping',
'fna',
'upload',
'ptt',
'urn:xmpp:whatsapp:push',
'verified_name',
'paused',
'update',
'key',
'out',
'error',
'query',
'true',
'business',
'atn',
'401',
'usync',
'delete',
'unread',
'w:stats',
'w:profile:picture',
'url',
'sidelist',
'net',
'medium',
'state',
'sticker',
'active',
'frc',
'prop',
'web',
'encrypt',
'identity',
'verified_level',
'document',
'w:compress',
'w:gp2',
'latency',
'mode',
'transport',
'registration',
'opus',
'rate',
'keygen',
'encopt',
'profile',
'priority',
'orientation',
'mute',
'unknown',
'none',
'resume',
'offer',
'ver',
'capability',
'sid',
'index',
'context',
'terminate',
'transaction-id',
'false',
'default',
'business_hours_config',
'serial',
'reason',
'side_list',
'version',
'screen_width',
'stream:error',
'tsoffline',
'features',
'token',
'relay',
'videostate',
'contact_remove',
'contact_add',
'remove',
'tag',
'refresh',
'protocol',
'e',
'resume_check',
'media_type',
'w:web',
'invite',
'group',
'readreceipts',
'note.m4r',
'jabber:iq:privacy',
'disable',
'background',
'delta',
'direct_path',
'conflict',
'skey',
'preaccept',
'admin',
'signature',
'404',
'item-not-found',
'day_of_week',
'accept',
'interactive',
'timeoffline',
'apple',
'sync',
'open_time',
'close_time',
'user_add',
'full',
'screen_height',
'timeout',
'duration',
'audio_duration',
'voip_settings',
'callee_updated_payload',
'description',
'rte',
'not-authorized',
'groups',
'voip',
'uploadfieldstat'
]
self.secondaryDictionary = [
'lg',
'lc',
's_t',
's_o',
'Opening.m4r',
'feature',
'complete',
'allow',
'from_ip',
'to_ip',
'creator',
'reject',
'video_duration',
'maxfpp',
'rc_dyn',
'privacy',
'ip_config',
'enable_ssrc_demux',
're',
'proto',
'latency_update_threshold',
'category',
'timestamp',
'specific_hours',
'options',
'url_text',
'nack',
'aud_pkt_reorder_pct',
'server-error',
'invalid',
'cond_net_medium',
'vertical',
'canonical',
'passive',
'is_biz',
'w:g2',
'cond_range_rtt',
'encode',
'dtx',
'group_info',
'ts',
'business_hours',
'timezone',
'target_bitrate',
'end',
'modify',
'en',
'user_remove',
'minfpp',
'superadmin',
'request',
'enable_audio_oob_fec_feature',
'log',
'userrate',
'vid_rc',
'max_bitrate',
'init_bwe',
'test_flags',
'max_tx_rott_based_bitrate',
'max_bytes',
'init_bitrate',
'use_local_probing_rx_bitrate',
'open_24h',
'mtu_size',
'enable_audio_pkt_piggyback_for_sender',
'enable_audio_piggyback_feature',
'enable_audio_oob_fec_for_sender',
'audio_piggyback_timeout_msec',
'audio_oob_fec_max_pkts',
'cond_range_packet_loss_pct',
'video_codec_priority',
'source_action',
'rows_seen',
'ad_position',
'event',
'Tri-tone.caf',
'rc',
'promote',
'off',
'enable_periodical_aud_rr_processing',
'cond_range_target_total_bitrate',
'cond_congestion_signal_mask',
'cond_congestion_no_rtcp_thr',
'cond_congestion_no_init_rtt_thr',
'group_update',
'author',
'interruption',
'keys',
'address',
'403',
'identity_verification',
'chord.m4r',
'forbidden',
'enc_supported',
'enc_rekey',
'body',
'email',
'thu',
'begin',
'wed',
'tue',
'busy',
'mon',
'fri',
'all',
'website',
'bamboo.m4r',
'live',
'battery',
'os',
'browser',
'encrypt_video',
'encrypt_v2',
'encrypt_url',
'encrypt_location',
'encrypt_image',
'encrypt_group_gen2',
'encrypt_contact',
'encrypt_blist',
'encrypt_audio',
'client',
'aurora.m4r',
'connected',
'Glass.caf',
'sat',
'recipient',
'create',
'rotate',
'popcorn.m4r',
'fbip',
'caller_bad_asn',
'sonar',
'mediaretry',
'dirty',
'longitude',
'latitude',
'405',
'callee_bad_asn',
'source',
'elapsed',
'circles.m4r',
'final',
'not-allowed',
'new',
'complete.m4r',
'status_session_summary',
'event_seq',
'locked',
'hello.m4r',
'xor_cipher',
'p2',
'p1',
'enabled',
'vcard',
'vid_rc_dyn',
'sun',
'demote',
'required',
'video_max_edge',
'video_max_bitrate',
'status_video_max_duration',
'status_video_max_bitrate',
'status_image_quality',
'status_image_max_edge',
'media_max_autodownload',
'max_subject',
'max_participants',
'max_keys',
'image_quality',
'image_max_kbytes',
'image_max_edge',
'file_max_size',
'lists',
'gif_provider',
'payments_disable_switch_psp',
'keys.m4r',
'microsoft',
'old',
'p256dh',
'kaios',
'endpoint',
'appointment_only',
'attestation',
'w:biz',
'status_entry',
'low',
'small_call_btn',
'force_long_connect',
'qcount',
'leave',
'flowcontrol',
'clear',
'pulse.m4r',
'Boing.caf',
'participating',
'Bell.caf',
'synth.m4r',
'w:ads',
'crypto',
'response',
'powersave',
'test',
'Chrome',
'input.m4r',
'start',
'announcement',
'cond_range_target_bitrate',
'other',
'2fa',
'digest',
'prof-services',
'America/Sao_Paulo',
'cond_peer_net_medium',
'bank',
'clean',
'Harp.caf',
'te2',
'fanout',
'livelocation',
'maxbwe',
'jb_max_playout_dist',
'TimePassing.caf',
'urn:xmpp:whatsapp:account',
'Windows 10',
'Xylophone.caf',
'size',
'nonce',
'501',
'expiration',
'Desktop',
'google',
'w:b',
'relay_id',
'blacklist',
'locales',
'outgoing',
'password',
'url_number',
'mms_vcache_aggregation_enabled',
'unsubscribe',
'jws',
'business_profile',
'relayelection',
'bitrate',
'retail',
'not_announcement',
'raw',
'ot',
'oid',
'Asia/Calcutta',
'Asia/Kolkata',
'cond_range_remb_minus_peer_rx_br',
'sender_inc_ratio',
'enable_cc_bwe_slow_ramp_up',
'cc_bwe_slow_ramp_up_peer_rx_bitrate',
'cc_bwe_slow_ramp_up_ceiling_multiplier',
'wa_zero_rate_sig',
'terminated',
'batterystate',
'[]',
'apparel',
'urn:xmpp:whatsapp:dirty',
'Asia/Jakarta',
'409',
'target_bitrate_upper_bound',
'peer_state',
'whitelist',
'rekey',
'406',
'Windows 7',
'cache',
'edu',
'400',
'spam_list',
'spam_flow',
'wns',
'contact_array',
'302',
'410',
'languagepack',
'mms_media_key_ttl',
'challenge',
'health',
'max_encode_width',
'bank-ref-id',
'cc',
'max_fps',
'codec_type',
'entertain',
'paid_message',
'407',
'auto',
'psa',
'beauty',
'failure',
'stop',
'bypassed',
'402',
'aec',
'500',
'portpredicting',
'travel',
'max_target_bitrate',
'comb_psnr_sample_interval',
'govt',
'not-a-biz',
'video_frame_crc_sample_interval',
'enable_pli_for_crc_mismatch',
'gdpr',
'grocery',
'min_target_bitrate',
'enable_frame_dropper',
'normalize',
'ns',
'Mac OS 10.13.6',
'America/Belem',
'ad',
'hsm',
'after',
'key_frame_interval',
'503',
'event-plan',
'additive_sender_bwe_inc_near_max',
'Asia/Kuala_Lumpur',
'finance',
'gone',
'Firefox',
'force_additive_sender_bwe_inc',
'America/Bogota',
'c0',
'c1',
'c2',
'504',
'c3',
'vpx_max_intra_bitrate_pct',
'pli_key_frame_pct',
'Mac OS 10.14.0',
'psnr_resolution_ctrl_sample_size',
'overshoot_rate_sample_interval',
'overshoot_rate_ema_sample_size',
'overshoot_rate_downgrade_threshold_pct',
'enc_psnr_downgrade_threshold',
'restaurant',
'vp8_cpu',
'agc',
'spam',
'high',
'bwe',
'Mac OS 10.14.1',
'expiration_ts',
'Africa/Lagos',
'codec_sub_type',
'vid_rc_battery',
'Mac OS 10.10.1',
'Windows 8.1',
'bank-phone-number',
'Safari',
'status_v2',
'gif_search',
'use_audio_packet_rate',
'audio_encode_offload',
'offset',
'transport_stats_p2p_threshold',
'spam_call_threshold_seconds',
'enable_upnp',
'enable_preaccept_received_update',
'enable_new_transport_stats',
'connected_if_received_data',
'vad_threshold',
'precise_rx_timestamps_mask',
'p2p_request_timeout',
'non_speech_bitrate',
'maxfpp_duration',
'echo_detector_mode',
'echo_detector_impl',
'disable_agc',
'caller_end_call_threshold',
'call_start_delay',
'android_call_connected_toast',
'aecm_adapt_step_size',
'cancel_offer',
'wa_log_time_series',
'waLogTimeSeries',
'account',
'delay_based_bwe_trendline_filter_enabled',
'delay_based_bwe_bitrate_estimator_enabled',
'bwe_impl',
'hotel',
'Mac OS 10.12.6',
'America/Mexico_City',
'on_rtp',
'#resource-limit',
'nonprofit',
'Asia/Karachi',
'Asia/Riyadh',
'en-GB',
'rejected',
'chat',
'unlocked',
'America/Manaus',
'block_dialog',
'America/Argentina/Buenos_Aires',
'not-acceptable',
'cbr',
'maxrtt',
'low_data_usage_bitrate',
'complexity',
'algorithm',
'targetlevel',
'limiterenable',
'ec_threshold',
'ec_off_threshold',
'compressiongain',
'use_udp_relay',
'use_tcp_relay',
'use_new_ping_format',
'tcp_relay_bind_timeout_in_msec',
'username',
'unsigned_mode',
'biz_status',
'America/Recife',
'audience',
'internal',
'create_certificate',
'Opera',
'Europe/Istanbul',
'min_packet_loss_pct',
'Linux x86_64',
'setup_failed',
'enc_rekey_retry',
'Mac OS 10.11.6',
'max_packet_loss_pct',
'low_threshold',
'Africa/Johannesburg',
'America/Araguaina',
'prev',
'420',
'max_capture_width',
'cond_rtt_ema_alpha',
'cond_range_ema_rtt',
'America/Noronha',
'Apex.m4r',
'invisible',
'Africa/Harare',
'Asia/Makassar',
'internal-server-error',
'Europe/Rome',
'p2p_pay',
'x',
'Europe/Madrid',
'America/Lima',
'net_medium',
'Africa/Cairo',
'force_logout',
'Asia/Dubai',
'max',
'Africa/Nairobi',
'Mac OS 10.13.3',
'Edge',
'Africa/Accra',
'aecm',
'favorites',
'America/Guayaquil',
'biz',
'America/Asuncion',
'Beacon.m4r',
'408',
'rusr',
'rexp',
'rproc',
'rusrreg',
'vp8_static_threshold',
'packet_loss_mode',
'no_rtcp_received_threshold',
'no_data_received_threshold',
'min_decrease_factor_on_congestion',
'max_key_frame_mode_bitrate',
'low_battery_notify_threshold',
'initial_rtt_congestion_threshold',
'equalize_packet_sizes',
'drop_threshold',
'cellular_bitrate',
'rtt_congestion_step',
'account_info',
'America/La_Paz',
'nack_rtt_interactive_threshold',
'America/Fortaleza',
'transaction',
'Mac OS 10.13.4',
'ka',
'Europe/Moscow',
'Mac OS 10.10.5',
'vpx_min_qp',
'Asia/Jerusalem',
'America/Santo_Domingo',
'vpa',
'relay_bind_failed',
'America/Campo_Grande',
'Asia/Aden',
'America/Caracas',
'Asia/Hong_Kong',
'Asia/Almaty',
'America/Santiago',
'Windows 8',
'es-MX',
'Pacific/Midway',
'Africa/Dar_es_Salaam',
'Europe/Berlin',
'Mac OS 10.13.5',
'America/Costa_Rica',
'Asia/Beirut',
'America/New_York',
'Africa/Porto-Novo',
'Linux i686',
'Mac OS 10.10.4',
'logout',
'America/Montevideo',
'ack_smb',
'Mac OS 10.14',
'Europe/Amsterdam',
'460',
'tos2',
'Asia/Kuwait',
'accept_smb',
'optout',
'America/Guatemala',
'Asia/Amman',
'Africa/Casablanca',
'Africa/Lome',
'backoff',
'psp-routing',
'Windows XP',
'America/Panama',
'America/Tegucigalpa',
'amr',
'Europe/London',
'no-raw-e2e',
'Asia/Muscat',
'upi',
'havehash',
'Africa/Douala',
'psp',
'Ubuntu',
'min',
'adm',
'Mac OS 10.13.2',
'Mac OS 10.13.1',
'America/Buenos_Aires',
'Asia/Singapore',
'Asia/Damascus',
'meta',
'rtcp_vid_plr_max_disorder_dist',
'rtcp_use_new_plr',
'rtcp_aud_plr_max_disorder_dist',
'min_elastic_disorder_buf_size_in_frames',
'max_audio_frame_disorder_distance',
'aud_disorder_dist_hist_reset_interv_in_sec',
'Mac OS 10.11',
'Asia/Shanghai',
'Africa/Kampala',
'Mac OS 10.13',
'Asia/Baku',
'America/Chihuahua',
'provider-type',
'product_catalog',
'ICICI',
'Asia/Bishkek',
'GMT',
'Asia/Bahrain',
'Asia/Qatar',
'Asia/Bangkok',
'Africa/Brazzaville',
'America/El_Salvador',
'US',
'max_rtt',
'builtin',
'credential-id',
'America/Jamaica',
'Mac OS 10.12.5',
'Unauthorized',
'427',
'iOS 8.2',
'Mac OS 10.9.5',
'pay',
'encr_media',
'device-id',
'Asia/Colombo',
'stage',
'Brazil/East',
'w:pay',
'accept2',
'Mac OS 10.11.1',
'page',
'bad-request',
'height',
'expires',
'transaction-prefix',
'America/Cancun',
'width',
'xml-not-well-formed',
'Africa/Khartoum',
'rim',
'es',
'Mac OS 10.14.2',
'pt',
'wa-support-phone-number',
'push',
'silent',
'BR',
'nodal',
'Africa/Kigali',
'counter',
'amount',
'Chromium OS 11021.56.0',
'Asia/Brunei',
'Africa/Maputo',
'Africa/Abidjan',
'Pacific/Majuro',
'Africa/Dakar',
'max_audio_ts_jitter_ms',
'Chromium',
'accept_pay',
'Europe/Brussels',
'Africa/Lusaka',
'Mac OS 10.12',
'Africa/Blantyre',
'seq-no',
'Asia/Tehran',
'pt-PT',
'Ubuntu Chromium',
'policy',
'America/Managua',
'Europe/Andorra',
'smb_tos',
'enable',
'Europe/Bucharest',
'android_record_preset',
'ex',
'America/Boa_Vista',
'en-AU',
'GB',
'sms-prefix',
'sms-gateways',
'providers',
'upi-bank-info',
'Mac OS 10.12.3',
'free',
'sender-alias',
'receiver-alias',
'is_vpa',
'bank-transaction-id',
'America/Eirunepe',
'Asia/Yekaterinburg',
'Mac OS 10.11.5',
'receiver',
'America/Tijuana',
'America/Port_of_Spain',
'currency',
'America/Port-au-Prince',
'uri',
'Asia/Baghdad',
'Africa/Ouagadougou',
'sender',
'Mac OS 10.13.0',
'android_audio_engine',
'limit',
'pin-format-version',
'otp-length',
'mpin-length',
'is-mpin-set',
'bank-name',
'atm-pin-length',
'account-number',
'account-name',
'America/Chicago',
'America/Los_Angeles',
'upi-batch',
'message-id',
'default-debit',
'default-credit',
'price',
'Mac OS 10.12.0',
'Asia/Vladivostok',
'America/Barbados',
'Europe/Paris',
'Asia/Krasnoyarsk',
'w:biz:catalog',
'w:auth:token',
'Mac OS 10.11.4',
'Asia/Yakutsk',
'Mac OS 10.12.4',
'America/Bahia',
'ip',
'cond_min_packet_loss_pct',
'cond_max_rtt',
'America/Toronto',
'Africa/Luanda',
'Asia/Dhaka',
'America/Hermosillo',
'visible',
'Europe/Zurich',
'provider',
'mmid',
'Africa/Libreville',
'Africa/Addis_Ababa',
'self',
'Africa/Ceuta',
'caller_timeout',
'lang',
'total',
'Windows Vista',
'limited',
'Africa/Niamey',
'ifsc-code',
'created',
'account-ref-id',
'Africa/Windhoek',
'America/Bahia_Banderas',
'status_ad',
'call_info',
'ICIWC',
'304',
'pin',
'Mac OS 10.11.3',
'banks',
'ads',
'Asia/Jayapura',
'audio_fps_threshold',
'Atlantic/Azores',
'delay',
'Atlantic/Canary',
'verification-data',
'notif-allowed',
'nodal-allowed',
'Atlantic/South_Georgia',
'iOS Messenger',
'terminator',
'mpin',
'America/Godthab',
'sms-phone-number',
'mcc',
'Asia/Oral',
'Africa/Kinshasa',
'fbid',
'Europe/Lisbon',
'Mac OS 10.12.1',
'Linux',
'Mac OS 10.12.2',
'server',
'Europe/Athens',
'Asia/Taipei',
'Europe/Vienna',
'receiver-vpa',
'future',
'Mac OS 10.11.0',
'vpas',
'Vivaldi',
'Africa/Gaborone',
'America/Monterrey',
'first',
'Europe/Kiev',
'token-type',
'min_media',
'valid',
'psp-config',
'Mac OS 10.10',
'Africa/Bamako',
'ar',
'Africa/Mogadishu',
'owner',
'Chromium OS 10895.78.0',
'America/Puerto_Rico',
'Africa/Bujumbura',
'upi-get-vpa',
'sender-vpa',
'feature-not-implemented',
'Africa/Mbabane',
'America/Phoenix',
'428',
'Poland',
'America/Guadeloupe',
'k1',
'America/Cordoba',
'America/Anguilla',
'Asia/Ho_Chi_Minh',
'INR',
'America/Nassau',
'fr',
'SUCCESS',
'Europe/Minsk',
'US/Indiana-Starke',
'America/Atikokan',
'Indian/Mauritius',
'sts',
'link',
'Europe/Kaliningrad',
'America/Mazatlan',
'Europe/Helsinki',
'Mac OS 10.10.3',
'Africa/Freetown',
'Europe/Sarajevo',
'Mac OS 10.11.2',
'Europe/Tirane',
'upi-get-token',
'speed',
'Australia/Perth',
'paid',
'America/Denver',
'America/Paramaribo',
'tos',
'ru',
'America/Detroit',
'Asia/Tbilisi',
'sound',
'sufficient-balance',
'Europe/Dublin',
'Asia/Seoul',
'Australia/Sydney',
'iOS 12.0.1',
'get-methods',
'Indian/Christmas',
'Asia/Magadan',
'Europe/Warsaw',
'America/Halifax',
'upi-get-accounts',
'uncallable',
'element_name',
'Turkey',
'ES',
'Atlantic/Madeira',
'show',
'before',
'MX',
'tracking_token',
'Africa/Algiers',
'#pay-tos-not-accepted',
'undefined',
'Mac OS 10.6.8',
'violation',
'actor',
'America/Antigua',
'Mac OS 10.9',
'Mac OS 10.8.5',
'Africa/Maseru',
'cancel',
'Asia/Manila',
'America/Merida',
'Africa/Tripoli',
'iOS 12.1',
'Mac OS 10.7.5',
'upi-bind-device',
'wait',
'upi-intent-to-send',
'upi-get-blocked-vpas',
'pcm',
'missing',
'America/St_Johns',
'sender_loss_high',
'Mac OS 10.10.2',
'Mac OS 10.7.3',
'Atlantic/Cape_Verde',
'get-transactions',
'Etc/GMT+3',
'Fedora',
'America/Indiana/Indianapolis',
'Africa/Nouakchott',
'upi-check-mpin',
'mp3',
'Mac OS 10.10.0',
'Asia/Tokyo',
'kind',
'k0',
'expired',
'America/Anchorage',
'tr',
'Asia/Novosibirsk',
'upi-register-vpa',
'otp',
'cts',
'Indian/Mayotte',
'America/Dawson',
'pid-setup',
'America/Regina',
'America/Maceio',
'Africa/Lubumbashi',
'US/Michigan',
'America/Cuiaba',
'Asia/Kamchatka',
'upgrade',
'iOS 11.4.1',
'Asia/Omsk',
'Asia/Katmandu',
'policy-violation',
'Pacific/Honolulu',
'Europe/Riga',
'Asia/Vientiane',
'Africa/Banjul',
'Android 8.0.0',
'Europe/Zagreb',
'Europe/Samara',
'Europe/Belgrade',
'upi-list-keys',
'hi',
'should_monitor_audio_health',
'cost',
'Asia/Pontianak',
'Antarctica/Davis',
'America/Guyana',
'Europe/Stockholm',
'America/Vancouver',
'America/Porto_Velho',
'file',
'Africa/Tunis',
'wallet-balance',
'ent_load_test',
'Pacific/Auckland',
'State Bank Of India',
'Europe/Prague',
'de',
'Indian/Maldives',
'Asia/Kabul',
'Asia/Aqtau',
'it',
'Asia/Phnom_Penh',
'Africa/Conakry',
'error-text',
'error-code',
'balance',
'Zulu',
'Mac OS 10.8',
'America/Belize',
'method',
'arch 64',
'Unexpected wa_fb_api error',
'INITIAL',
'Etc/GMT+4',
'Asia/Tashkent',
'America/Rio_Branco',
'send',
'W-SU',
'Asia/Nicosia',
'Asia/Irkutsk',
'America/Punta_Arenas',
'America/Aruba',
'iOS 10.3.1',
'Chromium OS 11151.17.0',
'upi-vpa-sync',
'America/Edmonton',
'nl',
'Asia/Yerevan',
'Android 7.0',
'ad_invalidated',
'Libya',
'Asia/Kathmandu',
'tizen',
'note',
'iOS 11.4',
'Pacific/Fiji',
'Europe/Budapest',
'Asia/Rangoon',
'http://etherx.jabber.org/streams',
'WET',
'Africa/Malabo',
'urn:xmpp:whatsapp:sync',
'srtp',
'catalog_status',
'Chromium OS 10895.56.0',
'Australia/Brisbane',
'Asia/Qyzylorda',
'Asia/Aqtobe',
'everyone',
'Africa/Ndjamena',
'rtt',
'lsp',
'Jamaica',
'Europe/Bratislava',
'Canada/Atlantic',
'Asia/Dushanbe',
'wma',
'view_slot_total',
'view_slot',
'view_media_total',
'view_media',
'time_gap',
'request_time_gap',
'min_total',
'Singapore',
'Pacific/Guam',
'Mac OS 10.6',
'Europe/Malta',
'Europe/Chisinau',
'Asia/Saigon',
'qr',
'nokia',
'Mac OS 10.9.4',
'Europe/Sofia',
'Europe/Monaco',
'Chile/Continental',
'Africa/Monrovia',
'#pay-tos-v2-not-accepted',
'jabber:iq:last',
'cta',
'WebKit',
'Asia/Dili',
'America/Ojinaga',
'upi-user-set-up',
'received',
'owning',
'iOS 12.0',
'field',
'advertising_id',
'adder',
'GMT+05:30',
'Chromium OS 10718.88.2',
'America/St_Kitts',
'America/Grand_Turk',
'America/Dominica',
'whatsapp:hsm:facebook:alerts',
'stat',
'port',
'device',
'creative',
'Pacific/Tongatapu',
'Europe/Copenhagen'
]
def getToken(self, index, secondary = False):
targetDict = self.dictionary
if secondary:
targetDict = self.secondaryDictionary
elif index > 236 and index < (236 + len(self.secondaryDictionary)):
targetDict = self.secondaryDictionary
index = index - 237
if index < 0 or index > len(targetDict) - 1:
return None
return targetDict[index]
def getIndex(self, token):
if token in self.dictionary:
return (self.dictionary.index(token), False)
elif token in self.secondaryDictionary:
return (self.secondaryDictionary.index(token), True)
return None
| 34,651 | Python | .py | 1,284 | 14.05919 | 75 | 0.386601 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,533 | layer.py | tgalal_yowsup/yowsup/layers/coder/layer.py | from yowsup.layers import YowLayer
from .encoder import WriteEncoder
from .decoder import ReadDecoder
from .tokendictionary import TokenDictionary
class YowCoderLayer(YowLayer):
def __init__(self):
YowLayer.__init__(self)
tokenDictionary = TokenDictionary()
self.writer = WriteEncoder(tokenDictionary)
self.reader = ReadDecoder(tokenDictionary)
def send(self, data):
self.write(self.writer.protocolTreeNodeToBytes(data))
def receive(self, data):
node = self.reader.getProtocolTreeNode(bytearray(data))
if node:
self.toUpper(node)
def write(self, i):
if(type(i) in(list, tuple)):
self.toLower(bytearray(i))
else:
self.toLower(bytearray([i]))
def __str__(self):
return "Coder Layer"
| 828 | Python | .py | 23 | 28.608696 | 63 | 0.670025 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,534 | encoder.py | tgalal_yowsup/yowsup/layers/coder/encoder.py | class WriteEncoder:
def __init__(self, tokenDictionary):
self.tokenDictionary = tokenDictionary
def protocolTreeNodeToBytes(self, node):
outBytes = [0] # flags
self.writeInternal(node, outBytes)
return outBytes
def writeInternal(self, node, data):
x = 1 + \
(0 if node.attributes is None else len(node.attributes) * 2) + \
(0 if not node.hasChildren() else 1) + \
(0 if node.data is None else 1)
self.writeListStart(x, data)
self.writeString(node.tag, data)
self.writeAttributes(node.attributes, data);
if node.data is not None:
self.writeBytes(node.data, data)
if node.hasChildren():
self.writeListStart(len(node.children), data);
for c in node.children:
self.writeInternal(c, data);
def writeAttributes(self, attributes, data):
if attributes is not None:
for key, value in attributes.items():
self.writeString(key, data);
self.writeString(value, data, True);
def writeBytes(self, bytes_, data, packed = False):
bytes__ = []
for b in bytes_:
if type(b) is int:
bytes__.append(b)
else:
bytes__.append(ord(b))
size = len(bytes__)
toWrite = bytes__
if size >= 0x100000:
data.append(254)
self.writeInt31(size, data)
elif size >= 0x100:
data.append(253)
self.writeInt20(size, data)
else:
r = None
if packed:
if size < 128:
r = self.tryPackAndWriteHeader(255, bytes__, data)
if r is None:
r = self.tryPackAndWriteHeader(251, bytes__, data)
if r is None:
data.append(252)
self.writeInt8(size, data)
else:
toWrite = r
data.extend(toWrite)
def writeInt8(self, v, data):
data.append(v & 0xFF)
def writeInt16(self, v, data):
data.append((v & 0xFF00) >> 8);
data.append((v & 0xFF) >> 0);
def writeInt20(self, v, data):
data.append((0xF0000 & v) >> 16)
data.append((0xFF00 & v) >> 8)
data.append((v & 0xFF) >> 0)
def writeInt24(self, v, data):
data.append((v & 0xFF0000) >> 16)
data.append((v & 0xFF00) >> 8)
data.append((v & 0xFF) >> 0)
def writeInt31(self, v, data):
data.append((0x7F000000 & v) >> 24)
data.append((0xFF0000 & v) >> 16)
data.append((0xFF00 & v) >> 8)
data.append((v & 0xFF) >> 0)
def writeListStart(self, i, data):
if i == 0:
data.append(0)
elif i < 256:
data.append(248)
self.writeInt8(i, data)
else:
data.append(249)
self.writeInt16(i, data)
def writeToken(self, token, data):
if token <= 255 and token >=0:
data.append(token)
else:
raise ValueError("Invalid token: %s" % token)
def writeString(self, tag, data, packed = False):
tok = self.tokenDictionary.getIndex(tag)
if tok:
index, secondary = tok
if not secondary:
self.writeToken(index, data)
else:
quotient = index // 256
if quotient == 0:
double_byte_token = 236
elif quotient == 1:
double_byte_token = 237
elif quotient == 2:
double_byte_token = 238
elif quotient == 3:
double_byte_token = 239
else:
raise ValueError("Double byte dictionary token out of range")
self.writeToken(double_byte_token, data)
self.writeToken(index % 256, data)
else:
at = '@'.encode() if type(tag) == bytes else '@'
try:
atIndex = tag.index(at)
if atIndex < 1:
raise ValueError("atIndex < 1")
else:
server = tag[atIndex+1:]
user = tag[0:atIndex]
self.writeJid(user, server, data)
except ValueError:
self.writeBytes(self.encodeString(tag), data, packed)
def encodeString(self, string):
res = []
if type(string) == bytes:
for char in string:
res.append(char)
else:
for char in string:
res.append(ord(char))
return res;
def writeJid(self, user, server, data):
data.append(250)
if user is not None:
self.writeString(user, data, True)
else:
self.writeToken(0, data)
self.writeString(server, data)
def tryPackAndWriteHeader(self, v, headerData, data):
size = len(headerData)
if size >= 128:
return None
arr = [0] * int((size + 1) / 2)
for i in range(0, size):
packByte = self.packByte(v, headerData[i])
if packByte == -1:
arr = []
break
n2 = int(i / 2)
arr[n2] |= (packByte << 4 * (1 - i % 2))
if len(arr) > 0:
if size % 2 == 1:
arr[-1] |= 15 #0xF
data.append(v)
self.writeInt8(size %2 << 7 | len(arr), data)
return arr
return None
def packByte(self, v, n2):
if v == 251:
return self.packHex(n2)
if v == 255:
return self.packNibble(n2)
return -1
def packHex(self, n):
if n in range(48, 58):
return n - 48
if n in range(65, 71):
return 10 + (n - 65)
return -1
def packNibble(self, n):
if n in (45, 46):
return 10 + (n - 45)
if n in range(48, 58):
return n - 48
return -1
| 6,085 | Python | .py | 171 | 23.608187 | 81 | 0.499063 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,535 | layer.py | tgalal_yowsup/yowsup/layers/protocol_chatstate/layer.py | from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer
from .protocolentities import *
class YowChatstateProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"chatstate": (self.recvChatstateNode, self.sendChatstateEntity)
}
super(YowChatstateProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Chatstate Layer"
def sendChatstateEntity(self, entity):
self.entityToLower(entity)
def recvChatstateNode(self, node):
self.toUpper(IncomingChatstateProtocolEntity.fromProtocolTreeNode(node))
| 608 | Python | .py | 14 | 36.714286 | 80 | 0.72758 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,536 | test_layer.py | tgalal_yowsup/yowsup/layers/protocol_chatstate/test_layer.py | from yowsup.layers import YowProtocolLayerTest
from yowsup.layers.protocol_chatstate import YowChatstateProtocolLayer
from yowsup.layers.protocol_chatstate.protocolentities import IncomingChatstateProtocolEntity, OutgoingChatstateProtocolEntity
class YowChatStateProtocolLayerTest(YowProtocolLayerTest, YowChatstateProtocolLayer):
def setUp(self):
YowChatstateProtocolLayer.__init__(self)
def test_send(self):
entity = OutgoingChatstateProtocolEntity(OutgoingChatstateProtocolEntity.STATE_PAUSED, "jid@s.whatsapp.net")
self.assertSent(entity)
def test_receive(self):
entity = IncomingChatstateProtocolEntity(IncomingChatstateProtocolEntity.STATE_TYPING, "jid@s.whatsapp.net")
self.assertReceived(entity) | 758 | Python | .py | 12 | 57.666667 | 126 | 0.822581 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,537 | test_chatstate_outgoing.py | tgalal_yowsup/yowsup/layers/protocol_chatstate/protocolentities/test_chatstate_outgoing.py | from yowsup.layers.protocol_chatstate.protocolentities.chatstate_outgoing import OutgoingChatstateProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
entity = OutgoingChatstateProtocolEntity(OutgoingChatstateProtocolEntity.STATE_PAUSED, "jid@s.whatsapp.net")
class OutgoingChatstateProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = OutgoingChatstateProtocolEntity
self.node = entity.toProtocolTreeNode()
| 514 | Python | .py | 8 | 60.5 | 112 | 0.859127 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,538 | chatstate_incoming.py | tgalal_yowsup/yowsup/layers/protocol_chatstate/protocolentities/chatstate_incoming.py | from .chatstate import ChatstateProtocolEntity
class IncomingChatstateProtocolEntity(ChatstateProtocolEntity):
'''
INCOMING
<chatstate from="xxxxxxxxxxx@s.whatsapp.net">
<{{composing|paused}}></{{composing|paused}}>
</chatstate>
OUTGOING
<chatstate to="xxxxxxxxxxx@s.whatsapp.net">
<{{composing|paused}}></{{composing|paused}}>
</chatstate>
'''
def __init__(self, _state, _from):
super(IncomingChatstateProtocolEntity, self).__init__(_state)
self.setIncomingData(_from)
def setIncomingData(self, _from):
self._from = _from
def toProtocolTreeNode(self):
node = super(IncomingChatstateProtocolEntity, self).toProtocolTreeNode()
node.setAttribute("from", self._from)
return node
def __str__(self):
out = super(IncomingChatstateProtocolEntity, self).__str__()
out += "From: %s\n" % self._from
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = ChatstateProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = IncomingChatstateProtocolEntity
entity.setIncomingData(
node.getAttributeValue("from"),
)
return entity
| 1,230 | Python | .py | 33 | 30.212121 | 80 | 0.670042 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,539 | chatstate_outgoing.py | tgalal_yowsup/yowsup/layers/protocol_chatstate/protocolentities/chatstate_outgoing.py | from .chatstate import ChatstateProtocolEntity
class OutgoingChatstateProtocolEntity(ChatstateProtocolEntity):
'''
INCOMING
<chatstate from="xxxxxxxxxxx@s.whatsapp.net">
<{{composing|paused}}></{{composing|paused}}>
</chatstate>
OUTGOING
<chatstate to="xxxxxxxxxxx@s.whatsapp.net">
<{{composing|paused}}></{{composing|paused}}>
</chatstate>
'''
def __init__(self, _state, _to):
super(OutgoingChatstateProtocolEntity, self).__init__(_state)
self.setOutgoingData(_to)
def setOutgoingData(self, _to):
self._to = _to
def toProtocolTreeNode(self):
node = super(OutgoingChatstateProtocolEntity, self).toProtocolTreeNode()
node.setAttribute("to", self._to)
return node
def __str__(self):
out = super(OutgoingChatstateProtocolEntity, self).__str__()
out += "To: %s\n" % self._to
return out
@staticmethod
def fromProtocolTreeNode(node):
entity = ChatstateProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = OutgoingChatstateProtocolEntity
entity.setOutgoingData(
node.getAttributeValue("to"),
)
return entity
| 1,210 | Python | .py | 33 | 29.606061 | 80 | 0.664378 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,540 | test_chatstate_incoming.py | tgalal_yowsup/yowsup/layers/protocol_chatstate/protocolentities/test_chatstate_incoming.py | from yowsup.layers.protocol_chatstate.protocolentities.chatstate_incoming import IncomingChatstateProtocolEntity
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
entity = IncomingChatstateProtocolEntity(IncomingChatstateProtocolEntity.STATE_TYPING, "jid@s.whatsapp.net")
class IncomingChatstateProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = IncomingChatstateProtocolEntity
self.node = entity.toProtocolTreeNode()
| 514 | Python | .py | 8 | 60.5 | 112 | 0.859127 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,541 | chatstate.py | tgalal_yowsup/yowsup/layers/protocol_chatstate/protocolentities/chatstate.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class ChatstateProtocolEntity(ProtocolEntity):
'''
INCOMING
<chatstate from="xxxxxxxxxxx@s.whatsapp.net">
<{{composing|paused}}></{{composing|paused}}>
</chatstate>
OUTGOING
<chatstate to="xxxxxxxxxxx@s.whatsapp.net">
<{{composing|paused}}></{{composing|paused}}>
</chatstate>
'''
STATE_TYPING = "composing"
STATE_PAUSED = "paused"
STATES = (STATE_TYPING, STATE_PAUSED)
def __init__(self, _state):
super(ChatstateProtocolEntity, self).__init__("chatstate")
assert _state in self.__class__.STATES, "Expected chat state to be in %s, got %s" % (self.__class__.STATES, _state)
self._state = _state
def getState(self):
return self._state
def toProtocolTreeNode(self):
node = self._createProtocolTreeNode({}, None, data = None)
node.addChild(ProtocolTreeNode(self._state))
return node
def __str__(self):
out = "CHATSTATE:\n"
out += "State: %s\n" % self._state
return out
@staticmethod
def fromProtocolTreeNode(node):
return ChatstateProtocolEntity(
node.getAllChildren()[0].tag,
)
| 1,234 | Python | .py | 34 | 29.470588 | 123 | 0.638655 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,542 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_chatstate/protocolentities/__init__.py | from .chatstate import ChatstateProtocolEntity
from .chatstate_incoming import IncomingChatstateProtocolEntity
from .chatstate_outgoing import OutgoingChatstateProtocolEntity
| 175 | Python | .py | 3 | 57.333333 | 63 | 0.918605 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,543 | layer.py | tgalal_yowsup/yowsup/layers/protocol_messages/layer.py | from yowsup.layers import YowProtocolLayer
from .protocolentities import TextMessageProtocolEntity
from .protocolentities import ExtendedTextMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.converter import AttributesConverter
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
import logging
logger = logging.getLogger(__name__)
class YowMessagesProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"message": (self.recvMessageStanza, self.sendMessageEntity)
}
super(YowMessagesProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Messages Layer"
def sendMessageEntity(self, entity):
if entity.getType() == "text":
self.entityToLower(entity)
###recieved node handlers handlers
def recvMessageStanza(self, node):
protoNode = node.getChild("proto")
if protoNode:
if protoNode and protoNode["mediatype"] is None:
message = AttributesConverter.get().protobytes_to_message(protoNode.getData())
if message.conversation:
self.toUpper(
TextMessageProtocolEntity(
message.conversation, MessageMetaAttributes.from_message_protocoltreenode(node)
)
)
elif message.extended_text:
self.toUpper(
ExtendedTextMessageProtocolEntity(
message.extended_text,
MessageMetaAttributes.from_message_protocoltreenode(node)
)
)
elif not message.sender_key_distribution_message:
# Will send receipts for unsupported message types to prevent stream errors
logger.warning("Unsupported message type: %s, will send receipts to "
"prevent stream errors" % message)
self.toLower(
OutgoingReceiptProtocolEntity(
messageIds=[node["id"]],
to=node["from"],
participant=node["participant"]
).toProtocolTreeNode()
)
| 2,492 | Python | .py | 49 | 35.77551 | 117 | 0.609606 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,544 | e2e_pb2.py | tgalal_yowsup/yowsup/layers/protocol_messages/proto/e2e_pb2.py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: e2e.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from . import protocol_pb2 as protocol__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='e2e.proto',
package='',
syntax='proto2',
serialized_options=None,
serialized_pb=_b('\n\te2e.proto\x1a\x0eprotocol.proto\"\xb0\x01\n\x0b\x43ontextInfo\x12\x11\n\tstanza_id\x18\x01 \x01(\t\x12\x13\n\x0bparticipant\x18\x02 \x01(\t\x12 \n\x0equoted_message\x18\x03 \x01(\x0b\x32\x08.Message\x12\x12\n\nremote_jid\x18\x04 \x01(\t\x12\x15\n\rmentioned_jid\x18\x0f \x03(\t\x12\x14\n\x0c\x65\x64it_version\x18\x10 \x01(\r\x12\x16\n\x0erevoke_message\x18\x11 \x01(\x08\"G\n\x05Point\x12\x13\n\x0bxDeprecated\x18\x01 \x01(\x02\x12\x13\n\x0byDeprecated\x18\x02 \x01(\x02\x12\t\n\x01x\x18\x03 \x01(\x02\x12\t\n\x01y\x18\x04 \x01(\x02\"N\n\x15InteractiveAnnotation\x12 \n\x10polygon_vertices\x18\x01 \x03(\x0b\x32\x06.Point\x12\x13\n\x0b\x61\x63tion_case\x18\x02 \x01(\r\"\xcf\x1a\n\x07Message\x12\x14\n\x0c\x63onversation\x18\x01 \x01(\t\x12N\n\x1fsender_key_distribution_message\x18\x02 \x01(\x0b\x32%.Message.SenderKeyDistributionMessage\x12,\n\rimage_message\x18\x03 \x01(\x0b\x32\x15.Message.ImageMessage\x12\x30\n\x0f\x63ontact_message\x18\x04 \x01(\x0b\x32\x17.Message.ContactMessage\x12\x32\n\x10location_message\x18\x05 \x01(\x0b\x32\x18.Message.LocationMessage\x12;\n\x15\x65xtended_text_message\x18\x06 \x01(\x0b\x32\x1c.Message.ExtendedTextMessage\x12\x32\n\x10\x64ocument_message\x18\x07 \x01(\x0b\x32\x18.Message.DocumentMessage\x12,\n\raudio_message\x18\x08 \x01(\x0b\x32\x15.Message.AudioMessage\x12,\n\rvideo_message\x18\t \x01(\x0b\x32\x15.Message.VideoMessage\x12\x1b\n\x04\x63\x61ll\x18\n \x01(\x0b\x32\r.Message.Call\x12\x1b\n\x04\x63hat\x18\x0b \x01(\x0b\x32\r.Message.Chat\x12\x32\n\x10protocol_message\x18\x0c \x01(\x0b\x32\x18.Message.ProtocolMessage\x12=\n\x16\x63ontacts_array_message\x18\r \x01(\x0b\x32\x1d.Message.ContactsArrayMessage\x12\x43\n\x19highly_structured_message\x18\x0e \x01(\x0b\x32 .Message.HighlyStructuredMessage\x12\x30\n\x0fsticker_message\x18\x1a \x01(\x0b\x32\x17.Message.StickerMessage\x1a\x61\n\x1cSenderKeyDistributionMessage\x12\x10\n\x08group_id\x18\x01 \x01(\t\x12/\n\'axolotl_sender_key_distribution_message\x18\x02 \x01(\x0c\x1a\x91\x03\n\x0cImageMessage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\x10\n\x08mimetype\x18\x02 \x01(\t\x12\x0f\n\x07\x63\x61ption\x18\x03 \x01(\t\x12\x13\n\x0b\x66ile_sha256\x18\x04 \x01(\x0c\x12\x13\n\x0b\x66ile_length\x18\x05 \x01(\x04\x12\x0e\n\x06height\x18\x06 \x01(\r\x12\r\n\x05width\x18\x07 \x01(\r\x12\x11\n\tmedia_key\x18\x08 \x01(\x0c\x12\x17\n\x0f\x66ile_enc_sha256\x18\t \x01(\x0c\x12\x37\n\x17interactive_annotations\x18\n \x03(\x0b\x32\x16.InteractiveAnnotation\x12\x13\n\x0b\x64irect_path\x18\x0b \x01(\t\x12\x1b\n\x13media_key_timestamp\x18\x0c \x01(\x04\x12\x16\n\x0ejpeg_thumbnail\x18\x10 \x01(\x0c\x12\"\n\x0c\x63ontext_info\x18\x11 \x01(\x0b\x32\x0c.ContextInfo\x12\x1a\n\x12\x66irst_scan_sidecar\x18\x12 \x01(\x0c\x12\x19\n\x11\x66irst_scan_length\x18\x13 \x01(\r\x1aY\n\x0e\x43ontactMessage\x12\x14\n\x0c\x64isplay_name\x18\x01 \x01(\t\x12\r\n\x05vcard\x18\x10 \x01(\x0c\x12\"\n\x0c\x63ontext_info\x18\x11 \x01(\x0b\x32\x0c.ContextInfo\x1a\xd2\x02\n\x0fLocationMessage\x12\x18\n\x10\x64\x65grees_latitude\x18\x01 \x01(\x01\x12\x19\n\x11\x64\x65grees_longitude\x18\x02 \x01(\x01\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x0f\n\x07\x61\x64\x64ress\x18\x04 \x01(\t\x12\x0b\n\x03url\x18\x05 \x01(\t\x12\x10\n\x08\x64uration\x18\x06 \x01(\x02\x12\x1a\n\x12\x61\x63\x63uracy_in_meters\x18\x07 \x01(\r\x12\x14\n\x0cspeed_in_mps\x18\x08 \x01(\x02\x12-\n%degrees_clockwise_from_magnetic_north\x18\t \x01(\r\x12/\n\'axolotl_sender_key_distribution_message\x18\n \x01(\x0c\x12\x16\n\x0ejpeg_thumbnail\x18\x10 \x01(\x0c\x12\"\n\x0c\x63ontext_info\x18\x11 \x01(\x0b\x32\x0c.ContextInfo\x1a\xb0\x01\n\x13\x45xtendedTextMessage\x12\x0c\n\x04text\x18\x01 \x01(\t\x12\x14\n\x0cmatched_text\x18\x02 \x01(\t\x12\x15\n\rcanonical_url\x18\x04 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x05 \x01(\t\x12\r\n\x05title\x18\x06 \x01(\t\x12\x16\n\x0ejpeg_thumbnail\x18\x10 \x01(\x0c\x12\"\n\x0c\x63ontext_info\x18\x11 \x01(\x0b\x32\x0c.ContextInfo\x1a\xdf\x01\n\x0f\x44ocumentMessage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\x10\n\x08mimetype\x18\x02 \x01(\t\x12\r\n\x05title\x18\x03 \x01(\t\x12\x13\n\x0b\x66ile_sha256\x18\x04 \x01(\x0c\x12\x13\n\x0b\x66ile_length\x18\x05 \x01(\x04\x12\x12\n\npage_count\x18\x06 \x01(\r\x12\x11\n\tmedia_key\x18\x07 \x01(\x0c\x12\x11\n\tfile_name\x18\x08 \x01(\t\x12\x16\n\x0ejpeg_thumbnail\x18\x10 \x01(\x0c\x12\"\n\x0c\x63ontext_info\x18\x11 \x01(\x0b\x32\x0c.ContextInfo\x1a\xc7\x01\n\x0c\x41udioMessage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\x10\n\x08mimetype\x18\x02 \x01(\t\x12\x13\n\x0b\x66ile_sha256\x18\x03 \x01(\x0c\x12\x13\n\x0b\x66ile_length\x18\x04 \x01(\x04\x12\x0f\n\x07seconds\x18\x05 \x01(\r\x12\x0b\n\x03ptt\x18\x06 \x01(\x08\x12\x11\n\tmedia_key\x18\x07 \x01(\x0c\x12\"\n\x0c\x63ontext_info\x18\x11 \x01(\x0b\x32\x0c.ContextInfo\x12\x19\n\x11streaming_sidecar\x18\x12 \x01(\x0c\x1a\x89\x03\n\x0cVideoMessage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\x10\n\x08mimetype\x18\x02 \x01(\t\x12\x13\n\x0b\x66ile_sha256\x18\x03 \x01(\x0c\x12\x13\n\x0b\x66ile_length\x18\x04 \x01(\x04\x12\x0f\n\x07seconds\x18\x05 \x01(\r\x12\x11\n\tmedia_key\x18\x06 \x01(\x0c\x12\x0f\n\x07\x63\x61ption\x18\x07 \x01(\t\x12\x14\n\x0cgif_playback\x18\x08 \x01(\x08\x12\x0e\n\x06height\x18\t \x01(\r\x12\r\n\x05width\x18\n \x01(\r\x12\x16\n\x0ejpeg_thumbnail\x18\x10 \x01(\x0c\x12\"\n\x0c\x63ontext_info\x18\x11 \x01(\x0b\x32\x0c.ContextInfo\x12\x19\n\x11streaming_sidecar\x18\x12 \x01(\x0c\x12@\n\x0fgif_attribution\x18\x13 \x01(\x0e\x32!.Message.VideoMessage.Attribution:\x04NONE\"-\n\x0b\x41ttribution\x12\x08\n\x04NONE\x10\x00\x12\t\n\x05GIPHY\x10\x01\x12\t\n\x05TENOR\x10\x02\x1a\x18\n\x04\x43\x61ll\x12\x10\n\x08\x63\x61ll_key\x18\x01 \x01(\x0c\x1a(\n\x04\x43hat\x12\x14\n\x0c\x64isplay_name\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\t\x1at\n\x0fProtocolMessage\x12\x18\n\x03key\x18\x01 \x01(\x0b\x32\x0b.MessageKey\x12\x33\n\x04type\x18\x02 \x01(\x0e\x32\x1d.Message.ProtocolMessage.Type:\x06REVOKE\"\x12\n\x04Type\x12\n\n\x06REVOKE\x10\x00\x1a{\n\x14\x43ontactsArrayMessage\x12\x14\n\x0c\x64isplay_name\x18\x01 \x01(\t\x12)\n\x08\x63ontacts\x18\x02 \x03(\x0b\x32\x17.Message.ContactMessage\x12\"\n\x0c\x63ontext_info\x18\x11 \x01(\x0b\x32\x0c.ContextInfo\x1a|\n\x17HighlyStructuredMessage\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x14\n\x0c\x65lement_name\x18\x02 \x01(\t\x12\x0e\n\x06params\x18\x03 \x03(\t\x12\x13\n\x0b\x66\x61llback_lg\x18\x04 \x01(\t\x12\x13\n\x0b\x66\x61llback_lc\x18\x05 \x01(\t\x1a\x91\x02\n\x0eStickerMessage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\x13\n\x0b\x66ile_sha256\x18\x02 \x01(\x0c\x12\x17\n\x0f\x66ile_enc_sha256\x18\x03 \x01(\x0c\x12\x11\n\tmedia_key\x18\x04 \x01(\x0c\x12\x10\n\x08mimetype\x18\x05 \x01(\t\x12\x0e\n\x06height\x18\x06 \x01(\r\x12\r\n\x05width\x18\x07 \x01(\r\x12\x13\n\x0b\x64irect_path\x18\x08 \x01(\t\x12\x13\n\x0b\x66ile_length\x18\t \x01(\x04\x12\x1b\n\x13media_key_timestamp\x18\n \x01(\x04\x12\x15\n\rpng_thumbnail\x18\x10 \x01(\x0c\x12\"\n\x0c\x63ontext_info\x18\x11 \x01(\x0b\x32\x0c.ContextInfo')
,
dependencies=[protocol__pb2.DESCRIPTOR,])
_MESSAGE_VIDEOMESSAGE_ATTRIBUTION = _descriptor.EnumDescriptor(
name='Attribution',
full_name='Message.VideoMessage.Attribution',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='NONE', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='GIPHY', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TENOR', index=2, number=2,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=3011,
serialized_end=3056,
)
_sym_db.RegisterEnumDescriptor(_MESSAGE_VIDEOMESSAGE_ATTRIBUTION)
_MESSAGE_PROTOCOLMESSAGE_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='Message.ProtocolMessage.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='REVOKE', index=0, number=0,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=3224,
serialized_end=3242,
)
_sym_db.RegisterEnumDescriptor(_MESSAGE_PROTOCOLMESSAGE_TYPE)
_CONTEXTINFO = _descriptor.Descriptor(
name='ContextInfo',
full_name='ContextInfo',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='stanza_id', full_name='ContextInfo.stanza_id', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='participant', full_name='ContextInfo.participant', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='quoted_message', full_name='ContextInfo.quoted_message', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='remote_jid', full_name='ContextInfo.remote_jid', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mentioned_jid', full_name='ContextInfo.mentioned_jid', index=4,
number=15, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='edit_version', full_name='ContextInfo.edit_version', index=5,
number=16, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='revoke_message', full_name='ContextInfo.revoke_message', index=6,
number=17, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=30,
serialized_end=206,
)
_POINT = _descriptor.Descriptor(
name='Point',
full_name='Point',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='xDeprecated', full_name='Point.xDeprecated', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='yDeprecated', full_name='Point.yDeprecated', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='x', full_name='Point.x', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='y', full_name='Point.y', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=208,
serialized_end=279,
)
_INTERACTIVEANNOTATION = _descriptor.Descriptor(
name='InteractiveAnnotation',
full_name='InteractiveAnnotation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='polygon_vertices', full_name='InteractiveAnnotation.polygon_vertices', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='action_case', full_name='InteractiveAnnotation.action_case', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=281,
serialized_end=359,
)
_MESSAGE_SENDERKEYDISTRIBUTIONMESSAGE = _descriptor.Descriptor(
name='SenderKeyDistributionMessage',
full_name='Message.SenderKeyDistributionMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='group_id', full_name='Message.SenderKeyDistributionMessage.group_id', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='axolotl_sender_key_distribution_message', full_name='Message.SenderKeyDistributionMessage.axolotl_sender_key_distribution_message', index=1,
number=2, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=1120,
serialized_end=1217,
)
_MESSAGE_IMAGEMESSAGE = _descriptor.Descriptor(
name='ImageMessage',
full_name='Message.ImageMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='url', full_name='Message.ImageMessage.url', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mimetype', full_name='Message.ImageMessage.mimetype', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='caption', full_name='Message.ImageMessage.caption', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_sha256', full_name='Message.ImageMessage.file_sha256', index=3,
number=4, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_length', full_name='Message.ImageMessage.file_length', index=4,
number=5, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='height', full_name='Message.ImageMessage.height', index=5,
number=6, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='width', full_name='Message.ImageMessage.width', index=6,
number=7, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='media_key', full_name='Message.ImageMessage.media_key', index=7,
number=8, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_enc_sha256', full_name='Message.ImageMessage.file_enc_sha256', index=8,
number=9, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='interactive_annotations', full_name='Message.ImageMessage.interactive_annotations', index=9,
number=10, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='direct_path', full_name='Message.ImageMessage.direct_path', index=10,
number=11, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='media_key_timestamp', full_name='Message.ImageMessage.media_key_timestamp', index=11,
number=12, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='jpeg_thumbnail', full_name='Message.ImageMessage.jpeg_thumbnail', index=12,
number=16, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='context_info', full_name='Message.ImageMessage.context_info', index=13,
number=17, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='first_scan_sidecar', full_name='Message.ImageMessage.first_scan_sidecar', index=14,
number=18, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='first_scan_length', full_name='Message.ImageMessage.first_scan_length', index=15,
number=19, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=1220,
serialized_end=1621,
)
_MESSAGE_CONTACTMESSAGE = _descriptor.Descriptor(
name='ContactMessage',
full_name='Message.ContactMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='display_name', full_name='Message.ContactMessage.display_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='vcard', full_name='Message.ContactMessage.vcard', index=1,
number=16, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='context_info', full_name='Message.ContactMessage.context_info', index=2,
number=17, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=1623,
serialized_end=1712,
)
_MESSAGE_LOCATIONMESSAGE = _descriptor.Descriptor(
name='LocationMessage',
full_name='Message.LocationMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='degrees_latitude', full_name='Message.LocationMessage.degrees_latitude', index=0,
number=1, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='degrees_longitude', full_name='Message.LocationMessage.degrees_longitude', index=1,
number=2, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='name', full_name='Message.LocationMessage.name', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='address', full_name='Message.LocationMessage.address', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='url', full_name='Message.LocationMessage.url', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='duration', full_name='Message.LocationMessage.duration', index=5,
number=6, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='accuracy_in_meters', full_name='Message.LocationMessage.accuracy_in_meters', index=6,
number=7, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='speed_in_mps', full_name='Message.LocationMessage.speed_in_mps', index=7,
number=8, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='degrees_clockwise_from_magnetic_north', full_name='Message.LocationMessage.degrees_clockwise_from_magnetic_north', index=8,
number=9, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='axolotl_sender_key_distribution_message', full_name='Message.LocationMessage.axolotl_sender_key_distribution_message', index=9,
number=10, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='jpeg_thumbnail', full_name='Message.LocationMessage.jpeg_thumbnail', index=10,
number=16, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='context_info', full_name='Message.LocationMessage.context_info', index=11,
number=17, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=1715,
serialized_end=2053,
)
_MESSAGE_EXTENDEDTEXTMESSAGE = _descriptor.Descriptor(
name='ExtendedTextMessage',
full_name='Message.ExtendedTextMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='text', full_name='Message.ExtendedTextMessage.text', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='matched_text', full_name='Message.ExtendedTextMessage.matched_text', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='canonical_url', full_name='Message.ExtendedTextMessage.canonical_url', index=2,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='description', full_name='Message.ExtendedTextMessage.description', index=3,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='title', full_name='Message.ExtendedTextMessage.title', index=4,
number=6, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='jpeg_thumbnail', full_name='Message.ExtendedTextMessage.jpeg_thumbnail', index=5,
number=16, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='context_info', full_name='Message.ExtendedTextMessage.context_info', index=6,
number=17, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=2056,
serialized_end=2232,
)
_MESSAGE_DOCUMENTMESSAGE = _descriptor.Descriptor(
name='DocumentMessage',
full_name='Message.DocumentMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='url', full_name='Message.DocumentMessage.url', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mimetype', full_name='Message.DocumentMessage.mimetype', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='title', full_name='Message.DocumentMessage.title', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_sha256', full_name='Message.DocumentMessage.file_sha256', index=3,
number=4, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_length', full_name='Message.DocumentMessage.file_length', index=4,
number=5, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='page_count', full_name='Message.DocumentMessage.page_count', index=5,
number=6, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='media_key', full_name='Message.DocumentMessage.media_key', index=6,
number=7, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_name', full_name='Message.DocumentMessage.file_name', index=7,
number=8, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='jpeg_thumbnail', full_name='Message.DocumentMessage.jpeg_thumbnail', index=8,
number=16, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='context_info', full_name='Message.DocumentMessage.context_info', index=9,
number=17, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=2235,
serialized_end=2458,
)
_MESSAGE_AUDIOMESSAGE = _descriptor.Descriptor(
name='AudioMessage',
full_name='Message.AudioMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='url', full_name='Message.AudioMessage.url', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mimetype', full_name='Message.AudioMessage.mimetype', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_sha256', full_name='Message.AudioMessage.file_sha256', index=2,
number=3, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_length', full_name='Message.AudioMessage.file_length', index=3,
number=4, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='seconds', full_name='Message.AudioMessage.seconds', index=4,
number=5, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='ptt', full_name='Message.AudioMessage.ptt', index=5,
number=6, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='media_key', full_name='Message.AudioMessage.media_key', index=6,
number=7, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='context_info', full_name='Message.AudioMessage.context_info', index=7,
number=17, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='streaming_sidecar', full_name='Message.AudioMessage.streaming_sidecar', index=8,
number=18, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=2461,
serialized_end=2660,
)
_MESSAGE_VIDEOMESSAGE = _descriptor.Descriptor(
name='VideoMessage',
full_name='Message.VideoMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='url', full_name='Message.VideoMessage.url', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mimetype', full_name='Message.VideoMessage.mimetype', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_sha256', full_name='Message.VideoMessage.file_sha256', index=2,
number=3, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_length', full_name='Message.VideoMessage.file_length', index=3,
number=4, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='seconds', full_name='Message.VideoMessage.seconds', index=4,
number=5, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='media_key', full_name='Message.VideoMessage.media_key', index=5,
number=6, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='caption', full_name='Message.VideoMessage.caption', index=6,
number=7, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='gif_playback', full_name='Message.VideoMessage.gif_playback', index=7,
number=8, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='height', full_name='Message.VideoMessage.height', index=8,
number=9, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='width', full_name='Message.VideoMessage.width', index=9,
number=10, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='jpeg_thumbnail', full_name='Message.VideoMessage.jpeg_thumbnail', index=10,
number=16, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='context_info', full_name='Message.VideoMessage.context_info', index=11,
number=17, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='streaming_sidecar', full_name='Message.VideoMessage.streaming_sidecar', index=12,
number=18, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='gif_attribution', full_name='Message.VideoMessage.gif_attribution', index=13,
number=19, type=14, cpp_type=8, label=1,
has_default_value=True, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
_MESSAGE_VIDEOMESSAGE_ATTRIBUTION,
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=2663,
serialized_end=3056,
)
_MESSAGE_CALL = _descriptor.Descriptor(
name='Call',
full_name='Message.Call',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='call_key', full_name='Message.Call.call_key', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=3058,
serialized_end=3082,
)
_MESSAGE_CHAT = _descriptor.Descriptor(
name='Chat',
full_name='Message.Chat',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='display_name', full_name='Message.Chat.display_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='id', full_name='Message.Chat.id', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=3084,
serialized_end=3124,
)
_MESSAGE_PROTOCOLMESSAGE = _descriptor.Descriptor(
name='ProtocolMessage',
full_name='Message.ProtocolMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='Message.ProtocolMessage.key', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='type', full_name='Message.ProtocolMessage.type', index=1,
number=2, type=14, cpp_type=8, label=1,
has_default_value=True, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
_MESSAGE_PROTOCOLMESSAGE_TYPE,
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=3126,
serialized_end=3242,
)
_MESSAGE_CONTACTSARRAYMESSAGE = _descriptor.Descriptor(
name='ContactsArrayMessage',
full_name='Message.ContactsArrayMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='display_name', full_name='Message.ContactsArrayMessage.display_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='contacts', full_name='Message.ContactsArrayMessage.contacts', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='context_info', full_name='Message.ContactsArrayMessage.context_info', index=2,
number=17, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=3244,
serialized_end=3367,
)
_MESSAGE_HIGHLYSTRUCTUREDMESSAGE = _descriptor.Descriptor(
name='HighlyStructuredMessage',
full_name='Message.HighlyStructuredMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='namespace', full_name='Message.HighlyStructuredMessage.namespace', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='element_name', full_name='Message.HighlyStructuredMessage.element_name', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='params', full_name='Message.HighlyStructuredMessage.params', index=2,
number=3, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='fallback_lg', full_name='Message.HighlyStructuredMessage.fallback_lg', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='fallback_lc', full_name='Message.HighlyStructuredMessage.fallback_lc', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=3369,
serialized_end=3493,
)
_MESSAGE_STICKERMESSAGE = _descriptor.Descriptor(
name='StickerMessage',
full_name='Message.StickerMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='url', full_name='Message.StickerMessage.url', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_sha256', full_name='Message.StickerMessage.file_sha256', index=1,
number=2, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_enc_sha256', full_name='Message.StickerMessage.file_enc_sha256', index=2,
number=3, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='media_key', full_name='Message.StickerMessage.media_key', index=3,
number=4, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mimetype', full_name='Message.StickerMessage.mimetype', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='height', full_name='Message.StickerMessage.height', index=5,
number=6, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='width', full_name='Message.StickerMessage.width', index=6,
number=7, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='direct_path', full_name='Message.StickerMessage.direct_path', index=7,
number=8, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='file_length', full_name='Message.StickerMessage.file_length', index=8,
number=9, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='media_key_timestamp', full_name='Message.StickerMessage.media_key_timestamp', index=9,
number=10, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='png_thumbnail', full_name='Message.StickerMessage.png_thumbnail', index=10,
number=16, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='context_info', full_name='Message.StickerMessage.context_info', index=11,
number=17, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=3496,
serialized_end=3769,
)
_MESSAGE = _descriptor.Descriptor(
name='Message',
full_name='Message',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='conversation', full_name='Message.conversation', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='sender_key_distribution_message', full_name='Message.sender_key_distribution_message', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='image_message', full_name='Message.image_message', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='contact_message', full_name='Message.contact_message', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='location_message', full_name='Message.location_message', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='extended_text_message', full_name='Message.extended_text_message', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='document_message', full_name='Message.document_message', index=6,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='audio_message', full_name='Message.audio_message', index=7,
number=8, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='video_message', full_name='Message.video_message', index=8,
number=9, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='call', full_name='Message.call', index=9,
number=10, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='chat', full_name='Message.chat', index=10,
number=11, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='protocol_message', full_name='Message.protocol_message', index=11,
number=12, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='contacts_array_message', full_name='Message.contacts_array_message', index=12,
number=13, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='highly_structured_message', full_name='Message.highly_structured_message', index=13,
number=14, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='sticker_message', full_name='Message.sticker_message', index=14,
number=26, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_MESSAGE_SENDERKEYDISTRIBUTIONMESSAGE, _MESSAGE_IMAGEMESSAGE, _MESSAGE_CONTACTMESSAGE, _MESSAGE_LOCATIONMESSAGE, _MESSAGE_EXTENDEDTEXTMESSAGE, _MESSAGE_DOCUMENTMESSAGE, _MESSAGE_AUDIOMESSAGE, _MESSAGE_VIDEOMESSAGE, _MESSAGE_CALL, _MESSAGE_CHAT, _MESSAGE_PROTOCOLMESSAGE, _MESSAGE_CONTACTSARRAYMESSAGE, _MESSAGE_HIGHLYSTRUCTUREDMESSAGE, _MESSAGE_STICKERMESSAGE, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=362,
serialized_end=3769,
)
_CONTEXTINFO.fields_by_name['quoted_message'].message_type = _MESSAGE
_INTERACTIVEANNOTATION.fields_by_name['polygon_vertices'].message_type = _POINT
_MESSAGE_SENDERKEYDISTRIBUTIONMESSAGE.containing_type = _MESSAGE
_MESSAGE_IMAGEMESSAGE.fields_by_name['interactive_annotations'].message_type = _INTERACTIVEANNOTATION
_MESSAGE_IMAGEMESSAGE.fields_by_name['context_info'].message_type = _CONTEXTINFO
_MESSAGE_IMAGEMESSAGE.containing_type = _MESSAGE
_MESSAGE_CONTACTMESSAGE.fields_by_name['context_info'].message_type = _CONTEXTINFO
_MESSAGE_CONTACTMESSAGE.containing_type = _MESSAGE
_MESSAGE_LOCATIONMESSAGE.fields_by_name['context_info'].message_type = _CONTEXTINFO
_MESSAGE_LOCATIONMESSAGE.containing_type = _MESSAGE
_MESSAGE_EXTENDEDTEXTMESSAGE.fields_by_name['context_info'].message_type = _CONTEXTINFO
_MESSAGE_EXTENDEDTEXTMESSAGE.containing_type = _MESSAGE
_MESSAGE_DOCUMENTMESSAGE.fields_by_name['context_info'].message_type = _CONTEXTINFO
_MESSAGE_DOCUMENTMESSAGE.containing_type = _MESSAGE
_MESSAGE_AUDIOMESSAGE.fields_by_name['context_info'].message_type = _CONTEXTINFO
_MESSAGE_AUDIOMESSAGE.containing_type = _MESSAGE
_MESSAGE_VIDEOMESSAGE.fields_by_name['context_info'].message_type = _CONTEXTINFO
_MESSAGE_VIDEOMESSAGE.fields_by_name['gif_attribution'].enum_type = _MESSAGE_VIDEOMESSAGE_ATTRIBUTION
_MESSAGE_VIDEOMESSAGE.containing_type = _MESSAGE
_MESSAGE_VIDEOMESSAGE_ATTRIBUTION.containing_type = _MESSAGE_VIDEOMESSAGE
_MESSAGE_CALL.containing_type = _MESSAGE
_MESSAGE_CHAT.containing_type = _MESSAGE
_MESSAGE_PROTOCOLMESSAGE.fields_by_name['key'].message_type = protocol__pb2._MESSAGEKEY
_MESSAGE_PROTOCOLMESSAGE.fields_by_name['type'].enum_type = _MESSAGE_PROTOCOLMESSAGE_TYPE
_MESSAGE_PROTOCOLMESSAGE.containing_type = _MESSAGE
_MESSAGE_PROTOCOLMESSAGE_TYPE.containing_type = _MESSAGE_PROTOCOLMESSAGE
_MESSAGE_CONTACTSARRAYMESSAGE.fields_by_name['contacts'].message_type = _MESSAGE_CONTACTMESSAGE
_MESSAGE_CONTACTSARRAYMESSAGE.fields_by_name['context_info'].message_type = _CONTEXTINFO
_MESSAGE_CONTACTSARRAYMESSAGE.containing_type = _MESSAGE
_MESSAGE_HIGHLYSTRUCTUREDMESSAGE.containing_type = _MESSAGE
_MESSAGE_STICKERMESSAGE.fields_by_name['context_info'].message_type = _CONTEXTINFO
_MESSAGE_STICKERMESSAGE.containing_type = _MESSAGE
_MESSAGE.fields_by_name['sender_key_distribution_message'].message_type = _MESSAGE_SENDERKEYDISTRIBUTIONMESSAGE
_MESSAGE.fields_by_name['image_message'].message_type = _MESSAGE_IMAGEMESSAGE
_MESSAGE.fields_by_name['contact_message'].message_type = _MESSAGE_CONTACTMESSAGE
_MESSAGE.fields_by_name['location_message'].message_type = _MESSAGE_LOCATIONMESSAGE
_MESSAGE.fields_by_name['extended_text_message'].message_type = _MESSAGE_EXTENDEDTEXTMESSAGE
_MESSAGE.fields_by_name['document_message'].message_type = _MESSAGE_DOCUMENTMESSAGE
_MESSAGE.fields_by_name['audio_message'].message_type = _MESSAGE_AUDIOMESSAGE
_MESSAGE.fields_by_name['video_message'].message_type = _MESSAGE_VIDEOMESSAGE
_MESSAGE.fields_by_name['call'].message_type = _MESSAGE_CALL
_MESSAGE.fields_by_name['chat'].message_type = _MESSAGE_CHAT
_MESSAGE.fields_by_name['protocol_message'].message_type = _MESSAGE_PROTOCOLMESSAGE
_MESSAGE.fields_by_name['contacts_array_message'].message_type = _MESSAGE_CONTACTSARRAYMESSAGE
_MESSAGE.fields_by_name['highly_structured_message'].message_type = _MESSAGE_HIGHLYSTRUCTUREDMESSAGE
_MESSAGE.fields_by_name['sticker_message'].message_type = _MESSAGE_STICKERMESSAGE
DESCRIPTOR.message_types_by_name['ContextInfo'] = _CONTEXTINFO
DESCRIPTOR.message_types_by_name['Point'] = _POINT
DESCRIPTOR.message_types_by_name['InteractiveAnnotation'] = _INTERACTIVEANNOTATION
DESCRIPTOR.message_types_by_name['Message'] = _MESSAGE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ContextInfo = _reflection.GeneratedProtocolMessageType('ContextInfo', (_message.Message,), dict(
DESCRIPTOR = _CONTEXTINFO,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:ContextInfo)
))
_sym_db.RegisterMessage(ContextInfo)
Point = _reflection.GeneratedProtocolMessageType('Point', (_message.Message,), dict(
DESCRIPTOR = _POINT,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Point)
))
_sym_db.RegisterMessage(Point)
InteractiveAnnotation = _reflection.GeneratedProtocolMessageType('InteractiveAnnotation', (_message.Message,), dict(
DESCRIPTOR = _INTERACTIVEANNOTATION,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:InteractiveAnnotation)
))
_sym_db.RegisterMessage(InteractiveAnnotation)
Message = _reflection.GeneratedProtocolMessageType('Message', (_message.Message,), dict(
SenderKeyDistributionMessage = _reflection.GeneratedProtocolMessageType('SenderKeyDistributionMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_SENDERKEYDISTRIBUTIONMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.SenderKeyDistributionMessage)
))
,
ImageMessage = _reflection.GeneratedProtocolMessageType('ImageMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_IMAGEMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.ImageMessage)
))
,
ContactMessage = _reflection.GeneratedProtocolMessageType('ContactMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_CONTACTMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.ContactMessage)
))
,
LocationMessage = _reflection.GeneratedProtocolMessageType('LocationMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_LOCATIONMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.LocationMessage)
))
,
ExtendedTextMessage = _reflection.GeneratedProtocolMessageType('ExtendedTextMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_EXTENDEDTEXTMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.ExtendedTextMessage)
))
,
DocumentMessage = _reflection.GeneratedProtocolMessageType('DocumentMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_DOCUMENTMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.DocumentMessage)
))
,
AudioMessage = _reflection.GeneratedProtocolMessageType('AudioMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_AUDIOMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.AudioMessage)
))
,
VideoMessage = _reflection.GeneratedProtocolMessageType('VideoMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_VIDEOMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.VideoMessage)
))
,
Call = _reflection.GeneratedProtocolMessageType('Call', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_CALL,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.Call)
))
,
Chat = _reflection.GeneratedProtocolMessageType('Chat', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_CHAT,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.Chat)
))
,
ProtocolMessage = _reflection.GeneratedProtocolMessageType('ProtocolMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_PROTOCOLMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.ProtocolMessage)
))
,
ContactsArrayMessage = _reflection.GeneratedProtocolMessageType('ContactsArrayMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_CONTACTSARRAYMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.ContactsArrayMessage)
))
,
HighlyStructuredMessage = _reflection.GeneratedProtocolMessageType('HighlyStructuredMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_HIGHLYSTRUCTUREDMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.HighlyStructuredMessage)
))
,
StickerMessage = _reflection.GeneratedProtocolMessageType('StickerMessage', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE_STICKERMESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message.StickerMessage)
))
,
DESCRIPTOR = _MESSAGE,
__module__ = 'e2e_pb2'
# @@protoc_insertion_point(class_scope:Message)
))
_sym_db.RegisterMessage(Message)
_sym_db.RegisterMessage(Message.SenderKeyDistributionMessage)
_sym_db.RegisterMessage(Message.ImageMessage)
_sym_db.RegisterMessage(Message.ContactMessage)
_sym_db.RegisterMessage(Message.LocationMessage)
_sym_db.RegisterMessage(Message.ExtendedTextMessage)
_sym_db.RegisterMessage(Message.DocumentMessage)
_sym_db.RegisterMessage(Message.AudioMessage)
_sym_db.RegisterMessage(Message.VideoMessage)
_sym_db.RegisterMessage(Message.Call)
_sym_db.RegisterMessage(Message.Chat)
_sym_db.RegisterMessage(Message.ProtocolMessage)
_sym_db.RegisterMessage(Message.ContactsArrayMessage)
_sym_db.RegisterMessage(Message.HighlyStructuredMessage)
_sym_db.RegisterMessage(Message.StickerMessage)
# @@protoc_insertion_point(module_scope)
| 73,026 | Python | .py | 1,515 | 43.060066 | 6,976 | 0.722536 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,545 | protocol_pb2.py | tgalal_yowsup/yowsup/layers/protocol_messages/proto/protocol_pb2.py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protocol.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='protocol.proto',
package='',
syntax='proto2',
serialized_options=None,
serialized_pb=_b('\n\x0eprotocol.proto\"R\n\nMessageKey\x12\x12\n\nremote_jid\x18\x01 \x01(\t\x12\x0f\n\x07\x66rom_me\x18\x02 \x01(\x08\x12\n\n\x02id\x18\x03 \x01(\t\x12\x13\n\x0bparticipant\x18\x04 \x01(\t')
)
_MESSAGEKEY = _descriptor.Descriptor(
name='MessageKey',
full_name='MessageKey',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='remote_jid', full_name='MessageKey.remote_jid', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='from_me', full_name='MessageKey.from_me', index=1,
number=2, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='id', full_name='MessageKey.id', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='participant', full_name='MessageKey.participant', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=18,
serialized_end=100,
)
DESCRIPTOR.message_types_by_name['MessageKey'] = _MESSAGEKEY
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
MessageKey = _reflection.GeneratedProtocolMessageType('MessageKey', (_message.Message,), dict(
DESCRIPTOR = _MESSAGEKEY,
__module__ = 'protocol_pb2'
# @@protoc_insertion_point(class_scope:MessageKey)
))
_sym_db.RegisterMessage(MessageKey)
# @@protoc_insertion_point(module_scope)
| 3,050 | Python | .py | 76 | 36.078947 | 210 | 0.723986 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,546 | test_message.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/test_message.py | from yowsup.layers.protocol_messages.protocolentities.message import MessageProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class MessageProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = MessageProtocolEntity
# ORDER_MATTERS for node.toString() to output return attribs in same order
attribs = {
"type": "message_type",
"id": "message-id",
"t": "12345",
"offline": "0",
"from": "from_jid",
"notify": "notify_name"
}
self.node = ProtocolTreeNode("message", attribs)
| 719 | Python | .py | 17 | 34.352941 | 90 | 0.68 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,547 | message.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/message.py | from yowsup.structs import ProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from copy import deepcopy
class MessageProtocolEntity(ProtocolEntity):
MESSAGE_TYPE_TEXT = "text"
MESSAGE_TYPE_MEDIA = "media"
def __init__(self, messageType, messageMetaAttributes):
"""
:type messageType: str
:type messageMetaAttributes: MessageMetaAttributes
"""
super(MessageProtocolEntity, self).__init__("message")
assert type(messageMetaAttributes) is MessageMetaAttributes
self._type = messageType
self._id = messageMetaAttributes.id or self._generateId()
self._from = messageMetaAttributes.sender
self.to = messageMetaAttributes.recipient
self.timestamp = messageMetaAttributes.timestamp or self._getCurrentTimestamp()
self.notify = messageMetaAttributes.notify
self.offline = messageMetaAttributes.offline
self.retry = messageMetaAttributes.retry
self.participant= messageMetaAttributes.participant
def getType(self):
return self._type
def getId(self):
return self._id
def getTimestamp(self):
return self.timestamp
def getFrom(self, full = True):
return self._from if full else self._from.split('@')[0]
def isBroadcast(self):
return False
def getTo(self, full = True):
return self.to if full else self.to.split('@')[0]
def getParticipant(self, full = True):
return self.participant if full else self.participant.split('@')[0]
def getAuthor(self, full = True):
return self.getParticipant(full) if self.isGroupMessage() else self.getFrom(full)
def getNotify(self):
return self.notify
def toProtocolTreeNode(self):
attribs = {
"type" : self._type,
"id" : self._id,
}
if self.participant:
attribs["participant"] = self.participant
if self.isOutgoing():
attribs["to"] = self.to
else:
attribs["from"] = self._from
attribs["t"] = str(self.timestamp)
if self.offline is not None:
attribs["offline"] = "1" if self.offline else "0"
if self.notify:
attribs["notify"] = self.notify
if self.retry:
attribs["retry"] = str(self.retry)
xNode = None
#if self.isOutgoing():
# serverNode = ProtocolTreeNode("server", {})
# xNode = ProtocolTreeNode("x", {"xmlns": "jabber:x:event"}, [serverNode])
return self._createProtocolTreeNode(attribs, children = [xNode] if xNode else None, data = None)
def isOutgoing(self):
return self._from is None
def isGroupMessage(self):
if self.isOutgoing():
return "-" in self.to
return self.participant != None
def __str__(self):
out = "Message:\n"
out += "ID: %s\n" % self._id
out += "To: %s\n" % self.to if self.isOutgoing() else "From: %s\n" % self._from
out += "Type: %s\n" % self._type
out += "Timestamp: %s\n" % self.timestamp
if self.participant:
out += "Participant: %s\n" % self.participant
return out
def ack(self, read=False):
return OutgoingReceiptProtocolEntity(self.getId(), self.getFrom(), read, participant=self.getParticipant())
def forward(self, to, _id = None):
OutgoingMessage = deepcopy(self)
OutgoingMessage.to = to
OutgoingMessage._from = None
OutgoingMessage._id = self._generateId() if _id is None else _id
return OutgoingMessage
@staticmethod
def fromProtocolTreeNode(node):
return MessageProtocolEntity(
node["type"],
MessageMetaAttributes.from_message_protocoltreenode(node)
)
| 4,028 | Python | .py | 93 | 34.483871 | 117 | 0.640297 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,548 | message_text.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/message_text.py | from .protomessage import ProtomessageProtocolEntity
from .message import MessageMetaAttributes
from .attributes.attributes_message import MessageAttributes
class TextMessageProtocolEntity(ProtomessageProtocolEntity):
def __init__(self, body, message_meta_attributes=None, to=None):
# flexible attributes for temp backwards compat
assert(bool(message_meta_attributes) ^ bool(to)), "Either set message_meta_attributes, or to, and not both"
if to:
message_meta_attributes = MessageMetaAttributes(recipient=to)
super(TextMessageProtocolEntity, self).__init__("text", MessageAttributes(body), message_meta_attributes)
self.setBody(body)
@property
def conversation(self):
return self.message_attributes.conversation
@conversation.setter
def conversation(self, value):
self.message_attributes.conversation = value
def getBody(self):
#obsolete
return self.conversation
def setBody(self, body):
#obsolete
self.conversation = body
| 1,056 | Python | .py | 23 | 39.086957 | 115 | 0.735151 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,549 | message_text_broadcast.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/message_text_broadcast.py | from .message_text import TextMessageProtocolEntity
from yowsup.structs import ProtocolTreeNode
import time
class BroadcastTextMessage(TextMessageProtocolEntity):
def __init__(self, jids, body):
broadcastTime = int(time.time() * 1000)
super(BroadcastTextMessage, self).__init__(body, to = "%s@broadcast" % broadcastTime)
self.setBroadcastProps(jids)
def setBroadcastProps(self, jids):
assert type(jids) is list, "jids must be a list, got %s instead." % type(jids)
self.jids = jids
def toProtocolTreeNode(self):
node = super(BroadcastTextMessage, self).toProtocolTreeNode()
toNodes = [ProtocolTreeNode("to", {"jid": jid}) for jid in self.jids]
broadcastNode = ProtocolTreeNode("broadcast", children = toNodes)
node.addChild(broadcastNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = TextMessageProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = BroadcastTextMessage
jids = [toNode.getAttributeValue("jid") for toNode in node.getChild("broadcast").getAllChildren()]
entity.setBroadcastProps(jids)
return entity
| 1,185 | Python | .py | 24 | 42.416667 | 106 | 0.711572 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,550 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/__init__.py | from .message_text import TextMessageProtocolEntity
from .message import MessageProtocolEntity
from .message_text_broadcast import BroadcastTextMessage
from .message_extendedtext import ExtendedTextMessageProtocolEntity
| 220 | Python | .py | 4 | 54 | 67 | 0.907407 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,551 | test_message_text.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/test_message_text.py | from yowsup.layers.protocol_messages.protocolentities.message_text import TextMessageProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_messages.protocolentities.test_message import MessageProtocolEntityTest
from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
class TextMessageProtocolEntityTest(MessageProtocolEntityTest):
def setUp(self):
super(TextMessageProtocolEntityTest, self).setUp()
self.ProtocolEntity = TextMessageProtocolEntity
m = Message()
m.conversation = "body_data"
proto_node = ProtocolTreeNode("proto", {}, None, m.SerializeToString())
self.node.addChild(proto_node)
| 690 | Python | .py | 12 | 52 | 99 | 0.795858 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,552 | message_extendedtext.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/message_extendedtext.py | from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_extendedtext import ExtendedTextAttributes
from yowsup.layers.protocol_messages.protocolentities.protomessage import ProtomessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class ExtendedTextMessageProtocolEntity(ProtomessageProtocolEntity):
def __init__(self, extended_text_attrs, message_meta_attrs):
# type: (ExtendedTextAttributes, MessageMetaAttributes) -> None
super(ExtendedTextMessageProtocolEntity, self).__init__(
"text", MessageAttributes(extended_text=extended_text_attrs), message_meta_attrs
)
@property
def text(self):
return self.message_attributes.extended_text.text
@text.setter
def text(self, value):
self.message_attributes.extended_text.text = value
@property
def context_info(self):
return self.message_attributes.extended_text.context_info
@context_info.setter
def context_info(self, value):
self.message_attributes.extended_text.context_info = value
| 1,257 | Python | .py | 22 | 51.136364 | 118 | 0.78926 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,553 | test_message_text_broadcast.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/test_message_text_broadcast.py | from yowsup.layers.protocol_messages.protocolentities.test_message_text import TextMessageProtocolEntityTest
from yowsup.layers.protocol_messages.protocolentities.message_text_broadcast import BroadcastTextMessage
from yowsup.structs import ProtocolTreeNode
class BroadcastTextMessageTest(TextMessageProtocolEntityTest):
def setUp(self):
super(BroadcastTextMessageTest, self).setUp()
self.ProtocolEntity = BroadcastTextMessage
broadcastNode = ProtocolTreeNode("broadcast")
jids = ["jid1", "jid2"]
toNodes = [ProtocolTreeNode("to", {"jid" : jid}) for jid in jids]
broadcastNode.addChildren(toNodes)
self.node.addChild(broadcastNode)
| 694 | Python | .py | 12 | 51.666667 | 108 | 0.779412 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,554 | proto.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/proto.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class ProtoProtocolEntity(ProtocolEntity):
def __init__(self, protoData, mediaType = None):
super(ProtoProtocolEntity, self).__init__("proto")
self.mediaType = mediaType
self.protoData = protoData
def getProtoData(self):
return self.protoData
def getMediaType(self):
return self.mediaType
def toProtocolTreeNode(self):
attribs = {}
if self.mediaType:
attribs["mediatype"] = self.mediaType
return ProtocolTreeNode("proto", attribs, data=self.protoData)
@staticmethod
def fromProtocolTreeNode(node):
return ProtoProtocolEntity(node.data, node["mediatype"]) | 727 | Python | .py | 18 | 33.166667 | 70 | 0.699291 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,555 | protomessage.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/protomessage.py | from .message import MessageProtocolEntity
from .proto import ProtoProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.converter import AttributesConverter
from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
import logging
logger = logging.getLogger(__name__)
class ProtomessageProtocolEntity(MessageProtocolEntity):
'''
<message t="{{TIME_STAMP}}" from="{{CONTACT_JID}}"
offline="{{OFFLINE}}" type="text" id="{{MESSAGE_ID}}" notify="{{NOTIFY_NAME}}">
<proto>
{{SERIALIZE_PROTO_DATA}}
</proto>
</message>
'''
def __init__(self, messageType, message_attributes, messageMetaAttributes):
super(ProtomessageProtocolEntity, self).__init__(messageType, messageMetaAttributes)
self._message_attributes = message_attributes # type: MessageAttributes
def __str__(self):
out = super(ProtomessageProtocolEntity, self).__str__()
return "%s\nmessage_attributes=%s" % (out, self._message_attributes)
def toProtocolTreeNode(self):
node = super(ProtomessageProtocolEntity, self).toProtocolTreeNode()
node.addChild(
ProtoProtocolEntity(
AttributesConverter.get().message_to_protobytes(self._message_attributes)
).toProtocolTreeNode()
)
return node
@property
def message_attributes(self):
return self._message_attributes
@message_attributes.setter
def message_attributes(self, value):
self._message_attributes = value
@classmethod
def fromProtocolTreeNode(cls, node):
entity = MessageProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = cls
m = Message()
m.ParseFromString(node.getChild("proto").getData())
entity.message_attributes = AttributesConverter.get().proto_to_message(m)
return entity
| 2,013 | Python | .py | 44 | 38.477273 | 108 | 0.704233 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,556 | 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 | .py | 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,557 | attributes_context_info.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_context_info.py | class ContextInfoAttributes(object):
def __init__(self,
stanza_id=None,
participant=None,
quoted_message=None,
remote_jid=None,
mentioned_jid=None,
edit_version=None,
revoke_message=None
):
self._stanza_id = stanza_id
self._participant = participant
self._quoted_message = quoted_message
self._remote_jid = remote_jid
self._mentioned_jid = mentioned_jid or []
self._edit_version = edit_version
self._revoke_message = revoke_message
def __str__(self):
attribs = []
if self._stanza_id is not None:
attribs.append(("stanza_id", self.stanza_id))
if self._participant is not None:
attribs.append(("participant", self.participant))
if self.quoted_message is not None:
attribs.append(("quoted_message", self.quoted_message))
if self._remote_jid is not None:
attribs.append(("remote_jid", self.remote_jid))
if self.mentioned_jid is not None and len(self.mentioned_jid):
attribs.append(("mentioned_jid", self.mentioned_jid))
if self.edit_version is not None:
attribs.append(("edit_version", self.edit_version))
if self.revoke_message is not None:
attribs.append(("revoke_message", self.revoke_message))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attribs)))
@property
def stanza_id(self):
return self._stanza_id
@stanza_id.setter
def stanza_id(self, value):
self._stanza_id = value
@property
def participant(self):
return self._participant
@participant.setter
def participant(self, value):
self._participant = value
@property
def quoted_message(self):
return self._quoted_message
@quoted_message.setter
def quoted_message(self, value):
self._quoted_message = value
@property
def remote_jid(self):
return self._remote_jid
@remote_jid.setter
def remote_jid(self, value):
self._remote_jid = value
@property
def mentioned_jid(self):
return self._mentioned_jid
@mentioned_jid.setter
def mentioned_jid(self, value):
self._mentioned_jid = value
@property
def edit_version(self):
return self._edit_version
@edit_version.setter
def edit_version(self, value):
self._edit_version = value
@property
def revoke_message(self):
return self._revoke_message
@revoke_message.setter
def revoke_message(self, value):
self._revoke_message = value
| 2,728 | Python | .py | 76 | 27.052632 | 77 | 0.611533 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,558 | attributes_message_key.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_message_key.py | class MessageKeyAttributes(object):
def __init__(self, remote_jid, from_me, id, participant):
self._remote_jid = remote_jid
self._from_me = from_me
self._id = id
self._participant = participant
def __str__(self):
attrs = []
if self.remote_jid is not None:
attrs.append(("remote_jid", self.remote_jid))
if self.from_me is not None:
attrs.append(("from_me", self.from_me))
if self.id is not None:
attrs.append(("id", self.id))
if self.participant is not None:
attrs.append(("participant", self.participant))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def remote_jid(self):
return self._remote_jid
@remote_jid.setter
def remote_jid(self, value):
self._remote_jid = value
@property
def from_me(self):
return self._from_me
@from_me.setter
def from_me(self, value):
self._from_me = value
@property
def id(self):
return self._id
@id.setter
def id(self, value):
self._id = value
@property
def participant(self):
return self._participant
@participant.setter
def participant(self, value):
self._participant = value
| 1,314 | Python | .py | 41 | 24.365854 | 75 | 0.589074 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,559 | attributes_location.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_location.py | class LocationAttributes(object):
def __init__(self,
degrees_latitude, degrees_longitude,
name=None, address=None, url=None,
duration=None, accuracy_in_meters=None, speed_in_mps=None, degrees_clockwise_from_magnetic_north=None,
axolotl_sender_key_distribution_message=None, jpeg_thumbnail=None):
"""
:param degrees_latitude: Actual location, Place
:param degrees_longitude: Actual location, Place
:param name: Place
:param address: Place
:param url: Place
:param duration:
:param accuracy_in_meters:
:param speed_in_mps:
:param degrees_clockwise_from_magnetic_north:
:param axolotl_sender_key_distribution_message:
:param jpeg_thumbnail: Actual location, Place
"""
self._degrees_latitude = degrees_latitude
self._degrees_longitude = degrees_longitude
self._name = name
self._address = address
self._url = url
self._duration = duration
self._accuracy_in_meters = accuracy_in_meters
self._speed_in_mps = speed_in_mps
self._degrees_clockwise_from_magnetic_north = degrees_clockwise_from_magnetic_north
self._axolotl_sender_key_distribution_message = axolotl_sender_key_distribution_message
self._jpeg_thumbnail = jpeg_thumbnail
def __str__(self):
attrs = []
if self.degrees_latitude is not None:
attrs.append(("degrees_latitude", self.degrees_latitude))
if self.degrees_longitude is not None:
attrs.append(("degrees_longitude", self.degrees_longitude))
if self.name is not None:
attrs.append(("name", self.name))
if self.address is not None:
attrs.append(("address", self.address))
if self.url is not None:
attrs.append(("url", self.url))
if self.duration is not None:
attrs.append(("duration", self.duration))
if self.accuracy_in_meters is not None:
attrs.append(("accuracy_in_meters", self.accuracy_in_meters))
if self.speed_in_mps is not None:
attrs.append(("speed_in_mps", self.speed_in_mps))
if self.degrees_clockwise_from_magnetic_north is not None:
attrs.append(("degrees_clockwise_from_magnetic_north", self.degrees_clockwise_from_magnetic_north))
if self.axolotl_sender_key_distribution_message is not None:
attrs.append(("axolotl_sender_key_distribution_message", "[binary data]"))
if self.jpeg_thumbnail is not None:
attrs.append(("jpeg_thumbnail", "[binary data]"))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def degrees_latitude(self):
return self._degrees_latitude
@degrees_latitude.setter
def degrees_latitude(self, value):
self._degrees_latitude = value
@property
def degrees_longitude(self):
return self._degrees_longitude
@degrees_longitude.setter
def degrees_longitude(self, value):
self._degrees_longitude = value
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def address(self):
return self._address
@address.setter
def address(self, value):
self._address = value
@property
def url(self):
return self._url
@url.setter
def url(self, value):
self._url = value
@property
def duration(self):
return self._duration
@duration.setter
def duration(self, value):
self._duration = value
@property
def accuracy_in_meters(self):
return self._accuracy_in_meters
@accuracy_in_meters.setter
def accuracy_in_meters(self, value):
self._accuracy_in_meters = value
@property
def speed_in_mps(self):
return self._speed_in_mps
@speed_in_mps.setter
def speed_in_mps(self, value):
self._speed_in_mps = value
@property
def degrees_clockwise_from_magnetic_north(self):
return self._degrees_clockwise_from_magnetic_north
@degrees_clockwise_from_magnetic_north.setter
def degrees_clockwise_from_magnetic_north(self, value):
self._degrees_clockwise_from_magnetic_north = value
@property
def axolotl_sender_key_distribution_message(self):
return self._axolotl_sender_key_distribution_message
@axolotl_sender_key_distribution_message.setter
def axolotl_sender_key_distribution_message(self, value):
self._axolotl_sender_key_distribution_message = value
@property
def jpeg_thumbnail(self):
return self._jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self._jpeg_thumbnail = value
| 4,869 | Python | .py | 121 | 31.958678 | 119 | 0.652763 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,560 | attributes_video.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_video.py | class VideoAttributes(object):
def __init__(self, downloadablemedia_attributes, width, height, seconds,
gif_playback=None, jpeg_thumbnail=None, gif_attribution=None, caption=None, streaming_sidecar=None):
self._downloadablemedia_attributes = downloadablemedia_attributes
self._width = width
self._height = height
self._seconds = seconds
self._gif_playback = gif_playback
self._jpeg_thumbnail = jpeg_thumbnail
self._gif_attribution = gif_attribution
self._caption = caption
self._streaming_sidecar = streaming_sidecar
def __str__(self):
attrs = []
if self.width is not None:
attrs.append(("width", self.width))
if self.height is not None:
attrs.append(("height", self.height))
if self.seconds is not None:
attrs.append(("seconds", self.seconds))
if self.gif_playback is not None:
attrs.append(("gif_playback", self.gif_playback))
if self.jpeg_thumbnail is not None:
attrs.append(("jpeg_thumbnail", "[binary data]"))
if self.gif_attribution is not None:
attrs.append(("gif_attribution", self.gif_attribution))
if self.caption is not None:
attrs.append(("caption", self.caption))
if self.streaming_sidecar is not None:
attrs.append(("streaming_sidecar", "[binary data]"))
attrs.append(("downloadable", self.downloadablemedia_attributes))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def downloadablemedia_attributes(self):
return self._downloadablemedia_attributes
@downloadablemedia_attributes.setter
def downloadablemedia_attributes(self, value):
self._downloadablemedia_attributes = value
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def seconds(self):
return self._seconds
@seconds.setter
def seconds(self, value):
self._seconds = value
@property
def gif_playback(self):
return self._gif_playback
@gif_playback.setter
def gif_playback(self, value):
self._gif_playback = value
@property
def jpeg_thumbnail(self):
return self._jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self._jpeg_thumbnail = value
@property
def gif_attribution(self):
return self._gif_attribution
@gif_attribution.setter
def gif_attribution(self, value):
self._gif_attribution = value
@property
def caption(self):
return self._caption
@caption.setter
def caption(self, value):
self._caption = value
@property
def streaming_sidecar(self):
return self._streaming_sidecar
@streaming_sidecar.setter
def streaming_sidecar(self, value):
self._streaming_sidecar = value
| 3,158 | Python | .py | 86 | 28.872093 | 117 | 0.646461 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,561 | converter.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/converter.py | from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
from yowsup.layers.protocol_messages.proto.protocol_pb2 import MessageKey
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_image import ImageAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_downloadablemedia \
import DownloadableMediaMessageAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_media import MediaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_context_info import ContextInfoAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
from yowsup.layers.protocol_messages.proto.e2e_pb2 import ContextInfo
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_extendedtext import ExtendedTextAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_document import DocumentAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_contact import ContactAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_location import LocationAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_video import VideoAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_audio import AudioAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_sticker import StickerAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_sender_key_distribution_message import \
SenderKeyDistributionMessageAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_protocol import ProtocolAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_protocol import MessageKeyAttributes
class AttributesConverter(object):
__instance = None
@classmethod
def get(cls):
if cls.__instance is None:
cls.__instance = AttributesConverter()
return cls.__instance
def sender_key_distribution_message_to_proto(self, sender_key_distribution_message_attributes):
# type: (SenderKeyDistributionMessageAttributes) -> Message.SenderKeyDistributionMessage
message = Message.SenderKeyDistributionMessage()
message.group_id = sender_key_distribution_message_attributes.group_id
message.axolotl_sender_key_distribution_message = \
sender_key_distribution_message_attributes.axolotl_sender_key_distribution_message
return message
def proto_to_sender_key_distribution_message(self, proto):
return SenderKeyDistributionMessageAttributes(
proto.group_id, proto.axolotl_sender_key_distribution_message
)
def message_key_to_proto(self, message_key):
# type: (MessageKeyAttributes) -> MessageKey
out = MessageKey()
out.remote_jid = message_key.remote_jid
out.from_me = message_key.from_me
out.id = message_key.id
out.participant = message_key.participant
return out
def proto_to_message_key(self, proto):
return MessageKeyAttributes(
proto.remote_jid, proto.from_me, proto.id, proto.participant
)
def protocol_to_proto(self, protocol):
# type: (ProtocolAttributes) -> Message.ProtocolMessage
message = Message.ProtocolMessage()
message.key.MergeFrom(self.message_key_to_proto(protocol.key))
message.type = protocol.type
return message
def proto_to_protocol(self, proto):
return ProtocolAttributes(
self.proto_to_message_key(proto.key),
proto.type
)
def contact_to_proto(self, contact_attributes):
# type: (ContactAttributes) -> Message.ContactMessage
contact_message = Message.ContactMessage()
contact_message.display_name = contact_attributes.display_name
contact_message.vcard = contact_attributes.vcard
if contact_attributes.context_info is not None:
contact_message.context_info.MergeFrom(self.contextinfo_to_proto(contact_attributes.context_info))
return contact_message
def proto_to_contact(self, proto):
# type: (Message.ContactMessage) -> ContactAttributes
return ContactAttributes(
proto.display_name,
proto.vcard,
self.proto_to_contextinfo(proto.context_info) if proto.HasField("context_info") else None
)
def location_to_proto(self, location_attributes):
# type: (LocationAttributes) -> Message.LocationMessage
location_message = Message.LocationMessage()
if location_attributes.degrees_latitude is not None:
location_message.degrees_latitude = location_attributes.degrees_latitude
if location_attributes.degrees_longitude is not None:
location_message.degrees_longitude = location_attributes.degrees_longitude
if location_attributes.name is not None:
location_message.name = location_attributes.name
if location_attributes.address is not None:
location_message.address = location_attributes.address
if location_attributes.url is not None:
location_message.url = location_attributes.url
if location_attributes.duration is not None:
location_message.duration = location_attributes.duration
if location_attributes.accuracy_in_meters is not None:
location_message.accuracy_in_meters = location_attributes.accuracy_in_meters
if location_attributes.speed_in_mps is not None:
location_message.speed_in_mps = location_attributes.speed_in_mps
if location_attributes.degrees_clockwise_from_magnetic_north is not None:
location_message.degrees_clockwise_from_magnetic_north = \
location_attributes.degrees_clockwise_from_magnetic_north
if location_attributes.axolotl_sender_key_distribution_message is not None:
location_message._axolotl_sender_key_distribution_message = \
location_attributes.axolotl_sender_key_distribution_message
if location_attributes.jpeg_thumbnail is not None:
location_message.jpeg_thumbnail = location_attributes.jpeg_thumbnail
return location_message
def proto_to_location(self, proto):
# type: (Message.LocationMessage) -> LocationAttributes
return LocationAttributes(
proto.degrees_latitude if proto.HasField("degrees_latitude") else None,
proto.degrees_longitude if proto.HasField("degrees_longitude") else None,
proto.name if proto.HasField("name") else None,
proto.address if proto.HasField("address") else None,
proto.url if proto.HasField("url") else None,
proto.duration if proto.HasField("duration") else None,
proto.accuracy_in_meters if proto.HasField("accuracy_in_meters") else None,
proto.speed_in_mps if proto.HasField("speed_in_mps") else None,
proto.degrees_clockwise_from_magnetic_north
if proto.HasField("degrees_clockwise_from_magnetic_north") else None,
proto.axolotl_sender_key_distribution_message
if proto.HasField("axolotl_sender_key_distribution_message") else None,
proto.jpeg_thumbnail if proto.HasField("jpeg_thumbnail") else None
)
def image_to_proto(self, image_attributes):
# type: (ImageAttributes) -> Message.ImageMessage
image_message = Message.ImageMessage()
image_message.width = image_attributes.width
image_message.height = image_attributes.height
if image_attributes.caption is not None:
image_message.caption = image_attributes.caption
if image_attributes.jpeg_thumbnail is not None:
image_message.jpeg_thumbnail = image_attributes.jpeg_thumbnail
return self.downloadablemedia_to_proto(image_attributes.downloadablemedia_attributes, image_message)
def proto_to_image(self, proto):
# type: (Message.ImageMessage) -> ImageAttributes
return ImageAttributes(
self.proto_to_downloadablemedia(proto),
proto.width, proto.height,
proto.caption if proto.HasField("caption") else None,
proto.jpeg_thumbnail if proto.HasField("jpeg_thumbnail") else None
)
def extendedtext_to_proto(self, extendedtext_attributes):
# type: (ExtendedTextAttributes) -> Message.ExtendedTextMessage
m = Message.ExtendedTextMessage()
if extendedtext_attributes.text is not None:
m.text = extendedtext_attributes.text
if extendedtext_attributes.matched_text is not None:
m.matched_text = extendedtext_attributes.matched_text
if extendedtext_attributes.canonical_url is not None:
m.canonical_url = extendedtext_attributes.canonical_url
if extendedtext_attributes.description is not None:
m.description = extendedtext_attributes.description
if extendedtext_attributes.title is not None:
m.title = extendedtext_attributes.title
if extendedtext_attributes.jpeg_thumbnail is not None:
m.jpeg_thumbnail = extendedtext_attributes.jpeg_thumbnail
if extendedtext_attributes.context_info is not None:
m.context_info.MergeFrom(self.contextinfo_to_proto(extendedtext_attributes.context_info))
return m
def proto_to_extendedtext(self, proto):
# type: (Message.ExtendedTextMessage) -> ExtendedTextAttributes
return ExtendedTextAttributes(
proto.text if proto.HasField("text") else None,
proto.matched_text if proto.HasField("matched_text") else None,
proto.canonical_url if proto.HasField("canonical_url") else None,
proto.description if proto.HasField("description") else None,
proto.title if proto.HasField("title") else None,
proto.jpeg_thumbnail if proto.HasField("jpeg_thumbnail") else None,
self.proto_to_contextinfo(proto.context_info) if proto.HasField("context_info") else None
)
def document_to_proto(self, document_attributes):
# type: (DocumentAttributes) -> Message.DocumentMessage
m = Message.DocumentMessage()
if document_attributes.file_name is not None:
m.file_name = document_attributes.file_name
if document_attributes.file_length is not None:
m.file_length = document_attributes.file_length
if document_attributes.title is not None:
m.title = document_attributes.title
if document_attributes.page_count is not None:
m.page_count = document_attributes.page_count
if document_attributes.jpeg_thumbnail is not None:
m.jpeg_thumbnail = document_attributes.jpeg_thumbnail
return self.downloadablemedia_to_proto(document_attributes.downloadablemedia_attributes, m)
def proto_to_document(self, proto):
return DocumentAttributes(
self.proto_to_downloadablemedia(proto),
proto.file_name if proto.HasField("file_name") else None,
proto.file_length if proto.HasField("file_length") else None,
proto.title if proto.HasField("title") else None,
proto.page_count if proto.HasField("page_count") else None,
proto.jpeg_thumbnail if proto.HasField("jpeg_thumbnail") else None
)
def audio_to_proto(self, audio_attributes):
# type: (AudioAttributes) -> Message.AudioMessage
m = Message.AudioMessage()
if audio_attributes.seconds is not None:
m.seconds = audio_attributes.seconds
if audio_attributes.ptt is not None:
m.ptt = audio_attributes.ptt
return self.downloadablemedia_to_proto(audio_attributes.downloadablemedia_attributes, m)
def proto_to_audio(self, proto):
return AudioAttributes(
self.proto_to_downloadablemedia(proto),
proto.seconds,
proto.ptt
)
def video_to_proto(self, video_attributes):
# type: (VideoAttributes) -> Message.VideoMessage
m = Message.VideoMessage()
if video_attributes.width is not None:
m.width = video_attributes.width
if video_attributes.height is not None:
m.height = video_attributes.height
if video_attributes.seconds is not None:
m.seconds = video_attributes.seconds
if video_attributes.gif_playback is not None:
m.gif_playback = video_attributes.gif_playback
if video_attributes.jpeg_thumbnail is not None:
m.jpeg_thumbnail = video_attributes.jpeg_thumbnail
if video_attributes.gif_attribution is not None:
m.gif_attribution = video_attributes.gif_attribution
if video_attributes.caption is not None:
m.caption = video_attributes.caption
if video_attributes.streaming_sidecar is not None:
m.streaming_sidecar = video_attributes.streaming_sidecar
return self.downloadablemedia_to_proto(video_attributes.downloadablemedia_attributes, m)
def proto_to_video(self, proto):
return VideoAttributes(
self.proto_to_downloadablemedia(proto),
proto.width, proto.height, proto.seconds, proto.gif_playback,
proto.jpeg_thumbnail, proto.gif_attribution, proto.caption, proto.streaming_sidecar
)
def sticker_to_proto(self, sticker_attributes):
# type: (StickerAttributes) -> Message.StickerMessage
m = Message.StickerMessage()
if sticker_attributes.width is not None:
m.width = sticker_attributes.width
if sticker_attributes.height is not None:
m.height = sticker_attributes.height
if sticker_attributes.png_thumbnail is not None:
m.png_thumbnail = sticker_attributes.png_thumbnail
return self.downloadablemedia_to_proto(sticker_attributes.downloadablemedia_attributes, m)
def proto_to_sticker(self, proto):
return StickerAttributes(
self.proto_to_downloadablemedia(proto),
proto.width, proto.height, proto.png_thumbnail
)
def downloadablemedia_to_proto(self, downloadablemedia_attributes, proto):
# type: (DownloadableMediaMessageAttributes, object) -> object
proto.mimetype = downloadablemedia_attributes.mimetype
proto.file_length = downloadablemedia_attributes.file_length
proto.file_sha256 = downloadablemedia_attributes.file_sha256
if downloadablemedia_attributes.url is not None:
proto.url = downloadablemedia_attributes.url
if downloadablemedia_attributes.media_key is not None:
proto.media_key = downloadablemedia_attributes.media_key
return self.media_to_proto(downloadablemedia_attributes, proto)
def proto_to_downloadablemedia(self, proto):
return DownloadableMediaMessageAttributes(
mimetype=proto.mimetype,
file_length=proto.file_length,
file_sha256=proto.file_sha256,
url=proto.url,
media_key=proto.media_key,
context_info=self.proto_to_contextinfo(proto.context_info)
if proto.HasField("context_info") else None
)
def media_to_proto(self, media_attributes, proto):
# type: (MediaAttributes, object) -> object
if media_attributes.context_info:
proto.context_info.MergeFrom(self.contextinfo_to_proto(media_attributes.context_info))
return proto
def proto_to_media(self, proto):
return MediaAttributes(
context_info=proto.context_info if proto.HasField("context_info") else None
)
def contextinfo_to_proto(self, contextinfo_attributes):
# type: (ContextInfoAttributes) -> ContextInfo
cxt_info = ContextInfo()
if contextinfo_attributes.stanza_id is not None:
cxt_info.stanza_id = contextinfo_attributes.stanza_id
if contextinfo_attributes.participant is not None:
cxt_info.participant = contextinfo_attributes.participant
if contextinfo_attributes.quoted_message:
cxt_info.quoted_message.MergeFrom(self.message_to_proto(contextinfo_attributes.quoted_message))
if contextinfo_attributes.remote_jid is not None:
cxt_info.remote_jid = contextinfo_attributes.remote_jid
if contextinfo_attributes.mentioned_jid is not None and len(contextinfo_attributes.mentioned_jid):
cxt_info.mentioned_jid[:] = contextinfo_attributes.mentioned_jid
if contextinfo_attributes.edit_version is not None:
cxt_info.edit_version = contextinfo_attributes.edit_version
if contextinfo_attributes.revoke_message is not None:
cxt_info.revoke_message = contextinfo_attributes.revoke_message
return cxt_info
def proto_to_contextinfo(self, proto):
# type: (ContextInfo) -> ContextInfoAttributes
return ContextInfoAttributes(
stanza_id=proto.stanza_id if proto.HasField("stanza_id") else None,
participant=proto.participant if proto.HasField("participant") else None,
quoted_message=self.proto_to_message(proto.quoted_message)
if proto.HasField("quoted_message") else None,
remote_jid=proto.remote_jid if proto.HasField("remote_jid") else None,
mentioned_jid=proto.mentioned_jid if len(proto.mentioned_jid) else [],
edit_version=proto.edit_version if proto.HasField("edit_version") else None,
revoke_message=proto.revoke_message if proto.HasField("revoke_message") else None
)
def message_to_proto(self, message_attributes):
# type: (MessageAttributes) -> Message
message = Message()
if message_attributes.conversation:
message.conversation = message_attributes.conversation
if message_attributes.image:
message.image_message.MergeFrom(self.image_to_proto(message_attributes.image))
if message_attributes.contact:
message.contact_message.MergeFrom(self.contact_to_proto(message_attributes.contact))
if message_attributes.location:
message.location_message.MergeFrom(self.location_to_proto(message_attributes.location))
if message_attributes.extended_text:
message.extended_text_message.MergeFrom(self.extendedtext_to_proto(message_attributes.extended_text))
if message_attributes.document:
message.document_message.MergeFrom(self.document_to_proto(message_attributes.document))
if message_attributes.audio:
message.audio_message.MergeFrom(self.audio_to_proto(message_attributes.audio))
if message_attributes.video:
message.video_message.MergeFrom(self.video_to_proto(message_attributes.video))
if message_attributes.sticker:
message.sticker_message.MergeFrom(self.sticker_to_proto(message_attributes.sticker))
if message_attributes.sender_key_distribution_message:
message.sender_key_distribution_message.MergeFrom(
self.sender_key_distribution_message_to_proto(message_attributes.sender_key_distribution_message)
)
if message_attributes.protocol:
message.protocol_message.MergeFrom(self.protocol_to_proto(message_attributes.protocol))
return message
def proto_to_message(self, proto):
# type: (Message) -> MessageAttributes
conversation = proto.conversation if proto.conversation else None
image = self.proto_to_image(proto.image_message) if proto.HasField("image_message") else None
contact = self.proto_to_contact(proto.contact_message) if proto.HasField("contact_message") else None
location = self.proto_to_location(proto.location_message) if proto.HasField("location_message") else None
extended_text = self.proto_to_extendedtext(proto.extended_text_message) \
if proto.HasField("extended_text_message") else None
document = self.proto_to_document(proto.document_message) \
if proto.HasField("document_message") else None
audio = self.proto_to_audio(proto.audio_message) if proto.HasField("audio_message") else None
video = self.proto_to_video(proto.video_message) if proto.HasField("video_message") else None
sticker = self.proto_to_sticker(proto.sticker_message) if proto.HasField("sticker_message") else None
sender_key_distribution_message = self.proto_to_sender_key_distribution_message(
proto.sender_key_distribution_message
) if proto.HasField("sender_key_distribution_message") else None
protocol = self.proto_to_protocol(proto.protocol_message) if proto.HasField("protocol_message") else None
return MessageAttributes(
conversation,
image,
contact,
location,
extended_text,
document,
audio,
video,
sticker,
sender_key_distribution_message,
protocol
)
def protobytes_to_message(self, protobytes):
# type: (bytes) -> MessageAttributes
m = Message()
m.ParseFromString(protobytes)
return self.proto_to_message(m)
def message_to_protobytes(self, message):
# type: (MessageAttributes) -> bytes
return self.message_to_proto(message).SerializeToString()
| 21,696 | Python | .py | 371 | 48.603774 | 118 | 0.71019 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,562 | attributes_protocol.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_protocol.py | from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_key import MessageKeyAttributes
class ProtocolAttributes(object):
TYPE_REVOKE = 0
TYPES = {
TYPE_REVOKE: "REVOKE"
}
def __init__(self, key, type):
self.key = key
self.type = type
def __str__(self):
return "[type=%s, key=%s]" % (self.TYPES[self.type], self.key)
@property
def key(self):
return self._key
@key.setter
def key(self, value):
assert isinstance(value, MessageKeyAttributes), type(value)
self._key = value
@property
def type(self):
return self._type
@type.setter
def type(self, value):
assert value in self.TYPES, "Unknown type: %s" % value
self._type = value
| 793 | Python | .py | 25 | 25.12 | 115 | 0.634211 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,563 | attributes_message_meta.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_message_meta.py | class MessageMetaAttributes(object):
def __init__(
self, id=None, sender=None, recipient=None, notify=None, timestamp=None, participant=None, offline=None,
retry=None
):
assert (sender or recipient), "Must specify either sender or recipient " \
"jid to create the message "
assert not (sender and recipient), "Can't set both attributes to message at same " \
"time (sender, recipient) "
self.id = id
self.sender = sender
self.recipient = recipient
self.notify = notify
self.timestamp = int(timestamp) if timestamp else None
self.participant = participant
self.offline = offline in ("1", True)
self.retry = int(retry) if retry else None
@staticmethod
def from_message_protocoltreenode(node):
return MessageMetaAttributes(
node["id"], node["from"], node["to"], node["notify"], node["t"], node["participant"], node["offline"],
node["retry"]
)
| 1,082 | Python | .py | 23 | 35.521739 | 116 | 0.587902 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,564 | attributes_document.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_document.py | from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_downloadablemedia import \
DownloadableMediaMessageAttributes
import os
class DocumentAttributes(object):
def __init__(self, downloadablemedia_attributes, file_name, file_length, title=None, page_count=None, jpeg_thumbnail=None):
self._downloadablemedia_attributes = downloadablemedia_attributes
self._file_name = file_name
self._file_length = file_length
self._title = title
self._page_count = page_count
self._jpeg_thumbnail = jpeg_thumbnail
def __str__(self):
attrs = []
if self.file_name is not None:
attrs.append(("file_name", self.file_name))
if self.file_length is not None:
attrs.append(("file_length", self.file_length))
if self.title is not None:
attrs.append(("title", self.title))
if self.page_count is not None:
attrs.append(("page_count", self.page_count))
if self.jpeg_thumbnail is not None:
attrs.append(("jpeg_thumbnail", self.jpeg_thumbnail))
attrs.append(("downloadable", self.downloadablemedia_attributes))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def downloadablemedia_attributes(self):
return self._downloadablemedia_attributes
@downloadablemedia_attributes.setter
def downloadablemedia_attributes(self, value):
self._downloadablemedia_attributes = value
@property
def file_name(self):
return self._file_name
@file_name.setter
def file_name(self, value):
self._file_name = value
@property
def file_length(self):
return self._file_length
@file_length.setter
def file_length(self, value):
self._file_length = value
@property
def title(self):
return self._title
@title.setter
def title(self, value):
self._title = value
@property
def page_count(self):
return self._page_count
@page_count.setter
def page_count(self, value):
self._page_count = value
@property
def jpeg_thumbnail(self):
return self._jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self._jpeg_thumbnail = value
@staticmethod
def from_filepath(filepath):
return DocumentAttributes(
DownloadableMediaMessageAttributes.from_file(filepath),
os.path.basename(filepath),
os.path.getsize(filepath)
)
| 2,565 | Python | .py | 68 | 30.058824 | 127 | 0.660484 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,565 | attributes_downloadablemedia.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_downloadablemedia.py | from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_media import MediaAttributes
from yowsup.common.tools import MimeTools
import base64
import hashlib
import os
class DownloadableMediaMessageAttributes(MediaAttributes):
def __init__(self, mimetype, file_length, file_sha256, url=None, media_key=None, context_info=None):
super(DownloadableMediaMessageAttributes, self).__init__(context_info)
self._mimetype = mimetype
self._file_length = file_length
self._file_sha256 = file_sha256
self._url = url
self._media_key = media_key
def __str__(self):
return "[url=%s, mimetype=%s, file_length=%d, file_sha256=%s, media_key=%s]" % (
self.url,self.mimetype, self.file_length, base64.b64encode(self.file_sha256) if self.file_sha256 else None,
base64.b64encode(self.media_key) if self.media_key else None
)
@property
def url(self):
return self._url
@url.setter
def url(self, value):
self._url = value
@property
def mimetype(self):
return self._mimetype
@mimetype.setter
def mimetype(self, value):
self._mimetype = value
@property
def file_length(self):
return self._file_length
@file_length.setter
def file_length(self, value):
self._file_length = value
@property
def file_sha256(self):
return self._file_sha256
@file_sha256.setter
def file_sha256(self, value):
self._file_sha256 = value
@property
def media_key(self):
return self._media_key
@media_key.setter
def media_key(self, value):
self._media_key = value
@staticmethod
def from_file(
filepath, mimetype=None, file_length=None,
file_sha256=None, url=None, media_key=None, context_info=None
):
mimetype = MimeTools.getMIME(filepath) if mimetype is None else mimetype
file_length = os.path.getsize(filepath) if file_length is None else file_length
if file_sha256 is None:
with open(filepath, 'rb') as f:
file_sha256 = hashlib.sha256(f.read()).digest()
return DownloadableMediaMessageAttributes(
mimetype, file_length, file_sha256, url, media_key, context_info
)
| 2,317 | Python | .py | 61 | 30.655738 | 119 | 0.663247 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,566 | attributes_audio.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_audio.py | from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_downloadablemedia import \
DownloadableMediaMessageAttributes
class AudioAttributes(object):
def __init__(self, downloadablemedia_attributes, seconds, ptt, streaming_sidecar=None):
# type: (DownloadableMediaMessageAttributes, int, bool, bytes) -> None
"""
:param seconds: duration of audio playback in seconds
:param ptt: indicates whether this is a push-to-talk audio message
:param streaming_sidecar
"""
self._downloadablemedia_attributes = downloadablemedia_attributes
self._seconds = seconds # type: int
self._ptt = ptt # type: bool
self._streaming_sidecar = streaming_sidecar # type: bytes
def __str__(self):
attrs = []
if self.seconds is not None:
attrs.append(("seconds", self.seconds))
if self.ptt is not None:
attrs.append(("ptt", self.ptt))
if self._streaming_sidecar is not None:
attrs.append(("streaming_sidecar", "[binary data]"))
attrs.append(("downloadable", self.downloadablemedia_attributes))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def downloadablemedia_attributes(self):
return self._downloadablemedia_attributes
@downloadablemedia_attributes.setter
def downloadablemedia_attributes(self, value):
self._downloadablemedia_attributes = value
@property
def seconds(self):
return self._seconds
@seconds.setter
def seconds(self, value):
self._seconds = value
@property
def ptt(self):
return self._ptt
@ptt.setter
def ptt(self, value):
self._ptt = value
@property
def streaming_sidecar(self):
return self._streaming_sidecar
@streaming_sidecar.setter
def streaming_sidecar(self, value):
self._streaming_sidecar = value
| 1,964 | Python | .py | 48 | 33.333333 | 102 | 0.668067 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,567 | attributes_image.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_image.py | from yowsup.common.tools import ImageTools
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_downloadablemedia \
import DownloadableMediaMessageAttributes
import os
class ImageAttributes(object):
def __init__(self, downloadablemedia_attributes, width, height, caption=None, jpeg_thumbnail=None):
self._downloadablemedia_attributes = downloadablemedia_attributes # type: DownloadableMediaMessageAttributes
self._width = width
self._height = height
self._caption = caption
self._jpeg_thumbnail = jpeg_thumbnail
def __str__(self):
attrs = []
if self.width is not None:
attrs.append(("width", self.width))
if self.height is not None:
attrs.append(("height", self.height))
if self.caption is not None:
attrs.append(("caption", self.caption))
if self.jpeg_thumbnail is not None:
attrs.append(("jpeg_thumbnail", "[binary data]"))
attrs.append(("downloadable", self.downloadablemedia_attributes))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def downloadablemedia_attributes(self):
return self._downloadablemedia_attributes
@downloadablemedia_attributes.setter
def downloadablemedia_attributes(self, value):
self._downloadablemedia_attributes = value
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def caption(self):
return self._caption
@caption.setter
def caption(self, value):
self._caption = value if value else ''
@property
def jpeg_thumbnail(self):
return self._jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self._jpeg_thumbnail = value if value else b''
@staticmethod
def from_filepath(filepath, dimensions=None, caption=None, jpeg_thumbnail=None):
assert os.path.exists(filepath)
if not jpeg_thumbnail:
jpeg_thumbnail = ImageTools.generatePreviewFromImage(filepath)
dimensions = dimensions or ImageTools.getImageDimensions(filepath)
width, height = dimensions if dimensions else (None, None)
assert width and height, "Could not determine image dimensions, install pillow or pass dimensions"
return ImageAttributes(
DownloadableMediaMessageAttributes.from_file(filepath), width, height, caption, jpeg_thumbnail
)
| 2,693 | Python | .py | 64 | 34.515625 | 117 | 0.685802 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,568 | attributes_message.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_message.py | from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_image import ImageAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_extendedtext import ExtendedTextAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_document import DocumentAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_contact import ContactAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_location import LocationAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_video import VideoAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_audio import AudioAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_sticker import StickerAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_sender_key_distribution_message import \
SenderKeyDistributionMessageAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_protocol import ProtocolAttributes
class MessageAttributes(object):
def __init__(
self,
conversation=None,
image=None,
contact=None,
location=None,
extended_text=None,
document=None,
audio=None,
video=None,
sticker=None,
sender_key_distribution_message=None,
protocol=None
):
self._conversation = conversation # type: str
self._image = image # type: ImageAttributes
self._contact = contact # type: ContactAttributes
self._location = location # type: LocationAttributes
self._extended_text = extended_text # type: ExtendedTextAttributes
self._document = document # type: DocumentAttributes
self._audio = audio # type: AudioAttributes
self._video = video # type: VideoAttributes
self._sticker = sticker # type: StickerAttributes
self._sender_key_distribution_message = \
sender_key_distribution_message # type: SenderKeyDistributionMessageAttributes
self._protocol = protocol # type: ProtocolAttributes
def __str__(self):
attrs = []
if self.conversation is not None:
attrs.append(("conversation", self.conversation))
if self.image is not None:
attrs.append(("image", self.image))
if self.contact is not None:
attrs.append(("contact", self.contact))
if self.location is not None:
attrs.append(("location", self.location))
if self.extended_text is not None:
attrs.append(("extended_text", self.extended_text))
if self.document is not None:
attrs.append(("document", self.document))
if self.audio is not None:
attrs.append(("audio", self.audio))
if self.video is not None:
attrs.append(("video", self.video))
if self.sticker is not None:
attrs.append(("sticker", self.sticker))
if self._sender_key_distribution_message is not None:
attrs.append(("sender_key_distribution_message", self.sender_key_distribution_message))
if self._protocol is not None:
attrs.append(("protocol", self.protocol))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def conversation(self):
return self._conversation
@conversation.setter
def conversation(self, value):
self._conversation = value
@property
def image(self):
return self._image
@image.setter
def image(self, value):
self._image = value
@property
def contact(self):
return self._contact
@contact.setter
def contact(self, value):
self._contact = value
@property
def location(self):
return self._location
@location.setter
def location(self, value):
self._location = value
@property
def extended_text(self):
return self._extended_text
@extended_text.setter
def extended_text(self, value):
self._extended_text = value
@property
def document(self):
return self._document
@document.setter
def document(self, value):
self._document = value
@property
def audio(self):
return self._audio
@audio.setter
def audio(self, value):
self._audio = value
@property
def video(self):
return self._video
@video.setter
def video(self, value):
self._video = value
@property
def sticker(self):
return self._sticker
@sticker.setter
def sticker(self, value):
self._sticker = value
@property
def sender_key_distribution_message(self):
return self._sender_key_distribution_message
@sender_key_distribution_message.setter
def sender_key_distribution_message(self, value):
self._sender_key_distribution_message = value
@property
def protocol(self):
return self._protocol
@protocol.setter
def protocol(self, value):
self._protocol = value
| 5,261 | Python | .py | 129 | 33.007752 | 118 | 0.685468 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,569 | attributes_sender_key_distribution_message.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_sender_key_distribution_message.py | class SenderKeyDistributionMessageAttributes(object):
def __init__(self, group_id, axolotl_sender_key_distribution_message):
self._group_id = group_id
self._axolotl_sender_key_distribution_message = axolotl_sender_key_distribution_message
def __str__(self):
attrs = []
if self.group_id is not None:
attrs.append(("group_id", self.group_id))
if self.axolotl_sender_key_distribution_message is not None:
attrs.append(("axolotl_sender_key_distribution_message", "[binary omitted]"))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def group_id(self):
return self._group_id
@group_id.setter
def group_id(self, value):
self._group_id = value
@property
def axolotl_sender_key_distribution_message(self):
return self._axolotl_sender_key_distribution_message
@axolotl_sender_key_distribution_message.setter
def axolotl_sender_key_distribution_message(self, value):
self._axolotl_sender_key_distribution_message = value
| 1,091 | Python | .py | 23 | 39.913043 | 95 | 0.676083 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,570 | attributes_extendedtext.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_extendedtext.py | class ExtendedTextAttributes(object):
def __init__(
self,
text, matched_text, canonical_url, description, title, jpeg_thumbnail, context_info
):
self._text = text
self._matched_text = matched_text
self._canonical_url = canonical_url
self._description = description
self._title = title
self._jpeg_thumbnail = jpeg_thumbnail
self._context_info = context_info
def __str__(self):
attrs = []
if self.text is not None:
attrs.append(("text", self.text))
if self.matched_text is not None:
attrs.append(("matched_text", self.matched_text))
if self.canonical_url is not None:
attrs.append(("canonical_url", self.canonical_url))
if self.description is not None:
attrs.append(("description", self.description))
if self.title is not None:
attrs.append(("title", self.title))
if self.jpeg_thumbnail is not None:
attrs.append(("jpeg_thumbnail", "[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 text(self):
return self._text
@text.setter
def text(self, value):
self._text = value
@property
def matched_text(self):
return self._matched_text
@matched_text.setter
def matched_text(self, value):
self._matched_text = value
@property
def canonical_url(self):
return self._canonical_url
@canonical_url.setter
def canonical_url(self, value):
self._canonical_url = value
@property
def description(self):
return self._description
@description.setter
def description(self, value):
self._description = value
@property
def title(self):
return self._title
@title.setter
def title(self, value):
self._title = value
@property
def jpeg_thumbnail(self):
return self._jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self._jpeg_thumbnail = value
@property
def context_info(self):
return self._context_info
@context_info.setter
def context_info(self, value):
self._context_info = value
| 2,396 | Python | .py | 71 | 25.873239 | 95 | 0.617583 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,571 | attributes_media.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_media.py | from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_context_info import ContextInfoAttributes
class MediaAttributes(object):
def __init__(self, context_info=None):
"""
:type context_info: ContextInfo | None
"""
if context_info:
assert type(context_info) is ContextInfoAttributes, type(context_info)
self._context_info = context_info # type: ContextInfoAttributes | None
else:
self._context_info = None
@property
def context_info(self):
return self._context_info
@context_info.setter
def context_info(self, value):
assert type(value) is ContextInfoAttributes, type(value)
self._context_info = value
| 747 | Python | .py | 18 | 33.611111 | 117 | 0.678621 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,572 | attributes_sticker.py | tgalal_yowsup/yowsup/layers/protocol_messages/protocolentities/attributes/attributes_sticker.py | class StickerAttributes(object):
def __init__(self, downloadablemedia_attributes, width, height, png_thumbnail=None):
self._downloadablemedia_attributes = downloadablemedia_attributes
self._width = width
self._height = height
self._png_thumbnail = png_thumbnail
def __str__(self):
attrs = []
if self.width is not None:
attrs.append(("width", self.width))
if self.height is not None:
attrs.append(("height", self.height))
if self.png_thumbnail is not None:
attrs.append(("png_thumbnail", self.png_thumbnail))
attrs.append(("downloadable", self.downloadablemedia_attributes))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def downloadablemedia_attributes(self):
return self._downloadablemedia_attributes
@downloadablemedia_attributes.setter
def downloadablemedia_attributes(self, value):
self._downloadablemedia_attributes = value
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def png_thumbnail(self):
return self._png_thumbnail
@png_thumbnail.setter
def png_thumbnail(self, value):
self._png_thumbnail = value
| 1,480 | Python | .py | 40 | 29.45 | 88 | 0.65035 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,573 | test_mediacipher.py | tgalal_yowsup/yowsup/layers/protocol_media/test_mediacipher.py | from yowsup.layers.protocol_media.mediacipher import MediaCipher
import base64
import unittest
class MediaCipherTest(unittest.TestCase):
IMAGE = (
b'EOnnZIBu1vTSI51IeJvaKR+8W1FqBETATI2Ikl6nVQ8=',
b'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8M'
b'CgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQ'
b'EBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAABAAEDAREAAhEBAxEB/8QAHwAAAQUBAQEB'
b'AQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKB'
b'kaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1'
b'dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl'
b'5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcF'
b'BAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5'
b'OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0'
b'tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD9U6AP/9k'
b'==',
b'dT9YPFSz4dprkH6uiXPEVERGZVIZbGYHzwue21WoLP1RCE2wmu11M8n6ysfROPtI39DCRFQhBBEVGFCT/nfV'
b'pt+fouIENBSXY44mR2en4HGvRR//dlM5OBLz2WuEOf01iKPazGtfacy6lnV0X5JagL4r1mKeyuSXJEV81kxj'
b'Vd3OArpLKt13XM36PcnTd/U6DHOV6Vf982Wc1UjR7kMb5JT+HlWrvz9CCGMTX5mqBYWEr3InCFyrmaZu8DXC'
b'60YUZCPLTHJP0hFQA1ooKQks4f3F39tzVL3dbX3io7XPQiSgHN6nuPCD0PF7dWINep+amk+ODjeQd/o2guqx'
b'O/AngNIxfFWq3915jMQWAXeARUFw7x+9Qx93UWC/sfQ72nTqdQaH5W4vsMUKaocZcAJ7YWudKo5Y15uo3ulP'
b'744Cyo54tvxUSV0zLC90LYCe8fJefREjreO73RlVqoynTyFHuVS7/YMnesO5lCHZJ2NpHuzpGKCU08RgCuSr'
b'K/wh4SLXZ1nhZEYX/xY4cDO7swrA3Y3Qt0gjFzNBfUT9aABQaU+WHY8pBS/oVfJsuj2iod2fsW8UoplImoOk'
b'bosYlMkdZSIfwBQ5kt3On2d+HPUNt7HVZWRECFj0C4IHhZCZIJw0wFmPMOiIHyzittXGb45uJA2Sd1gnRbw0'
b'1XFuoIyvS7z0MtW0QUiD6kaJFBkpTo7hxN/HyN8xQwOkeBcKORdpeSp62iPBuRvel9I2p07it7UyYhzas+Jv'
b'tl6i+hIz6Z5nzQEZ+zPAYxDmoy4h9GQuXUivTzU9I0/Sd4QvM3rfewGeXsNSjWI1CLVZG+4wL1TPCbQGaHEB'
b'NF8zmpTMYV+NvCzv/2DwYuYoiUI='
)
def setUp(self):
self._cipher = MediaCipher() # type: MediaCipher
def test_decrypt_image(self):
media_key, media_plaintext, media_ciphertext = map(base64.b64decode, self.IMAGE)
self.assertEqual(media_plaintext, self._cipher.decrypt_image(media_ciphertext, media_key))
def test_encrypt_image(self):
media_key, media_plaintext, media_ciphertext = map(base64.b64decode, self.IMAGE)
encrypted = self._cipher.encrypt(media_plaintext, media_key, MediaCipher.INFO_IMAGE)
self.assertEqual(media_ciphertext, encrypted)
| 2,766 | Python | .py | 38 | 64.973684 | 98 | 0.829842 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,574 | mediacipher.py | tgalal_yowsup/yowsup/layers/protocol_media/mediacipher.py | from axolotl.kdf.hkdfv3 import HKDFv3
from axolotl.util.byteutil import ByteUtil
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
import hmac
import hashlib
class MediaCipher(object):
INFO_IMAGE = b"WhatsApp Image Keys"
INFO_AUDIO = b"WhatsApp Audio Keys"
INFO_VIDEO = b"WhatsApp Video Keys"
INFO_DOCUM = b"WhatsApp Document Keys"
def encrypt_image(self, plaintext, ref_key):
return self.encrypt(plaintext, ref_key, self.INFO_IMAGE)
def encrypt_audio(self, ciphertext, ref_key):
return self.encrypt(ciphertext, ref_key, self.INFO_AUDIO)
def encrypt_video(self, ciphertext, ref_key):
return self.encrypt(ciphertext, ref_key, self.INFO_VIDEO)
def encrypt_document(self, ciphertext, ref_key):
return self.encrypt(ciphertext, ref_key, self.INFO_DOCUM)
def decrypt_image(self, ciphertext, ref_key):
return self.decrypt(ciphertext, ref_key, self.INFO_IMAGE)
def decrypt_audio(self, ciphertext, ref_key):
return self.decrypt(ciphertext, ref_key, self.INFO_AUDIO)
def decrypt_video(self, ciphertext, ref_key):
return self.decrypt(ciphertext, ref_key, self.INFO_VIDEO)
def decrypt_document(self, ciphertext, ref_key):
return self.decrypt(ciphertext, ref_key, self.INFO_DOCUM)
def encrypt(self, plaintext, ref_key, media_info):
derived = HKDFv3().deriveSecrets(ref_key, media_info, 112)
parts = ByteUtil.split(derived, 16, 32)
iv = parts[0]
key = parts[1]
mac_key = derived[48:80]
cipher_encryptor = Cipher(
algorithms.AES(key), modes.CBC(iv), backend=default_backend()
).encryptor()
if len(plaintext) % 16 != 0:
padder = padding.PKCS7(128).padder()
padded_plaintext = padder.update(plaintext) + padder.finalize()
else:
padded_plaintext = plaintext
ciphertext = cipher_encryptor.update(padded_plaintext) + cipher_encryptor.finalize()
mac = hmac.new(mac_key, digestmod=hashlib.sha256)
mac.update(iv)
mac.update(ciphertext)
return ciphertext + mac.digest()[:10]
def decrypt(self, ciphertext, ref_key, media_info):
derived = HKDFv3().deriveSecrets(ref_key, media_info, 112)
parts = ByteUtil.split(derived, 16, 32)
iv = parts[0]
key = parts[1]
mac_key = derived[48:80]
media_ciphertext = ciphertext[:-10]
mac_value = ciphertext[-10:]
mac = hmac.new(mac_key, digestmod=hashlib.sha256)
mac.update(iv)
mac.update(media_ciphertext)
if mac_value != mac.digest()[:10]:
raise ValueError("Invalid MAC")
cipher_decryptor = Cipher(
algorithms.AES(key), modes.CBC(iv), backend=default_backend()
).decryptor()
decrypted = cipher_decryptor.update(media_ciphertext) + cipher_decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
return unpadder.update(decrypted) + unpadder.finalize()
| 3,153 | Python | .py | 66 | 39.924242 | 92 | 0.677861 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,575 | layer.py | tgalal_yowsup/yowsup/layers/protocol_media/layer.py | from yowsup.layers import YowProtocolLayer
from .protocolentities import ImageDownloadableMediaMessageProtocolEntity
from .protocolentities import AudioDownloadableMediaMessageProtocolEntity
from .protocolentities import VideoDownloadableMediaMessageProtocolEntity
from .protocolentities import DocumentDownloadableMediaMessageProtocolEntity
from .protocolentities import StickerDownloadableMediaMessageProtocolEntity
from .protocolentities import LocationMediaMessageProtocolEntity
from .protocolentities import ContactMediaMessageProtocolEntity
from .protocolentities import ResultRequestUploadIqProtocolEntity
from .protocolentities import MediaMessageProtocolEntity
from .protocolentities import ExtendedTextMediaMessageProtocolEntity
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity, ErrorIqProtocolEntity
import logging
logger = logging.getLogger(__name__)
class YowMediaProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"message": (self.recvMessageStanza, self.sendMessageEntity),
"iq": (self.recvIq, self.sendIq)
}
super(YowMediaProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Media Layer"
def sendMessageEntity(self, entity):
if entity.getType() == "media":
self.entityToLower(entity)
def recvMessageStanza(self, node):
if node.getAttributeValue("type") == "media":
mediaNode = node.getChild("proto")
if mediaNode.getAttributeValue("mediatype") == "image":
entity = ImageDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(entity)
elif mediaNode.getAttributeValue("mediatype") == "sticker":
entity = StickerDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(entity)
elif mediaNode.getAttributeValue("mediatype") in ("audio", "ptt"):
entity = AudioDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(entity)
elif mediaNode.getAttributeValue("mediatype") in ("video", "gif"):
entity = VideoDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(entity)
elif mediaNode.getAttributeValue("mediatype") == "location":
entity = LocationMediaMessageProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(entity)
elif mediaNode.getAttributeValue("mediatype") == "contact":
entity = ContactMediaMessageProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(entity)
elif mediaNode.getAttributeValue("mediatype") == "document":
entity = DocumentDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(entity)
elif mediaNode.getAttributeValue("mediatype") == "url":
entity = ExtendedTextMediaMessageProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(entity)
else:
logger.warn("Unsupported mediatype: %s, will send receipts" % mediaNode.getAttributeValue("mediatype"))
self.toLower(MediaMessageProtocolEntity.fromProtocolTreeNode(node).ack(True).toProtocolTreeNode())
def sendIq(self, entity):
"""
:type entity: IqProtocolEntity
"""
if entity.getType() == IqProtocolEntity.TYPE_SET and entity.getXmlns() == "w:m":
#media upload!
self._sendIq(entity, self.onRequestUploadSuccess, self.onRequestUploadError)
def recvIq(self, node):
"""
:type node: ProtocolTreeNode
"""
def onRequestUploadSuccess(self, resultNode, requestUploadEntity):
self.toUpper(ResultRequestUploadIqProtocolEntity.fromProtocolTreeNode(resultNode))
def onRequestUploadError(self, errorNode, requestUploadEntity):
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(errorNode))
| 4,067 | Python | .py | 71 | 47.408451 | 119 | 0.722529 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,576 | mediauploader.py | tgalal_yowsup/yowsup/layers/protocol_media/mediauploader.py | from yowsup.common.http.warequest import WARequest
from yowsup.common.http.waresponseparser import JSONResponseParser
import socket
import ssl
import os
import hashlib
import sys
from time import sleep
import threading
import logging
from yowsup.common.tools import MimeTools
logger = logging.getLogger(__name__)
class MediaUploader(WARequest, threading.Thread):
def __init__(self, jid, accountJid, sourcePath, uploadUrl, resumeOffset=0, successClbk=None, errorClbk=None, progressCallback=None, asynchronous=True):
WARequest.__init__(self)
self.asynchronous = asynchronous
self.jid = jid
self.accountJid = accountJid
self.sourcePath = sourcePath
self.uploadUrl = uploadUrl
self.resumeOffset = resumeOffset
self.successCallback = successClbk
self.errorCallback = errorClbk
self.progressCallback = progressCallback
self.pvars = ["name", "type", "size", "url", "error",
"mimetype", "filehash", "width", "height"]
self.setParser(JSONResponseParser())
self.sock = socket.socket()
def start(self):
if self.asynchronous:
threading.Thread.__init__(self)
super(MediaUploader, self).start()
else:
self.run()
def run(self):
sourcePath = self.sourcePath
uploadUrl = self.uploadUrl
_host = uploadUrl.replace("https://", "")
self.url = _host[:_host.index('/')]
try:
filename = os.path.basename(sourcePath)
filetype = MimeTools.getMIME(filename)
filesize = os.path.getsize(sourcePath)
self.sock.connect((self.url, self.port))
ssl_sock = ssl.wrap_socket(self.sock)
m = hashlib.md5()
m.update(filename.encode())
crypto = m.hexdigest() + os.path.splitext(filename)[1]
boundary = "zzXXzzYYzzXXzzQQ" # "-------" + m.hexdigest() #"zzXXzzYYzzXXzzQQ"
contentLength = 0
hBAOS = "--" + boundary + "\r\n"
hBAOS += "Content-Disposition: form-data; name=\"to\"\r\n\r\n"
hBAOS += self.jid + "\r\n"
hBAOS += "--" + boundary + "\r\n"
hBAOS += "Content-Disposition: form-data; name=\"from\"\r\n\r\n"
hBAOS += self.accountJid.replace("@whatsapp.net", "") + "\r\n"
hBAOS += "--" + boundary + "\r\n"
hBAOS += "Content-Disposition: form-data; name=\"file\"; filename=\"" + crypto + "\"\r\n"
hBAOS += "Content-Type: " + filetype + "\r\n\r\n"
fBAOS = "\r\n--" + boundary + "--\r\n"
contentLength += len(hBAOS)
contentLength += len(fBAOS)
contentLength += filesize
POST = "POST %s\r\n" % uploadUrl
POST += "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n"
POST += "Host: %s\r\n" % self.url
POST += "User-Agent: %s\r\n" % self.getUserAgent()
POST += "Content-Length: " + str(contentLength) + "\r\n\r\n"
ssl_sock.write(bytearray(POST.encode()))
ssl_sock.write(bytearray(hBAOS.encode()))
totalsent = 0
buf = 1024
f = open(sourcePath, 'rb')
stream = f.read()
f.close()
status = 0
lastEmit = 0
while totalsent < int(filesize):
ssl_sock.write(stream[:buf])
status = totalsent * 100 / filesize
if lastEmit != status and status != 100 and filesize > 12288:
if self.progressCallback:
self.progressCallback(self.sourcePath, self.jid, uploadUrl, int(status))
lastEmit = status
stream = stream[buf:]
totalsent = totalsent + buf
ssl_sock.write(bytearray(fBAOS.encode()))
sleep(1)
data = ssl_sock.recv(8192)
data += ssl_sock.recv(8192)
data += ssl_sock.recv(8192)
data += ssl_sock.recv(8192)
data += ssl_sock.recv(8192)
data += ssl_sock.recv(8192)
data += ssl_sock.recv(8192)
if self.progressCallback:
self.progressCallback(self.sourcePath, self.jid, uploadUrl, 100)
lines = data.decode().splitlines()
result = None
for l in lines:
if l.startswith("{"):
result = self.parser.parse(l, self.pvars)
break
if not result:
raise Exception("json data not found")
if result["url"] is not None:
if self.successCallback:
self.successCallback(sourcePath, self.jid, result["url"])
else:
logger.exception("uploadUrl: %s, result of uploading media has no url" % uploadUrl)
if self.errorCallback:
self.errorCallback(sourcePath, self.jid, uploadUrl)
except:
logger.exception("Error occured at transfer %s" % sys.exc_info()[1])
if self.errorCallback:
self.errorCallback(sourcePath, self.jid, uploadUrl)
| 5,226 | Python | .py | 116 | 33.060345 | 155 | 0.56234 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,577 | iq_requestupload.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/iq_requestupload.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
import hashlib
import base64
import os
from yowsup.common.tools import WATools
class RequestUploadIqProtocolEntity(IqProtocolEntity):
'''
<iq to="s.whatsapp.net" type="set" xmlns="w:m">
<media hash="{{b64_hash}}" type="{{type}}" size="{{size_bytes}}" orighash={{b64_orighash?}}></media>
</iq>
'''
MEDIA_TYPE_IMAGE = "image"
MEDIA_TYPE_VIDEO = "video"
MEDIA_TYPE_AUDIO = "audio"
MEDIA_TYPE_DOCUM = "document"
XMLNS = "w:m"
TYPES_MEDIA = (MEDIA_TYPE_AUDIO, MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO, MEDIA_TYPE_DOCUM)
def __init__(self, mediaType, b64Hash = None, size = None, origHash = None, filePath = None ):
super(RequestUploadIqProtocolEntity, self).__init__("w:m", _type = "set", to = YowConstants.WHATSAPP_SERVER)
assert (b64Hash and size) or filePath, "Either specify hash and size, or specify filepath and let me generate the rest"
if filePath:
assert os.path.exists(filePath), "Either specified path does not exist, or yowsup doesn't have permission to read: %s" % filePath
b64Hash = self.__class__.getFileHashForUpload(filePath)
size = os.path.getsize(filePath)
self.setRequestArguments(mediaType, b64Hash, size, origHash)
def setRequestArguments(self, mediaType, b64Hash, size, origHash = None):
assert mediaType in self.__class__.TYPES_MEDIA, "Expected media type to be in %s, got %s" % (self.__class__.TYPES_MEDIA, mediaType)
self.mediaType = mediaType
self.b64Hash = b64Hash
self.size = int(size)
self.origHash = origHash
@staticmethod
def getFileHashForUpload(filePath):
return WATools.getFileHashForUpload(filePath)
def __str__(self):
out = super(RequestUploadIqProtocolEntity, self).__str__()
out += "Media Type: %s\n" % self.mediaType
out += "B64Hash: %s\n" % self.b64Hash
out += "Size: %s\n" % self.size
if self.origHash:
out += "OrigHash: %s\n" % self.origHash
return out
def toProtocolTreeNode(self):
node = super(RequestUploadIqProtocolEntity, self).toProtocolTreeNode()
attribs = {
"hash": self.b64Hash,
"type": self.mediaType,
"size": str(self.size)
}
if self.origHash:
attribs["orighash"] = self.origHash
mediaNode = ProtocolTreeNode("encr_media", attribs)
node.addChild(mediaNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
assert node.getAttributeValue("type") == "set", "Expected set as iq type in request upload, got %s" % node.getAttributeValue("type")
entity = IqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = RequestUploadIqProtocolEntity
mediaNode = node.getChild("encr_media")
entity.setRequestArguments(
mediaNode.getAttributeValue("type"),
mediaNode.getAttributeValue("hash"),
mediaNode.getAttributeValue("size"),
mediaNode.getAttributeValue("orighash")
)
return entity
| 3,260 | Python | .py | 69 | 39.333333 | 141 | 0.66331 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,578 | message_media_downloadable_image.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media_downloadable_image.py | from .message_media_downloadable import DownloadableMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_image import ImageAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class ImageDownloadableMediaMessageProtocolEntity(DownloadableMediaMessageProtocolEntity):
def __init__(self, image_attrs, message_meta_attrs):
# type: (ImageAttributes, MessageMetaAttributes) -> None
super(ImageDownloadableMediaMessageProtocolEntity, self).__init__(
"image", MessageAttributes(image=image_attrs), message_meta_attrs
)
@property
def media_specific_attributes(self):
return self.message_attributes.image
@property
def downloadablemedia_specific_attributes(self):
return self.message_attributes.image.downloadablemedia_attributes
@property
def width(self):
return self.media_specific_attributes.width
@width.setter
def width(self, value):
self.media_specific_attributes.width = value
@property
def height(self):
return self.media_specific_attributes.height
@height.setter
def height(self, value):
self.media_specific_attributes.height = value
@property
def jpeg_thumbnail(self):
return self.media_specific_attributes.jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self.media_specific_attributes.jpeg_thumbnail = value if value is not None else b""
@property
def caption(self):
return self.media_specific_attributes.caption
@caption.setter
def caption(self, value):
self.media_specific_attributes.caption = value if value is not None else ""
| 1,903 | Python | .py | 40 | 41.275 | 117 | 0.763371 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,579 | test_message_media_downloadable_audio.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/test_message_media_downloadable_audio.py | from yowsup.layers.protocol_media.protocolentities.message_media_downloadable_audio import AudioDownloadableMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
from .test_message_media import MediaMessageProtocolEntityTest
class AudioDownloadableMediaMessageProtocolEntityTest(MediaMessageProtocolEntityTest):
def setUp(self):
super(AudioDownloadableMediaMessageProtocolEntityTest, self).setUp()
self.ProtocolEntity = AudioDownloadableMediaMessageProtocolEntity
proto_node = self.node.getChild("proto")
m = Message()
media_message = Message.AudioMessage()
media_message.url = "url"
media_message.mimetype = "audio/ogg"
media_message.file_sha256 = b"SHA256"
media_message.file_length = 123
media_message.media_key = b"MEDIA_KEY"
media_message.seconds = 24
media_message.ptt = True
m.audio_message.MergeFrom(media_message)
proto_node.setData(m.SerializeToString())
| 1,022 | Python | .py | 19 | 46.578947 | 134 | 0.756244 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,580 | test_message_media_downloadable_image.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/test_message_media_downloadable_image.py | from yowsup.layers.protocol_media.protocolentities.message_media_downloadable_image \
import ImageDownloadableMediaMessageProtocolEntity
from .test_message_media import MediaMessageProtocolEntityTest
from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
class ImageDownloadableMediaMessageProtocolEntityTest(MediaMessageProtocolEntityTest):
def setUp(self):
super(ImageDownloadableMediaMessageProtocolEntityTest, self).setUp()
self.ProtocolEntity = ImageDownloadableMediaMessageProtocolEntity
proto_node = self.node.getChild("proto")
m = Message()
media_message = Message.ImageMessage()
media_message.url = "url"
media_message.mimetype = "image/jpeg"
media_message.caption = "caption"
media_message.file_sha256 = b"SHA256"
media_message.file_length = 123
media_message.height = 20
media_message.width = 20
media_message.media_key = b"MEDIA_KEY"
media_message.jpeg_thumbnail = b"THUMBNAIL"
m.image_message.MergeFrom(media_message)
proto_node.setData(m.SerializeToString())
| 1,122 | Python | .py | 22 | 43.727273 | 86 | 0.744991 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,581 | test_message_media_extendedtext.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/test_message_media_extendedtext.py | from yowsup.layers.protocol_media.protocolentities.test_message_media import MediaMessageProtocolEntityTest
from yowsup.layers.protocol_media.protocolentities import ExtendedTextMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
class ExtendedTextMediaMessageProtocolEntityTest(MediaMessageProtocolEntityTest):
def setUp(self):
super(ExtendedTextMediaMessageProtocolEntityTest, self).setUp()
self.ProtocolEntity = ExtendedTextMediaMessageProtocolEntity
m = Message()
media_message = Message.ExtendedTextMessage()
media_message.canonical_url = "url"
media_message.text = "text"
media_message.matched_text = "matched_text"
media_message.description = "desc"
media_message.title = "title"
media_message.jpeg_thumbnail = b"thumb"
m.extended_text_message.MergeFrom(media_message)
proto_node = self.node.getChild("proto")
proto_node["mediatype"] = "url"
proto_node.setData(m.SerializeToString())
self._entity = ExtendedTextMediaMessageProtocolEntity\
.fromProtocolTreeNode(self.node) # type: ExtendedTextMediaMessageProtocolEntity
def test_properties(self):
self.assertEqual("url", self._entity.canonical_url)
self.assertEqual("text", self._entity.text)
self.assertEqual("matched_text", self._entity.matched_text)
self.assertEqual("desc", self._entity.description)
self.assertEqual("title", self._entity.title)
self.assertEqual(b"thumb", self._entity.jpeg_thumbnail)
| 1,598 | Python | .py | 28 | 49.142857 | 107 | 0.737852 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,582 | message_media_downloadable_sticker.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media_downloadable_sticker.py | from .message_media_downloadable import DownloadableMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_sticker import StickerAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class StickerDownloadableMediaMessageProtocolEntity(DownloadableMediaMessageProtocolEntity):
def __init__(self, sticker_attrs, message_meta_attrs):
# type: (StickerAttributes, MessageMetaAttributes) -> None
super(StickerDownloadableMediaMessageProtocolEntity, self).__init__(
"sticker", MessageAttributes(sticker=sticker_attrs), message_meta_attrs
)
@property
def media_specific_attributes(self):
return self.message_attributes.sticker
@property
def downloadablemedia_specific_attributes(self):
return self.message_attributes.sticker.downloadablemedia_attributes
@property
def width(self):
return self.media_specific_attributes.width
@width.setter
def width(self, value):
self.media_specific_attributes.width = value
@property
def height(self):
return self.media_specific_attributes.height
@height.setter
def height(self, value):
self.media_specific_attributes.height = value
@property
def png_thumbnail(self):
return self.media_specific_attributes.png_thumbnail
@png_thumbnail.setter
def png_thumbnail(self, value):
self.media_specific_attributes.png_thumbnail = value
| 1,664 | Python | .py | 34 | 42.705882 | 117 | 0.775309 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,583 | test_message_media_location.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/test_message_media_location.py | from yowsup.layers.protocol_media.protocolentities.test_message_media import MediaMessageProtocolEntityTest
from yowsup.layers.protocol_media.protocolentities import LocationMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
class LocationMediaMessageProtocolEntityTest(MediaMessageProtocolEntityTest):
def setUp(self):
super(LocationMediaMessageProtocolEntityTest, self).setUp()
self.ProtocolEntity = LocationMediaMessageProtocolEntity
m = Message()
location_message = Message.LocationMessage()
location_message.degrees_latitude = 30.089037
location_message.degrees_longitude = 31.319488
location_message.name = "kaos"
location_message.url = "kaos_url"
m.location_message.MergeFrom(location_message)
proto_node = self.node.getChild("proto")
proto_node["mediatype"] = "location"
proto_node.setData(m.SerializeToString()) | 967 | Python | .py | 17 | 49.764706 | 107 | 0.768499 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,584 | 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 | .py | 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,585 | iq_requestupload_result.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/iq_requestupload_result.py | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class ResultRequestUploadIqProtocolEntity(ResultIqProtocolEntity):
def __init__(self, _id, url, ip = None, resumeOffset = 0, duplicate = False):
super(ResultRequestUploadIqProtocolEntity, self).__init__(_id = _id, _from = YowConstants.WHATSAPP_SERVER)
self.setUploadProps(url, ip, resumeOffset, duplicate)
def setUploadProps(self, url ,ip = None, resumeOffset = 0, duplicate = False):
self.url = url
self.ip = ip
self.resumeOffset = resumeOffset or 0
self.duplicate = duplicate
def isDuplicate(self):
return self.duplicate
def getUrl(self):
return self.url
def getResumeOffset(self):
return self.resumeOffset
def getIp(self):
return self.ip
def __str__(self):
out = super(ResultRequestUploadIqProtocolEntity, self).__str__()
out += "URL: %s\n" % self.url
if self.ip:
out += "IP: %s\n" % self.ip
return out
def toProtocolTreeNode(self):
node = super(ResultRequestUploadIqProtocolEntity, self).toProtocolTreeNode()
if not self.isDuplicate():
mediaNode = ProtocolTreeNode("encr_media", {"url": self.url})
if self.ip:
mediaNode["ip"] = self.ip
if self.resumeOffset:
mediaNode["resume"] = str(self.resumeOffset)
else:
mediaNode = ProtocolTreeNode("duplicate", {"url": self.url})
node.addChild(mediaNode)
return node
@staticmethod
def fromProtocolTreeNode(node):
entity= ResultIqProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = ResultRequestUploadIqProtocolEntity
mediaNode = node.getChild("encr_media")
if mediaNode:
entity.setUploadProps(mediaNode["url"], mediaNode["ip"], mediaNode["resume"])
else:
duplicateNode = node.getChild("duplicate")
if duplicateNode:
entity.setUploadProps(duplicateNode["url"], duplicateNode["ip"], duplicate = True)
return entity
| 2,222 | Python | .py | 50 | 35.54 | 114 | 0.657103 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,586 | message_media_downloadable_audio.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media_downloadable_audio.py | from .message_media_downloadable import DownloadableMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_audio import AudioAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class AudioDownloadableMediaMessageProtocolEntity(DownloadableMediaMessageProtocolEntity):
def __init__(self, audio_attrs, message_meta_attrs):
# type: (AudioAttributes, MessageMetaAttributes) -> None
super(AudioDownloadableMediaMessageProtocolEntity, self).__init__(
"audio", MessageAttributes(audio=audio_attrs), message_meta_attrs
)
@property
def media_specific_attributes(self):
return self.message_attributes.audio
@property
def downloadablemedia_specific_attributes(self):
return self.message_attributes.audio.downloadablemedia_attributes
@property
def seconds(self):
return self.media_specific_attributes.seconds
@seconds.setter
def seconds(self, value):
"""
:type value: int
"""
self.media_specific_attributes.seconds = value
@property
def ptt(self):
return self.media_specific_attributes.ptt
@ptt.setter
def ptt(self, value):
"""
:type value: bool
"""
self.media_specific_attributes.ptt = value
@property
def streaming_sidecar(self):
return self.media_specific_attributes.streaming_sidecar
@streaming_sidecar.setter
def streaming_sidecar(self, value):
self.media_specific_attributes.streaming_sidecar = value
| 1,755 | Python | .py | 40 | 37.225 | 117 | 0.747214 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,587 | message_media_location.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media_location.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_location import LocationAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class LocationMediaMessageProtocolEntity(MediaMessageProtocolEntity):
def __init__(self, location_attrs, message_meta_attrs):
# type: (LocationAttributes, MessageMetaAttributes) -> None
super(LocationMediaMessageProtocolEntity, self).__init__(
"location", MessageAttributes(location=location_attrs), message_meta_attrs
)
@property
def media_specific_attributes(self):
return self.message_attributes.contact
@property
def degrees_latitude(self):
return self.media_specific_attributes.degrees_latitude
@degrees_latitude.setter
def degrees_latitude(self, value):
self.media_specific_attributes.degrees_latitude = value
@property
def degrees_longitude(self):
return self.media_specific_attributes.degrees_longitude
@degrees_longitude.setter
def degrees_longitude(self, value):
self.media_specific_attributes.degrees_longitude = value
@property
def name(self):
return self.media_specific_attributes.name
@name.setter
def name(self, value):
self.media_specific_attributes.name = value
@property
def address(self):
return self.proto.addrees
@address.setter
def address(self, value):
self.media_specific_attributes.address = value
@property
def url(self):
return self.media_specific_attributes.url
@url.setter
def url(self, value):
self.media_specific_attributes.url = value
@property
def duration(self):
return self.media_specific_attributes.duration
@duration.setter
def duration(self, value):
self.media_specific_attributes.duration = value
@property
def accuracy_in_meters(self):
return self.media_specific_attributes.accuracy_in_meters
@accuracy_in_meters.setter
def accuracy_in_meters(self, value):
self.media_specific_attributes.accuracy_in_meters = value
@property
def speed_in_mps(self):
return self.media_specific_attributes.speed_in_mps
@speed_in_mps.setter
def speed_in_mps(self, value):
self.media_specific_attributes.speed_in_mps = value
@property
def degrees_clockwise_from_magnetic_north(self):
return self.media_specific_attributes.degrees_clockwise_from_magnetic_north
@degrees_clockwise_from_magnetic_north.setter
def degrees_clockwise_from_magnetic_north(self, value):
self.media_specific_attributes.degrees_clockwise_from_magnetic_north = value
@property
def axolotl_sender_key_distribution_message(self):
return self.media_specific_attributes.axolotl_sender_key_distribution_message
@axolotl_sender_key_distribution_message.setter
def axolotl_sender_key_distribution_message(self, value):
self.media_specific_attributes.axolotl_sender_key_distribution_message = value
@property
def jpeg_thumbnail(self):
return self.media_specific_attributes.jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self.media_specific_attributes.jpeg_thumbnail = value
| 3,506 | Python | .py | 79 | 37.898734 | 117 | 0.748089 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,588 | message_media_downloadable_video.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media_downloadable_video.py | from .message_media_downloadable import DownloadableMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_video import VideoAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class VideoDownloadableMediaMessageProtocolEntity(DownloadableMediaMessageProtocolEntity):
def __init__(self, video_attrs, message_meta_attrs):
# type: (VideoAttributes, MessageMetaAttributes) -> None
super(VideoDownloadableMediaMessageProtocolEntity, self).__init__(
"video", MessageAttributes(video=video_attrs), message_meta_attrs
)
@property
def media_specific_attributes(self):
return self.message_attributes.video
@property
def downloadablemedia_specific_attributes(self):
return self.message_attributes.video.downloadablemedia_attributes
@property
def width(self):
return self.media_specific_attributes.width
@width.setter
def width(self, value):
self.media_specific_attributes.width = value
@property
def height(self):
return self.media_specific_attributes.height
@height.setter
def height(self, value):
self.media_specific_attributes.height = value
@property
def seconds(self):
return self.media_specific_attributes.seconds
@seconds.setter
def seconds(self, value):
self.media_specific_attributes.seconds = value
@property
def gif_playback(self):
return self.media_specific_attributes.gif_playback
@gif_playback.setter
def gif_playback(self, value):
self.media_specific_attributes.gif_playback = value
@property
def jpeg_thumbnail(self):
return self.media_specific_attributes.jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self.media_specific_attributes.jpeg_thumbnail = value
@property
def caption(self):
return self.media_specific_attributes.caption
@caption.setter
def caption(self, value):
self.media_specific_attributes.caption = value
@property
def gif_attribution(self):
return self.proto.gif_attribution
@gif_attribution.setter
def gif_attribution(self, value):
self.media_specific_attributes.gif_attributions = value
@property
def streaming_sidecar(self):
return self.media_specific_attributes.streaming_sidecar
@streaming_sidecar.setter
def streaming_sidecar(self, value):
self.media_specific_attributes.streaming_sidecar = value
| 2,732 | Python | .py | 64 | 36.25 | 117 | 0.750378 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,589 | 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 | .py | 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,590 | test_message_media_downloadable_video.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/test_message_media_downloadable_video.py | from yowsup.layers.protocol_media.protocolentities.message_media_downloadable_video \
import VideoDownloadableMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
from .test_message_media import MediaMessageProtocolEntityTest
class VideoDownloadableMediaMessageProtocolEntityTest(MediaMessageProtocolEntityTest):
def setUp(self):
super(VideoDownloadableMediaMessageProtocolEntityTest, self).setUp()
self.ProtocolEntity = VideoDownloadableMediaMessageProtocolEntity
proto_node = self.node.getChild("proto")
m = Message()
media_message = Message.VideoMessage()
media_message.url = "url"
media_message.mimetype = "video/mp4"
media_message.caption = "caption"
media_message.file_sha256 = b"shaval"
media_message.file_length = 4
media_message.width = 1
media_message.height = 2
media_message.seconds = 3
media_message.media_key = b"MEDIA_KEY"
media_message.jpeg_thumbnail = b"THUMBNAIL"
media_message.gif_attribution = 0
media_message.gif_playback = False
media_message.streaming_sidecar = b''
m.video_message.MergeFrom(media_message)
proto_node.setData(m.SerializeToString())
| 1,282 | Python | .py | 26 | 41.769231 | 86 | 0.73126 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,591 | message_media_downloadable_document.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media_downloadable_document.py | from .message_media_downloadable import DownloadableMediaMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_document import DocumentAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class DocumentDownloadableMediaMessageProtocolEntity(DownloadableMediaMessageProtocolEntity):
def __init__(self, document_attrs, message_meta_attrs):
"""
:type document_attrs: DocumentAttributes
:type message_meta_attrs: MessageMetaAttributes
"""
super(DocumentDownloadableMediaMessageProtocolEntity, self).__init__(
"document", MessageAttributes(document=document_attrs), message_meta_attrs
)
@property
def media_specific_attributes(self):
return self.message_attributes.document
@property
def downloadablemedia_specific_attributes(self):
return self.message_attributes.document.downloadablemedia_attributes
@property
def file_name(self):
return self.media_specific_attributes.file_name
@file_name.setter
def file_name(self, value):
self.media_specific_attributes.file_name = value
@property
def file_length(self):
return self.media_specific_attributes.file_length
@file_length.setter
def file_length(self, value):
self.media_specific_attributes.file_length = value
@property
def title(self):
return self.media_specific_attributes.title
@title.setter
def title(self, value):
self.media_specific_attributes.title = value
@property
def page_count(self):
return self.media_specific_attributes.page_count
@page_count.setter
def page_count(self, value):
self.media_specific_attributes.page_count = value
@property
def jpeg_thumbnail(self):
return self.media_specific_attributes.image_message.jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self.media_specific_attributes.image_message.jpeg_thumbnail = value
| 2,214 | Python | .py | 49 | 38.673469 | 117 | 0.755927 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,592 | __init__.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/__init__.py | from .message_media import MediaMessageProtocolEntity
from .message_media_downloadable import DownloadableMediaMessageProtocolEntity
from .message_media_downloadable_image import ImageDownloadableMediaMessageProtocolEntity
from .message_media_downloadable_audio import AudioDownloadableMediaMessageProtocolEntity
from .message_media_downloadable_video import VideoDownloadableMediaMessageProtocolEntity
from .message_media_downloadable_document import DocumentDownloadableMediaMessageProtocolEntity
from .message_media_downloadable_sticker import StickerDownloadableMediaMessageProtocolEntity
from .message_media_location import LocationMediaMessageProtocolEntity
from .message_media_contact import ContactMediaMessageProtocolEntity
from .message_media_extendedtext import ExtendedTextMediaMessageProtocolEntity
from .iq_requestupload import RequestUploadIqProtocolEntity
from .iq_requestupload_result import ResultRequestUploadIqProtocolEntity
| 945 | Python | .py | 12 | 77.75 | 95 | 0.919614 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,593 | test_iq_requestupload_result.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/test_iq_requestupload_result.py | from yowsup.layers.protocol_iq.protocolentities.test_iq_result import ResultIqProtocolEntityTest
from yowsup.layers.protocol_media.protocolentities import ResultRequestUploadIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class ResultRequestUploadIqProtocolEntityTest(ResultIqProtocolEntityTest):
def setUp(self):
super(ResultRequestUploadIqProtocolEntityTest, self).setUp()
mediaNode = ProtocolTreeNode("encr_media", {"url": "url", "ip": "1.2.3.4"})
self.ProtocolEntity = ResultRequestUploadIqProtocolEntity
self.node.addChild(mediaNode) | 587 | Python | .py | 9 | 60.333333 | 96 | 0.811744 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,594 | test_iq_requestupload.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/test_iq_requestupload.py | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
from yowsup.layers.protocol_media.protocolentities import RequestUploadIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class RequestUploadIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self):
super(RequestUploadIqProtocolEntityTest, self).setUp()
mediaNode = ProtocolTreeNode("encr_media", {"hash": "hash", "size": "1234", "orighash": "orighash", "type": "image"})
self.ProtocolEntity = RequestUploadIqProtocolEntity
self.node.setAttribute("type", "set")
self.node.addChild(mediaNode) | 632 | Python | .py | 10 | 57.9 | 125 | 0.776886 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,595 | message_media_downloadable.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media_downloadable.py | from .message_media import MediaMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class DownloadableMediaMessageProtocolEntity(MediaMessageProtocolEntity):
def __init__(self, media_type, message_attrs, message_meta_attrs):
# type: (str, MessageAttributes, MessageMetaAttributes) -> None
super(DownloadableMediaMessageProtocolEntity, self).__init__(
media_type, message_attrs, message_meta_attrs
)
@property
def downloadablemedia_specific_attributes(self):
raise NotImplementedError()
@property
def url(self):
return self.downloadablemedia_specific_attributes.url
@url.setter
def url(self, value):
self.downloadablemedia_specific_attributes.url = value
@property
def mimetype(self):
return self.downloadablemedia_specific_attributes.mimetype
@mimetype.setter
def mimetype(self, value):
self.downloadablemedia_specific_attributes.mimetype = value
@property
def file_sha256(self):
return self.downloadablemedia_specific_attributes.file_sha256
@file_sha256.setter
def file_sha256(self, value):
self.downloadablemedia_specific_attributes.file_sha256 = value
@property
def file_length(self):
return self.downloadablemedia_specific_attributes.file_length
@file_length.setter
def file_length(self, value):
self.downloadablemedia_specific_attributes.file_length = value
@property
def media_key(self):
return self.downloadablemedia_specific_attributes.media_key
@media_key.setter
def media_key(self, value):
self.downloadablemedia_specific_attributes.media_key = value
| 1,887 | Python | .py | 42 | 38.47619 | 117 | 0.756004 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,596 | message_media_extendedtext.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media_extendedtext.py | from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_extendedtext import ExtendedTextAttributes
from .message_media import MediaMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
class ExtendedTextMediaMessageProtocolEntity(MediaMessageProtocolEntity):
def __init__(self, extended_text_attrs, message_meta_attrs):
# type: (ExtendedTextAttributes, MessageMetaAttributes) -> None
super(ExtendedTextMediaMessageProtocolEntity, self).__init__(
"url", MessageAttributes(extended_text=extended_text_attrs), message_meta_attrs
)
@property
def media_specific_attributes(self):
return self.message_attributes.extended_text
@property
def text(self):
return self.media_specific_attributes.text
@text.setter
def text(self, value):
self.media_specific_attributes.text = value
@property
def matched_text(self):
return self.media_specific_attributes.matched_text
@matched_text.setter
def matched_text(self, value):
self.media_specific_attributes.matched_text = value
@property
def canonical_url(self):
return self.media_specific_attributes.canonical_url
@canonical_url.setter
def canonical_url(self, value):
self.media_specific_attributes.canonical_url = value
@property
def description(self):
return self.media_specific_attributes.description
@description.setter
def description(self, value):
self.media_specific_attributes.description = value
@property
def title(self):
return self.media_specific_attributes.title
@title.setter
def title(self, value):
self.media_specific_attributes.title = value
@property
def jpeg_thumbnail(self):
return self.media_specific_attributes.jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self.media_specific_attributes.jpeg_thumbnail = value
| 2,169 | Python | .py | 49 | 37.897959 | 118 | 0.752969 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,597 | test_message_media.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/test_message_media.py | from yowsup.layers.protocol_media.protocolentities.message_media import MediaMessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.test_message import MessageProtocolEntityTest
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_messages.proto.e2e_pb2 import Message
class MediaMessageProtocolEntityTest(MessageProtocolEntityTest):
def setUp(self):
super(MediaMessageProtocolEntityTest, self).setUp()
self.ProtocolEntity = MediaMessageProtocolEntity
proto_node = ProtocolTreeNode("proto", {"mediatype": "image"}, None, Message().SerializeToString())
self.node.addChild(proto_node)
| 661 | Python | .py | 10 | 61.3 | 107 | 0.818182 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,598 | message_media.py | tgalal_yowsup/yowsup/layers/protocol_media/protocolentities/message_media.py | from yowsup.layers.protocol_messages.protocolentities.protomessage import ProtomessageProtocolEntity
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes
import logging
logger = logging.getLogger(__name__)
class MediaMessageProtocolEntity(ProtomessageProtocolEntity):
TYPE_MEDIA_IMAGE = "image"
TYPE_MEDIA_VIDEO = "video"
TYPE_MEDIA_AUDIO = "audio"
TYPE_MEDIA_CONTACT = "contact"
TYPE_MEDIA_LOCATION = "location"
TYPE_MEDIA_DOCUMENT = "document"
TYPE_MEDIA_GIF = "gif"
TYPE_MEDIA_PTT = "ptt"
TYPE_MEDIA_URL = "url"
TYPE_MEDIA_STICKER = "sticker"
TYPES_MEDIA = (
TYPE_MEDIA_IMAGE, TYPE_MEDIA_AUDIO, TYPE_MEDIA_VIDEO,
TYPE_MEDIA_CONTACT, TYPE_MEDIA_LOCATION, TYPE_MEDIA_DOCUMENT,
TYPE_MEDIA_GIF, TYPE_MEDIA_PTT, TYPE_MEDIA_URL, TYPE_MEDIA_STICKER
)
def __init__(self, media_type, message_attrs, message_meta_attrs):
"""
:type media_type: str
:type message_attrs: MessageAttributes
:type message_meta_attrs: MessageMetaAttributes
"""
super(MediaMessageProtocolEntity, self).__init__("media", message_attrs, message_meta_attrs)
self.media_type = media_type # type: str
def __str__(self):
out = super(MediaMessageProtocolEntity, self).__str__()
out += "\nmediatype=%s" % self.media_type
return out
@property
def media_type(self):
return self._media_type
@media_type.setter
def media_type(self, value):
if value not in MediaMessageProtocolEntity.TYPES_MEDIA:
logger.warn("media type: '%s' is not supported" % value)
self._media_type = value
def toProtocolTreeNode(self):
node = super(MediaMessageProtocolEntity, self).toProtocolTreeNode()
protoNode = node.getChild("proto")
protoNode["mediatype"] = self.media_type
return node
@classmethod
def fromProtocolTreeNode(cls, node):
entity = ProtomessageProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = cls
entity.media_type = node.getChild("proto")["mediatype"]
return entity
| 2,300 | Python | .py | 52 | 37.5 | 117 | 0.700179 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |
21,599 | interface.py | tgalal_yowsup/yowsup/layers/interface/interface.py | from yowsup.layers import YowLayer, YowLayerEvent
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.protocol_media.protocolentities.iq_requestupload import RequestUploadIqProtocolEntity
from yowsup.layers.protocol_media.mediauploader import MediaUploader
from yowsup.layers.network.layer import YowNetworkLayer
from yowsup.layers.auth.protocolentities import StreamErrorProtocolEntity
from yowsup.layers import EventCallback
import inspect
import logging
logger = logging.getLogger(__name__)
class ProtocolEntityCallback(object):
def __init__(self, entityType):
self.entityType = entityType
def __call__(self, fn):
fn.entity_callback = self.entityType
return fn
class YowInterfaceLayer(YowLayer):
PROP_RECONNECT_ON_STREAM_ERR = "org.openwhatsapp.yowsup.prop.interface.reconnect_on_stream_error"
def __init__(self):
super(YowInterfaceLayer, self).__init__()
self.reconnect = False
self.entity_callbacks = {}
self.iqRegistry = {}
# self.receiptsRegistry = {}
members = inspect.getmembers(self, predicate=inspect.ismethod)
for m in members:
if hasattr(m[1], "entity_callback"):
fname = m[0]
fn = m[1]
self.entity_callbacks[fn.entity_callback] = getattr(self, fname)
def _sendIq(self, iqEntity, onSuccess=None, onError=None):
assert iqEntity.getTag() == "iq", "Expected *IqProtocolEntity in _sendIq, got %s" % iqEntity.getTag()
self.iqRegistry[iqEntity.getId()] = (iqEntity, onSuccess, onError)
self.toLower(iqEntity)
def processIqRegistry(self, entity):
"""
:type entity: IqProtocolEntity
"""
if entity.getTag() == "iq":
iq_id = entity.getId()
if iq_id in self.iqRegistry:
originalIq, successClbk, errorClbk = self.iqRegistry[iq_id]
del self.iqRegistry[iq_id]
if entity.getType() == IqProtocolEntity.TYPE_RESULT and successClbk:
successClbk(entity, originalIq)
elif entity.getType() == IqProtocolEntity.TYPE_ERROR and errorClbk:
errorClbk(entity, originalIq)
return True
return False
def getOwnJid(self, full=True):
return self.getLayerInterface(YowAuthenticationProtocolLayer).getUsername(full)
def connect(self):
self.getLayerInterface(YowNetworkLayer).connect()
def disconnect(self):
disconnectEvent = YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT)
self.broadcastEvent(disconnectEvent)
def send(self, data):
self.toLower(data)
def receive(self, entity):
if not self.processIqRegistry(entity):
entityType = entity.getTag()
if entityType in self.entity_callbacks:
self.entity_callbacks[entityType](entity)
else:
self.toUpper(entity)
@ProtocolEntityCallback("stream:error")
def onStreamError(self, streamErrorEntity):
logger.error(streamErrorEntity)
if self.getProp(self.__class__.PROP_RECONNECT_ON_STREAM_ERR, True):
if streamErrorEntity.getErrorType() == StreamErrorProtocolEntity.TYPE_CONFLICT:
logger.warn("Not reconnecting because you signed in in another location")
else:
logger.info("Initiating reconnect")
self.reconnect = True
else:
logger.warn("Not reconnecting because property %s is not set" %
self.__class__.PROP_RECONNECT_ON_STREAM_ERR)
self.toUpper(streamErrorEntity)
self.disconnect()
@EventCallback(YowNetworkLayer.EVENT_STATE_CONNECTED)
def onConnected(self, yowLayerEvent):
self.reconnect = False
@EventCallback(YowNetworkLayer.EVENT_STATE_DISCONNECTED)
def onDisconnected(self, yowLayerEvent):
if self.reconnect:
self.reconnect = False
self.connect()
def _sendMediaMessage(self, builder, success, error=None, progress=None):
# axolotlIface = self.getLayerInterface(YowAxolotlLayer)
# if axolotlIface:
# axolotlIface.encryptMedia(builder)
iq = RequestUploadIqProtocolEntity(
builder.mediaType, filePath=builder.getFilepath(), encrypted=builder.isEncrypted())
def successFn(resultEntity, requestUploadEntity): return self.__onRequestUploadSuccess(
resultEntity, requestUploadEntity, builder, success, error, progress)
def errorFn(errorEntity, requestUploadEntity): return self.__onRequestUploadError(
errorEntity, requestUploadEntity, error)
self._sendIq(iq, successFn, errorFn)
def __onRequestUploadSuccess(self, resultRequestUploadIqProtocolEntity, requestUploadEntity, builder, success, error=None, progress=None):
if(resultRequestUploadIqProtocolEntity.isDuplicate()):
return success(builder.build(resultRequestUploadIqProtocolEntity.getUrl(), resultRequestUploadIqProtocolEntity.getIp()))
else:
def successFn(path, jid, url): return self.__onMediaUploadSuccess(
builder, url, resultRequestUploadIqProtocolEntity.getIp(), success)
def errorFn(path, jid, errorText): return self.__onMediaUploadError(
builder, errorText, error)
mediaUploader = MediaUploader(builder.jid, self.getOwnJid(), builder.getFilepath(),
resultRequestUploadIqProtocolEntity.getUrl(),
resultRequestUploadIqProtocolEntity.getResumeOffset(),
successFn, errorFn, progress, asynchronous=True)
mediaUploader.start()
def __onRequestUploadError(self, errorEntity, requestUploadEntity, builder, error=None):
if error:
return error(errorEntity.code, errorEntity.text, errorEntity.backoff)
def __onMediaUploadSuccess(self, builder, url, ip, successClbk):
messageNode = builder.build(url, ip)
return successClbk(messageNode)
def __onMediaUploadError(self, builder, errorText, errorClbk=None):
if errorClbk:
return errorClbk(0, errorText, 0)
def __str__(self):
return "Interface Layer"
| 6,443 | Python | .py | 123 | 41.918699 | 142 | 0.678537 | tgalal/yowsup | 7,053 | 2,225 | 472 | GPL-3.0 | 9/5/2024, 5:13:02 PM (Europe/Amsterdam) |