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