예제 #1
0
파일: manager.py 프로젝트: tgalal/yowsup
 def save(self, config, serialize_type=TYPE_JSON, dest=None):
     outputdata = self.config_to_str(config, serialize_type)
     if dest is None:
         StorageTools.writePhoneConfig(config.phone, outputdata)
     else:
         with open(dest, 'wb') as outputfile:
             outputfile.write(outputdata)
예제 #2
0
 def handleSuccess(self, node):
     if node.data != None:
         StorageTools.writeNonce(self.credentials[0], node.data)
     successEvent = YowLayerEvent(self.__class__.EVENT_AUTHED, passive=self.getProp(self.__class__.PROP_PASSIVE))
     self.broadcastEvent(successEvent)
     nodeEntity = SuccessProtocolEntity.fromProtocolTreeNode(node)
     self.toUpper(nodeEntity)
예제 #3
0
 def save(self, profile_name, config, serialize_type=TYPE_JSON, dest=None):
     outputdata = self.config_to_str(config, serialize_type)
     if dest is None:
         StorageTools.writeProfileConfig(profile_name, outputdata)
     else:
         with open(dest, 'wb') as outputfile:
             outputfile.write(outputdata)
예제 #4
0
 def handleSuccess(self, node):
     if (node.data != None):
         StorageTools.writeNonce(self.credentials[0], node.data)
     successEvent = YowLayerEvent(self.__class__.EVENT_AUTHED,
                                  passive=self.getProp(
                                      self.__class__.PROP_PASSIVE))
     self.broadcastEvent(successEvent)
     nodeEntity = SuccessProtocolEntity.fromProtocolTreeNode(node)
     self.toUpper(nodeEntity)
예제 #5
0
    def send(self, parser = None):
        if self.__id is not None:
            request = WAExistsRequest(self.cc, self.p_in, self.__id)
            result = request.send()
            if result["status"] == "ok":
                return result

        self.__id = WATools.generateIdentity()
        self.addParam("id", self.__id)

        res = super(WACodeRequest, self).send(parser)
        if res["status"] == "sent":
            StorageTools.writeIdentity(self.cc + self.p_in, self.__id)
        return res
예제 #6
0
    def send(self, parser = None):
        if self.__id is not None:
            request = WAExistsRequest(self.cc, self.p_in, self.__id)
            result = request.send()
            if result["status"] == "ok":
                return result

        self.__id = WATools.generateIdentity()
        self.addParam("id", self.__id)

        res = super(WACodeRequest, self).send(parser)
        if res["status"] == "sent":
            StorageTools.writeIdentity(self.cc + self.p_in, self.__id)
        return res
예제 #7
0
    def __init__(self,
                 cc,
                 p_in,
                 mcc="000",
                 mnc="000",
                 sim_mcc="000",
                 sim_mnc="000",
                 method="sms"):
        super(WACodeRequest, self).__init__()
        idx = StorageTools.getIdentity(cc + p_in)

        self.p_in = p_in
        self.__id = idx
        self.cc = cc

        self.addParam("cc", cc)
        self.addParam("in", p_in)
        self.addParam("lc", "GB")
        self.addParam("lg", "en")
        self.addParam("sim_mcc", sim_mcc.zfill(3))
        self.addParam("sim_mnc", sim_mnc.zfill(3))
        self.addParam("method", method)

        self.addParam("token", CURRENT_ENV.getToken(p_in))

        self.url = "v.whatsapp.net/v2/code"

        self.pvars = ["status","reason","length", "method", "retry_after", "code", "param"] +\
                    ["login", "pw", "type", "expiration", "kind", "price", "cost", "currency", "price_expiration"]

        self.setParser(JSONResponseParser())
