コード例 #1
0
	def __do_import(self, token):
		# Google
		google = self.google.getContacts(token)
		self.send("%d buddies imported from google" % len(google))

		result = { }
		for number, name in google.iteritems():
			number = re.sub("[^0-9]", "", number)
			number = number if number[0] == "0"  else "+" + number

			result[number] = { 'nick': name, 'state': 0 }

		# WhatsApp
		user = self.session.legacyName
		password = self.session.password
		sync = WAContactsSyncRequest(user, password, result.keys())
		whatsapp = sync.send()['c']

		for w in whatsapp:
			result[w['p']]['state'] = w['w']
			result[w['p']]['number'] = w['n']

		self.send("%d buddies are using whatsapp" % len(filter(lambda w: w['w'], whatsapp)))

		for r in result.values():
			if r['nick']:
				self.session.buddies.add(
					number = r['number'],
					nick = r['nick'],
					groups = [u'Google'],
					state = r['state']
				)

		self.send("%d buddies imported" % len(whatsapp))
コード例 #2
0
ファイル: bot.py プロジェクト: BBBSnowball/transwhat
	def _add(self, *numbers):
		#self.send("Looking up %s on WhatsApp" % number)

		result = {}
		for number in numbers:
	                result[number] = { 'nick': None, 'state': 0 }

		# WhatsApp
                user = self.session.legacyName
                password = self.session.password
                sync = WAContactsSyncRequest(user, password, result.keys())
                whatsapp = sync.send()['c']

                for w in whatsapp:
                        result[w['p']]['state'] = w['w']
                        result[w['p']]['number'] = w['n']

                self.send("%d buddies are using whatsapp" % len(filter(lambda w: w['w'], whatsapp)))

                for r in result.values():
                        if r['nick']:
                                self.session.buddies.add(
                                        number = r['number'],
                                        nick = r['nick'],
                                        groups = [u'added'],
                                        state = r['state']
                                )
                                self.send("buddy %s has nick '%s'" % (r['number'], r['nick']))

                self.send("%d buddies imported" % len(whatsapp))
コード例 #3
0
ファイル: Contacts.py プロジェクト: Cyr0/wazapp-desktop
    def getWAUsers(self, phoneNumbers):
        waUsername = str(getConfig('countryCode') + getConfig('phoneNumber'))
        waPassword = base64.b64decode(getConfig('password'))
        waContactsSync = WAContactsSyncRequest(waUsername, waPassword, phoneNumbers)
        results = waContactsSync.send()

        waUsers = {}
        for entry in results.get('c', []):
            hasWhatsApp = bool(entry['w'])
            if hasWhatsApp:
                requestedPhone = entry['p']
                phone = entry['n']
                waUsers[requestedPhone] = phone
        return waUsers
コード例 #4
0
ファイル: Contacts.py プロジェクト: sadjous/wazapp-desktop
    def getWAUsers(self, phoneNumbers):
        waUsername = str(getConfig('countryCode') + getConfig('phoneNumber'))
        waPassword = base64.b64decode(getConfig('password'))
        waContactsSync = WAContactsSyncRequest(waUsername, waPassword,
                                               phoneNumbers)
        results = waContactsSync.send()

        waUsers = {}
        for entry in results.get('c', []):
            hasWhatsApp = bool(entry['w'])
            if hasWhatsApp:
                requestedPhone = entry['p']
                phone = entry['n']
                waUsers[requestedPhone] = phone
        return waUsers
