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.Looper;
20import android.os.PowerManager;
21import android.os.PowerManager.WakeLock;
22import android.os.SystemClock;
23import android.preference.PreferenceManager;
24import android.provider.ContactsContract;
25import android.util.Log;
26import android.util.LruCache;
27
28import net.java.otr4j.OtrException;
29import net.java.otr4j.session.Session;
30import net.java.otr4j.session.SessionID;
31import net.java.otr4j.session.SessionImpl;
32import net.java.otr4j.session.SessionStatus;
33
34import org.openintents.openpgp.util.OpenPgpApi;
35import org.openintents.openpgp.util.OpenPgpServiceConnection;
36
37import java.math.BigInteger;
38import java.security.SecureRandom;
39import java.util.ArrayList;
40import java.util.Arrays;
41import java.util.Collection;
42import java.util.Collections;
43import java.util.Comparator;
44import java.util.Hashtable;
45import java.util.Iterator;
46import java.util.List;
47import java.util.Locale;
48import java.util.Map;
49import java.util.concurrent.CopyOnWriteArrayList;
50
51import de.duenndns.ssl.MemorizingTrustManager;
52import eu.siacs.conversations.Config;
53import eu.siacs.conversations.R;
54import eu.siacs.conversations.crypto.PgpEngine;
55import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
56import eu.siacs.conversations.entities.Account;
57import eu.siacs.conversations.entities.Blockable;
58import eu.siacs.conversations.entities.Bookmark;
59import eu.siacs.conversations.entities.Contact;
60import eu.siacs.conversations.entities.Conversation;
61import eu.siacs.conversations.entities.Message;
62import eu.siacs.conversations.entities.MucOptions;
63import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
64import eu.siacs.conversations.entities.Transferable;
65import eu.siacs.conversations.entities.TransferablePlaceholder;
66import eu.siacs.conversations.generator.IqGenerator;
67import eu.siacs.conversations.generator.MessageGenerator;
68import eu.siacs.conversations.generator.PresenceGenerator;
69import eu.siacs.conversations.http.HttpConnectionManager;
70import eu.siacs.conversations.parser.IqParser;
71import eu.siacs.conversations.parser.MessageParser;
72import eu.siacs.conversations.parser.PresenceParser;
73import eu.siacs.conversations.persistance.DatabaseBackend;
74import eu.siacs.conversations.persistance.FileBackend;
75import eu.siacs.conversations.ui.UiCallback;
76import eu.siacs.conversations.utils.CryptoHelper;
77import eu.siacs.conversations.utils.ExceptionHelper;
78import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
79import eu.siacs.conversations.utils.PRNGFixes;
80import eu.siacs.conversations.utils.PhoneHelper;
81import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
82import eu.siacs.conversations.utils.Xmlns;
83import eu.siacs.conversations.xml.Element;
84import eu.siacs.conversations.xmpp.OnBindListener;
85import eu.siacs.conversations.xmpp.OnContactStatusChanged;
86import eu.siacs.conversations.xmpp.OnIqPacketReceived;
87import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
88import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
89import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
90import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
91import eu.siacs.conversations.xmpp.OnStatusChanged;
92import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
93import eu.siacs.conversations.xmpp.XmppConnection;
94import eu.siacs.conversations.xmpp.chatstate.ChatState;
95import eu.siacs.conversations.xmpp.forms.Data;
96import eu.siacs.conversations.xmpp.forms.Field;
97import eu.siacs.conversations.xmpp.jid.InvalidJidException;
98import eu.siacs.conversations.xmpp.jid.Jid;
99import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
100import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
101import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
102import eu.siacs.conversations.xmpp.pep.Avatar;
103import eu.siacs.conversations.xmpp.stanzas.IqPacket;
104import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
105import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
106import me.leolin.shortcutbadger.ShortcutBadger;
107
108public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
109
110 public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
111 public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
112 private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
113 public static final String ACTION_TRY_AGAIN = "try_again";
114 public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
115 private ContentObserver contactObserver = new ContentObserver(null) {
116 @Override
117 public void onChange(boolean selfChange) {
118 super.onChange(selfChange);
119 Intent intent = new Intent(getApplicationContext(),
120 XmppConnectionService.class);
121 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
122 startService(intent);
123 }
124 };
125
126 private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
127 private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
128
129 private final IBinder mBinder = new XmppConnectionBinder();
130 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
131 private final FileObserver fileObserver = new FileObserver(
132 FileBackend.getConversationsImageDirectory()) {
133
134 @Override
135 public void onEvent(int event, String path) {
136 if (event == FileObserver.DELETE) {
137 markFileDeleted(path.split("\\.")[0]);
138 }
139 }
140 };
141 private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
142
143 @Override
144 public void onJinglePacketReceived(Account account, JinglePacket packet) {
145 mJingleConnectionManager.deliverPacket(account, packet);
146 }
147 };
148 private final OnBindListener mOnBindListener = new OnBindListener() {
149
150 @Override
151 public void onBind(final Account account) {
152 account.getRoster().clearPresences();
153 account.pendingConferenceJoins.clear();
154 account.pendingConferenceLeaves.clear();
155 fetchRosterFromServer(account);
156 fetchBookmarks(account);
157 sendPresence(account);
158 connectMultiModeConversations(account);
159 updateConversationUi();
160 }
161 };
162 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
163
164 @Override
165 public void onMessageAcknowledged(Account account, String uuid) {
166 for (final Conversation conversation : getConversations()) {
167 if (conversation.getAccount() == account) {
168 Message message = conversation.findUnsentMessageWithUuid(uuid);
169 if (message != null) {
170 markMessage(message, Message.STATUS_SEND);
171 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
172 databaseBackend.updateConversation(conversation);
173 }
174 }
175 }
176 }
177 }
178 };
179 private final IqGenerator mIqGenerator = new IqGenerator(this);
180 public DatabaseBackend databaseBackend;
181 public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
182
183 @Override
184 public void onContactStatusChanged(Contact contact, boolean online) {
185 Conversation conversation = find(getConversations(), contact);
186 if (conversation != null) {
187 if (online) {
188 conversation.endOtrIfNeeded();
189 if (contact.getPresences().size() == 1) {
190 sendUnsentMessages(conversation);
191 }
192 } else {
193 if (contact.getPresences().size() >= 1) {
194 if (conversation.hasValidOtrSession()) {
195 String otrResource = conversation.getOtrSession().getSessionID().getUserID();
196 if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
197 conversation.endOtrIfNeeded();
198 }
199 }
200 } else {
201 conversation.endOtrIfNeeded();
202 }
203 }
204 }
205 }
206 };
207 private FileBackend fileBackend = new FileBackend(this);
208 private MemorizingTrustManager mMemorizingTrustManager;
209 private NotificationService mNotificationService = new NotificationService(
210 this);
211 private OnMessagePacketReceived mMessageParser = new MessageParser(this);
212 private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
213 private IqParser mIqParser = new IqParser(this);
214 private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
215 @Override
216 public void onIqPacketReceived(Account account, IqPacket packet) {
217 if (packet.getType() == IqPacket.TYPE.ERROR) {
218 Element error = packet.findChild("error");
219 String text = error != null ? error.findChildContent("text") : null;
220 if (text != null) {
221 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received iq error - "+text);
222 }
223 }
224 }
225 };
226 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
227 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
228 private List<Account> accounts;
229 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
230 this);
231 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
232 this);
233 private AvatarService mAvatarService = new AvatarService(this);
234 private final List<String> mInProgressAvatarFetches = new ArrayList<>();
235 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
236 private OnConversationUpdate mOnConversationUpdate = null;
237 private int convChangedListenerCount = 0;
238 private OnShowErrorToast mOnShowErrorToast = null;
239 private int showErrorToastListenerCount = 0;
240 private int unreadCount = -1;
241 private OnAccountUpdate mOnAccountUpdate = null;
242 private OnStatusChanged statusListener = new OnStatusChanged() {
243
244 @Override
245 public void onStatusChanged(Account account) {
246 XmppConnection connection = account.getXmppConnection();
247 if (mOnAccountUpdate != null) {
248 mOnAccountUpdate.onAccountUpdate();
249 }
250 if (account.getStatus() == Account.State.ONLINE) {
251 for (Conversation conversation : account.pendingConferenceLeaves) {
252 leaveMuc(conversation);
253 }
254 for (Conversation conversation : account.pendingConferenceJoins) {
255 joinMuc(conversation);
256 }
257 mMessageArchiveService.executePendingQueries(account);
258 mJingleConnectionManager.cancelInTransmission();
259 List<Conversation> conversations = getConversations();
260 for (Conversation conversation : conversations) {
261 if (conversation.getAccount() == account) {
262 conversation.startOtrIfNeeded();
263 sendUnsentMessages(conversation);
264 }
265 }
266 if (connection != null && connection.getFeatures().csi()) {
267 if (checkListeners()) {
268 Log.d(Config.LOGTAG, account.getJid().toBareJid()
269 + " sending csi//inactive");
270 connection.sendInactive();
271 } else {
272 Log.d(Config.LOGTAG, account.getJid().toBareJid()
273 + " sending csi//active");
274 connection.sendActive();
275 }
276 }
277 syncDirtyContacts(account);
278 account.getAxolotlService().publishOwnDeviceIdIfNeeded();
279 account.getAxolotlService().publishBundlesIfNeeded();
280
281 scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
282 } else if (account.getStatus() == Account.State.OFFLINE) {
283 resetSendingToWaiting(account);
284 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
285 int timeToReconnect = mRandom.nextInt(50) + 10;
286 scheduleWakeUpCall(timeToReconnect,account.getUuid().hashCode());
287 }
288 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
289 databaseBackend.updateAccount(account);
290 reconnectAccount(account, true);
291 } else if ((account.getStatus() != Account.State.CONNECTING)
292 && (account.getStatus() != Account.State.NO_INTERNET)) {
293 if (connection != null) {
294 int next = connection.getTimeToNextAttempt();
295 Log.d(Config.LOGTAG, account.getJid().toBareJid()
296 + ": error connecting account. try again in "
297 + next + "s for the "
298 + (connection.getAttempt() + 1) + " time");
299 scheduleWakeUpCall(next,account.getUuid().hashCode());
300 }
301 }
302 getNotificationService().updateErrorNotification();
303 }
304 };
305 private int accountChangedListenerCount = 0;
306 private OnRosterUpdate mOnRosterUpdate = null;
307 private OnUpdateBlocklist mOnUpdateBlocklist = null;
308 private int updateBlocklistListenerCount = 0;
309 private int rosterChangedListenerCount = 0;
310 private OnMucRosterUpdate mOnMucRosterUpdate = null;
311 private int mucRosterChangedListenerCount = 0;
312 private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
313 private int keyStatusUpdatedListenerCount = 0;
314 private SecureRandom mRandom;
315 private OpenPgpServiceConnection pgpServiceConnection;
316 private PgpEngine mPgpEngine = null;
317 private WakeLock wakeLock;
318 private PowerManager pm;
319 private LruCache<String, Bitmap> mBitmapCache;
320 private Thread mPhoneContactMergerThread;
321
322 private boolean mRestoredFromDatabase = false;
323 public boolean areMessagesInitialized() {
324 return this.mRestoredFromDatabase;
325 }
326
327 public PgpEngine getPgpEngine() {
328 if (pgpServiceConnection.isBound()) {
329 if (this.mPgpEngine == null) {
330 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
331 getApplicationContext(),
332 pgpServiceConnection.getService()), this);
333 }
334 return mPgpEngine;
335 } else {
336 return null;
337 }
338
339 }
340
341 public FileBackend getFileBackend() {
342 return this.fileBackend;
343 }
344
345 public AvatarService getAvatarService() {
346 return this.mAvatarService;
347 }
348
349 public void attachLocationToConversation(final Conversation conversation,
350 final Uri uri,
351 final UiCallback<Message> callback) {
352 int encryption = conversation.getNextEncryption();
353 if (encryption == Message.ENCRYPTION_PGP) {
354 encryption = Message.ENCRYPTION_DECRYPTED;
355 }
356 Message message = new Message(conversation,uri.toString(),encryption);
357 if (conversation.getNextCounterpart() != null) {
358 message.setCounterpart(conversation.getNextCounterpart());
359 }
360 if (encryption == Message.ENCRYPTION_DECRYPTED) {
361 getPgpEngine().encrypt(message, callback);
362 } else {
363 callback.success(message);
364 }
365 }
366
367 public void attachFileToConversation(final Conversation conversation,
368 final Uri uri,
369 final UiCallback<Message> callback) {
370 final Message message;
371 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
372 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
373 } else {
374 message = new Message(conversation, "", conversation.getNextEncryption());
375 }
376 message.setCounterpart(conversation.getNextCounterpart());
377 message.setType(Message.TYPE_FILE);
378 String path = getFileBackend().getOriginalPath(uri);
379 if (path!=null) {
380 message.setRelativeFilePath(path);
381 getFileBackend().updateFileParams(message);
382 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
383 getPgpEngine().encrypt(message, callback);
384 } else {
385 callback.success(message);
386 }
387 } else {
388 mFileAddingExecutor.execute(new Runnable() {
389 @Override
390 public void run() {
391 try {
392 getFileBackend().copyFileToPrivateStorage(message, uri);
393 getFileBackend().updateFileParams(message);
394 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
395 getPgpEngine().encrypt(message, callback);
396 } else {
397 callback.success(message);
398 }
399 } catch (FileBackend.FileCopyException e) {
400 callback.error(e.getResId(), message);
401 }
402 }
403 });
404 }
405 }
406
407 public void attachImageToConversation(final Conversation conversation,
408 final Uri uri, final UiCallback<Message> callback) {
409 final Message message;
410 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
411 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
412 } else {
413 message = new Message(conversation, "",conversation.getNextEncryption());
414 }
415 message.setCounterpart(conversation.getNextCounterpart());
416 message.setType(Message.TYPE_IMAGE);
417 mFileAddingExecutor.execute(new Runnable() {
418
419 @Override
420 public void run() {
421 try {
422 getFileBackend().copyImageToPrivateStorage(message, uri);
423 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
424 getPgpEngine().encrypt(message, callback);
425 } else {
426 callback.success(message);
427 }
428 } catch (final FileBackend.FileCopyException e) {
429 callback.error(e.getResId(), message);
430 }
431 }
432 });
433 }
434
435 public Conversation find(Bookmark bookmark) {
436 return find(bookmark.getAccount(), bookmark.getJid());
437 }
438
439 public Conversation find(final Account account, final Jid jid) {
440 return find(getConversations(), account, jid);
441 }
442
443 @Override
444 public int onStartCommand(Intent intent, int flags, int startId) {
445 final String action = intent == null ? null : intent.getAction();
446 if (action != null) {
447 switch (action) {
448 case ConnectivityManager.CONNECTIVITY_ACTION:
449 if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
450 resetAllAttemptCounts(true);
451 }
452 break;
453 case ACTION_MERGE_PHONE_CONTACTS:
454 if (mRestoredFromDatabase) {
455 PhoneHelper.loadPhoneContacts(getApplicationContext(),
456 new CopyOnWriteArrayList<Bundle>(),
457 this);
458 }
459 return START_STICKY;
460 case Intent.ACTION_SHUTDOWN:
461 logoutAndSave();
462 return START_NOT_STICKY;
463 case ACTION_CLEAR_NOTIFICATION:
464 mNotificationService.clear();
465 break;
466 case ACTION_DISABLE_FOREGROUND:
467 getPreferences().edit().putBoolean("keep_foreground_service",false).commit();
468 toggleForegroundService();
469 break;
470 case ACTION_TRY_AGAIN:
471 resetAllAttemptCounts(false);
472 break;
473 case ACTION_DISABLE_ACCOUNT:
474 try {
475 String jid = intent.getStringExtra("account");
476 Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
477 if (account != null) {
478 account.setOption(Account.OPTION_DISABLED,true);
479 updateAccount(account);
480 }
481 } catch (final InvalidJidException ignored) {
482 break;
483 }
484 break;
485 }
486 }
487 this.wakeLock.acquire();
488
489 for (Account account : accounts) {
490 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
491 if (!hasInternetConnection()) {
492 account.setStatus(Account.State.NO_INTERNET);
493 if (statusListener != null) {
494 statusListener.onStatusChanged(account);
495 }
496 } else {
497 if (account.getStatus() == Account.State.NO_INTERNET) {
498 account.setStatus(Account.State.OFFLINE);
499 if (statusListener != null) {
500 statusListener.onStatusChanged(account);
501 }
502 }
503 if (account.getStatus() == Account.State.ONLINE) {
504 long lastReceived = account.getXmppConnection().getLastPacketReceived();
505 long lastSent = account.getXmppConnection().getLastPingSent();
506 long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
507 long msToNextPing = (Math.max(lastReceived,lastSent) + pingInterval) - SystemClock.elapsedRealtime();
508 long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
509 if (lastSent > lastReceived) {
510 if (pingTimeoutIn < 0) {
511 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
512 this.reconnectAccount(account, true);
513 } else {
514 int secs = (int) (pingTimeoutIn / 1000);
515 this.scheduleWakeUpCall(secs,account.getUuid().hashCode());
516 }
517 } else if (msToNextPing <= 0) {
518 account.getXmppConnection().sendPing();
519 Log.d(Config.LOGTAG, account.getJid().toBareJid()+" send ping");
520 this.scheduleWakeUpCall(Config.PING_TIMEOUT,account.getUuid().hashCode());
521 } else {
522 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
523 }
524 } else if (account.getStatus() == Account.State.OFFLINE) {
525 reconnectAccount(account,true);
526 } else if (account.getStatus() == Account.State.CONNECTING) {
527 long timeout = Config.CONNECT_TIMEOUT - ((SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000);
528 if (timeout < 0) {
529 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
530 reconnectAccount(account, true);
531 } else {
532 scheduleWakeUpCall((int) timeout,account.getUuid().hashCode());
533 }
534 } else {
535 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
536 reconnectAccount(account, true);
537 }
538 }
539
540 }
541 if (mOnAccountUpdate != null) {
542 mOnAccountUpdate.onAccountUpdate();
543 }
544 }
545 }
546 /*PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
547 if (!pm.isScreenOn()) {
548 removeStaleListeners();
549 }*/
550 if (wakeLock.isHeld()) {
551 try {
552 wakeLock.release();
553 } catch (final RuntimeException ignored) {
554 }
555 }
556 return START_STICKY;
557 }
558
559 private void resetAllAttemptCounts(boolean reallyAll) {
560 Log.d(Config.LOGTAG,"resetting all attepmt counts");
561 for(Account account : accounts) {
562 if (account.hasErrorStatus() || reallyAll) {
563 final XmppConnection connection = account.getXmppConnection();
564 if (connection != null) {
565 connection.resetAttemptCount();
566 }
567 }
568 }
569 }
570
571 public boolean hasInternetConnection() {
572 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
573 .getSystemService(Context.CONNECTIVITY_SERVICE);
574 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
575 return activeNetwork != null && activeNetwork.isConnected();
576 }
577
578 @SuppressLint("TrulyRandom")
579 @Override
580 public void onCreate() {
581 ExceptionHelper.init(getApplicationContext());
582 PRNGFixes.apply();
583 this.mRandom = new SecureRandom();
584 updateMemorizingTrustmanager();
585 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
586 final int cacheSize = maxMemory / 8;
587 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
588 @Override
589 protected int sizeOf(final String key, final Bitmap bitmap) {
590 return bitmap.getByteCount() / 1024;
591 }
592 };
593
594 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
595 this.accounts = databaseBackend.getAccounts();
596
597 restoreFromDatabase();
598
599 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
600 this.fileObserver.startWatching();
601 this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
602 this.pgpServiceConnection.bindToService();
603
604 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
605 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
606 toggleForegroundService();
607 updateUnreadCountBadge();
608 }
609
610 public void toggleForegroundService() {
611 if (getPreferences().getBoolean("keep_foreground_service",false)) {
612 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
613 } else {
614 stopForeground(true);
615 }
616 }
617
618 @Override
619 public void onTaskRemoved(final Intent rootIntent) {
620 super.onTaskRemoved(rootIntent);
621 if (!getPreferences().getBoolean("keep_foreground_service",false)) {
622 this.logoutAndSave();
623 }
624 }
625
626 private void logoutAndSave() {
627 for (final Account account : accounts) {
628 databaseBackend.writeRoster(account.getRoster());
629 if (account.getXmppConnection() != null) {
630 disconnect(account, false);
631 }
632 }
633 Context context = getApplicationContext();
634 AlarmManager alarmManager = (AlarmManager) context
635 .getSystemService(Context.ALARM_SERVICE);
636 Intent intent = new Intent(context, EventReceiver.class);
637 alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
638 Log.d(Config.LOGTAG, "good bye");
639 stopSelf();
640 }
641
642 protected void scheduleWakeUpCall(int seconds, int requestCode) {
643 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
644
645 Context context = getApplicationContext();
646 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
647
648 Intent intent = new Intent(context, EventReceiver.class);
649 intent.setAction("ping");
650 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
651 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
652 }
653
654 public XmppConnection createConnection(final Account account) {
655 final SharedPreferences sharedPref = getPreferences();
656 account.setResource(sharedPref.getString("resource", "mobile")
657 .toLowerCase(Locale.getDefault()));
658 final XmppConnection connection = new XmppConnection(account, this);
659 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
660 connection.setOnStatusChangedListener(this.statusListener);
661 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
662 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
663 connection.setOnJinglePacketReceivedListener(this.jingleListener);
664 connection.setOnBindListener(this.mOnBindListener);
665 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
666 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
667 return connection;
668 }
669
670 public void sendChatState(Conversation conversation) {
671 if (sendChatStates()) {
672 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
673 sendMessagePacket(conversation.getAccount(), packet);
674 }
675 }
676
677 private void sendFileMessage(final Message message, final boolean delay) {
678 Log.d(Config.LOGTAG, "send file message");
679 final Account account = message.getConversation().getAccount();
680 final XmppConnection connection = account.getXmppConnection();
681 if (connection != null && connection.getFeatures().httpUpload()) {
682 mHttpConnectionManager.createNewUploadConnection(message, delay);
683 } else {
684 mJingleConnectionManager.createNewConnection(message);
685 }
686 }
687
688 public void sendMessage(final Message message) {
689 sendMessage(message, false, false);
690 }
691
692 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
693 final Account account = message.getConversation().getAccount();
694 final Conversation conversation = message.getConversation();
695 account.deactivateGracePeriod();
696 MessagePacket packet = null;
697 boolean saveInDb = true;
698 message.setStatus(Message.STATUS_WAITING);
699
700 if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
701 message.getConversation().endOtrIfNeeded();
702 message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
703 new Conversation.OnMessageFound() {
704 @Override
705 public void onMessageFound(Message message) {
706 markMessage(message,Message.STATUS_SEND_FAILED);
707 }
708 });
709 }
710
711 if (account.isOnlineAndConnected()) {
712 switch (message.getEncryption()) {
713 case Message.ENCRYPTION_NONE:
714 if (message.needsUploading()) {
715 if (account.httpUploadAvailable() || message.fixCounterpart()) {
716 this.sendFileMessage(message,delay);
717 } else {
718 break;
719 }
720 } else {
721 packet = mMessageGenerator.generateChat(message);
722 }
723 break;
724 case Message.ENCRYPTION_PGP:
725 case Message.ENCRYPTION_DECRYPTED:
726 if (message.needsUploading()) {
727 if (account.httpUploadAvailable() || message.fixCounterpart()) {
728 this.sendFileMessage(message,delay);
729 } else {
730 break;
731 }
732 } else {
733 packet = mMessageGenerator.generatePgpChat(message);
734 }
735 break;
736 case Message.ENCRYPTION_OTR:
737 SessionImpl otrSession = conversation.getOtrSession();
738 if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
739 try {
740 message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
741 } catch (InvalidJidException e) {
742 break;
743 }
744 if (message.needsUploading()) {
745 mJingleConnectionManager.createNewConnection(message);
746 } else {
747 packet = mMessageGenerator.generateOtrChat(message);
748 }
749 } else if (otrSession == null) {
750 if (message.fixCounterpart()) {
751 conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
752 } else {
753 break;
754 }
755 }
756 break;
757 case Message.ENCRYPTION_AXOLOTL:
758 if (message.needsUploading()) {
759 if (account.httpUploadAvailable() || message.fixCounterpart()) {
760 this.sendFileMessage(message,delay);
761 } else {
762 break;
763 }
764 } else {
765 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
766 if (axolotlMessage == null) {
767 account.getAxolotlService().prepareMessage(message,delay);
768 message.setAxolotlFingerprint(account.getAxolotlService().getOwnPublicKey().getFingerprint().replaceAll("\\s", ""));
769 } else {
770 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
771 }
772 }
773 break;
774
775 }
776 if (packet != null) {
777 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
778 message.setStatus(Message.STATUS_UNSEND);
779 } else {
780 message.setStatus(Message.STATUS_SEND);
781 }
782 }
783 } else {
784 switch(message.getEncryption()) {
785 case Message.ENCRYPTION_DECRYPTED:
786 if (!message.needsUploading()) {
787 String pgpBody = message.getEncryptedBody();
788 String decryptedBody = message.getBody();
789 message.setBody(pgpBody);
790 message.setEncryption(Message.ENCRYPTION_PGP);
791 databaseBackend.createMessage(message);
792 saveInDb = false;
793 message.setBody(decryptedBody);
794 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
795 }
796 break;
797 case Message.ENCRYPTION_OTR:
798 if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
799 conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
800 }
801 break;
802 case Message.ENCRYPTION_AXOLOTL:
803 message.setAxolotlFingerprint(account.getAxolotlService().getOwnPublicKey().getFingerprint().replaceAll("\\s", ""));
804 break;
805 }
806 }
807
808 if (resend) {
809 if (packet != null) {
810 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
811 markMessage(message,Message.STATUS_UNSEND);
812 } else {
813 markMessage(message,Message.STATUS_SEND);
814 }
815 }
816 } else {
817 conversation.add(message);
818 if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
819 databaseBackend.createMessage(message);
820 }
821 updateConversationUi();
822 }
823 if (packet != null) {
824 if (delay) {
825 mMessageGenerator.addDelay(packet,message.getTimeSent());
826 }
827 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
828 if (this.sendChatStates()) {
829 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
830 }
831 }
832 sendMessagePacket(account, packet);
833 }
834 }
835
836 private void sendUnsentMessages(final Conversation conversation) {
837 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
838
839 @Override
840 public void onMessageFound(Message message) {
841 resendMessage(message, true);
842 }
843 });
844 }
845
846 public void resendMessage(final Message message, final boolean delay) {
847 sendMessage(message, true, delay);
848 }
849
850 public void fetchRosterFromServer(final Account account) {
851 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
852 if (!"".equals(account.getRosterVersion())) {
853 Log.d(Config.LOGTAG, account.getJid().toBareJid()
854 + ": fetching roster version " + account.getRosterVersion());
855 } else {
856 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
857 }
858 iqPacket.query(Xmlns.ROSTER).setAttribute("ver",account.getRosterVersion());
859 sendIqPacket(account,iqPacket,mIqParser);
860 }
861
862 public void fetchBookmarks(final Account account) {
863 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
864 final Element query = iqPacket.query("jabber:iq:private");
865 query.addChild("storage", "storage:bookmarks");
866 final OnIqPacketReceived callback = new OnIqPacketReceived() {
867
868 @Override
869 public void onIqPacketReceived(final Account account, final IqPacket packet) {
870 final Element query = packet.query();
871 final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
872 final Element storage = query.findChild("storage",
873 "storage:bookmarks");
874 if (storage != null) {
875 for (final Element item : storage.getChildren()) {
876 if (item.getName().equals("conference")) {
877 final Bookmark bookmark = Bookmark.parse(item, account);
878 bookmarks.add(bookmark);
879 Conversation conversation = find(bookmark);
880 if (conversation != null) {
881 conversation.setBookmark(bookmark);
882 } else if (bookmark.autojoin() && bookmark.getJid() != null) {
883 conversation = findOrCreateConversation(
884 account, bookmark.getJid(), true);
885 conversation.setBookmark(bookmark);
886 joinMuc(conversation);
887 }
888 }
889 }
890 }
891 account.setBookmarks(bookmarks);
892 }
893 };
894 sendIqPacket(account, iqPacket, callback);
895 }
896
897 public void pushBookmarks(Account account) {
898 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
899 Element query = iqPacket.query("jabber:iq:private");
900 Element storage = query.addChild("storage", "storage:bookmarks");
901 for (Bookmark bookmark : account.getBookmarks()) {
902 storage.addChild(bookmark);
903 }
904 sendIqPacket(account, iqPacket, mDefaultIqHandler);
905 }
906
907 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
908 if (mPhoneContactMergerThread != null) {
909 mPhoneContactMergerThread.interrupt();
910 }
911 mPhoneContactMergerThread = new Thread(new Runnable() {
912 @Override
913 public void run() {
914 Log.d(Config.LOGTAG,"start merging phone contacts with roster");
915 for (Account account : accounts) {
916 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
917 for (Bundle phoneContact : phoneContacts) {
918 if (Thread.interrupted()) {
919 Log.d(Config.LOGTAG,"interrupted merging phone contacts");
920 return;
921 }
922 Jid jid;
923 try {
924 jid = Jid.fromString(phoneContact.getString("jid"));
925 } catch (final InvalidJidException e) {
926 continue;
927 }
928 final Contact contact = account.getRoster().getContact(jid);
929 String systemAccount = phoneContact.getInt("phoneid")
930 + "#"
931 + phoneContact.getString("lookup");
932 contact.setSystemAccount(systemAccount);
933 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
934 getAvatarService().clear(contact);
935 }
936 contact.setSystemName(phoneContact.getString("displayname"));
937 withSystemAccounts.remove(contact);
938 }
939 for(Contact contact : withSystemAccounts) {
940 contact.setSystemAccount(null);
941 contact.setSystemName(null);
942 if (contact.setPhotoUri(null)) {
943 getAvatarService().clear(contact);
944 }
945 }
946 }
947 Log.d(Config.LOGTAG,"finished merging phone contacts");
948 updateAccountUi();
949 }
950 });
951 mPhoneContactMergerThread.start();
952 }
953
954 private void restoreFromDatabase() {
955 synchronized (this.conversations) {
956 final Map<String, Account> accountLookupTable = new Hashtable<>();
957 for (Account account : this.accounts) {
958 accountLookupTable.put(account.getUuid(), account);
959 }
960 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
961 for (Conversation conversation : this.conversations) {
962 Account account = accountLookupTable.get(conversation.getAccountUuid());
963 conversation.setAccount(account);
964 }
965 Runnable runnable =new Runnable() {
966 @Override
967 public void run() {
968 Log.d(Config.LOGTAG,"restoring roster");
969 for(Account account : accounts) {
970 databaseBackend.readRoster(account.getRoster());
971 account.initAccountServices(XmppConnectionService.this);
972 }
973 getBitmapCache().evictAll();
974 Looper.prepare();
975 PhoneHelper.loadPhoneContacts(getApplicationContext(),
976 new CopyOnWriteArrayList<Bundle>(),
977 XmppConnectionService.this);
978 Log.d(Config.LOGTAG,"restoring messages");
979 for (Conversation conversation : conversations) {
980 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
981 checkDeletedFiles(conversation);
982 }
983 mRestoredFromDatabase = true;
984 Log.d(Config.LOGTAG,"restored all messages");
985 updateConversationUi();
986 }
987 };
988 mDatabaseExecutor.execute(runnable);
989 }
990 }
991
992 public List<Conversation> getConversations() {
993 return this.conversations;
994 }
995
996 private void checkDeletedFiles(Conversation conversation) {
997 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
998
999 @Override
1000 public void onMessageFound(Message message) {
1001 if (!getFileBackend().isFileAvailable(message)) {
1002 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1003 }
1004 }
1005 });
1006 }
1007
1008 private void markFileDeleted(String uuid) {
1009 for (Conversation conversation : getConversations()) {
1010 Message message = conversation.findMessageWithFileAndUuid(uuid);
1011 if (message != null) {
1012 if (!getFileBackend().isFileAvailable(message)) {
1013 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1014 updateConversationUi();
1015 }
1016 return;
1017 }
1018 }
1019 }
1020
1021 public void populateWithOrderedConversations(final List<Conversation> list) {
1022 populateWithOrderedConversations(list, true);
1023 }
1024
1025 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1026 list.clear();
1027 if (includeNoFileUpload) {
1028 list.addAll(getConversations());
1029 } else {
1030 for (Conversation conversation : getConversations()) {
1031 if (conversation.getMode() == Conversation.MODE_SINGLE
1032 || conversation.getAccount().httpUploadAvailable()) {
1033 list.add(conversation);
1034 }
1035 }
1036 }
1037 Collections.sort(list, new Comparator<Conversation>() {
1038 @Override
1039 public int compare(Conversation lhs, Conversation rhs) {
1040 Message left = lhs.getLatestMessage();
1041 Message right = rhs.getLatestMessage();
1042 if (left.getTimeSent() > right.getTimeSent()) {
1043 return -1;
1044 } else if (left.getTimeSent() < right.getTimeSent()) {
1045 return 1;
1046 } else {
1047 return 0;
1048 }
1049 }
1050 });
1051 }
1052
1053 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1054 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1055 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1056 return;
1057 }
1058 Runnable runnable = new Runnable() {
1059 @Override
1060 public void run() {
1061 final Account account = conversation.getAccount();
1062 List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1063 if (messages.size() > 0) {
1064 conversation.addAll(0, messages);
1065 checkDeletedFiles(conversation);
1066 callback.onMoreMessagesLoaded(messages.size(), conversation);
1067 } else if (conversation.hasMessagesLeftOnServer()
1068 && account.isOnlineAndConnected()
1069 && account.getXmppConnection().getFeatures().mam()) {
1070 MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1071 if (query != null) {
1072 query.setCallback(callback);
1073 }
1074 callback.informUser(R.string.fetching_history_from_server);
1075 }
1076 }
1077 };
1078 mDatabaseExecutor.execute(runnable);
1079 }
1080
1081 public List<Account> getAccounts() {
1082 return this.accounts;
1083 }
1084
1085 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1086 for (final Conversation conversation : haystack) {
1087 if (conversation.getContact() == contact) {
1088 return conversation;
1089 }
1090 }
1091 return null;
1092 }
1093
1094 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1095 if (jid == null) {
1096 return null;
1097 }
1098 for (final Conversation conversation : haystack) {
1099 if ((account == null || conversation.getAccount() == account)
1100 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1101 return conversation;
1102 }
1103 }
1104 return null;
1105 }
1106
1107 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1108 return this.findOrCreateConversation(account, jid, muc, null);
1109 }
1110
1111 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1112 synchronized (this.conversations) {
1113 Conversation conversation = find(account, jid);
1114 if (conversation != null) {
1115 return conversation;
1116 }
1117 conversation = databaseBackend.findConversation(account, jid);
1118 if (conversation != null) {
1119 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1120 conversation.setAccount(account);
1121 if (muc) {
1122 conversation.setMode(Conversation.MODE_MULTI);
1123 conversation.setContactJid(jid);
1124 } else {
1125 conversation.setMode(Conversation.MODE_SINGLE);
1126 conversation.setContactJid(jid.toBareJid());
1127 }
1128 conversation.setNextEncryption(-1);
1129 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1130 this.databaseBackend.updateConversation(conversation);
1131 } else {
1132 String conversationName;
1133 Contact contact = account.getRoster().getContact(jid);
1134 if (contact != null) {
1135 conversationName = contact.getDisplayName();
1136 } else {
1137 conversationName = jid.getLocalpart();
1138 }
1139 if (muc) {
1140 conversation = new Conversation(conversationName, account, jid,
1141 Conversation.MODE_MULTI);
1142 } else {
1143 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1144 Conversation.MODE_SINGLE);
1145 }
1146 this.databaseBackend.createConversation(conversation);
1147 }
1148 if (account.getXmppConnection() != null
1149 && account.getXmppConnection().getFeatures().mam()
1150 && !muc) {
1151 if (query == null) {
1152 this.mMessageArchiveService.query(conversation);
1153 } else {
1154 if (query.getConversation() == null) {
1155 this.mMessageArchiveService.query(conversation, query.getStart());
1156 }
1157 }
1158 }
1159 checkDeletedFiles(conversation);
1160 this.conversations.add(conversation);
1161 updateConversationUi();
1162 return conversation;
1163 }
1164 }
1165
1166 public void archiveConversation(Conversation conversation) {
1167 getNotificationService().clear(conversation);
1168 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1169 conversation.setNextEncryption(-1);
1170 synchronized (this.conversations) {
1171 if (conversation.getMode() == Conversation.MODE_MULTI) {
1172 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1173 Bookmark bookmark = conversation.getBookmark();
1174 if (bookmark != null && bookmark.autojoin()) {
1175 bookmark.setAutojoin(false);
1176 pushBookmarks(bookmark.getAccount());
1177 }
1178 }
1179 leaveMuc(conversation);
1180 } else {
1181 conversation.endOtrIfNeeded();
1182 }
1183 this.databaseBackend.updateConversation(conversation);
1184 this.conversations.remove(conversation);
1185 updateConversationUi();
1186 }
1187 }
1188
1189 public void createAccount(final Account account) {
1190 account.initAccountServices(this);
1191 databaseBackend.createAccount(account);
1192 this.accounts.add(account);
1193 this.reconnectAccountInBackground(account);
1194 updateAccountUi();
1195 }
1196
1197 public void updateAccount(final Account account) {
1198 this.statusListener.onStatusChanged(account);
1199 databaseBackend.updateAccount(account);
1200 reconnectAccount(account, false);
1201 updateAccountUi();
1202 getNotificationService().updateErrorNotification();
1203 }
1204
1205 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1206 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1207 sendIqPacket(account, iq, new OnIqPacketReceived() {
1208 @Override
1209 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1210 if (packet.getType() == IqPacket.TYPE.RESULT) {
1211 account.setPassword(newPassword);
1212 databaseBackend.updateAccount(account);
1213 callback.onPasswordChangeSucceeded();
1214 } else {
1215 callback.onPasswordChangeFailed();
1216 }
1217 }
1218 });
1219 }
1220
1221 public void deleteAccount(final Account account) {
1222 synchronized (this.conversations) {
1223 for (final Conversation conversation : conversations) {
1224 if (conversation.getAccount() == account) {
1225 if (conversation.getMode() == Conversation.MODE_MULTI) {
1226 leaveMuc(conversation);
1227 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1228 conversation.endOtrIfNeeded();
1229 }
1230 conversations.remove(conversation);
1231 }
1232 }
1233 if (account.getXmppConnection() != null) {
1234 this.disconnect(account, true);
1235 }
1236 databaseBackend.deleteAccount(account);
1237 this.accounts.remove(account);
1238 updateAccountUi();
1239 getNotificationService().updateErrorNotification();
1240 }
1241 }
1242
1243 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1244 synchronized (this) {
1245 if (checkListeners()) {
1246 switchToForeground();
1247 }
1248 this.mOnConversationUpdate = listener;
1249 this.mNotificationService.setIsInForeground(true);
1250 if (this.convChangedListenerCount < 2) {
1251 this.convChangedListenerCount++;
1252 }
1253 }
1254 }
1255
1256 public void removeOnConversationListChangedListener() {
1257 synchronized (this) {
1258 this.convChangedListenerCount--;
1259 if (this.convChangedListenerCount <= 0) {
1260 this.convChangedListenerCount = 0;
1261 this.mOnConversationUpdate = null;
1262 this.mNotificationService.setIsInForeground(false);
1263 if (checkListeners()) {
1264 switchToBackground();
1265 }
1266 }
1267 }
1268 }
1269
1270 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1271 synchronized (this) {
1272 if (checkListeners()) {
1273 switchToForeground();
1274 }
1275 this.mOnShowErrorToast = onShowErrorToast;
1276 if (this.showErrorToastListenerCount < 2) {
1277 this.showErrorToastListenerCount++;
1278 }
1279 }
1280 this.mOnShowErrorToast = onShowErrorToast;
1281 }
1282
1283 public void removeOnShowErrorToastListener() {
1284 synchronized (this) {
1285 this.showErrorToastListenerCount--;
1286 if (this.showErrorToastListenerCount <= 0) {
1287 this.showErrorToastListenerCount = 0;
1288 this.mOnShowErrorToast = null;
1289 if (checkListeners()) {
1290 switchToBackground();
1291 }
1292 }
1293 }
1294 }
1295
1296 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1297 synchronized (this) {
1298 if (checkListeners()) {
1299 switchToForeground();
1300 }
1301 this.mOnAccountUpdate = listener;
1302 if (this.accountChangedListenerCount < 2) {
1303 this.accountChangedListenerCount++;
1304 }
1305 }
1306 }
1307
1308 public void removeOnAccountListChangedListener() {
1309 synchronized (this) {
1310 this.accountChangedListenerCount--;
1311 if (this.accountChangedListenerCount <= 0) {
1312 this.mOnAccountUpdate = null;
1313 this.accountChangedListenerCount = 0;
1314 if (checkListeners()) {
1315 switchToBackground();
1316 }
1317 }
1318 }
1319 }
1320
1321 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1322 synchronized (this) {
1323 if (checkListeners()) {
1324 switchToForeground();
1325 }
1326 this.mOnRosterUpdate = listener;
1327 if (this.rosterChangedListenerCount < 2) {
1328 this.rosterChangedListenerCount++;
1329 }
1330 }
1331 }
1332
1333 public void removeOnRosterUpdateListener() {
1334 synchronized (this) {
1335 this.rosterChangedListenerCount--;
1336 if (this.rosterChangedListenerCount <= 0) {
1337 this.rosterChangedListenerCount = 0;
1338 this.mOnRosterUpdate = null;
1339 if (checkListeners()) {
1340 switchToBackground();
1341 }
1342 }
1343 }
1344 }
1345
1346 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1347 synchronized (this) {
1348 if (checkListeners()) {
1349 switchToForeground();
1350 }
1351 this.mOnUpdateBlocklist = listener;
1352 if (this.updateBlocklistListenerCount < 2) {
1353 this.updateBlocklistListenerCount++;
1354 }
1355 }
1356 }
1357
1358 public void removeOnUpdateBlocklistListener() {
1359 synchronized (this) {
1360 this.updateBlocklistListenerCount--;
1361 if (this.updateBlocklistListenerCount <= 0) {
1362 this.updateBlocklistListenerCount = 0;
1363 this.mOnUpdateBlocklist = null;
1364 if (checkListeners()) {
1365 switchToBackground();
1366 }
1367 }
1368 }
1369 }
1370
1371 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1372 synchronized (this) {
1373 if (checkListeners()) {
1374 switchToForeground();
1375 }
1376 this.mOnKeyStatusUpdated = listener;
1377 if (this.keyStatusUpdatedListenerCount < 2) {
1378 this.keyStatusUpdatedListenerCount++;
1379 }
1380 }
1381 }
1382
1383 public void removeOnNewKeysAvailableListener() {
1384 synchronized (this) {
1385 this.keyStatusUpdatedListenerCount--;
1386 if (this.keyStatusUpdatedListenerCount <= 0) {
1387 this.keyStatusUpdatedListenerCount = 0;
1388 this.mOnKeyStatusUpdated = null;
1389 if (checkListeners()) {
1390 switchToBackground();
1391 }
1392 }
1393 }
1394 }
1395
1396 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1397 synchronized (this) {
1398 if (checkListeners()) {
1399 switchToForeground();
1400 }
1401 this.mOnMucRosterUpdate = listener;
1402 if (this.mucRosterChangedListenerCount < 2) {
1403 this.mucRosterChangedListenerCount++;
1404 }
1405 }
1406 }
1407
1408 public void removeOnMucRosterUpdateListener() {
1409 synchronized (this) {
1410 this.mucRosterChangedListenerCount--;
1411 if (this.mucRosterChangedListenerCount <= 0) {
1412 this.mucRosterChangedListenerCount = 0;
1413 this.mOnMucRosterUpdate = null;
1414 if (checkListeners()) {
1415 switchToBackground();
1416 }
1417 }
1418 }
1419 }
1420
1421 private boolean checkListeners() {
1422 return (this.mOnAccountUpdate == null
1423 && this.mOnConversationUpdate == null
1424 && this.mOnRosterUpdate == null
1425 && this.mOnUpdateBlocklist == null
1426 && this.mOnShowErrorToast == null
1427 && this.mOnKeyStatusUpdated == null);
1428 }
1429
1430 private void switchToForeground() {
1431 for (Account account : getAccounts()) {
1432 if (account.getStatus() == Account.State.ONLINE) {
1433 XmppConnection connection = account.getXmppConnection();
1434 if (connection != null && connection.getFeatures().csi()) {
1435 connection.sendActive();
1436 }
1437 }
1438 }
1439 Log.d(Config.LOGTAG, "app switched into foreground");
1440 }
1441
1442 private void switchToBackground() {
1443 for (Account account : getAccounts()) {
1444 if (account.getStatus() == Account.State.ONLINE) {
1445 XmppConnection connection = account.getXmppConnection();
1446 if (connection != null && connection.getFeatures().csi()) {
1447 connection.sendInactive();
1448 }
1449 }
1450 }
1451 for(Conversation conversation : getConversations()) {
1452 conversation.setIncomingChatState(ChatState.ACTIVE);
1453 }
1454 this.mNotificationService.setIsInForeground(false);
1455 Log.d(Config.LOGTAG, "app switched into background");
1456 }
1457
1458 private void connectMultiModeConversations(Account account) {
1459 List<Conversation> conversations = getConversations();
1460 for (Conversation conversation : conversations) {
1461 if ((conversation.getMode() == Conversation.MODE_MULTI)
1462 && (conversation.getAccount() == account)) {
1463 conversation.resetMucOptions();
1464 joinMuc(conversation);
1465 }
1466 }
1467 }
1468
1469 public void joinMuc(Conversation conversation) {
1470 Account account = conversation.getAccount();
1471 account.pendingConferenceJoins.remove(conversation);
1472 account.pendingConferenceLeaves.remove(conversation);
1473 if (account.getStatus() == Account.State.ONLINE) {
1474 final String nick = conversation.getMucOptions().getProposedNick();
1475 final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1476 if (joinJid == null) {
1477 return; //safety net
1478 }
1479 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1480 PresencePacket packet = new PresencePacket();
1481 packet.setFrom(conversation.getAccount().getJid());
1482 packet.setTo(joinJid);
1483 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1484 if (conversation.getMucOptions().getPassword() != null) {
1485 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1486 }
1487 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1488 String sig = account.getPgpSignature();
1489 if (sig != null) {
1490 packet.addChild("status").setContent("online");
1491 packet.addChild("x", "jabber:x:signed").setContent(sig);
1492 }
1493 sendPresencePacket(account, packet);
1494 fetchConferenceConfiguration(conversation);
1495 if (!joinJid.equals(conversation.getJid())) {
1496 conversation.setContactJid(joinJid);
1497 databaseBackend.updateConversation(conversation);
1498 }
1499 conversation.setHasMessagesLeftOnServer(false);
1500 } else {
1501 account.pendingConferenceJoins.add(conversation);
1502 }
1503 }
1504
1505 public void providePasswordForMuc(Conversation conversation, String password) {
1506 if (conversation.getMode() == Conversation.MODE_MULTI) {
1507 conversation.getMucOptions().setPassword(password);
1508 if (conversation.getBookmark() != null) {
1509 conversation.getBookmark().setAutojoin(true);
1510 pushBookmarks(conversation.getAccount());
1511 }
1512 databaseBackend.updateConversation(conversation);
1513 joinMuc(conversation);
1514 }
1515 }
1516
1517 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1518 final MucOptions options = conversation.getMucOptions();
1519 final Jid joinJid = options.createJoinJid(nick);
1520 if (options.online()) {
1521 Account account = conversation.getAccount();
1522 options.setOnRenameListener(new OnRenameListener() {
1523
1524 @Override
1525 public void onSuccess() {
1526 conversation.setContactJid(joinJid);
1527 databaseBackend.updateConversation(conversation);
1528 Bookmark bookmark = conversation.getBookmark();
1529 if (bookmark != null) {
1530 bookmark.setNick(nick);
1531 pushBookmarks(bookmark.getAccount());
1532 }
1533 callback.success(conversation);
1534 }
1535
1536 @Override
1537 public void onFailure() {
1538 callback.error(R.string.nick_in_use, conversation);
1539 }
1540 });
1541
1542 PresencePacket packet = new PresencePacket();
1543 packet.setTo(joinJid);
1544 packet.setFrom(conversation.getAccount().getJid());
1545
1546 String sig = account.getPgpSignature();
1547 if (sig != null) {
1548 packet.addChild("status").setContent("online");
1549 packet.addChild("x", "jabber:x:signed").setContent(sig);
1550 }
1551 sendPresencePacket(account, packet);
1552 } else {
1553 conversation.setContactJid(joinJid);
1554 databaseBackend.updateConversation(conversation);
1555 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1556 Bookmark bookmark = conversation.getBookmark();
1557 if (bookmark != null) {
1558 bookmark.setNick(nick);
1559 pushBookmarks(bookmark.getAccount());
1560 }
1561 joinMuc(conversation);
1562 }
1563 }
1564 }
1565
1566 public void leaveMuc(Conversation conversation) {
1567 Account account = conversation.getAccount();
1568 account.pendingConferenceJoins.remove(conversation);
1569 account.pendingConferenceLeaves.remove(conversation);
1570 if (account.getStatus() == Account.State.ONLINE) {
1571 PresencePacket packet = new PresencePacket();
1572 packet.setTo(conversation.getJid());
1573 packet.setFrom(conversation.getAccount().getJid());
1574 packet.setAttribute("type", "unavailable");
1575 sendPresencePacket(conversation.getAccount(), packet);
1576 conversation.getMucOptions().setOffline();
1577 conversation.deregisterWithBookmark();
1578 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1579 + ": leaving muc " + conversation.getJid());
1580 } else {
1581 account.pendingConferenceLeaves.add(conversation);
1582 }
1583 }
1584
1585 private String findConferenceServer(final Account account) {
1586 String server;
1587 if (account.getXmppConnection() != null) {
1588 server = account.getXmppConnection().getMucServer();
1589 if (server != null) {
1590 return server;
1591 }
1592 }
1593 for (Account other : getAccounts()) {
1594 if (other != account && other.getXmppConnection() != null) {
1595 server = other.getXmppConnection().getMucServer();
1596 if (server != null) {
1597 return server;
1598 }
1599 }
1600 }
1601 return null;
1602 }
1603
1604 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1605 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1606 if (account.getStatus() == Account.State.ONLINE) {
1607 try {
1608 String server = findConferenceServer(account);
1609 if (server == null) {
1610 if (callback != null) {
1611 callback.error(R.string.no_conference_server_found, null);
1612 }
1613 return;
1614 }
1615 String name = new BigInteger(75, getRNG()).toString(32);
1616 Jid jid = Jid.fromParts(name, server, null);
1617 final Conversation conversation = findOrCreateConversation(account, jid, true);
1618 joinMuc(conversation);
1619 Bundle options = new Bundle();
1620 options.putString("muc#roomconfig_persistentroom", "1");
1621 options.putString("muc#roomconfig_membersonly", "1");
1622 options.putString("muc#roomconfig_publicroom", "0");
1623 options.putString("muc#roomconfig_whois", "anyone");
1624 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1625 @Override
1626 public void onPushSucceeded() {
1627 for (Jid invite : jids) {
1628 invite(conversation, invite);
1629 }
1630 if (account.countPresences() > 1) {
1631 directInvite(conversation, account.getJid().toBareJid());
1632 }
1633 if (callback != null) {
1634 callback.success(conversation);
1635 }
1636 }
1637
1638 @Override
1639 public void onPushFailed() {
1640 if (callback != null) {
1641 callback.error(R.string.conference_creation_failed, conversation);
1642 }
1643 }
1644 });
1645
1646 } catch (InvalidJidException e) {
1647 if (callback != null) {
1648 callback.error(R.string.conference_creation_failed, null);
1649 }
1650 }
1651 } else {
1652 if (callback != null) {
1653 callback.error(R.string.not_connected_try_again, null);
1654 }
1655 }
1656 }
1657
1658 public void fetchConferenceConfiguration(final Conversation conversation) {
1659 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1660 request.setTo(conversation.getJid().toBareJid());
1661 request.query("http://jabber.org/protocol/disco#info");
1662 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1663 @Override
1664 public void onIqPacketReceived(Account account, IqPacket packet) {
1665 if (packet.getType() != IqPacket.TYPE.ERROR) {
1666 ArrayList<String> features = new ArrayList<>();
1667 for (Element child : packet.query().getChildren()) {
1668 if (child != null && child.getName().equals("feature")) {
1669 String var = child.getAttribute("var");
1670 if (var != null) {
1671 features.add(var);
1672 }
1673 }
1674 }
1675 conversation.getMucOptions().updateFeatures(features);
1676 updateConversationUi();
1677 }
1678 }
1679 });
1680 }
1681
1682 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1683 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1684 request.setTo(conversation.getJid().toBareJid());
1685 request.query("http://jabber.org/protocol/muc#owner");
1686 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1687 @Override
1688 public void onIqPacketReceived(Account account, IqPacket packet) {
1689 if (packet.getType() != IqPacket.TYPE.ERROR) {
1690 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1691 for (Field field : data.getFields()) {
1692 if (options.containsKey(field.getName())) {
1693 field.setValue(options.getString(field.getName()));
1694 }
1695 }
1696 data.submit();
1697 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1698 set.setTo(conversation.getJid().toBareJid());
1699 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1700 sendIqPacket(account, set, new OnIqPacketReceived() {
1701 @Override
1702 public void onIqPacketReceived(Account account, IqPacket packet) {
1703 if (packet.getType() == IqPacket.TYPE.RESULT) {
1704 if (callback != null) {
1705 callback.onPushSucceeded();
1706 }
1707 } else {
1708 if (callback != null) {
1709 callback.onPushFailed();
1710 }
1711 }
1712 }
1713 });
1714 } else {
1715 if (callback != null) {
1716 callback.onPushFailed();
1717 }
1718 }
1719 }
1720 });
1721 }
1722
1723 public void pushSubjectToConference(final Conversation conference, final String subject) {
1724 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1725 this.sendMessagePacket(conference.getAccount(), packet);
1726 final MucOptions mucOptions = conference.getMucOptions();
1727 final MucOptions.User self = mucOptions.getSelf();
1728 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1729 Bundle options = new Bundle();
1730 options.putString("muc#roomconfig_persistentroom", "1");
1731 this.pushConferenceConfiguration(conference, options, null);
1732 }
1733 }
1734
1735 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1736 final Jid jid = user.toBareJid();
1737 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1738 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1739 @Override
1740 public void onIqPacketReceived(Account account, IqPacket packet) {
1741 if (packet.getType() == IqPacket.TYPE.RESULT) {
1742 callback.onAffiliationChangedSuccessful(jid);
1743 } else {
1744 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1745 }
1746 }
1747 });
1748 }
1749
1750 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1751 List<Jid> jids = new ArrayList<>();
1752 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1753 if (user.getAffiliation() == before && user.getJid() != null) {
1754 jids.add(user.getJid());
1755 }
1756 }
1757 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1758 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1759 }
1760
1761 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1762 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1763 Log.d(Config.LOGTAG, request.toString());
1764 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1765 @Override
1766 public void onIqPacketReceived(Account account, IqPacket packet) {
1767 Log.d(Config.LOGTAG, packet.toString());
1768 if (packet.getType() == IqPacket.TYPE.RESULT) {
1769 callback.onRoleChangedSuccessful(nick);
1770 } else {
1771 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1772 }
1773 }
1774 });
1775 }
1776
1777 public void disconnect(Account account, boolean force) {
1778 if ((account.getStatus() == Account.State.ONLINE)
1779 || (account.getStatus() == Account.State.DISABLED)) {
1780 if (!force) {
1781 List<Conversation> conversations = getConversations();
1782 for (Conversation conversation : conversations) {
1783 if (conversation.getAccount() == account) {
1784 if (conversation.getMode() == Conversation.MODE_MULTI) {
1785 leaveMuc(conversation);
1786 } else {
1787 if (conversation.endOtrIfNeeded()) {
1788 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1789 + ": ended otr session with "
1790 + conversation.getJid());
1791 }
1792 }
1793 }
1794 }
1795 sendOfflinePresence(account);
1796 }
1797 account.getXmppConnection().disconnect(force);
1798 }
1799 }
1800
1801 @Override
1802 public IBinder onBind(Intent intent) {
1803 return mBinder;
1804 }
1805
1806 public void updateMessage(Message message) {
1807 databaseBackend.updateMessage(message);
1808 updateConversationUi();
1809 }
1810
1811 protected void syncDirtyContacts(Account account) {
1812 for (Contact contact : account.getRoster().getContacts()) {
1813 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1814 pushContactToServer(contact);
1815 }
1816 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1817 deleteContactOnServer(contact);
1818 }
1819 }
1820 }
1821
1822 public void createContact(Contact contact) {
1823 SharedPreferences sharedPref = getPreferences();
1824 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1825 if (autoGrant) {
1826 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1827 contact.setOption(Contact.Options.ASKING);
1828 }
1829 pushContactToServer(contact);
1830 }
1831
1832 public void onOtrSessionEstablished(Conversation conversation) {
1833 final Account account = conversation.getAccount();
1834 final Session otrSession = conversation.getOtrSession();
1835 Log.d(Config.LOGTAG,
1836 account.getJid().toBareJid() + " otr session established with "
1837 + conversation.getJid() + "/"
1838 + otrSession.getSessionID().getUserID());
1839 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
1840
1841 @Override
1842 public void onMessageFound(Message message) {
1843 SessionID id = otrSession.getSessionID();
1844 try {
1845 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1846 } catch (InvalidJidException e) {
1847 return;
1848 }
1849 if (message.needsUploading()) {
1850 mJingleConnectionManager.createNewConnection(message);
1851 } else {
1852 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
1853 if (outPacket != null) {
1854 mMessageGenerator.addDelay(outPacket, message.getTimeSent());
1855 message.setStatus(Message.STATUS_SEND);
1856 databaseBackend.updateMessage(message);
1857 sendMessagePacket(account, outPacket);
1858 }
1859 }
1860 updateConversationUi();
1861 }
1862 });
1863 }
1864
1865 public boolean renewSymmetricKey(Conversation conversation) {
1866 Account account = conversation.getAccount();
1867 byte[] symmetricKey = new byte[32];
1868 this.mRandom.nextBytes(symmetricKey);
1869 Session otrSession = conversation.getOtrSession();
1870 if (otrSession != null) {
1871 MessagePacket packet = new MessagePacket();
1872 packet.setType(MessagePacket.TYPE_CHAT);
1873 packet.setFrom(account.getJid());
1874 packet.addChild("private", "urn:xmpp:carbons:2");
1875 packet.addChild("no-copy", "urn:xmpp:hints");
1876 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1877 + otrSession.getSessionID().getUserID());
1878 try {
1879 packet.setBody(otrSession
1880 .transformSending(CryptoHelper.FILETRANSFER
1881 + CryptoHelper.bytesToHex(symmetricKey))[0]);
1882 sendMessagePacket(account, packet);
1883 conversation.setSymmetricKey(symmetricKey);
1884 return true;
1885 } catch (OtrException e) {
1886 return false;
1887 }
1888 }
1889 return false;
1890 }
1891
1892 public void pushContactToServer(final Contact contact) {
1893 contact.resetOption(Contact.Options.DIRTY_DELETE);
1894 contact.setOption(Contact.Options.DIRTY_PUSH);
1895 final Account account = contact.getAccount();
1896 if (account.getStatus() == Account.State.ONLINE) {
1897 final boolean ask = contact.getOption(Contact.Options.ASKING);
1898 final boolean sendUpdates = contact
1899 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1900 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1901 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1902 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1903 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1904 if (sendUpdates) {
1905 sendPresencePacket(account,
1906 mPresenceGenerator.sendPresenceUpdatesTo(contact));
1907 }
1908 if (ask) {
1909 sendPresencePacket(account,
1910 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1911 }
1912 }
1913 }
1914
1915 public void publishAvatar(final Account account,
1916 final Uri image,
1917 final UiCallback<Avatar> callback) {
1918 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1919 final int size = Config.AVATAR_SIZE;
1920 final Avatar avatar = getFileBackend()
1921 .getPepAvatar(image, size, format);
1922 if (avatar != null) {
1923 avatar.height = size;
1924 avatar.width = size;
1925 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1926 avatar.type = "image/webp";
1927 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1928 avatar.type = "image/jpeg";
1929 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1930 avatar.type = "image/png";
1931 }
1932 if (!getFileBackend().save(avatar)) {
1933 callback.error(R.string.error_saving_avatar, avatar);
1934 return;
1935 }
1936 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1937 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1938
1939 @Override
1940 public void onIqPacketReceived(Account account, IqPacket result) {
1941 if (result.getType() == IqPacket.TYPE.RESULT) {
1942 final IqPacket packet = XmppConnectionService.this.mIqGenerator
1943 .publishAvatarMetadata(avatar);
1944 sendIqPacket(account, packet, new OnIqPacketReceived() {
1945
1946 @Override
1947 public void onIqPacketReceived(Account account,
1948 IqPacket result) {
1949 if (result.getType() == IqPacket.TYPE.RESULT) {
1950 if (account.setAvatar(avatar.getFilename())) {
1951 getAvatarService().clear(account);
1952 databaseBackend.updateAccount(account);
1953 }
1954 callback.success(avatar);
1955 } else {
1956 callback.error(
1957 R.string.error_publish_avatar_server_reject,
1958 avatar);
1959 }
1960 }
1961 });
1962 } else {
1963 callback.error(
1964 R.string.error_publish_avatar_server_reject,
1965 avatar);
1966 }
1967 }
1968 });
1969 } else {
1970 callback.error(R.string.error_publish_avatar_converting, null);
1971 }
1972 }
1973
1974 public void fetchAvatar(Account account, Avatar avatar) {
1975 fetchAvatar(account, avatar, null);
1976 }
1977
1978 private static String generateFetchKey(Account account, final Avatar avatar) {
1979 return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1980 }
1981
1982 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1983 final String KEY = generateFetchKey(account, avatar);
1984 synchronized(this.mInProgressAvatarFetches) {
1985 if (this.mInProgressAvatarFetches.contains(KEY)) {
1986 return;
1987 } else {
1988 switch (avatar.origin) {
1989 case PEP:
1990 this.mInProgressAvatarFetches.add(KEY);
1991 fetchAvatarPep(account, avatar, callback);
1992 break;
1993 case VCARD:
1994 this.mInProgressAvatarFetches.add(KEY);
1995 fetchAvatarVcard(account, avatar, callback);
1996 break;
1997 }
1998 }
1999 }
2000 }
2001
2002 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2003 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2004 sendIqPacket(account, packet, new OnIqPacketReceived() {
2005
2006 @Override
2007 public void onIqPacketReceived(Account account, IqPacket result) {
2008 synchronized (mInProgressAvatarFetches) {
2009 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2010 }
2011 final String ERROR = account.getJid().toBareJid()
2012 + ": fetching avatar for " + avatar.owner + " failed ";
2013 if (result.getType() == IqPacket.TYPE.RESULT) {
2014 avatar.image = mIqParser.avatarData(result);
2015 if (avatar.image != null) {
2016 if (getFileBackend().save(avatar)) {
2017 if (account.getJid().toBareJid().equals(avatar.owner)) {
2018 if (account.setAvatar(avatar.getFilename())) {
2019 databaseBackend.updateAccount(account);
2020 }
2021 getAvatarService().clear(account);
2022 updateConversationUi();
2023 updateAccountUi();
2024 } else {
2025 Contact contact = account.getRoster()
2026 .getContact(avatar.owner);
2027 contact.setAvatar(avatar);
2028 getAvatarService().clear(contact);
2029 updateConversationUi();
2030 updateRosterUi();
2031 }
2032 if (callback != null) {
2033 callback.success(avatar);
2034 }
2035 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2036 + ": succesfuly fetched pep avatar for " + avatar.owner);
2037 return;
2038 }
2039 } else {
2040
2041 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2042 }
2043 } else {
2044 Element error = result.findChild("error");
2045 if (error == null) {
2046 Log.d(Config.LOGTAG, ERROR + "(server error)");
2047 } else {
2048 Log.d(Config.LOGTAG, ERROR + error.toString());
2049 }
2050 }
2051 if (callback != null) {
2052 callback.error(0, null);
2053 }
2054
2055 }
2056 });
2057 }
2058
2059 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2060 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2061 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2062 @Override
2063 public void onIqPacketReceived(Account account, IqPacket packet) {
2064 synchronized (mInProgressAvatarFetches) {
2065 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2066 }
2067 if (packet.getType() == IqPacket.TYPE.RESULT) {
2068 Element vCard = packet.findChild("vCard", "vcard-temp");
2069 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2070 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2071 if (image != null) {
2072 avatar.image = image;
2073 if (getFileBackend().save(avatar)) {
2074 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2075 + ": successfully fetched vCard avatar for " + avatar.owner);
2076 Contact contact = account.getRoster()
2077 .getContact(avatar.owner);
2078 contact.setAvatar(avatar);
2079 getAvatarService().clear(contact);
2080 updateConversationUi();
2081 updateRosterUi();
2082 }
2083 }
2084 }
2085 }
2086 });
2087 }
2088
2089 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2090 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2091 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2092
2093 @Override
2094 public void onIqPacketReceived(Account account, IqPacket packet) {
2095 if (packet.getType() == IqPacket.TYPE.RESULT) {
2096 Element pubsub = packet.findChild("pubsub",
2097 "http://jabber.org/protocol/pubsub");
2098 if (pubsub != null) {
2099 Element items = pubsub.findChild("items");
2100 if (items != null) {
2101 Avatar avatar = Avatar.parseMetadata(items);
2102 if (avatar != null) {
2103 avatar.owner = account.getJid().toBareJid();
2104 if (fileBackend.isAvatarCached(avatar)) {
2105 if (account.setAvatar(avatar.getFilename())) {
2106 databaseBackend.updateAccount(account);
2107 }
2108 getAvatarService().clear(account);
2109 callback.success(avatar);
2110 } else {
2111 fetchAvatarPep(account, avatar, callback);
2112 }
2113 return;
2114 }
2115 }
2116 }
2117 }
2118 callback.error(0, null);
2119 }
2120 });
2121 }
2122
2123 public void deleteContactOnServer(Contact contact) {
2124 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2125 contact.resetOption(Contact.Options.DIRTY_PUSH);
2126 contact.setOption(Contact.Options.DIRTY_DELETE);
2127 Account account = contact.getAccount();
2128 if (account.getStatus() == Account.State.ONLINE) {
2129 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2130 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2131 item.setAttribute("jid", contact.getJid().toString());
2132 item.setAttribute("subscription", "remove");
2133 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2134 }
2135 }
2136
2137 public void updateConversation(Conversation conversation) {
2138 this.databaseBackend.updateConversation(conversation);
2139 }
2140
2141 public void reconnectAccount(final Account account, final boolean force) {
2142 synchronized (account) {
2143 if (account.getXmppConnection() != null) {
2144 disconnect(account, force);
2145 }
2146 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2147
2148 synchronized (this.mInProgressAvatarFetches) {
2149 for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2150 final String KEY = iterator.next();
2151 if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2152 iterator.remove();
2153 }
2154 }
2155 }
2156
2157 if (account.getXmppConnection() == null) {
2158 account.setXmppConnection(createConnection(account));
2159 }
2160 Thread thread = new Thread(account.getXmppConnection());
2161 thread.start();
2162 scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2163 } else {
2164 account.getRoster().clearPresences();
2165 account.setXmppConnection(null);
2166 }
2167 }
2168 }
2169
2170 public void reconnectAccountInBackground(final Account account) {
2171 new Thread(new Runnable() {
2172 @Override
2173 public void run() {
2174 reconnectAccount(account,false);
2175 }
2176 }).start();
2177 }
2178
2179 public void invite(Conversation conversation, Jid contact) {
2180 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2181 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2182 sendMessagePacket(conversation.getAccount(), packet);
2183 }
2184
2185 public void directInvite(Conversation conversation, Jid jid) {
2186 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2187 sendMessagePacket(conversation.getAccount(),packet);
2188 }
2189
2190 public void resetSendingToWaiting(Account account) {
2191 for (Conversation conversation : getConversations()) {
2192 if (conversation.getAccount() == account) {
2193 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2194
2195 @Override
2196 public void onMessageFound(Message message) {
2197 markMessage(message, Message.STATUS_WAITING);
2198 }
2199 });
2200 }
2201 }
2202 }
2203
2204 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2205 if (uuid == null) {
2206 return null;
2207 }
2208 for (Conversation conversation : getConversations()) {
2209 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2210 final Message message = conversation.findSentMessageWithUuid(uuid);
2211 if (message != null) {
2212 markMessage(message, status);
2213 }
2214 return message;
2215 }
2216 }
2217 return null;
2218 }
2219
2220 public boolean markMessage(Conversation conversation, String uuid,
2221 int status) {
2222 if (uuid == null) {
2223 return false;
2224 } else {
2225 Message message = conversation.findSentMessageWithUuid(uuid);
2226 if (message != null) {
2227 markMessage(message, status);
2228 return true;
2229 } else {
2230 return false;
2231 }
2232 }
2233 }
2234
2235 public void markMessage(Message message, int status) {
2236 if (status == Message.STATUS_SEND_FAILED
2237 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2238 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2239 return;
2240 }
2241 message.setStatus(status);
2242 databaseBackend.updateMessage(message);
2243 updateConversationUi();
2244 }
2245
2246 public SharedPreferences getPreferences() {
2247 return PreferenceManager
2248 .getDefaultSharedPreferences(getApplicationContext());
2249 }
2250
2251 public boolean forceEncryption() {
2252 return getPreferences().getBoolean("force_encryption", false);
2253 }
2254
2255 public boolean confirmMessages() {
2256 return getPreferences().getBoolean("confirm_messages", true);
2257 }
2258
2259 public boolean sendChatStates() {
2260 return getPreferences().getBoolean("chat_states", false);
2261 }
2262
2263 public boolean saveEncryptedMessages() {
2264 return !getPreferences().getBoolean("dont_save_encrypted", false);
2265 }
2266
2267 public boolean indicateReceived() {
2268 return getPreferences().getBoolean("indicate_received", false);
2269 }
2270
2271 public int unreadCount() {
2272 int count = 0;
2273 for(Conversation conversation : getConversations()) {
2274 count += conversation.unreadCount();
2275 }
2276 return count;
2277 }
2278
2279
2280 public void showErrorToastInUi(int resId) {
2281 if (mOnShowErrorToast != null) {
2282 mOnShowErrorToast.onShowErrorToast(resId);
2283 }
2284 }
2285
2286 public void updateConversationUi() {
2287 if (mOnConversationUpdate != null) {
2288 mOnConversationUpdate.onConversationUpdate();
2289 }
2290 }
2291
2292 public void updateAccountUi() {
2293 if (mOnAccountUpdate != null) {
2294 mOnAccountUpdate.onAccountUpdate();
2295 }
2296 }
2297
2298 public void updateRosterUi() {
2299 if (mOnRosterUpdate != null) {
2300 mOnRosterUpdate.onRosterUpdate();
2301 }
2302 }
2303
2304 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2305 if (mOnUpdateBlocklist != null) {
2306 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2307 }
2308 }
2309
2310 public void updateMucRosterUi() {
2311 if (mOnMucRosterUpdate != null) {
2312 mOnMucRosterUpdate.onMucRosterUpdate();
2313 }
2314 }
2315
2316 public void keyStatusUpdated() {
2317 if(mOnKeyStatusUpdated != null) {
2318 mOnKeyStatusUpdated.onKeyStatusUpdated();
2319 }
2320 }
2321
2322 public Account findAccountByJid(final Jid accountJid) {
2323 for (Account account : this.accounts) {
2324 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2325 return account;
2326 }
2327 }
2328 return null;
2329 }
2330
2331 public Conversation findConversationByUuid(String uuid) {
2332 for (Conversation conversation : getConversations()) {
2333 if (conversation.getUuid().equals(uuid)) {
2334 return conversation;
2335 }
2336 }
2337 return null;
2338 }
2339
2340 public void markRead(final Conversation conversation) {
2341 mNotificationService.clear(conversation);
2342 conversation.markRead();
2343 updateUnreadCountBadge();
2344 }
2345
2346 public synchronized void updateUnreadCountBadge() {
2347 int count = unreadCount();
2348 if (unreadCount != count) {
2349 Log.d(Config.LOGTAG, "update unread count to " + count);
2350 if (count > 0) {
2351 ShortcutBadger.with(getApplicationContext()).count(count);
2352 } else {
2353 ShortcutBadger.with(getApplicationContext()).remove();
2354 }
2355 unreadCount = count;
2356 }
2357 }
2358
2359 public void sendReadMarker(final Conversation conversation) {
2360 final Message markable = conversation.getLatestMarkableMessage();
2361 this.markRead(conversation);
2362 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2363 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2364 Account account = conversation.getAccount();
2365 final Jid to = markable.getCounterpart();
2366 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2367 this.sendMessagePacket(conversation.getAccount(), packet);
2368 }
2369 updateConversationUi();
2370 }
2371
2372 public SecureRandom getRNG() {
2373 return this.mRandom;
2374 }
2375
2376 public MemorizingTrustManager getMemorizingTrustManager() {
2377 return this.mMemorizingTrustManager;
2378 }
2379
2380 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2381 this.mMemorizingTrustManager = trustManager;
2382 }
2383
2384 public void updateMemorizingTrustmanager() {
2385 final MemorizingTrustManager tm;
2386 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2387 if (dontTrustSystemCAs) {
2388 tm = new MemorizingTrustManager(getApplicationContext(), null);
2389 } else {
2390 tm = new MemorizingTrustManager(getApplicationContext());
2391 }
2392 setMemorizingTrustManager(tm);
2393 }
2394
2395 public PowerManager getPowerManager() {
2396 return this.pm;
2397 }
2398
2399 public LruCache<String, Bitmap> getBitmapCache() {
2400 return this.mBitmapCache;
2401 }
2402
2403 public void syncRosterToDisk(final Account account) {
2404 Runnable runnable = new Runnable() {
2405
2406 @Override
2407 public void run() {
2408 databaseBackend.writeRoster(account.getRoster());
2409 }
2410 };
2411 mDatabaseExecutor.execute(runnable);
2412
2413 }
2414
2415 public List<String> getKnownHosts() {
2416 final List<String> hosts = new ArrayList<>();
2417 for (final Account account : getAccounts()) {
2418 if (!hosts.contains(account.getServer().toString())) {
2419 hosts.add(account.getServer().toString());
2420 }
2421 for (final Contact contact : account.getRoster().getContacts()) {
2422 if (contact.showInRoster()) {
2423 final String server = contact.getServer().toString();
2424 if (server != null && !hosts.contains(server)) {
2425 hosts.add(server);
2426 }
2427 }
2428 }
2429 }
2430 return hosts;
2431 }
2432
2433 public List<String> getKnownConferenceHosts() {
2434 final ArrayList<String> mucServers = new ArrayList<>();
2435 for (final Account account : accounts) {
2436 if (account.getXmppConnection() != null) {
2437 final String server = account.getXmppConnection().getMucServer();
2438 if (server != null && !mucServers.contains(server)) {
2439 mucServers.add(server);
2440 }
2441 }
2442 }
2443 return mucServers;
2444 }
2445
2446 public void sendMessagePacket(Account account, MessagePacket packet) {
2447 XmppConnection connection = account.getXmppConnection();
2448 if (connection != null) {
2449 connection.sendMessagePacket(packet);
2450 }
2451 }
2452
2453 public void sendPresencePacket(Account account, PresencePacket packet) {
2454 XmppConnection connection = account.getXmppConnection();
2455 if (connection != null) {
2456 connection.sendPresencePacket(packet);
2457 }
2458 }
2459
2460 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2461 final XmppConnection connection = account.getXmppConnection();
2462 if (connection != null) {
2463 connection.sendIqPacket(packet, callback);
2464 }
2465 }
2466
2467 public void sendPresence(final Account account) {
2468 sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2469 }
2470
2471 public void sendOfflinePresence(final Account account) {
2472 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2473 }
2474
2475 public MessageGenerator getMessageGenerator() {
2476 return this.mMessageGenerator;
2477 }
2478
2479 public PresenceGenerator getPresenceGenerator() {
2480 return this.mPresenceGenerator;
2481 }
2482
2483 public IqGenerator getIqGenerator() {
2484 return this.mIqGenerator;
2485 }
2486
2487 public IqParser getIqParser() {
2488 return this.mIqParser;
2489 }
2490
2491 public JingleConnectionManager getJingleConnectionManager() {
2492 return this.mJingleConnectionManager;
2493 }
2494
2495 public MessageArchiveService getMessageArchiveService() {
2496 return this.mMessageArchiveService;
2497 }
2498
2499 public List<Contact> findContacts(Jid jid) {
2500 ArrayList<Contact> contacts = new ArrayList<>();
2501 for (Account account : getAccounts()) {
2502 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2503 Contact contact = account.getRoster().getContactFromRoster(jid);
2504 if (contact != null) {
2505 contacts.add(contact);
2506 }
2507 }
2508 }
2509 return contacts;
2510 }
2511
2512 public NotificationService getNotificationService() {
2513 return this.mNotificationService;
2514 }
2515
2516 public HttpConnectionManager getHttpConnectionManager() {
2517 return this.mHttpConnectionManager;
2518 }
2519
2520 public void resendFailedMessages(final Message message) {
2521 final Collection<Message> messages = new ArrayList<>();
2522 Message current = message;
2523 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2524 messages.add(current);
2525 if (current.mergeable(current.next())) {
2526 current = current.next();
2527 } else {
2528 break;
2529 }
2530 }
2531 for (final Message msg : messages) {
2532 msg.setTime(System.currentTimeMillis());
2533 markMessage(msg, Message.STATUS_WAITING);
2534 this.resendMessage(msg,false);
2535 }
2536 }
2537
2538 public void clearConversationHistory(final Conversation conversation) {
2539 conversation.clearMessages();
2540 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2541 new Thread(new Runnable() {
2542 @Override
2543 public void run() {
2544 databaseBackend.deleteMessagesInConversation(conversation);
2545 }
2546 }).start();
2547 }
2548
2549 public void sendBlockRequest(final Blockable blockable) {
2550 if (blockable != null && blockable.getBlockedJid() != null) {
2551 final Jid jid = blockable.getBlockedJid();
2552 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2553
2554 @Override
2555 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2556 if (packet.getType() == IqPacket.TYPE.RESULT) {
2557 account.getBlocklist().add(jid);
2558 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2559 }
2560 }
2561 });
2562 }
2563 }
2564
2565 public void sendUnblockRequest(final Blockable blockable) {
2566 if (blockable != null && blockable.getJid() != null) {
2567 final Jid jid = blockable.getBlockedJid();
2568 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2569 @Override
2570 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2571 if (packet.getType() == IqPacket.TYPE.RESULT) {
2572 account.getBlocklist().remove(jid);
2573 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2574 }
2575 }
2576 });
2577 }
2578 }
2579
2580 public interface OnMoreMessagesLoaded {
2581 public void onMoreMessagesLoaded(int count, Conversation conversation);
2582
2583 public void informUser(int r);
2584 }
2585
2586 public interface OnAccountPasswordChanged {
2587 public void onPasswordChangeSucceeded();
2588
2589 public void onPasswordChangeFailed();
2590 }
2591
2592 public interface OnAffiliationChanged {
2593 public void onAffiliationChangedSuccessful(Jid jid);
2594
2595 public void onAffiliationChangeFailed(Jid jid, int resId);
2596 }
2597
2598 public interface OnRoleChanged {
2599 public void onRoleChangedSuccessful(String nick);
2600
2601 public void onRoleChangeFailed(String nick, int resid);
2602 }
2603
2604 public interface OnConversationUpdate {
2605 public void onConversationUpdate();
2606 }
2607
2608 public interface OnAccountUpdate {
2609 public void onAccountUpdate();
2610 }
2611
2612 public interface OnRosterUpdate {
2613 public void onRosterUpdate();
2614 }
2615
2616 public interface OnMucRosterUpdate {
2617 public void onMucRosterUpdate();
2618 }
2619
2620 public interface OnConferenceOptionsPushed {
2621 public void onPushSucceeded();
2622
2623 public void onPushFailed();
2624 }
2625
2626 public interface OnShowErrorToast {
2627 void onShowErrorToast(int resId);
2628 }
2629
2630 public class XmppConnectionBinder extends Binder {
2631 public XmppConnectionService getService() {
2632 return XmppConnectionService.this;
2633 }
2634 }
2635}