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