1package eu.siacs.conversations.services;
2
3import android.annotation.SuppressLint;
4import android.app.AlarmManager;
5import android.app.PendingIntent;
6import android.app.Service;
7import android.content.Context;
8import android.content.Intent;
9import android.content.SharedPreferences;
10import android.database.ContentObserver;
11import android.graphics.Bitmap;
12import android.net.ConnectivityManager;
13import android.net.NetworkInfo;
14import android.net.Uri;
15import android.os.Binder;
16import android.os.Bundle;
17import android.os.FileObserver;
18import android.os.IBinder;
19import android.os.PowerManager;
20import android.os.PowerManager.WakeLock;
21import android.os.SystemClock;
22import android.preference.PreferenceManager;
23import android.provider.ContactsContract;
24import android.util.Log;
25import android.util.LruCache;
26
27import net.java.otr4j.OtrException;
28import net.java.otr4j.session.Session;
29import net.java.otr4j.session.SessionID;
30import net.java.otr4j.session.SessionStatus;
31
32import org.openintents.openpgp.util.OpenPgpApi;
33import org.openintents.openpgp.util.OpenPgpServiceConnection;
34
35import java.math.BigInteger;
36import java.security.SecureRandom;
37import java.util.ArrayList;
38import java.util.Collections;
39import java.util.Comparator;
40import java.util.Hashtable;
41import java.util.List;
42import java.util.Locale;
43import java.util.concurrent.CopyOnWriteArrayList;
44
45import de.duenndns.ssl.MemorizingTrustManager;
46import eu.siacs.conversations.Config;
47import eu.siacs.conversations.R;
48import eu.siacs.conversations.crypto.PgpEngine;
49import eu.siacs.conversations.entities.Account;
50import eu.siacs.conversations.entities.Bookmark;
51import eu.siacs.conversations.entities.Contact;
52import eu.siacs.conversations.entities.Conversation;
53import eu.siacs.conversations.entities.Downloadable;
54import eu.siacs.conversations.entities.DownloadableFile;
55import eu.siacs.conversations.entities.DownloadablePlaceholder;
56import eu.siacs.conversations.entities.Message;
57import eu.siacs.conversations.entities.MucOptions;
58import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
59import eu.siacs.conversations.entities.Presences;
60import eu.siacs.conversations.generator.IqGenerator;
61import eu.siacs.conversations.generator.MessageGenerator;
62import eu.siacs.conversations.generator.PresenceGenerator;
63import eu.siacs.conversations.http.HttpConnectionManager;
64import eu.siacs.conversations.parser.IqParser;
65import eu.siacs.conversations.parser.MessageParser;
66import eu.siacs.conversations.parser.PresenceParser;
67import eu.siacs.conversations.persistance.DatabaseBackend;
68import eu.siacs.conversations.persistance.FileBackend;
69import eu.siacs.conversations.ui.UiCallback;
70import eu.siacs.conversations.utils.CryptoHelper;
71import eu.siacs.conversations.utils.ExceptionHelper;
72import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
73import eu.siacs.conversations.utils.PRNGFixes;
74import eu.siacs.conversations.utils.PhoneHelper;
75import eu.siacs.conversations.xml.Element;
76import eu.siacs.conversations.xmpp.OnBindListener;
77import eu.siacs.conversations.xmpp.OnContactStatusChanged;
78import eu.siacs.conversations.xmpp.OnIqPacketReceived;
79import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
80import eu.siacs.conversations.xmpp.OnStatusChanged;
81import eu.siacs.conversations.xmpp.XmppConnection;
82import eu.siacs.conversations.xmpp.forms.Data;
83import eu.siacs.conversations.xmpp.forms.Field;
84import eu.siacs.conversations.xmpp.jid.InvalidJidException;
85import eu.siacs.conversations.xmpp.jid.Jid;
86import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
87import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
88import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
89import eu.siacs.conversations.xmpp.pep.Avatar;
90import eu.siacs.conversations.xmpp.stanzas.IqPacket;
91import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
92import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
93
94public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
95
96 public static String ACTION_CLEAR_NOTIFICATION = "clear_notification";
97 private static String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
98 public static String ACTION_DISABLE_FOREGROUND = "disable_foreground";
99 private ContentObserver contactObserver = new ContentObserver(null) {
100 @Override
101 public void onChange(boolean selfChange) {
102 super.onChange(selfChange);
103 Intent intent = new Intent(getApplicationContext(),
104 XmppConnectionService.class);
105 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
106 startService(intent);
107 }
108 };
109 private final IBinder mBinder = new XmppConnectionBinder();
110 public DatabaseBackend databaseBackend;
111 public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
112
113 @Override
114 public void onContactStatusChanged(Contact contact, boolean online) {
115 Conversation conversation = find(getConversations(), contact);
116 if (conversation != null) {
117 if (online && contact.getPresences().size() > 1) {
118 conversation.endOtrIfNeeded();
119 } else {
120 conversation.resetOtrSession();
121 }
122 if (online && (contact.getPresences().size() == 1)) {
123 sendUnsendMessages(conversation);
124 }
125 }
126 }
127 };
128 private FileBackend fileBackend = new FileBackend(this);
129 private MemorizingTrustManager mMemorizingTrustManager;
130 private NotificationService mNotificationService = new NotificationService(
131 this);
132 private MessageParser mMessageParser = new MessageParser(this);
133 private PresenceParser mPresenceParser = new PresenceParser(this);
134 private IqParser mIqParser = new IqParser(this);
135 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
136 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
137 private List<Account> accounts;
138 private final CopyOnWriteArrayList<Conversation> conversations = new CopyOnWriteArrayList<Conversation>();
139 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
140 this);
141 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
142 this);
143 private AvatarService mAvatarService = new AvatarService(this);
144 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
145 private OnConversationUpdate mOnConversationUpdate = null;
146 private Integer convChangedListenerCount = 0;
147 private OnAccountUpdate mOnAccountUpdate = null;
148 private OnStatusChanged statusListener = new OnStatusChanged() {
149
150 @Override
151 public void onStatusChanged(Account account) {
152 XmppConnection connection = account.getXmppConnection();
153 if (mOnAccountUpdate != null) {
154 mOnAccountUpdate.onAccountUpdate();
155 }
156 if (account.getStatus() == Account.State.ONLINE) {
157 for (Conversation conversation : account.pendingConferenceLeaves) {
158 leaveMuc(conversation);
159 }
160 for (Conversation conversation : account.pendingConferenceJoins) {
161 joinMuc(conversation);
162 }
163 mJingleConnectionManager.cancelInTransmission();
164 List<Conversation> conversations = getConversations();
165 for (Conversation conversation : conversations) {
166 if (conversation.getAccount() == account) {
167 conversation.startOtrIfNeeded();
168 sendUnsendMessages(conversation);
169 }
170 }
171 if (connection != null && connection.getFeatures().csi()) {
172 if (checkListeners()) {
173 Log.d(Config.LOGTAG, account.getJid().toBareJid()
174 + " sending csi//inactive");
175 connection.sendInactive();
176 } else {
177 Log.d(Config.LOGTAG, account.getJid().toBareJid()
178 + " sending csi//active");
179 connection.sendActive();
180 }
181 }
182 syncDirtyContacts(account);
183 scheduleWakeupCall(Config.PING_MAX_INTERVAL, true);
184 } else if (account.getStatus() == Account.State.OFFLINE) {
185 resetSendingToWaiting(account);
186 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
187 int timeToReconnect = mRandom.nextInt(50) + 10;
188 scheduleWakeupCall(timeToReconnect, false);
189 }
190 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
191 databaseBackend.updateAccount(account);
192 reconnectAccount(account, true);
193 } else if ((account.getStatus() != Account.State.CONNECTING)
194 && (account.getStatus() != Account.State.NO_INTERNET)) {
195 if (connection != null) {
196 int next = connection.getTimeToNextAttempt();
197 Log.d(Config.LOGTAG, account.getJid().toBareJid()
198 + ": error connecting account. try again in "
199 + next + "s for the "
200 + (connection.getAttempt() + 1) + " time");
201 scheduleWakeupCall((int) (next * 1.2), false);
202 }
203 }
204 getNotificationService().updateErrorNotification();
205 }
206 };
207
208 private int accountChangedListenerCount = 0;
209 private OnRosterUpdate mOnRosterUpdate = null;
210 private int rosterChangedListenerCount = 0;
211 private OnMucRosterUpdate mOnMucRosterUpdate = null;
212 private int mucRosterChangedListenerCount = 0;
213 private SecureRandom mRandom;
214 private FileObserver fileObserver = new FileObserver(
215 FileBackend.getConversationsImageDirectory()) {
216
217 @Override
218 public void onEvent(int event, String path) {
219 if (event == FileObserver.DELETE) {
220 markFileDeleted(path.split("\\.")[0]);
221 }
222 }
223 };
224 private OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
225
226 @Override
227 public void onJinglePacketReceived(Account account, JinglePacket packet) {
228 mJingleConnectionManager.deliverPacket(account, packet);
229 }
230 };
231
232 private OpenPgpServiceConnection pgpServiceConnection;
233 private PgpEngine mPgpEngine = null;
234 private Intent pingIntent;
235 private PendingIntent pendingPingIntent = null;
236 private WakeLock wakeLock;
237 private PowerManager pm;
238 private OnBindListener mOnBindListener = new OnBindListener() {
239
240 @Override
241 public void onBind(final Account account) {
242 account.getRoster().clearPresences();
243 account.clearPresences(); // self presences
244 account.pendingConferenceJoins.clear();
245 account.pendingConferenceLeaves.clear();
246 fetchRosterFromServer(account);
247 fetchBookmarks(account);
248 sendPresencePacket(account,
249 mPresenceGenerator.sendPresence(account));
250 connectMultiModeConversations(account);
251 updateConversationUi();
252 }
253 };
254
255 private OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
256
257 @Override
258 public void onMessageAcknowledged(Account account, String uuid) {
259 for (final Conversation conversation : getConversations()) {
260 if (conversation.getAccount() == account) {
261 for (final Message message : conversation.getMessages()) {
262 final int s = message.getStatus();
263 if ((s == Message.STATUS_UNSEND || s == Message.STATUS_WAITING) && message.getUuid().equals(uuid)) {
264 markMessage(message, Message.STATUS_SEND);
265 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
266 databaseBackend.updateConversation(conversation);
267 }
268 return;
269 }
270 }
271 }
272 }
273 }
274 };
275 private LruCache<String, Bitmap> mBitmapCache;
276 private IqGenerator mIqGenerator = new IqGenerator(this);
277 private Thread mPhoneContactMergerThread;
278
279 public PgpEngine getPgpEngine() {
280 if (pgpServiceConnection.isBound()) {
281 if (this.mPgpEngine == null) {
282 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
283 getApplicationContext(),
284 pgpServiceConnection.getService()), this);
285 }
286 return mPgpEngine;
287 } else {
288 return null;
289 }
290
291 }
292
293 public FileBackend getFileBackend() {
294 return this.fileBackend;
295 }
296
297 public AvatarService getAvatarService() {
298 return this.mAvatarService;
299 }
300
301 public void attachFileToConversation(Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
302 final Message message;
303 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
304 message = new Message(conversation, "",
305 Message.ENCRYPTION_DECRYPTED);
306 } else {
307 message = new Message(conversation, "",
308 conversation.getNextEncryption(forceEncryption()));
309 }
310 message.setCounterpart(conversation.getNextCounterpart());
311 message.setType(Message.TYPE_FILE);
312 message.setStatus(Message.STATUS_OFFERED);
313 String path = getFileBackend().getOriginalPath(uri);
314 if (path!=null) {
315 message.setRelativeFilePath(path);
316 getFileBackend().updateFileParams(message);
317 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
318 getPgpEngine().encrypt(message, callback);
319 } else {
320 callback.success(message);
321 }
322 } else {
323 new Thread(new Runnable() {
324 @Override
325 public void run() {
326 try {
327 getFileBackend().copyFileToPrivateStorage(message, uri);
328 getFileBackend().updateFileParams(message);
329 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
330 getPgpEngine().encrypt(message, callback);
331 } else {
332 callback.success(message);
333 }
334 } catch (FileBackend.FileCopyException e) {
335 callback.error(e.getResId(),message);
336 }
337 }
338 }).start();
339
340 }
341 }
342
343 public void attachImageToConversation(final Conversation conversation,
344 final Uri uri, final UiCallback<Message> callback) {
345 final Message message;
346 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
347 message = new Message(conversation, "",
348 Message.ENCRYPTION_DECRYPTED);
349 } else {
350 message = new Message(conversation, "",
351 conversation.getNextEncryption(forceEncryption()));
352 }
353 message.setCounterpart(conversation.getNextCounterpart());
354 message.setType(Message.TYPE_IMAGE);
355 message.setStatus(Message.STATUS_OFFERED);
356 new Thread(new Runnable() {
357
358 @Override
359 public void run() {
360 try {
361 DownloadableFile file = getFileBackend().copyImageToPrivateStorage(message, uri);
362 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
363 getPgpEngine().encrypt(message, callback);
364 } else {
365 callback.success(message);
366 }
367 } catch (FileBackend.FileCopyException e) {
368 callback.error(e.getResId(), message);
369 }
370 }
371 }).start();
372 }
373
374 public Conversation find(Bookmark bookmark) {
375 return find(bookmark.getAccount(), bookmark.getJid());
376 }
377
378 public Conversation find(final Account account, final Jid jid) {
379 return find(getConversations(), account, jid);
380 }
381
382 @Override
383 public int onStartCommand(Intent intent, int flags, int startId) {
384 if (intent != null && intent.getAction() != null) {
385 if (intent.getAction().equals(ACTION_MERGE_PHONE_CONTACTS)) {
386 PhoneHelper.loadPhoneContacts(getApplicationContext(), this);
387 return START_STICKY;
388 } else if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
389 logoutAndSave();
390 return START_NOT_STICKY;
391 } else if (intent.getAction().equals(ACTION_CLEAR_NOTIFICATION)) {
392 mNotificationService.clear();
393 } else if (intent.getAction().equals(ACTION_DISABLE_FOREGROUND)) {
394 getPreferences().edit().putBoolean("keep_foreground_service",false).commit();
395 toggleForegroundService();
396 }
397 }
398 this.wakeLock.acquire();
399
400 for (Account account : accounts) {
401 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
402 if (!hasInternetConnection()) {
403 account.setStatus(Account.State.NO_INTERNET);
404 if (statusListener != null) {
405 statusListener.onStatusChanged(account);
406 }
407 } else {
408 if (account.getStatus() == Account.State.NO_INTERNET) {
409 account.setStatus(Account.State.OFFLINE);
410 if (statusListener != null) {
411 statusListener.onStatusChanged(account);
412 }
413 }
414 if (account.getStatus() == Account.State.ONLINE) {
415 long lastReceived = account.getXmppConnection()
416 .getLastPacketReceived();
417 long lastSent = account.getXmppConnection()
418 .getLastPingSent();
419 if (lastSent - lastReceived >= Config.PING_TIMEOUT * 1000) {
420 Log.d(Config.LOGTAG, account.getJid()
421 + ": ping timeout");
422 this.reconnectAccount(account, true);
423 } else if (SystemClock.elapsedRealtime() - lastReceived >= Config.PING_MIN_INTERVAL * 1000) {
424 account.getXmppConnection().sendPing();
425 this.scheduleWakeupCall(2, false);
426 }
427 } else if (account.getStatus() == Account.State.OFFLINE) {
428 if (account.getXmppConnection() == null) {
429 account.setXmppConnection(this
430 .createConnection(account));
431 }
432 new Thread(account.getXmppConnection()).start();
433 } else if ((account.getStatus() == Account.State.CONNECTING)
434 && ((SystemClock.elapsedRealtime() - account
435 .getXmppConnection().getLastConnect()) / 1000 >= Config.CONNECT_TIMEOUT)) {
436 Log.d(Config.LOGTAG, account.getJid()
437 + ": time out during connect reconnecting");
438 reconnectAccount(account, true);
439 } else {
440 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
441 reconnectAccount(account, true);
442 }
443 }
444 // in any case. reschedule wakup call
445 this.scheduleWakeupCall(Config.PING_MAX_INTERVAL, true);
446 }
447 if (mOnAccountUpdate != null) {
448 mOnAccountUpdate.onAccountUpdate();
449 }
450 }
451 }
452 /*PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
453 if (!pm.isScreenOn()) {
454 removeStaleListeners();
455 }*/
456 if (wakeLock.isHeld()) {
457 try {
458 wakeLock.release();
459 } catch (final RuntimeException ignored) {
460 }
461 }
462 return START_STICKY;
463 }
464
465 public boolean hasInternetConnection() {
466 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
467 .getSystemService(Context.CONNECTIVITY_SERVICE);
468 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
469 return activeNetwork != null && activeNetwork.isConnected();
470 }
471
472 @SuppressLint("TrulyRandom")
473 @Override
474 public void onCreate() {
475 ExceptionHelper.init(getApplicationContext());
476 PRNGFixes.apply();
477 this.mRandom = new SecureRandom();
478 this.mMemorizingTrustManager = new MemorizingTrustManager(
479 getApplicationContext());
480
481 int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
482 int cacheSize = maxMemory / 8;
483 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
484 @Override
485 protected int sizeOf(String key, Bitmap bitmap) {
486 return bitmap.getByteCount() / 1024;
487 }
488 };
489
490 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
491 this.accounts = databaseBackend.getAccounts();
492
493 for (Account account : this.accounts) {
494 account.initOtrEngine(this);
495 this.databaseBackend.readRoster(account.getRoster());
496 }
497 initConversations();
498 PhoneHelper.loadPhoneContacts(getApplicationContext(),this);
499
500 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
501 this.fileObserver.startWatching();
502 this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
503 this.pgpServiceConnection.bindToService();
504
505 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
506 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
507 toggleForegroundService();
508 }
509
510 public void toggleForegroundService() {
511 if (getPreferences().getBoolean("keep_foreground_service",false)) {
512 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
513 } else {
514 stopForeground(true);
515 }
516 }
517
518 @Override
519 public void onTaskRemoved(Intent rootIntent) {
520 super.onTaskRemoved(rootIntent);
521 if (!getPreferences().getBoolean("keep_foreground_service",false)) {
522 this.logoutAndSave();
523 }
524 }
525
526 private void logoutAndSave() {
527 for (Account account : accounts) {
528 databaseBackend.writeRoster(account.getRoster());
529 if (account.getXmppConnection() != null) {
530 disconnect(account, false);
531 }
532 }
533 Context context = getApplicationContext();
534 AlarmManager alarmManager = (AlarmManager) context
535 .getSystemService(Context.ALARM_SERVICE);
536 Intent intent = new Intent(context, EventReceiver.class);
537 alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
538 Log.d(Config.LOGTAG, "good bye");
539 stopSelf();
540 }
541
542 protected void scheduleWakeupCall(int seconds, boolean ping) {
543 long timeToWake = SystemClock.elapsedRealtime() + seconds * 1000;
544 Context context = getApplicationContext();
545 AlarmManager alarmManager = (AlarmManager) context
546 .getSystemService(Context.ALARM_SERVICE);
547
548 if (ping) {
549 if (this.pingIntent == null) {
550 this.pingIntent = new Intent(context, EventReceiver.class);
551 this.pingIntent.setAction("ping");
552 this.pingIntent.putExtra("time", timeToWake);
553 this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
554 this.pingIntent, 0);
555 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
556 timeToWake, pendingPingIntent);
557 } else {
558 long scheduledTime = this.pingIntent.getLongExtra("time", 0);
559 if (scheduledTime < SystemClock.elapsedRealtime()
560 || (scheduledTime > timeToWake)) {
561 this.pingIntent.putExtra("time", timeToWake);
562 alarmManager.cancel(this.pendingPingIntent);
563 this.pendingPingIntent = PendingIntent.getBroadcast(
564 context, 0, this.pingIntent, 0);
565 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
566 timeToWake, pendingPingIntent);
567 }
568 }
569 } else {
570 Intent intent = new Intent(context, EventReceiver.class);
571 intent.setAction("ping_check");
572 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0,
573 intent, 0);
574 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake,
575 alarmIntent);
576 }
577
578 }
579
580 public XmppConnection createConnection(Account account) {
581 SharedPreferences sharedPref = getPreferences();
582 account.setResource(sharedPref.getString("resource", "mobile")
583 .toLowerCase(Locale.getDefault()));
584 XmppConnection connection = new XmppConnection(account, this);
585 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
586 connection.setOnStatusChangedListener(this.statusListener);
587 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
588 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
589 connection.setOnJinglePacketReceivedListener(this.jingleListener);
590 connection.setOnBindListener(this.mOnBindListener);
591 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
592 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
593 return connection;
594 }
595
596 public void sendMessage(Message message) {
597 Account account = message.getConversation().getAccount();
598 account.deactivateGracePeriod();
599 Conversation conv = message.getConversation();
600 MessagePacket packet = null;
601 boolean saveInDb = true;
602 boolean send = false;
603 if (account.getStatus() == Account.State.ONLINE
604 && account.getXmppConnection() != null) {
605 if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
606 if (message.getCounterpart() != null) {
607 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
608 if (!conv.hasValidOtrSession()) {
609 conv.startOtrSession(message.getCounterpart().getResourcepart(),true);
610 message.setStatus(Message.STATUS_WAITING);
611 } else if (conv.hasValidOtrSession()
612 && conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
613 mJingleConnectionManager
614 .createNewConnection(message);
615 }
616 } else {
617 mJingleConnectionManager.createNewConnection(message);
618 }
619 } else {
620 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
621 conv.startOtrIfNeeded();
622 }
623 message.setStatus(Message.STATUS_WAITING);
624 }
625 } else {
626 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
627 if (!conv.hasValidOtrSession() && (message.getCounterpart() != null)) {
628 conv.startOtrSession(message.getCounterpart().getResourcepart(), true);
629 message.setStatus(Message.STATUS_WAITING);
630 } else if (conv.hasValidOtrSession()) {
631 if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
632 packet = mMessageGenerator.generateOtrChat(message);
633 send = true;
634 } else {
635 message.setStatus(Message.STATUS_WAITING);
636 conv.startOtrIfNeeded();
637 }
638 } else {
639 message.setStatus(Message.STATUS_WAITING);
640 }
641 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
642 message.getConversation().endOtrIfNeeded();
643 failWaitingOtrMessages(message.getConversation());
644 packet = mMessageGenerator.generatePgpChat(message);
645 send = true;
646 } else {
647 message.getConversation().endOtrIfNeeded();
648 failWaitingOtrMessages(message.getConversation());
649 packet = mMessageGenerator.generateChat(message);
650 send = true;
651 }
652 }
653 if (!account.getXmppConnection().getFeatures().sm()
654 && conv.getMode() != Conversation.MODE_MULTI) {
655 message.setStatus(Message.STATUS_SEND);
656 }
657 } else {
658 message.setStatus(Message.STATUS_WAITING);
659 if (message.getType() == Message.TYPE_TEXT) {
660 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
661 String pgpBody = message.getEncryptedBody();
662 String decryptedBody = message.getBody();
663 message.setBody(pgpBody);
664 message.setEncryption(Message.ENCRYPTION_PGP);
665 databaseBackend.createMessage(message);
666 saveInDb = false;
667 message.setBody(decryptedBody);
668 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
669 } else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
670 if (!conv.hasValidOtrSession()
671 && message.getCounterpart() != null) {
672 conv.startOtrSession(message.getCounterpart().getResourcepart(), false);
673 }
674 }
675 }
676
677 }
678 conv.add(message);
679 if (saveInDb) {
680 if (message.getEncryption() == Message.ENCRYPTION_NONE
681 || saveEncryptedMessages()) {
682 databaseBackend.createMessage(message);
683 }
684 }
685 if ((send) && (packet != null)) {
686 sendMessagePacket(account, packet);
687 }
688 updateConversationUi();
689 }
690
691 private void sendUnsendMessages(Conversation conversation) {
692 for (int i = 0; i < conversation.getMessages().size(); ++i) {
693 int status = conversation.getMessages().get(i).getStatus();
694 if (status == Message.STATUS_WAITING) {
695 resendMessage(conversation.getMessages().get(i));
696 }
697 }
698 }
699
700 private void resendMessage(Message message) {
701 Account account = message.getConversation().getAccount();
702 MessagePacket packet = null;
703 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
704 Presences presences = message.getConversation().getContact()
705 .getPresences();
706 if (!message.getConversation().hasValidOtrSession()) {
707 if ((message.getCounterpart() != null)
708 && (presences.has(message.getCounterpart().getResourcepart()))) {
709 message.getConversation().startOtrSession(message.getCounterpart().getResourcepart(), true);
710 } else {
711 if (presences.size() == 1) {
712 String presence = presences.asStringArray()[0];
713 message.getConversation().startOtrSession(presence, true);
714 }
715 }
716 } else {
717 if (message.getConversation().getOtrSession()
718 .getSessionStatus() == SessionStatus.ENCRYPTED) {
719 try {
720 message.setCounterpart(Jid.fromSessionID(message.getConversation().getOtrSession().getSessionID()));
721 if (message.getType() == Message.TYPE_TEXT) {
722 packet = mMessageGenerator.generateOtrChat(message,
723 true);
724 } else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
725 mJingleConnectionManager.createNewConnection(message);
726 }
727 } catch (InvalidJidException e) {
728
729 }
730 }
731 }
732 } else if (message.getType() == Message.TYPE_TEXT) {
733 if (message.getEncryption() == Message.ENCRYPTION_NONE) {
734 packet = mMessageGenerator.generateChat(message, true);
735 } else if ((message.getEncryption() == Message.ENCRYPTION_DECRYPTED)
736 || (message.getEncryption() == Message.ENCRYPTION_PGP)) {
737 packet = mMessageGenerator.generatePgpChat(message, true);
738 }
739 } else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
740 Contact contact = message.getConversation().getContact();
741 Presences presences = contact.getPresences();
742 if ((message.getCounterpart() != null)
743 && (presences.has(message.getCounterpart().getResourcepart()))) {
744 markMessage(message, Message.STATUS_OFFERED);
745 mJingleConnectionManager.createNewConnection(message);
746 } else {
747 if (presences.size() == 1) {
748 String presence = presences.asStringArray()[0];
749 try {
750 message.setCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
751 } catch (InvalidJidException e) {
752 return;
753 }
754 markMessage(message, Message.STATUS_OFFERED);
755 mJingleConnectionManager.createNewConnection(message);
756 }
757 }
758 }
759 if (packet != null) {
760 if (!account.getXmppConnection().getFeatures().sm()
761 && message.getConversation().getMode() != Conversation.MODE_MULTI) {
762 markMessage(message, Message.STATUS_SEND);
763 } else {
764 markMessage(message, Message.STATUS_UNSEND);
765 }
766 sendMessagePacket(account, packet);
767 }
768 }
769
770 public void fetchRosterFromServer(Account account) {
771 IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
772 if (!"".equals(account.getRosterVersion())) {
773 Log.d(Config.LOGTAG, account.getJid().toBareJid()
774 + ": fetching roster version " + account.getRosterVersion());
775 } else {
776 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
777 }
778 iqPacket.query("jabber:iq:roster").setAttribute("ver",
779 account.getRosterVersion());
780 account.getXmppConnection().sendIqPacket(iqPacket,
781 new OnIqPacketReceived() {
782
783 @Override
784 public void onIqPacketReceived(final Account account,
785 IqPacket packet) {
786 Element query = packet.findChild("query");
787 if (query != null) {
788 account.getRoster().markAllAsNotInRoster();
789 mIqParser.rosterItems(account, query);
790 }
791 }
792 });
793 }
794
795 public void fetchBookmarks(Account account) {
796 IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
797 Element query = iqPacket.query("jabber:iq:private");
798 query.addChild("storage", "storage:bookmarks");
799 OnIqPacketReceived callback = new OnIqPacketReceived() {
800
801 @Override
802 public void onIqPacketReceived(Account account, IqPacket packet) {
803 Element query = packet.query();
804 List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
805 Element storage = query.findChild("storage",
806 "storage:bookmarks");
807 if (storage != null) {
808 for (Element item : storage.getChildren()) {
809 if (item.getName().equals("conference")) {
810 Bookmark bookmark = Bookmark.parse(item, account);
811 bookmarks.add(bookmark);
812 Conversation conversation = find(bookmark);
813 if (conversation != null) {
814 conversation.setBookmark(bookmark);
815 } else if (bookmark.autojoin() && bookmark.getJid() != null) {
816 conversation = findOrCreateConversation(
817 account, bookmark.getJid(), true);
818 conversation.setBookmark(bookmark);
819 joinMuc(conversation);
820 }
821 }
822 }
823 }
824 account.setBookmarks(bookmarks);
825 }
826 };
827 sendIqPacket(account, iqPacket, callback);
828
829 }
830
831 public void pushBookmarks(Account account) {
832 IqPacket iqPacket = new IqPacket(IqPacket.TYPE_SET);
833 Element query = iqPacket.query("jabber:iq:private");
834 Element storage = query.addChild("storage", "storage:bookmarks");
835 for (Bookmark bookmark : account.getBookmarks()) {
836 storage.addChild(bookmark);
837 }
838 sendIqPacket(account, iqPacket, null);
839 }
840
841 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
842 if (mPhoneContactMergerThread != null) {
843 mPhoneContactMergerThread.interrupt();
844 }
845 mPhoneContactMergerThread = new Thread(new Runnable() {
846 @Override
847 public void run() {
848 Log.d(Config.LOGTAG,"start merging phone contacts with roster");
849 for (Account account : accounts) {
850 account.getRoster().clearSystemAccounts();
851 for (Bundle phoneContact : phoneContacts) {
852 if (Thread.interrupted()) {
853 Log.d(Config.LOGTAG,"interrupted merging phone contacts");
854 return;
855 }
856 Jid jid;
857 try {
858 jid = Jid.fromString(phoneContact.getString("jid"));
859 } catch (final InvalidJidException e) {
860 break;
861 }
862 final Contact contact = account.getRoster()
863 .getContact(jid);
864 String systemAccount = phoneContact.getInt("phoneid")
865 + "#"
866 + phoneContact.getString("lookup");
867 contact.setSystemAccount(systemAccount);
868 contact.setPhotoUri(phoneContact.getString("photouri"));
869 getAvatarService().clear(contact);
870 contact.setSystemName(phoneContact.getString("displayname"));
871 }
872 }
873 Log.d(Config.LOGTAG,"finished merging phone contacts");
874 updateAccountUi();
875 }
876 });
877 mPhoneContactMergerThread.start();
878 }
879
880 private void initConversations() {
881 synchronized (this.conversations) {
882 Hashtable<String, Account> accountLookupTable = new Hashtable<>();
883 for (Account account : this.accounts) {
884 accountLookupTable.put(account.getUuid(), account);
885 }
886 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
887 for (Conversation conv : this.conversations) {
888 Account account = accountLookupTable.get(conv.getAccountUuid());
889 conv.setAccount(account);
890 conv.addAll(0, databaseBackend.getMessages(conv, 50));
891 checkDeletedFiles(conv);
892 }
893 }
894 }
895
896 public List<Conversation> getConversations() {
897 return this.conversations;
898 }
899
900 private void checkDeletedFiles(Conversation conversation) {
901 for (Message message : conversation.getMessages()) {
902 if ((message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE)
903 && message.getEncryption() != Message.ENCRYPTION_PGP) {
904 if (!getFileBackend().isFileAvailable(message)) {
905 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
906 }
907 }
908 }
909 }
910
911 private void markFileDeleted(String uuid) {
912 for (Conversation conversation : getConversations()) {
913 for (Message message : conversation.getMessages()) {
914 if (message.getType() == Message.TYPE_IMAGE
915 && message.getEncryption() != Message.ENCRYPTION_PGP
916 && message.getUuid().equals(uuid)) {
917 if (!getFileBackend().isFileAvailable(message)) {
918 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
919 updateConversationUi();
920 }
921 return;
922 }
923 }
924 }
925 }
926
927 public void populateWithOrderedConversations(final List<Conversation> list) {
928 populateWithOrderedConversations(list, true);
929 }
930
931 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeConferences) {
932 list.clear();
933 if (includeConferences) {
934 list.addAll(getConversations());
935 } else {
936 for (Conversation conversation : getConversations()) {
937 if (conversation.getMode() == Conversation.MODE_SINGLE) {
938 list.add(conversation);
939 }
940 }
941 }
942 Collections.sort(list, new Comparator<Conversation>() {
943 @Override
944 public int compare(Conversation lhs, Conversation rhs) {
945 Message left = lhs.getLatestMessage();
946 Message right = rhs.getLatestMessage();
947 if (left.getTimeSent() > right.getTimeSent()) {
948 return -1;
949 } else if (left.getTimeSent() < right.getTimeSent()) {
950 return 1;
951 } else {
952 return 0;
953 }
954 }
955 });
956 }
957
958 public int loadMoreMessages(Conversation conversation, long timestamp) {
959 List<Message> messages = databaseBackend.getMessages(conversation, 50,
960 timestamp);
961 for (Message message : messages) {
962 message.setConversation(conversation);
963 }
964 conversation.addAll(0, messages);
965 return messages.size();
966 }
967
968 public List<Account> getAccounts() {
969 return this.accounts;
970 }
971
972 public Conversation find(List<Conversation> haystack, Contact contact) {
973 for (Conversation conversation : haystack) {
974 if (conversation.getContact() == contact) {
975 return conversation;
976 }
977 }
978 return null;
979 }
980
981 public Conversation find(final List<Conversation> haystack,
982 final Account account,
983 final Jid jid) {
984 if (jid == null ) {
985 return null;
986 }
987 for (Conversation conversation : haystack) {
988 if ((account == null || conversation.getAccount() == account)
989 && (conversation.getContactJid().toBareJid().equals(jid.toBareJid()))) {
990 return conversation;
991 }
992 }
993 return null;
994 }
995
996 public Conversation findOrCreateConversation(final Account account, final Jid jid,final boolean muc) {
997 return this.findOrCreateConversation(account,jid,muc,null);
998 }
999
1000 public Conversation findOrCreateConversation(final Account account, final Jid jid,final boolean muc, final MessageArchiveService.Query query) {
1001 synchronized (this.conversations) {
1002 Conversation conversation = find(account, jid);
1003 if (conversation != null) {
1004 return conversation;
1005 }
1006 conversation = databaseBackend.findConversation(account, jid);
1007 if (conversation != null) {
1008 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1009 conversation.setAccount(account);
1010 if (muc) {
1011 conversation.setMode(Conversation.MODE_MULTI);
1012 } else {
1013 conversation.setMode(Conversation.MODE_SINGLE);
1014 }
1015 conversation.addAll(0, databaseBackend.getMessages(conversation, 50));
1016 this.databaseBackend.updateConversation(conversation);
1017 } else {
1018 String conversationName;
1019 Contact contact = account.getRoster().getContact(jid);
1020 if (contact != null) {
1021 conversationName = contact.getDisplayName();
1022 } else {
1023 conversationName = jid.getLocalpart();
1024 }
1025 if (muc) {
1026 conversation = new Conversation(conversationName, account, jid,
1027 Conversation.MODE_MULTI);
1028 } else {
1029 conversation = new Conversation(conversationName, account, jid,
1030 Conversation.MODE_SINGLE);
1031 }
1032 this.databaseBackend.createConversation(conversation);
1033 }
1034 if (query == null) {
1035 this.mMessageArchiveService.query(conversation);
1036 } else {
1037 if (query.getConversation() == null) {
1038 this.mMessageArchiveService.query(conversation,query.getStart());
1039 }
1040 }
1041 this.conversations.add(conversation);
1042 updateConversationUi();
1043 return conversation;
1044 }
1045 }
1046
1047 public void archiveConversation(Conversation conversation) {
1048 synchronized (this.conversations) {
1049 if (conversation.getMode() == Conversation.MODE_MULTI) {
1050 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1051 Bookmark bookmark = conversation.getBookmark();
1052 if (bookmark != null && bookmark.autojoin()) {
1053 bookmark.setAutojoin(false);
1054 pushBookmarks(bookmark.getAccount());
1055 }
1056 }
1057 leaveMuc(conversation);
1058 } else {
1059 conversation.endOtrIfNeeded();
1060 }
1061 this.databaseBackend.updateConversation(conversation);
1062 this.conversations.remove(conversation);
1063 updateConversationUi();
1064 }
1065 }
1066
1067 public void clearConversationHistory(Conversation conversation) {
1068 this.databaseBackend.deleteMessagesInConversation(conversation);
1069 conversation.getMessages().clear();
1070 updateConversationUi();
1071 }
1072
1073 public void createAccount(Account account) {
1074 account.initOtrEngine(this);
1075 databaseBackend.createAccount(account);
1076 this.accounts.add(account);
1077 this.reconnectAccount(account, false);
1078 updateAccountUi();
1079 }
1080
1081 public void updateAccount(Account account) {
1082 this.statusListener.onStatusChanged(account);
1083 databaseBackend.updateAccount(account);
1084 reconnectAccount(account, false);
1085 updateAccountUi();
1086 getNotificationService().updateErrorNotification();
1087 }
1088
1089 public void deleteAccount(Account account) {
1090 synchronized (this.conversations) {
1091 for (Conversation conversation : conversations) {
1092 if (conversation.getAccount() == account) {
1093 if (conversation.getMode() == Conversation.MODE_MULTI) {
1094 leaveMuc(conversation);
1095 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1096 conversation.endOtrIfNeeded();
1097 }
1098 conversations.remove(conversation);
1099 }
1100 }
1101 if (account.getXmppConnection() != null) {
1102 this.disconnect(account, true);
1103 }
1104 databaseBackend.deleteAccount(account);
1105 this.accounts.remove(account);
1106 updateAccountUi();
1107 getNotificationService().updateErrorNotification();
1108 }
1109 }
1110
1111 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1112 synchronized (this) {
1113 if (checkListeners()) {
1114 switchToForeground();
1115 }
1116 this.mOnConversationUpdate = listener;
1117 this.mNotificationService.setIsInForeground(true);
1118 if (this.convChangedListenerCount < 2) {
1119 this.convChangedListenerCount++;
1120 }
1121 }
1122 }
1123
1124 public void removeOnConversationListChangedListener() {
1125 synchronized (this) {
1126 this.convChangedListenerCount--;
1127 if (this.convChangedListenerCount <= 0) {
1128 this.convChangedListenerCount = 0;
1129 this.mOnConversationUpdate = null;
1130 this.mNotificationService.setIsInForeground(false);
1131 if (checkListeners()) {
1132 switchToBackground();
1133 }
1134 }
1135 }
1136 }
1137
1138 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1139 synchronized (this) {
1140 if (checkListeners()) {
1141 switchToForeground();
1142 }
1143 this.mOnAccountUpdate = listener;
1144 if (this.accountChangedListenerCount < 2) {
1145 this.accountChangedListenerCount++;
1146 }
1147 }
1148 }
1149
1150 public void removeOnAccountListChangedListener() {
1151 synchronized (this) {
1152 this.accountChangedListenerCount--;
1153 if (this.accountChangedListenerCount <= 0) {
1154 this.mOnAccountUpdate = null;
1155 this.accountChangedListenerCount = 0;
1156 if (checkListeners()) {
1157 switchToBackground();
1158 }
1159 }
1160 }
1161 }
1162
1163 public void setOnRosterUpdateListener(OnRosterUpdate listener) {
1164 synchronized (this) {
1165 if (checkListeners()) {
1166 switchToForeground();
1167 }
1168 this.mOnRosterUpdate = listener;
1169 if (this.rosterChangedListenerCount < 2) {
1170 this.rosterChangedListenerCount++;
1171 }
1172 }
1173 }
1174
1175 public void removeOnRosterUpdateListener() {
1176 synchronized (this) {
1177 this.rosterChangedListenerCount--;
1178 if (this.rosterChangedListenerCount <= 0) {
1179 this.rosterChangedListenerCount = 0;
1180 this.mOnRosterUpdate = null;
1181 if (checkListeners()) {
1182 switchToBackground();
1183 }
1184 }
1185 }
1186 }
1187
1188 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1189 synchronized (this) {
1190 if (checkListeners()) {
1191 switchToForeground();
1192 }
1193 this.mOnMucRosterUpdate = listener;
1194 if (this.mucRosterChangedListenerCount < 2) {
1195 this.mucRosterChangedListenerCount++;
1196 }
1197 }
1198 }
1199
1200 public void removeOnMucRosterUpdateListener() {
1201 synchronized (this) {
1202 this.mucRosterChangedListenerCount--;
1203 if (this.mucRosterChangedListenerCount <= 0) {
1204 this.mucRosterChangedListenerCount = 0;
1205 this.mOnMucRosterUpdate = null;
1206 if (checkListeners()) {
1207 switchToBackground();
1208 }
1209 }
1210 }
1211 }
1212
1213 private boolean checkListeners() {
1214 return (this.mOnAccountUpdate == null
1215 && this.mOnConversationUpdate == null && this.mOnRosterUpdate == null);
1216 }
1217
1218 private void switchToForeground() {
1219 for (Account account : getAccounts()) {
1220 if (account.getStatus() == Account.State.ONLINE) {
1221 XmppConnection connection = account.getXmppConnection();
1222 if (connection != null && connection.getFeatures().csi()) {
1223 connection.sendActive();
1224 }
1225 }
1226 }
1227 Log.d(Config.LOGTAG, "app switched into foreground");
1228 }
1229
1230 private void switchToBackground() {
1231 for (Account account : getAccounts()) {
1232 if (account.getStatus() == Account.State.ONLINE) {
1233 XmppConnection connection = account.getXmppConnection();
1234 if (connection != null && connection.getFeatures().csi()) {
1235 connection.sendInactive();
1236 }
1237 }
1238 }
1239 this.mNotificationService.setIsInForeground(false);
1240 Log.d(Config.LOGTAG, "app switched into background");
1241 }
1242
1243 public void connectMultiModeConversations(Account account) {
1244 List<Conversation> conversations = getConversations();
1245 for (Conversation conversation : conversations) {
1246 if ((conversation.getMode() == Conversation.MODE_MULTI)
1247 && (conversation.getAccount() == account)) {
1248 joinMuc(conversation);
1249 }
1250 }
1251 }
1252
1253 public void joinMuc(Conversation conversation) {
1254 Account account = conversation.getAccount();
1255 account.pendingConferenceJoins.remove(conversation);
1256 account.pendingConferenceLeaves.remove(conversation);
1257 if (account.getStatus() == Account.State.ONLINE) {
1258 final String nick = conversation.getMucOptions().getProposedNick();
1259 final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1260 if (joinJid == null) {
1261 return; //safety net
1262 }
1263 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1264 PresencePacket packet = new PresencePacket();
1265 packet.setFrom(conversation.getAccount().getJid());
1266 packet.setTo(joinJid);
1267 Element x = packet.addChild("x","http://jabber.org/protocol/muc");
1268 if (conversation.getMucOptions().getPassword() != null) {
1269 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1270 }
1271 x.addChild("history").setAttribute("since",PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1272 String sig = account.getPgpSignature();
1273 if (sig != null) {
1274 packet.addChild("status").setContent("online");
1275 packet.addChild("x", "jabber:x:signed").setContent(sig);
1276 }
1277 sendPresencePacket(account, packet);
1278 if (!joinJid.equals(conversation.getContactJid())) {
1279 conversation.setContactJid(joinJid);
1280 databaseBackend.updateConversation(conversation);
1281 }
1282 } else {
1283 account.pendingConferenceJoins.add(conversation);
1284 }
1285 }
1286
1287 public void providePasswordForMuc(Conversation conversation, String password) {
1288 if (conversation.getMode() == Conversation.MODE_MULTI) {
1289 conversation.getMucOptions().setPassword(password);
1290 if (conversation.getBookmark() != null) {
1291 conversation.getBookmark().setAutojoin(true);
1292 pushBookmarks(conversation.getAccount());
1293 }
1294 databaseBackend.updateConversation(conversation);
1295 joinMuc(conversation);
1296 }
1297 }
1298
1299 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1300 final MucOptions options = conversation.getMucOptions();
1301 final Jid joinJid = options.createJoinJid(nick);
1302 if (options.online()) {
1303 Account account = conversation.getAccount();
1304 options.setOnRenameListener(new OnRenameListener() {
1305
1306 @Override
1307 public void onSuccess() {
1308 conversation.setContactJid(joinJid);
1309 databaseBackend.updateConversation(conversation);
1310 Bookmark bookmark = conversation.getBookmark();
1311 if (bookmark != null) {
1312 bookmark.setNick(nick);
1313 pushBookmarks(bookmark.getAccount());
1314 }
1315 callback.success(conversation);
1316 }
1317
1318 @Override
1319 public void onFailure() {
1320 callback.error(R.string.nick_in_use, conversation);
1321 }
1322 });
1323
1324 PresencePacket packet = new PresencePacket();
1325 packet.setTo(joinJid);
1326 packet.setFrom(conversation.getAccount().getJid());
1327
1328 String sig = account.getPgpSignature();
1329 if (sig != null) {
1330 packet.addChild("status").setContent("online");
1331 packet.addChild("x", "jabber:x:signed").setContent(sig);
1332 }
1333 sendPresencePacket(account, packet);
1334 } else {
1335 conversation.setContactJid(joinJid);
1336 databaseBackend.updateConversation(conversation);
1337 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1338 Bookmark bookmark = conversation.getBookmark();
1339 if (bookmark != null) {
1340 bookmark.setNick(nick);
1341 pushBookmarks(bookmark.getAccount());
1342 }
1343 joinMuc(conversation);
1344 }
1345 }
1346 }
1347
1348 public void leaveMuc(Conversation conversation) {
1349 Account account = conversation.getAccount();
1350 account.pendingConferenceJoins.remove(conversation);
1351 account.pendingConferenceLeaves.remove(conversation);
1352 if (account.getStatus() == Account.State.ONLINE) {
1353 PresencePacket packet = new PresencePacket();
1354 packet.setTo(conversation.getContactJid());
1355 packet.setFrom(conversation.getAccount().getJid());
1356 packet.setAttribute("type", "unavailable");
1357 sendPresencePacket(conversation.getAccount(), packet);
1358 conversation.getMucOptions().setOffline();
1359 conversation.deregisterWithBookmark();
1360 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1361 + ": leaving muc " + conversation.getContactJid());
1362 } else {
1363 account.pendingConferenceLeaves.add(conversation);
1364 }
1365 }
1366
1367 private String findConferenceServer(final Account account) {
1368 String server;
1369 if (account.getXmppConnection() != null) {
1370 server = account.getXmppConnection().getMucServer();
1371 if (server != null) {
1372 return server;
1373 }
1374 }
1375 for(Account other : getAccounts()) {
1376 if (other != account && other.getXmppConnection() != null) {
1377 server = other.getXmppConnection().getMucServer();
1378 if (server != null) {
1379 return server;
1380 }
1381 }
1382 }
1383 return null;
1384 }
1385
1386 public void createAdhocConference(final Account account, final List<Jid> jids, final UiCallback<Conversation> callback) {
1387 Log.d(Config.LOGTAG,account.getJid().toBareJid().toString()+": creating adhoc conference with "+ jids.toString());
1388 if (account.getStatus() == Account.State.ONLINE) {
1389 try {
1390 String server = findConferenceServer(account);
1391 if (server == null) {
1392 if (callback != null) {
1393 callback.error(R.string.no_conference_server_found,null);
1394 }
1395 return;
1396 }
1397 String name = new BigInteger(75,getRNG()).toString(32);
1398 Jid jid = Jid.fromParts(name,server,null);
1399 final Conversation conversation = findOrCreateConversation(account, jid, true);
1400 joinMuc(conversation);
1401 Bundle options = new Bundle();
1402 options.putString("muc#roomconfig_persistentroom", "1");
1403 options.putString("muc#roomconfig_membersonly", "1");
1404 options.putString("muc#roomconfig_publicroom", "0");
1405 options.putString("muc#roomconfig_whois", "anyone");
1406 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1407 @Override
1408 public void onPushSucceeded() {
1409 for(Jid invite : jids) {
1410 invite(conversation,invite);
1411 }
1412 if (callback != null) {
1413 callback.success(conversation);
1414 }
1415 }
1416
1417 @Override
1418 public void onPushFailed() {
1419 if (callback != null) {
1420 callback.error(R.string.conference_creation_failed, conversation);
1421 }
1422 }
1423 });
1424
1425 } catch (InvalidJidException e) {
1426 if (callback != null) {
1427 callback.error(R.string.conference_creation_failed, null);
1428 }
1429 }
1430 } else {
1431 if (callback != null) {
1432 callback.error(R.string.not_connected_try_again,null);
1433 }
1434 }
1435 }
1436
1437 public void pushConferenceConfiguration(final Conversation conversation,final Bundle options, final OnConferenceOptionsPushed callback) {
1438 IqPacket request = new IqPacket(IqPacket.TYPE_GET);
1439 request.setTo(conversation.getContactJid().toBareJid());
1440 request.query("http://jabber.org/protocol/muc#owner");
1441 sendIqPacket(conversation.getAccount(),request,new OnIqPacketReceived() {
1442 @Override
1443 public void onIqPacketReceived(Account account, IqPacket packet) {
1444 if (packet.getType() != IqPacket.TYPE_ERROR) {
1445 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1446 for (Field field : data.getFields()) {
1447 if (options.containsKey(field.getName())) {
1448 field.setValue(options.getString(field.getName()));
1449 }
1450 }
1451 data.submit();
1452 IqPacket set = new IqPacket(IqPacket.TYPE_SET);
1453 set.setTo(conversation.getContactJid().toBareJid());
1454 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1455 sendIqPacket(account, set, new OnIqPacketReceived() {
1456 @Override
1457 public void onIqPacketReceived(Account account, IqPacket packet) {
1458 if (packet.getType() == IqPacket.TYPE_RESULT) {
1459 if (callback != null) {
1460 callback.onPushSucceeded();
1461 }
1462 } else {
1463 if (callback != null) {
1464 callback.onPushFailed();
1465 }
1466 }
1467 }
1468 });
1469 } else {
1470 if (callback != null) {
1471 callback.onPushFailed();
1472 }
1473 }
1474 }
1475 });
1476 }
1477
1478 public void disconnect(Account account, boolean force) {
1479 if ((account.getStatus() == Account.State.ONLINE)
1480 || (account.getStatus() == Account.State.DISABLED)) {
1481 if (!force) {
1482 List<Conversation> conversations = getConversations();
1483 for (Conversation conversation : conversations) {
1484 if (conversation.getAccount() == account) {
1485 if (conversation.getMode() == Conversation.MODE_MULTI) {
1486 leaveMuc(conversation);
1487 } else {
1488 if (conversation.endOtrIfNeeded()) {
1489 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1490 + ": ended otr session with "
1491 + conversation.getContactJid());
1492 }
1493 }
1494 }
1495 }
1496 }
1497 account.getXmppConnection().disconnect(force);
1498 }
1499 }
1500
1501 @Override
1502 public IBinder onBind(Intent intent) {
1503 return mBinder;
1504 }
1505
1506 public void updateMessage(Message message) {
1507 databaseBackend.updateMessage(message);
1508 updateConversationUi();
1509 }
1510
1511 protected void syncDirtyContacts(Account account) {
1512 for (Contact contact : account.getRoster().getContacts()) {
1513 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1514 pushContactToServer(contact);
1515 }
1516 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1517 deleteContactOnServer(contact);
1518 }
1519 }
1520 }
1521
1522 public void createContact(Contact contact) {
1523 SharedPreferences sharedPref = getPreferences();
1524 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1525 if (autoGrant) {
1526 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1527 contact.setOption(Contact.Options.ASKING);
1528 }
1529 pushContactToServer(contact);
1530 }
1531
1532 public void onOtrSessionEstablished(Conversation conversation) {
1533 Account account = conversation.getAccount();
1534 List<Message> messages = conversation.getMessages();
1535 Session otrSession = conversation.getOtrSession();
1536 Log.d(Config.LOGTAG,
1537 account.getJid().toBareJid() + " otr session established with "
1538 + conversation.getContactJid() + "/"
1539 + otrSession.getSessionID().getUserID());
1540 for (Message msg : messages) {
1541 if ((msg.getStatus() == Message.STATUS_UNSEND || msg.getStatus() == Message.STATUS_WAITING)
1542 && (msg.getEncryption() == Message.ENCRYPTION_OTR)) {
1543 SessionID id = otrSession.getSessionID();
1544 try {
1545 msg.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1546 } catch (InvalidJidException e) {
1547 break;
1548 }
1549 if (msg.getType() == Message.TYPE_TEXT) {
1550 MessagePacket outPacket = mMessageGenerator
1551 .generateOtrChat(msg, true);
1552 if (outPacket != null) {
1553 msg.setStatus(Message.STATUS_SEND);
1554 databaseBackend.updateMessage(msg);
1555 sendMessagePacket(account, outPacket);
1556 }
1557 } else if (msg.getType() == Message.TYPE_IMAGE || msg.getType() == Message.TYPE_FILE) {
1558 mJingleConnectionManager.createNewConnection(msg);
1559 }
1560 }
1561 }
1562 updateConversationUi();
1563 }
1564
1565 public boolean renewSymmetricKey(Conversation conversation) {
1566 Account account = conversation.getAccount();
1567 byte[] symmetricKey = new byte[32];
1568 this.mRandom.nextBytes(symmetricKey);
1569 Session otrSession = conversation.getOtrSession();
1570 if (otrSession != null) {
1571 MessagePacket packet = new MessagePacket();
1572 packet.setType(MessagePacket.TYPE_CHAT);
1573 packet.setFrom(account.getJid());
1574 packet.addChild("private", "urn:xmpp:carbons:2");
1575 packet.addChild("no-copy", "urn:xmpp:hints");
1576 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1577 + otrSession.getSessionID().getUserID());
1578 try {
1579 packet.setBody(otrSession
1580 .transformSending(CryptoHelper.FILETRANSFER
1581 + CryptoHelper.bytesToHex(symmetricKey)));
1582 sendMessagePacket(account, packet);
1583 conversation.setSymmetricKey(symmetricKey);
1584 return true;
1585 } catch (OtrException e) {
1586 return false;
1587 }
1588 }
1589 return false;
1590 }
1591
1592 public void pushContactToServer(Contact contact) {
1593 contact.resetOption(Contact.Options.DIRTY_DELETE);
1594 contact.setOption(Contact.Options.DIRTY_PUSH);
1595 Account account = contact.getAccount();
1596 if (account.getStatus() == Account.State.ONLINE) {
1597 boolean ask = contact.getOption(Contact.Options.ASKING);
1598 boolean sendUpdates = contact
1599 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1600 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1601 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1602 iq.query("jabber:iq:roster").addChild(contact.asElement());
1603 account.getXmppConnection().sendIqPacket(iq, null);
1604 if (sendUpdates) {
1605 sendPresencePacket(account,
1606 mPresenceGenerator.sendPresenceUpdatesTo(contact));
1607 }
1608 if (ask) {
1609 sendPresencePacket(account,
1610 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1611 }
1612 }
1613 }
1614
1615 public void publishAvatar(Account account, Uri image,
1616 final UiCallback<Avatar> callback) {
1617 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1618 final int size = Config.AVATAR_SIZE;
1619 final Avatar avatar = getFileBackend()
1620 .getPepAvatar(image, size, format);
1621 if (avatar != null) {
1622 avatar.height = size;
1623 avatar.width = size;
1624 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1625 avatar.type = "image/webp";
1626 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1627 avatar.type = "image/jpeg";
1628 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1629 avatar.type = "image/png";
1630 }
1631 if (!getFileBackend().save(avatar)) {
1632 callback.error(R.string.error_saving_avatar, avatar);
1633 return;
1634 }
1635 IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1636 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1637
1638 @Override
1639 public void onIqPacketReceived(Account account, IqPacket result) {
1640 if (result.getType() == IqPacket.TYPE_RESULT) {
1641 IqPacket packet = XmppConnectionService.this.mIqGenerator
1642 .publishAvatarMetadata(avatar);
1643 sendIqPacket(account, packet, new OnIqPacketReceived() {
1644
1645 @Override
1646 public void onIqPacketReceived(Account account,
1647 IqPacket result) {
1648 if (result.getType() == IqPacket.TYPE_RESULT) {
1649 if (account.setAvatar(avatar.getFilename())) {
1650 databaseBackend.updateAccount(account);
1651 }
1652 callback.success(avatar);
1653 } else {
1654 callback.error(
1655 R.string.error_publish_avatar_server_reject,
1656 avatar);
1657 }
1658 }
1659 });
1660 } else {
1661 callback.error(
1662 R.string.error_publish_avatar_server_reject,
1663 avatar);
1664 }
1665 }
1666 });
1667 } else {
1668 callback.error(R.string.error_publish_avatar_converting, null);
1669 }
1670 }
1671
1672 public void fetchAvatar(Account account, Avatar avatar) {
1673 fetchAvatar(account, avatar, null);
1674 }
1675
1676 public void fetchAvatar(Account account, final Avatar avatar,
1677 final UiCallback<Avatar> callback) {
1678 IqPacket packet = this.mIqGenerator.retrieveAvatar(avatar);
1679 sendIqPacket(account, packet, new OnIqPacketReceived() {
1680
1681 @Override
1682 public void onIqPacketReceived(Account account, IqPacket result) {
1683 final String ERROR = account.getJid().toBareJid()
1684 + ": fetching avatar for " + avatar.owner + " failed ";
1685 if (result.getType() == IqPacket.TYPE_RESULT) {
1686 avatar.image = mIqParser.avatarData(result);
1687 if (avatar.image != null) {
1688 if (getFileBackend().save(avatar)) {
1689 if (account.getJid().toBareJid().equals(avatar.owner)) {
1690 if (account.setAvatar(avatar.getFilename())) {
1691 databaseBackend.updateAccount(account);
1692 }
1693 getAvatarService().clear(account);
1694 updateConversationUi();
1695 updateAccountUi();
1696 } else {
1697 Contact contact = account.getRoster()
1698 .getContact(avatar.owner);
1699 contact.setAvatar(avatar.getFilename());
1700 getAvatarService().clear(contact);
1701 updateConversationUi();
1702 updateRosterUi();
1703 }
1704 if (callback != null) {
1705 callback.success(avatar);
1706 }
1707 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1708 + ": succesfully fetched avatar for "
1709 + avatar.owner);
1710 return;
1711 }
1712 } else {
1713
1714 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1715 }
1716 } else {
1717 Element error = result.findChild("error");
1718 if (error == null) {
1719 Log.d(Config.LOGTAG, ERROR + "(server error)");
1720 } else {
1721 Log.d(Config.LOGTAG, ERROR + error.toString());
1722 }
1723 }
1724 if (callback != null) {
1725 callback.error(0, null);
1726 }
1727
1728 }
1729 });
1730 }
1731
1732 public void checkForAvatar(Account account,
1733 final UiCallback<Avatar> callback) {
1734 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
1735 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1736
1737 @Override
1738 public void onIqPacketReceived(Account account, IqPacket packet) {
1739 if (packet.getType() == IqPacket.TYPE_RESULT) {
1740 Element pubsub = packet.findChild("pubsub",
1741 "http://jabber.org/protocol/pubsub");
1742 if (pubsub != null) {
1743 Element items = pubsub.findChild("items");
1744 if (items != null) {
1745 Avatar avatar = Avatar.parseMetadata(items);
1746 if (avatar != null) {
1747 avatar.owner = account.getJid().toBareJid();
1748 if (fileBackend.isAvatarCached(avatar)) {
1749 if (account.setAvatar(avatar.getFilename())) {
1750 databaseBackend.updateAccount(account);
1751 }
1752 getAvatarService().clear(account);
1753 callback.success(avatar);
1754 } else {
1755 fetchAvatar(account, avatar, callback);
1756 }
1757 return;
1758 }
1759 }
1760 }
1761 }
1762 callback.error(0, null);
1763 }
1764 });
1765 }
1766
1767 public void deleteContactOnServer(Contact contact) {
1768 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
1769 contact.resetOption(Contact.Options.DIRTY_PUSH);
1770 contact.setOption(Contact.Options.DIRTY_DELETE);
1771 Account account = contact.getAccount();
1772 if (account.getStatus() == Account.State.ONLINE) {
1773 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1774 Element item = iq.query("jabber:iq:roster").addChild("item");
1775 item.setAttribute("jid", contact.getJid().toString());
1776 item.setAttribute("subscription", "remove");
1777 account.getXmppConnection().sendIqPacket(iq, null);
1778 }
1779 }
1780
1781 public void updateConversation(Conversation conversation) {
1782 this.databaseBackend.updateConversation(conversation);
1783 }
1784
1785 public void reconnectAccount(final Account account, final boolean force) {
1786 new Thread(new Runnable() {
1787
1788 @Override
1789 public void run() {
1790 if (account.getXmppConnection() != null) {
1791 disconnect(account, force);
1792 }
1793 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1794 if (account.getXmppConnection() == null) {
1795 account.setXmppConnection(createConnection(account));
1796 }
1797 Thread thread = new Thread(account.getXmppConnection());
1798 thread.start();
1799 scheduleWakeupCall((int) (Config.CONNECT_TIMEOUT * 1.2),
1800 false);
1801 } else {
1802 account.getRoster().clearPresences();
1803 account.setXmppConnection(null);
1804 }
1805 }
1806 }).start();
1807 }
1808
1809 public void invite(Conversation conversation, Jid contact) {
1810 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
1811 sendMessagePacket(conversation.getAccount(), packet);
1812 }
1813
1814 public void resetSendingToWaiting(Account account) {
1815 for (Conversation conversation : getConversations()) {
1816 if (conversation.getAccount() == account) {
1817 for (Message message : conversation.getMessages()) {
1818 if (message.getType() != Message.TYPE_IMAGE
1819 && message.getStatus() == Message.STATUS_UNSEND) {
1820 markMessage(message, Message.STATUS_WAITING);
1821 }
1822 }
1823 }
1824 }
1825 }
1826
1827 public boolean markMessage(final Account account, final Jid recipient, final String uuid,
1828 final int status) {
1829 if (uuid == null) {
1830 return false;
1831 } else {
1832 for (Conversation conversation : getConversations()) {
1833 if (conversation.getContactJid().equals(recipient)
1834 && conversation.getAccount().equals(account)) {
1835 return markMessage(conversation, uuid, status);
1836 }
1837 }
1838 return false;
1839 }
1840 }
1841
1842 public boolean markMessage(Conversation conversation, String uuid,
1843 int status) {
1844 if (uuid == null) {
1845 return false;
1846 } else {
1847 for (Message message : conversation.getMessages()) {
1848 if (uuid.equals(message.getUuid())
1849 || (message.getStatus() >= Message.STATUS_SEND && uuid
1850 .equals(message.getRemoteMsgId()))) {
1851 markMessage(message, status);
1852 return true;
1853 }
1854 }
1855 return false;
1856 }
1857 }
1858
1859 public void markMessage(Message message, int status) {
1860 if (status == Message.STATUS_SEND_FAILED
1861 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
1862 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
1863 return;
1864 }
1865 message.setStatus(status);
1866 databaseBackend.updateMessage(message);
1867 updateConversationUi();
1868 }
1869
1870 public SharedPreferences getPreferences() {
1871 return PreferenceManager
1872 .getDefaultSharedPreferences(getApplicationContext());
1873 }
1874
1875 public boolean forceEncryption() {
1876 return getPreferences().getBoolean("force_encryption", false);
1877 }
1878
1879 public boolean confirmMessages() {
1880 return getPreferences().getBoolean("confirm_messages", true);
1881 }
1882
1883 public boolean saveEncryptedMessages() {
1884 return !getPreferences().getBoolean("dont_save_encrypted", false);
1885 }
1886
1887 public boolean indicateReceived() {
1888 return getPreferences().getBoolean("indicate_received", false);
1889 }
1890
1891 public void updateConversationUi() {
1892 if (mOnConversationUpdate != null) {
1893 mOnConversationUpdate.onConversationUpdate();
1894 }
1895 }
1896
1897 public void updateAccountUi() {
1898 if (mOnAccountUpdate != null) {
1899 mOnAccountUpdate.onAccountUpdate();
1900 }
1901 }
1902
1903 public void updateRosterUi() {
1904 if (mOnRosterUpdate != null) {
1905 mOnRosterUpdate.onRosterUpdate();
1906 }
1907 }
1908
1909 public void updateMucRosterUi() {
1910 if (mOnMucRosterUpdate != null) {
1911 mOnMucRosterUpdate.onMucRosterUpdate();
1912 }
1913 }
1914
1915 public Account findAccountByJid(final Jid accountJid) {
1916 for (Account account : this.accounts) {
1917 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
1918 return account;
1919 }
1920 }
1921 return null;
1922 }
1923
1924 public Conversation findConversationByUuid(String uuid) {
1925 for (Conversation conversation : getConversations()) {
1926 if (conversation.getUuid().equals(uuid)) {
1927 return conversation;
1928 }
1929 }
1930 return null;
1931 }
1932
1933 public void markRead(Conversation conversation, boolean calledByUi) {
1934 mNotificationService.clear(conversation);
1935 final Message markable = conversation.getLatestMarkableMessage();
1936 conversation.markRead();
1937 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null && calledByUi) {
1938 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()+ ": sending read marker to " + markable.getCounterpart().toString());
1939 Account account = conversation.getAccount();
1940 final Jid to = markable.getCounterpart();
1941 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
1942 this.sendMessagePacket(conversation.getAccount(),packet);
1943 }
1944 if (!calledByUi) {
1945 updateConversationUi();
1946 }
1947 }
1948
1949 public void failWaitingOtrMessages(Conversation conversation) {
1950 for (Message message : conversation.getMessages()) {
1951 if (message.getEncryption() == Message.ENCRYPTION_OTR
1952 && message.getStatus() == Message.STATUS_WAITING) {
1953 markMessage(message, Message.STATUS_SEND_FAILED);
1954 }
1955 }
1956 }
1957
1958 public SecureRandom getRNG() {
1959 return this.mRandom;
1960 }
1961
1962 public MemorizingTrustManager getMemorizingTrustManager() {
1963 return this.mMemorizingTrustManager;
1964 }
1965
1966 public PowerManager getPowerManager() {
1967 return this.pm;
1968 }
1969
1970 public LruCache<String, Bitmap> getBitmapCache() {
1971 return this.mBitmapCache;
1972 }
1973
1974 public void syncRosterToDisk(final Account account) {
1975 new Thread(new Runnable() {
1976
1977 @Override
1978 public void run() {
1979 databaseBackend.writeRoster(account.getRoster());
1980 }
1981 }).start();
1982
1983 }
1984
1985 public List<String> getKnownHosts() {
1986 List<String> hosts = new ArrayList<>();
1987 for (Account account : getAccounts()) {
1988 if (!hosts.contains(account.getServer().toString())) {
1989 hosts.add(account.getServer().toString());
1990 }
1991 for (Contact contact : account.getRoster().getContacts()) {
1992 if (contact.showInRoster()) {
1993 final String server = contact.getServer().toString();
1994 if (server != null && !hosts.contains(server)) {
1995 hosts.add(server);
1996 }
1997 }
1998 }
1999 }
2000 return hosts;
2001 }
2002
2003 public List<String> getKnownConferenceHosts() {
2004 ArrayList<String> mucServers = new ArrayList<>();
2005 for (Account account : accounts) {
2006 if (account.getXmppConnection() != null) {
2007 String server = account.getXmppConnection().getMucServer();
2008 if (server != null && !mucServers.contains(server)) {
2009 mucServers.add(server);
2010 }
2011 }
2012 }
2013 return mucServers;
2014 }
2015
2016 public void sendMessagePacket(Account account, MessagePacket packet) {
2017 XmppConnection connection = account.getXmppConnection();
2018 if (connection != null) {
2019 connection.sendMessagePacket(packet);
2020 }
2021 }
2022
2023 public void sendPresencePacket(Account account, PresencePacket packet) {
2024 XmppConnection connection = account.getXmppConnection();
2025 if (connection != null) {
2026 connection.sendPresencePacket(packet);
2027 }
2028 }
2029
2030 public void sendIqPacket(Account account, IqPacket packet,
2031 OnIqPacketReceived callback) {
2032 XmppConnection connection = account.getXmppConnection();
2033 if (connection != null) {
2034 connection.sendIqPacket(packet, callback);
2035 }
2036 }
2037
2038 public MessageGenerator getMessageGenerator() {
2039 return this.mMessageGenerator;
2040 }
2041
2042 public PresenceGenerator getPresenceGenerator() {
2043 return this.mPresenceGenerator;
2044 }
2045
2046 public IqGenerator getIqGenerator() {
2047 return this.mIqGenerator;
2048 }
2049
2050 public JingleConnectionManager getJingleConnectionManager() {
2051 return this.mJingleConnectionManager;
2052 }
2053
2054 public MessageArchiveService getMessageArchiveService() {
2055 return this.mMessageArchiveService;
2056 }
2057
2058 public List<Contact> findContacts(Jid jid) {
2059 ArrayList<Contact> contacts = new ArrayList<>();
2060 for (Account account : getAccounts()) {
2061 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2062 Contact contact = account.getRoster().getContactFromRoster(jid);
2063 if (contact != null) {
2064 contacts.add(contact);
2065 }
2066 }
2067 }
2068 return contacts;
2069 }
2070
2071 public NotificationService getNotificationService() {
2072 return this.mNotificationService;
2073 }
2074
2075 public HttpConnectionManager getHttpConnectionManager() {
2076 return this.mHttpConnectionManager;
2077 }
2078
2079 public void resendFailedMessages(Message message) {
2080 List<Message> messages = new ArrayList<>();
2081 Message current = message;
2082 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2083 messages.add(current);
2084 if (current.mergeable(current.next())) {
2085 current = current.next();
2086 } else {
2087 break;
2088 }
2089 }
2090 for (Message msg : messages) {
2091 markMessage(msg, Message.STATUS_WAITING);
2092 this.resendMessage(msg);
2093 }
2094 }
2095
2096 public interface OnConversationUpdate {
2097 public void onConversationUpdate();
2098 }
2099
2100 public interface OnAccountUpdate {
2101 public void onAccountUpdate();
2102 }
2103
2104 public interface OnRosterUpdate {
2105 public void onRosterUpdate();
2106 }
2107
2108 public interface OnMucRosterUpdate {
2109 public void onMucRosterUpdate();
2110 }
2111
2112 private interface OnConferenceOptionsPushed {
2113 public void onPushSucceeded();
2114 public void onPushFailed();
2115 }
2116
2117 public class XmppConnectionBinder extends Binder {
2118 public XmppConnectionService getService() {
2119 return XmppConnectionService.this;
2120 }
2121 }
2122}