예제 #8
0
    def __init__(self,cc, p_in, code):
        super(WARegRequest,self).__init__()
        idx = StorageTools.getIdentity(cc + p_in)

        if idx is None:
            logger.error("You have to request code first")

        self.addParam("cc", cc)
        self.addParam("in", p_in)

        self.addParam("id", idx)
        self.addParam("code", code)

        self.addParam("lc", "GB")
        self.addParam("lg", "en")

        self.addParam("mistyped", '6')
        # self.addParam('network_radio_type', '1')
        self.addParam('simnum', '1')
        self.addParam('s', '')
        self.addParam('copiedrc', '1')
        self.addParam('hasinrc', '1')
        self.addParam('rcmatch', '1')
        self.addParam('pid', os.getpid())
        self.addParam('rchash', hashlib.sha256(os.urandom(20)).hexdigest())
        self.addParam('anhash', hashlib.md5(os.urandom(20)).hexdigest())
        self.addParam('extexist', '1')
        self.addParam('extstate', '1')

        self.url = "v.whatsapp.net/v2/register"

        self.pvars = ["status", "login", "pw", "type", "expiration", "kind", "price", "cost", "currency", "price_expiration",
                      "reason","retry_after"]

        self.setParser(JSONResponseParser())
예제 #9
0
    def load(self, username):
        """
        :param username:
        :type username:
        :return:
        :rtype:
        """
        config_dir = StorageTools.getStorageForPhone(username)
        logger.debug("Detecting config for username=%s, dir=%s" %
                     (username, config_dir))
        exhausted = []
        for ftype in self.MAP_EXT:
            if len(ftype):
                fname = (self.NAME_FILE_CONFIG + "." + ftype)
            else:
                fname = self.NAME_FILE_CONFIG

            fpath = os.path.join(config_dir, fname)
            logger.debug("Trying %s" % fpath)
            if os.path.isfile(fpath):
                return self.load_path(fpath)

            exhausted.append(fpath)

        logger.error(
            "Could not find a config for username=%s, paths checked: %s" %
            (username, ":".join(exhausted)))
예제 #10
0
 def initStore(self):
     self.store = LiteAxolotlStore(
         StorageTools.constructPath(
             self.getProp(
                 YowAuthenticationProtocolLayer.PROP_CREDENTIALS)[0],
             self.__class__._DB))
     self.state = self.__class__._STATE_HASKEYS if  self.store.getLocalRegistrationId() is not None \
         else self.__class__._STATE_INIT
예제 #11
0
파일: layer.py 프로젝트: oscardb22/yowsup
 def initStore(self):
     self.store = LiteAxolotlStore(
         StorageTools.constructPath(
             self.getProp(
                 YowAuthenticationProtocolLayer.PROP_CREDENTIALS)[0],
             self.__class__._DB
         )
     )
     self.state = self.__class__._STATE_HASKEYS if self.store.getLocalRegistrationId() is not None \
         else self.__class__._STATE_INIT
예제 #12
0
 def store(self):
     try:
         if self._store is None:
             self.store = LiteAxolotlStore(
                 StorageTools.constructPath(
                     self.getProp(
                         YowAuthenticationProtocolLayer.PROP_CREDENTIALS)
                     [0], self.__class__._DB))
         return self._store
     except AttributeError:
         return None
예제 #13
0
    def _sendAuth(self):
        passive = self.getProp(self.__class__.PROP_PASSIVE, False)
        nonce = StorageTools.getNonce(self.credentials[0])

        if nonce == None:
            self.entityToLower(AuthProtocolEntity(self.credentials[0], passive=passive))
        else:
            inputKey, outputKey, authBlob = self.generateAuthBlob(nonce)
            #to prevent enr whole response
            self.broadcastEvent(YowLayerEvent(YowCryptLayer.EVENT_KEYS_READY, keys = (inputKey, None)))
            self.entityToLower(AuthProtocolEntity(self.credentials[0], passive=passive, nonce=authBlob))
            self.broadcastEvent(YowLayerEvent(YowCryptLayer.EVENT_KEYS_READY, keys = (inputKey, outputKey)))