コード例 #5
0
ファイル: buddy.py プロジェクト: vaginessa/transwhat
    def sync(self, user, password):
        cur = self.db.cursor()
        cur.execute(
            """SELECT
					n.number AS number,
					n.state AS state
				FROM buddies AS r 
				LEFT JOIN numbers AS n
					ON r.buddy_id = n.id
				WHERE
					r.owner_id = %s""", self.owner.id)

        # prefix every number with leading 0 to force internation format
        numbers = dict([("+" + number, state)
                        for number, state in cur.fetchall()])

        if len(numbers) == 0:
            return 0

        result = WAContactsSyncRequest(user, password, numbers.keys()).send()

        using = 0
        for number in result['c']:
            cur = self.db.cursor()
            cur.execute("UPDATE numbers SET state = %s WHERE number = %s",
                        (number['w'], number['n']))
            self.db.commit()
            using += number['w']

        return using
コード例 #6
0
def onCommand(command):
	if command.lower().strip()=="sync":
		contactfile=os.path.join('configs','contacts')
		with open(contactfile,'r') as conts:
			contacts=conts.read()
			contacts = contacts.split(',')
		wsync = WAContactsSyncRequest(bot.username, bot.password, contacts)
		print("Syncing %s contacts" % len(contacts))
		result = wsync.send()
		print(resultToString(result))
	else:
		method,rest=command.split(' ',1)
		print "calling %s with "% method
		rest=tuple(x for x in rest.split())
		pprint(rest)
		bot.methodsInterface.call(method,(rest))
コード例 #7
0
def onCommand(command):
    if command.lower().strip() == "sync":
        contactfile = os.path.join('configs', 'contacts')
        with open(contactfile, 'r') as conts:
            contacts = conts.read()
            contacts = contacts.split(',')
        wsync = WAContactsSyncRequest(bot.username, bot.password, contacts)
        print("Syncing %s contacts" % len(contacts))
        result = wsync.send()
        print(resultToString(result))
    else:
        method, rest = command.split(' ', 1)
        print "calling %s with " % method
        rest = tuple(x for x in rest.split())
        pprint(rest)
        bot.methodsInterface.call(method, (rest))
コード例 #8
0
ファイル: Contacts.py プロジェクト: makuss/wazapp-desktop
    def getWAUsers(self, phoneNumbers):
        waUsers = {}
        waUsername = str(getConfig('countryCode') + getConfig('phoneNumber'))
        waPassword = base64.b64decode(getConfig('password'))
        waContactsSync = WAContactsSyncRequest(waUsername, waPassword, phoneNumbers)
        try:
            results = waContactsSync.send()
        except Exception as e:
            QMessageBox.warning(None, 'Failure', 'Failed to connect to WhatsApp server.\nError was:\n%s' % (e))
            return waUsers

        for entry in results.get('c', []):
            hasWhatsApp = bool(entry['w'])
            if hasWhatsApp:
                requestedPhone = entry['p']
                phone = entry['n']
                waUsers[requestedPhone] = phone
        return waUsers
コード例 #9
0
ファイル: contacts.py プロジェクト: AbinashBishoyi/wazapp
	def __init__(self,store, contactsManager, mode,userid = None):
		WADebug.attach(self);
		self.store = store;
		self.mode = mode
		self.uid = userid;
		
		super(ContactsSyncer,self).__init__();
		
		acc = AccountsManager.getCurrentAccount();
		
		if not acc:
			self.contactsRefreshFail.emit()
			
		
		username = str(acc.username)
		password = acc.password
		
		self.contactsManager = contactsManager
			
		self.syncer = WAContactsSyncRequest(username, password, [])	
