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