예제 #14
0
    def _sendAuth(self):
        passive = self.getProp(self.__class__.PROP_PASSIVE, False)
        nonce = StorageTools.getNonce(self.credentials[0])

        if nonce == None:
            self.entityToLower(AuthProtocolEntity(self.credentials[0], passive=passive))
        else:
            inputKey, outputKey, authBlob = self.generateAuthBlob(nonce)
            #to prevent enr whole response
            self.broadcastEvent(YowLayerEvent(YowCryptLayer.EVENT_KEYS_READY, keys = (inputKey, None)))
            self.entityToLower(AuthProtocolEntity(self.credentials[0], passive=passive, nonce=authBlob))
            self.broadcastEvent(YowLayerEvent(YowCryptLayer.EVENT_KEYS_READY, keys = (inputKey, outputKey)))
예제 #15
0
 def store(self):
     try:
         if self._store is None:
             self.store = LiteAxolotlStore(
                 StorageTools.constructPath(
                     self.getProp(
                         YowAuthenticationProtocolLayer.PROP_CREDENTIALS)[0],
                     self.__class__._DB
                 )
             )
         return self._store
     except AttributeError:
         return None
예제 #16
0
 def save_as(media, filename):
     """
     Save binary data `media` as `filename`.
     Return saved path if successful.
     Otherwise, print error and return `None`.
     """
     try:
         layer = self.getLayerInterface(YowAuthenticationProtocolLayer)
         username = layer.getUsername(False)
         path = StorageTools.getStorageForPhone(username) + filename
         with open(path, 'wb') as f:
             f.write(media)
         return path
     except Exception as e:
         logger.error("Save Error:%s", e)
         return None
예제 #17
0
    def __init__(self,
                 cc,
                 p_in,
                 mcc="000",
                 mnc="000",
                 sim_mcc="000",
                 sim_mnc="000",
                 method="sms"):
        super(WACodeRequest, self).__init__()
        idx = StorageTools.getIdentity(cc + p_in)

        self.p_in = p_in
        self.__id = idx
        self.cc = cc

        self.addParam("cc", cc)
        self.addParam("in", p_in)
        self.addParam("lc", "GB")
        self.addParam("lg", "en")
        self.addParam("sim_mcc", sim_mcc.zfill(3))
        self.addParam("sim_mnc", sim_mnc.zfill(3))
        self.addParam("mcc", sim_mcc.zfill(3))
        self.addParam("mnc", sim_mnc.zfill(3))
        self.addParam("method", method)

        self.addParam("mistyped", "6")
        self.addParam("network_radio_type", "1")
        self.addParam("simnum", "1")
        self.addParam("s", "")
        self.addParam("copiedrc", "1")
        self.addParam("hasinrc", "1")
        self.addParam("rcmatch", "1")
        self.addParam("pid", int(random.uniform(100, 9999)))
        self.addParam("rchash", hashlib.sha256(os.urandom(20)).hexdigest())
        self.addParam("anhash", os.urandom(20))
        self.addParam("extexist", "1")
        self.addParam("extstate", "1")

        self.addParam("token", YowsupEnv.getCurrent().getToken(p_in))

        self.url = "v.whatsapp.net/v2/code"

        self.pvars = ["status","reason","length", "method", "retry_after", "code", "param"] +\
                    ["login", "pw", "type", "expiration", "kind", "price", "cost", "currency", "price_expiration"]

        self.setParser(JSONResponseParser())
