1package eu.siacs.conversations.services;
2
3import android.annotation.SuppressLint;
4import android.annotation.TargetApi;
5import android.app.AlarmManager;
6import android.app.PendingIntent;
7import android.app.Service;
8import android.content.Context;
9import android.content.Intent;
10import android.content.IntentFilter;
11import android.content.SharedPreferences;
12import android.database.ContentObserver;
13import android.graphics.Bitmap;
14import android.media.AudioManager;
15import android.net.ConnectivityManager;
16import android.net.NetworkInfo;
17import android.net.Uri;
18import android.os.Binder;
19import android.os.Build;
20import android.os.Bundle;
21import android.os.Environment;
22import android.os.IBinder;
23import android.os.PowerManager;
24import android.os.PowerManager.WakeLock;
25import android.os.SystemClock;
26import android.preference.PreferenceManager;
27import android.provider.ContactsContract;
28import android.security.KeyChain;
29import android.support.v4.app.RemoteInput;
30import android.util.DisplayMetrics;
31import android.util.Log;
32import android.util.LruCache;
33import android.util.Pair;
34
35import net.java.otr4j.OtrException;
36import net.java.otr4j.session.Session;
37import net.java.otr4j.session.SessionID;
38import net.java.otr4j.session.SessionImpl;
39import net.java.otr4j.session.SessionStatus;
40
41import org.openintents.openpgp.IOpenPgpService2;
42import org.openintents.openpgp.util.OpenPgpApi;
43import org.openintents.openpgp.util.OpenPgpServiceConnection;
44
45import java.math.BigInteger;
46import java.security.SecureRandom;
47import java.security.cert.CertificateException;
48import java.security.cert.X509Certificate;
49import java.util.ArrayList;
50import java.util.Arrays;
51import java.util.Collection;
52import java.util.Collections;
53import java.util.HashMap;
54import java.util.HashSet;
55import java.util.Hashtable;
56import java.util.Iterator;
57import java.util.List;
58import java.util.Locale;
59import java.util.Map;
60import java.util.concurrent.CopyOnWriteArrayList;
61
62import de.duenndns.ssl.MemorizingTrustManager;
63import eu.siacs.conversations.Config;
64import eu.siacs.conversations.R;
65import eu.siacs.conversations.crypto.PgpDecryptionService;
66import eu.siacs.conversations.crypto.PgpEngine;
67import eu.siacs.conversations.crypto.axolotl.AxolotlService;
68import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
69import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
70import eu.siacs.conversations.entities.Account;
71import eu.siacs.conversations.entities.Blockable;
72import eu.siacs.conversations.entities.Bookmark;
73import eu.siacs.conversations.entities.Contact;
74import eu.siacs.conversations.entities.Conversation;
75import eu.siacs.conversations.entities.DownloadableFile;
76import eu.siacs.conversations.entities.Message;
77import eu.siacs.conversations.entities.MucOptions;
78import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
79import eu.siacs.conversations.entities.Presence;
80import eu.siacs.conversations.entities.PresenceTemplate;
81import eu.siacs.conversations.entities.Roster;
82import eu.siacs.conversations.entities.ServiceDiscoveryResult;
83import eu.siacs.conversations.entities.Transferable;
84import eu.siacs.conversations.entities.TransferablePlaceholder;
85import eu.siacs.conversations.generator.AbstractGenerator;
86import eu.siacs.conversations.generator.IqGenerator;
87import eu.siacs.conversations.generator.MessageGenerator;
88import eu.siacs.conversations.generator.PresenceGenerator;
89import eu.siacs.conversations.http.HttpConnectionManager;
90import eu.siacs.conversations.parser.AbstractParser;
91import eu.siacs.conversations.parser.IqParser;
92import eu.siacs.conversations.parser.MessageParser;
93import eu.siacs.conversations.parser.PresenceParser;
94import eu.siacs.conversations.persistance.DatabaseBackend;
95import eu.siacs.conversations.persistance.FileBackend;
96import eu.siacs.conversations.ui.SettingsActivity;
97import eu.siacs.conversations.ui.UiCallback;
98import eu.siacs.conversations.utils.ConversationsFileObserver;
99import eu.siacs.conversations.utils.CryptoHelper;
100import eu.siacs.conversations.utils.ExceptionHelper;
101import eu.siacs.conversations.utils.MimeUtils;
102import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
103import eu.siacs.conversations.utils.PRNGFixes;
104import eu.siacs.conversations.utils.PhoneHelper;
105import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
106import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
107import eu.siacs.conversations.utils.Xmlns;
108import eu.siacs.conversations.utils.XmppUri;
109import eu.siacs.conversations.xml.Element;
110import eu.siacs.conversations.xmpp.OnBindListener;
111import eu.siacs.conversations.xmpp.OnContactStatusChanged;
112import eu.siacs.conversations.xmpp.OnIqPacketReceived;
113import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
114import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
115import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
116import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
117import eu.siacs.conversations.xmpp.OnStatusChanged;
118import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
119import eu.siacs.conversations.xmpp.XmppConnection;
120import eu.siacs.conversations.xmpp.chatstate.ChatState;
121import eu.siacs.conversations.xmpp.forms.Data;
122import eu.siacs.conversations.xmpp.forms.Field;
123import eu.siacs.conversations.xmpp.jid.InvalidJidException;
124import eu.siacs.conversations.xmpp.jid.Jid;
125import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
126import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
127import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
128import eu.siacs.conversations.xmpp.pep.Avatar;
129import eu.siacs.conversations.xmpp.stanzas.IqPacket;
130import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
131import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
132import me.leolin.shortcutbadger.ShortcutBadger;
133
134public class XmppConnectionService extends Service {
135
136 public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
137 public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
138 public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
139 public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
140 public static final String ACTION_TRY_AGAIN = "try_again";
141 public static final String ACTION_IDLE_PING = "idle_ping";
142 private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
143 public static final String ACTION_GCM_TOKEN_REFRESH = "gcm_token_refresh";
144 public static final String ACTION_GCM_MESSAGE_RECEIVED = "gcm_message_received";
145 private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
146 private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
147 private ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor(true);
148 private final IBinder mBinder = new XmppConnectionBinder();
149 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
150 private final IqGenerator mIqGenerator = new IqGenerator(this);
151 private final List<String> mInProgressAvatarFetches = new ArrayList<>();
152 private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
153
154 private long mLastActivity = 0;
155
156 public DatabaseBackend databaseBackend;
157 private ContentObserver contactObserver = new ContentObserver(null) {
158 @Override
159 public void onChange(boolean selfChange) {
160 super.onChange(selfChange);
161 Intent intent = new Intent(getApplicationContext(),
162 XmppConnectionService.class);
163 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
164 startService(intent);
165 }
166 };
167 private FileBackend fileBackend = new FileBackend(this);
168 private MemorizingTrustManager mMemorizingTrustManager;
169 private NotificationService mNotificationService = new NotificationService(
170 this);
171 private OnMessagePacketReceived mMessageParser = new MessageParser(this);
172 private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
173 private IqParser mIqParser = new IqParser(this);
174 private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
175 @Override
176 public void onIqPacketReceived(Account account, IqPacket packet) {
177 if (packet.getType() != IqPacket.TYPE.RESULT) {
178 Element error = packet.findChild("error");
179 String text = error != null ? error.findChildContent("text") : null;
180 if (text != null) {
181 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
182 }
183 }
184 }
185 };
186 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
187 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
188 private List<Account> accounts;
189 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
190 this);
191 public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
192
193 @Override
194 public void onContactStatusChanged(Contact contact, boolean online) {
195 Conversation conversation = find(getConversations(), contact);
196 if (conversation != null) {
197 if (online) {
198 conversation.endOtrIfNeeded();
199 if (contact.getPresences().size() == 1) {
200 sendUnsentMessages(conversation);
201 }
202 } else {
203 //check if the resource we are haveing a conversation with is still online
204 if (conversation.hasValidOtrSession()) {
205 String otrResource = conversation.getOtrSession().getSessionID().getUserID();
206 if (!(Arrays.asList(contact.getPresences().toResourceArray()).contains(otrResource))) {
207 conversation.endOtrIfNeeded();
208 }
209 }
210 }
211 }
212 }
213 };
214 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
215 this);
216 private AvatarService mAvatarService = new AvatarService(this);
217 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
218 private PushManagementService mPushManagementService = new PushManagementService(this);
219 private OnConversationUpdate mOnConversationUpdate = null;
220
221
222 private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
223 Environment.getExternalStorageDirectory().getAbsolutePath()
224 ) {
225 @Override
226 public void onEvent(int event, String path) {
227 markFileDeleted(path);
228 }
229 };
230 private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
231
232 @Override
233 public void onJinglePacketReceived(Account account, JinglePacket packet) {
234 mJingleConnectionManager.deliverPacket(account, packet);
235 }
236 };
237 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
238
239 @Override
240 public void onMessageAcknowledged(Account account, String uuid) {
241 for (final Conversation conversation : getConversations()) {
242 if (conversation.getAccount() == account) {
243 Message message = conversation.findUnsentMessageWithUuid(uuid);
244 if (message != null) {
245 markMessage(message, Message.STATUS_SEND);
246 }
247 }
248 }
249 }
250 };
251 private int convChangedListenerCount = 0;
252 private OnShowErrorToast mOnShowErrorToast = null;
253 private int showErrorToastListenerCount = 0;
254 private int unreadCount = -1;
255 private OnAccountUpdate mOnAccountUpdate = null;
256 private OnCaptchaRequested mOnCaptchaRequested = null;
257 private int accountChangedListenerCount = 0;
258 private int captchaRequestedListenerCount = 0;
259 private OnRosterUpdate mOnRosterUpdate = null;
260 private OnUpdateBlocklist mOnUpdateBlocklist = null;
261 private int updateBlocklistListenerCount = 0;
262 private int rosterChangedListenerCount = 0;
263 private OnMucRosterUpdate mOnMucRosterUpdate = null;
264 private int mucRosterChangedListenerCount = 0;
265 private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
266 private int keyStatusUpdatedListenerCount = 0;
267 private SecureRandom mRandom;
268 private LruCache<Pair<String,String>,ServiceDiscoveryResult> discoCache = new LruCache<>(20);
269 private final OnBindListener mOnBindListener = new OnBindListener() {
270
271 @Override
272 public void onBind(final Account account) {
273 synchronized (mInProgressAvatarFetches) {
274 for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
275 final String KEY = iterator.next();
276 if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
277 iterator.remove();
278 }
279 }
280 }
281 account.getRoster().clearPresences();
282 mJingleConnectionManager.cancelInTransmission();
283 fetchRosterFromServer(account);
284 fetchBookmarks(account);
285 sendPresence(account);
286 if (mPushManagementService.available(account)) {
287 mPushManagementService.registerPushTokenOnServer(account);
288 }
289 connectMultiModeConversations(account);
290 syncDirtyContacts(account);
291 }
292 };
293 private OnStatusChanged statusListener = new OnStatusChanged() {
294
295 @Override
296 public void onStatusChanged(final Account account) {
297 XmppConnection connection = account.getXmppConnection();
298 if (mOnAccountUpdate != null) {
299 mOnAccountUpdate.onAccountUpdate();
300 }
301 if (account.getStatus() == Account.State.ONLINE) {
302 synchronized (mLowPingTimeoutMode) {
303 if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) {
304 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode");
305 }
306 }
307 if (account.setShowErrorNotification(true)) {
308 databaseBackend.updateAccount(account);
309 }
310 mMessageArchiveService.executePendingQueries(account);
311 if (connection != null && connection.getFeatures().csi()) {
312 if (checkListeners()) {
313 Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
314 connection.sendInactive();
315 } else {
316 Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
317 connection.sendActive();
318 }
319 }
320 List<Conversation> conversations = getConversations();
321 for (Conversation conversation : conversations) {
322 if (conversation.getAccount() == account
323 && !account.pendingConferenceJoins.contains(conversation)) {
324 if (!conversation.startOtrIfNeeded()) {
325 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": couldn't start OTR with "+conversation.getContact().getJid()+" when needed");
326 }
327 sendUnsentMessages(conversation);
328 }
329 }
330 for (Conversation conversation : account.pendingConferenceLeaves) {
331 leaveMuc(conversation);
332 }
333 account.pendingConferenceLeaves.clear();
334 for (Conversation conversation : account.pendingConferenceJoins) {
335 joinMuc(conversation);
336 }
337 account.pendingConferenceJoins.clear();
338 scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
339 } else {
340 if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
341 resetSendingToWaiting(account);
342 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
343 synchronized (mLowPingTimeoutMode) {
344 if (mLowPingTimeoutMode.contains(account.getJid().toBareJid())) {
345 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": went into offline state during low ping mode. reconnecting now");
346 reconnectAccount(account, true, false);
347 } else {
348 int timeToReconnect = mRandom.nextInt(10) + 2;
349 scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
350 }
351 }
352 }
353 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
354 databaseBackend.updateAccount(account);
355 reconnectAccount(account, true, false);
356 } else if ((account.getStatus() != Account.State.CONNECTING)
357 && (account.getStatus() != Account.State.NO_INTERNET)) {
358 resetSendingToWaiting(account);
359 if (connection != null) {
360 int next = connection.getTimeToNextAttempt();
361 Log.d(Config.LOGTAG, account.getJid().toBareJid()
362 + ": error connecting account. try again in "
363 + next + "s for the "
364 + (connection.getAttempt() + 1) + " time");
365 scheduleWakeUpCall(next, account.getUuid().hashCode());
366 }
367 }
368 }
369 getNotificationService().updateErrorNotification();
370 }
371 };
372 private OpenPgpServiceConnection pgpServiceConnection;
373 private PgpEngine mPgpEngine = null;
374 private WakeLock wakeLock;
375 private PowerManager pm;
376 private LruCache<String, Bitmap> mBitmapCache;
377 private EventReceiver mEventReceiver = new EventReceiver();
378
379 private boolean mRestoredFromDatabase = false;
380
381 private static String generateFetchKey(Account account, final Avatar avatar) {
382 return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
383 }
384
385 public boolean areMessagesInitialized() {
386 return this.mRestoredFromDatabase;
387 }
388
389 public PgpEngine getPgpEngine() {
390 if (!Config.supportOpenPgp()) {
391 return null;
392 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
393 if (this.mPgpEngine == null) {
394 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
395 getApplicationContext(),
396 pgpServiceConnection.getService()), this);
397 }
398 return mPgpEngine;
399 } else {
400 return null;
401 }
402
403 }
404
405 public OpenPgpApi getOpenPgpApi() {
406 if (!Config.supportOpenPgp()) {
407 return null;
408 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
409 return new OpenPgpApi(this, pgpServiceConnection.getService());
410 } else {
411 return null;
412 }
413 }
414
415 public FileBackend getFileBackend() {
416 return this.fileBackend;
417 }
418
419 public AvatarService getAvatarService() {
420 return this.mAvatarService;
421 }
422
423 public void attachLocationToConversation(final Conversation conversation,
424 final Uri uri,
425 final UiCallback<Message> callback) {
426 int encryption = conversation.getNextEncryption();
427 if (encryption == Message.ENCRYPTION_PGP) {
428 encryption = Message.ENCRYPTION_DECRYPTED;
429 }
430 Message message = new Message(conversation, uri.toString(), encryption);
431 if (conversation.getNextCounterpart() != null) {
432 message.setCounterpart(conversation.getNextCounterpart());
433 }
434 if (encryption == Message.ENCRYPTION_DECRYPTED) {
435 getPgpEngine().encrypt(message, callback);
436 } else {
437 callback.success(message);
438 }
439 }
440
441 public void attachFileToConversation(final Conversation conversation,
442 final Uri uri,
443 final UiCallback<Message> callback) {
444 if (FileBackend.weOwnFile(this, uri)) {
445 Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
446 callback.error(R.string.security_error_invalid_file_access, null);
447 return;
448 }
449 final Message message;
450 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
451 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
452 } else {
453 message = new Message(conversation, "", conversation.getNextEncryption());
454 }
455 message.setCounterpart(conversation.getNextCounterpart());
456 message.setType(Message.TYPE_FILE);
457 final String path = getFileBackend().getOriginalPath(uri);
458 mFileAddingExecutor.execute(new Runnable() {
459 @Override
460 public void run() {
461 if (path != null) {
462 message.setRelativeFilePath(path);
463 getFileBackend().updateFileParams(message);
464 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
465 getPgpEngine().encrypt(message, callback);
466 } else {
467 callback.success(message);
468 }
469 } else {
470 try {
471 getFileBackend().copyFileToPrivateStorage(message, uri);
472 getFileBackend().updateFileParams(message);
473 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
474 final PgpEngine pgpEngine = getPgpEngine();
475 if (pgpEngine != null) {
476 pgpEngine.encrypt(message, callback);
477 } else if (callback != null) {
478 callback.error(R.string.unable_to_connect_to_keychain, null);
479 }
480 } else {
481 callback.success(message);
482 }
483 } catch (FileBackend.FileCopyException e) {
484 callback.error(e.getResId(), message);
485 }
486 }
487 }
488 });
489 }
490
491 public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
492 if (FileBackend.weOwnFile(this, uri)) {
493 Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
494 callback.error(R.string.security_error_invalid_file_access, null);
495 return;
496 }
497
498 final String mimeType = MimeUtils.guessMimeTypeFromUri(this, uri);
499 final String compressPictures = getCompressPicturesPreference();
500
501 if ("never".equals(compressPictures)
502 || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
503 || (mimeType != null && mimeType.endsWith("/gif"))) {
504 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+ ": not compressing picture. sending as file");
505 attachFileToConversation(conversation, uri, callback);
506 return;
507 }
508 final Message message;
509 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
510 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
511 } else {
512 message = new Message(conversation, "", conversation.getNextEncryption());
513 }
514 message.setCounterpart(conversation.getNextCounterpart());
515 message.setType(Message.TYPE_IMAGE);
516 mFileAddingExecutor.execute(new Runnable() {
517
518 @Override
519 public void run() {
520 try {
521 getFileBackend().copyImageToPrivateStorage(message, uri);
522 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
523 final PgpEngine pgpEngine = getPgpEngine();
524 if (pgpEngine != null) {
525 pgpEngine.encrypt(message, callback);
526 } else if (callback != null){
527 callback.error(R.string.unable_to_connect_to_keychain, null);
528 }
529 } else {
530 callback.success(message);
531 }
532 } catch (final FileBackend.FileCopyException e) {
533 callback.error(e.getResId(), message);
534 }
535 }
536 });
537 }
538
539 public Conversation find(Bookmark bookmark) {
540 return find(bookmark.getAccount(), bookmark.getJid());
541 }
542
543 public Conversation find(final Account account, final Jid jid) {
544 return find(getConversations(), account, jid);
545 }
546
547 @Override
548 public int onStartCommand(Intent intent, int flags, int startId) {
549 final String action = intent == null ? null : intent.getAction();
550 String pushedAccountHash = null;
551 boolean interactive = false;
552 if (action != null) {
553 final Conversation c = findConversationByUuid(intent.getStringExtra("uuid"));
554 switch (action) {
555 case ConnectivityManager.CONNECTIVITY_ACTION:
556 if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
557 resetAllAttemptCounts(true, false);
558 }
559 break;
560 case ACTION_MERGE_PHONE_CONTACTS:
561 if (mRestoredFromDatabase) {
562 loadPhoneContacts();
563 }
564 return START_STICKY;
565 case Intent.ACTION_SHUTDOWN:
566 logoutAndSave(true);
567 return START_NOT_STICKY;
568 case ACTION_CLEAR_NOTIFICATION:
569 if (c != null) {
570 mNotificationService.clear(c);
571 } else {
572 mNotificationService.clear();
573 }
574 break;
575 case ACTION_DISABLE_FOREGROUND:
576 getPreferences().edit().putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, false).commit();
577 toggleForegroundService();
578 break;
579 case ACTION_DISMISS_ERROR_NOTIFICATIONS:
580 dismissErrorNotifications();
581 break;
582 case ACTION_TRY_AGAIN:
583 resetAllAttemptCounts(false, true);
584 interactive = true;
585 break;
586 case ACTION_REPLY_TO_CONVERSATION:
587 Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
588 if (remoteInput != null && c != null) {
589 final CharSequence body = remoteInput.getCharSequence("text_reply");
590 if (body != null && body.length() > 0) {
591 directReply(c, body.toString(),intent.getBooleanExtra("dismiss_notification",false));
592 }
593 }
594 break;
595 case AudioManager.RINGER_MODE_CHANGED_ACTION:
596 if (xaOnSilentMode()) {
597 refreshAllPresences();
598 }
599 break;
600 case Intent.ACTION_SCREEN_ON:
601 deactivateGracePeriod();
602 case Intent.ACTION_SCREEN_OFF:
603 if (awayWhenScreenOff()) {
604 refreshAllPresences();
605 }
606 break;
607 case ACTION_GCM_TOKEN_REFRESH:
608 refreshAllGcmTokens();
609 break;
610 case ACTION_IDLE_PING:
611 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
612 scheduleNextIdlePing();
613 }
614 break;
615 case ACTION_GCM_MESSAGE_RECEIVED:
616 Log.d(Config.LOGTAG,"gcm push message arrived in service. extras="+intent.getExtras());
617 pushedAccountHash = intent.getStringExtra("account");
618 break;
619 }
620 }
621 synchronized (this) {
622 this.wakeLock.acquire();
623 boolean pingNow = ConnectivityManager.CONNECTIVITY_ACTION.equals(action);
624 HashSet<Account> pingCandidates = new HashSet<>();
625 for (Account account : accounts) {
626 pingNow |= processAccountState(account,
627 interactive,
628 "ui".equals(action),
629 CryptoHelper.getAccountFingerprint(account).equals(pushedAccountHash),
630 pingCandidates);
631 }
632 if (pingNow) {
633 for (Account account : pingCandidates) {
634 final boolean lowTimeout = mLowPingTimeoutMode.contains(account.getJid().toBareJid());
635 account.getXmppConnection().sendPing();
636 Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")");
637 scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
638 }
639 }
640 if (wakeLock.isHeld()) {
641 try {
642 wakeLock.release();
643 } catch (final RuntimeException ignored) {
644 }
645 }
646 }
647 return START_STICKY;
648 }
649
650 private boolean processAccountState(Account account, boolean interactive, boolean isUiAction, boolean isAccountPushed, HashSet<Account> pingCandidates) {
651 boolean pingNow = false;
652 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
653 if (!hasInternetConnection()) {
654 account.setStatus(Account.State.NO_INTERNET);
655 if (statusListener != null) {
656 statusListener.onStatusChanged(account);
657 }
658 } else {
659 if (account.getStatus() == Account.State.NO_INTERNET) {
660 account.setStatus(Account.State.OFFLINE);
661 if (statusListener != null) {
662 statusListener.onStatusChanged(account);
663 }
664 }
665 if (account.getStatus() == Account.State.ONLINE) {
666 synchronized (mLowPingTimeoutMode) {
667 long lastReceived = account.getXmppConnection().getLastPacketReceived();
668 long lastSent = account.getXmppConnection().getLastPingSent();
669 long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
670 long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
671 int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().toBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
672 long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
673 if (lastSent > lastReceived) {
674 if (pingTimeoutIn < 0) {
675 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
676 this.reconnectAccount(account, true, interactive);
677 } else {
678 int secs = (int) (pingTimeoutIn / 1000);
679 this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
680 }
681 } else {
682 pingCandidates.add(account);
683 if (isAccountPushed) {
684 pingNow = true;
685 if (mLowPingTimeoutMode.add(account.getJid().toBareJid())) {
686 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": entering low ping timeout mode");
687 }
688 } else if (msToNextPing <= 0) {
689 pingNow = true;
690 } else {
691 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
692 if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) {
693 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode");
694 }
695 }
696 }
697 }
698 } else if (account.getStatus() == Account.State.OFFLINE) {
699 reconnectAccount(account, true, interactive);
700 } else if (account.getStatus() == Account.State.CONNECTING) {
701 long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
702 long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
703 long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
704 long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
705 if (timeout < 0) {
706 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast="+secondsSinceLastConnect+")");
707 account.getXmppConnection().resetAttemptCount(false);
708 reconnectAccount(account, true, interactive);
709 } else if (discoTimeout < 0) {
710 account.getXmppConnection().sendDiscoTimeout();
711 scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
712 } else {
713 scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
714 }
715 } else {
716 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
717 reconnectAccount(account, true, interactive);
718 }
719 }
720 }
721 }
722 return pingNow;
723 }
724
725 public boolean isDataSaverDisabled() {
726 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
727 ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
728 return !connectivityManager.isActiveNetworkMetered()
729 || connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
730 } else {
731 return true;
732 }
733 }
734
735 private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) {
736 Message message = new Message(conversation,body,conversation.getNextEncryption());
737 message.markUnread();
738 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
739 getPgpEngine().encrypt(message, new UiCallback<Message>() {
740 @Override
741 public void success(Message message) {
742 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
743 sendMessage(message);
744 if (dismissAfterReply) {
745 markRead(message.getConversation(),true);
746 } else {
747 mNotificationService.pushFromDirectReply(message);
748 }
749 }
750
751 @Override
752 public void error(int errorCode, Message object) {
753
754 }
755
756 @Override
757 public void userInputRequried(PendingIntent pi, Message object) {
758
759 }
760 });
761 } else {
762 sendMessage(message);
763 if (dismissAfterReply) {
764 markRead(conversation,true);
765 } else {
766 mNotificationService.pushFromDirectReply(message);
767 }
768 }
769 }
770
771 private boolean xaOnSilentMode() {
772 return getPreferences().getBoolean("xa_on_silent_mode", false);
773 }
774
775 private boolean manuallyChangePresence() {
776 return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, false);
777 }
778
779 private boolean treatVibrateAsSilent() {
780 return getPreferences().getBoolean(SettingsActivity.TREAT_VIBRATE_AS_SILENT, false);
781 }
782
783 private boolean awayWhenScreenOff() {
784 return getPreferences().getBoolean(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, false);
785 }
786
787 private String getCompressPicturesPreference() {
788 return getPreferences().getString("picture_compression", "auto");
789 }
790
791 private Presence.Status getTargetPresence() {
792 if (xaOnSilentMode() && isPhoneSilenced()) {
793 return Presence.Status.XA;
794 } else if (awayWhenScreenOff() && !isInteractive()) {
795 return Presence.Status.AWAY;
796 } else {
797 return Presence.Status.ONLINE;
798 }
799 }
800
801 @SuppressLint("NewApi")
802 @SuppressWarnings("deprecation")
803 public boolean isInteractive() {
804 final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
805
806 final boolean isScreenOn;
807 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
808 isScreenOn = pm.isScreenOn();
809 } else {
810 isScreenOn = pm.isInteractive();
811 }
812 return isScreenOn;
813 }
814
815 private boolean isPhoneSilenced() {
816 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
817 try {
818 if (treatVibrateAsSilent()) {
819 return audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
820 } else {
821 return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
822 }
823 } catch (Throwable throwable) {
824 Log.d(Config.LOGTAG,"platform bug in isPhoneSilenced ("+ throwable.getMessage()+")");
825 return false;
826 }
827 }
828
829 private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
830 Log.d(Config.LOGTAG, "resetting all attempt counts");
831 for (Account account : accounts) {
832 if (account.hasErrorStatus() || reallyAll) {
833 final XmppConnection connection = account.getXmppConnection();
834 if (connection != null) {
835 connection.resetAttemptCount(retryImmediately);
836 }
837 }
838 if (account.setShowErrorNotification(true)) {
839 databaseBackend.updateAccount(account);
840 }
841 }
842 mNotificationService.updateErrorNotification();
843 }
844
845 private void dismissErrorNotifications() {
846 for (final Account account : this.accounts) {
847 if (account.hasErrorStatus()) {
848 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": dismissing error notification");
849 if (account.setShowErrorNotification(false)) {
850 databaseBackend.updateAccount(account);
851 }
852 }
853 }
854 }
855
856 public boolean hasInternetConnection() {
857 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
858 .getSystemService(Context.CONNECTIVITY_SERVICE);
859 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
860 return activeNetwork != null && activeNetwork.isConnected();
861 }
862
863 @SuppressLint("TrulyRandom")
864 @Override
865 public void onCreate() {
866 ExceptionHelper.init(getApplicationContext());
867 PRNGFixes.apply();
868 this.mRandom = new SecureRandom();
869 updateMemorizingTrustmanager();
870 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
871 final int cacheSize = maxMemory / 8;
872 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
873 @Override
874 protected int sizeOf(final String key, final Bitmap bitmap) {
875 return bitmap.getByteCount() / 1024;
876 }
877 };
878
879 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
880 this.accounts = databaseBackend.getAccounts();
881
882 if (Config.FREQUENT_RESTARTS_THRESHOLD != 0
883 && Config.FREQUENT_RESTARTS_DETECTION_WINDOW != 0
884 && !keepForegroundService()
885 && databaseBackend.startTimeCountExceedsThreshold()) {
886 getPreferences().edit().putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE,true).commit();
887 Log.d(Config.LOGTAG,"number of restarts exceeds threshold. enabling foreground service");
888 }
889
890 restoreFromDatabase();
891
892 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
893 new Thread(new Runnable() {
894 @Override
895 public void run() {
896 fileObserver.startWatching();
897 }
898 }).start();
899 if (Config.supportOpenPgp()) {
900 this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
901 @Override
902 public void onBound(IOpenPgpService2 service) {
903 for (Account account : accounts) {
904 final PgpDecryptionService pgp = account.getPgpDecryptionService();
905 if(pgp != null) {
906 pgp.continueDecryption(true);
907 }
908 }
909 }
910
911 @Override
912 public void onError(Exception e) {
913 }
914 });
915 this.pgpServiceConnection.bindToService();
916 }
917
918 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
919 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
920
921 toggleForegroundService();
922 updateUnreadCountBadge();
923 toggleScreenEventReceiver();
924 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
925 scheduleNextIdlePing();
926 }
927 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
928 registerReceiver(this.mEventReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
929 }
930 }
931
932 @Override
933 public void onTrimMemory(int level) {
934 super.onTrimMemory(level);
935 if (level >= TRIM_MEMORY_COMPLETE) {
936 Log.d(Config.LOGTAG, "clear cache due to low memory");
937 getBitmapCache().evictAll();
938 }
939 }
940
941 @Override
942 public void onDestroy() {
943 try {
944 unregisterReceiver(this.mEventReceiver);
945 } catch (IllegalArgumentException e) {
946 //ignored
947 }
948 fileObserver.stopWatching();
949 super.onDestroy();
950 }
951
952 public void toggleScreenEventReceiver() {
953 if (awayWhenScreenOff() && !manuallyChangePresence()) {
954 final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
955 filter.addAction(Intent.ACTION_SCREEN_OFF);
956 registerReceiver(this.mEventReceiver, filter);
957 } else {
958 try {
959 unregisterReceiver(this.mEventReceiver);
960 } catch (IllegalArgumentException e) {
961 //ignored
962 }
963 }
964 }
965
966 public void toggleForegroundService() {
967 if (keepForegroundService()) {
968 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
969 } else {
970 stopForeground(true);
971 }
972 }
973
974 private boolean keepForegroundService() {
975 return getPreferences().getBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE,false);
976 }
977
978 @Override
979 public void onTaskRemoved(final Intent rootIntent) {
980 super.onTaskRemoved(rootIntent);
981 if (!keepForegroundService()) {
982 this.logoutAndSave(false);
983 } else {
984 Log.d(Config.LOGTAG,"ignoring onTaskRemoved because foreground service is activated");
985 }
986 }
987
988 private void logoutAndSave(boolean stop) {
989 int activeAccounts = 0;
990 databaseBackend.clearStartTimeCounter(true); // regular swipes don't count towards restart counter
991 for (final Account account : accounts) {
992 if (account.getStatus() != Account.State.DISABLED) {
993 activeAccounts++;
994 }
995 databaseBackend.writeRoster(account.getRoster());
996 if (account.getXmppConnection() != null) {
997 new Thread(new Runnable() {
998 @Override
999 public void run() {
1000 disconnect(account, false);
1001 }
1002 }).start();
1003 }
1004 }
1005 if (stop || activeAccounts == 0) {
1006 Log.d(Config.LOGTAG, "good bye");
1007 stopSelf();
1008 }
1009 }
1010
1011 public void scheduleWakeUpCall(int seconds, int requestCode) {
1012 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1013 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1014 Intent intent = new Intent(this, EventReceiver.class);
1015 intent.setAction("ping");
1016 PendingIntent alarmIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1017 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
1018 }
1019
1020 @TargetApi(Build.VERSION_CODES.M)
1021 private void scheduleNextIdlePing() {
1022 Log.d(Config.LOGTAG,"schedule next idle ping");
1023 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1024 Intent intent = new Intent(this, EventReceiver.class);
1025 intent.setAction(ACTION_IDLE_PING);
1026 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1027 SystemClock.elapsedRealtime()+(Config.IDLE_PING_INTERVAL * 1000),
1028 PendingIntent.getBroadcast(this,0,intent,0)
1029 );
1030 }
1031
1032 public XmppConnection createConnection(final Account account) {
1033 final SharedPreferences sharedPref = getPreferences();
1034 String resource;
1035 try {
1036 resource = sharedPref.getString("resource", getString(R.string.default_resource)).toLowerCase(Locale.ENGLISH);
1037 if (resource.trim().isEmpty()) {
1038 throw new Exception();
1039 }
1040 } catch (Exception e) {
1041 resource = "conversations";
1042 }
1043 account.setResource(resource);
1044 final XmppConnection connection = new XmppConnection(account, this);
1045 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1046 connection.setOnStatusChangedListener(this.statusListener);
1047 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1048 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1049 connection.setOnJinglePacketReceivedListener(this.jingleListener);
1050 connection.setOnBindListener(this.mOnBindListener);
1051 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1052 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1053 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1054 AxolotlService axolotlService = account.getAxolotlService();
1055 if (axolotlService != null) {
1056 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1057 }
1058 return connection;
1059 }
1060
1061 public void sendChatState(Conversation conversation) {
1062 if (sendChatStates()) {
1063 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1064 sendMessagePacket(conversation.getAccount(), packet);
1065 }
1066 }
1067
1068 private void sendFileMessage(final Message message, final boolean delay) {
1069 Log.d(Config.LOGTAG, "send file message");
1070 final Account account = message.getConversation().getAccount();
1071 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())) {
1072 mHttpConnectionManager.createNewUploadConnection(message, delay);
1073 } else {
1074 mJingleConnectionManager.createNewConnection(message);
1075 }
1076 }
1077
1078 public void sendMessage(final Message message) {
1079 sendMessage(message, false, false);
1080 }
1081
1082 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1083 final Account account = message.getConversation().getAccount();
1084 if (account.setShowErrorNotification(true)) {
1085 databaseBackend.updateAccount(account);
1086 mNotificationService.updateErrorNotification();
1087 }
1088 final Conversation conversation = message.getConversation();
1089 account.deactivateGracePeriod();
1090 MessagePacket packet = null;
1091 final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1092 || account.getServerIdentity() != XmppConnection.Identity.SLACK)
1093 && !message.edited();
1094 boolean saveInDb = addToConversation;
1095 message.setStatus(Message.STATUS_WAITING);
1096
1097 if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
1098 message.getConversation().endOtrIfNeeded();
1099 message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
1100 new Conversation.OnMessageFound() {
1101 @Override
1102 public void onMessageFound(Message message) {
1103 markMessage(message, Message.STATUS_SEND_FAILED);
1104 }
1105 });
1106 }
1107
1108 if (account.isOnlineAndConnected()) {
1109 switch (message.getEncryption()) {
1110 case Message.ENCRYPTION_NONE:
1111 if (message.needsUploading()) {
1112 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1113 || message.fixCounterpart()) {
1114 this.sendFileMessage(message, delay);
1115 } else {
1116 break;
1117 }
1118 } else {
1119 packet = mMessageGenerator.generateChat(message);
1120 }
1121 break;
1122 case Message.ENCRYPTION_PGP:
1123 case Message.ENCRYPTION_DECRYPTED:
1124 if (message.needsUploading()) {
1125 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1126 || message.fixCounterpart()) {
1127 this.sendFileMessage(message, delay);
1128 } else {
1129 break;
1130 }
1131 } else {
1132 packet = mMessageGenerator.generatePgpChat(message);
1133 }
1134 break;
1135 case Message.ENCRYPTION_OTR:
1136 SessionImpl otrSession = conversation.getOtrSession();
1137 if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
1138 try {
1139 message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
1140 } catch (InvalidJidException e) {
1141 break;
1142 }
1143 if (message.needsUploading()) {
1144 mJingleConnectionManager.createNewConnection(message);
1145 } else {
1146 packet = mMessageGenerator.generateOtrChat(message);
1147 }
1148 } else if (otrSession == null) {
1149 if (message.fixCounterpart()) {
1150 conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
1151 } else {
1152 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fix counterpart for OTR message to contact "+message.getContact().getJid());
1153 break;
1154 }
1155 } else {
1156 Log.d(Config.LOGTAG,account.getJid().toBareJid()+" OTR session with "+message.getContact()+" is in wrong state: "+otrSession.getSessionStatus().toString());
1157 }
1158 break;
1159 case Message.ENCRYPTION_AXOLOTL:
1160 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1161 if (message.needsUploading()) {
1162 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1163 || message.fixCounterpart()) {
1164 this.sendFileMessage(message, delay);
1165 } else {
1166 break;
1167 }
1168 } else {
1169 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1170 if (axolotlMessage == null) {
1171 account.getAxolotlService().preparePayloadMessage(message, delay);
1172 } else {
1173 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1174 }
1175 }
1176 break;
1177
1178 }
1179 if (packet != null) {
1180 if (account.getXmppConnection().getFeatures().sm()
1181 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1182 message.setStatus(Message.STATUS_UNSEND);
1183 } else {
1184 message.setStatus(Message.STATUS_SEND);
1185 }
1186 }
1187 } else {
1188 switch (message.getEncryption()) {
1189 case Message.ENCRYPTION_DECRYPTED:
1190 if (!message.needsUploading()) {
1191 String pgpBody = message.getEncryptedBody();
1192 String decryptedBody = message.getBody();
1193 message.setBody(pgpBody);
1194 message.setEncryption(Message.ENCRYPTION_PGP);
1195 if (message.edited()) {
1196 message.setBody(decryptedBody);
1197 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1198 databaseBackend.updateMessage(message, message.getEditedId());
1199 updateConversationUi();
1200 return;
1201 } else {
1202 databaseBackend.createMessage(message);
1203 saveInDb = false;
1204 message.setBody(decryptedBody);
1205 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1206 }
1207 }
1208 break;
1209 case Message.ENCRYPTION_OTR:
1210 if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
1211 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": create otr session without starting for "+message.getContact().getJid());
1212 conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
1213 }
1214 break;
1215 case Message.ENCRYPTION_AXOLOTL:
1216 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1217 break;
1218 }
1219 }
1220
1221 if (resend) {
1222 if (packet != null && addToConversation) {
1223 if (account.getXmppConnection().getFeatures().sm()
1224 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1225 markMessage(message, Message.STATUS_UNSEND);
1226 } else {
1227 markMessage(message, Message.STATUS_SEND);
1228 }
1229 }
1230 } else {
1231 if (addToConversation) {
1232 conversation.add(message);
1233 }
1234 if (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages()) {
1235 if (saveInDb) {
1236 databaseBackend.createMessage(message);
1237 } else if (message.edited()) {
1238 databaseBackend.updateMessage(message, message.getEditedId());
1239 }
1240 }
1241 updateConversationUi();
1242 }
1243 if (packet != null) {
1244 if (delay) {
1245 mMessageGenerator.addDelay(packet, message.getTimeSent());
1246 }
1247 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1248 if (this.sendChatStates()) {
1249 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1250 }
1251 }
1252 sendMessagePacket(account, packet);
1253 }
1254 }
1255
1256 private void sendUnsentMessages(final Conversation conversation) {
1257 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
1258
1259 @Override
1260 public void onMessageFound(Message message) {
1261 resendMessage(message, true);
1262 }
1263 });
1264 }
1265
1266 public void resendMessage(final Message message, final boolean delay) {
1267 sendMessage(message, true, delay);
1268 }
1269
1270 public void fetchRosterFromServer(final Account account) {
1271 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1272 if (!"".equals(account.getRosterVersion())) {
1273 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1274 + ": fetching roster version " + account.getRosterVersion());
1275 } else {
1276 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1277 }
1278 iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
1279 sendIqPacket(account, iqPacket, mIqParser);
1280 }
1281
1282 public void fetchBookmarks(final Account account) {
1283 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1284 final Element query = iqPacket.query("jabber:iq:private");
1285 query.addChild("storage", "storage:bookmarks");
1286 final OnIqPacketReceived callback = new OnIqPacketReceived() {
1287
1288 @Override
1289 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1290 if (packet.getType() == IqPacket.TYPE.RESULT) {
1291 final Element query = packet.query();
1292 final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1293 final Element storage = query.findChild("storage", "storage:bookmarks");
1294 final boolean autojoin = respectAutojoin();
1295 if (storage != null) {
1296 for (final Element item : storage.getChildren()) {
1297 if (item.getName().equals("conference")) {
1298 final Bookmark bookmark = Bookmark.parse(item, account);
1299 Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1300 if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1301 bookmark.setBookmarkName(old.getBookmarkName());
1302 }
1303 Conversation conversation = find(bookmark);
1304 if (conversation != null) {
1305 conversation.setBookmark(bookmark);
1306 } else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1307 conversation = findOrCreateConversation(
1308 account, bookmark.getJid(), true);
1309 conversation.setBookmark(bookmark);
1310 joinMuc(conversation);
1311 }
1312 }
1313 }
1314 }
1315 account.setBookmarks(new ArrayList<>(bookmarks.values()));
1316 } else {
1317 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1318 }
1319 }
1320 };
1321 sendIqPacket(account, iqPacket, callback);
1322 }
1323
1324 public void pushBookmarks(Account account) {
1325 Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1326 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1327 Element query = iqPacket.query("jabber:iq:private");
1328 Element storage = query.addChild("storage", "storage:bookmarks");
1329 for (Bookmark bookmark : account.getBookmarks()) {
1330 storage.addChild(bookmark);
1331 }
1332 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1333 }
1334
1335 private void restoreFromDatabase() {
1336 synchronized (this.conversations) {
1337 final Map<String, Account> accountLookupTable = new Hashtable<>();
1338 for (Account account : this.accounts) {
1339 accountLookupTable.put(account.getUuid(), account);
1340 }
1341 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1342 for (Conversation conversation : this.conversations) {
1343 Account account = accountLookupTable.get(conversation.getAccountUuid());
1344 conversation.setAccount(account);
1345 }
1346 Runnable runnable = new Runnable() {
1347 @Override
1348 public void run() {
1349 Log.d(Config.LOGTAG, "restoring roster");
1350 for (Account account : accounts) {
1351 databaseBackend.readRoster(account.getRoster());
1352 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1353 }
1354 getBitmapCache().evictAll();
1355 loadPhoneContacts();
1356 Log.d(Config.LOGTAG, "restoring messages");
1357 for (Conversation conversation : conversations) {
1358 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1359 checkDeletedFiles(conversation);
1360 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
1361
1362 @Override
1363 public void onMessageFound(Message message) {
1364 markMessage(message, Message.STATUS_WAITING);
1365 }
1366 });
1367 conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1368 @Override
1369 public void onMessageFound(Message message) {
1370 mNotificationService.pushFromBacklog(message);
1371 }
1372 });
1373 }
1374 mNotificationService.finishBacklog(false);
1375 mRestoredFromDatabase = true;
1376 Log.d(Config.LOGTAG, "restored all messages");
1377 updateConversationUi();
1378 }
1379 };
1380 mDatabaseExecutor.execute(runnable);
1381 }
1382 }
1383
1384 public void loadPhoneContacts() {
1385 mContactMergerExecutor.execute(new Runnable() {
1386 @Override
1387 public void run() {
1388 PhoneHelper.loadPhoneContacts(XmppConnectionService.this, new OnPhoneContactsLoadedListener() {
1389 @Override
1390 public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
1391 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1392 for (Account account : accounts) {
1393 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1394 for (Bundle phoneContact : phoneContacts) {
1395 Jid jid;
1396 try {
1397 jid = Jid.fromString(phoneContact.getString("jid"));
1398 } catch (final InvalidJidException e) {
1399 continue;
1400 }
1401 final Contact contact = account.getRoster().getContact(jid);
1402 String systemAccount = phoneContact.getInt("phoneid")
1403 + "#"
1404 + phoneContact.getString("lookup");
1405 contact.setSystemAccount(systemAccount);
1406 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1407 getAvatarService().clear(contact);
1408 }
1409 contact.setSystemName(phoneContact.getString("displayname"));
1410 withSystemAccounts.remove(contact);
1411 }
1412 for (Contact contact : withSystemAccounts) {
1413 contact.setSystemAccount(null);
1414 contact.setSystemName(null);
1415 if (contact.setPhotoUri(null)) {
1416 getAvatarService().clear(contact);
1417 }
1418 }
1419 }
1420 Log.d(Config.LOGTAG, "finished merging phone contacts");
1421 updateAccountUi();
1422 }
1423 });
1424 }
1425 });
1426 }
1427
1428 public List<Conversation> getConversations() {
1429 return this.conversations;
1430 }
1431
1432 private void checkDeletedFiles(Conversation conversation) {
1433 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1434
1435 @Override
1436 public void onMessageFound(Message message) {
1437 if (!getFileBackend().isFileAvailable(message)) {
1438 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1439 final int s = message.getStatus();
1440 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1441 markMessage(message, Message.STATUS_SEND_FAILED);
1442 }
1443 }
1444 }
1445 });
1446 }
1447
1448 private void markFileDeleted(final String path) {
1449 Log.d(Config.LOGTAG,"deleted file "+path);
1450 for (Conversation conversation : getConversations()) {
1451 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1452 @Override
1453 public void onMessageFound(Message message) {
1454 DownloadableFile file = fileBackend.getFile(message);
1455 if (file.getAbsolutePath().equals(path)) {
1456 if (!file.exists()) {
1457 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1458 final int s = message.getStatus();
1459 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1460 markMessage(message, Message.STATUS_SEND_FAILED);
1461 } else {
1462 updateConversationUi();
1463 }
1464 } else {
1465 Log.d(Config.LOGTAG,"found matching message for file "+path+" but file still exists");
1466 }
1467 }
1468 }
1469 });
1470 }
1471 }
1472
1473 public void populateWithOrderedConversations(final List<Conversation> list) {
1474 populateWithOrderedConversations(list, true);
1475 }
1476
1477 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1478 list.clear();
1479 if (includeNoFileUpload) {
1480 list.addAll(getConversations());
1481 } else {
1482 for (Conversation conversation : getConversations()) {
1483 if (conversation.getMode() == Conversation.MODE_SINGLE
1484 || conversation.getAccount().httpUploadAvailable()) {
1485 list.add(conversation);
1486 }
1487 }
1488 }
1489 try {
1490 Collections.sort(list);
1491 } catch (IllegalArgumentException e) {
1492 //ignore
1493 }
1494 }
1495
1496 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1497 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1498 return;
1499 } else if (timestamp == 0) {
1500 return;
1501 }
1502 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1503 Runnable runnable = new Runnable() {
1504 @Override
1505 public void run() {
1506 final Account account = conversation.getAccount();
1507 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1508 if (messages.size() > 0) {
1509 conversation.addAll(0, messages);
1510 checkDeletedFiles(conversation);
1511 callback.onMoreMessagesLoaded(messages.size(), conversation);
1512 } else if (conversation.hasMessagesLeftOnServer()
1513 && account.isOnlineAndConnected()
1514 && conversation.getLastClearHistory() == 0) {
1515 if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1516 || (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1517 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1518 if (query != null) {
1519 query.setCallback(callback);
1520 }
1521 callback.informUser(R.string.fetching_history_from_server);
1522 }
1523 }
1524 }
1525 };
1526 mDatabaseExecutor.execute(runnable);
1527 }
1528
1529 public List<Account> getAccounts() {
1530 return this.accounts;
1531 }
1532
1533 public List<Conversation> findAllConferencesWith(Contact contact) {
1534 ArrayList<Conversation> results = new ArrayList<>();
1535 for(Conversation conversation : conversations) {
1536 if (conversation.getMode() == Conversation.MODE_MULTI
1537 && conversation.getMucOptions().isContactInRoom(contact)) {
1538 results.add(conversation);
1539 }
1540 }
1541 return results;
1542 }
1543
1544 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1545 for (final Conversation conversation : haystack) {
1546 if (conversation.getContact() == contact) {
1547 return conversation;
1548 }
1549 }
1550 return null;
1551 }
1552
1553 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1554 if (jid == null) {
1555 return null;
1556 }
1557 for (final Conversation conversation : haystack) {
1558 if ((account == null || conversation.getAccount() == account)
1559 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1560 return conversation;
1561 }
1562 }
1563 return null;
1564 }
1565
1566 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1567 return this.findOrCreateConversation(account, jid, muc, null);
1568 }
1569
1570 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1571 synchronized (this.conversations) {
1572 Conversation conversation = find(account, jid);
1573 if (conversation != null) {
1574 return conversation;
1575 }
1576 conversation = databaseBackend.findConversation(account, jid);
1577 if (conversation != null) {
1578 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1579 conversation.setAccount(account);
1580 if (muc) {
1581 conversation.setMode(Conversation.MODE_MULTI);
1582 conversation.setContactJid(jid);
1583 } else {
1584 conversation.setMode(Conversation.MODE_SINGLE);
1585 conversation.setContactJid(jid.toBareJid());
1586 }
1587 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1588 this.databaseBackend.updateConversation(conversation);
1589 } else {
1590 String conversationName;
1591 Contact contact = account.getRoster().getContact(jid);
1592 if (contact != null) {
1593 conversationName = contact.getDisplayName();
1594 } else {
1595 conversationName = jid.getLocalpart();
1596 }
1597 if (muc) {
1598 conversation = new Conversation(conversationName, account, jid,
1599 Conversation.MODE_MULTI);
1600 } else {
1601 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1602 Conversation.MODE_SINGLE);
1603 }
1604 this.databaseBackend.createConversation(conversation);
1605 }
1606 if (account.getXmppConnection() != null
1607 && account.getXmppConnection().getFeatures().mam()
1608 && !muc) {
1609 if (query == null) {
1610 this.mMessageArchiveService.query(conversation);
1611 } else {
1612 if (query.getConversation() == null) {
1613 this.mMessageArchiveService.query(conversation, query.getStart());
1614 }
1615 }
1616 }
1617 checkDeletedFiles(conversation);
1618 this.conversations.add(conversation);
1619 updateConversationUi();
1620 return conversation;
1621 }
1622 }
1623
1624 public void archiveConversation(Conversation conversation) {
1625 getNotificationService().clear(conversation);
1626 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1627 synchronized (this.conversations) {
1628 if (conversation.getMode() == Conversation.MODE_MULTI) {
1629 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1630 Bookmark bookmark = conversation.getBookmark();
1631 if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1632 bookmark.setAutojoin(false);
1633 pushBookmarks(bookmark.getAccount());
1634 }
1635 }
1636 leaveMuc(conversation);
1637 } else {
1638 conversation.endOtrIfNeeded();
1639 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1640 Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1641 sendPresencePacket(
1642 conversation.getAccount(),
1643 mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1644 );
1645 }
1646 }
1647 updateConversation(conversation);
1648 this.conversations.remove(conversation);
1649 updateConversationUi();
1650 }
1651 }
1652
1653 public void createAccount(final Account account) {
1654 account.initAccountServices(this);
1655 databaseBackend.createAccount(account);
1656 this.accounts.add(account);
1657 this.reconnectAccountInBackground(account);
1658 updateAccountUi();
1659 }
1660
1661 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1662 new Thread(new Runnable() {
1663 @Override
1664 public void run() {
1665 try {
1666 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1667 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1668 if (findAccountByJid(info.first) == null) {
1669 Account account = new Account(info.first, "");
1670 account.setPrivateKeyAlias(alias);
1671 account.setOption(Account.OPTION_DISABLED, true);
1672 account.setDisplayName(info.second);
1673 createAccount(account);
1674 callback.onAccountCreated(account);
1675 if (Config.X509_VERIFICATION) {
1676 try {
1677 getMemorizingTrustManager().getNonInteractive(account.getJid().getDomainpart()).checkClientTrusted(chain, "RSA");
1678 } catch (CertificateException e) {
1679 callback.informUser(R.string.certificate_chain_is_not_trusted);
1680 }
1681 }
1682 } else {
1683 callback.informUser(R.string.account_already_exists);
1684 }
1685 } catch (Exception e) {
1686 e.printStackTrace();
1687 callback.informUser(R.string.unable_to_parse_certificate);
1688 }
1689 }
1690 }).start();
1691
1692 }
1693
1694 public void updateKeyInAccount(final Account account, final String alias) {
1695 Log.d(Config.LOGTAG, "update key in account " + alias);
1696 try {
1697 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1698 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1699 if (account.getJid().toBareJid().equals(info.first)) {
1700 account.setPrivateKeyAlias(alias);
1701 account.setDisplayName(info.second);
1702 databaseBackend.updateAccount(account);
1703 if (Config.X509_VERIFICATION) {
1704 try {
1705 getMemorizingTrustManager().getNonInteractive(account.getJid().getDomainpart()).checkClientTrusted(chain, "RSA");
1706 } catch (CertificateException e) {
1707 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1708 }
1709 account.getAxolotlService().regenerateKeys(true);
1710 }
1711 } else {
1712 showErrorToastInUi(R.string.jid_does_not_match_certificate);
1713 }
1714 } catch (Exception e) {
1715 e.printStackTrace();
1716 }
1717 }
1718
1719 public boolean updateAccount(final Account account) {
1720 if (databaseBackend.updateAccount(account)) {
1721 account.setShowErrorNotification(true);
1722 this.statusListener.onStatusChanged(account);
1723 databaseBackend.updateAccount(account);
1724 reconnectAccountInBackground(account);
1725 updateAccountUi();
1726 getNotificationService().updateErrorNotification();
1727 return true;
1728 } else {
1729 return false;
1730 }
1731 }
1732
1733 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1734 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1735 sendIqPacket(account, iq, new OnIqPacketReceived() {
1736 @Override
1737 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1738 if (packet.getType() == IqPacket.TYPE.RESULT) {
1739 account.setPassword(newPassword);
1740 account.setOption(Account.OPTION_MAGIC_CREATE, false);
1741 databaseBackend.updateAccount(account);
1742 callback.onPasswordChangeSucceeded();
1743 } else {
1744 callback.onPasswordChangeFailed();
1745 }
1746 }
1747 });
1748 }
1749
1750 public void deleteAccount(final Account account) {
1751 synchronized (this.conversations) {
1752 for (final Conversation conversation : conversations) {
1753 if (conversation.getAccount() == account) {
1754 if (conversation.getMode() == Conversation.MODE_MULTI) {
1755 leaveMuc(conversation);
1756 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1757 conversation.endOtrIfNeeded();
1758 }
1759 conversations.remove(conversation);
1760 }
1761 }
1762 if (account.getXmppConnection() != null) {
1763 new Thread(new Runnable() {
1764 @Override
1765 public void run() {
1766 disconnect(account, true);
1767 }
1768 }).start();
1769 }
1770 Runnable runnable = new Runnable() {
1771 @Override
1772 public void run() {
1773 if (!databaseBackend.deleteAccount(account)) {
1774 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": unable to delete account");
1775 }
1776 }
1777 };
1778 mDatabaseExecutor.execute(runnable);
1779 this.accounts.remove(account);
1780 updateAccountUi();
1781 getNotificationService().updateErrorNotification();
1782 }
1783 }
1784
1785 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1786 synchronized (this) {
1787 this.mLastActivity = System.currentTimeMillis();
1788 if (checkListeners()) {
1789 switchToForeground();
1790 }
1791 this.mOnConversationUpdate = listener;
1792 this.mNotificationService.setIsInForeground(true);
1793 if (this.convChangedListenerCount < 2) {
1794 this.convChangedListenerCount++;
1795 }
1796 }
1797 }
1798
1799 public void removeOnConversationListChangedListener() {
1800 synchronized (this) {
1801 this.convChangedListenerCount--;
1802 if (this.convChangedListenerCount <= 0) {
1803 this.convChangedListenerCount = 0;
1804 this.mOnConversationUpdate = null;
1805 this.mNotificationService.setIsInForeground(false);
1806 if (checkListeners()) {
1807 switchToBackground();
1808 }
1809 }
1810 }
1811 }
1812
1813 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1814 synchronized (this) {
1815 if (checkListeners()) {
1816 switchToForeground();
1817 }
1818 this.mOnShowErrorToast = onShowErrorToast;
1819 if (this.showErrorToastListenerCount < 2) {
1820 this.showErrorToastListenerCount++;
1821 }
1822 }
1823 this.mOnShowErrorToast = onShowErrorToast;
1824 }
1825
1826 public void removeOnShowErrorToastListener() {
1827 synchronized (this) {
1828 this.showErrorToastListenerCount--;
1829 if (this.showErrorToastListenerCount <= 0) {
1830 this.showErrorToastListenerCount = 0;
1831 this.mOnShowErrorToast = null;
1832 if (checkListeners()) {
1833 switchToBackground();
1834 }
1835 }
1836 }
1837 }
1838
1839 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1840 synchronized (this) {
1841 if (checkListeners()) {
1842 switchToForeground();
1843 }
1844 this.mOnAccountUpdate = listener;
1845 if (this.accountChangedListenerCount < 2) {
1846 this.accountChangedListenerCount++;
1847 }
1848 }
1849 }
1850
1851 public void removeOnAccountListChangedListener() {
1852 synchronized (this) {
1853 this.accountChangedListenerCount--;
1854 if (this.accountChangedListenerCount <= 0) {
1855 this.mOnAccountUpdate = null;
1856 this.accountChangedListenerCount = 0;
1857 if (checkListeners()) {
1858 switchToBackground();
1859 }
1860 }
1861 }
1862 }
1863
1864 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1865 synchronized (this) {
1866 if (checkListeners()) {
1867 switchToForeground();
1868 }
1869 this.mOnCaptchaRequested = listener;
1870 if (this.captchaRequestedListenerCount < 2) {
1871 this.captchaRequestedListenerCount++;
1872 }
1873 }
1874 }
1875
1876 public void removeOnCaptchaRequestedListener() {
1877 synchronized (this) {
1878 this.captchaRequestedListenerCount--;
1879 if (this.captchaRequestedListenerCount <= 0) {
1880 this.mOnCaptchaRequested = null;
1881 this.captchaRequestedListenerCount = 0;
1882 if (checkListeners()) {
1883 switchToBackground();
1884 }
1885 }
1886 }
1887 }
1888
1889 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1890 synchronized (this) {
1891 if (checkListeners()) {
1892 switchToForeground();
1893 }
1894 this.mOnRosterUpdate = listener;
1895 if (this.rosterChangedListenerCount < 2) {
1896 this.rosterChangedListenerCount++;
1897 }
1898 }
1899 }
1900
1901 public void removeOnRosterUpdateListener() {
1902 synchronized (this) {
1903 this.rosterChangedListenerCount--;
1904 if (this.rosterChangedListenerCount <= 0) {
1905 this.rosterChangedListenerCount = 0;
1906 this.mOnRosterUpdate = null;
1907 if (checkListeners()) {
1908 switchToBackground();
1909 }
1910 }
1911 }
1912 }
1913
1914 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1915 synchronized (this) {
1916 if (checkListeners()) {
1917 switchToForeground();
1918 }
1919 this.mOnUpdateBlocklist = listener;
1920 if (this.updateBlocklistListenerCount < 2) {
1921 this.updateBlocklistListenerCount++;
1922 }
1923 }
1924 }
1925
1926 public void removeOnUpdateBlocklistListener() {
1927 synchronized (this) {
1928 this.updateBlocklistListenerCount--;
1929 if (this.updateBlocklistListenerCount <= 0) {
1930 this.updateBlocklistListenerCount = 0;
1931 this.mOnUpdateBlocklist = null;
1932 if (checkListeners()) {
1933 switchToBackground();
1934 }
1935 }
1936 }
1937 }
1938
1939 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1940 synchronized (this) {
1941 if (checkListeners()) {
1942 switchToForeground();
1943 }
1944 this.mOnKeyStatusUpdated = listener;
1945 if (this.keyStatusUpdatedListenerCount < 2) {
1946 this.keyStatusUpdatedListenerCount++;
1947 }
1948 }
1949 }
1950
1951 public void removeOnNewKeysAvailableListener() {
1952 synchronized (this) {
1953 this.keyStatusUpdatedListenerCount--;
1954 if (this.keyStatusUpdatedListenerCount <= 0) {
1955 this.keyStatusUpdatedListenerCount = 0;
1956 this.mOnKeyStatusUpdated = null;
1957 if (checkListeners()) {
1958 switchToBackground();
1959 }
1960 }
1961 }
1962 }
1963
1964 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1965 synchronized (this) {
1966 if (checkListeners()) {
1967 switchToForeground();
1968 }
1969 this.mOnMucRosterUpdate = listener;
1970 if (this.mucRosterChangedListenerCount < 2) {
1971 this.mucRosterChangedListenerCount++;
1972 }
1973 }
1974 }
1975
1976 public void removeOnMucRosterUpdateListener() {
1977 synchronized (this) {
1978 this.mucRosterChangedListenerCount--;
1979 if (this.mucRosterChangedListenerCount <= 0) {
1980 this.mucRosterChangedListenerCount = 0;
1981 this.mOnMucRosterUpdate = null;
1982 if (checkListeners()) {
1983 switchToBackground();
1984 }
1985 }
1986 }
1987 }
1988
1989 public boolean checkListeners() {
1990 return (this.mOnAccountUpdate == null
1991 && this.mOnConversationUpdate == null
1992 && this.mOnRosterUpdate == null
1993 && this.mOnCaptchaRequested == null
1994 && this.mOnUpdateBlocklist == null
1995 && this.mOnShowErrorToast == null
1996 && this.mOnKeyStatusUpdated == null);
1997 }
1998
1999 private void switchToForeground() {
2000 final boolean broadcastLastActivity = broadcastLastActivity();
2001 for (Conversation conversation : getConversations()) {
2002 conversation.setIncomingChatState(ChatState.ACTIVE);
2003 }
2004 for (Account account : getAccounts()) {
2005 if (account.getStatus() == Account.State.ONLINE) {
2006 account.deactivateGracePeriod();
2007 final XmppConnection connection = account.getXmppConnection();
2008 if (connection != null ) {
2009 if (connection.getFeatures().csi()) {
2010 connection.sendActive();
2011 }
2012 if (broadcastLastActivity) {
2013 sendPresence(account, false); //send new presence but don't include idle because we are not
2014 }
2015 }
2016 }
2017 }
2018 Log.d(Config.LOGTAG, "app switched into foreground");
2019 }
2020
2021 private void switchToBackground() {
2022 final boolean broadcastLastActivity = broadcastLastActivity();
2023 for (Account account : getAccounts()) {
2024 if (account.getStatus() == Account.State.ONLINE) {
2025 XmppConnection connection = account.getXmppConnection();
2026 if (connection != null) {
2027 if (broadcastLastActivity) {
2028 sendPresence(account, broadcastLastActivity);
2029 }
2030 if (connection.getFeatures().csi()) {
2031 connection.sendInactive();
2032 }
2033 }
2034 }
2035 }
2036 this.mNotificationService.setIsInForeground(false);
2037 Log.d(Config.LOGTAG, "app switched into background");
2038 }
2039
2040 private void connectMultiModeConversations(Account account) {
2041 List<Conversation> conversations = getConversations();
2042 for (Conversation conversation : conversations) {
2043 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2044 joinMuc(conversation);
2045 }
2046 }
2047 }
2048
2049 public void joinMuc(Conversation conversation) {
2050 joinMuc(conversation,null, false);
2051 }
2052
2053 public void joinMuc(Conversation conversation, boolean followedInvite) {
2054 joinMuc(conversation, null, followedInvite);
2055 }
2056
2057 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2058 joinMuc(conversation,onConferenceJoined,false);
2059 }
2060
2061 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2062 Account account = conversation.getAccount();
2063 account.pendingConferenceJoins.remove(conversation);
2064 account.pendingConferenceLeaves.remove(conversation);
2065 if (account.getStatus() == Account.State.ONLINE) {
2066 conversation.resetMucOptions();
2067 if (onConferenceJoined != null) {
2068 conversation.getMucOptions().flagNoAutoPushConfiguration();
2069 }
2070 conversation.setHasMessagesLeftOnServer(false);
2071 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2072
2073 private void join(Conversation conversation) {
2074 Account account = conversation.getAccount();
2075 final MucOptions mucOptions = conversation.getMucOptions();
2076 final Jid joinJid = mucOptions.getSelf().getFullJid();
2077 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
2078 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
2079 packet.setTo(joinJid);
2080 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2081 if (conversation.getMucOptions().getPassword() != null) {
2082 x.addChild("password").setContent(mucOptions.getPassword());
2083 }
2084
2085 if (mucOptions.mamSupport()) {
2086 // Use MAM instead of the limited muc history to get history
2087 x.addChild("history").setAttribute("maxchars", "0");
2088 } else {
2089 // Fallback to muc history
2090 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
2091 }
2092 sendPresencePacket(account, packet);
2093 if (onConferenceJoined != null) {
2094 onConferenceJoined.onConferenceJoined(conversation);
2095 }
2096 if (!joinJid.equals(conversation.getJid())) {
2097 conversation.setContactJid(joinJid);
2098 databaseBackend.updateConversation(conversation);
2099 }
2100
2101 if (mucOptions.mamSupport()) {
2102 getMessageArchiveService().catchupMUC(conversation);
2103 }
2104 if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
2105 fetchConferenceMembers(conversation);
2106 if (followedInvite && conversation.getBookmark() == null) {
2107 saveConversationAsBookmark(conversation,null);
2108 }
2109 }
2110 sendUnsentMessages(conversation);
2111 }
2112
2113 @Override
2114 public void onConferenceConfigurationFetched(Conversation conversation) {
2115 join(conversation);
2116 }
2117
2118 @Override
2119 public void onFetchFailed(final Conversation conversation, Element error) {
2120 if (error != null && "remote-server-not-found".equals(error.getName())) {
2121 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2122 } else {
2123 join(conversation);
2124 fetchConferenceConfiguration(conversation);
2125 }
2126 }
2127 });
2128 updateConversationUi();
2129 } else {
2130 account.pendingConferenceJoins.add(conversation);
2131 conversation.resetMucOptions();
2132 conversation.setHasMessagesLeftOnServer(false);
2133 updateConversationUi();
2134 }
2135 }
2136
2137 private void fetchConferenceMembers(final Conversation conversation) {
2138 final Account account = conversation.getAccount();
2139 final String[] affiliations = {"member","admin","owner"};
2140 OnIqPacketReceived callback = new OnIqPacketReceived() {
2141
2142 private int i = 0;
2143
2144 @Override
2145 public void onIqPacketReceived(Account account, IqPacket packet) {
2146
2147 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2148 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2149 for(Element child : query.getChildren()) {
2150 if ("item".equals(child.getName())) {
2151 MucOptions.User user = AbstractParser.parseItem(conversation,child);
2152 if (!user.realJidMatchesAccount()) {
2153 conversation.getMucOptions().updateUser(user);
2154 }
2155 }
2156 }
2157 } else {
2158 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
2159 }
2160 ++i;
2161 if (i >= affiliations.length) {
2162 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
2163 getAvatarService().clear(conversation);
2164 updateMucRosterUi();
2165 updateConversationUi();
2166 }
2167 }
2168 };
2169 for(String affiliation : affiliations) {
2170 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2171 }
2172 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
2173 }
2174
2175 public void providePasswordForMuc(Conversation conversation, String password) {
2176 if (conversation.getMode() == Conversation.MODE_MULTI) {
2177 conversation.getMucOptions().setPassword(password);
2178 if (conversation.getBookmark() != null) {
2179 if (respectAutojoin()) {
2180 conversation.getBookmark().setAutojoin(true);
2181 }
2182 pushBookmarks(conversation.getAccount());
2183 }
2184 updateConversation(conversation);
2185 joinMuc(conversation);
2186 }
2187 }
2188
2189 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2190 final MucOptions options = conversation.getMucOptions();
2191 final Jid joinJid = options.createJoinJid(nick);
2192 if (options.online()) {
2193 Account account = conversation.getAccount();
2194 options.setOnRenameListener(new OnRenameListener() {
2195
2196 @Override
2197 public void onSuccess() {
2198 conversation.setContactJid(joinJid);
2199 databaseBackend.updateConversation(conversation);
2200 Bookmark bookmark = conversation.getBookmark();
2201 if (bookmark != null) {
2202 bookmark.setNick(nick);
2203 pushBookmarks(bookmark.getAccount());
2204 }
2205 callback.success(conversation);
2206 }
2207
2208 @Override
2209 public void onFailure() {
2210 callback.error(R.string.nick_in_use, conversation);
2211 }
2212 });
2213
2214 PresencePacket packet = new PresencePacket();
2215 packet.setTo(joinJid);
2216 packet.setFrom(conversation.getAccount().getJid());
2217
2218 String sig = account.getPgpSignature();
2219 if (sig != null) {
2220 packet.addChild("status").setContent("online");
2221 packet.addChild("x", "jabber:x:signed").setContent(sig);
2222 }
2223 sendPresencePacket(account, packet);
2224 } else {
2225 conversation.setContactJid(joinJid);
2226 databaseBackend.updateConversation(conversation);
2227 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2228 Bookmark bookmark = conversation.getBookmark();
2229 if (bookmark != null) {
2230 bookmark.setNick(nick);
2231 pushBookmarks(bookmark.getAccount());
2232 }
2233 joinMuc(conversation);
2234 }
2235 }
2236 }
2237
2238 public void leaveMuc(Conversation conversation) {
2239 leaveMuc(conversation, false);
2240 }
2241
2242 private void leaveMuc(Conversation conversation, boolean now) {
2243 Account account = conversation.getAccount();
2244 account.pendingConferenceJoins.remove(conversation);
2245 account.pendingConferenceLeaves.remove(conversation);
2246 if (account.getStatus() == Account.State.ONLINE || now) {
2247 PresencePacket packet = new PresencePacket();
2248 packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2249 packet.setFrom(conversation.getAccount().getJid());
2250 packet.setAttribute("type", "unavailable");
2251 sendPresencePacket(conversation.getAccount(), packet);
2252 conversation.getMucOptions().setOffline();
2253 conversation.deregisterWithBookmark();
2254 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2255 + ": leaving muc " + conversation.getJid());
2256 } else {
2257 account.pendingConferenceLeaves.add(conversation);
2258 }
2259 }
2260
2261 private String findConferenceServer(final Account account) {
2262 String server;
2263 if (account.getXmppConnection() != null) {
2264 server = account.getXmppConnection().getMucServer();
2265 if (server != null) {
2266 return server;
2267 }
2268 }
2269 for (Account other : getAccounts()) {
2270 if (other != account && other.getXmppConnection() != null) {
2271 server = other.getXmppConnection().getMucServer();
2272 if (server != null) {
2273 return server;
2274 }
2275 }
2276 }
2277 return null;
2278 }
2279
2280 public void createAdhocConference(final Account account,
2281 final String subject,
2282 final Iterable<Jid> jids,
2283 final UiCallback<Conversation> callback) {
2284 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2285 if (account.getStatus() == Account.State.ONLINE) {
2286 try {
2287 String server = findConferenceServer(account);
2288 if (server == null) {
2289 if (callback != null) {
2290 callback.error(R.string.no_conference_server_found, null);
2291 }
2292 return;
2293 }
2294 final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2295 final Conversation conversation = findOrCreateConversation(account, jid, true);
2296 joinMuc(conversation, new OnConferenceJoined() {
2297 @Override
2298 public void onConferenceJoined(final Conversation conversation) {
2299 pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConferenceOptionsPushed() {
2300 @Override
2301 public void onPushSucceeded() {
2302 if (subject != null && !subject.trim().isEmpty()) {
2303 pushSubjectToConference(conversation, subject.trim());
2304 }
2305 for (Jid invite : jids) {
2306 invite(conversation, invite);
2307 }
2308 if (account.countPresences() > 1) {
2309 directInvite(conversation, account.getJid().toBareJid());
2310 }
2311 saveConversationAsBookmark(conversation, subject);
2312 if (callback != null) {
2313 callback.success(conversation);
2314 }
2315 }
2316
2317 @Override
2318 public void onPushFailed() {
2319 archiveConversation(conversation);
2320 if (callback != null) {
2321 callback.error(R.string.conference_creation_failed, conversation);
2322 }
2323 }
2324 });
2325 }
2326 });
2327 } catch (InvalidJidException e) {
2328 if (callback != null) {
2329 callback.error(R.string.conference_creation_failed, null);
2330 }
2331 }
2332 } else {
2333 if (callback != null) {
2334 callback.error(R.string.not_connected_try_again, null);
2335 }
2336 }
2337 }
2338
2339 public void fetchConferenceConfiguration(final Conversation conversation) {
2340 fetchConferenceConfiguration(conversation, null);
2341 }
2342
2343 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2344 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2345 request.setTo(conversation.getJid().toBareJid());
2346 request.query("http://jabber.org/protocol/disco#info");
2347 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2348 @Override
2349 public void onIqPacketReceived(Account account, IqPacket packet) {
2350 Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2351 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2352 ArrayList<String> features = new ArrayList<>();
2353 for (Element child : query.getChildren()) {
2354 if (child != null && child.getName().equals("feature")) {
2355 String var = child.getAttribute("var");
2356 if (var != null) {
2357 features.add(var);
2358 }
2359 }
2360 }
2361 Element form = query.findChild("x", "jabber:x:data");
2362 if (form != null) {
2363 conversation.getMucOptions().updateFormData(Data.parse(form));
2364 }
2365 conversation.getMucOptions().updateFeatures(features);
2366 if (callback != null) {
2367 callback.onConferenceConfigurationFetched(conversation);
2368 }
2369 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2370 updateConversationUi();
2371 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2372 if (callback != null) {
2373 callback.onFetchFailed(conversation, packet.getError());
2374 }
2375 }
2376 }
2377 });
2378 }
2379
2380 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2381 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2382 request.setTo(conversation.getJid().toBareJid());
2383 request.query("http://jabber.org/protocol/muc#owner");
2384 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2385 @Override
2386 public void onIqPacketReceived(Account account, IqPacket packet) {
2387 if (packet.getType() == IqPacket.TYPE.RESULT) {
2388 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2389 for (Field field : data.getFields()) {
2390 if (options.containsKey(field.getFieldName())) {
2391 field.setValue(options.getString(field.getFieldName()));
2392 }
2393 }
2394 data.submit();
2395 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2396 set.setTo(conversation.getJid().toBareJid());
2397 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2398 sendIqPacket(account, set, new OnIqPacketReceived() {
2399 @Override
2400 public void onIqPacketReceived(Account account, IqPacket packet) {
2401 if (callback != null) {
2402 if (packet.getType() == IqPacket.TYPE.RESULT) {
2403 callback.onPushSucceeded();
2404 } else {
2405 callback.onPushFailed();
2406 }
2407 }
2408 }
2409 });
2410 } else {
2411 if (callback != null) {
2412 callback.onPushFailed();
2413 }
2414 }
2415 }
2416 });
2417 }
2418
2419 public void pushSubjectToConference(final Conversation conference, final String subject) {
2420 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2421 this.sendMessagePacket(conference.getAccount(), packet);
2422 final MucOptions mucOptions = conference.getMucOptions();
2423 final MucOptions.User self = mucOptions.getSelf();
2424 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2425 Bundle options = new Bundle();
2426 options.putString("muc#roomconfig_persistentroom", "1");
2427 this.pushConferenceConfiguration(conference, options, null);
2428 }
2429 }
2430
2431 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2432 final Jid jid = user.toBareJid();
2433 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2434 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2435 @Override
2436 public void onIqPacketReceived(Account account, IqPacket packet) {
2437 if (packet.getType() == IqPacket.TYPE.RESULT) {
2438 conference.getMucOptions().changeAffiliation(jid, affiliation);
2439 getAvatarService().clear(conference);
2440 callback.onAffiliationChangedSuccessful(jid);
2441 } else {
2442 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2443 }
2444 }
2445 });
2446 }
2447
2448 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2449 List<Jid> jids = new ArrayList<>();
2450 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2451 if (user.getAffiliation() == before && user.getRealJid() != null) {
2452 jids.add(user.getRealJid());
2453 }
2454 }
2455 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2456 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2457 }
2458
2459 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2460 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2461 Log.d(Config.LOGTAG, request.toString());
2462 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2463 @Override
2464 public void onIqPacketReceived(Account account, IqPacket packet) {
2465 Log.d(Config.LOGTAG, packet.toString());
2466 if (packet.getType() == IqPacket.TYPE.RESULT) {
2467 callback.onRoleChangedSuccessful(nick);
2468 } else {
2469 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2470 }
2471 }
2472 });
2473 }
2474
2475 private void disconnect(Account account, boolean force) {
2476 if ((account.getStatus() == Account.State.ONLINE)
2477 || (account.getStatus() == Account.State.DISABLED)) {
2478 final XmppConnection connection = account.getXmppConnection();
2479 if (!force) {
2480 List<Conversation> conversations = getConversations();
2481 for (Conversation conversation : conversations) {
2482 if (conversation.getAccount() == account) {
2483 if (conversation.getMode() == Conversation.MODE_MULTI) {
2484 leaveMuc(conversation, true);
2485 } else {
2486 if (conversation.endOtrIfNeeded()) {
2487 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2488 + ": ended otr session with "
2489 + conversation.getJid());
2490 }
2491 }
2492 }
2493 }
2494 sendOfflinePresence(account);
2495 }
2496 connection.disconnect(force);
2497 }
2498 }
2499
2500 @Override
2501 public IBinder onBind(Intent intent) {
2502 return mBinder;
2503 }
2504
2505 public void updateMessage(Message message) {
2506 databaseBackend.updateMessage(message);
2507 updateConversationUi();
2508 }
2509
2510 public void updateMessage(Message message, String uuid) {
2511 databaseBackend.updateMessage(message, uuid);
2512 updateConversationUi();
2513 }
2514
2515 protected void syncDirtyContacts(Account account) {
2516 for (Contact contact : account.getRoster().getContacts()) {
2517 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2518 pushContactToServer(contact);
2519 }
2520 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2521 deleteContactOnServer(contact);
2522 }
2523 }
2524 }
2525
2526 public void createContact(Contact contact) {
2527 boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2528 if (autoGrant) {
2529 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2530 contact.setOption(Contact.Options.ASKING);
2531 }
2532 pushContactToServer(contact);
2533 }
2534
2535 public void onOtrSessionEstablished(Conversation conversation) {
2536 final Account account = conversation.getAccount();
2537 final Session otrSession = conversation.getOtrSession();
2538 Log.d(Config.LOGTAG,
2539 account.getJid().toBareJid() + " otr session established with "
2540 + conversation.getJid() + "/"
2541 + otrSession.getSessionID().getUserID());
2542 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2543
2544 @Override
2545 public void onMessageFound(Message message) {
2546 SessionID id = otrSession.getSessionID();
2547 try {
2548 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2549 } catch (InvalidJidException e) {
2550 return;
2551 }
2552 if (message.needsUploading()) {
2553 mJingleConnectionManager.createNewConnection(message);
2554 } else {
2555 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2556 if (outPacket != null) {
2557 mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2558 message.setStatus(Message.STATUS_SEND);
2559 databaseBackend.updateMessage(message);
2560 sendMessagePacket(account, outPacket);
2561 }
2562 }
2563 updateConversationUi();
2564 }
2565 });
2566 }
2567
2568 public boolean renewSymmetricKey(Conversation conversation) {
2569 Account account = conversation.getAccount();
2570 byte[] symmetricKey = new byte[32];
2571 this.mRandom.nextBytes(symmetricKey);
2572 Session otrSession = conversation.getOtrSession();
2573 if (otrSession != null) {
2574 MessagePacket packet = new MessagePacket();
2575 packet.setType(MessagePacket.TYPE_CHAT);
2576 packet.setFrom(account.getJid());
2577 MessageGenerator.addMessageHints(packet);
2578 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2579 + otrSession.getSessionID().getUserID());
2580 try {
2581 packet.setBody(otrSession
2582 .transformSending(CryptoHelper.FILETRANSFER
2583 + CryptoHelper.bytesToHex(symmetricKey))[0]);
2584 sendMessagePacket(account, packet);
2585 conversation.setSymmetricKey(symmetricKey);
2586 return true;
2587 } catch (OtrException e) {
2588 return false;
2589 }
2590 }
2591 return false;
2592 }
2593
2594 public void pushContactToServer(final Contact contact) {
2595 contact.resetOption(Contact.Options.DIRTY_DELETE);
2596 contact.setOption(Contact.Options.DIRTY_PUSH);
2597 final Account account = contact.getAccount();
2598 if (account.getStatus() == Account.State.ONLINE) {
2599 final boolean ask = contact.getOption(Contact.Options.ASKING);
2600 final boolean sendUpdates = contact
2601 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2602 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2603 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2604 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2605 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2606 if (sendUpdates) {
2607 sendPresencePacket(account,
2608 mPresenceGenerator.sendPresenceUpdatesTo(contact));
2609 }
2610 if (ask) {
2611 sendPresencePacket(account,
2612 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2613 }
2614 }
2615 }
2616
2617 public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2618 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2619 final int size = Config.AVATAR_SIZE;
2620 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2621 if (avatar != null) {
2622 avatar.height = size;
2623 avatar.width = size;
2624 if (format.equals(Bitmap.CompressFormat.WEBP)) {
2625 avatar.type = "image/webp";
2626 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2627 avatar.type = "image/jpeg";
2628 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
2629 avatar.type = "image/png";
2630 }
2631 if (!getFileBackend().save(avatar)) {
2632 callback.error(R.string.error_saving_avatar, avatar);
2633 return;
2634 }
2635 publishAvatar(account, avatar, callback);
2636 } else {
2637 callback.error(R.string.error_publish_avatar_converting, null);
2638 }
2639 }
2640
2641 public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2642 IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2643 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2644
2645 @Override
2646 public void onIqPacketReceived(Account account, IqPacket result) {
2647 if (result.getType() == IqPacket.TYPE.RESULT) {
2648 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2649 sendIqPacket(account, packet, new OnIqPacketReceived() {
2650 @Override
2651 public void onIqPacketReceived(Account account, IqPacket result) {
2652 if (result.getType() == IqPacket.TYPE.RESULT) {
2653 if (account.setAvatar(avatar.getFilename())) {
2654 getAvatarService().clear(account);
2655 databaseBackend.updateAccount(account);
2656 }
2657 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar "+(avatar.size/1024)+"KiB");
2658 if (callback != null) {
2659 callback.success(avatar);
2660 }
2661 } else {
2662 if (callback != null) {
2663 callback.error(R.string.error_publish_avatar_server_reject,avatar);
2664 }
2665 }
2666 }
2667 });
2668 } else {
2669 Element error = result.findChild("error");
2670 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server rejected avatar "+(avatar.size/1024)+"KiB "+(error!=null?error.toString():""));
2671 if (callback != null) {
2672 callback.error(R.string.error_publish_avatar_server_reject, avatar);
2673 }
2674 }
2675 }
2676 });
2677 }
2678
2679 public void republishAvatarIfNeeded(Account account) {
2680 if (account.getAxolotlService().isPepBroken()) {
2681 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2682 return;
2683 }
2684 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2685 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2686
2687 private Avatar parseAvatar(IqPacket packet) {
2688 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2689 if (pubsub != null) {
2690 Element items = pubsub.findChild("items");
2691 if (items != null) {
2692 return Avatar.parseMetadata(items);
2693 }
2694 }
2695 return null;
2696 }
2697
2698 private boolean errorIsItemNotFound(IqPacket packet) {
2699 Element error = packet.findChild("error");
2700 return packet.getType() == IqPacket.TYPE.ERROR
2701 && error != null
2702 && error.hasChild("item-not-found");
2703 }
2704
2705 @Override
2706 public void onIqPacketReceived(Account account, IqPacket packet) {
2707 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2708 Avatar serverAvatar = parseAvatar(packet);
2709 if (serverAvatar == null && account.getAvatar() != null) {
2710 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2711 if (avatar != null) {
2712 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2713 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2714 } else {
2715 Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2716 }
2717 }
2718 }
2719 }
2720 });
2721 }
2722
2723 public void fetchAvatar(Account account, Avatar avatar) {
2724 fetchAvatar(account, avatar, null);
2725 }
2726
2727 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2728 final String KEY = generateFetchKey(account, avatar);
2729 synchronized (this.mInProgressAvatarFetches) {
2730 if (!this.mInProgressAvatarFetches.contains(KEY)) {
2731 switch (avatar.origin) {
2732 case PEP:
2733 this.mInProgressAvatarFetches.add(KEY);
2734 fetchAvatarPep(account, avatar, callback);
2735 break;
2736 case VCARD:
2737 this.mInProgressAvatarFetches.add(KEY);
2738 fetchAvatarVcard(account, avatar, callback);
2739 break;
2740 }
2741 }
2742 }
2743 }
2744
2745 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2746 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2747 sendIqPacket(account, packet, new OnIqPacketReceived() {
2748
2749 @Override
2750 public void onIqPacketReceived(Account account, IqPacket result) {
2751 synchronized (mInProgressAvatarFetches) {
2752 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2753 }
2754 final String ERROR = account.getJid().toBareJid()
2755 + ": fetching avatar for " + avatar.owner + " failed ";
2756 if (result.getType() == IqPacket.TYPE.RESULT) {
2757 avatar.image = mIqParser.avatarData(result);
2758 if (avatar.image != null) {
2759 if (getFileBackend().save(avatar)) {
2760 if (account.getJid().toBareJid().equals(avatar.owner)) {
2761 if (account.setAvatar(avatar.getFilename())) {
2762 databaseBackend.updateAccount(account);
2763 }
2764 getAvatarService().clear(account);
2765 updateConversationUi();
2766 updateAccountUi();
2767 } else {
2768 Contact contact = account.getRoster()
2769 .getContact(avatar.owner);
2770 contact.setAvatar(avatar);
2771 getAvatarService().clear(contact);
2772 updateConversationUi();
2773 updateRosterUi();
2774 }
2775 if (callback != null) {
2776 callback.success(avatar);
2777 }
2778 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2779 + ": successfully fetched pep avatar for " + avatar.owner);
2780 return;
2781 }
2782 } else {
2783
2784 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2785 }
2786 } else {
2787 Element error = result.findChild("error");
2788 if (error == null) {
2789 Log.d(Config.LOGTAG, ERROR + "(server error)");
2790 } else {
2791 Log.d(Config.LOGTAG, ERROR + error.toString());
2792 }
2793 }
2794 if (callback != null) {
2795 callback.error(0, null);
2796 }
2797
2798 }
2799 });
2800 }
2801
2802 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2803 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2804 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2805 @Override
2806 public void onIqPacketReceived(Account account, IqPacket packet) {
2807 synchronized (mInProgressAvatarFetches) {
2808 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2809 }
2810 if (packet.getType() == IqPacket.TYPE.RESULT) {
2811 Element vCard = packet.findChild("vCard", "vcard-temp");
2812 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2813 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2814 if (image != null) {
2815 avatar.image = image;
2816 if (getFileBackend().save(avatar)) {
2817 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2818 + ": successfully fetched vCard avatar for " + avatar.owner);
2819 if (avatar.owner.isBareJid()) {
2820 if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2821 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": had no avatar. replacing with vcard");
2822 account.setAvatar(avatar.getFilename());
2823 databaseBackend.updateAccount(account);
2824 getAvatarService().clear(account);
2825 updateAccountUi();
2826 } else {
2827 Contact contact = account.getRoster().getContact(avatar.owner);
2828 contact.setAvatar(avatar);
2829 getAvatarService().clear(contact);
2830 updateRosterUi();
2831 }
2832 updateConversationUi();
2833 } else {
2834 Conversation conversation = find(account, avatar.owner.toBareJid());
2835 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2836 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2837 if (user != null) {
2838 if (user.setAvatar(avatar)) {
2839 getAvatarService().clear(user);
2840 updateConversationUi();
2841 updateMucRosterUi();
2842 }
2843 }
2844 }
2845 }
2846 }
2847 }
2848 }
2849 }
2850 });
2851 }
2852
2853 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2854 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2855 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2856
2857 @Override
2858 public void onIqPacketReceived(Account account, IqPacket packet) {
2859 if (packet.getType() == IqPacket.TYPE.RESULT) {
2860 Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2861 if (pubsub != null) {
2862 Element items = pubsub.findChild("items");
2863 if (items != null) {
2864 Avatar avatar = Avatar.parseMetadata(items);
2865 if (avatar != null) {
2866 avatar.owner = account.getJid().toBareJid();
2867 if (fileBackend.isAvatarCached(avatar)) {
2868 if (account.setAvatar(avatar.getFilename())) {
2869 databaseBackend.updateAccount(account);
2870 }
2871 getAvatarService().clear(account);
2872 callback.success(avatar);
2873 } else {
2874 fetchAvatarPep(account, avatar, callback);
2875 }
2876 return;
2877 }
2878 }
2879 }
2880 }
2881 callback.error(0, null);
2882 }
2883 });
2884 }
2885
2886 public void deleteContactOnServer(Contact contact) {
2887 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2888 contact.resetOption(Contact.Options.DIRTY_PUSH);
2889 contact.setOption(Contact.Options.DIRTY_DELETE);
2890 Account account = contact.getAccount();
2891 if (account.getStatus() == Account.State.ONLINE) {
2892 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2893 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2894 item.setAttribute("jid", contact.getJid().toString());
2895 item.setAttribute("subscription", "remove");
2896 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2897 }
2898 }
2899
2900 public void updateConversation(final Conversation conversation) {
2901 mDatabaseExecutor.execute(new Runnable() {
2902 @Override
2903 public void run() {
2904 databaseBackend.updateConversation(conversation);
2905 }
2906 });
2907 }
2908
2909 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2910 synchronized (account) {
2911 XmppConnection connection = account.getXmppConnection();
2912 if (connection == null) {
2913 connection = createConnection(account);
2914 account.setXmppConnection(connection);
2915 }
2916 boolean hasInternet = hasInternetConnection();
2917 if (!account.isOptionSet(Account.OPTION_DISABLED) && hasInternet) {
2918 if (!force) {
2919 disconnect(account, false);
2920 }
2921 Thread thread = new Thread(connection);
2922 connection.setInteractive(interactive);
2923 connection.prepareNewConnection();
2924 connection.interrupt();
2925 thread.start();
2926 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2927 } else {
2928 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
2929 account.getRoster().clearPresences();
2930 connection.resetEverything();
2931 account.getAxolotlService().resetBrokenness();
2932 if (!hasInternet) {
2933 account.setStatus(Account.State.NO_INTERNET);
2934 }
2935 }
2936 }
2937 }
2938
2939 public void reconnectAccountInBackground(final Account account) {
2940 new Thread(new Runnable() {
2941 @Override
2942 public void run() {
2943 reconnectAccount(account, false, true);
2944 }
2945 }).start();
2946 }
2947
2948 public void invite(Conversation conversation, Jid contact) {
2949 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2950 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2951 sendMessagePacket(conversation.getAccount(), packet);
2952 }
2953
2954 public void directInvite(Conversation conversation, Jid jid) {
2955 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2956 sendMessagePacket(conversation.getAccount(), packet);
2957 }
2958
2959 public void resetSendingToWaiting(Account account) {
2960 for (Conversation conversation : getConversations()) {
2961 if (conversation.getAccount() == account) {
2962 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2963
2964 @Override
2965 public void onMessageFound(Message message) {
2966 markMessage(message, Message.STATUS_WAITING);
2967 }
2968 });
2969 }
2970 }
2971 }
2972
2973 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2974 return markMessage(account, recipient, uuid, status, null);
2975 }
2976
2977 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
2978 if (uuid == null) {
2979 return null;
2980 }
2981 for (Conversation conversation : getConversations()) {
2982 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2983 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2984 if (message != null) {
2985 markMessage(message, status, errorMessage);
2986 }
2987 return message;
2988 }
2989 }
2990 return null;
2991 }
2992
2993 public boolean markMessage(Conversation conversation, String uuid, int status) {
2994 if (uuid == null) {
2995 return false;
2996 } else {
2997 Message message = conversation.findSentMessageWithUuid(uuid);
2998 if (message != null) {
2999 markMessage(message, status);
3000 return true;
3001 } else {
3002 return false;
3003 }
3004 }
3005 }
3006
3007 public void markMessage(Message message, int status) {
3008 markMessage(message, status, null);
3009 }
3010
3011
3012 public void markMessage(Message message, int status, String errorMessage) {
3013 if (status == Message.STATUS_SEND_FAILED
3014 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
3015 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
3016 return;
3017 }
3018 message.setErrorMessage(errorMessage);
3019 message.setStatus(status);
3020 databaseBackend.updateMessage(message);
3021 updateConversationUi();
3022 }
3023
3024 public SharedPreferences getPreferences() {
3025 return PreferenceManager
3026 .getDefaultSharedPreferences(getApplicationContext());
3027 }
3028
3029 public boolean confirmMessages() {
3030 return getPreferences().getBoolean("confirm_messages", true);
3031 }
3032
3033 public boolean allowMessageCorrection() {
3034 return getPreferences().getBoolean("allow_message_correction", true);
3035 }
3036
3037 public boolean sendChatStates() {
3038 return getPreferences().getBoolean("chat_states", false);
3039 }
3040
3041 public boolean saveEncryptedMessages() {
3042 return !getPreferences().getBoolean("dont_save_encrypted", false);
3043 }
3044
3045 private boolean respectAutojoin() {
3046 return getPreferences().getBoolean("autojoin", true);
3047 }
3048
3049 public boolean indicateReceived() {
3050 return getPreferences().getBoolean("indicate_received", false);
3051 }
3052
3053 public boolean useTorToConnect() {
3054 return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
3055 }
3056
3057 public boolean showExtendedConnectionOptions() {
3058 return getPreferences().getBoolean("show_connection_options", false);
3059 }
3060
3061 public boolean broadcastLastActivity() {
3062 return getPreferences().getBoolean("last_activity", false);
3063 }
3064
3065 public int unreadCount() {
3066 int count = 0;
3067 for (Conversation conversation : getConversations()) {
3068 count += conversation.unreadCount();
3069 }
3070 return count;
3071 }
3072
3073
3074 public void showErrorToastInUi(int resId) {
3075 if (mOnShowErrorToast != null) {
3076 mOnShowErrorToast.onShowErrorToast(resId);
3077 }
3078 }
3079
3080 public void updateConversationUi() {
3081 if (mOnConversationUpdate != null) {
3082 mOnConversationUpdate.onConversationUpdate();
3083 }
3084 }
3085
3086 public void updateAccountUi() {
3087 if (mOnAccountUpdate != null) {
3088 mOnAccountUpdate.onAccountUpdate();
3089 }
3090 }
3091
3092 public void updateRosterUi() {
3093 if (mOnRosterUpdate != null) {
3094 mOnRosterUpdate.onRosterUpdate();
3095 }
3096 }
3097
3098 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3099 if (mOnCaptchaRequested != null) {
3100 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3101 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3102 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3103
3104 mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3105 return true;
3106 }
3107 return false;
3108 }
3109
3110 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3111 if (mOnUpdateBlocklist != null) {
3112 mOnUpdateBlocklist.OnUpdateBlocklist(status);
3113 }
3114 }
3115
3116 public void updateMucRosterUi() {
3117 if (mOnMucRosterUpdate != null) {
3118 mOnMucRosterUpdate.onMucRosterUpdate();
3119 }
3120 }
3121
3122 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3123 if (mOnKeyStatusUpdated != null) {
3124 mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3125 }
3126 }
3127
3128 public Account findAccountByJid(final Jid accountJid) {
3129 for (Account account : this.accounts) {
3130 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3131 return account;
3132 }
3133 }
3134 return null;
3135 }
3136
3137 public Conversation findConversationByUuid(String uuid) {
3138 for (Conversation conversation : getConversations()) {
3139 if (conversation.getUuid().equals(uuid)) {
3140 return conversation;
3141 }
3142 }
3143 return null;
3144 }
3145
3146 public boolean markRead(final Conversation conversation) {
3147 return markRead(conversation,true);
3148 }
3149
3150 public boolean markRead(final Conversation conversation, boolean clear) {
3151 if (clear) {
3152 mNotificationService.clear(conversation);
3153 }
3154 final List<Message> readMessages = conversation.markRead();
3155 if (readMessages.size() > 0) {
3156 Runnable runnable = new Runnable() {
3157 @Override
3158 public void run() {
3159 for (Message message : readMessages) {
3160 databaseBackend.updateMessage(message);
3161 }
3162 }
3163 };
3164 mDatabaseExecutor.execute(runnable);
3165 updateUnreadCountBadge();
3166 return true;
3167 } else {
3168 return false;
3169 }
3170 }
3171
3172 public synchronized void updateUnreadCountBadge() {
3173 int count = unreadCount();
3174 if (unreadCount != count) {
3175 Log.d(Config.LOGTAG, "update unread count to " + count);
3176 if (count > 0) {
3177 ShortcutBadger.applyCount(getApplicationContext(), count);
3178 } else {
3179 ShortcutBadger.removeCount(getApplicationContext());
3180 }
3181 unreadCount = count;
3182 }
3183 }
3184
3185 public void sendReadMarker(final Conversation conversation) {
3186 final Message markable = conversation.getLatestMarkableMessage();
3187 if (this.markRead(conversation)) {
3188 updateConversationUi();
3189 }
3190 if (confirmMessages()
3191 && markable != null
3192 && markable.trusted()
3193 && markable.getRemoteMsgId() != null) {
3194 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3195 Account account = conversation.getAccount();
3196 final Jid to = markable.getCounterpart();
3197 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
3198 this.sendMessagePacket(conversation.getAccount(), packet);
3199 }
3200 }
3201
3202 public SecureRandom getRNG() {
3203 return this.mRandom;
3204 }
3205
3206 public MemorizingTrustManager getMemorizingTrustManager() {
3207 return this.mMemorizingTrustManager;
3208 }
3209
3210 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3211 this.mMemorizingTrustManager = trustManager;
3212 }
3213
3214 public void updateMemorizingTrustmanager() {
3215 final MemorizingTrustManager tm;
3216 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
3217 if (dontTrustSystemCAs) {
3218 tm = new MemorizingTrustManager(getApplicationContext(), null);
3219 } else {
3220 tm = new MemorizingTrustManager(getApplicationContext());
3221 }
3222 setMemorizingTrustManager(tm);
3223 }
3224
3225 public PowerManager getPowerManager() {
3226 return this.pm;
3227 }
3228
3229 public LruCache<String, Bitmap> getBitmapCache() {
3230 return this.mBitmapCache;
3231 }
3232
3233 public void syncRosterToDisk(final Account account) {
3234 Runnable runnable = new Runnable() {
3235
3236 @Override
3237 public void run() {
3238 databaseBackend.writeRoster(account.getRoster());
3239 }
3240 };
3241 mDatabaseExecutor.execute(runnable);
3242
3243 }
3244
3245 public List<String> getKnownHosts() {
3246 final List<String> hosts = new ArrayList<>();
3247 for (final Account account : getAccounts()) {
3248 if (!hosts.contains(account.getServer().toString())) {
3249 hosts.add(account.getServer().toString());
3250 }
3251 for (final Contact contact : account.getRoster().getContacts()) {
3252 if (contact.showInRoster()) {
3253 final String server = contact.getServer().toString();
3254 if (server != null && !hosts.contains(server)) {
3255 hosts.add(server);
3256 }
3257 }
3258 }
3259 }
3260 if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3261 hosts.add(Config.DOMAIN_LOCK);
3262 }
3263 if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3264 hosts.add(Config.MAGIC_CREATE_DOMAIN);
3265 }
3266 return hosts;
3267 }
3268
3269 public List<String> getKnownConferenceHosts() {
3270 final ArrayList<String> mucServers = new ArrayList<>();
3271 for (final Account account : accounts) {
3272 if (account.getXmppConnection() != null) {
3273 final String server = account.getXmppConnection().getMucServer();
3274 if (server != null && !mucServers.contains(server)) {
3275 mucServers.add(server);
3276 }
3277 }
3278 }
3279 return mucServers;
3280 }
3281
3282 public void sendMessagePacket(Account account, MessagePacket packet) {
3283 XmppConnection connection = account.getXmppConnection();
3284 if (connection != null) {
3285 connection.sendMessagePacket(packet);
3286 }
3287 }
3288
3289 public void sendPresencePacket(Account account, PresencePacket packet) {
3290 XmppConnection connection = account.getXmppConnection();
3291 if (connection != null) {
3292 connection.sendPresencePacket(packet);
3293 }
3294 }
3295
3296 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3297 final XmppConnection connection = account.getXmppConnection();
3298 if (connection != null) {
3299 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3300 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3301 }
3302 }
3303
3304 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3305 final XmppConnection connection = account.getXmppConnection();
3306 if (connection != null) {
3307 connection.sendIqPacket(packet, callback);
3308 }
3309 }
3310
3311 public void sendPresence(final Account account) {
3312 sendPresence(account, checkListeners() && broadcastLastActivity());
3313 }
3314
3315 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3316 PresencePacket packet;
3317 if (manuallyChangePresence()) {
3318 packet = mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3319 String message = account.getPresenceStatusMessage();
3320 if (message != null && !message.isEmpty()) {
3321 packet.addChild(new Element("status").setContent(message));
3322 }
3323 } else {
3324 packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3325 }
3326 if (mLastActivity > 0 && includeIdleTimestamp) {
3327 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3328 packet.addChild("idle","urn:xmpp:idle:1").setAttribute("since", AbstractGenerator.getTimestamp(since));
3329 }
3330 sendPresencePacket(account, packet);
3331 }
3332
3333 private void deactivateGracePeriod() {
3334 for(Account account : getAccounts()) {
3335 account.deactivateGracePeriod();
3336 }
3337 }
3338
3339 public void refreshAllPresences() {
3340 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3341 for (Account account : getAccounts()) {
3342 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3343 sendPresence(account, includeIdleTimestamp);
3344 }
3345 }
3346 }
3347
3348 private void refreshAllGcmTokens() {
3349 for(Account account : getAccounts()) {
3350 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3351 mPushManagementService.registerPushTokenOnServer(account);
3352 }
3353 }
3354 }
3355
3356 private void sendOfflinePresence(final Account account) {
3357 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending offline presence");
3358 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3359 }
3360
3361 public MessageGenerator getMessageGenerator() {
3362 return this.mMessageGenerator;
3363 }
3364
3365 public PresenceGenerator getPresenceGenerator() {
3366 return this.mPresenceGenerator;
3367 }
3368
3369 public IqGenerator getIqGenerator() {
3370 return this.mIqGenerator;
3371 }
3372
3373 public IqParser getIqParser() {
3374 return this.mIqParser;
3375 }
3376
3377 public JingleConnectionManager getJingleConnectionManager() {
3378 return this.mJingleConnectionManager;
3379 }
3380
3381 public MessageArchiveService getMessageArchiveService() {
3382 return this.mMessageArchiveService;
3383 }
3384
3385 public List<Contact> findContacts(Jid jid) {
3386 ArrayList<Contact> contacts = new ArrayList<>();
3387 for (Account account : getAccounts()) {
3388 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3389 Contact contact = account.getRoster().getContactFromRoster(jid);
3390 if (contact != null) {
3391 contacts.add(contact);
3392 }
3393 }
3394 }
3395 return contacts;
3396 }
3397
3398 public Conversation findFirstMuc(Jid jid) {
3399 for(Conversation conversation : getConversations()) {
3400 if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3401 && conversation.getMode() == Conversation.MODE_MULTI) {
3402 return conversation;
3403 }
3404 }
3405 return null;
3406 }
3407
3408 public NotificationService getNotificationService() {
3409 return this.mNotificationService;
3410 }
3411
3412 public HttpConnectionManager getHttpConnectionManager() {
3413 return this.mHttpConnectionManager;
3414 }
3415
3416 public void resendFailedMessages(final Message message) {
3417 final Collection<Message> messages = new ArrayList<>();
3418 Message current = message;
3419 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3420 messages.add(current);
3421 if (current.mergeable(current.next())) {
3422 current = current.next();
3423 } else {
3424 break;
3425 }
3426 }
3427 for (final Message msg : messages) {
3428 msg.setTime(System.currentTimeMillis());
3429 markMessage(msg, Message.STATUS_WAITING);
3430 this.resendMessage(msg, false);
3431 }
3432 }
3433
3434 public void clearConversationHistory(final Conversation conversation) {
3435 conversation.clearMessages();
3436 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3437 conversation.setLastClearHistory(System.currentTimeMillis());
3438 Runnable runnable = new Runnable() {
3439 @Override
3440 public void run() {
3441 databaseBackend.deleteMessagesInConversation(conversation);
3442 databaseBackend.updateConversation(conversation);
3443 }
3444 };
3445 mDatabaseExecutor.execute(runnable);
3446 }
3447
3448 public void sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3449 if (blockable != null && blockable.getBlockedJid() != null) {
3450 final Jid jid = blockable.getBlockedJid();
3451 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3452
3453 @Override
3454 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3455 if (packet.getType() == IqPacket.TYPE.RESULT) {
3456 account.getBlocklist().add(jid);
3457 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3458 }
3459 }
3460 });
3461 }
3462 }
3463
3464 public void sendUnblockRequest(final Blockable blockable) {
3465 if (blockable != null && blockable.getJid() != null) {
3466 final Jid jid = blockable.getBlockedJid();
3467 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3468 @Override
3469 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3470 if (packet.getType() == IqPacket.TYPE.RESULT) {
3471 account.getBlocklist().remove(jid);
3472 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3473 }
3474 }
3475 });
3476 }
3477 }
3478
3479 public void publishDisplayName(Account account) {
3480 String displayName = account.getDisplayName();
3481 if (displayName != null && !displayName.isEmpty()) {
3482 IqPacket publish = mIqGenerator.publishNick(displayName);
3483 sendIqPacket(account, publish, new OnIqPacketReceived() {
3484 @Override
3485 public void onIqPacketReceived(Account account, IqPacket packet) {
3486 if (packet.getType() == IqPacket.TYPE.ERROR) {
3487 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3488 }
3489 }
3490 });
3491 }
3492 }
3493
3494 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3495 ServiceDiscoveryResult result = discoCache.get(key);
3496 if (result != null) {
3497 return result;
3498 } else {
3499 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3500 if (result != null) {
3501 discoCache.put(key, result);
3502 }
3503 return result;
3504 }
3505 }
3506
3507 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3508 final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3509 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3510 if (disco != null) {
3511 presence.setServiceDiscoveryResult(disco);
3512 } else {
3513 if (!account.inProgressDiscoFetches.contains(key)) {
3514 account.inProgressDiscoFetches.add(key);
3515 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3516 request.setTo(jid);
3517 request.query("http://jabber.org/protocol/disco#info");
3518 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3519 sendIqPacket(account, request, new OnIqPacketReceived() {
3520 @Override
3521 public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3522 if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3523 ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3524 if (presence.getVer().equals(disco.getVer())) {
3525 databaseBackend.insertDiscoveryResult(disco);
3526 injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3527 } else {
3528 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3529 }
3530 }
3531 account.inProgressDiscoFetches.remove(key);
3532 }
3533 });
3534 }
3535 }
3536 }
3537
3538 private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3539 for(Contact contact : roster.getContacts()) {
3540 for(Presence presence : contact.getPresences().getPresences().values()) {
3541 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3542 presence.setServiceDiscoveryResult(disco);
3543 }
3544 }
3545 }
3546 }
3547
3548 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3549 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3550 request.addChild("prefs","urn:xmpp:mam:0");
3551 sendIqPacket(account, request, new OnIqPacketReceived() {
3552 @Override
3553 public void onIqPacketReceived(Account account, IqPacket packet) {
3554 Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3555 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3556 callback.onPreferencesFetched(prefs);
3557 } else {
3558 callback.onPreferencesFetchFailed();
3559 }
3560 }
3561 });
3562 }
3563
3564 public PushManagementService getPushManagementService() {
3565 return mPushManagementService;
3566 }
3567
3568 public Account getPendingAccount() {
3569 Account pending = null;
3570 for(Account account : getAccounts()) {
3571 if (account.isOptionSet(Account.OPTION_REGISTER)) {
3572 pending = account;
3573 } else {
3574 return null;
3575 }
3576 }
3577 return pending;
3578 }
3579
3580 public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3581 if (!statusMessage.isEmpty()) {
3582 databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3583 }
3584 changeStatusReal(account, status, statusMessage, send);
3585 }
3586
3587 private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3588 account.setPresenceStatus(status);
3589 account.setPresenceStatusMessage(statusMessage);
3590 databaseBackend.updateAccount(account);
3591 if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3592 sendPresence(account);
3593 }
3594 }
3595
3596 public void changeStatus(Presence.Status status, String statusMessage) {
3597 if (!statusMessage.isEmpty()) {
3598 databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3599 }
3600 for(Account account : getAccounts()) {
3601 changeStatusReal(account, status, statusMessage, true);
3602 }
3603 }
3604
3605 public List<PresenceTemplate> getPresenceTemplates(Account account) {
3606 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3607 for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3608 if (!templates.contains(template)) {
3609 templates.add(0, template);
3610 }
3611 }
3612 return templates;
3613 }
3614
3615 public void saveConversationAsBookmark(Conversation conversation, String name) {
3616 Account account = conversation.getAccount();
3617 Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3618 if (!conversation.getJid().isBareJid()) {
3619 bookmark.setNick(conversation.getJid().getResourcepart());
3620 }
3621 if (name != null && !name.trim().isEmpty()) {
3622 bookmark.setBookmarkName(name.trim());
3623 }
3624 bookmark.setAutojoin(getPreferences().getBoolean("autojoin",true));
3625 account.getBookmarks().add(bookmark);
3626 pushBookmarks(account);
3627 conversation.setBookmark(bookmark);
3628 }
3629
3630 public void clearStartTimeCounter() {
3631 mDatabaseExecutor.execute(new Runnable() {
3632 @Override
3633 public void run() {
3634 databaseBackend.clearStartTimeCounter(false);
3635 }
3636 });
3637 }
3638
3639 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3640 boolean needsRosterWrite = false;
3641 boolean performedVerification = false;
3642 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3643 for(XmppUri.Fingerprint fp : fingerprints) {
3644 if (fp.type == XmppUri.FingerprintType.OTR) {
3645 performedVerification |= contact.addOtrFingerprint(fp.fingerprint);
3646 needsRosterWrite |= performedVerification;
3647 } else if (fp.type == XmppUri.FingerprintType.OMEMO) {
3648 String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3649 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3650 if (fingerprintStatus != null) {
3651 if (!fingerprintStatus.isVerified()) {
3652 performedVerification = true;
3653 axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3654 }
3655 } else {
3656 axolotlService.preVerifyFingerprint(contact,fingerprint);
3657 }
3658 }
3659 }
3660 if (needsRosterWrite) {
3661 syncRosterToDisk(contact.getAccount());
3662 }
3663 return performedVerification;
3664 }
3665
3666 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3667 final AxolotlService axolotlService = account.getAxolotlService();
3668 boolean verifiedSomething = false;
3669 for(XmppUri.Fingerprint fp : fingerprints) {
3670 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3671 String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3672 Log.d(Config.LOGTAG,"trying to verify own fp="+fingerprint);
3673 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3674 if (fingerprintStatus != null) {
3675 if (!fingerprintStatus.isVerified()) {
3676 axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3677 verifiedSomething = true;
3678 }
3679 } else {
3680 axolotlService.preVerifyFingerprint(account,fingerprint);
3681 verifiedSomething = true;
3682 }
3683 }
3684 }
3685 return verifiedSomething;
3686 }
3687
3688 public boolean blindTrustBeforeVerification() {
3689 return getPreferences().getBoolean(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, true);
3690 }
3691
3692 public interface OnMamPreferencesFetched {
3693 void onPreferencesFetched(Element prefs);
3694 void onPreferencesFetchFailed();
3695 }
3696
3697 public void pushMamPreferences(Account account, Element prefs) {
3698 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3699 set.addChild(prefs);
3700 sendIqPacket(account, set, null);
3701 }
3702
3703 public interface OnAccountCreated {
3704 void onAccountCreated(Account account);
3705
3706 void informUser(int r);
3707 }
3708
3709 public interface OnMoreMessagesLoaded {
3710 void onMoreMessagesLoaded(int count, Conversation conversation);
3711
3712 void informUser(int r);
3713 }
3714
3715 public interface OnAccountPasswordChanged {
3716 void onPasswordChangeSucceeded();
3717
3718 void onPasswordChangeFailed();
3719 }
3720
3721 public interface OnAffiliationChanged {
3722 void onAffiliationChangedSuccessful(Jid jid);
3723
3724 void onAffiliationChangeFailed(Jid jid, int resId);
3725 }
3726
3727 public interface OnRoleChanged {
3728 void onRoleChangedSuccessful(String nick);
3729
3730 void onRoleChangeFailed(String nick, int resid);
3731 }
3732
3733 public interface OnConversationUpdate {
3734 void onConversationUpdate();
3735 }
3736
3737 public interface OnAccountUpdate {
3738 void onAccountUpdate();
3739 }
3740
3741 public interface OnCaptchaRequested {
3742 void onCaptchaRequested(Account account,
3743 String id,
3744 Data data,
3745 Bitmap captcha);
3746 }
3747
3748 public interface OnRosterUpdate {
3749 void onRosterUpdate();
3750 }
3751
3752 public interface OnMucRosterUpdate {
3753 void onMucRosterUpdate();
3754 }
3755
3756 public interface OnConferenceConfigurationFetched {
3757 void onConferenceConfigurationFetched(Conversation conversation);
3758
3759 void onFetchFailed(Conversation conversation, Element error);
3760 }
3761
3762 public interface OnConferenceJoined {
3763 void onConferenceJoined(Conversation conversation);
3764 }
3765
3766 public interface OnConferenceOptionsPushed {
3767 void onPushSucceeded();
3768
3769 void onPushFailed();
3770 }
3771
3772 public interface OnShowErrorToast {
3773 void onShowErrorToast(int resId);
3774 }
3775
3776 public class XmppConnectionBinder extends Binder {
3777 public XmppConnectionService getService() {
3778 return XmppConnectionService.this;
3779 }
3780 }
3781}