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 List<Conversation> conversations = getConversations();
207 for (int i = 0; i < conversations.size(); ++i) {
208 if (conversations.get(i).getAccount() == account) {
209 sendUnsendMessages(conversations.get(i));
210 }
211 }
212 scheduleWakeupCall(PING_MAX_INTERVAL, true);
213 } else if (account.getStatus() == Account.STATUS_OFFLINE) {
214 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
215 int timeToReconnect = mRandom.nextInt(50) + 10;
216 scheduleWakeupCall(timeToReconnect, false);
217 }
218
219 } else if (account.getStatus() == Account.STATUS_REGISTRATION_SUCCESSFULL) {
220 databaseBackend.updateAccount(account);
221 reconnectAccount(account, true);
222 }
223 }
224 };
225
226 private OnPresencePacketReceived presenceListener = new OnPresencePacketReceived() {
227
228 @Override
229 public void onPresencePacketReceived(Account account,
230 PresencePacket packet) {
231 if (packet.hasChild("x")
232 && (packet.findChild("x").getAttribute("xmlns")
233 .startsWith("http://jabber.org/protocol/muc"))) {
234 Conversation muc = findMuc(
235 packet.getAttribute("from").split("/")[0], account);
236 if (muc != null) {
237 int error = muc.getMucOptions().getError();
238 muc.getMucOptions().processPacket(packet);
239 if ((muc.getMucOptions().getError() != error)
240 && (convChangedListener != null)) {
241 Log.d(LOGTAG, "muc error status changed");
242 convChangedListener.onConversationListChanged();
243 }
244 }
245 } else {
246 String[] fromParts = packet.getAttribute("from").split("/");
247 String type = packet.getAttribute("type");
248 if (fromParts[0].equals(account.getJid())) {
249 if (fromParts.length==2) {
250 if (type == null) {
251 account.updatePresence(fromParts[1],Presences.parseShow(packet.findChild("show")));
252 } else if (type.equals("unavailable")) {
253 account.removePresence(fromParts[1]);
254 }
255 }
256
257 } else {
258 Contact contact = findContact(account, fromParts[0]);
259 if (contact == null) {
260 // most likely roster not synced
261 return;
262 }
263 if (type == null) {
264 if (fromParts.length == 2) {
265 contact.updatePresence(fromParts[1], Presences.parseShow(packet.findChild("show")));
266 PgpEngine pgp = getPgpEngine();
267 if (pgp != null) {
268 Element x = packet.findChild("x");
269 if ((x != null)
270 && (x.getAttribute("xmlns")
271 .equals("jabber:x:signed"))) {
272 try {
273 contact.setPgpKeyId(pgp.fetchKeyId(
274 packet.findChild("status")
275 .getContent(), x
276 .getContent()));
277 } catch (OpenPgpException e) {
278 Log.d(LOGTAG, "faulty pgp. just ignore");
279 }
280 }
281 }
282 databaseBackend.updateContact(contact);
283 } else {
284 // Log.d(LOGTAG,"presence without resource "+packet.toString());
285 }
286 } else if (type.equals("unavailable")) {
287 if (fromParts.length != 2) {
288 // Log.d(LOGTAG,"received presence with no resource "+packet.toString());
289 } else {
290 contact.removePresence(fromParts[1]);
291 databaseBackend.updateContact(contact);
292 }
293 } else if (type.equals("subscribe")) {
294 if (contact
295 .getSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT)) {
296 sendPresenceUpdatesTo(contact);
297 contact.setSubscriptionOption(Contact.Subscription.FROM);
298 contact.resetSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
299 replaceContactInConversation(contact.getJid(),
300 contact);
301 databaseBackend.updateContact(contact);
302 if ((contact
303 .getSubscriptionOption(Contact.Subscription.ASKING))
304 && (!contact
305 .getSubscriptionOption(Contact.Subscription.TO))) {
306 requestPresenceUpdatesFrom(contact);
307 }
308 } else {
309 // TODO: ask user to handle it maybe
310 }
311 } else {
312 // Log.d(LOGTAG, packet.toString());
313 }
314 replaceContactInConversation(contact.getJid(), contact);
315 }
316 }
317 }
318 };
319
320 private OnIqPacketReceived unknownIqListener = new OnIqPacketReceived() {
321
322 @Override
323 public void onIqPacketReceived(Account account, IqPacket packet) {
324 if (packet.hasChild("query")) {
325 Element query = packet.findChild("query");
326 String xmlns = query.getAttribute("xmlns");
327 if ((xmlns != null) && (xmlns.equals("jabber:iq:roster"))) {
328 processRosterItems(account, query);
329 mergePhoneContactsWithRoster(null);
330 }
331 }
332 }
333 };
334
335 private OpenPgpServiceConnection pgpServiceConnection;
336 private PgpEngine mPgpEngine = null;
337 private Intent pingIntent;
338 private PendingIntent pendingPingIntent = null;
339
340 public PgpEngine getPgpEngine() {
341 if (pgpServiceConnection.isBound()) {
342 if (this.mPgpEngine == null) {
343 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
344 getApplicationContext(),
345 pgpServiceConnection.getService()));
346 }
347 return mPgpEngine;
348 } else {
349 return null;
350 }
351
352 }
353
354 protected Conversation findMuc(String name, Account account) {
355 for (Conversation conversation : this.conversations) {
356 if (conversation.getContactJid().split("/")[0].equals(name)
357 && (conversation.getAccount() == account)) {
358 return conversation;
359 }
360 }
361 return null;
362 }
363
364 private void processRosterItems(Account account, Element elements) {
365 String version = elements.getAttribute("ver");
366 if (version != null) {
367 account.setRosterVersion(version);
368 databaseBackend.updateAccount(account);
369 }
370 for (Element item : elements.getChildren()) {
371 if (item.getName().equals("item")) {
372 String jid = item.getAttribute("jid");
373 String subscription = item.getAttribute("subscription");
374 Contact contact = databaseBackend.findContact(account, jid);
375 if (contact == null) {
376 if (!subscription.equals("remove")) {
377 String name = item.getAttribute("name");
378 if (name == null) {
379 name = jid.split("@")[0];
380 }
381 contact = new Contact(account, name, jid, null);
382 contact.parseSubscriptionFromElement(item);
383 databaseBackend.createContact(contact);
384 }
385 } else {
386 if (subscription.equals("remove")) {
387 databaseBackend.deleteContact(contact);
388 replaceContactInConversation(contact.getJid(), null);
389 } else {
390 contact.parseSubscriptionFromElement(item);
391 databaseBackend.updateContact(contact);
392 replaceContactInConversation(contact.getJid(), contact);
393 }
394 }
395 }
396 }
397 }
398
399 private void replaceContactInConversation(String jid, Contact contact) {
400 List<Conversation> conversations = getConversations();
401 for (int i = 0; i < conversations.size(); ++i) {
402 if ((conversations.get(i).getContactJid().equals(jid))) {
403 conversations.get(i).setContact(contact);
404 break;
405 }
406 }
407 }
408
409 public class XmppConnectionBinder extends Binder {
410 public XmppConnectionService getService() {
411 return XmppConnectionService.this;
412 }
413 }
414
415 @Override
416 public int onStartCommand(Intent intent, int flags, int startId) {
417 // Log.d(LOGTAG,"calling start service. caller was:"+intent.getAction());
418 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
419 .getSystemService(Context.CONNECTIVITY_SERVICE);
420 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
421 boolean isConnected = activeNetwork != null
422 && activeNetwork.isConnected();
423
424 for (Account account : accounts) {
425 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
426 if (!isConnected) {
427 account.setStatus(Account.STATUS_NO_INTERNET);
428 if (statusListener != null) {
429 statusListener.onStatusChanged(account);
430 }
431 } else {
432 if (account.getStatus() == Account.STATUS_NO_INTERNET) {
433 account.setStatus(Account.STATUS_OFFLINE);
434 if (statusListener != null) {
435 statusListener.onStatusChanged(account);
436 }
437 }
438
439 // TODO 3 remaining cases
440 if (account.getStatus() == Account.STATUS_ONLINE) {
441 long lastReceived = account.getXmppConnection().lastPaketReceived;
442 long lastSent = account.getXmppConnection().lastPingSent;
443 if (lastSent - lastReceived >= PING_TIMEOUT * 1000) {
444 Log.d(LOGTAG, account.getJid() + ": ping timeout");
445 this.reconnectAccount(account, true);
446 } else if (SystemClock.elapsedRealtime() - lastReceived >= PING_MIN_INTERVAL * 1000) {
447 account.getXmppConnection().sendPing();
448 account.getXmppConnection().lastPingSent = SystemClock
449 .elapsedRealtime();
450 this.scheduleWakeupCall(2, false);
451 }
452 } else if (account.getStatus() == Account.STATUS_OFFLINE) {
453 if (account.getXmppConnection() == null) {
454 account.setXmppConnection(this
455 .createConnection(account));
456 }
457 account.getXmppConnection().lastPingSent = SystemClock
458 .elapsedRealtime();
459 new Thread(account.getXmppConnection()).start();
460 } else if ((account.getStatus() == Account.STATUS_CONNECTING)
461 && ((SystemClock.elapsedRealtime() - account
462 .getXmppConnection().lastConnect) / 1000 >= CONNECT_TIMEOUT)) {
463 Log.d(LOGTAG, account.getJid()
464 + ": time out during connect reconnecting");
465 reconnectAccount(account, true);
466 } else {
467 Log.d(LOGTAG,
468 "seconds since last connect:"
469 + ((SystemClock.elapsedRealtime() - account
470 .getXmppConnection().lastConnect) / 1000));
471 Log.d(LOGTAG,
472 account.getJid() + ": status="
473 + account.getStatus());
474 // TODO notify user of ssl cert problem or auth problem
475 // or what ever
476 }
477 // in any case. reschedule wakup call
478 this.scheduleWakeupCall(PING_MAX_INTERVAL, true);
479 }
480 if (accountChangedListener != null) {
481 accountChangedListener.onAccountListChangedListener();
482 }
483 }
484 }
485 return START_STICKY;
486 }
487
488 @Override
489 public void onCreate() {
490 ExceptionHelper.init(getApplicationContext());
491 databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
492 this.accounts = databaseBackend.getAccounts();
493
494 getContentResolver().registerContentObserver(
495 ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
496 this.pgpServiceConnection = new OpenPgpServiceConnection(
497 getApplicationContext(), "org.sufficientlysecure.keychain");
498 this.pgpServiceConnection.bindToService();
499
500 }
501
502 @Override
503 public void onDestroy() {
504 super.onDestroy();
505 for (Account account : accounts) {
506 if (account.getXmppConnection() != null) {
507 disconnect(account, true);
508 }
509 }
510 }
511
512 protected void scheduleWakeupCall(int seconds, boolean ping) {
513 long timeToWake = SystemClock.elapsedRealtime() + seconds * 1000;
514 Context context = getApplicationContext();
515 AlarmManager alarmManager = (AlarmManager) context
516 .getSystemService(Context.ALARM_SERVICE);
517
518 if (ping) {
519 if (this.pingIntent == null) {
520 this.pingIntent = new Intent(context, EventReceiver.class);
521 this.pingIntent.setAction("ping");
522 this.pingIntent.putExtra("time", timeToWake);
523 this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
524 this.pingIntent, 0);
525 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
526 timeToWake, pendingPingIntent);
527 // Log.d(LOGTAG,"schedule ping in "+seconds+" seconds");
528 } else {
529 long scheduledTime = this.pingIntent.getLongExtra("time", 0);
530 if (scheduledTime < SystemClock.elapsedRealtime()
531 || (scheduledTime > timeToWake)) {
532 this.pingIntent.putExtra("time", timeToWake);
533 alarmManager.cancel(this.pendingPingIntent);
534 this.pendingPingIntent = PendingIntent.getBroadcast(
535 context, 0, this.pingIntent, 0);
536 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
537 timeToWake, pendingPingIntent);
538 // Log.d(LOGTAG,"reschedule old ping to ping in "+seconds+" seconds");
539 }
540 }
541 } else {
542 Intent intent = new Intent(context, EventReceiver.class);
543 intent.setAction("ping_check");
544 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0,
545 intent, 0);
546 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake,
547 alarmIntent);
548 }
549
550 }
551
552 public XmppConnection createConnection(Account account) {
553 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
554 XmppConnection connection = new XmppConnection(account, pm);
555 connection.setOnMessagePacketReceivedListener(this.messageListener);
556 connection.setOnStatusChangedListener(this.statusListener);
557 connection.setOnPresencePacketReceivedListener(this.presenceListener);
558 connection
559 .setOnUnregisteredIqPacketReceivedListener(this.unknownIqListener);
560 connection
561 .setOnTLSExceptionReceivedListener(new OnTLSExceptionReceived() {
562
563 @Override
564 public void onTLSExceptionReceived(String fingerprint,
565 Account account) {
566 Log.d(LOGTAG, "tls exception arrived in service");
567 if (tlsException != null) {
568 tlsException.onTLSExceptionReceived(fingerprint,
569 account);
570 }
571 }
572 });
573 connection.setOnBindListener(new OnBindListener() {
574
575 @Override
576 public void onBind(Account account) {
577 databaseBackend.clearPresences(account);
578 account.clearPresences(); // self presences
579 if (account.getXmppConnection().hasFeatureRosterManagment()) {
580 updateRoster(account, null);
581 }
582 connectMultiModeConversations(account);
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)&&(conversation.getMessages().get(i).getEncryption() == Message.ENCRYPTION_NONE)) {
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 long lastMsgTime = conversation.getLatestMessage().getTimeSent();
1024 long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
1025 x.addChild("history").setAttribute("seconds", diff + "");
1026 }
1027 packet.addChild(x);
1028 conversation.getAccount().getXmppConnection()
1029 .sendPresencePacket(packet);
1030 }
1031
1032 private OnRenameListener renameListener = null;
1033
1034 public void setOnRenameListener(OnRenameListener listener) {
1035 this.renameListener = listener;
1036 }
1037
1038 public void renameInMuc(final Conversation conversation, final String nick) {
1039 final MucOptions options = conversation.getMucOptions();
1040 if (options.online()) {
1041 options.setOnRenameListener(new OnRenameListener() {
1042
1043 @Override
1044 public void onRename(boolean success) {
1045 if (renameListener != null) {
1046 renameListener.onRename(success);
1047 }
1048 if (success) {
1049 databaseBackend.updateConversation(conversation);
1050 }
1051 }
1052 });
1053 options.flagAboutToRename();
1054 PresencePacket packet = new PresencePacket();
1055 packet.setAttribute("to",
1056 conversation.getContactJid().split("/")[0] + "/" + nick);
1057 packet.setAttribute("from", conversation.getAccount().getFullJid());
1058
1059 conversation.getAccount().getXmppConnection()
1060 .sendPresencePacket(packet, null);
1061 } else {
1062 String jid = conversation.getContactJid().split("/")[0] + "/"
1063 + nick;
1064 conversation.setContactJid(jid);
1065 databaseBackend.updateConversation(conversation);
1066 if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1067 joinMuc(conversation);
1068 }
1069 }
1070 }
1071
1072 public void leaveMuc(Conversation conversation) {
1073 PresencePacket packet = new PresencePacket();
1074 packet.setAttribute("to", conversation.getContactJid());
1075 packet.setAttribute("from", conversation.getAccount().getFullJid());
1076 packet.setAttribute("type", "unavailable");
1077 conversation.getAccount().getXmppConnection()
1078 .sendPresencePacket(packet);
1079 conversation.getMucOptions().setOffline();
1080 }
1081
1082 public void disconnect(Account account, boolean force) {
1083 if ((account.getStatus() == Account.STATUS_ONLINE)
1084 || (account.getStatus() == Account.STATUS_DISABLED)) {
1085 if (!force) {
1086 List<Conversation> conversations = getConversations();
1087 for (int i = 0; i < conversations.size(); i++) {
1088 Conversation conversation = conversations.get(i);
1089 if (conversation.getAccount() == account) {
1090 if (conversation.getMode() == Conversation.MODE_MULTI) {
1091 leaveMuc(conversation);
1092 } else {
1093 conversation.endOtrIfNeeded();
1094 }
1095 }
1096 }
1097 }
1098 account.getXmppConnection().disconnect(force);
1099 }
1100 }
1101
1102 @Override
1103 public IBinder onBind(Intent intent) {
1104 return mBinder;
1105 }
1106
1107 public void updateContact(Contact contact) {
1108 databaseBackend.updateContact(contact);
1109 replaceContactInConversation(contact.getJid(), contact);
1110 }
1111
1112 public void updateMessage(Message message) {
1113 databaseBackend.updateMessage(message);
1114 }
1115
1116 public void createContact(Contact contact) {
1117 SharedPreferences sharedPref = PreferenceManager
1118 .getDefaultSharedPreferences(getApplicationContext());
1119 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1120 if (autoGrant) {
1121 contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
1122 contact.setSubscriptionOption(Contact.Subscription.ASKING);
1123 }
1124 databaseBackend.createContact(contact);
1125 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1126 Element query = new Element("query");
1127 query.setAttribute("xmlns", "jabber:iq:roster");
1128 Element item = new Element("item");
1129 item.setAttribute("jid", contact.getJid());
1130 item.setAttribute("name", contact.getJid());
1131 query.addChild(item);
1132 iq.addChild(query);
1133 Account account = contact.getAccount();
1134 account.getXmppConnection().sendIqPacket(iq, null);
1135 if (autoGrant) {
1136 requestPresenceUpdatesFrom(contact);
1137 }
1138 replaceContactInConversation(contact.getJid(), contact);
1139 }
1140
1141 public void requestPresenceUpdatesFrom(Contact contact) {
1142 // Requesting a Subscription type=subscribe
1143 PresencePacket packet = new PresencePacket();
1144 packet.setAttribute("type", "subscribe");
1145 packet.setAttribute("to", contact.getJid());
1146 packet.setAttribute("from", contact.getAccount().getJid());
1147 Log.d(LOGTAG, packet.toString());
1148 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1149 }
1150
1151 public void stopPresenceUpdatesFrom(Contact contact) {
1152 // Unsubscribing type='unsubscribe'
1153 PresencePacket packet = new PresencePacket();
1154 packet.setAttribute("type", "unsubscribe");
1155 packet.setAttribute("to", contact.getJid());
1156 packet.setAttribute("from", contact.getAccount().getJid());
1157 Log.d(LOGTAG, packet.toString());
1158 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1159 }
1160
1161 public void stopPresenceUpdatesTo(Contact contact) {
1162 // Canceling a Subscription type=unsubscribed
1163 PresencePacket packet = new PresencePacket();
1164 packet.setAttribute("type", "unsubscribed");
1165 packet.setAttribute("to", contact.getJid());
1166 packet.setAttribute("from", contact.getAccount().getJid());
1167 Log.d(LOGTAG, packet.toString());
1168 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1169 }
1170
1171 public void sendPresenceUpdatesTo(Contact contact) {
1172 // type='subscribed'
1173 PresencePacket packet = new PresencePacket();
1174 packet.setAttribute("type", "subscribed");
1175 packet.setAttribute("to", contact.getJid());
1176 packet.setAttribute("from", contact.getAccount().getJid());
1177 Log.d(LOGTAG, packet.toString());
1178 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1179 }
1180
1181 public void sendPgpPresence(Account account, String signature) {
1182 PresencePacket packet = new PresencePacket();
1183 packet.setAttribute("from", account.getFullJid());
1184 Element status = new Element("status");
1185 status.setContent("online");
1186 packet.addChild(status);
1187 Element x = new Element("x");
1188 x.setAttribute("xmlns", "jabber:x:signed");
1189 x.setContent(signature);
1190 packet.addChild(x);
1191 account.getXmppConnection().sendPresencePacket(packet);
1192 }
1193
1194 public void generatePgpAnnouncement(Account account)
1195 throws PgpEngine.UserInputRequiredException {
1196 if (account.getStatus() == Account.STATUS_ONLINE) {
1197 String signature = getPgpEngine().generateSignature("online");
1198 account.setKey("pgp_signature", signature);
1199 databaseBackend.updateAccount(account);
1200 sendPgpPresence(account, signature);
1201 }
1202 }
1203
1204 public void updateConversation(Conversation conversation) {
1205 this.databaseBackend.updateConversation(conversation);
1206 }
1207
1208 public Contact findContact(String uuid) {
1209 Contact contact = this.databaseBackend.getContact(uuid);
1210 for (Account account : getAccounts()) {
1211 if (contact.getAccountUuid().equals(account.getUuid())) {
1212 contact.setAccount(account);
1213 }
1214 }
1215 return contact;
1216 }
1217
1218 public void removeOnTLSExceptionReceivedListener() {
1219 this.tlsException = null;
1220 }
1221
1222 // TODO dont let thread sleep but schedule wake up
1223 public void reconnectAccount(final Account account, final boolean force) {
1224 new Thread(new Runnable() {
1225
1226 @Override
1227 public void run() {
1228 if (account.getXmppConnection() != null) {
1229 disconnect(account, force);
1230 }
1231 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1232 if (account.getXmppConnection() == null) {
1233 account.setXmppConnection(createConnection(account));
1234 }
1235 Thread thread = new Thread(account.getXmppConnection());
1236 thread.start();
1237 scheduleWakeupCall((int) (CONNECT_TIMEOUT * 1.2), false);
1238 }
1239 }
1240 }).start();
1241 }
1242
1243 public void updateConversationInGui() {
1244 if (convChangedListener != null) {
1245 convChangedListener.onConversationListChanged();
1246 }
1247 }
1248
1249 public void sendConversationSubject(Conversation conversation,
1250 String subject) {
1251 MessagePacket packet = new MessagePacket();
1252 packet.setType(MessagePacket.TYPE_GROUPCHAT);
1253 packet.setTo(conversation.getContactJid().split("/")[0]);
1254 Element subjectChild = new Element("subject");
1255 subjectChild.setContent(subject);
1256 packet.addChild(subjectChild);
1257 packet.setFrom(conversation.getAccount().getJid());
1258 Account account = conversation.getAccount();
1259 if (account.getStatus() == Account.STATUS_ONLINE) {
1260 account.getXmppConnection().sendMessagePacket(packet);
1261 }
1262 }
1263
1264 public void inviteToConference(Conversation conversation,
1265 List<Contact> contacts) {
1266 for (Contact contact : contacts) {
1267 MessagePacket packet = new MessagePacket();
1268 packet.setTo(conversation.getContactJid().split("/")[0]);
1269 packet.setFrom(conversation.getAccount().getFullJid());
1270 Element x = new Element("x");
1271 x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user");
1272 Element invite = new Element("invite");
1273 invite.setAttribute("to", contact.getJid());
1274 x.addChild(invite);
1275 packet.addChild(x);
1276 Log.d(LOGTAG, packet.toString());
1277 conversation.getAccount().getXmppConnection()
1278 .sendMessagePacket(packet);
1279 }
1280
1281 }
1282}