예제 #18
0
    def process(self):
        self.args = vars(self.parse_args())

        if self.args["debug"]:
            logger.setLevel(logging.DEBUG)
            yowlogger.setLevel(level=logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)
            yowlogger.setLevel(level=logging.INFO)

        YowsupEnv.setEnv("android")

        config_manager = ConfigManager()
        profile_name = None
        config_loaded_from_profile = True
        if self.args["config"]:
            config = config_manager.load(self.args["config"])
            if not os.path.isfile(self.args["config"]):
                profile_name = self.args["config"]
            elif not self.args["config"].startswith(
                    StorageTools.getStorageForProfile(config.phone)):
                config_loaded_from_profile = False
        else:
            raise ValueError("Must specify --config")

        if config is None:
            config = Config()

        if not config_loaded_from_profile:
            # config file was explicitly specified and is not that of profile,
            # load profile config and override values
            internal_config = config_manager.load(config.phone,
                                                  profile_only=True)
            if internal_config is not None:
                for property in config.keys():
                    if property != "version" and config[property] is not None:
                        internal_config[property] = config[property]
                config = internal_config

        if self._profile is None or self._profile.config is None:
            self._profile = YowProfile(profile_name or config.phone, config)

        if self._profile.config.phone is None:
            print("Invalid config")
            sys.exit(1)
예제 #19
0
    def load(self, path_or_profile_name, profile_only=False):
        # type: (str, bool) -> Config
        """
        Will first try to interpret path_or_profile_name as direct path to a config file and load from there. If
        this fails will interpret it as profile name and load from profile dir.
        :param path_or_profile_name:
        :param profile_only
        :return Config instance, or None if no config could be found
        """
        logger.debug("load(path_or_profile_name=%s, profile_only=%s)" %
                     (path_or_profile_name, profile_only))

        exhausted = []
        if not profile_only:
            config = self._load_path(path_or_profile_name)
        else:
            config = None
        if config is not None:
            return config
        else:
            logger.debug(
                "path_or_profile_name is not a path, using it as profile name")
            if not profile_only:
                exhausted.append(path_or_profile_name)
            profile_name = path_or_profile_name
            config_dir = StorageTools.getStorageForProfile(profile_name)
            logger.debug("Detecting config for profile=%s, dir=%s" %
                         (profile_name, config_dir))
            for ftype in self.MAP_EXT:
                if len(ftype):
                    fname = (self.NAME_FILE_CONFIG + "." + ftype)
                else:
                    fname = self.NAME_FILE_CONFIG

                fpath = os.path.join(config_dir, fname)
                logger.debug("Trying %s" % fpath)
                if os.path.isfile(fpath):
                    return self._load_path(fpath)

                exhausted.append(fpath)

            logger.error(
                "Could not find a config for profile=%s, paths checked: %s" %
                (profile_name, ":".join(exhausted)))
예제 #20
0
    def store(self):
        if self._store is None:
            conn_str = self.getProp(self.__class__.PROP_CONNECTION_STRING)
            conn_type = self.getProp(self.__class__.PROP_STORE_TYPE)
            phone_number = self.getProp(
                YowAuthenticationProtocolLayer.PROP_CREDENTIALS)[0]
            if (conn_type == 'mysql' and conn_str):
                # try:
                self.store = MyAxolotlStore(conn_str, phone_number)
            # except:
            #    logger.error("ERROR:: {} ".format(sys.exc_info()[1]))
            else:
                self.store = LiteAxolotlStore(
                    StorageTools.constructPath(phone_number,
                                               self.__class__._DB))
            self.state = self.__class__._STATE_HASKEYS if  self.store.getLocalRegistrationId() is not None \
                else self.__class__._STATE_INIT

        return self._store
예제 #21
0
파일: regrequest.py 프로젝트: 3esmit/yowsup
    def __init__(self,cc, p_in, code):
        super(WARegRequest,self).__init__()
        idx = StorageTools.getIdentity(cc + p_in)

        if idx is None:
            raise ValueError("You have to request code first")

        self.addParam("cc", cc)
        self.addParam("in", p_in)

        self.addParam("id", idx)
        self.addParam("code", code)

        self.url = "v.whatsapp.net/v2/register"

        self.pvars = ["status", "login", "pw", "type", "expiration", "kind", "price", "cost", "currency", "price_expiration",
                      "reason","retry_after"]

        self.setParser(JSONResponseParser())
