1package eu.siacs.conversations.services;
2
3import java.text.ParseException;
4import java.text.SimpleDateFormat;
5import java.util.Date;
6import java.util.Hashtable;
7import java.util.List;
8import java.util.Random;
9
10import org.json.JSONException;
11import org.openintents.openpgp.util.OpenPgpApi;
12import org.openintents.openpgp.util.OpenPgpServiceConnection;
13
14import net.java.otr4j.OtrException;
15import net.java.otr4j.session.Session;
16import net.java.otr4j.session.SessionStatus;
17
18import eu.siacs.conversations.crypto.PgpEngine;
19import eu.siacs.conversations.crypto.PgpEngine.OpenPgpException;
20import eu.siacs.conversations.entities.Account;
21import eu.siacs.conversations.entities.Contact;
22import eu.siacs.conversations.entities.Conversation;
23import eu.siacs.conversations.entities.Message;
24import eu.siacs.conversations.entities.MucOptions;
25import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
26import eu.siacs.conversations.entities.Presences;
27import eu.siacs.conversations.persistance.DatabaseBackend;
28import eu.siacs.conversations.persistance.OnPhoneContactsMerged;
29import eu.siacs.conversations.ui.OnAccountListChangedListener;
30import eu.siacs.conversations.ui.OnConversationListChangedListener;
31import eu.siacs.conversations.ui.OnRosterFetchedListener;
32import eu.siacs.conversations.utils.ExceptionHelper;
33import eu.siacs.conversations.utils.MessageParser;
34import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
35import eu.siacs.conversations.utils.PhoneHelper;
36import eu.siacs.conversations.utils.UIHelper;
37import eu.siacs.conversations.xml.Element;
38import eu.siacs.conversations.xmpp.OnIqPacketReceived;
39import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
40import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
41import eu.siacs.conversations.xmpp.OnStatusChanged;
42import eu.siacs.conversations.xmpp.OnTLSExceptionReceived;
43import eu.siacs.conversations.xmpp.XmppConnection;
44import eu.siacs.conversations.xmpp.stanzas.IqPacket;
45import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
46import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
47import android.app.AlarmManager;
48import android.app.PendingIntent;
49import android.app.Service;
50import android.content.Context;
51import android.content.Intent;
52import android.content.SharedPreferences;
53import android.database.ContentObserver;
54import android.database.DatabaseUtils;
55import android.net.ConnectivityManager;
56import android.net.NetworkInfo;
57import android.os.Binder;
58import android.os.Bundle;
59import android.os.IBinder;
60import android.os.PowerManager;
61import android.os.SystemClock;
62import android.preference.PreferenceManager;
63import android.provider.ContactsContract;
64import android.util.Log;
65
66public class XmppConnectionService extends Service {
67
68 protected static final String LOGTAG = "xmppService";
69 public DatabaseBackend databaseBackend;
70
71 public long startDate;
72
73 private static final int PING_INTERVAL = 300;
74 private static final int PING_TIMEOUT = 2;
75
76 private List<Account> accounts;
77 private List<Conversation> conversations = null;
78
79 public OnConversationListChangedListener convChangedListener = null;
80 private OnAccountListChangedListener accountChangedListener = null;
81 private OnTLSExceptionReceived tlsException = null;
82
83 public void setOnTLSExceptionReceivedListener(OnTLSExceptionReceived listener) {
84 tlsException = listener;
85 }
86
87 private Random mRandom = new Random(System.currentTimeMillis());
88
89 private ContentObserver contactObserver = new ContentObserver(null) {
90 @Override
91 public void onChange(boolean selfChange) {
92 super.onChange(selfChange);
93 Log.d(LOGTAG, "contact list has changed");
94 mergePhoneContactsWithRoster(null);
95 }
96 };
97
98 private XmppConnectionService service = this;
99
100 private final IBinder mBinder = new XmppConnectionBinder();
101 private OnMessagePacketReceived messageListener = new OnMessagePacketReceived() {
102
103 @Override
104 public void onMessagePacketReceived(Account account,
105 MessagePacket packet) {
106 Message message = null;
107 boolean notify = true;
108 if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
109 String pgpBody = MessageParser.getPgpBody(packet);
110 if (pgpBody != null) {
111 message = MessageParser.parsePgpChat(pgpBody, packet,
112 account, service);
113 message.markUnread();
114 } else if (packet.hasChild("body")
115 && (packet.getBody().startsWith("?OTR"))) {
116 message = MessageParser.parseOtrChat(packet, account,
117 service);
118 if (message!=null) {
119 message.markUnread();
120 }
121 } else if (packet.hasChild("body")) {
122 message = MessageParser.parsePlainTextChat(packet, account,
123 service);
124 message.markUnread();
125 } else if (packet.hasChild("received")
126 || (packet.hasChild("sent"))) {
127 message = MessageParser.parseCarbonMessage(packet, account,
128 service);
129 if (message!=null) {
130 message.getConversation().markRead();
131 }
132 notify = false;
133 }
134
135 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
136 message = MessageParser
137 .parseGroupchat(packet, account, service);
138 if (message != null) {
139 if (message.getStatus() == Message.STATUS_RECIEVED) {
140 message.markUnread();
141 } else {
142 message.getConversation().markRead();
143 notify = false;
144 }
145 }
146 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
147 message = MessageParser.parseError(packet, account, service);
148 } else {
149 //Log.d(LOGTAG, "unparsed message " + packet.toString());
150 }
151 if (message == null) {
152 return;
153 }
154 if (packet.hasChild("delay")) {
155 try {
156 String stamp = packet.findChild("delay").getAttribute(
157 "stamp");
158 stamp = stamp.replace("Z", "+0000");
159 Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
160 .parse(stamp);
161 message.setTime(date.getTime());
162 } catch (ParseException e) {
163 Log.d(LOGTAG, "error trying to parse date" + e.getMessage());
164 }
165 }
166 Conversation conversation = message.getConversation();
167 conversation.getMessages().add(message);
168 if (packet.getType() != MessagePacket.TYPE_ERROR) {
169 databaseBackend.createMessage(message);
170 }
171 if (convChangedListener != null) {
172 convChangedListener.onConversationListChanged();
173 } else {
174 UIHelper.updateNotification(getApplicationContext(), getConversations(), notify);
175 }
176 }
177 };
178 private OnStatusChanged statusListener = new OnStatusChanged() {
179
180 @Override
181 public void onStatusChanged(Account account) {
182 if (accountChangedListener != null) {
183 accountChangedListener.onAccountListChangedListener();
184 }
185 if (account.getStatus() == Account.STATUS_ONLINE) {
186 databaseBackend.clearPresences(account);
187 if (account.getXmppConnection().hasFeatureRosterManagment()) {
188 updateRoster(account, null);
189 }
190 connectMultiModeConversations(account);
191 List<Conversation> conversations = getConversations();
192 for (int i = 0; i < conversations.size(); ++i) {
193 if (conversations.get(i).getAccount() == account) {
194 sendUnsendMessages(conversations.get(i));
195 }
196 }
197 if (convChangedListener != null) {
198 convChangedListener.onConversationListChanged();
199 }
200 scheduleWakeupCall(PING_INTERVAL, true);
201 } else if (account.getStatus() == Account.STATUS_OFFLINE) {
202 Log.d(LOGTAG,"onStatusChanged offline");
203 databaseBackend.clearPresences(account);
204 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
205 int timeToReconnect = mRandom.nextInt(50)+10;
206 scheduleWakeupCall(timeToReconnect,false);
207 }
208
209 }
210 }
211 };
212
213 private OnPresencePacketReceived presenceListener = new OnPresencePacketReceived() {
214
215 @Override
216 public void onPresencePacketReceived(Account account,
217 PresencePacket packet) {
218 if (packet.hasChild("x")&&(packet.findChild("x").getAttribute("xmlns").startsWith("http://jabber.org/protocol/muc"))) {
219 Conversation muc = findMuc(packet.getAttribute("from").split("/")[0]);
220 if (muc!=null) {
221 int error = muc.getMucOptions().getError();
222 muc.getMucOptions().processPacket(packet);
223 if ((muc.getMucOptions().getError()!=error)&&(convChangedListener!=null)) {
224 Log.d(LOGTAG,"muc error status changed");
225 convChangedListener.onConversationListChanged();
226 }
227 }
228 } else {
229 String[] fromParts = packet.getAttribute("from").split("/");
230 Contact contact = findContact(account, fromParts[0]);
231 if (contact == null) {
232 // most likely self or roster not synced
233 return;
234 }
235 String type = packet.getAttribute("type");
236 if (type == null) {
237 Element show = packet.findChild("show");
238 if (show == null) {
239 contact.updatePresence(fromParts[1], Presences.ONLINE);
240 } else if (show.getContent().equals("away")) {
241 contact.updatePresence(fromParts[1], Presences.AWAY);
242 } else if (show.getContent().equals("xa")) {
243 contact.updatePresence(fromParts[1], Presences.XA);
244 } else if (show.getContent().equals("chat")) {
245 contact.updatePresence(fromParts[1], Presences.CHAT);
246 } else if (show.getContent().equals("dnd")) {
247 contact.updatePresence(fromParts[1], Presences.DND);
248 }
249 PgpEngine pgp = getPgpEngine();
250 if (pgp!=null) {
251 Element x = packet.findChild("x");
252 if ((x != null)
253 && (x.getAttribute("xmlns").equals("jabber:x:signed"))) {
254 try {
255 contact.setPgpKeyId(pgp.fetchKeyId(packet.findChild("status")
256 .getContent(), x.getContent()));
257 } catch (OpenPgpException e) {
258 Log.d(LOGTAG,"faulty pgp. just ignore");
259 }
260 }
261 }
262 databaseBackend.updateContact(contact);
263 } else if (type.equals("unavailable")) {
264 if (fromParts.length != 2) {
265 // Log.d(LOGTAG,"received presence with no resource "+packet.toString());
266 } else {
267 contact.removePresence(fromParts[1]);
268 databaseBackend.updateContact(contact);
269 }
270 } else if (type.equals("subscribe")) {
271 if (contact
272 .getSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT)) {
273 sendPresenceUpdatesTo(contact);
274 contact.setSubscriptionOption(Contact.Subscription.FROM);
275 contact.resetSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
276 replaceContactInConversation(contact.getJid(), contact);
277 databaseBackend.updateContact(contact);
278 if ((contact
279 .getSubscriptionOption(Contact.Subscription.ASKING))
280 && (!contact
281 .getSubscriptionOption(Contact.Subscription.TO))) {
282 requestPresenceUpdatesFrom(contact);
283 }
284 } else {
285 // TODO: ask user to handle it maybe
286 }
287 } else {
288 Log.d(LOGTAG, packet.toString());
289 }
290 replaceContactInConversation(contact.getJid(), contact);
291 }
292 }
293 };
294
295 private OnIqPacketReceived unknownIqListener = new OnIqPacketReceived() {
296
297 @Override
298 public void onIqPacketReceived(Account account, IqPacket packet) {
299 if (packet.hasChild("query")) {
300 Element query = packet.findChild("query");
301 String xmlns = query.getAttribute("xmlns");
302 if ((xmlns != null) && (xmlns.equals("jabber:iq:roster"))) {
303 processRosterItems(account, query);
304 mergePhoneContactsWithRoster(null);
305 }
306 }
307 }
308 };
309
310 private OpenPgpServiceConnection pgpServiceConnection;
311 private PgpEngine mPgpEngine = null;
312
313 public PgpEngine getPgpEngine() {
314 if (pgpServiceConnection.isBound()) {
315 if (this.mPgpEngine == null) {
316 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
317 getApplicationContext(),
318 pgpServiceConnection.getService()));
319 }
320 return mPgpEngine;
321 } else {
322 return null;
323 }
324
325 }
326
327 protected Conversation findMuc(String name) {
328 for(Conversation conversation : this.conversations) {
329 if (conversation.getContactJid().split("/")[0].equals(name)) {
330 return conversation;
331 }
332 }
333 return null;
334 }
335
336 private void processRosterItems(Account account, Element elements) {
337 String version = elements.getAttribute("ver");
338 if (version != null) {
339 account.setRosterVersion(version);
340 databaseBackend.updateAccount(account);
341 }
342 for (Element item : elements.getChildren()) {
343 if (item.getName().equals("item")) {
344 String jid = item.getAttribute("jid");
345 String subscription = item.getAttribute("subscription");
346 Contact contact = databaseBackend.findContact(account, jid);
347 if (contact == null) {
348 if (!subscription.equals("remove")) {
349 String name = item.getAttribute("name");
350 if (name == null) {
351 name = jid.split("@")[0];
352 }
353 contact = new Contact(account, name, jid, null);
354 contact.parseSubscriptionFromElement(item);
355 databaseBackend.createContact(contact);
356 }
357 } else {
358 if (subscription.equals("remove")) {
359 databaseBackend.deleteContact(contact);
360 replaceContactInConversation(contact.getJid(), null);
361 } else {
362 contact.parseSubscriptionFromElement(item);
363 databaseBackend.updateContact(contact);
364 replaceContactInConversation(contact.getJid(), contact);
365 }
366 }
367 }
368 }
369 }
370
371 private void replaceContactInConversation(String jid, Contact contact) {
372 List<Conversation> conversations = getConversations();
373 for (int i = 0; i < conversations.size(); ++i) {
374 if ((conversations.get(i).getContactJid().equals(jid))) {
375 conversations.get(i).setContact(contact);
376 break;
377 }
378 }
379 }
380
381 public class XmppConnectionBinder extends Binder {
382 public XmppConnectionService getService() {
383 return XmppConnectionService.this;
384 }
385 }
386
387 @Override
388 public int onStartCommand(Intent intent, int flags, int startId) {
389 ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
390
391 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
392 boolean isConnected = activeNetwork != null
393 && activeNetwork.isConnected();
394 for (Account account : accounts) {
395 if (!isConnected) {
396 account.setStatus(Account.STATUS_NO_INTERNET);
397 } else {
398 if (account.getStatus() == Account.STATUS_NO_INTERNET) {
399 account.setStatus(Account.STATUS_OFFLINE);
400 }
401 }
402 if (accountChangedListener!=null) {
403 accountChangedListener.onAccountListChangedListener();
404 }
405 if ((!account.isOptionSet(Account.OPTION_DISABLED))&&(isConnected)) {
406 if (account.getXmppConnection() == null) {
407 account.setXmppConnection(this.createConnection(account));
408 }
409 if (account.getStatus()==Account.STATUS_OFFLINE) {
410 Thread thread = new Thread(account.getXmppConnection());
411 thread.start();
412 } else {
413 if (intent.getBooleanExtra("ping", false)) {
414 Log.d(LOGTAG,"start service ping");
415 ping(account,PING_TIMEOUT);
416 }
417 }
418 }
419 }
420 return START_STICKY;
421 }
422
423 @Override
424 public void onCreate() {
425 ExceptionHelper.init(getApplicationContext());
426 databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
427 this.accounts = databaseBackend.getAccounts();
428
429 getContentResolver().registerContentObserver(
430 ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
431 this.pgpServiceConnection = new OpenPgpServiceConnection(
432 getApplicationContext(), "org.sufficientlysecure.keychain");
433 this.pgpServiceConnection.bindToService();
434
435
436 }
437
438 @Override
439 public void onDestroy() {
440 super.onDestroy();
441 for (Account account : accounts) {
442 if (account.getXmppConnection() != null) {
443 disconnect(account,true);
444 }
445 }
446 }
447
448 protected void scheduleWakeupCall(int seconds,boolean ping) {
449 Context context = getApplicationContext();
450 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
451 Intent intent = new Intent(context, EventReceiver.class);
452 intent.putExtra("ping", ping);
453 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
454 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
455 SystemClock.elapsedRealtime() +
456 seconds * 1000, alarmIntent);
457 if (ping) {
458 Log.d(LOGTAG,"schedule ping in "+seconds+" seconds");
459 } else {
460 Log.d(LOGTAG,"schedule reconnect in "+seconds+" seconds");
461 }
462
463 }
464
465 public XmppConnection createConnection(Account account) {
466 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
467 XmppConnection connection = new XmppConnection(account, pm);
468 connection.setOnMessagePacketReceivedListener(this.messageListener);
469 connection.setOnStatusChangedListener(this.statusListener);
470 connection.setOnPresencePacketReceivedListener(this.presenceListener);
471 connection
472 .setOnUnregisteredIqPacketReceivedListener(this.unknownIqListener);
473 connection.setOnTLSExceptionReceivedListener(new OnTLSExceptionReceived() {
474
475 @Override
476 public void onTLSExceptionReceived(String fingerprint, Account account) {
477 Log.d(LOGTAG,"tls exception arrived in service");
478 if (tlsException!=null) {
479 tlsException.onTLSExceptionReceived(fingerprint,account);
480 }
481 }
482 });
483 return connection;
484 }
485
486 public void sendMessage(Message message, String presence) {
487 Account account = message.getConversation().getAccount();
488 Conversation conv = message.getConversation();
489 boolean saveInDb = false;
490 boolean addToConversation = false;
491 if (account.getStatus() == Account.STATUS_ONLINE) {
492 MessagePacket packet;
493 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
494 if (!conv.hasValidOtrSession()) {
495 // starting otr session. messages will be send later
496 conv.startOtrSession(getApplicationContext(), presence);
497 } else if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
498 // otr session aleary exists, creating message packet
499 // accordingly
500 packet = prepareMessagePacket(account, message,
501 conv.getOtrSession());
502 account.getXmppConnection().sendMessagePacket(packet);
503 message.setStatus(Message.STATUS_SEND);
504 }
505 saveInDb = true;
506 addToConversation = true;
507 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
508 long keyId = message.getConversation().getContact()
509 .getPgpKeyId();
510 packet = new MessagePacket();
511 packet.setType(MessagePacket.TYPE_CHAT);
512 packet.setFrom(message.getConversation().getAccount()
513 .getFullJid());
514 packet.setTo(message.getCounterpart());
515 packet.setBody("This is an XEP-0027 encryted message");
516 Element x = new Element("x");
517 x.setAttribute("xmlns", "jabber:x:encrypted");
518 x.setContent(this.getPgpEngine().encrypt(keyId,
519 message.getBody()));
520 packet.addChild(x);
521 account.getXmppConnection().sendMessagePacket(packet);
522 message.setStatus(Message.STATUS_SEND);
523 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
524 saveInDb = true;
525 addToConversation = true;
526 } else {
527 // don't encrypt
528 if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
529 message.setStatus(Message.STATUS_SEND);
530 saveInDb = true;
531 addToConversation = true;
532 }
533
534 packet = prepareMessagePacket(account, message, null);
535 account.getXmppConnection().sendMessagePacket(packet);
536 }
537 } else {
538 // account is offline
539 saveInDb = true;
540 addToConversation = true;
541
542 }
543 if (saveInDb) {
544 databaseBackend.createMessage(message);
545 }
546 if (addToConversation) {
547 conv.getMessages().add(message);
548 if (convChangedListener != null) {
549 convChangedListener.onConversationListChanged();
550 }
551 }
552
553 }
554
555 private void sendUnsendMessages(Conversation conversation) {
556 for (int i = 0; i < conversation.getMessages().size(); ++i) {
557 if (conversation.getMessages().get(i).getStatus() == Message.STATUS_UNSEND) {
558 Message message = conversation.getMessages().get(i);
559 MessagePacket packet = prepareMessagePacket(
560 conversation.getAccount(), message, null);
561 conversation.getAccount().getXmppConnection()
562 .sendMessagePacket(packet);
563 message.setStatus(Message.STATUS_SEND);
564 if (conversation.getMode() == Conversation.MODE_SINGLE) {
565 databaseBackend.updateMessage(message);
566 } else {
567 databaseBackend.deleteMessage(message);
568 conversation.getMessages().remove(i);
569 i--;
570 }
571 }
572 }
573 }
574
575 public MessagePacket prepareMessagePacket(Account account, Message message,
576 Session otrSession) {
577 MessagePacket packet = new MessagePacket();
578 if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
579 packet.setType(MessagePacket.TYPE_CHAT);
580 if (otrSession != null) {
581 try {
582 packet.setBody(otrSession.transformSending(message
583 .getBody()));
584 } catch (OtrException e) {
585 Log.d(LOGTAG,
586 account.getJid()
587 + ": could not encrypt message to "
588 + message.getCounterpart());
589 }
590 Element privateMarker = new Element("private");
591 privateMarker.setAttribute("xmlns", "urn:xmpp:carbons:2");
592 packet.addChild(privateMarker);
593 packet.setTo(otrSession.getSessionID().getAccountID() + "/"
594 + otrSession.getSessionID().getUserID());
595 packet.setFrom(account.getFullJid());
596 } else {
597 packet.setBody(message.getBody());
598 packet.setTo(message.getCounterpart());
599 packet.setFrom(account.getJid());
600 }
601 } else if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
602 packet.setType(MessagePacket.TYPE_GROUPCHAT);
603 packet.setBody(message.getBody());
604 packet.setTo(message.getCounterpart().split("/")[0]);
605 packet.setFrom(account.getJid());
606 }
607 return packet;
608 }
609
610 public void getRoster(Account account,
611 final OnRosterFetchedListener listener) {
612 List<Contact> contacts = databaseBackend.getContactsByAccount(account);
613 for (int i = 0; i < contacts.size(); ++i) {
614 contacts.get(i).setAccount(account);
615 }
616 if (listener != null) {
617 listener.onRosterFetched(contacts);
618 }
619 }
620
621 public void updateRoster(final Account account,
622 final OnRosterFetchedListener listener) {
623 IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
624 Element query = new Element("query");
625 query.setAttribute("xmlns", "jabber:iq:roster");
626 if (!"".equals(account.getRosterVersion())) {
627 Log.d(LOGTAG,account.getJid()+ ": fetching roster version "+account.getRosterVersion());
628 } else {
629 Log.d(LOGTAG,account.getJid()+": fetching roster");
630 }
631 query.setAttribute("ver", account.getRosterVersion());
632 iqPacket.addChild(query);
633 account.getXmppConnection().sendIqPacket(iqPacket,
634 new OnIqPacketReceived() {
635
636 @Override
637 public void onIqPacketReceived(final Account account,
638 IqPacket packet) {
639 Element roster = packet.findChild("query");
640 if (roster != null) {
641 Log.d(LOGTAG,account.getJid()+": processing roster");
642 processRosterItems(account, roster);
643 StringBuilder mWhere = new StringBuilder();
644 mWhere.append("jid NOT IN(");
645 List<Element> items = roster.getChildren();
646 for (int i = 0; i < items.size(); ++i) {
647 mWhere.append(DatabaseUtils
648 .sqlEscapeString(items.get(i)
649 .getAttribute("jid")));
650 if (i != items.size() - 1) {
651 mWhere.append(",");
652 }
653 }
654 mWhere.append(") and accountUuid = \"");
655 mWhere.append(account.getUuid());
656 mWhere.append("\"");
657 List<Contact> contactsToDelete = databaseBackend
658 .getContacts(mWhere.toString());
659 for (Contact contact : contactsToDelete) {
660 databaseBackend.deleteContact(contact);
661 replaceContactInConversation(contact.getJid(),
662 null);
663 }
664
665 } else {
666 Log.d(LOGTAG,account.getJid()+": empty roster returend");
667 }
668 mergePhoneContactsWithRoster(new OnPhoneContactsMerged() {
669
670 @Override
671 public void phoneContactsMerged() {
672 if (listener != null) {
673 getRoster(account, listener);
674 }
675 }
676 });
677 }
678 });
679 }
680
681 public void mergePhoneContactsWithRoster(
682 final OnPhoneContactsMerged listener) {
683 PhoneHelper.loadPhoneContacts(getApplicationContext(),
684 new OnPhoneContactsLoadedListener() {
685 @Override
686 public void onPhoneContactsLoaded(
687 Hashtable<String, Bundle> phoneContacts) {
688 List<Contact> contacts = databaseBackend
689 .getContactsByAccount(null);
690 for (int i = 0; i < contacts.size(); ++i) {
691 Contact contact = contacts.get(i);
692 if (phoneContacts.containsKey(contact.getJid())) {
693 Bundle phoneContact = phoneContacts.get(contact
694 .getJid());
695 String systemAccount = phoneContact
696 .getInt("phoneid")
697 + "#"
698 + phoneContact.getString("lookup");
699 contact.setSystemAccount(systemAccount);
700 contact.setPhotoUri(phoneContact
701 .getString("photouri"));
702 contact.setDisplayName(phoneContact
703 .getString("displayname"));
704 databaseBackend.updateContact(contact);
705 replaceContactInConversation(contact.getJid(),
706 contact);
707 } else {
708 if ((contact.getSystemAccount() != null)
709 || (contact.getProfilePhoto() != null)) {
710 contact.setSystemAccount(null);
711 contact.setPhotoUri(null);
712 databaseBackend.updateContact(contact);
713 replaceContactInConversation(
714 contact.getJid(), contact);
715 }
716 }
717 }
718 if (listener != null) {
719 listener.phoneContactsMerged();
720 }
721 }
722 });
723 }
724
725 public List<Conversation> getConversations() {
726 if (this.conversations == null) {
727 Hashtable<String, Account> accountLookupTable = new Hashtable<String, Account>();
728 for (Account account : this.accounts) {
729 accountLookupTable.put(account.getUuid(), account);
730 }
731 this.conversations = databaseBackend
732 .getConversations(Conversation.STATUS_AVAILABLE);
733 for (Conversation conv : this.conversations) {
734 Account account = accountLookupTable.get(conv.getAccountUuid());
735 conv.setAccount(account);
736 conv.setContact(findContact(account, conv.getContactJid()));
737 conv.setMessages(databaseBackend.getMessages(conv, 50));
738 }
739 }
740 return this.conversations;
741 }
742
743 public List<Account> getAccounts() {
744 return this.accounts;
745 }
746
747 public Contact findContact(Account account, String jid) {
748 Contact contact = databaseBackend.findContact(account, jid);
749 if (contact != null) {
750 contact.setAccount(account);
751 }
752 return contact;
753 }
754
755 public Conversation findOrCreateConversation(Account account, String jid,
756 boolean muc) {
757 for (Conversation conv : this.getConversations()) {
758 if ((conv.getAccount().equals(account))
759 && (conv.getContactJid().split("/")[0].equals(jid))) {
760 return conv;
761 }
762 }
763 Conversation conversation = databaseBackend.findConversation(account,
764 jid);
765 if (conversation != null) {
766 conversation.setStatus(Conversation.STATUS_AVAILABLE);
767 conversation.setAccount(account);
768 if (muc) {
769 conversation.setMode(Conversation.MODE_MULTI);
770 if (account.getStatus() == Account.STATUS_ONLINE) {
771 joinMuc(conversation);
772 }
773 } else {
774 conversation.setMode(Conversation.MODE_SINGLE);
775 }
776 this.databaseBackend.updateConversation(conversation);
777 conversation.setContact(findContact(account,
778 conversation.getContactJid()));
779 } else {
780 String conversationName;
781 Contact contact = findContact(account, jid);
782 if (contact != null) {
783 conversationName = contact.getDisplayName();
784 } else {
785 conversationName = jid.split("@")[0];
786 }
787 if (muc) {
788 conversation = new Conversation(conversationName, account, jid,
789 Conversation.MODE_MULTI);
790 if (account.getStatus() == Account.STATUS_ONLINE) {
791 joinMuc(conversation);
792 }
793 } else {
794 conversation = new Conversation(conversationName, account, jid,
795 Conversation.MODE_SINGLE);
796 }
797 conversation.setContact(contact);
798 this.databaseBackend.createConversation(conversation);
799 }
800 this.conversations.add(conversation);
801 if (this.convChangedListener != null) {
802 this.convChangedListener.onConversationListChanged();
803 }
804 return conversation;
805 }
806
807 public void archiveConversation(Conversation conversation) {
808 if (conversation.getMode() == Conversation.MODE_MULTI) {
809 leaveMuc(conversation);
810 } else {
811 try {
812 conversation.endOtrIfNeeded();
813 } catch (OtrException e) {
814 Log.d(LOGTAG,
815 "error ending otr session for "
816 + conversation.getName());
817 }
818 }
819 this.databaseBackend.updateConversation(conversation);
820 this.conversations.remove(conversation);
821 if (this.convChangedListener != null) {
822 this.convChangedListener.onConversationListChanged();
823 }
824 }
825
826 public int getConversationCount() {
827 return this.databaseBackend.getConversationCount();
828 }
829
830 public void createAccount(Account account) {
831 databaseBackend.createAccount(account);
832 this.accounts.add(account);
833 account.setXmppConnection(this.createConnection(account));
834 if (accountChangedListener != null)
835 accountChangedListener.onAccountListChangedListener();
836 }
837
838 public void deleteContact(Contact contact) {
839 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
840 Element query = new Element("query");
841 query.setAttribute("xmlns", "jabber:iq:roster");
842 Element item = new Element("item");
843 item.setAttribute("jid", contact.getJid());
844 item.setAttribute("subscription", "remove");
845 query.addChild(item);
846 iq.addChild(query);
847 contact.getAccount().getXmppConnection().sendIqPacket(iq, null);
848 replaceContactInConversation(contact.getJid(), null);
849 databaseBackend.deleteContact(contact);
850 }
851
852 public void updateAccount(Account account) {
853 databaseBackend.updateAccount(account);
854 reconnectAccount(account);
855 if (accountChangedListener != null)
856 accountChangedListener.onAccountListChangedListener();
857 }
858
859 public void deleteAccount(Account account) {
860 Log.d(LOGTAG, "called delete account");
861 if (account.getXmppConnection() != null) {
862 this.disconnect(account,false);
863 }
864 databaseBackend.deleteAccount(account);
865 this.accounts.remove(account);
866 if (accountChangedListener != null)
867 accountChangedListener.onAccountListChangedListener();
868 }
869
870 public void setOnConversationListChangedListener(
871 OnConversationListChangedListener listener) {
872 this.convChangedListener = listener;
873 }
874
875 public void removeOnConversationListChangedListener() {
876 this.convChangedListener = null;
877 }
878
879 public void setOnAccountListChangedListener(
880 OnAccountListChangedListener listener) {
881 this.accountChangedListener = listener;
882 }
883
884 public void removeOnAccountListChangedListener() {
885 this.accountChangedListener = null;
886 }
887
888 public void connectMultiModeConversations(Account account) {
889 List<Conversation> conversations = getConversations();
890 for (int i = 0; i < conversations.size(); i++) {
891 Conversation conversation = conversations.get(i);
892 if ((conversation.getMode() == Conversation.MODE_MULTI)
893 && (conversation.getAccount() == account)) {
894 joinMuc(conversation);
895 }
896 }
897 }
898
899 public void joinMuc(Conversation conversation) {
900 String[] mucParts = conversation.getContactJid().split("/");
901 String muc;
902 String nick;
903 if (mucParts.length == 2) {
904 muc = mucParts[0];
905 nick = mucParts[1];
906 } else {
907 muc = mucParts[0];
908 nick = conversation.getAccount().getUsername();
909 }
910 PresencePacket packet = new PresencePacket();
911 packet.setAttribute("to", muc + "/"
912 + nick);
913 Element x = new Element("x");
914 x.setAttribute("xmlns", "http://jabber.org/protocol/muc");
915 if (conversation.getMessages().size() != 0) {
916 Element history = new Element("history");
917 long lastMsgTime = conversation.getLatestMessage().getTimeSent();
918 long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
919 history.setAttribute("seconds", diff + "");
920 x.addChild(history);
921 }
922 packet.addChild(x);
923 conversation.getAccount().getXmppConnection()
924 .sendPresencePacket(packet);
925 }
926
927 private OnRenameListener renameListener = null;
928 private boolean pongReceived;
929 public void setOnRenameListener(OnRenameListener listener) {
930 this.renameListener = listener;
931 }
932
933 public void renameInMuc(final Conversation conversation, final String nick) {
934 final MucOptions options = conversation.getMucOptions();
935 if (options.online()) {
936 options.setOnRenameListener(new OnRenameListener() {
937
938 @Override
939 public void onRename(boolean success) {
940 if (renameListener!=null) {
941 renameListener.onRename(success);
942 }
943 if (success) {
944 databaseBackend.updateConversation(conversation);
945 }
946 }
947 });
948 PresencePacket packet = new PresencePacket();
949 packet.setAttribute("to", conversation.getContactJid().split("/")[0]+"/"+nick);
950 packet.setAttribute("from", conversation.getAccount().getFullJid());
951
952 conversation.getAccount().getXmppConnection().sendPresencePacket(packet, new OnPresencePacketReceived() {
953
954 @Override
955 public void onPresencePacketReceived(Account account, PresencePacket packet) {
956 final boolean changed;
957 String type = packet.getAttribute("type");
958 changed = (!"error".equals(type));
959 if (!changed) {
960 options.getOnRenameListener().onRename(false);
961 } else {
962 if (type==null) {
963 options.getOnRenameListener().onRename(true);
964 options.setNick(packet.getAttribute("from").split("/")[1]);
965 } else {
966 options.processPacket(packet);
967 }
968 }
969 }
970 });
971 } else {
972 String jid = conversation.getContactJid().split("/")[0]+"/"+nick;
973 conversation.setContactJid(jid);
974 databaseBackend.updateConversation(conversation);
975 if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
976 joinMuc(conversation);
977 }
978 }
979 }
980
981 public void leaveMuc(Conversation conversation) {
982 PresencePacket packet = new PresencePacket();
983 packet.setAttribute("to", conversation.getContactJid());
984 packet.setAttribute("from", conversation.getAccount().getFullJid());
985 packet.setAttribute("type","unavailable");
986 conversation.getAccount().getXmppConnection().sendPresencePacket(packet);
987 conversation.getMucOptions().setOffline();
988 }
989
990 public void disconnect(final Account account, boolean blocking) {
991 List<Conversation> conversations = getConversations();
992 for (int i = 0; i < conversations.size(); i++) {
993 Conversation conversation = conversations.get(i);
994 if (conversation.getAccount() == account) {
995 if (conversation.getMode() == Conversation.MODE_MULTI) {
996 leaveMuc(conversation);
997 } else {
998 try {
999 conversation.endOtrIfNeeded();
1000 } catch (OtrException e) {
1001 Log.d(LOGTAG, "error ending otr session for "
1002 + conversation.getName());
1003 }
1004 }
1005 }
1006 }
1007 if (!blocking) {
1008 new Thread(new Runnable() {
1009
1010 @Override
1011 public void run() {
1012 account.getXmppConnection().disconnect(false);
1013 Log.d(LOGTAG, "disconnected account: " + account.getJid());
1014 account.setXmppConnection(null);
1015 }
1016 }).start();
1017 } else {
1018 account.getXmppConnection().disconnect(false);
1019 Log.d(LOGTAG, "disconnected account: " + account.getJid());
1020 account.setXmppConnection(null);
1021 }
1022 }
1023
1024 @Override
1025 public IBinder onBind(Intent intent) {
1026 return mBinder;
1027 }
1028
1029 public void updateContact(Contact contact) {
1030 databaseBackend.updateContact(contact);
1031 replaceContactInConversation(contact.getJid(), contact);
1032 }
1033
1034 public void updateMessage(Message message) {
1035 databaseBackend.updateMessage(message);
1036 }
1037
1038 public void createContact(Contact contact) {
1039 SharedPreferences sharedPref = PreferenceManager
1040 .getDefaultSharedPreferences(getApplicationContext());
1041 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1042 if (autoGrant) {
1043 contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
1044 contact.setSubscriptionOption(Contact.Subscription.ASKING);
1045 }
1046 databaseBackend.createContact(contact);
1047 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1048 Element query = new Element("query");
1049 query.setAttribute("xmlns", "jabber:iq:roster");
1050 Element item = new Element("item");
1051 item.setAttribute("jid", contact.getJid());
1052 item.setAttribute("name", contact.getJid());
1053 query.addChild(item);
1054 iq.addChild(query);
1055 Account account = contact.getAccount();
1056 account.getXmppConnection().sendIqPacket(iq, null);
1057 if (autoGrant) {
1058 requestPresenceUpdatesFrom(contact);
1059 }
1060 replaceContactInConversation(contact.getJid(), contact);
1061 }
1062
1063 public void requestPresenceUpdatesFrom(Contact contact) {
1064 // Requesting a Subscription type=subscribe
1065 PresencePacket packet = new PresencePacket();
1066 packet.setAttribute("type", "subscribe");
1067 packet.setAttribute("to", contact.getJid());
1068 packet.setAttribute("from", contact.getAccount().getJid());
1069 Log.d(LOGTAG, packet.toString());
1070 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1071 }
1072
1073 public void stopPresenceUpdatesFrom(Contact contact) {
1074 // Unsubscribing type='unsubscribe'
1075 PresencePacket packet = new PresencePacket();
1076 packet.setAttribute("type", "unsubscribe");
1077 packet.setAttribute("to", contact.getJid());
1078 packet.setAttribute("from", contact.getAccount().getJid());
1079 Log.d(LOGTAG, packet.toString());
1080 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1081 }
1082
1083 public void stopPresenceUpdatesTo(Contact contact) {
1084 // Canceling a Subscription type=unsubscribed
1085 PresencePacket packet = new PresencePacket();
1086 packet.setAttribute("type", "unsubscribed");
1087 packet.setAttribute("to", contact.getJid());
1088 packet.setAttribute("from", contact.getAccount().getJid());
1089 Log.d(LOGTAG, packet.toString());
1090 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1091 }
1092
1093 public void sendPresenceUpdatesTo(Contact contact) {
1094 // type='subscribed'
1095 PresencePacket packet = new PresencePacket();
1096 packet.setAttribute("type", "subscribed");
1097 packet.setAttribute("to", contact.getJid());
1098 packet.setAttribute("from", contact.getAccount().getJid());
1099 Log.d(LOGTAG, packet.toString());
1100 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1101 }
1102
1103 public void sendPgpPresence(Account account, String signature) {
1104 PresencePacket packet = new PresencePacket();
1105 packet.setAttribute("from", account.getFullJid());
1106 Element status = new Element("status");
1107 status.setContent("online");
1108 packet.addChild(status);
1109 Element x = new Element("x");
1110 x.setAttribute("xmlns", "jabber:x:signed");
1111 x.setContent(signature);
1112 packet.addChild(x);
1113 account.getXmppConnection().sendPresencePacket(packet);
1114 }
1115
1116 public void generatePgpAnnouncement(Account account)
1117 throws PgpEngine.UserInputRequiredException {
1118 if (account.getStatus() == Account.STATUS_ONLINE) {
1119 String signature = getPgpEngine().generateSignature("online");
1120 account.setKey("pgp_signature", signature);
1121 databaseBackend.updateAccount(account);
1122 sendPgpPresence(account, signature);
1123 }
1124 }
1125
1126 public void updateConversation(Conversation conversation) {
1127 this.databaseBackend.updateConversation(conversation);
1128 }
1129
1130 public Contact findContact(String uuid) {
1131 Contact contact = this.databaseBackend.getContact(uuid);
1132 for(Account account : getAccounts()) {
1133 if (contact.getAccountUuid().equals(account.getUuid())) {
1134 contact.setAccount(account);
1135 }
1136 }
1137 return contact;
1138 }
1139
1140 public void removeOnTLSExceptionReceivedListener() {
1141 this.tlsException = null;
1142 }
1143
1144 public void reconnectAccount(final Account account) {
1145 new Thread(new Runnable() {
1146
1147 @Override
1148 public void run() {
1149 if (account.getXmppConnection() != null) {
1150 disconnect(account,true);
1151 }
1152 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1153 if (account.getXmppConnection()==null) {
1154 account.setXmppConnection(createConnection(account));
1155 }
1156 Thread thread = new Thread(account.getXmppConnection());
1157 thread.start();
1158 }
1159 }
1160 }).start();
1161 }
1162
1163 public void ping(final Account account,final int timeout) {
1164 account.getXmppConnection().r();
1165 Log.d(LOGTAG,account.getJid()+": sending ping");
1166 IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
1167 Element ping = new Element("ping");
1168 iq.setAttribute("from",account.getFullJid());
1169 ping.setAttribute("xmlns", "urn:xmpp:ping");
1170 iq.addChild(ping);
1171 pongReceived = false;
1172 account.getXmppConnection().sendIqPacket(iq, new OnIqPacketReceived() {
1173
1174 @Override
1175 public void onIqPacketReceived(Account account, IqPacket packet) {
1176 pongReceived = true;
1177 }
1178 });
1179 new Thread(new Runnable() {
1180
1181 @Override
1182 public void run() {
1183 int i = 0;
1184 while(i <= (5 * timeout)) {
1185 if (pongReceived) {
1186 scheduleWakeupCall(PING_INTERVAL,true);
1187 break;
1188 }
1189 try {
1190 Thread.sleep(200);
1191 } catch (InterruptedException e) {
1192
1193 }
1194 ++i;
1195 }
1196 if (!pongReceived) {
1197 Log.d("xmppService",account.getJid()+" no pong after "+timeout+" seconds");
1198 reconnectAccount(account);
1199 }
1200
1201 }
1202 }).start();
1203 }
1204}