コード例 #10
0
def mainProcess(argumentsPro):
    #pdb.set_trace()
    parser = argparse.ArgumentParser(
        description='yowsup-cli Command line options')

    clientsGroup = parser.add_argument_group("Client options")

    regGroup = parser.add_argument_group("Registration options")

    modes = clientsGroup.add_mutually_exclusive_group()
    modes.add_argument('-l',
                       '--listen',
                       help='Listen to messages',
                       action="store_true",
                       required=False,
                       default=False)
    modes.add_argument(
        '-s',
        '--send',
        help=
        "Send message to phone number and close connection. Phone is full number including country code, without '+' or '00'",
        action="store",
        nargs=2,
        metavar=('<phone>', '<message>'),
        required=False)
    modes.add_argument(
        '-p',
        '--sendImage',
        help=
        "Send image to phone number and close connection. Phone is full number including country code, without '+' or '00'",
        action="store",
        nargs=2,
        metavar=('<phone>', '<image path>'),
        required=False)
    modes.add_argument(
        '-i',
        '--interactive',
        help=
        "Start an interactive conversation with a contact. Phone is full number including country code, without '+' or '00'",
        action="store",
        metavar='<phone>',
        required=False)
    modes.add_argument(
        '-b',
        '--broadcast',
        help="Broadcast message to multiple recepients, comma seperated",
        action="store",
        nargs=2,
        metavar=('<jids>', '<message>'),
        required=False)

    #modes.add_argument('-b','--bot', help='Bot', action="store_true", required=False, default=False)

    clientsGroup.add_argument(
        '-w',
        '--wait',
        help=
        'If used with -s, then connection will not close until server confirms reception of the message',
        action="store_true",
        required=False,
        default=False)
    clientsGroup.add_argument(
        '-a',
        '--autoack',
        help=
        'If used with -l or -i, then a message received ack would be automatically sent for received messages',
        action="store_true",
        required=False,
        default=False)
    clientsGroup.add_argument(
        '-k',
        '--keepalive',
        help=
        "When used with -l or -i, Yowsup will automatically respond to server's ping requests to keep connection alive",
        action="store_true",
        required=False,
        default=False)

    regSteps = regGroup.add_mutually_exclusive_group()
    regSteps.add_argument(
        "-r",
        '--requestcode',
        help='Request the 3 digit registration code from Whatsapp.',
        action="store",
        required=False,
        metavar="(sms|voice)")
    regSteps.add_argument(
        "-R",
        '--register',
        help='Register account on Whatsapp using the provided 3 digit code',
        action="store",
        required=False,
        metavar="code")
    regSteps.add_argument(
        "-e",
        '--exists',
        help=
        'Check if account credentials are valid. WARNING: Whatsapp now changes your password everytime you use this. Make sure you update your config file if the output informs about a password change',
        action="store_true",
        required=False)

    contactOptions = parser.add_argument_group(
        "Contacts options").add_mutually_exclusive_group()

    contactOptions.add_argument(
        '--sync',
        help=
        'Sync provided numbers. Numbers should be comma-separated. If a number is not in international format, Whatsapp will assume your own country code for it. Returned data indicate which numbers are whatsapp users and which are not. For Whatsapp users, it will return some info about each user, like user status.',
        metavar="numbers",
        action="store",
        required=False)

    debugTools = parser.add_argument_group(
        "Debug tools").add_mutually_exclusive_group()

    debugTools.add_argument(
        '--generatepassword',
        help=
        "Generate password from given string in same way Whatsapp generates it from a given IMEI or MAC Address",
        action="store",
        metavar="input")
    debugTools.add_argument(
        '--decodestring',
        help=
        "Decode byte arrays found in decompiled version of Whatsapp. Tested with S40 version. Input should be comma separated without the enclosing brackets. Example: ./yowsup-cli --decodestring 112,61,100,123,114,103,96,114,99,99,61,125,118,103",
        action="store",
        metavar="encoded_array")

    parser.add_argument("--help-config",
                        help="Display info about configuration format",
                        action="store_true")
    parser.add_argument(
        '-c',
        '--config',
        help=
        "Path to config file containing authentication info. For more info about config format use --help-config",
        action="store",
        metavar="file",
        required=False,
        default=False)
    #parser.add_argument('-D','--dbus', help='Start DBUS interface', action="store_true", required=False, default=False)
    parser.add_argument('-I',
                        '--ignorecached',
                        help="Don't use cached token if exists",
                        action="store_true",
                        required=False,
                        default=False)
    parser.add_argument('-d',
                        '--debug',
                        help='Enable debug messages',
                        action="store_true",
                        required=False,
                        default=False)
    parser.add_argument('-v',
                        '--version',
                        help="Print version info and exit",
                        action='store_true',
                        required=False,
                        default=False)

    args = vars(parser.parse_args(argumentsPro))
    if len(sys.argv) == 1:
        parser.print_help()

    elif args["help_config"]:
        print(CONFIG_HELP)
    elif args["version"]:
        print("yowsup-cli %s, using Yowsup %s" % (__version__, Constants.v))
    else:
        credentials = getCredentials(args["config"] or DEFAULT_CONFIG)

        if credentials:

            #cc, phone, idx, pw, admingp, adminusr, operatorusr, clientusr, nobodyusr
            countryCode, login, identity, password = credentials

            identity = Utilities.processIdentity(identity)
            password = base64.b64decode(bytes(password.encode('utf-8')))

            if countryCode:
                phoneNumber = login[len(countryCode):]
            else:
                dissected = dissectPhoneNumber(login)
                if not dissected:
                    sys.exit(
                        "ERROR. Couldn't detect cc, you have to manually place it your config"
                    )
                countryCode, phoneNumber = dissected

            Debugger.enabled = args['debug']

            if args["ignorecached"]:
                Utilities.tokenCacheEnabled = False

            if args["interactive"]:
                #val = args["interactive"]
                #wa = WhatsappCmdClient(val, args['keepalive'] ,args['autoack'])
                #wa.login(login, password)
                pass
            elif args['send']:
                #pdb.set_trace()
                phone = args["send"][0]
                message = args["send"][1]
                wa = WhatsappEchoClient(phone, message, args['wait'])
                wa.login(login, password)
            elif args["sendImage"]:
                phone = args["sendImage"][0]
                imagePath = args["sendImage"][1]
                wa = UploaderClient(phone, imagePath, args['wait'])
                wa.login(login, password)
            elif args['listen']:
                #pdb.set_trace()
                wa = WhatsappListenerClient(args['keepalive'], args['autoack'])
                wa.login(login, password)
                wa.listening()

            elif args['broadcast']:

                phones = args["broadcast"][0]
                message = args["broadcast"][1]

                wa = WhatsappEchoClient(phones, message, args['wait'])
                wa.login(login, password)

            elif args["requestcode"]:

                method = args["requestcode"]
                if method not in ("sms", "voice"):
                    print("coderequest accepts only sms or voice as a value")
                else:

                    wc = WACodeRequestV2(countryCode, phoneNumber, identity,
                                         method)

                    result = wc.send()
                    print(resultToString(result))

            elif args["register"]:
                code = args["register"]
                code = "".join(code.split('-'))
                wr = WARegRequestV2(countryCode, phoneNumber, code, identity)

                result = wr.send()
                print(resultToString(result))

            elif args["exists"]:

                we = WAExistsRequestV2(countryCode, phoneNumber, identity)
                result = we.send()
                print(resultToString(result))

                if result["pw"] is not None:
                    print(
                        "\n=========\nWARNING: %s%s's has changed by server to \"%s\", you must update your config file with the new password\n========="
                        % (countryCode, phoneNumber, result["pw"]))

            elif args["sync"]:

                contacts = args["sync"].split(',')
                wsync = WAContactsSyncRequest(login, password, contacts)

                print("Syncing %s contacts" % len(contacts))
                result = wsync.send()

                print(resultToString(result))

        elif args["dbus"]:
            startDbusInterface()
        elif args["generatepassword"]:
            print(Utilities.processIdentity(args["generatepassword"]))
        elif args["decodestring"]:
            print(
                Utilities.decodeString(
                    map(int,
                        "".join(args["decodestring"].split(' ')).split(','))))
        else:
            print("Error: config file is invalid")