예제 #22
0
    def load(self, profile_name):
        # type: (str) -> Config

        config_dir = StorageTools.getStorageForProfile(profile_name)
        logger.debug("Detecting config for profile=%s, dir=%s" % (profile_name, config_dir))
        exhausted = []
        for ftype in self.MAP_EXT:
            if len(ftype):
                fname = (self.NAME_FILE_CONFIG + "." + ftype)
            else:
                fname = self.NAME_FILE_CONFIG

            fpath = os.path.join(config_dir, fname)
            logger.debug("Trying %s" % fpath)
            if os.path.isfile(fpath):
                return self.load_path(fpath)

            exhausted.append(fpath)

        logger.error("Could not find a config for profile=%s, paths checked: %s" % (profile_name, ":".join(exhausted)))
예제 #23
0
    def __init__(self, cc, p_in, code):
        super(WARegRequest, self).__init__()
        idx = StorageTools.getIdentity(cc + p_in)

        if idx is None:
            raise ValueError("You have to request code first")

        self.addParam("cc", cc)
        self.addParam("in", p_in)

        self.addParam("id", idx)
        self.addParam("code", code)

        self.url = "v.whatsapp.net/v2/register"

        self.pvars = [
            "status", "login", "pw", "type", "expiration", "kind", "price",
            "cost", "currency", "price_expiration", "reason", "retry_after"
        ]

        self.setParser(JSONResponseParser())
예제 #24
0
    def __init__(self,cc, p_in, mcc= "000", mnc = "000", sim_mcc = "000", sim_mnc = "000", method="sms"):
        super(WACodeRequest,self).__init__()
        idx = StorageTools.getIdentity(cc + p_in)

        self.p_in = p_in
        self.__id = idx
        self.cc = cc

        self.addParam("cc", cc)
        self.addParam("in", p_in)
        self.addParam("lc", "GB")
        self.addParam("lg", "en")
        self.addParam("sim_mcc", sim_mcc.zfill(3))
        self.addParam("sim_mnc", sim_mnc.zfill(3))
        self.addParam("mcc", sim_mcc.zfill(3))
        self.addParam("mnc", sim_mnc.zfill(3))
        self.addParam("method", method)

        self.addParam("mistyped", "6")
        self.addParam("network_radio_type", "1")
        self.addParam("simnum", "1")
        self.addParam("s", "")
        self.addParam("copiedrc", "1")
        self.addParam("hasinrc", "1")
        self.addParam("rcmatch", "1")
        self.addParam("pid", os.getpid())
        self.addParam("rchash", hashlib.sha256(os.urandom(20)).hexdigest())
        self.addParam("anhash", hashlib.md5(os.urandom(20)).hexdigest())
        self.addParam("extexist", "1")
        self.addParam("extstate", "1")

        self.addParam("token", CURRENT_ENV.getToken(p_in))

        self.url = "v.whatsapp.net/v2/code"

        self.pvars = ["status","reason","length", "method", "retry_after", "code", "param"] +\
                    ["login", "pw", "type", "expiration", "kind", "price", "cost", "currency", "price_expiration"]

        self.setParser(JSONResponseParser())
예제 #25
0
파일: manager.py 프로젝트: tgalal/yowsup
    def load(self, username):
        """
        :param username:
        :type username:
        :return:
        :rtype:
        """
        config_dir = StorageTools.getStorageForPhone(username)
        logger.debug("Detecting config for username=%s, dir=%s" % (username, config_dir))
        exhausted = []
        for ftype in self.MAP_EXT:
            if len(ftype):
                fname = (self.NAME_FILE_CONFIG + "." + ftype)
            else:
                fname = self.NAME_FILE_CONFIG

            fpath = os.path.join(config_dir, fname)
            logger.debug("Trying %s" % fpath)
            if os.path.isfile(fpath):
                return self.load_path(fpath)

            exhausted.append(fpath)

        logger.error("Could not find a config for username=%s, paths checked: %s" % (username, ":".join(exhausted)))
