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 PresencePacket packet = new PresencePacket();
1039 packet.setAttribute("to",
1040 conversation.getContactJid().split("/")[0] + "/" + nick);
1041 packet.setAttribute("from", conversation.getAccount().getFullJid());
1042
1043 conversation.getAccount().getXmppConnection()
1044 .sendPresencePacket(packet, new OnPresencePacketReceived() {
1045
1046 @Override
1047 public void onPresencePacketReceived(Account account,
1048 PresencePacket packet) {
1049 final boolean changed;
1050 String type = packet.getAttribute("type");
1051 changed = (!"error".equals(type));
1052 if (!changed) {
1053 options.getOnRenameListener().onRename(false);
1054 } else {
1055 if (type == null) {
1056 options.getOnRenameListener()
1057 .onRename(true);
1058 options.setNick(packet.getAttribute("from")
1059 .split("/")[1]);
1060 } else {
1061 options.processPacket(packet);
1062 }
1063 }
1064 }
1065 });
1066 } else {
1067 String jid = conversation.getContactJid().split("/")[0] + "/"
1068 + nick;
1069 conversation.setContactJid(jid);
1070 databaseBackend.updateConversation(conversation);
1071 if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1072 joinMuc(conversation);
1073 }
1074 }
1075 }
1076
1077 public void leaveMuc(Conversation conversation) {
1078 PresencePacket packet = new PresencePacket();
1079 packet.setAttribute("to", conversation.getContactJid());
1080 packet.setAttribute("from", conversation.getAccount().getFullJid());
1081 packet.setAttribute("type", "unavailable");
1082 conversation.getAccount().getXmppConnection()
1083 .sendPresencePacket(packet);
1084 conversation.getMucOptions().setOffline();
1085 }
1086
1087 public void disconnect(Account account, boolean force) {
1088 if ((account.getStatus() == Account.STATUS_ONLINE)||(account.getStatus() == Account.STATUS_DISABLED)) {
1089 if (!force) {
1090 List<Conversation> conversations = getConversations();
1091 for (int i = 0; i < conversations.size(); i++) {
1092 Conversation conversation = conversations.get(i);
1093 if (conversation.getAccount() == account) {
1094 if (conversation.getMode() == Conversation.MODE_MULTI) {
1095 leaveMuc(conversation);
1096 } else {
1097 conversation.endOtrIfNeeded();
1098 }
1099 }
1100 }
1101 }
1102 account.getXmppConnection().disconnect(force);
1103 }
1104 }
1105
1106 @Override
1107 public IBinder onBind(Intent intent) {
1108 return mBinder;
1109 }
1110
1111 public void updateContact(Contact contact) {
1112 databaseBackend.updateContact(contact);
1113 replaceContactInConversation(contact.getJid(), contact);
1114 }
1115
1116 public void updateMessage(Message message) {
1117 databaseBackend.updateMessage(message);
1118 }
1119
1120 public void createContact(Contact contact) {
1121 SharedPreferences sharedPref = PreferenceManager
1122 .getDefaultSharedPreferences(getApplicationContext());
1123 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1124 if (autoGrant) {
1125 contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
1126 contact.setSubscriptionOption(Contact.Subscription.ASKING);
1127 }
1128 databaseBackend.createContact(contact);
1129 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1130 Element query = new Element("query");
1131 query.setAttribute("xmlns", "jabber:iq:roster");
1132 Element item = new Element("item");
1133 item.setAttribute("jid", contact.getJid());
1134 item.setAttribute("name", contact.getJid());
1135 query.addChild(item);
1136 iq.addChild(query);
1137 Account account = contact.getAccount();
1138 account.getXmppConnection().sendIqPacket(iq, null);
1139 if (autoGrant) {
1140 requestPresenceUpdatesFrom(contact);
1141 }
1142 replaceContactInConversation(contact.getJid(), contact);
1143 }
1144
1145 public void requestPresenceUpdatesFrom(Contact contact) {
1146 // Requesting a Subscription type=subscribe
1147 PresencePacket packet = new PresencePacket();
1148 packet.setAttribute("type", "subscribe");
1149 packet.setAttribute("to", contact.getJid());
1150 packet.setAttribute("from", contact.getAccount().getJid());
1151 Log.d(LOGTAG, packet.toString());
1152 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1153 }
1154
1155 public void stopPresenceUpdatesFrom(Contact contact) {
1156 // Unsubscribing type='unsubscribe'
1157 PresencePacket packet = new PresencePacket();
1158 packet.setAttribute("type", "unsubscribe");
1159 packet.setAttribute("to", contact.getJid());
1160 packet.setAttribute("from", contact.getAccount().getJid());
1161 Log.d(LOGTAG, packet.toString());
1162 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1163 }
1164
1165 public void stopPresenceUpdatesTo(Contact contact) {
1166 // Canceling a Subscription type=unsubscribed
1167 PresencePacket packet = new PresencePacket();
1168 packet.setAttribute("type", "unsubscribed");
1169 packet.setAttribute("to", contact.getJid());
1170 packet.setAttribute("from", contact.getAccount().getJid());
1171 Log.d(LOGTAG, packet.toString());
1172 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1173 }
1174
1175 public void sendPresenceUpdatesTo(Contact contact) {
1176 // type='subscribed'
1177 PresencePacket packet = new PresencePacket();
1178 packet.setAttribute("type", "subscribed");
1179 packet.setAttribute("to", contact.getJid());
1180 packet.setAttribute("from", contact.getAccount().getJid());
1181 Log.d(LOGTAG, packet.toString());
1182 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1183 }
1184
1185 public void sendPgpPresence(Account account, String signature) {
1186 PresencePacket packet = new PresencePacket();
1187 packet.setAttribute("from", account.getFullJid());
1188 Element status = new Element("status");
1189 status.setContent("online");
1190 packet.addChild(status);
1191 Element x = new Element("x");
1192 x.setAttribute("xmlns", "jabber:x:signed");
1193 x.setContent(signature);
1194 packet.addChild(x);
1195 account.getXmppConnection().sendPresencePacket(packet);
1196 }
1197
1198 public void generatePgpAnnouncement(Account account)
1199 throws PgpEngine.UserInputRequiredException {
1200 if (account.getStatus() == Account.STATUS_ONLINE) {
1201 String signature = getPgpEngine().generateSignature("online");
1202 account.setKey("pgp_signature", signature);
1203 databaseBackend.updateAccount(account);
1204 sendPgpPresence(account, signature);
1205 }
1206 }
1207
1208 public void updateConversation(Conversation conversation) {
1209 this.databaseBackend.updateConversation(conversation);
1210 }
1211
1212 public Contact findContact(String uuid) {
1213 Contact contact = this.databaseBackend.getContact(uuid);
1214 for (Account account : getAccounts()) {
1215 if (contact.getAccountUuid().equals(account.getUuid())) {
1216 contact.setAccount(account);
1217 }
1218 }
1219 return contact;
1220 }
1221
1222 public void removeOnTLSExceptionReceivedListener() {
1223 this.tlsException = null;
1224 }
1225
1226 //TODO dont let thread sleep but schedule wake up
1227 public void reconnectAccount(final Account account,final boolean force) {
1228 new Thread(new Runnable() {
1229
1230 @Override
1231 public void run() {
1232 if (account.getXmppConnection() != null) {
1233 disconnect(account, force);
1234 }
1235 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1236 if (account.getXmppConnection() == null) {
1237 account.setXmppConnection(createConnection(account));
1238 }
1239 Thread thread = new Thread(account.getXmppConnection());
1240 thread.start();
1241 scheduleWakeupCall((int) (CONNECT_TIMEOUT * 1.2),false);
1242 }
1243 }
1244 }).start();
1245 }
1246
1247 public void updateConversationInGui() {
1248 if (convChangedListener!=null) {
1249 convChangedListener.onConversationListChanged();
1250 }
1251 }
1252
1253 public void sendConversationSubject(Conversation conversation,
1254 String subject) {
1255 MessagePacket packet = new MessagePacket();
1256 packet.setType(MessagePacket.TYPE_GROUPCHAT);
1257 packet.setTo(conversation.getContactJid().split("/")[0]);
1258 Element subjectChild = new Element("subject");
1259 subjectChild.setContent(subject);
1260 packet.addChild(subjectChild);
1261 packet.setFrom(conversation.getAccount().getJid());
1262 Account account = conversation.getAccount();
1263 if (account.getStatus() == Account.STATUS_ONLINE) {
1264 account.getXmppConnection().sendMessagePacket(packet);
1265 }
1266 }
1267
1268 public void inviteToConference(Conversation conversation,
1269 List<Contact> contacts) {
1270 for(Contact contact : contacts) {
1271 MessagePacket packet = new MessagePacket();
1272 packet.setTo(conversation.getContactJid().split("/")[0]);
1273 packet.setFrom(conversation.getAccount().getFullJid());
1274 Element x = new Element("x");
1275 x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user");
1276 Element invite = new Element("invite");
1277 invite.setAttribute("to", contact.getJid());
1278 x.addChild(invite);
1279 packet.addChild(x);
1280 Log.d(LOGTAG,packet.toString());
1281 conversation.getAccount().getXmppConnection().sendMessagePacket(packet);
1282 }
1283
1284 }
1285}