コード例 #11
0
ファイル: commandLineCli.py プロジェクト: morfeokmg/maurrepo
def mainProcess(argumentsPro):
	#pdb.set_trace()
	parser = argparse.ArgumentParser(description='yowsup-cli Command line options')
	
	clientsGroup = parser.add_argument_group("Client options")
	
	regGroup = parser.add_argument_group("Registration options")
	
	
	modes = clientsGroup.add_mutually_exclusive_group()
	modes.add_argument('-l','--listen', help='Listen to messages', action="store_true", required=False, default=False)
	modes.add_argument('-s','--send', help="Send message to phone number and close connection. Phone is full number including country code, without '+' or '00'", action="store",  nargs=2, metavar=('<phone>','<message>'), required=False)
	modes.add_argument('-p','--sendImage', help="Send image to phone number and close connection. Phone is full number including country code, without '+' or '00'", action="store",  nargs=2, metavar=('<phone>','<image path>'), required=False)
	modes.add_argument('-i','--interactive', help="Start an interactive conversation with a contact. Phone is full number including country code, without '+' or '00'", action="store", metavar='<phone>', required=False)
	modes.add_argument('-b','--broadcast', help="Broadcast message to multiple recepients, comma seperated", action="store", nargs=2, metavar=('<jids>', '<message>'), required=False)
	
	#modes.add_argument('-b','--bot', help='Bot', action="store_true", required=False, default=False)
	
	
	clientsGroup.add_argument('-w','--wait', help='If used with -s, then connection will not close until server confirms reception of the message', action="store_true", required=False, default=False)
	clientsGroup.add_argument('-a','--autoack', help='If used with -l or -i, then a message received ack would be automatically sent for received messages', action="store_true", required=False, default=False)
	clientsGroup.add_argument('-k','--keepalive', help="When used with -l or -i, Yowsup will automatically respond to server's ping requests to keep connection alive", action="store_true", required=False, default=False)
	
	
	regSteps = regGroup.add_mutually_exclusive_group()
	regSteps.add_argument("-r", '--requestcode', help='Request the 3 digit registration code from Whatsapp.', action="store", required=False, metavar="(sms|voice)")
	regSteps.add_argument("-R", '--register', help='Register account on Whatsapp using the provided 3 digit code', action="store", required=False, metavar="code")
	regSteps.add_argument("-e", '--exists', help='Check if account credentials are valid. WARNING: Whatsapp now changes your password everytime you use this. Make sure you update your config file if the output informs about a password change', action="store_true", required=False)
	
	
	
	
	
	contactOptions = parser.add_argument_group("Contacts options").add_mutually_exclusive_group();
	
	contactOptions.add_argument('--sync', help='Sync provided numbers. Numbers should be comma-separated. If a number is not in international format, Whatsapp will assume your own country code for it. Returned data indicate which numbers are whatsapp users and which are not. For Whatsapp users, it will return some info about each user, like user status.', metavar="numbers", action="store", required=False)
	
	
	
	debugTools = parser.add_argument_group("Debug tools").add_mutually_exclusive_group();
	
	debugTools.add_argument('--generatepassword', help="Generate password from given string in same way Whatsapp generates it from a given IMEI or MAC Address", action="store", metavar="input")
	debugTools.add_argument('--decodestring', help="Decode byte arrays found in decompiled version of Whatsapp. Tested with S40 version. Input should be comma separated without the enclosing brackets. Example: ./yowsup-cli --decodestring 112,61,100,123,114,103,96,114,99,99,61,125,118,103", action="store", metavar="encoded_array")
	
	
	parser.add_argument("--help-config", help="Display info about configuration format", action="store_true")
	parser.add_argument('-c','--config', help="Path to config file containing authentication info. For more info about config format use --help-config", action="store", metavar="file", required=False, default=False)
	#parser.add_argument('-D','--dbus', help='Start DBUS interface', action="store_true", required=False, default=False)
	parser.add_argument('-I','--ignorecached', help="Don't use cached token if exists", action="store_true", required=False, default=False)
	parser.add_argument('-d','--debug', help='Enable debug messages', action="store_true", required=False, default=False)
	parser.add_argument('-v', '--version', help="Print version info and exit", action='store_true', required=False, default=False)
	
	
	args = vars(parser.parse_args(argumentsPro))
	if len(sys.argv) == 1:
		parser.print_help()
	
	elif args["help_config"]:
		print(CONFIG_HELP)
	elif args["version"]:
		print("yowsup-cli %s, using Yowsup %s"%(__version__, Constants.v))
	else:
		credentials = getCredentials(args["config"] or DEFAULT_CONFIG)
		
		if credentials:

			#cc, phone, idx, pw, admingp, adminusr, operatorusr, clientusr, nobodyusr	
			countryCode, login, identity, password = credentials
	
			identity = Utilities.processIdentity(identity)
			password = base64.b64decode(bytes(password.encode('utf-8')))
	
			if countryCode:
				phoneNumber = login[len(countryCode):]
			else:
				dissected = dissectPhoneNumber(login)
				if not dissected:
						sys.exit("ERROR. Couldn't detect cc, you have to manually place it your config")
				countryCode, phoneNumber = dissected
					
			Debugger.enabled = args['debug']
	
			if args["ignorecached"]:
				Utilities.tokenCacheEnabled = False
	
			if args["interactive"]:
				#val = args["interactive"]
				#wa = WhatsappCmdClient(val, args['keepalive'] ,args['autoack'])
				#wa.login(login, password)
				pass
			elif args['send']:
				#pdb.set_trace()
				phone = args["send"][0]
				message = args["send"][1]
				wa = WhatsappEchoClient(phone, message, args['wait'])
				wa.login(login, password)
                	elif args["sendImage"]:
                        	phone = args["sendImage"][0]
                        	imagePath = args["sendImage"][1]
                        	wa = UploaderClient(phone, imagePath, args['wait'])
                        	wa.login(login, password)
			elif args['listen']:
				#pdb.set_trace()
				wa = WhatsappListenerClient(args['keepalive'], args['autoack'])
				wa.login(login, password)
				wa.listening()
				
			elif args['broadcast']:
				
				phones = args["broadcast"][0]
				message = args["broadcast"][1]
				
				wa = WhatsappEchoClient(phones, message, args['wait'])
				wa.login(login, password)
	
			elif args["requestcode"]:
	
				method = args["requestcode"]
				if method not in ("sms","voice"):
					print("coderequest accepts only sms or voice as a value")
				else:
	
					wc = WACodeRequestV2(countryCode, phoneNumber, identity, method)
						
					result = wc.send()
					print(resultToString(result))
					
			elif args["register"]:
				code = args["register"]
				code = "".join(code.split('-'))
				wr = WARegRequestV2(countryCode, phoneNumber, code, identity)
				
				
				result = wr.send()
				print(resultToString(result))
				
			elif args["exists"]:
	
				we = WAExistsRequestV2(countryCode, phoneNumber, identity)
				result = we.send()
				print(resultToString(result))
	
				if result["pw"] is not None:
					print("\n=========\nWARNING: %s%s's has changed by server to \"%s\", you must update your config file with the new password\n=========" %(countryCode, phoneNumber, result["pw"]))
		
			elif args["sync"]:
	
				contacts = args["sync"].split(',')
				wsync = WAContactsSyncRequest(login, password, contacts)
				
				print("Syncing %s contacts" % len(contacts))
				result = wsync.send()
				
				print(resultToString(result))
	
		elif args["dbus"]:
	            startDbusInterface()
		elif args["generatepassword"]:
			print(Utilities.processIdentity(args["generatepassword"]));
		elif args["decodestring"]:
			print(Utilities.decodeString(map(int, "".join(args["decodestring"].split(' ')).split(','))))
		else:
			print("Error: config file is invalid")
