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