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