コード例 #12
0
			result = wr.send()
			print(resultToString(result))
			
		elif args["exists"]:

			we = WAExistsRequestV2(countryCode, phoneNumber, identity)
			result = we.send()
			print(resultToString(result))

			if result["pw"] is not None:
				print("\n=========\nWARNING: %s%s's has changed by server to \"%s\", you must update your config file with the new password\n=========" %(countryCode, phoneNumber, result["pw"]))
	
		elif args["sync"]:

			contacts = args["sync"].split(',')
			wsync = WAContactsSyncRequest(login, password, contacts)
			
			print("Syncing %s contacts" % len(contacts))
			result = wsync.send()
			
			print(resultToString(result))

	elif args["dbus"]:
            startDbusInterface()
	elif args["generatepassword"]:
		print(Utilities.processIdentity(args["generatepassword"]));
	elif args["decodestring"]:
		print(Utilities.decodeString(map(int, "".join(args["decodestring"].split(' ')).split(','))))
	else:
		print("Error: config file is invalid")
コード例 #13
0
ファイル: contacts.py プロジェクト: AbinashBishoyi/wazapp
class ContactsSyncer(QObject):
	'''
	Interfaces with whatsapp contacts server to get contact list
	'''
	contactsRefreshSuccess = QtCore.Signal(str,dict);
	contactsRefreshFail = QtCore.Signal();
	contactsSyncStatus = QtCore.Signal(str);

	def __init__(self,store, contactsManager, mode,userid = None):
		WADebug.attach(self);
		self.store = store;
		self.mode = mode
		self.uid = userid;
		
		super(ContactsSyncer,self).__init__();
		
		acc = AccountsManager.getCurrentAccount();
		
		if not acc:
			self.contactsRefreshFail.emit()
			
		
		username = str(acc.username)
		password = acc.password
		
		self.contactsManager = contactsManager
			
		self.syncer = WAContactsSyncRequest(username, password, [])	
		
	def sync(self):
		self._d("INITiATING SYNC")
		self.contactsSyncStatus.emit("GETTING");

		if self.mode == "STATUS":
			self.uid = "+" + self.uid
			self._d("Sync contact for status: " + self.uid)
			self.syncer.setContacts([self.uid])

		elif self.mode == "SYNC":
			
			phoneContacts = self.contactsManager.getPhoneContacts();
			contacts = []
			for c in phoneContacts:
				for number in c[2]:
					try:
						contacts.append(str(number))
					except UnicodeEncodeError:
						continue
			
			self.syncer.setContacts(contacts)


		self.contactsSyncStatus.emit("SENDING");
		result = self.syncer.send()
		
		if result:
			print("DONE!!")
			self.updateContacts(result["c"]);
		else:
			self.contactsRefreshFail.emit();
		
		
		
	def updateContacts(self, contacts):
		#data = str(data);
	
		if self.mode == "STATUS":
			for c in contacts:
				
				
				if not c['w'] == 1:
					continue

				status = c["s"];
				
				jid = "*****@*****.**" % c['n']
				status = c["s"]#.encode('utf-8')

				contact = self.store.Contact.getOrCreateContactByJid(jid)
				contact.status = status.encode("unicode_escape")
				contact.save()

				self.contactsRefreshSuccess.emit(self.mode, contact);

		else:
			for c in contacts:
				self.contactsSyncStatus.emit("LOADING");
				
				if not c['w'] == 1:
					continue
				
				jid = "*****@*****.**" % c['n']
				status = c["s"].encode("unicode_escape")
				#number = str(c["p"])
				
				contact = self.store.Contact.getOrCreateContactByJid(jid)
				contact.status = status
				contact.iscontact = "yes"
				contact.save()

			self.contactsRefreshSuccess.emit(self.mode, {});	

		
	def onRefreshing(self):
		self.start();

	@async
	def start(self):
		try:
			self.sync();
		except:
			self._d(sys.exc_info()[1])
			self.contactsRefreshFail.emit()