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