예제 #26
0
    def __init__(self,cc, p_in, mcc= "000", mnc = "000", sim_mcc = "000", sim_mnc = "000", method="sms"):
        super(WACodeRequest,self).__init__()
        idx = StorageTools.getIdentity(cc + p_in)

        self.p_in = p_in
        self.__id = idx
        self.cc = cc

        self.addParam("cc", cc)
        self.addParam("in", p_in)
        self.addParam("lc", "GB")
        self.addParam("lg", "en")
        self.addParam("sim_mcc", sim_mcc.zfill(3))
        self.addParam("sim_mnc", sim_mnc.zfill(3))
        self.addParam("method", method)

        self.addParam("token", CURRENT_ENV.getToken(p_in))

        self.url = "v.whatsapp.net/v2/code"

        self.pvars = ["status","reason","length", "method", "retry_after", "code", "param"] +\
                    ["login", "pw", "type", "expiration", "kind", "price", "cost", "currency", "price_expiration"]

        self.setParser(JSONResponseParser())
예제 #27
0
from yowsup_ext.layers.cleverbot.layer import YowCleverBotLayer
from yowsup_ext.layers.store import YowStorageLayer

import sys
import logging

logging.basicConfig(level = logging.DEBUG)
logger = logging.getLogger(__name__)

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: run.py username password")
        sys.exit(1)
    credentials = (sys.argv[1], sys.argv[2])
    stackBuilder = YowStackBuilder()
    phoneStorage =  StorageTools.getStorageForPhone(credentials[0])
    stackBuilder.setProp(YowStorageLayer.PROP_DB_PATH, StorageTools.constructPath(phoneStorage, "yowstore.db"))
    stack = stackBuilder\
        .pushDefaultLayers(True)\
        .push(YowStorageLayer)\
        .push(YowCleverBotLayer)\
        .build()

    stack.setCredentials(credentials)
    logger.info("Starting")
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))

    try:
        stack.loop(timeout = 0.5, discrete = 0.5)
    except AuthError as e:
        print("Auth Error, reason %s" % e)
예제 #28
0
from yowsup_ext.layers.cleverbot.layer import YowCleverBotLayer
from yowsup_ext.layers.store import YowStorageLayer

import sys
import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: run.py username password")
        sys.exit(1)
    credentials = (sys.argv[1], sys.argv[2])
    stackBuilder = YowStackBuilder()
    phoneStorage = StorageTools.getStorageForPhone(credentials[0])
    stackBuilder.setProp(
        YowStorageLayer.PROP_DB_PATH,
        StorageTools.constructPath(phoneStorage, "yowstore.db"))
    stack = stackBuilder\
        .pushDefaultLayers(True)\
        .push(YowStorageLayer)\
        .push(YowCleverBotLayer)\
        .build()

    stack.setCredentials(credentials)
    logger.info("Starting")
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))

    try:
        stack.loop(timeout=0.5, discrete=0.5)
예제 #29
0
 def get_manager(self, profile_name, username):
     logger.debug("get_manager(profile_name=%s, username=%s)" % (profile_name, username))
     dbpath = StorageTools.constructPath(profile_name, self.DB)
     store = LiteAxolotlStore(dbpath)
     return AxolotlManager(store, username)
예제 #30
0
 def setStack(self, stack):
     super(YowStorageLayer, self).setStack(stack)
     self.db = peewee.SqliteDatabase(self.getProp(self.__class__.PROP_DB_PATH, StorageTools.constructPath("yow.db")), threadlocals=True)
     db.set_db(self.db)
     self.db.connect()
     self.setup_models()
예제 #31
0
파일: factory.py 프로젝트: tgalal/yowsup
 def get_manager(self, username):
     logger.debug("get_manager(username=%s)" % username)
     dbpath = StorageTools.constructPath(username, self.DB)
     store = LiteAxolotlStore(dbpath)
     return AxolotlManager(store, username)