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