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