Esempio n. 1
0
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()