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 = 2;
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 {
152 // Log.d(LOGTAG, "unparsed message " + packet.toString());
153 }
154 if ((message == null)||(message.getBody() == null)) {
155 return;
156 }
157 if (packet.hasChild("delay")) {
158 try {
159 String stamp = packet.findChild("delay").getAttribute(
160 "stamp");
161 stamp = stamp.replace("Z", "+0000");
162 Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
163 .parse(stamp);
164 message.setTime(date.getTime());
165 } catch (ParseException e) {
166 Log.d(LOGTAG, "error trying to parse date" + e.getMessage());
167 }
168 }
169 Conversation conversation = message.getConversation();
170 conversation.getMessages().add(message);
171 if (packet.getType() != MessagePacket.TYPE_ERROR) {
172 databaseBackend.createMessage(message);
173 }
174 if (convChangedListener != null) {
175 convChangedListener.onConversationListChanged();
176 } else {
177 UIHelper.updateNotification(getApplicationContext(),
178 getConversations(), message.getConversation(), notify);
179 }
180 }
181 };
182 private OnStatusChanged statusListener = new OnStatusChanged() {
183
184 @Override
185 public void onStatusChanged(Account account) {
186 if (accountChangedListener != null) {
187 accountChangedListener.onAccountListChangedListener();
188 }
189 if (account.getStatus() == Account.STATUS_ONLINE) {
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 connection.setOnBindListener(new OnBindListener() {
545
546 @Override
547 public void onBind(Account account) {
548 databaseBackend.clearPresences(account);
549 }
550 });
551 return connection;
552 }
553
554 public void sendMessage(Message message, String presence) {
555 Account account = message.getConversation().getAccount();
556 Conversation conv = message.getConversation();
557 boolean saveInDb = false;
558 boolean addToConversation = false;
559 if (account.getStatus() == Account.STATUS_ONLINE) {
560 MessagePacket packet;
561 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
562 if (!conv.hasValidOtrSession()) {
563 // starting otr session. messages will be send later
564 conv.startOtrSession(getApplicationContext(), presence);
565 } else if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
566 // otr session aleary exists, creating message packet
567 // accordingly
568 packet = prepareMessagePacket(account, message,
569 conv.getOtrSession());
570 account.getXmppConnection().sendMessagePacket(packet);
571 message.setStatus(Message.STATUS_SEND);
572 }
573 saveInDb = true;
574 addToConversation = true;
575 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
576 message.getConversation().endOtrIfNeeded();
577 long keyId = message.getConversation().getContact()
578 .getPgpKeyId();
579 packet = new MessagePacket();
580 packet.setType(MessagePacket.TYPE_CHAT);
581 packet.setFrom(message.getConversation().getAccount()
582 .getFullJid());
583 packet.setTo(message.getCounterpart());
584 packet.setBody("This is an XEP-0027 encryted message");
585 Element x = new Element("x");
586 x.setAttribute("xmlns", "jabber:x:encrypted");
587 x.setContent(this.getPgpEngine().encrypt(keyId,
588 message.getBody()));
589 packet.addChild(x);
590 account.getXmppConnection().sendMessagePacket(packet);
591 message.setStatus(Message.STATUS_SEND);
592 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
593 saveInDb = true;
594 addToConversation = true;
595 } else {
596 message.getConversation().endOtrIfNeeded();
597 // don't encrypt
598 if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
599 message.setStatus(Message.STATUS_SEND);
600 saveInDb = true;
601 addToConversation = true;
602 }
603
604 packet = prepareMessagePacket(account, message, null);
605 account.getXmppConnection().sendMessagePacket(packet);
606 }
607 } else {
608 // account is offline
609 saveInDb = true;
610 addToConversation = true;
611
612 }
613 if (saveInDb) {
614 databaseBackend.createMessage(message);
615 }
616 if (addToConversation) {
617 conv.getMessages().add(message);
618 if (convChangedListener != null) {
619 convChangedListener.onConversationListChanged();
620 }
621 }
622
623 }
624
625 private void sendUnsendMessages(Conversation conversation) {
626 for (int i = 0; i < conversation.getMessages().size(); ++i) {
627 if (conversation.getMessages().get(i).getStatus() == Message.STATUS_UNSEND) {
628 Message message = conversation.getMessages().get(i);
629 MessagePacket packet = prepareMessagePacket(
630 conversation.getAccount(), message, null);
631 conversation.getAccount().getXmppConnection()
632 .sendMessagePacket(packet);
633 message.setStatus(Message.STATUS_SEND);
634 if (conversation.getMode() == Conversation.MODE_SINGLE) {
635 databaseBackend.updateMessage(message);
636 } else {
637 databaseBackend.deleteMessage(message);
638 conversation.getMessages().remove(i);
639 i--;
640 }
641 }
642 }
643 }
644
645 public MessagePacket prepareMessagePacket(Account account, Message message,
646 Session otrSession) {
647 MessagePacket packet = new MessagePacket();
648 if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
649 packet.setType(MessagePacket.TYPE_CHAT);
650 if (otrSession != null) {
651 try {
652 packet.setBody(otrSession.transformSending(message
653 .getBody()));
654 } catch (OtrException e) {
655 Log.d(LOGTAG,
656 account.getJid()
657 + ": could not encrypt message to "
658 + message.getCounterpart());
659 }
660 Element privateMarker = new Element("private");
661 privateMarker.setAttribute("xmlns", "urn:xmpp:carbons:2");
662 packet.addChild(privateMarker);
663 packet.setTo(otrSession.getSessionID().getAccountID() + "/"
664 + otrSession.getSessionID().getUserID());
665 packet.setFrom(account.getFullJid());
666 } else {
667 packet.setBody(message.getBody());
668 packet.setTo(message.getCounterpart());
669 packet.setFrom(account.getJid());
670 }
671 } else if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
672 packet.setType(MessagePacket.TYPE_GROUPCHAT);
673 packet.setBody(message.getBody());
674 packet.setTo(message.getCounterpart().split("/")[0]);
675 packet.setFrom(account.getJid());
676 }
677 return packet;
678 }
679
680 private void getRoster(Account account,
681 final OnRosterFetchedListener listener) {
682 List<Contact> contacts = databaseBackend.getContactsByAccount(account);
683 for (int i = 0; i < contacts.size(); ++i) {
684 contacts.get(i).setAccount(account);
685 }
686 if (listener != null) {
687 listener.onRosterFetched(contacts);
688 }
689 }
690
691 public List<Contact> getRoster(Account account) {
692 List<Contact> contacts = databaseBackend.getContactsByAccount(account);
693 for (int i = 0; i < contacts.size(); ++i) {
694 contacts.get(i).setAccount(account);
695 }
696 return contacts;
697 }
698
699 public void updateRoster(final Account account,
700 final OnRosterFetchedListener listener) {
701 IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
702 Element query = new Element("query");
703 query.setAttribute("xmlns", "jabber:iq:roster");
704 if (!"".equals(account.getRosterVersion())) {
705 Log.d(LOGTAG, account.getJid() + ": fetching roster version "
706 + account.getRosterVersion());
707 } else {
708 Log.d(LOGTAG, account.getJid() + ": fetching roster");
709 }
710 query.setAttribute("ver", account.getRosterVersion());
711 iqPacket.addChild(query);
712 account.getXmppConnection().sendIqPacket(iqPacket,
713 new OnIqPacketReceived() {
714
715 @Override
716 public void onIqPacketReceived(final Account account,
717 IqPacket packet) {
718 Element roster = packet.findChild("query");
719 if (roster != null) {
720 Log.d(LOGTAG, account.getJid()
721 + ": processing roster");
722 processRosterItems(account, roster);
723 StringBuilder mWhere = new StringBuilder();
724 mWhere.append("jid NOT IN(");
725 List<Element> items = roster.getChildren();
726 for (int i = 0; i < items.size(); ++i) {
727 mWhere.append(DatabaseUtils
728 .sqlEscapeString(items.get(i)
729 .getAttribute("jid")));
730 if (i != items.size() - 1) {
731 mWhere.append(",");
732 }
733 }
734 mWhere.append(") and accountUuid = \"");
735 mWhere.append(account.getUuid());
736 mWhere.append("\"");
737 List<Contact> contactsToDelete = databaseBackend
738 .getContacts(mWhere.toString());
739 for (Contact contact : contactsToDelete) {
740 databaseBackend.deleteContact(contact);
741 replaceContactInConversation(contact.getJid(),
742 null);
743 }
744
745 } else {
746 Log.d(LOGTAG, account.getJid()
747 + ": empty roster returend");
748 }
749 mergePhoneContactsWithRoster(new OnPhoneContactsMerged() {
750
751 @Override
752 public void phoneContactsMerged() {
753 if (listener != null) {
754 getRoster(account, listener);
755 }
756 }
757 });
758 }
759 });
760 }
761
762 public void mergePhoneContactsWithRoster(
763 final OnPhoneContactsMerged listener) {
764 PhoneHelper.loadPhoneContacts(getApplicationContext(),
765 new OnPhoneContactsLoadedListener() {
766 @Override
767 public void onPhoneContactsLoaded(
768 Hashtable<String, Bundle> phoneContacts) {
769 List<Contact> contacts = databaseBackend
770 .getContactsByAccount(null);
771 for (int i = 0; i < contacts.size(); ++i) {
772 Contact contact = contacts.get(i);
773 if (phoneContacts.containsKey(contact.getJid())) {
774 Bundle phoneContact = phoneContacts.get(contact
775 .getJid());
776 String systemAccount = phoneContact
777 .getInt("phoneid")
778 + "#"
779 + phoneContact.getString("lookup");
780 contact.setSystemAccount(systemAccount);
781 contact.setPhotoUri(phoneContact
782 .getString("photouri"));
783 contact.setDisplayName(phoneContact
784 .getString("displayname"));
785 databaseBackend.updateContact(contact);
786 replaceContactInConversation(contact.getJid(),
787 contact);
788 } else {
789 if ((contact.getSystemAccount() != null)
790 || (contact.getProfilePhoto() != null)) {
791 contact.setSystemAccount(null);
792 contact.setPhotoUri(null);
793 databaseBackend.updateContact(contact);
794 replaceContactInConversation(
795 contact.getJid(), contact);
796 }
797 }
798 }
799 if (listener != null) {
800 listener.phoneContactsMerged();
801 }
802 }
803 });
804 }
805
806 public List<Conversation> getConversations() {
807 if (this.conversations == null) {
808 Hashtable<String, Account> accountLookupTable = new Hashtable<String, Account>();
809 for (Account account : this.accounts) {
810 accountLookupTable.put(account.getUuid(), account);
811 }
812 this.conversations = databaseBackend
813 .getConversations(Conversation.STATUS_AVAILABLE);
814 for (Conversation conv : this.conversations) {
815 Account account = accountLookupTable.get(conv.getAccountUuid());
816 conv.setAccount(account);
817 conv.setContact(findContact(account, conv.getContactJid()));
818 conv.setMessages(databaseBackend.getMessages(conv, 50));
819 }
820 }
821 return this.conversations;
822 }
823
824 public List<Account> getAccounts() {
825 return this.accounts;
826 }
827
828 public Contact findContact(Account account, String jid) {
829 Contact contact = databaseBackend.findContact(account, jid);
830 if (contact != null) {
831 contact.setAccount(account);
832 }
833 return contact;
834 }
835
836 public Conversation findOrCreateConversation(Account account, String jid,
837 boolean muc) {
838 for (Conversation conv : this.getConversations()) {
839 if ((conv.getAccount().equals(account))
840 && (conv.getContactJid().split("/")[0].equals(jid))) {
841 return conv;
842 }
843 }
844 Conversation conversation = databaseBackend.findConversation(account,
845 jid);
846 if (conversation != null) {
847 conversation.setStatus(Conversation.STATUS_AVAILABLE);
848 conversation.setAccount(account);
849 if (muc) {
850 conversation.setMode(Conversation.MODE_MULTI);
851 if (account.getStatus() == Account.STATUS_ONLINE) {
852 joinMuc(conversation);
853 }
854 } else {
855 conversation.setMode(Conversation.MODE_SINGLE);
856 }
857 conversation.setMessages(databaseBackend.getMessages(conversation, 50));
858 this.databaseBackend.updateConversation(conversation);
859 conversation.setContact(findContact(account,
860 conversation.getContactJid()));
861 } else {
862 String conversationName;
863 Contact contact = findContact(account, jid);
864 if (contact != null) {
865 conversationName = contact.getDisplayName();
866 } else {
867 conversationName = jid.split("@")[0];
868 }
869 if (muc) {
870 conversation = new Conversation(conversationName, account, jid,
871 Conversation.MODE_MULTI);
872 if (account.getStatus() == Account.STATUS_ONLINE) {
873 joinMuc(conversation);
874 }
875 } else {
876 conversation = new Conversation(conversationName, account, jid,
877 Conversation.MODE_SINGLE);
878 }
879 conversation.setContact(contact);
880 this.databaseBackend.createConversation(conversation);
881 }
882 this.conversations.add(conversation);
883 if (this.convChangedListener != null) {
884 this.convChangedListener.onConversationListChanged();
885 }
886 return conversation;
887 }
888
889 public void archiveConversation(Conversation conversation) {
890 if (conversation.getMode() == Conversation.MODE_MULTI) {
891 leaveMuc(conversation);
892 } else {
893 conversation.endOtrIfNeeded();
894 }
895 this.databaseBackend.updateConversation(conversation);
896 this.conversations.remove(conversation);
897 if (this.convChangedListener != null) {
898 this.convChangedListener.onConversationListChanged();
899 }
900 }
901
902 public int getConversationCount() {
903 return this.databaseBackend.getConversationCount();
904 }
905
906 public void createAccount(Account account) {
907 databaseBackend.createAccount(account);
908 this.accounts.add(account);
909 this.reconnectAccount(account, false);
910 if (accountChangedListener != null)
911 accountChangedListener.onAccountListChangedListener();
912 }
913
914 public void deleteContact(Contact contact) {
915 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
916 Element query = new Element("query");
917 query.setAttribute("xmlns", "jabber:iq:roster");
918 Element item = new Element("item");
919 item.setAttribute("jid", contact.getJid());
920 item.setAttribute("subscription", "remove");
921 query.addChild(item);
922 iq.addChild(query);
923 contact.getAccount().getXmppConnection().sendIqPacket(iq, null);
924 replaceContactInConversation(contact.getJid(), null);
925 databaseBackend.deleteContact(contact);
926 }
927
928 public void updateAccount(Account account) {
929 databaseBackend.updateAccount(account);
930 reconnectAccount(account,false);
931 if (accountChangedListener != null)
932 accountChangedListener.onAccountListChangedListener();
933 }
934
935 public void deleteAccount(Account account) {
936 if (account.getXmppConnection() != null) {
937 this.disconnect(account, true);
938 }
939 databaseBackend.deleteAccount(account);
940 this.accounts.remove(account);
941 if (accountChangedListener != null)
942 accountChangedListener.onAccountListChangedListener();
943 }
944
945 public void setOnConversationListChangedListener(
946 OnConversationListChangedListener listener) {
947 this.convChangedListener = listener;
948 }
949
950 public void removeOnConversationListChangedListener() {
951 this.convChangedListener = null;
952 }
953
954 public void setOnAccountListChangedListener(
955 OnAccountListChangedListener listener) {
956 this.accountChangedListener = listener;
957 }
958
959 public void removeOnAccountListChangedListener() {
960 this.accountChangedListener = null;
961 }
962
963 public void connectMultiModeConversations(Account account) {
964 List<Conversation> conversations = getConversations();
965 for (int i = 0; i < conversations.size(); i++) {
966 Conversation conversation = conversations.get(i);
967 if ((conversation.getMode() == Conversation.MODE_MULTI)
968 && (conversation.getAccount() == account)) {
969 joinMuc(conversation);
970 }
971 }
972 }
973
974 public void joinMuc(Conversation conversation) {
975 String[] mucParts = conversation.getContactJid().split("/");
976 String muc;
977 String nick;
978 if (mucParts.length == 2) {
979 muc = mucParts[0];
980 nick = mucParts[1];
981 } else {
982 muc = mucParts[0];
983 nick = conversation.getAccount().getUsername();
984 }
985 PresencePacket packet = new PresencePacket();
986 packet.setAttribute("to", muc + "/" + nick);
987 Element x = new Element("x");
988 x.setAttribute("xmlns", "http://jabber.org/protocol/muc");
989 if (conversation.getMessages().size() != 0) {
990 Element history = new Element("history");
991 long lastMsgTime = conversation.getLatestMessage().getTimeSent();
992 long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
993 history.setAttribute("seconds", diff + "");
994 x.addChild(history);
995 }
996 packet.addChild(x);
997 conversation.getAccount().getXmppConnection()
998 .sendPresencePacket(packet);
999 }
1000
1001 private OnRenameListener renameListener = null;
1002
1003 public void setOnRenameListener(OnRenameListener listener) {
1004 this.renameListener = listener;
1005 }
1006
1007 public void renameInMuc(final Conversation conversation, final String nick) {
1008 final MucOptions options = conversation.getMucOptions();
1009 if (options.online()) {
1010 options.setOnRenameListener(new OnRenameListener() {
1011
1012 @Override
1013 public void onRename(boolean success) {
1014 if (renameListener != null) {
1015 renameListener.onRename(success);
1016 }
1017 if (success) {
1018 databaseBackend.updateConversation(conversation);
1019 }
1020 }
1021 });
1022 PresencePacket packet = new PresencePacket();
1023 packet.setAttribute("to",
1024 conversation.getContactJid().split("/")[0] + "/" + nick);
1025 packet.setAttribute("from", conversation.getAccount().getFullJid());
1026
1027 conversation.getAccount().getXmppConnection()
1028 .sendPresencePacket(packet, new OnPresencePacketReceived() {
1029
1030 @Override
1031 public void onPresencePacketReceived(Account account,
1032 PresencePacket packet) {
1033 final boolean changed;
1034 String type = packet.getAttribute("type");
1035 changed = (!"error".equals(type));
1036 if (!changed) {
1037 options.getOnRenameListener().onRename(false);
1038 } else {
1039 if (type == null) {
1040 options.getOnRenameListener()
1041 .onRename(true);
1042 options.setNick(packet.getAttribute("from")
1043 .split("/")[1]);
1044 } else {
1045 options.processPacket(packet);
1046 }
1047 }
1048 }
1049 });
1050 } else {
1051 String jid = conversation.getContactJid().split("/")[0] + "/"
1052 + nick;
1053 conversation.setContactJid(jid);
1054 databaseBackend.updateConversation(conversation);
1055 if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1056 joinMuc(conversation);
1057 }
1058 }
1059 }
1060
1061 public void leaveMuc(Conversation conversation) {
1062 PresencePacket packet = new PresencePacket();
1063 packet.setAttribute("to", conversation.getContactJid());
1064 packet.setAttribute("from", conversation.getAccount().getFullJid());
1065 packet.setAttribute("type", "unavailable");
1066 conversation.getAccount().getXmppConnection()
1067 .sendPresencePacket(packet);
1068 conversation.getMucOptions().setOffline();
1069 }
1070
1071 public void disconnect(Account account, boolean force) {
1072 if ((account.getStatus() == Account.STATUS_ONLINE)||(account.getStatus() == Account.STATUS_DISABLED)) {
1073 List<Conversation> conversations = getConversations();
1074 for (int i = 0; i < conversations.size(); i++) {
1075 Conversation conversation = conversations.get(i);
1076 if (conversation.getAccount() == account) {
1077 if (conversation.getMode() == Conversation.MODE_MULTI) {
1078 leaveMuc(conversation);
1079 } else {
1080 conversation.endOtrIfNeeded();
1081 }
1082 }
1083 }
1084 account.getXmppConnection().disconnect(force);
1085 }
1086 }
1087
1088 @Override
1089 public IBinder onBind(Intent intent) {
1090 return mBinder;
1091 }
1092
1093 public void updateContact(Contact contact) {
1094 databaseBackend.updateContact(contact);
1095 replaceContactInConversation(contact.getJid(), contact);
1096 }
1097
1098 public void updateMessage(Message message) {
1099 databaseBackend.updateMessage(message);
1100 }
1101
1102 public void createContact(Contact contact) {
1103 SharedPreferences sharedPref = PreferenceManager
1104 .getDefaultSharedPreferences(getApplicationContext());
1105 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1106 if (autoGrant) {
1107 contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
1108 contact.setSubscriptionOption(Contact.Subscription.ASKING);
1109 }
1110 databaseBackend.createContact(contact);
1111 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1112 Element query = new Element("query");
1113 query.setAttribute("xmlns", "jabber:iq:roster");
1114 Element item = new Element("item");
1115 item.setAttribute("jid", contact.getJid());
1116 item.setAttribute("name", contact.getJid());
1117 query.addChild(item);
1118 iq.addChild(query);
1119 Account account = contact.getAccount();
1120 account.getXmppConnection().sendIqPacket(iq, null);
1121 if (autoGrant) {
1122 requestPresenceUpdatesFrom(contact);
1123 }
1124 replaceContactInConversation(contact.getJid(), contact);
1125 }
1126
1127 public void requestPresenceUpdatesFrom(Contact contact) {
1128 // Requesting a Subscription type=subscribe
1129 PresencePacket packet = new PresencePacket();
1130 packet.setAttribute("type", "subscribe");
1131 packet.setAttribute("to", contact.getJid());
1132 packet.setAttribute("from", contact.getAccount().getJid());
1133 Log.d(LOGTAG, packet.toString());
1134 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1135 }
1136
1137 public void stopPresenceUpdatesFrom(Contact contact) {
1138 // Unsubscribing type='unsubscribe'
1139 PresencePacket packet = new PresencePacket();
1140 packet.setAttribute("type", "unsubscribe");
1141 packet.setAttribute("to", contact.getJid());
1142 packet.setAttribute("from", contact.getAccount().getJid());
1143 Log.d(LOGTAG, packet.toString());
1144 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1145 }
1146
1147 public void stopPresenceUpdatesTo(Contact contact) {
1148 // Canceling a Subscription type=unsubscribed
1149 PresencePacket packet = new PresencePacket();
1150 packet.setAttribute("type", "unsubscribed");
1151 packet.setAttribute("to", contact.getJid());
1152 packet.setAttribute("from", contact.getAccount().getJid());
1153 Log.d(LOGTAG, packet.toString());
1154 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1155 }
1156
1157 public void sendPresenceUpdatesTo(Contact contact) {
1158 // type='subscribed'
1159 PresencePacket packet = new PresencePacket();
1160 packet.setAttribute("type", "subscribed");
1161 packet.setAttribute("to", contact.getJid());
1162 packet.setAttribute("from", contact.getAccount().getJid());
1163 Log.d(LOGTAG, packet.toString());
1164 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1165 }
1166
1167 public void sendPgpPresence(Account account, String signature) {
1168 PresencePacket packet = new PresencePacket();
1169 packet.setAttribute("from", account.getFullJid());
1170 Element status = new Element("status");
1171 status.setContent("online");
1172 packet.addChild(status);
1173 Element x = new Element("x");
1174 x.setAttribute("xmlns", "jabber:x:signed");
1175 x.setContent(signature);
1176 packet.addChild(x);
1177 account.getXmppConnection().sendPresencePacket(packet);
1178 }
1179
1180 public void generatePgpAnnouncement(Account account)
1181 throws PgpEngine.UserInputRequiredException {
1182 if (account.getStatus() == Account.STATUS_ONLINE) {
1183 String signature = getPgpEngine().generateSignature("online");
1184 account.setKey("pgp_signature", signature);
1185 databaseBackend.updateAccount(account);
1186 sendPgpPresence(account, signature);
1187 }
1188 }
1189
1190 public void updateConversation(Conversation conversation) {
1191 this.databaseBackend.updateConversation(conversation);
1192 }
1193
1194 public Contact findContact(String uuid) {
1195 Contact contact = this.databaseBackend.getContact(uuid);
1196 for (Account account : getAccounts()) {
1197 if (contact.getAccountUuid().equals(account.getUuid())) {
1198 contact.setAccount(account);
1199 }
1200 }
1201 return contact;
1202 }
1203
1204 public void removeOnTLSExceptionReceivedListener() {
1205 this.tlsException = null;
1206 }
1207
1208 //TODO dont let thread sleep but schedule wake up
1209 public void reconnectAccount(final Account account,final boolean force) {
1210 new Thread(new Runnable() {
1211
1212 @Override
1213 public void run() {
1214 if (account.getXmppConnection() != null) {
1215 disconnect(account, force);
1216 }
1217 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1218 if (account.getXmppConnection() == null) {
1219 account.setXmppConnection(createConnection(account));
1220 }
1221 Thread thread = new Thread(account.getXmppConnection());
1222 thread.start();
1223 scheduleWakeupCall((int) (CONNECT_TIMEOUT * 1.2),false);
1224 }
1225 }
1226 }).start();
1227 }
1228
1229 public void updateConversationInGui() {
1230 if (convChangedListener!=null) {
1231 convChangedListener.onConversationListChanged();
1232 }
1233 }
1234
1235 public void sendConversationSubject(Conversation conversation,
1236 String subject) {
1237 MessagePacket packet = new MessagePacket();
1238 packet.setType(MessagePacket.TYPE_GROUPCHAT);
1239 packet.setTo(conversation.getContactJid().split("/")[0]);
1240 Element subjectChild = new Element("subject");
1241 subjectChild.setContent(subject);
1242 packet.addChild(subjectChild);
1243 packet.setFrom(conversation.getAccount().getJid());
1244 Account account = conversation.getAccount();
1245 if (account.getStatus() == Account.STATUS_ONLINE) {
1246 account.getXmppConnection().sendMessagePacket(packet);
1247 }
1248 }
1249}