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