1package eu.siacs.conversations.services;
2
3import static eu.siacs.conversations.utils.Compatibility.s;
4import static eu.siacs.conversations.utils.Random.SECURE_RANDOM;
5
6import android.Manifest;
7import android.annotation.SuppressLint;
8import android.annotation.TargetApi;
9import android.app.AlarmManager;
10import android.app.KeyguardManager;
11import android.app.Notification;
12import android.app.NotificationManager;
13import android.app.PendingIntent;
14import android.app.Service;
15import android.content.BroadcastReceiver;
16import android.content.ComponentName;
17import android.content.Context;
18import android.content.Intent;
19import android.content.IntentFilter;
20import android.content.SharedPreferences;
21import android.content.pm.PackageManager;
22import android.content.pm.ServiceInfo;
23import android.database.ContentObserver;
24import android.graphics.Bitmap;
25import android.graphics.drawable.AnimatedImageDrawable;
26import android.graphics.drawable.BitmapDrawable;
27import android.graphics.drawable.Drawable;
28import android.media.AudioManager;
29import android.net.ConnectivityManager;
30import android.net.Network;
31import android.net.NetworkCapabilities;
32import android.net.NetworkInfo;
33import android.net.Uri;
34import android.os.Binder;
35import android.os.Build;
36import android.os.Bundle;
37import android.os.Environment;
38import android.os.IBinder;
39import android.os.Messenger;
40import android.os.PowerManager;
41import android.os.PowerManager.WakeLock;
42import android.os.SystemClock;
43import android.preference.PreferenceManager;
44import android.provider.ContactsContract;
45import android.provider.DocumentsContract;
46import android.security.KeyChain;
47import android.text.TextUtils;
48import android.util.DisplayMetrics;
49import android.util.Log;
50import android.util.LruCache;
51import android.util.Pair;
52
53import androidx.annotation.BoolRes;
54import androidx.annotation.IntegerRes;
55import androidx.annotation.NonNull;
56import androidx.annotation.Nullable;
57import androidx.core.app.RemoteInput;
58import androidx.core.content.ContextCompat;
59
60import com.cheogram.android.EmojiSearch;
61import com.cheogram.android.WebxdcUpdate;
62
63import com.google.common.base.Objects;
64import com.google.common.base.Optional;
65import com.google.common.base.Strings;
66import com.google.common.collect.Collections2;
67import com.google.common.collect.ImmutableSet;
68import com.google.common.collect.Iterables;
69import com.google.common.collect.Multimap;
70import com.google.common.io.Files;
71
72import com.kedia.ogparser.JsoupProxy;
73import com.kedia.ogparser.OpenGraphCallback;
74import com.kedia.ogparser.OpenGraphParser;
75import com.kedia.ogparser.OpenGraphResult;
76
77import org.conscrypt.Conscrypt;
78import org.jxmpp.stringprep.libidn.LibIdnXmppStringprep;
79import org.openintents.openpgp.IOpenPgpService2;
80import org.openintents.openpgp.util.OpenPgpApi;
81import org.openintents.openpgp.util.OpenPgpServiceConnection;
82
83import java.io.File;
84import java.io.FileInputStream;
85import java.io.IOException;
86import java.net.URI;
87import java.security.Security;
88import java.security.cert.CertificateException;
89import java.security.cert.X509Certificate;
90import java.util.ArrayList;
91import java.util.Arrays;
92import java.util.Collection;
93import java.util.Collections;
94import java.util.HashMap;
95import java.util.HashSet;
96import java.util.Hashtable;
97import java.util.Iterator;
98import java.util.List;
99import java.util.ListIterator;
100import java.util.Map;
101import java.util.Set;
102import java.util.WeakHashMap;
103import java.util.concurrent.CopyOnWriteArrayList;
104import java.util.concurrent.CountDownLatch;
105import java.util.concurrent.Executor;
106import java.util.concurrent.Executors;
107import java.util.concurrent.Semaphore;
108import java.util.concurrent.RejectedExecutionException;
109import java.util.concurrent.ScheduledExecutorService;
110import java.util.concurrent.TimeUnit;
111import java.util.concurrent.atomic.AtomicBoolean;
112import java.util.concurrent.atomic.AtomicLong;
113import java.util.concurrent.atomic.AtomicReference;
114import java.util.function.Consumer;
115
116import io.ipfs.cid.Cid;
117
118import eu.siacs.conversations.AppSettings;
119import eu.siacs.conversations.Config;
120import eu.siacs.conversations.R;
121import eu.siacs.conversations.android.JabberIdContact;
122import eu.siacs.conversations.crypto.OmemoSetting;
123import eu.siacs.conversations.crypto.PgpDecryptionService;
124import eu.siacs.conversations.crypto.PgpEngine;
125import eu.siacs.conversations.crypto.axolotl.AxolotlService;
126import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
127import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
128import eu.siacs.conversations.entities.Account;
129import eu.siacs.conversations.entities.Blockable;
130import eu.siacs.conversations.entities.Bookmark;
131import eu.siacs.conversations.entities.Contact;
132import eu.siacs.conversations.entities.Conversation;
133import eu.siacs.conversations.entities.Conversational;
134import eu.siacs.conversations.entities.DownloadableFile;
135import eu.siacs.conversations.entities.Message;
136import eu.siacs.conversations.entities.MucOptions;
137import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
138import eu.siacs.conversations.entities.Presence;
139import eu.siacs.conversations.entities.PresenceTemplate;
140import eu.siacs.conversations.entities.Reaction;
141import eu.siacs.conversations.entities.Roster;
142import eu.siacs.conversations.entities.ServiceDiscoveryResult;
143import eu.siacs.conversations.generator.AbstractGenerator;
144import eu.siacs.conversations.generator.IqGenerator;
145import eu.siacs.conversations.generator.MessageGenerator;
146import eu.siacs.conversations.generator.PresenceGenerator;
147import eu.siacs.conversations.http.HttpConnectionManager;
148import eu.siacs.conversations.parser.AbstractParser;
149import eu.siacs.conversations.parser.IqParser;
150import eu.siacs.conversations.persistance.DatabaseBackend;
151import eu.siacs.conversations.persistance.FileBackend;
152import eu.siacs.conversations.persistance.UnifiedPushDatabase;
153import eu.siacs.conversations.receiver.SystemEventReceiver;
154import eu.siacs.conversations.ui.ChooseAccountForProfilePictureActivity;
155import eu.siacs.conversations.ui.ConversationsActivity;
156import eu.siacs.conversations.ui.RtpSessionActivity;
157import eu.siacs.conversations.ui.UiCallback;
158import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
159import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
160import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
161import eu.siacs.conversations.ui.util.QuoteHelper;
162import eu.siacs.conversations.utils.AccountUtils;
163import eu.siacs.conversations.utils.Compatibility;
164import eu.siacs.conversations.utils.ConversationsFileObserver;
165import eu.siacs.conversations.utils.CryptoHelper;
166import eu.siacs.conversations.utils.Emoticons;
167import eu.siacs.conversations.utils.EasyOnboardingInvite;
168import eu.siacs.conversations.utils.ExceptionHelper;
169import eu.siacs.conversations.utils.FileUtils;
170import eu.siacs.conversations.utils.MessageUtils;
171import eu.siacs.conversations.utils.MimeUtils;
172import eu.siacs.conversations.utils.PhoneHelper;
173import eu.siacs.conversations.utils.QuickLoader;
174import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
175import eu.siacs.conversations.utils.ReplacingTaskManager;
176import eu.siacs.conversations.utils.Resolver;
177import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
178import eu.siacs.conversations.utils.StringUtils;
179import eu.siacs.conversations.utils.TorServiceUtils;
180import eu.siacs.conversations.utils.ThemeHelper;
181import eu.siacs.conversations.utils.WakeLockHelper;
182import eu.siacs.conversations.utils.XmppUri;
183import eu.siacs.conversations.xml.Element;
184import eu.siacs.conversations.xml.LocalizedContent;
185import eu.siacs.conversations.xml.Namespace;
186import eu.siacs.conversations.xmpp.InvalidJid;
187import eu.siacs.conversations.xmpp.Jid;
188import eu.siacs.conversations.xmpp.OnContactStatusChanged;
189import eu.siacs.conversations.xmpp.OnGatewayResult;
190import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
191import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
192import eu.siacs.conversations.xmpp.OnStatusChanged;
193import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
194import eu.siacs.conversations.xmpp.XmppConnection;
195import eu.siacs.conversations.xmpp.chatstate.ChatState;
196import eu.siacs.conversations.xmpp.forms.Data;
197import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
198import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
199import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
200import eu.siacs.conversations.xmpp.jingle.Media;
201import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
202import eu.siacs.conversations.xmpp.mam.MamReference;
203import eu.siacs.conversations.xmpp.pep.Avatar;
204import eu.siacs.conversations.xmpp.pep.PublishOptions;
205import im.conversations.android.xmpp.model.stanza.Iq;
206import me.leolin.shortcutbadger.ShortcutBadger;
207
208import okhttp3.HttpUrl;
209import okhttp3.OkHttpClient;
210
211public class XmppConnectionService extends Service {
212
213 public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
214 public static final String ACTION_MARK_AS_READ = "mark_as_read";
215 public static final String ACTION_SNOOZE = "snooze";
216 public static final String ACTION_CLEAR_MESSAGE_NOTIFICATION = "clear_message_notification";
217 public static final String ACTION_CLEAR_MISSED_CALL_NOTIFICATION = "clear_missed_call_notification";
218 public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
219 public static final String ACTION_TRY_AGAIN = "try_again";
220
221 public static final String ACTION_TEMPORARILY_DISABLE = "temporarily_disable";
222 public static final String ACTION_PING = "ping";
223 public static final String ACTION_IDLE_PING = "idle_ping";
224 public static final String ACTION_INTERNAL_PING = "internal_ping";
225 public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
226 public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
227 public static final String ACTION_DISMISS_CALL = "dismiss_call";
228 public static final String ACTION_END_CALL = "end_call";
229 public static final String ACTION_STARTING_CALL = "starting_call";
230 public static final String ACTION_PROVISION_ACCOUNT = "provision_account";
231 public static final String ACTION_CALL_INTEGRATION_SERVICE_STARTED = "call_integration_service_started";
232 private static final String ACTION_POST_CONNECTIVITY_CHANGE = "eu.siacs.conversations.POST_CONNECTIVITY_CHANGE";
233 public static final String ACTION_RENEW_UNIFIED_PUSH_ENDPOINTS = "eu.siacs.conversations.UNIFIED_PUSH_RENEW";
234 public static final String ACTION_QUICK_LOG = "eu.siacs.conversations.QUICK_LOG";
235
236 private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
237
238 public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
239 private final static Executor FILE_OBSERVER_EXECUTOR = Executors.newSingleThreadExecutor();
240 private final static Executor FILE_ATTACHMENT_EXECUTOR = Executors.newSingleThreadExecutor();
241
242 private final ScheduledExecutorService internalPingExecutor = Executors.newSingleThreadScheduledExecutor();
243 private final static SerialSingleThreadExecutor VIDEO_COMPRESSION_EXECUTOR = new SerialSingleThreadExecutor("VideoCompression");
244 private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter");
245 private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader");
246 private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor");
247 private final ReplacingTaskManager mRosterSyncTaskManager = new ReplacingTaskManager();
248 private final IBinder mBinder = new XmppConnectionBinder();
249 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
250 private final IqGenerator mIqGenerator = new IqGenerator(this);
251 private final Set<String> mInProgressAvatarFetches = new HashSet<>();
252 private final Set<String> mOmittedPepAvatarFetches = new HashSet<>();
253 private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
254 private final Consumer<Iq> mDefaultIqHandler = (packet) -> {
255 if (packet.getType() != Iq.Type.RESULT) {
256 final var error = packet.getError();
257 String text = error != null ? error.findChildContent("text") : null;
258 if (text != null) {
259 Log.d(Config.LOGTAG, "received iq error: " + text);
260 }
261 }
262 };
263 public DatabaseBackend databaseBackend;
264 private Multimap<String, String> mutedMucUsers;
265 private final ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor("ContactMerger");
266 private final ReplacingSerialSingleThreadExecutor mStickerScanExecutor = new ReplacingSerialSingleThreadExecutor("StickerScan");
267 private long mLastActivity = 0;
268 private long mLastMucPing = 0;
269 private Map<String, Message> mScheduledMessages = new HashMap<>();
270 private long mLastStickerRescan = 0;
271 private final AppSettings appSettings = new AppSettings(this);
272 private final FileBackend fileBackend = new FileBackend(this);
273 private MemorizingTrustManager mMemorizingTrustManager;
274 private final NotificationService mNotificationService = new NotificationService(this);
275 private final UnifiedPushBroker unifiedPushBroker = new UnifiedPushBroker(this);
276 private final ChannelDiscoveryService mChannelDiscoveryService = new ChannelDiscoveryService(this);
277 private final ShortcutService mShortcutService = new ShortcutService(this);
278 private final AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
279 private final AtomicBoolean mOngoingVideoTranscoding = new AtomicBoolean(false);
280 private final AtomicBoolean mForceDuringOnCreate = new AtomicBoolean(false);
281 private final AtomicReference<OngoingCall> ongoingCall = new AtomicReference<>();
282 private final MessageGenerator mMessageGenerator = new MessageGenerator(this);
283 public OnContactStatusChanged onContactStatusChanged = (contact, online) -> {
284 Conversation conversation = find(getConversations(), contact);
285 if (conversation != null) {
286 if (online) {
287 if (contact.getPresences().size() == 1) {
288 sendUnsentMessages(conversation);
289 }
290 }
291 }
292 };
293 private final PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
294 private List<Account> accounts;
295 private final JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(this);
296 private final HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
297 private final AvatarService mAvatarService = new AvatarService(this);
298 private final MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
299 private final PushManagementService mPushManagementService = new PushManagementService(this);
300 private final QuickConversationsService mQuickConversationsService = new QuickConversationsService(this);
301 private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
302 Environment.getExternalStorageDirectory().getAbsolutePath()
303 ) {
304 @Override
305 public void onEvent(final int event, final File file) {
306 markFileDeleted(file);
307 }
308 };
309 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
310
311 @Override
312 public boolean onMessageAcknowledged(final Account account, final Jid to, final String id) {
313 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
314 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
315 mJingleConnectionManager.updateProposedSessionDiscovered(
316 account,
317 to,
318 sessionId,
319 JingleConnectionManager.DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED
320 );
321 }
322
323
324 final Jid bare = to.asBareJid();
325
326 for (final Conversation conversation : getConversations()) {
327 if (conversation.getAccount() == account && conversation.getJid().asBareJid().equals(bare)) {
328 final Message message = conversation.findUnsentMessageWithUuid(id);
329 if (message != null) {
330 message.setStatus(Message.STATUS_SEND);
331 message.setErrorMessage(null);
332 databaseBackend.updateMessage(message, false);
333 return true;
334 }
335 }
336 }
337 return false;
338 }
339 };
340
341 private final AtomicBoolean diallerIntegrationActive = new AtomicBoolean(false);
342
343 public void setDiallerIntegrationActive(boolean active) {
344 diallerIntegrationActive.set(active);
345 }
346
347 private boolean destroyed = false;
348
349 private int unreadCount = -1;
350
351 //Ui callback listeners
352 private final Set<OnConversationUpdate> mOnConversationUpdates = Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
353 private final Set<OnShowErrorToast> mOnShowErrorToasts = Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
354 private final Set<OnAccountUpdate> mOnAccountUpdates = Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
355 private final Set<OnCaptchaRequested> mOnCaptchaRequested = Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
356 private final Set<OnRosterUpdate> mOnRosterUpdates = Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
357 private final Set<OnUpdateBlocklist> mOnUpdateBlocklist = Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
358 private final Set<OnMucRosterUpdate> mOnMucRosterUpdate = Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
359 private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated = Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
360 private final Set<OnJingleRtpConnectionUpdate> onJingleRtpConnectionUpdate = Collections.newSetFromMap(new WeakHashMap<OnJingleRtpConnectionUpdate, Boolean>());
361
362 private final Object LISTENER_LOCK = new Object();
363
364
365 public final Set<String> FILENAMES_TO_IGNORE_DELETION = new HashSet<>();
366
367
368
369 private final AtomicLong mLastExpiryRun = new AtomicLong(0);
370 private final LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache = new LruCache<>(20);
371 private final OnStatusChanged statusListener = new OnStatusChanged() {
372
373 @Override
374 public void onStatusChanged(final Account account) {
375 XmppConnection connection = account.getXmppConnection();
376 updateAccountUi();
377
378 if (account.getStatus() == Account.State.ONLINE || account.getStatus().isError()) {
379 mQuickConversationsService.signalAccountStateChange();
380 }
381
382 if (account.getStatus() == Account.State.ONLINE) {
383 synchronized (mLowPingTimeoutMode) {
384 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
385 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
386 }
387 }
388 if (account.setShowErrorNotification(true)) {
389 databaseBackend.updateAccount(account);
390 }
391 mMessageArchiveService.executePendingQueries(account);
392 if (connection != null && connection.getFeatures().csi()) {
393 if (checkListeners()) {
394 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//inactive");
395 connection.sendInactive();
396 } else {
397 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//active");
398 connection.sendActive();
399 }
400 }
401 List<Conversation> conversations = getConversations();
402 for (Conversation conversation : conversations) {
403 final boolean inProgressJoin;
404 synchronized (account.inProgressConferenceJoins) {
405 inProgressJoin = account.inProgressConferenceJoins.contains(conversation);
406 }
407 final boolean pendingJoin;
408 synchronized (account.pendingConferenceJoins) {
409 pendingJoin = account.pendingConferenceJoins.contains(conversation);
410 }
411 if (conversation.getAccount() == account
412 && !pendingJoin
413 && !inProgressJoin) {
414 sendUnsentMessages(conversation);
415 }
416 }
417 final List<Conversation> pendingLeaves;
418 synchronized (account.pendingConferenceLeaves) {
419 pendingLeaves = new ArrayList<>(account.pendingConferenceLeaves);
420 account.pendingConferenceLeaves.clear();
421
422 }
423 for (Conversation conversation : pendingLeaves) {
424 leaveMuc(conversation);
425 }
426 final List<Conversation> pendingJoins;
427 synchronized (account.pendingConferenceJoins) {
428 pendingJoins = new ArrayList<>(account.pendingConferenceJoins);
429 account.pendingConferenceJoins.clear();
430 }
431 for (Conversation conversation : pendingJoins) {
432 joinMuc(conversation);
433 }
434 scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
435 } else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED || account.getStatus() == Account.State.LOGGED_OUT) {
436 resetSendingToWaiting(account);
437 if (account.isConnectionEnabled() && isInLowPingTimeoutMode(account)) {
438 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": went into offline state during low ping mode. reconnecting now");
439 reconnectAccount(account, true, false);
440 } else {
441 final int timeToReconnect = SECURE_RANDOM.nextInt(10) + 2;
442 scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
443 }
444 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
445 databaseBackend.updateAccount(account);
446 reconnectAccount(account, true, false);
447 } else if (account.getStatus() != Account.State.CONNECTING && account.getStatus() != Account.State.NO_INTERNET) {
448 resetSendingToWaiting(account);
449 if (connection != null && account.getStatus().isAttemptReconnect()) {
450 final boolean aggressive = account.getStatus() == Account.State.SEE_OTHER_HOST
451 || hasJingleRtpConnection(account);
452 final int next = connection.getTimeToNextAttempt(aggressive);
453 final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
454 if (next <= 0) {
455 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + lowPingTimeoutMode);
456 reconnectAccount(account, true, false);
457 } else {
458 final int attempt = connection.getAttempt() + 1;
459 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + lowPingTimeoutMode+", aggressive="+aggressive);
460 scheduleWakeUpCall(next, account.getUuid().hashCode());
461 if (aggressive) {
462 internalPingExecutor.schedule(
463 XmppConnectionService.this::manageAccountConnectionStatesInternal,
464 (next * 1000L) + 50,
465 TimeUnit.MILLISECONDS
466 );
467 }
468 }
469 }
470 }
471 getNotificationService().updateErrorNotification();
472 }
473 };
474 private OpenPgpServiceConnection pgpServiceConnection;
475 private PgpEngine mPgpEngine = null;
476 private WakeLock wakeLock;
477 private LruCache<String, Drawable> mDrawableCache;
478 private final BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
479 private final BroadcastReceiver mInternalRestrictedEventReceiver = new RestrictedEventReceiver(Arrays.asList(TorServiceUtils.ACTION_STATUS));
480 private final BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
481 private EmojiSearch emojiSearch = null;
482
483 private static String generateFetchKey(Account account, final Avatar avatar) {
484 return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
485 }
486
487 private boolean isInLowPingTimeoutMode(Account account) {
488 synchronized (mLowPingTimeoutMode) {
489 return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
490 }
491 }
492
493 public void startOngoingVideoTranscodingForegroundNotification() {
494 mOngoingVideoTranscoding.set(true);
495 toggleForegroundService();
496 }
497
498 public void stopOngoingVideoTranscodingForegroundNotification() {
499 mOngoingVideoTranscoding.set(false);
500 toggleForegroundService();
501 }
502
503 public boolean areMessagesInitialized() {
504 return this.restoredFromDatabaseLatch.getCount() == 0;
505 }
506
507 public PgpEngine getPgpEngine() {
508 if (!Config.supportOpenPgp()) {
509 return null;
510 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
511 if (this.mPgpEngine == null) {
512 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
513 getApplicationContext(),
514 pgpServiceConnection.getService()), this);
515 }
516 return mPgpEngine;
517 } else {
518 return null;
519 }
520
521 }
522
523 public OpenPgpApi getOpenPgpApi() {
524 if (!Config.supportOpenPgp()) {
525 return null;
526 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
527 return new OpenPgpApi(this, pgpServiceConnection.getService());
528 } else {
529 return null;
530 }
531 }
532
533 public AppSettings getAppSettings() {
534 return this.appSettings;
535 }
536
537 public FileBackend getFileBackend() {
538 return this.fileBackend;
539 }
540
541 public DownloadableFile getFileForCid(Cid cid) {
542 return this.databaseBackend.getFileForCid(cid);
543 }
544
545 public String getUrlForCid(Cid cid) {
546 return this.databaseBackend.getUrlForCid(cid);
547 }
548
549 public void saveCid(Cid cid, File file) throws BlockedMediaException {
550 saveCid(cid, file, null);
551 }
552
553 public void saveCid(Cid cid, File file, String url) throws BlockedMediaException {
554 if (this.databaseBackend.isBlockedMedia(cid)) {
555 throw new BlockedMediaException();
556 }
557 this.databaseBackend.saveCid(cid, file, url);
558 }
559
560 public boolean muteMucUser(MucOptions.User user) {
561 boolean muted = databaseBackend.muteMucUser(user);
562 if (!muted) return false;
563 mutedMucUsers.put(user.getMuc().toString(), user.getOccupantId());
564 return true;
565 }
566
567 public boolean unmuteMucUser(MucOptions.User user) {
568 boolean unmuted = databaseBackend.unmuteMucUser(user);
569 if (!unmuted) return false;
570 mutedMucUsers.remove(user.getMuc().toString(), user.getOccupantId());
571 return true;
572 }
573
574 public boolean isMucUserMuted(MucOptions.User user) {
575 return mutedMucUsers.containsEntry("" + user.getMuc(), user.getOccupantId());
576 }
577
578 public void blockMedia(File f) {
579 try {
580 Cid[] cids = getFileBackend().calculateCids(new FileInputStream(f));
581 for (Cid cid : cids) {
582 blockMedia(cid);
583 }
584 } catch (final IOException e) { }
585 }
586
587 public void blockMedia(Cid cid) {
588 this.databaseBackend.blockMedia(cid);
589 }
590
591 public void clearBlockedMedia() {
592 this.databaseBackend.clearBlockedMedia();
593 }
594
595 public Message getMessage(Conversation conversation, String uuid) {
596 return this.databaseBackend.getMessage(conversation, uuid);
597 }
598
599 public Map<String, Message> getMessageFuzzyIds(Conversation conversation, Collection<String> ids) {
600 return this.databaseBackend.getMessageFuzzyIds(conversation, ids);
601 }
602
603 public void insertWebxdcUpdate(final WebxdcUpdate update) {
604 this.databaseBackend.insertWebxdcUpdate(update);
605 }
606
607 public WebxdcUpdate findLastWebxdcUpdate(Message message) {
608 return this.databaseBackend.findLastWebxdcUpdate(message);
609 }
610
611 public List<WebxdcUpdate> findWebxdcUpdates(Message message, long serial) {
612 return this.databaseBackend.findWebxdcUpdates(message, serial);
613 }
614
615 public AvatarService getAvatarService() {
616 return this.mAvatarService;
617 }
618
619 public void attachLocationToConversation(final Conversation conversation, final Uri uri, final String subject, final UiCallback<Message> callback) {
620 int encryption = conversation.getNextEncryption();
621 if (encryption == Message.ENCRYPTION_PGP) {
622 encryption = Message.ENCRYPTION_DECRYPTED;
623 }
624 Message message = new Message(conversation, uri.toString(), encryption);
625 if (subject != null && subject.length() > 0) message.setSubject(subject);
626 message.setThread(conversation.getThread());
627 Message.configurePrivateMessage(message);
628 if (encryption == Message.ENCRYPTION_DECRYPTED) {
629 getPgpEngine().encrypt(message, callback);
630 } else {
631 sendMessage(message);
632 callback.success(message);
633 }
634 }
635
636 public void attachFileToConversation(final Conversation conversation, final Uri uri, final String type, final String subject, final UiCallback<Message> callback) {
637 final Message message;
638 if (conversation.getReplyTo() == null) {
639 message = new Message(conversation, "", conversation.getNextEncryption());
640 } else {
641 message = conversation.getReplyTo().reply();
642 message.setEncryption(conversation.getNextEncryption());
643 }
644 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
645 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
646 }
647 if (subject != null && subject.length() > 0) message.setSubject(subject);
648 message.setThread(conversation.getThread());
649 if (!Message.configurePrivateFileMessage(message)) {
650 message.setCounterpart(conversation.getNextCounterpart());
651 message.setType(Message.TYPE_FILE);
652 }
653 Log.d(Config.LOGTAG, "attachFile: type=" + message.getType());
654 Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart());
655 final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback);
656 if (runnable.isVideoMessage()) {
657 VIDEO_COMPRESSION_EXECUTOR.execute(runnable);
658 } else {
659 FILE_ATTACHMENT_EXECUTOR.execute(runnable);
660 }
661 }
662
663 public void attachImageToConversation(final Conversation conversation, final Uri uri, final String type, final String subject, final UiCallback<Message> callback) {
664 final String mimeType = MimeUtils.guessMimeTypeFromUriAndMime(this, uri, type);
665 final String compressPictures = getCompressPicturesPreference();
666
667 if ("never".equals(compressPictures)
668 || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
669 || (mimeType != null && mimeType.endsWith("/gif"))
670 || getFileBackend().unusualBounds(uri) || "data".equals(uri.getScheme())) {
671 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": not compressing picture. sending as file");
672 attachFileToConversation(conversation, uri, mimeType, subject, callback);
673 return;
674 }
675 final Message message;
676
677 if (conversation.getReplyTo() == null) {
678 message = new Message(conversation, "", conversation.getNextEncryption());
679 } else {
680 message = conversation.getReplyTo().reply();
681 message.setEncryption(conversation.getNextEncryption());
682 }
683 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
684 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
685 }
686 if (subject != null && subject.length() > 0) message.setSubject(subject);
687 message.setThread(conversation.getThread());
688 if (!Message.configurePrivateFileMessage(message)) {
689 message.setCounterpart(conversation.getNextCounterpart());
690 message.setType(Message.TYPE_IMAGE);
691 }
692 Log.d(Config.LOGTAG, "attachImage: type=" + message.getType());
693 FILE_ATTACHMENT_EXECUTOR.execute(() -> {
694 try {
695 getFileBackend().copyImageToPrivateStorage(message, uri);
696 } catch (FileBackend.ImageCompressionException e) {
697 Log.d(Config.LOGTAG, "unable to compress image. fall back to file transfer", e);
698 attachFileToConversation(conversation, uri, mimeType, subject, callback);
699 return;
700 } catch (final FileBackend.FileCopyException e) {
701 callback.error(e.getResId(), message);
702 return;
703 }
704 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
705 final PgpEngine pgpEngine = getPgpEngine();
706 if (pgpEngine != null) {
707 pgpEngine.encrypt(message, callback);
708 } else if (callback != null) {
709 callback.error(R.string.unable_to_connect_to_keychain, null);
710 }
711 } else {
712 sendMessage(message);
713 callback.success(message);
714 }
715 });
716 }
717
718 private File stickerDir() {
719 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
720 final String dir = p.getString("sticker_directory", "Stickers");
721 if (dir.startsWith("content://")) {
722 Uri uri = Uri.parse(dir);
723 uri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri));
724 return new File(FileUtils.getPath(getBaseContext(), uri));
725 } else {
726 return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir);
727 }
728 }
729
730 public void rescanStickers() {
731 long msToRescan = (mLastStickerRescan + 600000L) - SystemClock.elapsedRealtime();
732 if (msToRescan > 0) return;
733 Log.d(Config.LOGTAG, "rescanStickers");
734
735 mLastStickerRescan = SystemClock.elapsedRealtime();
736 mStickerScanExecutor.execute(() -> {
737 Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
738 try {
739 for (File file : Files.fileTraverser().breadthFirst(stickerDir())) {
740 try {
741 if (file.isFile() && file.canRead()) {
742 DownloadableFile df = new DownloadableFile(file.getAbsolutePath());
743 Drawable icon = fileBackend.getThumbnail(df, getResources(), (int) (getResources().getDisplayMetrics().density * 288), false);
744 final String filename = Files.getNameWithoutExtension(df.getName());
745 Cid[] cids = fileBackend.calculateCids(new FileInputStream(df));
746 for (Cid cid : cids) {
747 saveCid(cid, file);
748 }
749 if (file.length() < 129000) {
750 emojiSearch.addEmoji(new EmojiSearch.CustomEmoji(filename, cids[0].toString(), icon, file.getParentFile().getName()));
751 }
752 }
753 } catch (final Exception e) {
754 Log.w(Config.LOGTAG, "rescanStickers: " + e);
755 }
756 }
757 } catch (final Exception e) {
758 Log.w(Config.LOGTAG, "rescanStickers: " + e);
759 }
760 });
761 }
762
763 protected void cleanupCache() {
764 if (Build.VERSION.SDK_INT < 26) return; // Doesn't support file.toPath
765 mStickerScanExecutor.execute(() -> {
766 Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
767 final var now = System.currentTimeMillis();
768 try {
769 for (File file : Files.fileTraverser().breadthFirst(getCacheDir())) {
770 if (file.isFile() && file.canRead() && file.canWrite()) {
771 final var attrs = java.nio.file.Files.readAttributes(file.toPath(), java.nio.file.attribute.BasicFileAttributes.class);
772 if ((now - attrs.lastAccessTime().toMillis()) > 1000L * 60 * 60 * 24 * 10) {
773 Log.d(Config.LOGTAG, "cleanupCache removing file not used recently: " + file);
774 file.delete();
775 }
776 }
777 }
778 } catch (final Exception e) {
779 Log.w(Config.LOGTAG, "cleanupCache " + e);
780 }
781 });
782 }
783
784 public EmojiSearch emojiSearch() {
785 return emojiSearch;
786 }
787
788 public Conversation find(Bookmark bookmark) {
789 return find(bookmark.getAccount(), bookmark.getJid());
790 }
791
792 public Conversation find(final Account account, final Jid jid) {
793 return find(getConversations(), account, jid);
794 }
795
796 public boolean isMuc(final Account account, final Jid jid) {
797 final Conversation c = find(account, jid);
798 return c != null && c.getMode() == Conversational.MODE_MULTI;
799 }
800
801 public void search(final List<String> term, final String uuid, final OnSearchResultsAvailable onSearchResultsAvailable) {
802 MessageSearchTask.search(this, term, uuid, onSearchResultsAvailable);
803 }
804
805 @Override
806 public int onStartCommand(final Intent intent, int flags, int startId) {
807 final String action = Strings.nullToEmpty(intent == null ? null : intent.getAction());
808 final boolean needsForegroundService = intent != null && intent.getBooleanExtra(SystemEventReceiver.EXTRA_NEEDS_FOREGROUND_SERVICE, false);
809 if (needsForegroundService) {
810 Log.d(Config.LOGTAG, "toggle forced foreground service after receiving event (action=" + action + ")");
811 toggleForegroundService(true, action.equals(ACTION_STARTING_CALL));
812 }
813 final String uuid = intent == null ? null : intent.getStringExtra("uuid");
814 switch (action) {
815 case QuickConversationsService.SMS_RETRIEVED_ACTION:
816 mQuickConversationsService.handleSmsReceived(intent);
817 break;
818 case ConnectivityManager.CONNECTIVITY_ACTION:
819 if (hasInternetConnection()) {
820 if (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0) {
821 schedulePostConnectivityChange();
822 }
823 if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
824 resetAllAttemptCounts(true, false);
825 }
826 Resolver.clearCache();
827 }
828 break;
829 case Intent.ACTION_SHUTDOWN:
830 logoutAndSave(true);
831 return START_NOT_STICKY;
832 case ACTION_CLEAR_MESSAGE_NOTIFICATION:
833 mNotificationExecutor.execute(() -> {
834 try {
835 final Conversation c = findConversationByUuid(uuid);
836 if (c != null) {
837 mNotificationService.clearMessages(c);
838 } else {
839 mNotificationService.clearMessages();
840 }
841 restoredFromDatabaseLatch.await();
842
843 } catch (InterruptedException e) {
844 Log.d(Config.LOGTAG, "unable to process clear message notification");
845 }
846 });
847 break;
848 case ACTION_CLEAR_MISSED_CALL_NOTIFICATION:
849 mNotificationExecutor.execute(() -> {
850 try {
851 final Conversation c = findConversationByUuid(uuid);
852 if (c != null) {
853 mNotificationService.clearMissedCalls(c);
854 } else {
855 mNotificationService.clearMissedCalls();
856 }
857 restoredFromDatabaseLatch.await();
858
859 } catch (InterruptedException e) {
860 Log.d(Config.LOGTAG, "unable to process clear missed call notification");
861 }
862 });
863 break;
864 case ACTION_DISMISS_CALL: {
865 if (intent == null) {
866 break;
867 }
868 final String sessionId = intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
869 Log.d(Config.LOGTAG, "received intent to dismiss call with session id " + sessionId);
870 mJingleConnectionManager.rejectRtpSession(sessionId);
871 break;
872 }
873 case TorServiceUtils.ACTION_STATUS:
874 final String status = intent == null ? null : intent.getStringExtra(TorServiceUtils.EXTRA_STATUS);
875 //TODO port and host are in 'extras' - but this may not be a reliable source?
876 if ("ON".equals(status)) {
877 handleOrbotStartedEvent();
878 return START_STICKY;
879 }
880 break;
881 case ACTION_END_CALL: {
882 if (intent == null) {
883 break;
884 }
885 final String sessionId = intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
886 Log.d(Config.LOGTAG, "received intent to end call with session id " + sessionId);
887 mJingleConnectionManager.endRtpSession(sessionId);
888 }
889 break;
890 case ACTION_PROVISION_ACCOUNT: {
891 if (intent == null) {
892 break;
893 }
894 final String address = intent.getStringExtra("address");
895 final String password = intent.getStringExtra("password");
896 if (QuickConversationsService.isQuicksy() || Strings.isNullOrEmpty(address) || Strings.isNullOrEmpty(password)) {
897 break;
898 }
899 provisionAccount(address, password);
900 break;
901 }
902 case ACTION_DISMISS_ERROR_NOTIFICATIONS:
903 dismissErrorNotifications();
904 break;
905 case ACTION_TRY_AGAIN:
906 resetAllAttemptCounts(false, true);
907 break;
908 case ACTION_REPLY_TO_CONVERSATION:
909 final Bundle remoteInput = intent == null ? null : RemoteInput.getResultsFromIntent(intent);
910 if (remoteInput == null) {
911 break;
912 }
913 final CharSequence body = remoteInput.getCharSequence("text_reply");
914 final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
915 final String lastMessageUuid = intent.getStringExtra("last_message_uuid");
916 if (body == null || body.length() <= 0) {
917 break;
918 }
919 mNotificationExecutor.execute(() -> {
920 try {
921 restoredFromDatabaseLatch.await();
922 final Conversation c = findConversationByUuid(uuid);
923 if (c != null) {
924 directReply(c, body.toString(), lastMessageUuid, dismissNotification);
925 }
926 } catch (InterruptedException e) {
927 Log.d(Config.LOGTAG, "unable to process direct reply");
928 }
929 });
930 break;
931 case ACTION_MARK_AS_READ:
932 mNotificationExecutor.execute(() -> {
933 final Conversation c = findConversationByUuid(uuid);
934 if (c == null) {
935 Log.d(Config.LOGTAG, "received mark read intent for unknown conversation (" + uuid + ")");
936 return;
937 }
938 try {
939 restoredFromDatabaseLatch.await();
940 sendReadMarker(c, null);
941 } catch (InterruptedException e) {
942 Log.d(Config.LOGTAG, "unable to process notification read marker for conversation " + c.getName());
943 }
944
945 });
946 break;
947 case ACTION_SNOOZE:
948 mNotificationExecutor.execute(() -> {
949 final Conversation c = findConversationByUuid(uuid);
950 if (c == null) {
951 Log.d(Config.LOGTAG, "received snooze intent for unknown conversation (" + uuid + ")");
952 return;
953 }
954 c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
955 mNotificationService.clearMessages(c);
956 updateConversation(c);
957 });
958 case AudioManager.RINGER_MODE_CHANGED_ACTION:
959 case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
960 if (dndOnSilentMode()) {
961 refreshAllPresences();
962 }
963 break;
964 case Intent.ACTION_SCREEN_ON:
965 deactivateGracePeriod();
966 case Intent.ACTION_USER_PRESENT:
967 case Intent.ACTION_SCREEN_OFF:
968 if (awayWhenScreenLocked()) {
969 refreshAllPresences();
970 }
971 break;
972 case ACTION_FCM_TOKEN_REFRESH:
973 refreshAllFcmTokens();
974 break;
975 case ACTION_RENEW_UNIFIED_PUSH_ENDPOINTS:
976 if (intent == null) {
977 break;
978 }
979 final String instance = intent.getStringExtra("instance");
980 final String application = intent.getStringExtra("application");
981 final Messenger messenger = intent.getParcelableExtra("messenger");
982 final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger;
983 if (messenger != null && application != null && instance != null) {
984 pushTargetMessenger = new UnifiedPushBroker.PushTargetMessenger(new UnifiedPushDatabase.PushTarget(application, instance),messenger);
985 Log.d(Config.LOGTAG,"found push target messenger");
986 } else {
987 pushTargetMessenger = null;
988 }
989 final Optional<UnifiedPushBroker.Transport> transport = renewUnifiedPushEndpoints(pushTargetMessenger);
990 if (instance != null && transport.isPresent()) {
991 unifiedPushBroker.rebroadcastEndpoint(messenger, instance, transport.get());
992 }
993 break;
994 case ACTION_IDLE_PING:
995 scheduleNextIdlePing();
996 break;
997 case ACTION_FCM_MESSAGE_RECEIVED:
998 Log.d(Config.LOGTAG, "push message arrived in service. account");
999 break;
1000 case ACTION_QUICK_LOG:
1001 final String message = intent == null ? null : intent.getStringExtra("message");
1002 if (message != null && Config.QUICK_LOG) {
1003 quickLog(message);
1004 }
1005 break;
1006 case Intent.ACTION_SEND:
1007 final Uri uri = intent == null ? null : intent.getData();
1008 if (uri != null) {
1009 Log.d(Config.LOGTAG, "received uri permission for " + uri);
1010 }
1011 return START_STICKY;
1012 case ACTION_TEMPORARILY_DISABLE:
1013 toggleSoftDisabled(true);
1014 if (checkListeners()) {
1015 stopSelf();
1016 }
1017 return START_NOT_STICKY;
1018 }
1019 sendScheduledMessages();
1020 final var extras = intent == null ? null : intent.getExtras();
1021 try {
1022 internalPingExecutor.execute(() -> manageAccountConnectionStates(action, extras));
1023 } catch (final RejectedExecutionException e) {
1024 Log.e(Config.LOGTAG, "can not schedule connection states manager");
1025 }
1026 if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
1027 expireOldMessages();
1028 }
1029 return START_STICKY;
1030 }
1031
1032 private void quickLog(final String message) {
1033 if (Strings.isNullOrEmpty(message)) {
1034 return;
1035 }
1036 final Account account = AccountUtils.getFirstEnabled(this);
1037 if (account == null) {
1038 return;
1039 }
1040 final Conversation conversation =
1041 findOrCreateConversation(account, Config.BUG_REPORTS, false, true);
1042 final Message report = new Message(conversation, message, Message.ENCRYPTION_NONE);
1043 report.setStatus(Message.STATUS_RECEIVED);
1044 conversation.add(report);
1045 databaseBackend.createMessage(report);
1046 updateConversationUi();
1047 }
1048
1049 private void manageAccountConnectionStatesInternal() {
1050 manageAccountConnectionStates(ACTION_INTERNAL_PING, null);
1051 }
1052
1053 private synchronized void manageAccountConnectionStates(
1054 final String action, final Bundle extras) {
1055 final String pushedAccountHash = extras == null ? null : extras.getString("account");
1056 final boolean interactive = java.util.Objects.equals(ACTION_TRY_AGAIN, action);
1057 WakeLockHelper.acquire(wakeLock);
1058 boolean pingNow =
1059 ConnectivityManager.CONNECTIVITY_ACTION.equals(action)
1060 || (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0
1061 && ACTION_POST_CONNECTIVITY_CHANGE.equals(action));
1062 final HashSet<Account> pingCandidates = new HashSet<>();
1063 final String androidId = pushedAccountHash == null ? null : PhoneHelper.getAndroidId(this);
1064 for (final Account account : accounts) {
1065 final boolean pushWasMeantForThisAccount =
1066 androidId != null
1067 && CryptoHelper.getAccountFingerprint(account, androidId)
1068 .equals(pushedAccountHash);
1069 pingNow |=
1070 processAccountState(
1071 account,
1072 interactive,
1073 "ui".equals(action),
1074 pushWasMeantForThisAccount,
1075 pingCandidates);
1076 }
1077 if (pingNow) {
1078 for (final Account account : pingCandidates) {
1079 final boolean lowTimeout = isInLowPingTimeoutMode(account);
1080 account.getXmppConnection().sendPing();
1081 Log.d(
1082 Config.LOGTAG,
1083 account.getJid().asBareJid()
1084 + " send ping (action="
1085 + action
1086 + ",lowTimeout="
1087 + lowTimeout
1088 + ")");
1089 scheduleWakeUpCall(
1090 lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT,
1091 account.getUuid().hashCode());
1092 }
1093 long msToMucPing = (mLastMucPing + (Config.PING_MAX_INTERVAL * 2000L)) - SystemClock.elapsedRealtime();
1094 if (msToMucPing <= 0) {
1095 Log.d(Config.LOGTAG, "ping MUCs");
1096 mLastMucPing = SystemClock.elapsedRealtime();
1097 for (Conversation c : getConversations()) {
1098 if (c.getMode() == Conversation.MODE_MULTI && (c.getMucOptions().online() || c.getMucOptions().getError() == MucOptions.Error.SHUTDOWN)) {
1099 mucSelfPingAndRejoin(c);
1100 }
1101 }
1102 }
1103 }
1104 WakeLockHelper.release(wakeLock);
1105 }
1106
1107 private void sendScheduledMessages() {
1108 Log.d(Config.LOGTAG, "looking for and sending scheduled messages");
1109
1110 for (final var message : new ArrayList<>(mScheduledMessages.values())) {
1111 if (message.getTimeSent() > System.currentTimeMillis()) continue;
1112
1113 final var conversation = message.getConversation();
1114 final var account = conversation.getAccount();
1115 final boolean inProgressJoin;
1116 synchronized (account.inProgressConferenceJoins) {
1117 inProgressJoin = account.inProgressConferenceJoins.contains(conversation);
1118 }
1119 final boolean pendingJoin;
1120 synchronized (account.pendingConferenceJoins) {
1121 pendingJoin = account.pendingConferenceJoins.contains(conversation);
1122 }
1123 if (conversation.getAccount() == account
1124 && !pendingJoin
1125 && !inProgressJoin) {
1126 resendMessage(message, false);
1127 }
1128 }
1129 }
1130
1131 private void handleOrbotStartedEvent() {
1132 for (final Account account : accounts) {
1133 if (account.getStatus() == Account.State.TOR_NOT_AVAILABLE) {
1134 reconnectAccount(account, true, false);
1135 }
1136 }
1137 }
1138
1139 private boolean processAccountState(final Account account, final boolean interactive, final boolean isUiAction, final boolean isAccountPushed, final HashSet<Account> pingCandidates) {
1140 if (!account.getStatus().isAttemptReconnect()) {
1141 return false;
1142 }
1143 if (!hasInternetConnection()) {
1144 account.setStatus(Account.State.NO_INTERNET);
1145 statusListener.onStatusChanged(account);
1146 } else {
1147 if (account.getStatus() == Account.State.NO_INTERNET) {
1148 account.setStatus(Account.State.OFFLINE);
1149 statusListener.onStatusChanged(account);
1150 }
1151 if (account.getStatus() == Account.State.ONLINE) {
1152 synchronized (mLowPingTimeoutMode) {
1153 long lastReceived = account.getXmppConnection().getLastPacketReceived();
1154 long lastSent = account.getXmppConnection().getLastPingSent();
1155 long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
1156 long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
1157 int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().asBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
1158 long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
1159 if (lastSent > lastReceived) {
1160 if (pingTimeoutIn < 0) {
1161 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
1162 this.reconnectAccount(account, true, interactive);
1163 } else {
1164 int secs = (int) (pingTimeoutIn / 1000);
1165 this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
1166 }
1167 } else {
1168 pingCandidates.add(account);
1169 if (isAccountPushed) {
1170 if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
1171 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": entering low ping timeout mode");
1172 }
1173 return true;
1174 } else if (msToNextPing <= 0) {
1175 return true;
1176 } else {
1177 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
1178 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
1179 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
1180 }
1181 }
1182 }
1183 }
1184 } else if (account.getStatus() == Account.State.OFFLINE) {
1185 reconnectAccount(account, true, interactive);
1186 } else if (account.getStatus() == Account.State.CONNECTING) {
1187 long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
1188 long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
1189 long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
1190 long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
1191 if (!areMessagesInitialized()) return false; // No point in thrashing a reconnect while still loading
1192 if (timeout < 0) {
1193 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast=" + secondsSinceLastConnect + ")");
1194 account.getXmppConnection().resetAttemptCount(false);
1195 reconnectAccount(account, true, interactive);
1196 } else if (discoTimeout < 0) {
1197 account.getXmppConnection().sendDiscoTimeout();
1198 scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
1199 } else {
1200 scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
1201 }
1202 } else {
1203 final boolean aggressive = account.getStatus() == Account.State.SEE_OTHER_HOST || hasJingleRtpConnection(account);
1204 if (account.getXmppConnection().getTimeToNextAttempt(aggressive) <= 0) {
1205 reconnectAccount(account, true, interactive);
1206 }
1207 }
1208 }
1209 return false;
1210 }
1211
1212 private void toggleSoftDisabled(final boolean softDisabled) {
1213 for(final Account account : this.accounts) {
1214 if (account.isEnabled()) {
1215 if (account.setOption(Account.OPTION_SOFT_DISABLED, softDisabled)) {
1216 updateAccount(account);
1217 }
1218 }
1219 }
1220 }
1221
1222 public boolean processUnifiedPushMessage(final Account account, final Jid transport, final Element push) {
1223 return unifiedPushBroker.processPushMessage(account, transport, push);
1224 }
1225
1226 public void reinitializeMuclumbusService() {
1227 mChannelDiscoveryService.initializeMuclumbusService();
1228 }
1229
1230 public void discoverChannels(String query, ChannelDiscoveryService.Method method, Map<Jid, Account> mucServices, ChannelDiscoveryService.OnChannelSearchResultsFound onChannelSearchResultsFound) {
1231 mChannelDiscoveryService.discover(Strings.nullToEmpty(query).trim(), method, mucServices, onChannelSearchResultsFound);
1232 }
1233
1234 public boolean isDataSaverDisabled() {
1235 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
1236 return true;
1237 }
1238 final ConnectivityManager connectivityManager = getSystemService(ConnectivityManager.class);
1239 return !Compatibility.isActiveNetworkMetered(connectivityManager)
1240 || Compatibility.getRestrictBackgroundStatus(connectivityManager)
1241 == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
1242 }
1243
1244 private void directReply(final Conversation conversation, final String body, final String lastMessageUuid, final boolean dismissAfterReply) {
1245 final Message inReplyTo = lastMessageUuid == null ? null : conversation.findMessageWithUuid(lastMessageUuid);
1246 Message message = new Message(conversation, body, conversation.getNextEncryption());
1247 if (inReplyTo != null) {
1248 if (Emoticons.isEmoji(body.replaceAll("\\s", ""))) {
1249 final var aggregated = inReplyTo.getAggregatedReactions();
1250 final ImmutableSet.Builder<String> reactionBuilder = new ImmutableSet.Builder<>();
1251 reactionBuilder.addAll(aggregated.ourReactions);
1252 reactionBuilder.add(body.replaceAll("\\s", ""));
1253 sendReactions(inReplyTo, reactionBuilder.build());
1254 return;
1255 } else {
1256 message = inReplyTo.reply();
1257 }
1258 message.clearFallbacks("urn:xmpp:reply:0");
1259 message.setBody(body);
1260 message.setEncryption(conversation.getNextEncryption());
1261 }
1262 if (inReplyTo != null && inReplyTo.isPrivateMessage()) {
1263 Message.configurePrivateMessage(message, inReplyTo.getCounterpart());
1264 }
1265 message.markUnread();
1266 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
1267 getPgpEngine().encrypt(message, new UiCallback<Message>() {
1268 @Override
1269 public void success(Message message) {
1270 if (dismissAfterReply) {
1271 markRead((Conversation) message.getConversation(), true);
1272 } else {
1273 mNotificationService.pushFromDirectReply(message);
1274 }
1275 }
1276
1277 @Override
1278 public void error(int errorCode, Message object) {
1279
1280 }
1281
1282 @Override
1283 public void userInputRequired(PendingIntent pi, Message object) {
1284
1285 }
1286 });
1287 } else {
1288 sendMessage(message);
1289 if (dismissAfterReply) {
1290 markRead(conversation, true);
1291 } else {
1292 mNotificationService.pushFromDirectReply(message);
1293 }
1294 }
1295 }
1296
1297 private boolean dndOnSilentMode() {
1298 return getBooleanPreference(AppSettings.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
1299 }
1300
1301 private boolean manuallyChangePresence() {
1302 return getBooleanPreference(AppSettings.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
1303 }
1304
1305 private boolean treatVibrateAsSilent() {
1306 return getBooleanPreference(AppSettings.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
1307 }
1308
1309 private boolean awayWhenScreenLocked() {
1310 return getBooleanPreference(AppSettings.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
1311 }
1312
1313 private String getCompressPicturesPreference() {
1314 return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
1315 }
1316
1317 private Presence.Status getTargetPresence() {
1318 if (dndOnSilentMode() && isPhoneSilenced()) {
1319 return Presence.Status.DND;
1320 } else if (awayWhenScreenLocked() && isScreenLocked()) {
1321 return Presence.Status.AWAY;
1322 } else {
1323 return Presence.Status.ONLINE;
1324 }
1325 }
1326
1327 public boolean isScreenLocked() {
1328 final KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
1329 final PowerManager powerManager = getSystemService(PowerManager.class);
1330 final boolean locked = keyguardManager != null && keyguardManager.isKeyguardLocked();
1331 final boolean interactive;
1332 try {
1333 interactive = powerManager != null && powerManager.isInteractive();
1334 } catch (final Exception e) {
1335 return false;
1336 }
1337 return locked || !interactive;
1338 }
1339
1340 private boolean isPhoneSilenced() {
1341 final NotificationManager notificationManager = getSystemService(NotificationManager.class);
1342 final int filter = notificationManager == null ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN : notificationManager.getCurrentInterruptionFilter();
1343 final boolean notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
1344 final AudioManager audioManager = getSystemService(AudioManager.class);
1345 final int ringerMode = audioManager == null ? AudioManager.RINGER_MODE_NORMAL : audioManager.getRingerMode();
1346 try {
1347 if (treatVibrateAsSilent()) {
1348 return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
1349 } else {
1350 return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
1351 }
1352 } catch (final Throwable throwable) {
1353 Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
1354 return notificationDnd;
1355 }
1356 }
1357
1358 private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
1359 Log.d(Config.LOGTAG, "resetting all attempt counts");
1360 for (Account account : accounts) {
1361 if (account.hasErrorStatus() || reallyAll) {
1362 final XmppConnection connection = account.getXmppConnection();
1363 if (connection != null) {
1364 connection.resetAttemptCount(retryImmediately);
1365 }
1366 }
1367 if (account.setShowErrorNotification(true)) {
1368 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1369 }
1370 }
1371 mNotificationService.updateErrorNotification();
1372 }
1373
1374 private void dismissErrorNotifications() {
1375 for (final Account account : this.accounts) {
1376 if (account.hasErrorStatus()) {
1377 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
1378 if (account.setShowErrorNotification(false)) {
1379 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1380 }
1381 }
1382 }
1383 }
1384
1385 private void expireOldMessages() {
1386 expireOldMessages(false);
1387 }
1388
1389 public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
1390 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1391 mDatabaseWriterExecutor.execute(() -> {
1392 long timestamp = getAutomaticMessageDeletionDate();
1393 if (timestamp > 0) {
1394 databaseBackend.expireOldMessages(timestamp);
1395 synchronized (XmppConnectionService.this.conversations) {
1396 for (Conversation conversation : XmppConnectionService.this.conversations) {
1397 conversation.expireOldMessages(timestamp);
1398 if (resetHasMessagesLeftOnServer) {
1399 conversation.messagesLoaded.set(true);
1400 conversation.setHasMessagesLeftOnServer(true);
1401 }
1402 }
1403 }
1404 updateConversationUi();
1405 }
1406 });
1407 }
1408
1409 public boolean hasInternetConnection() {
1410 final ConnectivityManager cm = ContextCompat.getSystemService(this, ConnectivityManager.class);
1411 if (cm == null) {
1412 return true; //if internet connection can not be checked it is probably best to just try
1413 }
1414 try {
1415 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
1416 final Network activeNetwork = cm.getActiveNetwork();
1417 final NetworkCapabilities capabilities = activeNetwork == null ? null : cm.getNetworkCapabilities(activeNetwork);
1418 return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1419 } else {
1420 final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
1421 return networkInfo != null && (networkInfo.isConnected() || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET);
1422 }
1423 } catch (final RuntimeException e) {
1424 Log.d(Config.LOGTAG, "unable to check for internet connection", e);
1425 return true; //if internet connection can not be checked it is probably best to just try
1426 }
1427 }
1428
1429 @SuppressLint("TrulyRandom")
1430 @Override
1431 public void onCreate() {
1432 com.cheogram.android.AndroidLoggingHandler.reset(new com.cheogram.android.AndroidLoggingHandler());
1433 java.util.logging.Logger.getLogger("").setLevel(java.util.logging.Level.FINEST);
1434 LibIdnXmppStringprep.setup();
1435 emojiSearch = new EmojiSearch(this);
1436 setTheme(R.style.Theme_Conversations3);
1437 ThemeHelper.applyCustomColors(this);
1438 if (Compatibility.runsTwentySix()) {
1439 mNotificationService.initializeChannels();
1440 }
1441 mChannelDiscoveryService.initializeMuclumbusService();
1442 mForceDuringOnCreate.set(Compatibility.runsAndTargetsTwentySix(this));
1443 toggleForegroundService();
1444 this.destroyed = false;
1445 OmemoSetting.load(this);
1446 try {
1447 Security.insertProviderAt(Conscrypt.newProvider(), 1);
1448 } catch (Throwable throwable) {
1449 Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
1450 }
1451 Resolver.init(this);
1452 updateMemorizingTrustManager();
1453 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
1454 final int cacheSize = maxMemory / 8;
1455 this.mDrawableCache = new LruCache<String, Drawable>(cacheSize) {
1456 @Override
1457 protected int sizeOf(final String key, final Drawable drawable) {
1458 if (drawable instanceof BitmapDrawable) {
1459 Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
1460 if (bitmap == null) return 1024;
1461
1462 return bitmap.getByteCount() / 1024;
1463 } else if (drawable instanceof AvatarService.TextDrawable) {
1464 return 50;
1465 } else {
1466 return drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight() * 40 / 1024;
1467 }
1468 }
1469 };
1470 if (mLastActivity == 0) {
1471 mLastActivity = getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
1472 }
1473
1474 Log.d(Config.LOGTAG, "initializing database...");
1475 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
1476 Log.d(Config.LOGTAG, "restoring accounts...");
1477 this.accounts = databaseBackend.getAccounts();
1478 for (Account account : this.accounts) {
1479 final int color = getPreferences().getInt("account_color:" + account.getUuid(), 0);
1480 if (color != 0) account.setColor(color);
1481 }
1482 final SharedPreferences.Editor editor = getPreferences().edit();
1483 final boolean hasEnabledAccounts = hasEnabledAccounts();
1484 editor.putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
1485 editor.apply();
1486 toggleSetProfilePictureActivity(hasEnabledAccounts);
1487 reconfigurePushDistributor();
1488
1489 if (CallIntegration.hasSystemFeature(this)) {
1490 CallIntegrationConnectionService.togglePhoneAccountsAsync(this, this.accounts);
1491 }
1492
1493 restoreFromDatabase();
1494
1495 if (QuickConversationsService.isContactListIntegration(this)
1496 && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
1497 == PackageManager.PERMISSION_GRANTED) {
1498 startContactObserver();
1499 }
1500 FILE_OBSERVER_EXECUTOR.execute(fileBackend::deleteHistoricAvatarPath);
1501 if (Compatibility.hasStoragePermission(this)) {
1502 Log.d(Config.LOGTAG, "starting file observer");
1503 FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::startWatching);
1504 FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1505 }
1506 if (Config.supportOpenPgp()) {
1507 this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
1508 @Override
1509 public void onBound(final IOpenPgpService2 service) {
1510 for (Account account : accounts) {
1511 final PgpDecryptionService pgp = account.getPgpDecryptionService();
1512 if (pgp != null) {
1513 pgp.continueDecryption(true);
1514 }
1515 }
1516 }
1517
1518 @Override
1519 public void onError(final Exception exception) {
1520 Log.e(Config.LOGTAG,"could not bind to OpenKeyChain", exception);
1521 }
1522 });
1523 this.pgpServiceConnection.bindToService();
1524 }
1525
1526 final PowerManager powerManager = getSystemService(PowerManager.class);
1527 if (powerManager != null) {
1528 this.wakeLock =
1529 powerManager.newWakeLock(
1530 PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1531 }
1532
1533 toggleForegroundService();
1534 updateUnreadCountBadge();
1535 toggleScreenEventReceiver();
1536 final IntentFilter systemBroadcastFilter = new IntentFilter();
1537 scheduleNextIdlePing();
1538 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1539 systemBroadcastFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1540 }
1541 systemBroadcastFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1542 ContextCompat.registerReceiver(
1543 this,
1544 this.mInternalEventReceiver,
1545 systemBroadcastFilter,
1546 ContextCompat.RECEIVER_NOT_EXPORTED);
1547 final IntentFilter exportedBroadcastFilter = new IntentFilter();
1548 exportedBroadcastFilter.addAction(TorServiceUtils.ACTION_STATUS);
1549 ContextCompat.registerReceiver(
1550 this,
1551 this.mInternalRestrictedEventReceiver,
1552 exportedBroadcastFilter,
1553 ContextCompat.RECEIVER_EXPORTED);
1554 mForceDuringOnCreate.set(false);
1555 toggleForegroundService();
1556 rescanStickers();
1557 cleanupCache();
1558 internalPingExecutor.scheduleAtFixedRate(this::manageAccountConnectionStatesInternal,10,10,TimeUnit.SECONDS);
1559 final SharedPreferences sharedPreferences =
1560 androidx.preference.PreferenceManager.getDefaultSharedPreferences(this);
1561 sharedPreferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
1562 @Override
1563 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, @Nullable String key) {
1564 Log.d(Config.LOGTAG,"preference '"+key+"' has changed");
1565 if (AppSettings.KEEP_FOREGROUND_SERVICE.equals(key)) {
1566 toggleForegroundService();
1567 }
1568 }
1569 });
1570 }
1571
1572
1573 private void checkForDeletedFiles() {
1574 if (destroyed) {
1575 Log.d(Config.LOGTAG, "Do not check for deleted files because service has been destroyed");
1576 return;
1577 }
1578 final long start = SystemClock.elapsedRealtime();
1579 final List<DatabaseBackend.FilePathInfo> relativeFilePaths = databaseBackend.getFilePathInfo();
1580 final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1581 for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1582 if (destroyed) {
1583 Log.d(Config.LOGTAG, "Stop checking for deleted files because service has been destroyed");
1584 return;
1585 }
1586 final File file = fileBackend.getFileForPath(filePath.path);
1587 if (filePath.setDeleted(!file.exists())) {
1588 changed.add(filePath);
1589 }
1590 }
1591 final long duration = SystemClock.elapsedRealtime() - start;
1592 Log.d(Config.LOGTAG, "found " + changed.size() + " changed files on start up. total=" + relativeFilePaths.size() + ". (" + duration + "ms)");
1593 if (changed.size() > 0) {
1594 databaseBackend.markFilesAsChanged(changed);
1595 markChangedFiles(changed);
1596 }
1597 }
1598
1599 public void startContactObserver() {
1600 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) {
1601 @Override
1602 public void onChange(boolean selfChange) {
1603 super.onChange(selfChange);
1604 if (restoredFromDatabaseLatch.getCount() == 0) {
1605 loadPhoneContacts();
1606 }
1607 }
1608 });
1609 }
1610
1611 @Override
1612 public void onTrimMemory(int level) {
1613 super.onTrimMemory(level);
1614 if (level >= TRIM_MEMORY_COMPLETE) {
1615 Log.d(Config.LOGTAG, "clear cache due to low memory");
1616 getDrawableCache().evictAll();
1617 }
1618 }
1619
1620 @Override
1621 public void onDestroy() {
1622 try {
1623 unregisterReceiver(this.mInternalEventReceiver);
1624 unregisterReceiver(this.mInternalRestrictedEventReceiver);
1625 unregisterReceiver(this.mInternalScreenEventReceiver);
1626 } catch (final IllegalArgumentException e) {
1627 //ignored
1628 }
1629 destroyed = false;
1630 fileObserver.stopWatching();
1631 internalPingExecutor.shutdown();
1632 super.onDestroy();
1633 }
1634
1635 public void restartFileObserver() {
1636 Log.d(Config.LOGTAG, "restarting file observer");
1637 FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::restartWatching);
1638 FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1639 }
1640
1641 public void toggleScreenEventReceiver() {
1642 if (awayWhenScreenLocked() && !manuallyChangePresence()) {
1643 final IntentFilter filter = new IntentFilter();
1644 filter.addAction(Intent.ACTION_SCREEN_ON);
1645 filter.addAction(Intent.ACTION_SCREEN_OFF);
1646 filter.addAction(Intent.ACTION_USER_PRESENT);
1647 registerReceiver(this.mInternalScreenEventReceiver, filter);
1648 } else {
1649 try {
1650 unregisterReceiver(this.mInternalScreenEventReceiver);
1651 } catch (IllegalArgumentException e) {
1652 //ignored
1653 }
1654 }
1655 }
1656
1657 public void toggleForegroundService() {
1658 toggleForegroundService(false, false);
1659 }
1660
1661 public void setOngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
1662 ongoingCall.set(new OngoingCall(id, media, reconnecting));
1663 toggleForegroundService(false, true);
1664 }
1665
1666 public void removeOngoingCall() {
1667 ongoingCall.set(null);
1668 toggleForegroundService(false, false);
1669 }
1670
1671 private void toggleForegroundService(boolean force, boolean needMic) {
1672 final boolean status;
1673 final OngoingCall ongoing = ongoingCall.get();
1674 final boolean ongoingVideoTranscoding = mOngoingVideoTranscoding.get();
1675 final int id;
1676 if (force
1677 || mForceDuringOnCreate.get()
1678 || ongoingVideoTranscoding
1679 || ongoing != null
1680 || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1681 final Notification notification;
1682 if (ongoing != null && !diallerIntegrationActive.get()) {
1683 notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1684 id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1685 startForegroundOrCatch(id, notification, true);
1686 } else if (ongoingVideoTranscoding) {
1687 notification = this.mNotificationService.getIndeterminateVideoTranscoding();
1688 id = NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID;
1689 startForegroundOrCatch(id, notification, false);
1690 } else {
1691 notification = this.mNotificationService.createForegroundNotification();
1692 id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1693 startForegroundOrCatch(id, notification, needMic || ongoing != null || diallerIntegrationActive.get());
1694 }
1695 mNotificationService.notify(id, notification);
1696 status = true;
1697 } else {
1698 id = 0;
1699 stopForeground(true);
1700 status = false;
1701 }
1702
1703 for (final int toBeRemoved :
1704 Collections2.filter(
1705 Arrays.asList(
1706 NotificationService.FOREGROUND_NOTIFICATION_ID,
1707 NotificationService.ONGOING_CALL_NOTIFICATION_ID,
1708 NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID),
1709 i -> i != id)) {
1710 mNotificationService.cancel(toBeRemoved);
1711 }
1712 Log.d(
1713 Config.LOGTAG,
1714 "ForegroundService: " + (status ? "on" : "off") + ", notification: " + id);
1715 }
1716
1717 private void startForegroundOrCatch(
1718 final int id, final Notification notification, final boolean requireMicrophone) {
1719 try {
1720 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
1721 final int foregroundServiceType;
1722 if (requireMicrophone
1723 && ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1724 == PackageManager.PERMISSION_GRANTED) {
1725 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1726 Log.d(Config.LOGTAG, "defaulting to microphone foreground service type");
1727 } else if (getSystemService(PowerManager.class)
1728 .isIgnoringBatteryOptimizations(getPackageName())) {
1729 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED;
1730 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1731 == PackageManager.PERMISSION_GRANTED) {
1732 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1733 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
1734 == PackageManager.PERMISSION_GRANTED) {
1735 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;
1736 } else {
1737 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
1738 Log.w(Config.LOGTAG, "falling back to special use foreground service type");
1739 }
1740
1741 startForeground(id, notification, foregroundServiceType);
1742 } else {
1743 startForeground(id, notification);
1744 }
1745 } catch (final IllegalStateException | SecurityException e) {
1746 Log.e(Config.LOGTAG, "Could not start foreground service", e);
1747 }
1748 }
1749
1750 public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1751 return !mOngoingVideoTranscoding.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1752 }
1753
1754 @Override
1755 public void onTaskRemoved(final Intent rootIntent) {
1756 super.onTaskRemoved(rootIntent);
1757 if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mOngoingVideoTranscoding.get() || ongoingCall.get() != null) {
1758 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1759 } else {
1760 this.logoutAndSave(false);
1761 }
1762 }
1763
1764 private void logoutAndSave(boolean stop) {
1765 int activeAccounts = 0;
1766 for (final Account account : accounts) {
1767 if (account.isConnectionEnabled()) {
1768 databaseBackend.writeRoster(account.getRoster());
1769 activeAccounts++;
1770 }
1771 if (account.getXmppConnection() != null) {
1772 new Thread(() -> disconnect(account, false)).start();
1773 }
1774 }
1775 if (stop || activeAccounts == 0) {
1776 Log.d(Config.LOGTAG, "good bye");
1777 stopSelf();
1778 }
1779 }
1780
1781 private void schedulePostConnectivityChange() {
1782 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1783 if (alarmManager == null) {
1784 return;
1785 }
1786 final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1787 final Intent intent = new Intent(this, SystemEventReceiver.class);
1788 intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1789 try {
1790 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, s()
1791 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1792 : PendingIntent.FLAG_UPDATE_CURRENT);
1793 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1794 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1795 } else {
1796 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1797 }
1798 } catch (RuntimeException e) {
1799 Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1800 }
1801 }
1802
1803 public void scheduleWakeUpCall(final int seconds, final int requestCode) {
1804 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000L;
1805 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1806 if (alarmManager == null) {
1807 return;
1808 }
1809 final Intent intent = new Intent(this, SystemEventReceiver.class);
1810 intent.setAction(ACTION_PING);
1811 try {
1812 final PendingIntent pendingIntent =
1813 PendingIntent.getBroadcast(
1814 this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1815 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1816 } catch (RuntimeException e) {
1817 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1818 }
1819 }
1820
1821 @TargetApi(Build.VERSION_CODES.M)
1822 private void scheduleNextIdlePing() {
1823 long timeUntilWake = Config.IDLE_PING_INTERVAL * 1000;
1824 final var now = System.currentTimeMillis();
1825 for (final var message : mScheduledMessages.values()) {
1826 if (message.getTimeSent() <= now) continue; // Just in case
1827 if (message.getTimeSent() - now < timeUntilWake) timeUntilWake = message.getTimeSent() - now;
1828 }
1829 final var timeToWake = SystemClock.elapsedRealtime() + timeUntilWake;
1830 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1831 if (alarmManager == null) {
1832 Log.d(Config.LOGTAG, "no alarm manager?");
1833 return;
1834 }
1835 final Intent intent = new Intent(this, SystemEventReceiver.class);
1836 intent.setAction(ACTION_IDLE_PING);
1837 try {
1838 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, s()
1839 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1840 : PendingIntent.FLAG_UPDATE_CURRENT);
1841 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1842 } catch (RuntimeException e) {
1843 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1844 }
1845 }
1846
1847 public XmppConnection createConnection(final Account account) {
1848 final XmppConnection connection = new XmppConnection(account, this);
1849 connection.setOnStatusChangedListener(this.statusListener);
1850 connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1851 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1852 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1853 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1854 AxolotlService axolotlService = account.getAxolotlService();
1855 if (axolotlService != null) {
1856 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1857 }
1858 return connection;
1859 }
1860
1861 public void sendChatState(Conversation conversation) {
1862 if (sendChatStates()) {
1863 final var packet = mMessageGenerator.generateChatState(conversation);
1864 sendMessagePacket(conversation.getAccount(), packet);
1865 }
1866 }
1867
1868 private void sendFileMessage(final Message message, final boolean delay) {
1869 Log.d(Config.LOGTAG, "send file message");
1870 final Account account = message.getConversation().getAccount();
1871 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1872 || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1873 mHttpConnectionManager.createNewUploadConnection(message, delay);
1874 } else {
1875 mJingleConnectionManager.startJingleFileTransfer(message);
1876 }
1877 }
1878
1879 public void sendMessage(final Message message) {
1880 sendMessage(message, false, false, false);
1881 }
1882
1883 private void sendMessage(final Message message, final boolean resend, final boolean previewedLinks, final boolean delay) {
1884 final Account account = message.getConversation().getAccount();
1885 if (account.setShowErrorNotification(true)) {
1886 databaseBackend.updateAccount(account);
1887 mNotificationService.updateErrorNotification();
1888 }
1889 final Conversation conversation = (Conversation) message.getConversation();
1890 account.deactivateGracePeriod();
1891
1892
1893 if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1894 final Contact contact = conversation.getContact();
1895 if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1896 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1897 createContact(contact, true);
1898 }
1899 }
1900
1901 im.conversations.android.xmpp.model.stanza.Message packet = null;
1902 final boolean addToConversation = !message.edited() && message.getRawBody() != null;
1903 boolean saveInDb = addToConversation;
1904 message.setStatus(Message.STATUS_WAITING);
1905
1906 if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1907 if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1908 databaseBackend.updateConversation(conversation);
1909 }
1910 }
1911
1912 final boolean inProgressJoin = isJoinInProgress(conversation);
1913
1914 if (message.getCounterpart() == null && !message.isPrivateMessage()) {
1915 message.setCounterpart(message.getConversation().getJid().asBareJid());
1916 }
1917
1918 boolean waitForPreview = false;
1919 if (getPreferences().getBoolean("send_link_previews", true) && !previewedLinks && !message.needsUploading() && message.getEncryption() != Message.ENCRYPTION_AXOLOTL) {
1920 message.clearLinkDescriptions();
1921 final List<URI> links = message.getLinks();
1922 if (!links.isEmpty()) {
1923 waitForPreview = true;
1924 if (account.isOnlineAndConnected()) {
1925 FILE_ATTACHMENT_EXECUTOR.execute(() -> {
1926 for (URI link : links) {
1927 if ("https".equals(link.getScheme())) {
1928 try {
1929 HttpUrl url = HttpUrl.parse(link.toString());
1930 OkHttpClient http = getHttpConnectionManager().buildHttpClient(url, account, 5, false);
1931 okhttp3.Response response = http.newCall(new okhttp3.Request.Builder().url(url).head().build()).execute();
1932 final String mimeType = response.header("Content-Type") == null ? "" : response.header("Content-Type");
1933 final boolean image = mimeType.startsWith("image/");
1934 final boolean audio = mimeType.startsWith("audio/");
1935 final boolean video = mimeType.startsWith("video/");
1936 final boolean pdf = mimeType.equals("application/pdf");
1937 final boolean html = mimeType.startsWith("text/html") || mimeType.startsWith("application/xhtml+xml");
1938 if (response.isSuccessful() && (image || audio || video || pdf)) {
1939 Message.FileParams params = message.getFileParams();
1940 params.url = url.toString();
1941 if (response.header("Content-Length") != null) params.size = Long.parseLong(response.header("Content-Length"), 10);
1942 if (!Message.configurePrivateFileMessage(message)) {
1943 message.setType(image ? Message.TYPE_IMAGE : Message.TYPE_FILE);
1944 }
1945 params.setName(HttpConnectionManager.extractFilenameFromResponse(response));
1946
1947 if (link.toString().equals(message.getRawBody())) {
1948 Element fallback = new Element("fallback", "urn:xmpp:fallback:0").setAttribute("for", Namespace.OOB);
1949 fallback.addChild("body", "urn:xmpp:fallback:0");
1950 message.addPayload(fallback);
1951 } else if (message.getRawBody().indexOf(link.toString()) >= 0) {
1952 // Part of the real body, not just a fallback
1953 Element fallback = new Element("fallback", "urn:xmpp:fallback:0").setAttribute("for", Namespace.OOB);
1954 fallback.addChild("body", "urn:xmpp:fallback:0")
1955 .setAttribute("start", "0")
1956 .setAttribute("end", "0");
1957 message.addPayload(fallback);
1958 }
1959
1960 final int encryption = message.getEncryption();
1961 getHttpConnectionManager().createNewDownloadConnection(message, false, (file) -> {
1962 message.setEncryption(encryption);
1963 synchronized (message.getConversation()) {
1964 if (message.getStatus() == Message.STATUS_WAITING) sendMessage(message, true, true, false);
1965 }
1966 });
1967 return;
1968 } else if (response.isSuccessful() && html) {
1969 Semaphore waiter = new Semaphore(0);
1970 OpenGraphParser.Builder openGraphBuilder = new OpenGraphParser.Builder(new OpenGraphCallback() {
1971 @Override
1972 public void onPostResponse(OpenGraphResult result) {
1973 Element rdf = new Element("Description", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
1974 rdf.setAttribute("xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
1975 rdf.setAttribute("rdf:about", link.toString());
1976 if (result.getTitle() != null && !"".equals(result.getTitle())) {
1977 rdf.addChild("title", "https://ogp.me/ns#").setContent(result.getTitle());
1978 }
1979 if (result.getDescription() != null && !"".equals(result.getDescription())) {
1980 rdf.addChild("description", "https://ogp.me/ns#").setContent(result.getDescription());
1981 }
1982 if (result.getUrl() != null) {
1983 rdf.addChild("url", "https://ogp.me/ns#").setContent(result.getUrl());
1984 }
1985 if (result.getImage() != null) {
1986 rdf.addChild("image", "https://ogp.me/ns#").setContent(result.getImage());
1987 }
1988 if (result.getType() != null) {
1989 rdf.addChild("type", "https://ogp.me/ns#").setContent(result.getType());
1990 }
1991 if (result.getSiteName() != null) {
1992 rdf.addChild("site_name", "https://ogp.me/ns#").setContent(result.getSiteName());
1993 }
1994 if (result.getVideo() != null) {
1995 rdf.addChild("video", "https://ogp.me/ns#").setContent(result.getVideo());
1996 }
1997 message.addPayload(rdf);
1998 waiter.release();
1999 }
2000
2001 public void onError(String error) {
2002 waiter.release();
2003 }
2004 })
2005 .showNullOnEmpty(true)
2006 .maxBodySize(90000)
2007 .timeout(5000);
2008 if (useTorToConnect()) {
2009 openGraphBuilder = openGraphBuilder.jsoupProxy(new JsoupProxy("127.0.0.1", 8118));
2010 }
2011 openGraphBuilder.build().parse(link.toString());
2012 waiter.tryAcquire(10L, TimeUnit.SECONDS);
2013 }
2014 } catch (final IOException | InterruptedException e) { }
2015 }
2016 }
2017 synchronized (message.getConversation()) {
2018 if (message.getStatus() == Message.STATUS_WAITING) sendMessage(message, true, true, false);
2019 }
2020 });
2021 }
2022 }
2023 }
2024
2025 if (account.isOnlineAndConnected() && !inProgressJoin && !waitForPreview && message.getTimeSent() <= System.currentTimeMillis()) {
2026 switch (message.getEncryption()) {
2027 case Message.ENCRYPTION_NONE:
2028 if (message.needsUploading()) {
2029 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
2030 || conversation.getMode() == Conversation.MODE_MULTI
2031 || message.fixCounterpart()) {
2032 this.sendFileMessage(message, delay);
2033 } else {
2034 break;
2035 }
2036 } else {
2037 packet = mMessageGenerator.generateChat(message);
2038 }
2039 break;
2040 case Message.ENCRYPTION_PGP:
2041 case Message.ENCRYPTION_DECRYPTED:
2042 if (message.needsUploading()) {
2043 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
2044 || conversation.getMode() == Conversation.MODE_MULTI
2045 || message.fixCounterpart()) {
2046 this.sendFileMessage(message, delay);
2047 } else {
2048 break;
2049 }
2050 } else {
2051 packet = mMessageGenerator.generatePgpChat(message);
2052 }
2053 break;
2054 case Message.ENCRYPTION_AXOLOTL:
2055 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
2056 if (message.needsUploading()) {
2057 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
2058 || conversation.getMode() == Conversation.MODE_MULTI
2059 || message.fixCounterpart()) {
2060 this.sendFileMessage(message, delay);
2061 } else {
2062 break;
2063 }
2064 } else {
2065 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
2066 if (axolotlMessage == null) {
2067 account.getAxolotlService().preparePayloadMessage(message, delay);
2068 } else {
2069 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
2070 }
2071 }
2072 break;
2073
2074 }
2075 if (packet != null) {
2076 if (account.getXmppConnection().getFeatures().sm()
2077 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
2078 message.setStatus(Message.STATUS_UNSEND);
2079 } else {
2080 message.setStatus(Message.STATUS_SEND);
2081 }
2082 }
2083 } else {
2084 switch (message.getEncryption()) {
2085 case Message.ENCRYPTION_DECRYPTED:
2086 if (!message.needsUploading()) {
2087 String pgpBody = message.getEncryptedBody();
2088 String decryptedBody = message.getBody();
2089 message.setBody(pgpBody); //TODO might throw NPE
2090 message.setEncryption(Message.ENCRYPTION_PGP);
2091 if (message.edited()) {
2092 message.setBody(decryptedBody);
2093 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
2094 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
2095 Log.e(Config.LOGTAG, "error updated message in DB after edit");
2096 }
2097 updateConversationUi();
2098 return;
2099 } else {
2100 databaseBackend.createMessage(message);
2101 saveInDb = false;
2102 message.setBody(decryptedBody);
2103 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
2104 }
2105 }
2106 break;
2107 case Message.ENCRYPTION_AXOLOTL:
2108 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
2109 break;
2110 }
2111 }
2112
2113 synchronized (mScheduledMessages) {
2114 if (message.getTimeSent() > System.currentTimeMillis()) {
2115 mScheduledMessages.put(message.getUuid(), message);
2116 scheduleNextIdlePing();
2117 } else {
2118 mScheduledMessages.remove(message.getUuid());
2119 }
2120 }
2121
2122 boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
2123 if (mucMessage) {
2124 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
2125 }
2126
2127 if (resend) {
2128 if (packet != null && addToConversation) {
2129 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
2130 markMessage(message, Message.STATUS_UNSEND);
2131 } else {
2132 markMessage(message, Message.STATUS_SEND);
2133 }
2134 }
2135 } else {
2136 if (addToConversation) {
2137 conversation.add(message);
2138 }
2139 if (saveInDb) {
2140 databaseBackend.createMessage(message);
2141 } else if (message.edited()) {
2142 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
2143 Log.e(Config.LOGTAG, "error updated message in DB after edit");
2144 }
2145 }
2146 updateConversationUi();
2147 }
2148 if (packet != null) {
2149 if (delay) {
2150 mMessageGenerator.addDelay(packet, message.getTimeSent());
2151 }
2152 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2153 if (this.sendChatStates()) {
2154 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
2155 }
2156 }
2157 sendMessagePacket(account, packet);
2158 if (message.getConversation().getMode() == Conversation.MODE_MULTI && message.hasCustomEmoji()) {
2159 if (message.getConversation() instanceof Conversation) presenceToMuc((Conversation) message.getConversation());
2160 }
2161 }
2162 }
2163
2164 private boolean isJoinInProgress(final Conversation conversation) {
2165 final Account account = conversation.getAccount();
2166 synchronized (account.inProgressConferenceJoins) {
2167 if (conversation.getMode() == Conversational.MODE_MULTI) {
2168 final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
2169 final boolean pending = account.pendingConferenceJoins.contains(conversation);
2170 final boolean inProgressJoin = inProgress || pending;
2171 if (inProgressJoin) {
2172 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
2173 }
2174 return inProgressJoin;
2175 } else {
2176 return false;
2177 }
2178 }
2179 }
2180
2181 private void sendUnsentMessages(final Conversation conversation) {
2182 synchronized (conversation) {
2183 conversation.findWaitingMessages(message -> resendMessage(message, true));
2184 }
2185 }
2186
2187 public void resendMessage(final Message message, final boolean delay) {
2188 sendMessage(message, true, false, delay);
2189 }
2190
2191 public void resendMessage(final Message message, final boolean delay, final boolean previewedLinks) {
2192 sendMessage(message, true, previewedLinks, delay);
2193 }
2194
2195 public Pair<Account,Account> onboardingIncomplete() {
2196 if (getAccounts().size() != 2) return null;
2197 Account onboarding = null;
2198 Account newAccount = null;
2199 for (final Account account : getAccounts()) {
2200 if (account.getJid().getDomain().equals(Config.ONBOARDING_DOMAIN)) {
2201 onboarding = account;
2202 } else {
2203 newAccount = account;
2204 }
2205 }
2206
2207 if (onboarding != null && newAccount != null) {
2208 return new Pair<>(onboarding, newAccount);
2209 }
2210
2211 return null;
2212 }
2213
2214 public boolean isOnboarding() {
2215 return getAccounts().size() == 1 && getAccounts().get(0).getJid().getDomain().equals(Config.ONBOARDING_DOMAIN);
2216 }
2217
2218 public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
2219 final XmppConnection connection = account.getXmppConnection();
2220 final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
2221 if (jid == null) {
2222 callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
2223 return;
2224 }
2225 final Iq request = new Iq(Iq.Type.SET);
2226 request.setTo(jid);
2227 final Element command = request.addChild("command", Namespace.COMMANDS);
2228 command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
2229 command.setAttribute("action", "execute");
2230 sendIqPacket(account, request, (response) -> {
2231 if (response.getType() == Iq.Type.RESULT) {
2232 final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
2233 final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
2234 if (x != null) {
2235 final Data data = Data.parse(x);
2236 final String uri = data.getValue("uri");
2237 final String landingUrl = data.getValue("landing-url");
2238 if (uri != null) {
2239 final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
2240 callback.inviteRequested(invite);
2241 return;
2242 }
2243 }
2244 callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
2245 Log.d(Config.LOGTAG, response.toString());
2246 } else if (response.getType() == Iq.Type.ERROR) {
2247 callback.inviteRequestFailed(IqParser.errorMessage(response));
2248 } else {
2249 callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
2250 }
2251 });
2252
2253 }
2254
2255 public void fetchBookmarks(final Account account) {
2256 final Iq iqPacket = new Iq(Iq.Type.GET);
2257 final Element query = iqPacket.query("jabber:iq:private");
2258 query.addChild("storage", Namespace.BOOKMARKS);
2259 final Consumer<Iq> callback = (response) -> {
2260 if (response.getType() == Iq.Type.RESULT) {
2261 final Element query1 = response.query();
2262 final Element storage = query1.findChild("storage", "storage:bookmarks");
2263 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
2264 processBookmarksInitial(account, bookmarks, false);
2265 } else {
2266 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not fetch bookmarks");
2267 }
2268 };
2269 sendIqPacket(account, iqPacket, callback);
2270 }
2271
2272 public void fetchBookmarks2(final Account account) {
2273 final Iq retrieve = mIqGenerator.retrieveBookmarks();
2274 sendIqPacket(account, retrieve, (response) -> {
2275 if (response.getType() == Iq.Type.RESULT) {
2276 final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
2277 final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubSub(pubsub, account);
2278 processBookmarksInitial(account, bookmarks, true);
2279 }
2280 });
2281 }
2282
2283 public void fetchMessageDisplayedSynchronization(final Account account) {
2284 Log.d(Config.LOGTAG, account.getJid() + ": retrieve mds");
2285 final var retrieve = mIqGenerator.retrieveMds();
2286 sendIqPacket(
2287 account,
2288 retrieve,
2289 (response) -> {
2290 if (response.getType() != Iq.Type.RESULT) {
2291 return;
2292 }
2293 final var pubSub = response.findChild("pubsub", Namespace.PUBSUB);
2294 final Element items = pubSub == null ? null : pubSub.findChild("items");
2295 if (items == null
2296 || !Namespace.MDS_DISPLAYED.equals(items.getAttribute("node"))) {
2297 return;
2298 }
2299 for (final Element child : items.getChildren()) {
2300 if ("item".equals(child.getName())) {
2301 processMdsItem(account, child);
2302 }
2303 }
2304 });
2305 }
2306
2307 public void processMdsItem(final Account account, final Element item) {
2308 final Jid jid =
2309 item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("id"));
2310 if (jid == null) {
2311 return;
2312 }
2313 final Element displayed = item.findChild("displayed", Namespace.MDS_DISPLAYED);
2314 final Element stanzaId =
2315 displayed == null ? null : displayed.findChild("stanza-id", Namespace.STANZA_IDS);
2316 final String id = stanzaId == null ? null : stanzaId.getAttribute("id");
2317 final Conversation conversation = find(account, jid);
2318 if (id != null && conversation != null) {
2319 conversation.setDisplayState(id);
2320 markReadUpToStanzaId(conversation, id);
2321 }
2322 }
2323
2324 public void markReadUpToStanzaId(final Conversation conversation, final String stanzaId) {
2325 final Message message = conversation.findMessageWithServerMsgId(stanzaId);
2326 if (message == null) { // do we want to check if isRead?
2327 return;
2328 }
2329 markReadUpTo(conversation, message);
2330 }
2331
2332 public void markReadUpTo(final Conversation conversation, final Message message) {
2333 final boolean isDismissNotification = isDismissNotification(message);
2334 final var uuid = message.getUuid();
2335 Log.d(
2336 Config.LOGTAG,
2337 conversation.getAccount().getJid().asBareJid()
2338 + ": mark "
2339 + conversation.getJid().asBareJid()
2340 + " as read up to "
2341 + uuid);
2342 markRead(conversation, uuid, isDismissNotification);
2343 }
2344
2345 private static boolean isDismissNotification(final Message message) {
2346 Message next = message.next();
2347 while (next != null) {
2348 if (message.getStatus() == Message.STATUS_RECEIVED) {
2349 return false;
2350 }
2351 next = next.next();
2352 }
2353 return true;
2354 }
2355
2356 public void processBookmarksInitial(final Account account, final Map<Jid, Bookmark> bookmarks, final boolean pep) {
2357 final Set<Jid> previousBookmarks = account.getBookmarkedJids();
2358 for (final Bookmark bookmark : bookmarks.values()) {
2359 previousBookmarks.remove(bookmark.getJid().asBareJid());
2360 processModifiedBookmark(bookmark, pep);
2361 }
2362 if (pep) {
2363 processDeletedBookmarks(account, previousBookmarks);
2364 }
2365 account.setBookmarks(bookmarks);
2366 }
2367
2368 public void processDeletedBookmarks(final Account account, final Collection<Jid> bookmarks) {
2369 Log.d(
2370 Config.LOGTAG,
2371 account.getJid().asBareJid()
2372 + ": "
2373 + bookmarks.size()
2374 + " bookmarks have been removed");
2375 for (final Jid bookmark : bookmarks) {
2376 processDeletedBookmark(account, bookmark);
2377 }
2378 }
2379
2380 public void processDeletedBookmark(final Account account, final Jid jid) {
2381 final Conversation conversation = find(account, jid);
2382 if (conversation == null) {
2383 return;
2384 }
2385 Log.d(
2386 Config.LOGTAG,
2387 account.getJid().asBareJid() + ": archiving MUC " + jid + " after PEP update");
2388 archiveConversation(conversation, false);
2389 }
2390
2391 private void processModifiedBookmark(final Bookmark bookmark, final boolean pep) {
2392 final Account account = bookmark.getAccount();
2393 Conversation conversation = find(bookmark);
2394 if (conversation != null) {
2395 if (conversation.getMode() != Conversation.MODE_MULTI) {
2396 return;
2397 }
2398 bookmark.setConversation(conversation);
2399 if (pep && !bookmark.autojoin()) {
2400 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
2401 archiveConversation(conversation, false);
2402 } else {
2403 final MucOptions mucOptions = conversation.getMucOptions();
2404 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
2405 final String current = mucOptions.getActualNick();
2406 final String proposed = mucOptions.getProposedNick();
2407 if (current != null && !current.equals(proposed)) {
2408 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
2409 joinMuc(conversation);
2410 }
2411 }
2412 }
2413 } else if (bookmark.autojoin()) {
2414 conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
2415 bookmark.setConversation(conversation);
2416 }
2417 }
2418
2419 public void processModifiedBookmark(final Bookmark bookmark) {
2420 processModifiedBookmark(bookmark, true);
2421 }
2422
2423 public void createBookmark(final Account account, final Bookmark bookmark) {
2424 account.putBookmark(bookmark);
2425 final XmppConnection connection = account.getXmppConnection();
2426 if (connection == null) {
2427 Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
2428 } else if (connection.getFeatures().bookmarks2()) {
2429 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": pushing bookmark via Bookmarks 2");
2430 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
2431 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
2432 } else if (connection.getFeatures().bookmarksConversion()) {
2433 pushBookmarksPep(account);
2434 } else {
2435 pushBookmarksPrivateXml(account);
2436 }
2437 }
2438
2439 public void deleteBookmark(final Account account, final Bookmark bookmark) {
2440 if (bookmark.getJid().toString().equals("discuss@conference.soprani.ca")) {
2441 getPreferences().edit().putBoolean("cheogram_sopranica_bookmark_deleted", true).apply();
2442 }
2443 account.removeBookmark(bookmark);
2444 final XmppConnection connection = account.getXmppConnection();
2445 if (connection == null) return;
2446
2447 if (connection.getFeatures().bookmarks2()) {
2448 final Iq request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
2449 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": removing bookmark via Bookmarks 2");
2450 sendIqPacket(account, request, (response) -> {
2451 if (response.getType() == Iq.Type.ERROR) {
2452 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
2453 }
2454 });
2455 } else if (connection.getFeatures().bookmarksConversion()) {
2456 pushBookmarksPep(account);
2457 } else {
2458 pushBookmarksPrivateXml(account);
2459 }
2460 }
2461
2462 private void pushBookmarksPrivateXml(Account account) {
2463 if (!account.areBookmarksLoaded()) return;
2464
2465 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
2466 final Iq iqPacket = new Iq(Iq.Type.SET);
2467 Element query = iqPacket.query("jabber:iq:private");
2468 Element storage = query.addChild("storage", "storage:bookmarks");
2469 for (final Bookmark bookmark : account.getBookmarks()) {
2470 storage.addChild(bookmark);
2471 }
2472 sendIqPacket(account, iqPacket, mDefaultIqHandler);
2473 }
2474
2475 private void pushBookmarksPep(Account account) {
2476 if (!account.areBookmarksLoaded()) return;
2477
2478 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
2479 final Element storage = new Element("storage", "storage:bookmarks");
2480 for (final Bookmark bookmark : account.getBookmarks()) {
2481 storage.addChild(bookmark);
2482 }
2483 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
2484
2485 }
2486
2487 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
2488 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2489
2490 }
2491
2492 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
2493 final Iq packet = mIqGenerator.publishElement(node, element, id, options);
2494 sendIqPacket(account, packet, (response) -> {
2495 if (response.getType() == Iq.Type.RESULT) {
2496 return;
2497 }
2498 if (retry && PublishOptions.preconditionNotMet(response)) {
2499 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
2500 @Override
2501 public void onPushSucceeded() {
2502 pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
2503 }
2504
2505 @Override
2506 public void onPushFailed() {
2507 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
2508 }
2509 });
2510 } else {
2511 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing "+node+" (retry=" + retry + ") " + response);
2512 }
2513 });
2514 }
2515
2516 private void restoreFromDatabase() {
2517 synchronized (this.conversations) {
2518 final Map<String, Account> accountLookupTable = new Hashtable<>();
2519 for (Account account : this.accounts) {
2520 accountLookupTable.put(account.getUuid(), account);
2521 }
2522 Log.d(Config.LOGTAG, "restoring conversations...");
2523 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2524 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2525 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
2526 Conversation conversation = iterator.next();
2527 Account account = accountLookupTable.get(conversation.getAccountUuid());
2528 if (account != null) {
2529 conversation.setAccount(account);
2530 } else {
2531 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
2532 conversations.remove(conversation);
2533 }
2534 }
2535 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2536 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
2537 Runnable runnable = () -> {
2538 if (DatabaseBackend.requiresMessageIndexRebuild()) {
2539 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2540 }
2541 mutedMucUsers = databaseBackend.loadMutedMucUsers();
2542 final long deletionDate = getAutomaticMessageDeletionDate();
2543 mLastExpiryRun.set(SystemClock.elapsedRealtime());
2544 if (deletionDate > 0) {
2545 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
2546 databaseBackend.expireOldMessages(deletionDate);
2547 }
2548 Log.d(Config.LOGTAG, "restoring roster...");
2549 for (final Account account : accounts) {
2550 databaseBackend.readRoster(account.getRoster());
2551 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
2552 }
2553 getDrawableCache().evictAll();
2554 loadPhoneContacts();
2555 Log.d(Config.LOGTAG, "restoring messages...");
2556 final long startMessageRestore = SystemClock.elapsedRealtime();
2557 final Conversation quickLoad = QuickLoader.get(this.conversations);
2558 if (quickLoad != null) {
2559 restoreMessages(quickLoad);
2560 updateConversationUi();
2561 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2562 Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
2563 }
2564 for (Conversation conversation : this.conversations) {
2565 if (quickLoad != conversation) {
2566 restoreMessages(conversation);
2567 }
2568 }
2569 mNotificationService.finishBacklog();
2570 restoredFromDatabaseLatch.countDown();
2571 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2572 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2573 updateConversationUi();
2574 };
2575 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2576 }
2577 }
2578
2579 private void restoreMessages(Conversation conversation) {
2580 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2581 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2582 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2583 }
2584
2585 public void loadPhoneContacts() {
2586 mContactMergerExecutor.execute(() -> {
2587 final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2588 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2589 for (final Account account : accounts) {
2590 final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2591 for (final JabberIdContact jidContact : contacts.values()) {
2592 final Contact contact = account.getRoster().getContact(jidContact.getJid());
2593 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2594 if (needsCacheClean) {
2595 getAvatarService().clear(contact);
2596 }
2597 withSystemAccounts.remove(contact);
2598 }
2599 for (final Contact contact : withSystemAccounts) {
2600 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2601 if (needsCacheClean) {
2602 getAvatarService().clear(contact);
2603 }
2604 }
2605 }
2606 Log.d(Config.LOGTAG, "finished merging phone contacts");
2607 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2608 updateRosterUi(UpdateRosterReason.INIT);
2609 mQuickConversationsService.considerSync();
2610 });
2611 }
2612
2613
2614 public void syncRoster(final Account account) {
2615 mRosterSyncTaskManager.execute(account, () -> {
2616 unregisterPhoneAccounts(account);
2617 databaseBackend.writeRoster(account.getRoster());
2618 try { Thread.sleep(500); } catch (InterruptedException e) { }
2619 });
2620 }
2621
2622 public List<Conversation> getConversations() {
2623 return this.conversations;
2624 }
2625
2626 private void markFileDeleted(final File file) {
2627 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2628 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2629 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2630 return;
2631 }
2632 }
2633 final boolean isInternalFile = fileBackend.isInternalFile(file);
2634 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2635 Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2636 markUuidsAsDeletedFiles(uuids);
2637 }
2638
2639 private void markUuidsAsDeletedFiles(List<String> uuids) {
2640 boolean deleted = false;
2641 for (Conversation conversation : getConversations()) {
2642 deleted |= conversation.markAsDeleted(uuids);
2643 }
2644 for (final String uuid : uuids) {
2645 evictPreview(uuid);
2646 }
2647 if (deleted) {
2648 updateConversationUi();
2649 }
2650 }
2651
2652 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2653 boolean changed = false;
2654 for (Conversation conversation : getConversations()) {
2655 changed |= conversation.markAsChanged(infos);
2656 }
2657 if (changed) {
2658 updateConversationUi();
2659 }
2660 }
2661
2662 public void populateWithOrderedConversations(final List<Conversation> list) {
2663 populateWithOrderedConversations(list, true, true);
2664 }
2665
2666 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2667 populateWithOrderedConversations(list, includeNoFileUpload, true);
2668 }
2669
2670 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2671 final List<String> orderedUuids;
2672 if (sort) {
2673 orderedUuids = null;
2674 } else {
2675 orderedUuids = new ArrayList<>();
2676 for (Conversation conversation : list) {
2677 orderedUuids.add(conversation.getUuid());
2678 }
2679 }
2680 list.clear();
2681 if (includeNoFileUpload) {
2682 list.addAll(getConversations());
2683 } else {
2684 for (Conversation conversation : getConversations()) {
2685 if (conversation.getMode() == Conversation.MODE_SINGLE
2686 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2687 list.add(conversation);
2688 }
2689 }
2690 }
2691 try {
2692 if (orderedUuids != null) {
2693 Collections.sort(list, (a, b) -> {
2694 final int indexA = orderedUuids.indexOf(a.getUuid());
2695 final int indexB = orderedUuids.indexOf(b.getUuid());
2696 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2697 return a.compareTo(b);
2698 }
2699 return indexA - indexB;
2700 });
2701 } else {
2702 Collections.sort(list);
2703 }
2704 } catch (IllegalArgumentException e) {
2705 //ignore
2706 }
2707 }
2708
2709 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2710 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback) || conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2711 return;
2712 } else if (timestamp == 0) {
2713 return;
2714 }
2715 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2716 final Runnable runnable = () -> {
2717 final Account account = conversation.getAccount();
2718 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2719 if (messages.size() > 0) {
2720 conversation.addAll(0, messages);
2721 callback.onMoreMessagesLoaded(messages.size(), conversation);
2722 } else if (conversation.hasMessagesLeftOnServer()
2723 && account.isOnlineAndConnected()
2724 && conversation.getLastClearHistory().getTimestamp() == 0) {
2725 final boolean mamAvailable;
2726 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2727 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2728 } else {
2729 mamAvailable = conversation.getMucOptions().mamSupport();
2730 }
2731 if (mamAvailable) {
2732 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2733 if (query != null) {
2734 query.setCallback(callback);
2735 callback.informUser(R.string.fetching_history_from_server);
2736 } else {
2737 callback.informUser(R.string.not_fetching_history_retention_period);
2738 }
2739
2740 }
2741 }
2742 };
2743 mDatabaseReaderExecutor.execute(runnable);
2744 }
2745
2746 public List<Account> getAccounts() {
2747 return this.accounts;
2748 }
2749
2750
2751 /**
2752 * 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)
2753 */
2754 public List<Conversation> findAllConferencesWith(Contact contact) {
2755 final ArrayList<Conversation> results = new ArrayList<>();
2756 for (final Conversation c : conversations) {
2757 if (c.getMode() != Conversation.MODE_MULTI) {
2758 continue;
2759 }
2760 final MucOptions mucOptions = c.getMucOptions();
2761 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2762 results.add(c);
2763 }
2764 }
2765 return results;
2766 }
2767
2768 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2769 for (final Conversation conversation : haystack) {
2770 if (conversation.getContact() == contact) {
2771 return conversation;
2772 }
2773 }
2774 return null;
2775 }
2776
2777 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2778 if (jid == null) {
2779 return null;
2780 }
2781 for (final Conversation conversation : haystack) {
2782 if ((account == null || conversation.getAccount() == account)
2783 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2784 return conversation;
2785 }
2786 }
2787 return null;
2788 }
2789
2790 public boolean isConversationsListEmpty(final Conversation ignore) {
2791 synchronized (this.conversations) {
2792 final int size = this.conversations.size();
2793 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2794 }
2795 }
2796
2797 public boolean isConversationStillOpen(final Conversation conversation) {
2798 synchronized (this.conversations) {
2799 for (Conversation current : this.conversations) {
2800 if (current == conversation) {
2801 return true;
2802 }
2803 }
2804 }
2805 return false;
2806 }
2807
2808 public void maybeRegisterWithMuc(Conversation c, String nickArg) {
2809 final var nick = nickArg == null ? c.getMucOptions().getSelf().getFullJid().getResource() : nickArg;
2810 final var register = new Iq(Iq.Type.GET);
2811 register.query(Namespace.REGISTER);
2812 register.setTo(c.getJid().asBareJid());
2813 sendIqPacket(c.getAccount(), register, (response) -> {
2814 if (response.getType() == Iq.Type.RESULT) {
2815 final Element query = response.query(Namespace.REGISTER);
2816 String username = query.findChildContent("username", Namespace.REGISTER);
2817 if (username == null) username = query.findChildContent("nick", Namespace.REGISTER);
2818 if (username != null && username.equals(nick)) {
2819 // Already registered with this nick, done
2820 Log.d(Config.LOGTAG, "Already registered with " + c.getJid().asBareJid() + " as " + username);
2821 return;
2822 }
2823 Data form = Data.parse(query.findChild("x", Namespace.DATA));
2824 if (form != null) {
2825 final var field = form.getFieldByName("muc#register_roomnick");
2826 if (field != null && nick.equals(field.getValue())) {
2827 Log.d(Config.LOGTAG, "Already registered with " + c.getJid().asBareJid() + " as " + field.getValue());
2828 return;
2829 }
2830 }
2831 if (form == null || !"form".equals(form.getFormType()) || !form.getFields().stream().anyMatch(f -> f.isRequired() && !"muc#register_roomnick".equals(f.getFieldName()))) {
2832 // No form, result form, or no required fields other than nickname, let's just send nickname
2833 if (form == null || !"form".equals(form.getFormType())) {
2834 form = new Data();
2835 form.put("FORM_TYPE", "http://jabber.org/protocol/muc#register");
2836 }
2837 form.put("muc#register_roomnick", nick);
2838 form.submit();
2839 final var finish = new Iq(Iq.Type.SET);
2840 finish.query(Namespace.REGISTER).addChild(form);
2841 finish.setTo(c.getJid().asBareJid());
2842 sendIqPacket(c.getAccount(), finish, (response2) -> {
2843 if (response.getType() == Iq.Type.RESULT) {
2844 Log.w(Config.LOGTAG, "Success registering with channel " + c.getJid().asBareJid() + "/" + nick);
2845 } else {
2846 Log.w(Config.LOGTAG, "Error registering with channel: " + response2);
2847 }
2848 });
2849 } else {
2850 // TODO: offer registration form to user
2851 Log.d(Config.LOGTAG, "Complex registration form for " + c.getJid().asBareJid() + ": " + response);
2852 }
2853 } else {
2854 // We said maybe. Guess not
2855 Log.d(Config.LOGTAG, "Could not register with " + c.getJid().asBareJid() + ": " + response);
2856 }
2857 });
2858 }
2859
2860 public void deregisterWithMuc(Conversation c) {
2861 final Iq register = new Iq(Iq.Type.GET);
2862 register.query(Namespace.REGISTER).addChild("remove");
2863 register.setTo(c.getJid().asBareJid());
2864 sendIqPacket(c.getAccount(), register, (response) -> {
2865 if (response.getType() == Iq.Type.RESULT) {
2866 Log.d(Config.LOGTAG, "deregistered with " + c.getJid().asBareJid());
2867 } else {
2868 Log.w(Config.LOGTAG, "Could not deregister with " + c.getJid().asBareJid() + ": " + response);
2869 }
2870 });
2871 }
2872
2873 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2874 return this.findOrCreateConversation(account, jid, muc, false, async);
2875 }
2876
2877 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2878 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async, null);
2879 }
2880
2881 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2882 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, query, async, null);
2883 }
2884
2885 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async, final String password) {
2886 synchronized (this.conversations) {
2887 Conversation conversation = find(account, jid);
2888 if (conversation != null) {
2889 return conversation;
2890 }
2891 conversation = databaseBackend.findConversation(account, jid);
2892 final boolean loadMessagesFromDb;
2893 if (conversation != null) {
2894 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2895 conversation.setAccount(account);
2896 if (muc) {
2897 conversation.setMode(Conversation.MODE_MULTI);
2898 conversation.setContactJid(jid);
2899 if (password != null) conversation.getMucOptions().setPassword(password);
2900 } else {
2901 conversation.setMode(Conversation.MODE_SINGLE);
2902 conversation.setContactJid(jid.asBareJid());
2903 }
2904 databaseBackend.updateConversation(conversation);
2905 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2906 } else {
2907 String conversationName;
2908 Contact contact = account.getRoster().getContact(jid);
2909 if (contact != null) {
2910 conversationName = contact.getDisplayName();
2911 } else {
2912 conversationName = jid.getLocal();
2913 }
2914 if (muc) {
2915 conversation = new Conversation(conversationName, account, jid,
2916 Conversation.MODE_MULTI);
2917 if (password != null) conversation.getMucOptions().setPassword(password);
2918 } else {
2919 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2920 Conversation.MODE_SINGLE);
2921 }
2922 this.databaseBackend.createConversation(conversation);
2923 loadMessagesFromDb = false;
2924 }
2925 final Conversation c = conversation;
2926 final Runnable runnable = () -> {
2927 if (loadMessagesFromDb) {
2928 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2929 updateConversationUi();
2930 c.messagesLoaded.set(true);
2931 }
2932 if (account.getXmppConnection() != null
2933 && !c.getContact().isBlocked()
2934 && account.getXmppConnection().getFeatures().mam()
2935 && !muc) {
2936 if (query == null) {
2937 mMessageArchiveService.query(c);
2938 } else {
2939 if (query.getConversation() == null) {
2940 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2941 }
2942 }
2943 }
2944 if (joinAfterCreate) {
2945 joinMuc(c);
2946 }
2947 };
2948 if (async) {
2949 mDatabaseReaderExecutor.execute(runnable);
2950 } else {
2951 runnable.run();
2952 }
2953 this.conversations.add(conversation);
2954 updateConversationUi();
2955 return conversation;
2956 }
2957 }
2958
2959 public void archiveConversation(Conversation conversation) {
2960 archiveConversation(conversation, true);
2961 }
2962
2963 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2964 if (isOnboarding()) return;
2965
2966 getNotificationService().clear(conversation);
2967 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2968 conversation.setNextMessage(null);
2969 synchronized (this.conversations) {
2970 getMessageArchiveService().kill(conversation);
2971 if (conversation.getMode() == Conversation.MODE_MULTI) {
2972 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2973 final Bookmark bookmark = conversation.getBookmark();
2974 if (maySynchronizeWithBookmarks && bookmark != null) {
2975 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2976 Account account = bookmark.getAccount();
2977 bookmark.setConversation(null);
2978 deleteBookmark(account, bookmark);
2979 } else if (bookmark.autojoin()) {
2980 bookmark.setAutojoin(false);
2981 createBookmark(bookmark.getAccount(), bookmark);
2982 }
2983 }
2984 }
2985 deregisterWithMuc(conversation);
2986 leaveMuc(conversation);
2987 } else {
2988 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2989 stopPresenceUpdatesTo(conversation.getContact());
2990 }
2991 }
2992 updateConversation(conversation);
2993 this.conversations.remove(conversation);
2994 updateConversationUi();
2995 }
2996 }
2997
2998 public void stopPresenceUpdatesTo(Contact contact) {
2999 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
3000 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
3001 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3002 }
3003
3004 public void createAccount(final Account account) {
3005 account.initAccountServices(this);
3006 databaseBackend.createAccount(account);
3007 if (CallIntegration.hasSystemFeature(this)) {
3008 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
3009 }
3010 this.accounts.add(account);
3011 this.reconnectAccountInBackground(account);
3012 updateAccountUi();
3013 syncEnabledAccountSetting();
3014 toggleForegroundService();
3015 }
3016
3017 private void syncEnabledAccountSetting() {
3018 final boolean hasEnabledAccounts = hasEnabledAccounts();
3019 getPreferences().edit().putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
3020 toggleSetProfilePictureActivity(hasEnabledAccounts);
3021 }
3022
3023 private void toggleSetProfilePictureActivity(final boolean enabled) {
3024 try {
3025 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
3026 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
3027 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
3028 } catch (IllegalStateException e) {
3029 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
3030 }
3031 }
3032
3033 public boolean reconfigurePushDistributor() {
3034 return this.unifiedPushBroker.reconfigurePushDistributor();
3035 }
3036
3037 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
3038 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
3039 }
3040
3041 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
3042 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
3043 }
3044
3045 public UnifiedPushBroker getUnifiedPushBroker() {
3046 return this.unifiedPushBroker;
3047 }
3048
3049 private void provisionAccount(final String address, final String password) {
3050 final Jid jid = Jid.ofEscaped(address);
3051 final Account account = new Account(jid, password);
3052 account.setOption(Account.OPTION_DISABLED, true);
3053 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
3054 createAccount(account);
3055 }
3056
3057 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
3058 new Thread(() -> {
3059 try {
3060 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
3061 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
3062 if (cert == null) {
3063 callback.informUser(R.string.unable_to_parse_certificate);
3064 return;
3065 }
3066 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
3067 if (info == null) {
3068 callback.informUser(R.string.certificate_does_not_contain_jid);
3069 return;
3070 }
3071 if (findAccountByJid(info.first) == null) {
3072 final Account account = new Account(info.first, "");
3073 account.setPrivateKeyAlias(alias);
3074 account.setOption(Account.OPTION_DISABLED, true);
3075 account.setOption(Account.OPTION_FIXED_USERNAME, true);
3076 account.setDisplayName(info.second);
3077 createAccount(account);
3078 callback.onAccountCreated(account);
3079 if (Config.X509_VERIFICATION) {
3080 try {
3081 getMemorizingTrustManager().getNonInteractive(account.getServer(), null, 0, null).checkClientTrusted(chain, "RSA");
3082 } catch (CertificateException e) {
3083 callback.informUser(R.string.certificate_chain_is_not_trusted);
3084 }
3085 }
3086 } else {
3087 callback.informUser(R.string.account_already_exists);
3088 }
3089 } catch (Exception e) {
3090 callback.informUser(R.string.unable_to_parse_certificate);
3091 }
3092 }).start();
3093
3094 }
3095
3096 public void updateKeyInAccount(final Account account, final String alias) {
3097 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
3098 try {
3099 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
3100 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
3101 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
3102 if (info == null) {
3103 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
3104 return;
3105 }
3106 if (account.getJid().asBareJid().equals(info.first)) {
3107 account.setPrivateKeyAlias(alias);
3108 account.setDisplayName(info.second);
3109 databaseBackend.updateAccount(account);
3110 if (Config.X509_VERIFICATION) {
3111 try {
3112 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
3113 } catch (CertificateException e) {
3114 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
3115 }
3116 account.getAxolotlService().regenerateKeys(true);
3117 }
3118 } else {
3119 showErrorToastInUi(R.string.jid_does_not_match_certificate);
3120 }
3121 } catch (Exception e) {
3122 e.printStackTrace();
3123 }
3124 }
3125
3126 public boolean updateAccount(final Account account) {
3127 if (databaseBackend.updateAccount(account)) {
3128 Integer color = account.getColorToSave();
3129 if (color == null) {
3130 getPreferences().edit().remove("account_color:" + account.getUuid()).commit();
3131 } else {
3132 getPreferences().edit().putInt("account_color:" + account.getUuid(), color.intValue()).commit();
3133 }
3134 account.setShowErrorNotification(true);
3135 this.statusListener.onStatusChanged(account);
3136 databaseBackend.updateAccount(account);
3137 reconnectAccountInBackground(account);
3138 updateAccountUi();
3139 getNotificationService().updateErrorNotification();
3140 toggleForegroundService();
3141 syncEnabledAccountSetting();
3142 mChannelDiscoveryService.cleanCache();
3143 if (CallIntegration.hasSystemFeature(this)) {
3144 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
3145 }
3146 return true;
3147 } else {
3148 return false;
3149 }
3150 }
3151
3152 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
3153 final Iq iq = getIqGenerator().generateSetPassword(account, newPassword);
3154 sendIqPacket(account, iq, (packet) -> {
3155 if (packet.getType() == Iq.Type.RESULT) {
3156 account.setPassword(newPassword);
3157 account.setOption(Account.OPTION_MAGIC_CREATE, false);
3158 databaseBackend.updateAccount(account);
3159 callback.onPasswordChangeSucceeded();
3160 } else {
3161 callback.onPasswordChangeFailed();
3162 }
3163 });
3164 }
3165
3166 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
3167 final Iq iqPacket = new Iq(Iq.Type.SET);
3168 final Element query = iqPacket.addChild("query",Namespace.REGISTER);
3169 query.addChild("remove");
3170 sendIqPacket(account, iqPacket, (response) -> {
3171 if (response.getType() == Iq.Type.RESULT) {
3172 deleteAccount(account);
3173 callback.accept(true);
3174 } else {
3175 callback.accept(false);
3176 }
3177 });
3178 }
3179
3180 public void deleteAccount(final Account account) {
3181 getPreferences().edit().remove("onboarding_continued").commit();
3182 final boolean connected = account.getStatus() == Account.State.ONLINE;
3183 synchronized (this.conversations) {
3184 if (connected) {
3185 account.getAxolotlService().deleteOmemoIdentity();
3186 }
3187 for (final Conversation conversation : conversations) {
3188 if (conversation.getAccount() == account) {
3189 if (conversation.getMode() == Conversation.MODE_MULTI) {
3190 if (connected) {
3191 leaveMuc(conversation);
3192 }
3193 }
3194 conversations.remove(conversation);
3195 mNotificationService.clear(conversation);
3196 }
3197 }
3198 new Thread(() -> {
3199 for (final Contact contact : account.getRoster().getContacts()) {
3200 contact.unregisterAsPhoneAccount(this);
3201 }
3202 }).start();
3203 if (account.getXmppConnection() != null) {
3204 new Thread(() -> disconnect(account, !connected)).start();
3205 }
3206 final Runnable runnable = () -> {
3207 if (!databaseBackend.deleteAccount(account)) {
3208 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
3209 }
3210 };
3211 mDatabaseWriterExecutor.execute(runnable);
3212 this.accounts.remove(account);
3213 if (CallIntegration.hasSystemFeature(this)) {
3214 CallIntegrationConnectionService.unregisterPhoneAccount(this, account);
3215 }
3216 this.mRosterSyncTaskManager.clear(account);
3217 updateAccountUi();
3218 mNotificationService.updateErrorNotification();
3219 syncEnabledAccountSetting();
3220 toggleForegroundService();
3221 }
3222 }
3223
3224 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
3225 final boolean remainingListeners;
3226 synchronized (LISTENER_LOCK) {
3227 remainingListeners = checkListeners();
3228 if (!this.mOnConversationUpdates.add(listener)) {
3229 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
3230 }
3231 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3232 }
3233 if (remainingListeners) {
3234 switchToForeground();
3235 }
3236 }
3237
3238 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
3239 final boolean remainingListeners;
3240 synchronized (LISTENER_LOCK) {
3241 this.mOnConversationUpdates.remove(listener);
3242 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3243 remainingListeners = checkListeners();
3244 }
3245 if (remainingListeners) {
3246 switchToBackground();
3247 }
3248 }
3249
3250 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
3251 final boolean remainingListeners;
3252 synchronized (LISTENER_LOCK) {
3253 remainingListeners = checkListeners();
3254 if (!this.mOnShowErrorToasts.add(listener)) {
3255 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
3256 }
3257 }
3258 if (remainingListeners) {
3259 switchToForeground();
3260 }
3261 }
3262
3263 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
3264 final boolean remainingListeners;
3265 synchronized (LISTENER_LOCK) {
3266 this.mOnShowErrorToasts.remove(onShowErrorToast);
3267 remainingListeners = checkListeners();
3268 }
3269 if (remainingListeners) {
3270 switchToBackground();
3271 }
3272 }
3273
3274 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
3275 final boolean remainingListeners;
3276 synchronized (LISTENER_LOCK) {
3277 remainingListeners = checkListeners();
3278 if (!this.mOnAccountUpdates.add(listener)) {
3279 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
3280 }
3281 }
3282 if (remainingListeners) {
3283 switchToForeground();
3284 }
3285 }
3286
3287 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
3288 final boolean remainingListeners;
3289 synchronized (LISTENER_LOCK) {
3290 this.mOnAccountUpdates.remove(listener);
3291 remainingListeners = checkListeners();
3292 }
3293 if (remainingListeners) {
3294 switchToBackground();
3295 }
3296 }
3297
3298 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3299 final boolean remainingListeners;
3300 synchronized (LISTENER_LOCK) {
3301 remainingListeners = checkListeners();
3302 if (!this.mOnCaptchaRequested.add(listener)) {
3303 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
3304 }
3305 }
3306 if (remainingListeners) {
3307 switchToForeground();
3308 }
3309 }
3310
3311 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3312 final boolean remainingListeners;
3313 synchronized (LISTENER_LOCK) {
3314 this.mOnCaptchaRequested.remove(listener);
3315 remainingListeners = checkListeners();
3316 }
3317 if (remainingListeners) {
3318 switchToBackground();
3319 }
3320 }
3321
3322 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
3323 final boolean remainingListeners;
3324 synchronized (LISTENER_LOCK) {
3325 remainingListeners = checkListeners();
3326 if (!this.mOnRosterUpdates.add(listener)) {
3327 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
3328 }
3329 }
3330 if (remainingListeners) {
3331 switchToForeground();
3332 }
3333 }
3334
3335 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
3336 final boolean remainingListeners;
3337 synchronized (LISTENER_LOCK) {
3338 this.mOnRosterUpdates.remove(listener);
3339 remainingListeners = checkListeners();
3340 }
3341 if (remainingListeners) {
3342 switchToBackground();
3343 }
3344 }
3345
3346 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3347 final boolean remainingListeners;
3348 synchronized (LISTENER_LOCK) {
3349 remainingListeners = checkListeners();
3350 if (!this.mOnUpdateBlocklist.add(listener)) {
3351 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
3352 }
3353 }
3354 if (remainingListeners) {
3355 switchToForeground();
3356 }
3357 }
3358
3359 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3360 final boolean remainingListeners;
3361 synchronized (LISTENER_LOCK) {
3362 this.mOnUpdateBlocklist.remove(listener);
3363 remainingListeners = checkListeners();
3364 }
3365 if (remainingListeners) {
3366 switchToBackground();
3367 }
3368 }
3369
3370 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
3371 final boolean remainingListeners;
3372 synchronized (LISTENER_LOCK) {
3373 remainingListeners = checkListeners();
3374 if (!this.mOnKeyStatusUpdated.add(listener)) {
3375 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
3376 }
3377 }
3378 if (remainingListeners) {
3379 switchToForeground();
3380 }
3381 }
3382
3383 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
3384 final boolean remainingListeners;
3385 synchronized (LISTENER_LOCK) {
3386 this.mOnKeyStatusUpdated.remove(listener);
3387 remainingListeners = checkListeners();
3388 }
3389 if (remainingListeners) {
3390 switchToBackground();
3391 }
3392 }
3393
3394 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3395 final boolean remainingListeners;
3396 synchronized (LISTENER_LOCK) {
3397 remainingListeners = checkListeners();
3398 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
3399 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
3400 }
3401 }
3402 if (remainingListeners) {
3403 switchToForeground();
3404 }
3405 }
3406
3407 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3408 final boolean remainingListeners;
3409 synchronized (LISTENER_LOCK) {
3410 this.onJingleRtpConnectionUpdate.remove(listener);
3411 remainingListeners = checkListeners();
3412 }
3413 if (remainingListeners) {
3414 switchToBackground();
3415 }
3416 }
3417
3418 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
3419 final boolean remainingListeners;
3420 synchronized (LISTENER_LOCK) {
3421 remainingListeners = checkListeners();
3422 if (!this.mOnMucRosterUpdate.add(listener)) {
3423 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
3424 }
3425 }
3426 if (remainingListeners) {
3427 switchToForeground();
3428 }
3429 }
3430
3431 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
3432 final boolean remainingListeners;
3433 synchronized (LISTENER_LOCK) {
3434 this.mOnMucRosterUpdate.remove(listener);
3435 remainingListeners = checkListeners();
3436 }
3437 if (remainingListeners) {
3438 switchToBackground();
3439 }
3440 }
3441
3442 public boolean checkListeners() {
3443 return (this.mOnAccountUpdates.size() == 0
3444 && this.mOnConversationUpdates.size() == 0
3445 && this.mOnRosterUpdates.size() == 0
3446 && this.mOnCaptchaRequested.size() == 0
3447 && this.mOnMucRosterUpdate.size() == 0
3448 && this.mOnUpdateBlocklist.size() == 0
3449 && this.mOnShowErrorToasts.size() == 0
3450 && this.onJingleRtpConnectionUpdate.size() == 0
3451 && this.mOnKeyStatusUpdated.size() == 0);
3452 }
3453
3454 private void switchToForeground() {
3455 toggleSoftDisabled(false);
3456 final boolean broadcastLastActivity = broadcastLastActivity();
3457 for (Conversation conversation : getConversations()) {
3458 if (conversation.getMode() == Conversation.MODE_MULTI) {
3459 conversation.getMucOptions().resetChatState();
3460 } else {
3461 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
3462 }
3463 }
3464 for (Account account : getAccounts()) {
3465 if (account.getStatus() == Account.State.ONLINE) {
3466 account.deactivateGracePeriod();
3467 final XmppConnection connection = account.getXmppConnection();
3468 if (connection != null) {
3469 if (connection.getFeatures().csi()) {
3470 connection.sendActive();
3471 }
3472 if (broadcastLastActivity) {
3473 sendPresence(account, false); //send new presence but don't include idle because we are not
3474 }
3475 }
3476 }
3477 }
3478 Log.d(Config.LOGTAG, "app switched into foreground");
3479 }
3480
3481 private void switchToBackground() {
3482 final boolean broadcastLastActivity = broadcastLastActivity();
3483 if (broadcastLastActivity) {
3484 mLastActivity = System.currentTimeMillis();
3485 final SharedPreferences.Editor editor = getPreferences().edit();
3486 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3487 editor.apply();
3488 }
3489 for (Account account : getAccounts()) {
3490 if (account.getStatus() == Account.State.ONLINE) {
3491 XmppConnection connection = account.getXmppConnection();
3492 if (connection != null) {
3493 if (broadcastLastActivity) {
3494 sendPresence(account, true);
3495 }
3496 if (connection.getFeatures().csi()) {
3497 connection.sendInactive();
3498 }
3499 }
3500 }
3501 }
3502 this.mNotificationService.setIsInForeground(false);
3503 Log.d(Config.LOGTAG, "app switched into background");
3504 }
3505
3506 public void connectMultiModeConversations(Account account) {
3507 List<Conversation> conversations = getConversations();
3508 for (Conversation conversation : conversations) {
3509 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
3510 joinMuc(conversation);
3511 }
3512 }
3513 }
3514
3515 public void mucSelfPingAndRejoin(final Conversation conversation) {
3516 final Account account = conversation.getAccount();
3517 synchronized (account.inProgressConferenceJoins) {
3518 if (account.inProgressConferenceJoins.contains(conversation)) {
3519 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
3520 return;
3521 }
3522 }
3523 synchronized (account.inProgressConferencePings) {
3524 if (!account.inProgressConferencePings.add(conversation)) {
3525 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
3526 return;
3527 }
3528 }
3529 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3530 final Iq ping = new Iq(Iq.Type.GET);
3531 ping.setTo(self);
3532 ping.addChild("ping", Namespace.PING);
3533 sendIqPacket(conversation.getAccount(), ping, (response) -> {
3534 if (response.getType() == Iq.Type.ERROR) {
3535 final var error = response.getError();
3536 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
3537 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
3538 } else {
3539 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
3540 joinMuc(conversation);
3541 }
3542 } else if (response.getType() == Iq.Type.RESULT) {
3543 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping to " + self + " came back fine");
3544 }
3545 synchronized (account.inProgressConferencePings) {
3546 account.inProgressConferencePings.remove(conversation);
3547 }
3548 });
3549 }
3550 public void joinMuc(Conversation conversation) {
3551 joinMuc(conversation, null, false);
3552 }
3553
3554 public void joinMuc(Conversation conversation, boolean followedInvite) {
3555 joinMuc(conversation, null, followedInvite);
3556 }
3557
3558 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3559 joinMuc(conversation, onConferenceJoined, false);
3560 }
3561
3562 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
3563 final Account account = conversation.getAccount();
3564 synchronized (account.pendingConferenceJoins) {
3565 account.pendingConferenceJoins.remove(conversation);
3566 }
3567 synchronized (account.pendingConferenceLeaves) {
3568 account.pendingConferenceLeaves.remove(conversation);
3569 }
3570 if (account.getStatus() == Account.State.ONLINE) {
3571 synchronized (account.inProgressConferenceJoins) {
3572 account.inProgressConferenceJoins.add(conversation);
3573 }
3574 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3575 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3576 }
3577 conversation.resetMucOptions();
3578 if (onConferenceJoined != null) {
3579 conversation.getMucOptions().flagNoAutoPushConfiguration();
3580 }
3581 conversation.setHasMessagesLeftOnServer(false);
3582 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
3583
3584 private void join(Conversation conversation) {
3585 Account account = conversation.getAccount();
3586 final MucOptions mucOptions = conversation.getMucOptions();
3587
3588 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
3589 synchronized (account.inProgressConferenceJoins) {
3590 account.inProgressConferenceJoins.remove(conversation);
3591 }
3592 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3593 updateConversationUi();
3594 if (onConferenceJoined != null) {
3595 onConferenceJoined.onConferenceJoined(conversation);
3596 }
3597 return;
3598 }
3599
3600 final Jid joinJid = mucOptions.getSelf().getFullJid();
3601 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
3602 final var packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null, mucOptions.getSelf().getNick());
3603 packet.setTo(joinJid);
3604 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3605 if (conversation.getMucOptions().getPassword() != null) {
3606 x.addChild("password").setContent(mucOptions.getPassword());
3607 }
3608
3609 if (mucOptions.mamSupport()) {
3610 // Use MAM instead of the limited muc history to get history
3611 x.addChild("history").setAttribute("maxchars", "0");
3612 } else {
3613 // Fallback to muc history
3614 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
3615 }
3616 sendPresencePacket(account, packet);
3617 if (onConferenceJoined != null) {
3618 onConferenceJoined.onConferenceJoined(conversation);
3619 }
3620 if (!joinJid.equals(conversation.getJid())) {
3621 conversation.setContactJid(joinJid);
3622 databaseBackend.updateConversation(conversation);
3623 }
3624
3625 maybeRegisterWithMuc(conversation, null);
3626
3627 if (mucOptions.mamSupport()) {
3628 getMessageArchiveService().catchupMUC(conversation);
3629 }
3630 fetchConferenceMembers(conversation);
3631 if (mucOptions.isPrivateAndNonAnonymous()) {
3632 if (followedInvite) {
3633 final Bookmark bookmark = conversation.getBookmark();
3634 if (bookmark != null) {
3635 if (!bookmark.autojoin()) {
3636 bookmark.setAutojoin(true);
3637 createBookmark(account, bookmark);
3638 }
3639 } else {
3640 saveConversationAsBookmark(conversation, null);
3641 }
3642 }
3643 }
3644 synchronized (account.inProgressConferenceJoins) {
3645 account.inProgressConferenceJoins.remove(conversation);
3646 sendUnsentMessages(conversation);
3647 }
3648 }
3649
3650 @Override
3651 public void onConferenceConfigurationFetched(Conversation conversation) {
3652 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3653 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3654 return;
3655 }
3656 join(conversation);
3657 }
3658
3659 @Override
3660 public void onFetchFailed(final Conversation conversation, final String errorCondition) {
3661 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3662 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3663 return;
3664 }
3665 if ("remote-server-not-found".equals(errorCondition)) {
3666 synchronized (account.inProgressConferenceJoins) {
3667 account.inProgressConferenceJoins.remove(conversation);
3668 }
3669 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
3670 updateConversationUi();
3671 } else {
3672 join(conversation);
3673 fetchConferenceConfiguration(conversation);
3674 }
3675 }
3676 });
3677 updateConversationUi();
3678 } else {
3679 synchronized (account.pendingConferenceJoins) {
3680 account.pendingConferenceJoins.add(conversation);
3681 }
3682 conversation.resetMucOptions();
3683 conversation.setHasMessagesLeftOnServer(false);
3684 updateConversationUi();
3685 }
3686 }
3687
3688 private void fetchConferenceMembers(final Conversation conversation) {
3689 final Account account = conversation.getAccount();
3690 final AxolotlService axolotlService = account.getAxolotlService();
3691 final var affiliations = new ArrayList<String>();
3692 affiliations.add("outcast");
3693 if (conversation.getMucOptions().isPrivateAndNonAnonymous()) affiliations.addAll(List.of("member", "admin", "owner"));
3694 final Consumer<Iq> callback = new Consumer<Iq>() {
3695
3696 private int i = 0;
3697 private boolean success = true;
3698
3699 @Override
3700 public void accept(Iq response) {
3701 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3702 Element query = response.query("http://jabber.org/protocol/muc#admin");
3703 if (response.getType() == Iq.Type.RESULT && query != null) {
3704 for (Element child : query.getChildren()) {
3705 if ("item".equals(child.getName())) {
3706 MucOptions.User user = AbstractParser.parseItem(conversation, child);
3707 user.setOnline(false);
3708 if (!user.realJidMatchesAccount()) {
3709 boolean isNew = conversation.getMucOptions().updateUser(user);
3710 Contact contact = user.getContact();
3711 if (omemoEnabled
3712 && isNew
3713 && user.getRealJid() != null
3714 && (contact == null || !contact.mutualPresenceSubscription())
3715 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3716 axolotlService.fetchDeviceIds(user.getRealJid());
3717 }
3718 }
3719 }
3720 }
3721 } else {
3722 success = false;
3723 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations.get(i) + " in " + conversation.getJid().asBareJid());
3724 }
3725 ++i;
3726 if (i >= affiliations.size()) {
3727 List<Jid> members = conversation.getMucOptions().getMembers(true);
3728 if (success) {
3729 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3730 boolean changed = false;
3731 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3732 Jid jid = iterator.next();
3733 if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3734 iterator.remove();
3735 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3736 changed = true;
3737 }
3738 }
3739 if (changed) {
3740 conversation.setAcceptedCryptoTargets(cryptoTargets);
3741 updateConversation(conversation);
3742 }
3743 }
3744 getAvatarService().clear(conversation);
3745 updateMucRosterUi();
3746 updateConversationUi();
3747 }
3748 }
3749 };
3750 for (String affiliation : affiliations) {
3751 final var x = mIqGenerator.queryAffiliation(conversation, affiliation);
3752 sendIqPacket(account, x, callback);
3753 }
3754 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3755 }
3756
3757 public void providePasswordForMuc(final Conversation conversation, final String password) {
3758 if (conversation.getMode() == Conversation.MODE_MULTI) {
3759 conversation.getMucOptions().setPassword(password);
3760 if (conversation.getBookmark() != null) {
3761 final Bookmark bookmark = conversation.getBookmark();
3762 bookmark.setAutojoin(true);
3763 createBookmark(conversation.getAccount(), bookmark);
3764 }
3765 updateConversation(conversation);
3766 joinMuc(conversation);
3767 }
3768 }
3769
3770 public void deleteAvatar(final Account account) {
3771 final AtomicBoolean executed = new AtomicBoolean(false);
3772 final Runnable onDeleted =
3773 () -> {
3774 if (executed.compareAndSet(false, true)) {
3775 account.setAvatar(null);
3776 databaseBackend.updateAccount(account);
3777 getAvatarService().clear(account);
3778 updateAccountUi();
3779 }
3780 };
3781 deleteVcardAvatar(account, onDeleted);
3782 deletePepNode(account, Namespace.AVATAR_DATA);
3783 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3784 }
3785
3786 public void deletePepNode(final Account account, final String node) {
3787 deletePepNode(account, node, null);
3788 }
3789
3790 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3791 final Iq request = mIqGenerator.deleteNode(node);
3792 sendIqPacket(account, request, (packet) -> {
3793 if (packet.getType() == Iq.Type.RESULT) {
3794 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully deleted pep node "+node);
3795 if (runnable != null) {
3796 runnable.run();
3797 }
3798 } else {
3799 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": failed to delete "+ packet);
3800 }
3801 });
3802 }
3803
3804 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3805 final Iq retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3806 sendIqPacket(account, retrieveVcard, (response) -> {
3807 if (response.getType() != Iq.Type.RESULT) {
3808 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": no vCard set. nothing to do");
3809 return;
3810 }
3811 final Element vcard = response.findChild("vCard", "vcard-temp");
3812 if (vcard == null) {
3813 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": no vCard set. nothing to do");
3814 return;
3815 }
3816 Element photo = vcard.findChild("PHOTO");
3817 if (photo == null) {
3818 photo = vcard.addChild("PHOTO");
3819 }
3820 photo.clearChildren();
3821 final Iq publication = new Iq(Iq.Type.SET);
3822 publication.setTo(account.getJid().asBareJid());
3823 publication.addChild(vcard);
3824 sendIqPacket(account, publication, (publicationResponse) -> {
3825 if (publicationResponse.getType() == Iq.Type.RESULT) {
3826 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully deleted vcard avatar");
3827 runnable.run();
3828 } else {
3829 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3830 }
3831 });
3832 });
3833 }
3834
3835 private boolean hasEnabledAccounts() {
3836 if (this.accounts == null) {
3837 return false;
3838 }
3839 for (final Account account : this.accounts) {
3840 if (account.isConnectionEnabled()) {
3841 return true;
3842 }
3843 }
3844 return false;
3845 }
3846
3847
3848 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3849 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3850 }
3851
3852 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3853 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3854 }
3855
3856
3857 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3858 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3859 }
3860
3861 public void persistSelfNick(final MucOptions.User self) {
3862 final Conversation conversation = self.getConversation();
3863 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3864 Jid full = self.getFullJid();
3865 if (!full.equals(conversation.getJid())) {
3866 Log.d(Config.LOGTAG, "nick changed. updating");
3867 conversation.setContactJid(full);
3868 databaseBackend.updateConversation(conversation);
3869 }
3870
3871 final String nick = self.getNick();
3872 final Bookmark bookmark = conversation.getBookmark();
3873 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3874 if (bookmark != null && (tookProposedNickFromBookmark || Strings.isNullOrEmpty(bookmarkedNick)) && !nick.equals(bookmarkedNick)) {
3875 final Account account = conversation.getAccount();
3876 final String defaultNick = MucOptions.defaultNick(account);
3877 if (Strings.isNullOrEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3878 return;
3879 }
3880 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + nick + "' into bookmark for " + conversation.getJid().asBareJid());
3881 bookmark.setNick(nick);
3882 createBookmark(bookmark.getAccount(), bookmark);
3883 }
3884 }
3885
3886 public void presenceToMuc(final Conversation conversation) {
3887 final MucOptions options = conversation.getMucOptions();
3888 if (options.online()) {
3889 Account account = conversation.getAccount();
3890 final Jid joinJid = options.getSelf().getFullJid();
3891 final var packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), options.getSelf().getNick());
3892 packet.setTo(joinJid);
3893 sendPresencePacket(account, packet);
3894 }
3895 }
3896
3897 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3898 final MucOptions options = conversation.getMucOptions();
3899 final Jid joinJid = options.createJoinJid(nick);
3900 if (joinJid == null) {
3901 return false;
3902 }
3903 if (options.online()) {
3904 maybeRegisterWithMuc(conversation, nick);
3905
3906 Account account = conversation.getAccount();
3907 options.setOnRenameListener(new OnRenameListener() {
3908
3909 @Override
3910 public void onSuccess() {
3911 final var packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3912 packet.setTo(joinJid);
3913 sendPresencePacket(account, packet);
3914 callback.success(conversation);
3915 }
3916
3917 @Override
3918 public void onFailure() {
3919 callback.error(R.string.nick_in_use, conversation);
3920 }
3921 });
3922
3923 final var packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3924 packet.setTo(joinJid);
3925 sendPresencePacket(account, packet);
3926 } else {
3927 conversation.setContactJid(joinJid);
3928 databaseBackend.updateConversation(conversation);
3929 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3930 Bookmark bookmark = conversation.getBookmark();
3931 if (bookmark != null) {
3932 bookmark.setNick(nick);
3933 createBookmark(bookmark.getAccount(), bookmark);
3934 }
3935 joinMuc(conversation);
3936 }
3937 }
3938 return true;
3939 }
3940
3941 public void leaveMuc(Conversation conversation) {
3942 leaveMuc(conversation, false);
3943 }
3944
3945 private void leaveMuc(Conversation conversation, boolean now) {
3946 final Account account = conversation.getAccount();
3947 synchronized (account.pendingConferenceJoins) {
3948 account.pendingConferenceJoins.remove(conversation);
3949 }
3950 synchronized (account.pendingConferenceLeaves) {
3951 account.pendingConferenceLeaves.remove(conversation);
3952 }
3953 if (account.getStatus() == Account.State.ONLINE || now) {
3954 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3955 conversation.getMucOptions().setOffline();
3956 Bookmark bookmark = conversation.getBookmark();
3957 if (bookmark != null) {
3958 bookmark.setConversation(null);
3959 }
3960 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3961 } else {
3962 synchronized (account.pendingConferenceLeaves) {
3963 account.pendingConferenceLeaves.add(conversation);
3964 }
3965 }
3966 }
3967
3968 public String findConferenceServer(final Account account) {
3969 String server;
3970 if (account.getXmppConnection() != null) {
3971 server = account.getXmppConnection().getMucServer();
3972 if (server != null) {
3973 return server;
3974 }
3975 }
3976 for (Account other : getAccounts()) {
3977 if (other != account && other.getXmppConnection() != null) {
3978 server = other.getXmppConnection().getMucServer();
3979 if (server != null) {
3980 return server;
3981 }
3982 }
3983 }
3984 return null;
3985 }
3986
3987
3988 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3989 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3990 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3991 if (!TextUtils.isEmpty(name)) {
3992 configuration.putString("muc#roomconfig_roomname", name);
3993 }
3994 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3995 @Override
3996 public void onPushSucceeded() {
3997 saveConversationAsBookmark(conversation, name);
3998 callback.success(conversation);
3999 }
4000
4001 @Override
4002 public void onPushFailed() {
4003 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
4004 callback.error(R.string.unable_to_set_channel_configuration, conversation);
4005 } else {
4006 callback.error(R.string.joined_an_existing_channel, conversation);
4007 }
4008 }
4009 });
4010 });
4011 }
4012
4013 public boolean createAdhocConference(final Account account,
4014 final String name,
4015 final Iterable<Jid> jids,
4016 final UiCallback<Conversation> callback) {
4017 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
4018 if (account.getStatus() == Account.State.ONLINE) {
4019 try {
4020 String server = findConferenceServer(account);
4021 if (server == null) {
4022 if (callback != null) {
4023 callback.error(R.string.no_conference_server_found, null);
4024 }
4025 return false;
4026 }
4027 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
4028 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
4029 joinMuc(conversation, new OnConferenceJoined() {
4030 @Override
4031 public void onConferenceJoined(final Conversation conversation) {
4032 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
4033 if (!TextUtils.isEmpty(name)) {
4034 configuration.putString("muc#roomconfig_roomname", name);
4035 }
4036 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
4037 @Override
4038 public void onPushSucceeded() {
4039 for (Jid invite : jids) {
4040 invite(conversation, invite);
4041 }
4042 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
4043 if (resource == null || "".equals(resource)) continue;
4044 Jid other = account.getJid().withResource(resource);
4045 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
4046 directInvite(conversation, other);
4047 }
4048 saveConversationAsBookmark(conversation, name);
4049 if (callback != null) {
4050 callback.success(conversation);
4051 }
4052 }
4053
4054 @Override
4055 public void onPushFailed() {
4056 archiveConversation(conversation);
4057 if (callback != null) {
4058 callback.error(R.string.conference_creation_failed, conversation);
4059 }
4060 }
4061 });
4062 }
4063 });
4064 return true;
4065 } catch (IllegalArgumentException e) {
4066 if (callback != null) {
4067 callback.error(R.string.conference_creation_failed, null);
4068 }
4069 return false;
4070 }
4071 } else {
4072 if (callback != null) {
4073 callback.error(R.string.not_connected_try_again, null);
4074 }
4075 return false;
4076 }
4077 }
4078
4079 public void checkIfMuc(final Account account, final Jid jid, Consumer<Boolean> cb) {
4080 if (jid.isDomainJid()) {
4081 // Spec basically says MUC needs to have a node
4082 // And also specifies that MUC and MUC service should have the same identity...
4083 cb.accept(false);
4084 return;
4085 }
4086
4087 final var request = mIqGenerator.queryDiscoInfo(jid.asBareJid());
4088 sendIqPacket(account, request, (reply) -> {
4089 final var result = new ServiceDiscoveryResult(reply);
4090 cb.accept(
4091 result.getFeatures().contains("http://jabber.org/protocol/muc") &&
4092 result.hasIdentity("conference", null)
4093 );
4094 });
4095 }
4096
4097 public void fetchConferenceConfiguration(final Conversation conversation) {
4098 fetchConferenceConfiguration(conversation, null);
4099 }
4100
4101 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
4102 final Iq request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
4103 final var account = conversation.getAccount();
4104 sendIqPacket(account, request, response -> {
4105 if (response.getType() == Iq.Type.RESULT) {
4106 final MucOptions mucOptions = conversation.getMucOptions();
4107 final Bookmark bookmark = conversation.getBookmark();
4108 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
4109
4110 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(response))) {
4111 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
4112 updateConversation(conversation);
4113 }
4114
4115 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
4116 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
4117 createBookmark(account, bookmark);
4118 }
4119 }
4120
4121
4122 if (callback != null) {
4123 callback.onConferenceConfigurationFetched(conversation);
4124 }
4125
4126
4127 updateConversationUi();
4128 } else if (response.getType() == Iq.Type.TIMEOUT) {
4129 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
4130 } else {
4131 if (callback != null) {
4132 callback.onFetchFailed(conversation, response.getErrorCondition());
4133 }
4134 }
4135 });
4136 }
4137
4138 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
4139 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
4140 }
4141
4142 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
4143 Log.d(Config.LOGTAG, "pushing node configuration");
4144 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), responseToRequest -> {
4145 if (responseToRequest.getType() == Iq.Type.RESULT) {
4146 Element pubsub = responseToRequest.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
4147 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
4148 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
4149 if (x != null) {
4150 final Data data = Data.parse(x);
4151 data.submit(options);
4152 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), responseToPublish -> {
4153 if (responseToPublish.getType() == Iq.Type.RESULT && callback != null) {
4154 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
4155 callback.onPushSucceeded();
4156 } else if (responseToPublish.getType() == Iq.Type.ERROR && callback != null) {
4157 callback.onPushFailed();
4158 }
4159 });
4160 } else if (callback != null) {
4161 callback.onPushFailed();
4162 }
4163 } else if (responseToRequest.getType() == Iq.Type.ERROR && callback != null) {
4164 callback.onPushFailed();
4165 }
4166 });
4167 }
4168
4169 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
4170 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
4171 conversation.setAttribute("accept_non_anonymous", true);
4172 updateConversation(conversation);
4173 }
4174 if (options.containsKey("muc#roomconfig_moderatedroom")) {
4175 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
4176 options.putString("members_by_default", moderated ? "0" : "1");
4177 }
4178 if (options.containsKey("muc#roomconfig_allowpm")) {
4179 // ejabberd :-/
4180 final boolean allow = "anyone".equals(options.getString("muc#roomconfig_allowpm"));
4181 options.putString("allow_private_messages", allow ? "1" : "0");
4182 options.putString("allow_private_messages_from_visitors", allow ? "anyone" : "nobody");
4183 }
4184 final var account = conversation.getAccount();
4185 final Iq request = new Iq(Iq.Type.GET);
4186 request.setTo(conversation.getJid().asBareJid());
4187 request.query("http://jabber.org/protocol/muc#owner");
4188 sendIqPacket(account, request, response -> {
4189 if (response.getType() == Iq.Type.RESULT) {
4190 final Data data = Data.parse(response.query().findChild("x", Namespace.DATA));
4191 data.submit(options);
4192 final Iq set = new Iq(Iq.Type.SET);
4193 set.setTo(conversation.getJid().asBareJid());
4194 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
4195 sendIqPacket(account, set, packet -> {
4196 if (callback != null) {
4197 if (packet.getType() == Iq.Type.RESULT) {
4198 callback.onPushSucceeded();
4199 } else {
4200 Log.d(Config.LOGTAG,"failed: "+packet.toString());
4201 callback.onPushFailed();
4202 }
4203 }
4204 });
4205 } else {
4206 if (callback != null) {
4207 callback.onPushFailed();
4208 }
4209 }
4210 });
4211 }
4212
4213 public void pushSubjectToConference(final Conversation conference, final String subject) {
4214 final var packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4215 this.sendMessagePacket(conference.getAccount(), packet);
4216 }
4217
4218 public void requestVoice(final Account account, final Jid jid) {
4219 final var packet = this.getMessageGenerator().requestVoice(jid);
4220 this.sendMessagePacket(account, packet);
4221 }
4222
4223 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
4224 final Jid jid = user.asBareJid();
4225 final Iq request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4226 sendIqPacket(conference.getAccount(), request, (response) -> {
4227 if (response.getType() == Iq.Type.RESULT) {
4228 conference.getMucOptions().changeAffiliation(jid, affiliation);
4229 getAvatarService().clear(conference);
4230 if (callback != null) {
4231 callback.onAffiliationChangedSuccessful(jid);
4232 } else {
4233 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
4234 }
4235 } else if (callback != null) {
4236 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
4237 } else {
4238 Log.d(Config.LOGTAG, "unable to change affiliation");
4239 }
4240 });
4241 }
4242
4243 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
4244 final var account =conference.getAccount();
4245 final Iq request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4246 sendIqPacket(account, request, (packet) -> {
4247 if (packet.getType() != Iq.Type.RESULT) {
4248 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
4249 }
4250 });
4251 }
4252
4253 public void moderateMessage(final Account account, final Message m, final String reason) {
4254 final var request = this.mIqGenerator.moderateMessage(account, m, reason);
4255 sendIqPacket(account, request, (packet) -> {
4256 if (packet.getType() != Iq.Type.RESULT) {
4257 showErrorToastInUi(R.string.unable_to_moderate);
4258 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to moderate: " + packet);
4259 }
4260 });
4261 }
4262
4263 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4264 final Iq request = new Iq(Iq.Type.SET);
4265 request.setTo(conversation.getJid().asBareJid());
4266 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4267 sendIqPacket(conversation.getAccount(), request, response -> {
4268 if (response.getType() == Iq.Type.RESULT) {
4269 if (callback != null) {
4270 callback.onRoomDestroySucceeded();
4271 }
4272 } else if (response.getType() == Iq.Type.ERROR) {
4273 if (callback != null) {
4274 callback.onRoomDestroyFailed();
4275 }
4276 }
4277 });
4278 }
4279
4280 private void disconnect(final Account account, boolean force) {
4281 final XmppConnection connection = account.getXmppConnection();
4282 if (connection == null) {
4283 return;
4284 }
4285 if (!force) {
4286 final List<Conversation> conversations = getConversations();
4287 for (Conversation conversation : conversations) {
4288 if (conversation.getAccount() == account) {
4289 if (conversation.getMode() == Conversation.MODE_MULTI) {
4290 leaveMuc(conversation, true);
4291 }
4292 }
4293 }
4294 sendOfflinePresence(account);
4295 }
4296 connection.disconnect(force);
4297 }
4298
4299 @Override
4300 public IBinder onBind(Intent intent) {
4301 return mBinder;
4302 }
4303
4304 public void deleteMessage(Message message) {
4305 mScheduledMessages.remove(message.getUuid());
4306 databaseBackend.deleteMessage(message.getUuid());
4307 ((Conversation) message.getConversation()).remove(message);
4308 updateConversationUi();
4309 }
4310
4311 public void updateMessage(Message message) {
4312 updateMessage(message, true);
4313 }
4314
4315 public void updateMessage(Message message, boolean includeBody) {
4316 databaseBackend.updateMessage(message, includeBody);
4317 updateConversationUi();
4318 }
4319
4320 public void createMessageAsync(final Message message) {
4321 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4322 }
4323
4324 public void updateMessage(Message message, String uuid) {
4325 if (!databaseBackend.updateMessage(message, uuid)) {
4326 Log.e(Config.LOGTAG, "error updated message in DB after edit");
4327 }
4328 updateConversationUi();
4329 }
4330
4331 public void syncDirtyContacts(Account account) {
4332 for (Contact contact : account.getRoster().getContacts()) {
4333 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
4334 pushContactToServer(contact);
4335 }
4336 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
4337 deleteContactOnServer(contact);
4338 }
4339 }
4340 }
4341
4342 protected void unregisterPhoneAccounts(final Account account) {
4343 for (final Contact contact : account.getRoster().getContacts()) {
4344 if (!contact.showInRoster()) {
4345 contact.unregisterAsPhoneAccount(this);
4346 }
4347 }
4348 }
4349
4350 public void createContact(final Contact contact, final boolean autoGrant) {
4351 createContact(contact, autoGrant, null);
4352 }
4353
4354 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
4355 if (autoGrant) {
4356 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4357 contact.setOption(Contact.Options.ASKING);
4358 }
4359 pushContactToServer(contact, preAuth);
4360 }
4361
4362 public void pushContactToServer(final Contact contact) {
4363 pushContactToServer(contact, null);
4364 }
4365
4366 private void pushContactToServer(final Contact contact, final String preAuth) {
4367 contact.resetOption(Contact.Options.DIRTY_DELETE);
4368 contact.setOption(Contact.Options.DIRTY_PUSH);
4369 final Account account = contact.getAccount();
4370 if (account.getStatus() == Account.State.ONLINE) {
4371 final boolean ask = contact.getOption(Contact.Options.ASKING);
4372 final boolean sendUpdates = contact
4373 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
4374 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
4375 final Iq iq = new Iq(Iq.Type.SET);
4376 iq.query(Namespace.ROSTER).addChild(contact.asElement());
4377 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4378 if (sendUpdates) {
4379 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
4380 }
4381 if (ask) {
4382 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
4383 }
4384 } else {
4385 syncRoster(contact.getAccount());
4386 }
4387 }
4388
4389 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4390 new Thread(() -> {
4391 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4392 final int size = Config.AVATAR_SIZE;
4393 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4394 if (avatar != null) {
4395 if (!getFileBackend().save(avatar)) {
4396 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4397 return;
4398 }
4399 avatar.owner = conversation.getJid().asBareJid();
4400 publishMucAvatar(conversation, avatar, callback);
4401 } else {
4402 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4403 }
4404 }).start();
4405 }
4406
4407 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
4408 new Thread(() -> {
4409 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4410 final int size = Config.AVATAR_SIZE;
4411 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4412 if (avatar != null) {
4413 if (!getFileBackend().save(avatar)) {
4414 Log.d(Config.LOGTAG, "unable to save vcard");
4415 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4416 return;
4417 }
4418 publishAvatar(account, avatar, callback);
4419 } else {
4420 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4421 }
4422 }).start();
4423
4424 }
4425
4426 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4427 final var account = conversation.getAccount();
4428 final Iq retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4429 sendIqPacket(account, retrieve, (response) -> {
4430 boolean itemNotFound = response.getType() == Iq.Type.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
4431 if (response.getType() == Iq.Type.RESULT || itemNotFound) {
4432 Element vcard = response.findChild("vCard", "vcard-temp");
4433 if (vcard == null) {
4434 vcard = new Element("vCard", "vcard-temp");
4435 }
4436 Element photo = vcard.findChild("PHOTO");
4437 if (photo == null) {
4438 photo = vcard.addChild("PHOTO");
4439 }
4440 photo.clearChildren();
4441 photo.addChild("TYPE").setContent(avatar.type);
4442 photo.addChild("BINVAL").setContent(avatar.image);
4443 final Iq publication = new Iq(Iq.Type.SET);
4444 publication.setTo(conversation.getJid().asBareJid());
4445 publication.addChild(vcard);
4446 sendIqPacket(account, publication, (publicationResponse) -> {
4447 if (publicationResponse.getType() == Iq.Type.RESULT) {
4448 callback.onAvatarPublicationSucceeded();
4449 } else {
4450 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
4451 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4452 }
4453 });
4454 } else {
4455 Log.d(Config.LOGTAG, "failed to request vcard " + response);
4456 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
4457 }
4458 });
4459 }
4460
4461 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
4462 final Bundle options;
4463 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4464 options = PublishOptions.openAccess();
4465 } else {
4466 options = null;
4467 }
4468 publishAvatar(account, avatar, options, true, callback);
4469 }
4470
4471 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4472 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4473 final Iq packet = this.mIqGenerator.publishAvatar(avatar, options);
4474 this.sendIqPacket(account, packet, result -> {
4475 if (result.getType() == Iq.Type.RESULT) {
4476 publishAvatarMetadata(account, avatar, options, true, callback);
4477 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4478 pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
4479 @Override
4480 public void onPushSucceeded() {
4481 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
4482 publishAvatar(account, avatar, options, false, callback);
4483 }
4484
4485 @Override
4486 public void onPushFailed() {
4487 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
4488 publishAvatar(account, avatar, null, false, callback);
4489 }
4490 });
4491 } else {
4492 Element error = result.findChild("error");
4493 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
4494 if (callback != null) {
4495 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4496 }
4497 }
4498 });
4499 }
4500
4501 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4502 final Iq packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4503 sendIqPacket(account, packet, result -> {
4504 if (result.getType() == Iq.Type.RESULT) {
4505 if (account.setAvatar(avatar.getFilename())) {
4506 getAvatarService().clear(account);
4507 databaseBackend.updateAccount(account);
4508 notifyAccountAvatarHasChanged(account);
4509 }
4510 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
4511 if (callback != null) {
4512 callback.onAvatarPublicationSucceeded();
4513 }
4514 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4515 pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
4516 @Override
4517 public void onPushSucceeded() {
4518 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
4519 publishAvatarMetadata(account, avatar, options, false, callback);
4520 }
4521
4522 @Override
4523 public void onPushFailed() {
4524 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
4525 publishAvatarMetadata(account, avatar, null, false, callback);
4526 }
4527 });
4528 } else {
4529 if (callback != null) {
4530 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4531 }
4532 }
4533 });
4534 }
4535
4536 public void republishAvatarIfNeeded(Account account) {
4537 if (account.getAxolotlService().isPepBroken()) {
4538 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
4539 return;
4540 }
4541 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4542 this.sendIqPacket(account, packet, new Consumer<Iq>() {
4543
4544 private Avatar parseAvatar(Iq packet) {
4545 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4546 if (pubsub != null) {
4547 Element items = pubsub.findChild("items");
4548 if (items != null) {
4549 return Avatar.parseMetadata(items);
4550 }
4551 }
4552 return null;
4553 }
4554
4555 private boolean errorIsItemNotFound(Iq packet) {
4556 Element error = packet.findChild("error");
4557 return packet.getType() == Iq.Type.ERROR
4558 && error != null
4559 && error.hasChild("item-not-found");
4560 }
4561
4562 @Override
4563 public void accept(final Iq packet) {
4564 if (packet.getType() == Iq.Type.RESULT || errorIsItemNotFound(packet)) {
4565 Avatar serverAvatar = parseAvatar(packet);
4566 if (serverAvatar == null && account.getAvatar() != null) {
4567 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4568 if (avatar != null) {
4569 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
4570 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
4571 } else {
4572 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
4573 }
4574 }
4575 }
4576 }
4577 });
4578 }
4579
4580 public void cancelAvatarFetches(final Account account) {
4581 synchronized (mInProgressAvatarFetches) {
4582 for (final Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
4583 final String KEY = iterator.next();
4584 if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
4585 iterator.remove();
4586 }
4587 }
4588 }
4589 }
4590
4591 public void fetchAvatar(Account account, Avatar avatar) {
4592 fetchAvatar(account, avatar, null);
4593 }
4594
4595 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4596 if (databaseBackend.isBlockedMedia(avatar.cid())) {
4597 if (callback != null) callback.error(0, null);
4598 return;
4599 }
4600
4601 final String KEY = generateFetchKey(account, avatar);
4602 synchronized (this.mInProgressAvatarFetches) {
4603 if (mInProgressAvatarFetches.add(KEY)) {
4604 switch (avatar.origin) {
4605 case PEP:
4606 this.mInProgressAvatarFetches.add(KEY);
4607 fetchAvatarPep(account, avatar, callback);
4608 break;
4609 case VCARD:
4610 this.mInProgressAvatarFetches.add(KEY);
4611 fetchAvatarVcard(account, avatar, callback);
4612 break;
4613 }
4614 } else if (avatar.origin == Avatar.Origin.PEP) {
4615 mOmittedPepAvatarFetches.add(KEY);
4616 } else {
4617 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
4618 }
4619 }
4620 }
4621
4622 private void fetchAvatarPep(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4623 final Iq packet = this.mIqGenerator.retrievePepAvatar(avatar);
4624 sendIqPacket(account, packet, (result) -> {
4625 synchronized (mInProgressAvatarFetches) {
4626 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
4627 }
4628 final String ERROR = account.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
4629 if (result.getType() == Iq.Type.RESULT) {
4630 avatar.image = IqParser.avatarData(result);
4631 if (avatar.image != null) {
4632 if (getFileBackend().save(avatar)) {
4633 if (account.getJid().asBareJid().equals(avatar.owner)) {
4634 if (account.setAvatar(avatar.getFilename())) {
4635 databaseBackend.updateAccount(account);
4636 }
4637 getAvatarService().clear(account);
4638 updateConversationUi();
4639 updateAccountUi();
4640 } else {
4641 final Contact contact = account.getRoster().getContact(avatar.owner);
4642 contact.setAvatar(avatar);
4643 syncRoster(account);
4644 getAvatarService().clear(contact);
4645 updateConversationUi();
4646 updateRosterUi(UpdateRosterReason.AVATAR);
4647 }
4648 if (callback != null) {
4649 callback.success(avatar);
4650 }
4651 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
4652 return;
4653 }
4654 } else {
4655
4656 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4657 }
4658 } else {
4659 Element error = result.findChild("error");
4660 if (error == null) {
4661 Log.d(Config.LOGTAG, ERROR + "(server error)");
4662 } else {
4663 Log.d(Config.LOGTAG, ERROR + error.toString());
4664 }
4665 }
4666 if (callback != null) {
4667 callback.error(0, null);
4668 }
4669
4670 });
4671 }
4672
4673 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4674 final Iq packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4675 this.sendIqPacket(account, packet, response -> {
4676 final boolean previouslyOmittedPepFetch;
4677 synchronized (mInProgressAvatarFetches) {
4678 final String KEY = generateFetchKey(account, avatar);
4679 mInProgressAvatarFetches.remove(KEY);
4680 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4681 }
4682 if (response.getType() == Iq.Type.RESULT) {
4683 Element vCard = response.findChild("vCard", "vcard-temp");
4684 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4685 String image = photo != null ? photo.findChildContent("BINVAL") : null;
4686 if (image != null) {
4687 avatar.image = image;
4688 if (getFileBackend().save(avatar)) {
4689 Log.d(Config.LOGTAG, account.getJid().asBareJid()
4690 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4691 if (avatar.owner.isBareJid()) {
4692 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4693 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4694 account.setAvatar(avatar.getFilename());
4695 databaseBackend.updateAccount(account);
4696 getAvatarService().clear(account);
4697 updateAccountUi();
4698 } else {
4699 final Contact contact = account.getRoster().getContact(avatar.owner);
4700 contact.setAvatar(avatar, previouslyOmittedPepFetch);
4701 syncRoster(account);
4702 getAvatarService().clear(contact);
4703 updateRosterUi(UpdateRosterReason.AVATAR);
4704 }
4705 updateConversationUi();
4706 } else {
4707 Conversation conversation = find(account, avatar.owner.asBareJid());
4708 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4709 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4710 if (user != null) {
4711 if (user.setAvatar(avatar)) {
4712 getAvatarService().clear(user);
4713 updateConversationUi();
4714 updateMucRosterUi();
4715 }
4716 if (user.getRealJid() != null) {
4717 Contact contact = account.getRoster().getContact(user.getRealJid());
4718 contact.setAvatar(avatar);
4719 syncRoster(account);
4720 getAvatarService().clear(contact);
4721 updateRosterUi(UpdateRosterReason.AVATAR);
4722 }
4723 }
4724 }
4725 }
4726 }
4727 }
4728 }
4729 });
4730 }
4731
4732 public void checkForAvatar(final Account account, final UiCallback<Avatar> callback) {
4733 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4734 this.sendIqPacket(account, packet, response -> {
4735 if (response.getType() == Iq.Type.RESULT) {
4736 Element pubsub = response.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4737 if (pubsub != null) {
4738 Element items = pubsub.findChild("items");
4739 if (items != null) {
4740 Avatar avatar = Avatar.parseMetadata(items);
4741 if (avatar != null) {
4742 avatar.owner = account.getJid().asBareJid();
4743 if (fileBackend.isAvatarCached(avatar)) {
4744 if (account.setAvatar(avatar.getFilename())) {
4745 databaseBackend.updateAccount(account);
4746 }
4747 getAvatarService().clear(account);
4748 callback.success(avatar);
4749 } else {
4750 fetchAvatarPep(account, avatar, callback);
4751 }
4752 return;
4753 }
4754 }
4755 }
4756 }
4757 callback.error(0, null);
4758 });
4759 }
4760
4761 public void notifyAccountAvatarHasChanged(final Account account) {
4762 final XmppConnection connection = account.getXmppConnection();
4763 if (connection != null && connection.getFeatures().bookmarksConversion()) {
4764 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4765 for (Conversation conversation : conversations) {
4766 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4767 presenceToMuc(conversation);
4768 }
4769 }
4770 }
4771 }
4772
4773 public void fetchVcard4(Account account, final Contact contact, final Consumer<Element> callback) {
4774 final var packet = this.mIqGenerator.retrieveVcard4(contact.getJid());
4775 sendIqPacket(account, packet, (result) -> {
4776 if (result.getType() == Iq.Type.RESULT) {
4777 final Element item = IqParser.getItem(result);
4778 if (item != null) {
4779 final Element vcard4 = item.findChild("vcard", Namespace.VCARD4);
4780 if (vcard4 != null) {
4781 if (callback != null) {
4782 callback.accept(vcard4);
4783 }
4784 return;
4785 }
4786 }
4787 } else {
4788 Element error = result.findChild("error");
4789 if (error == null) {
4790 Log.d(Config.LOGTAG, "fetchVcard4 (server error)");
4791 } else {
4792 Log.d(Config.LOGTAG, "fetchVcard4 " + error.toString());
4793 }
4794 }
4795 if (callback != null) {
4796 callback.accept(null);
4797 }
4798
4799 });
4800 }
4801
4802 public void deleteContactOnServer(Contact contact) {
4803 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4804 contact.resetOption(Contact.Options.DIRTY_PUSH);
4805 contact.setOption(Contact.Options.DIRTY_DELETE);
4806 Account account = contact.getAccount();
4807 if (account.getStatus() == Account.State.ONLINE) {
4808 final Iq iq = new Iq(Iq.Type.SET);
4809 Element item = iq.query(Namespace.ROSTER).addChild("item");
4810 item.setAttribute("jid", contact.getJid());
4811 item.setAttribute("subscription", "remove");
4812 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4813 }
4814 }
4815
4816 public void updateConversation(final Conversation conversation) {
4817 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4818 }
4819
4820 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4821 synchronized (account) {
4822 final XmppConnection existingConnection = account.getXmppConnection();
4823 final XmppConnection connection;
4824 if (existingConnection != null) {
4825 connection = existingConnection;
4826 } else if (account.isConnectionEnabled()) {
4827 connection = createConnection(account);
4828 account.setXmppConnection(connection);
4829 } else {
4830 return;
4831 }
4832 final boolean hasInternet = hasInternetConnection();
4833 if (account.isConnectionEnabled() && hasInternet) {
4834 if (!force) {
4835 disconnect(account, false);
4836 }
4837 Thread thread = new Thread(connection);
4838 connection.setInteractive(interactive);
4839 connection.prepareNewConnection();
4840 connection.interrupt();
4841 thread.start();
4842 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4843 } else {
4844 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4845 account.getRoster().clearPresences();
4846 connection.resetEverything();
4847 final AxolotlService axolotlService = account.getAxolotlService();
4848 if (axolotlService != null) {
4849 axolotlService.resetBrokenness();
4850 }
4851 if (!hasInternet) {
4852 account.setStatus(Account.State.NO_INTERNET);
4853 }
4854 }
4855 }
4856 }
4857
4858 public void reconnectAccountInBackground(final Account account) {
4859 new Thread(() -> reconnectAccount(account, false, true)).start();
4860 }
4861
4862 public void invite(final Conversation conversation, final Jid contact) {
4863 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4864 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4865 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4866 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4867 }
4868 final var packet = mMessageGenerator.invite(conversation, contact);
4869 sendMessagePacket(conversation.getAccount(), packet);
4870 }
4871
4872 public void directInvite(Conversation conversation, Jid jid) {
4873 final var packet = mMessageGenerator.directInvite(conversation, jid);
4874 sendMessagePacket(conversation.getAccount(), packet);
4875 }
4876
4877 public void resetSendingToWaiting(Account account) {
4878 for (Conversation conversation : getConversations()) {
4879 if (conversation.getAccount() == account) {
4880 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4881 }
4882 }
4883 }
4884
4885 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4886 return markMessage(account, recipient, uuid, status, null);
4887 }
4888
4889 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4890 if (uuid == null) {
4891 return null;
4892 }
4893 for (Conversation conversation : getConversations()) {
4894 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4895 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4896 if (message != null) {
4897 markMessage(message, status, errorMessage);
4898 }
4899 return message;
4900 }
4901 }
4902 return null;
4903 }
4904
4905 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4906 return markMessage(conversation, uuid, status, serverMessageId, null, null, null, null, null);
4907 }
4908
4909 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body, final Element html, final String subject, final Element thread, final Set<Message.FileParams> attachments) {
4910 if (uuid == null) {
4911 return false;
4912 } else {
4913 final Message message = conversation.findSentMessageWithUuid(uuid);
4914 if (message != null) {
4915 if (message.getServerMsgId() == null) {
4916 message.setServerMsgId(serverMessageId);
4917 }
4918 if (message.getEncryption() == Message.ENCRYPTION_NONE && (body != null || html != null || subject != null || thread != null || attachments != null)) {
4919 message.setBody(body.content);
4920 if (body.count > 1) {
4921 message.setBodyLanguage(body.language);
4922 }
4923 message.setHtml(html);
4924 message.setSubject(subject);
4925 message.setThread(thread);
4926 if (attachments != null && attachments.isEmpty()) {
4927 message.setRelativeFilePath(null);
4928 message.resetFileParams();
4929 }
4930 markMessage(message, status, null, true);
4931 } else {
4932 markMessage(message, status);
4933 }
4934 return true;
4935 } else {
4936 return false;
4937 }
4938 }
4939 }
4940
4941 public void markMessage(Message message, int status) {
4942 markMessage(message, status, null);
4943 }
4944
4945
4946 public void markMessage(final Message message, final int status, final String errorMessage) {
4947 markMessage(message, status, errorMessage, false);
4948 }
4949
4950 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4951 final int oldStatus = message.getStatus();
4952 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4953 return;
4954 }
4955 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4956 return;
4957 }
4958 message.setErrorMessage(errorMessage);
4959 message.setStatus(status);
4960 databaseBackend.updateMessage(message, includeBody);
4961 updateConversationUi();
4962 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4963 mNotificationService.pushFailedDelivery(message);
4964 }
4965 }
4966
4967 public SharedPreferences getPreferences() {
4968 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4969 }
4970
4971 public long getAutomaticMessageDeletionDate() {
4972 final long timeout = getLongPreference(AppSettings.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4973 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4974 }
4975
4976 public long getLongPreference(String name, @IntegerRes int res) {
4977 long defaultValue = getResources().getInteger(res);
4978 try {
4979 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4980 } catch (NumberFormatException e) {
4981 return defaultValue;
4982 }
4983 }
4984
4985 public boolean getBooleanPreference(String name, @BoolRes int res) {
4986 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4987 }
4988
4989 public String getStringPreference(String name, @BoolRes int res) {
4990 return getPreferences().getString(name, getResources().getString(res));
4991 }
4992
4993 public boolean confirmMessages() {
4994 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4995 }
4996
4997 public boolean allowMessageCorrection() {
4998 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4999 }
5000
5001 public boolean sendChatStates() {
5002 return getBooleanPreference("chat_states", R.bool.chat_states);
5003 }
5004
5005 public boolean useTorToConnect() {
5006 return getBooleanPreference("use_tor", R.bool.use_tor);
5007 }
5008
5009 public boolean showExtendedConnectionOptions() {
5010 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
5011 }
5012
5013 public boolean broadcastLastActivity() {
5014 return getBooleanPreference(AppSettings.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
5015 }
5016
5017 public int unreadCount() {
5018 int count = 0;
5019 for (Conversation conversation : getConversations()) {
5020 count += conversation.unreadCount(this);
5021 }
5022 return count;
5023 }
5024
5025
5026 private <T> List<T> threadSafeList(Set<T> set) {
5027 synchronized (LISTENER_LOCK) {
5028 return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
5029 }
5030 }
5031
5032 public void showErrorToastInUi(int resId) {
5033 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
5034 listener.onShowErrorToast(resId);
5035 }
5036 }
5037
5038 public void updateConversationUi() {
5039 updateConversationUi(false);
5040 }
5041
5042 public void updateConversationUi(boolean newCaps) {
5043 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
5044 listener.onConversationUpdate(newCaps);
5045 }
5046 }
5047
5048 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
5049 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
5050 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
5051 }
5052 }
5053
5054 public void notifyJingleRtpConnectionUpdate(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices) {
5055 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
5056 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
5057 }
5058 }
5059
5060 public void updateAccountUi() {
5061 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
5062 listener.onAccountUpdate();
5063 }
5064 }
5065
5066 public void updateRosterUi(final UpdateRosterReason reason) {
5067 if (reason == UpdateRosterReason.PRESENCE) throw new IllegalArgumentException("PRESENCE must also come with a contact");
5068 updateRosterUi(reason, null);
5069 }
5070
5071 public void updateRosterUi(final UpdateRosterReason reason, final Contact contact) {
5072 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
5073 listener.onRosterUpdate(reason, contact);
5074 }
5075 }
5076
5077 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
5078 if (mOnCaptchaRequested.size() > 0) {
5079 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
5080 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
5081 (int) (captcha.getHeight() * metrics.scaledDensity), false);
5082 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
5083 listener.onCaptchaRequested(account, id, data, scaled);
5084 }
5085 return true;
5086 }
5087 return false;
5088 }
5089
5090 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
5091 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
5092 listener.OnUpdateBlocklist(status);
5093 }
5094 }
5095
5096 public void updateMucRosterUi() {
5097 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
5098 listener.onMucRosterUpdate();
5099 }
5100 }
5101
5102 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
5103 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
5104 listener.onKeyStatusUpdated(report);
5105 }
5106 }
5107
5108 public Account findAccountByJid(final Jid jid) {
5109 for (final Account account : this.accounts) {
5110 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
5111 return account;
5112 }
5113 }
5114 return null;
5115 }
5116
5117 public Account findAccountByUuid(final String uuid) {
5118 for (Account account : this.accounts) {
5119 if (account.getUuid().equals(uuid)) {
5120 return account;
5121 }
5122 }
5123 return null;
5124 }
5125
5126 public Conversation findConversationByUuid(String uuid) {
5127 for (Conversation conversation : getConversations()) {
5128 if (conversation.getUuid().equals(uuid)) {
5129 return conversation;
5130 }
5131 }
5132 return null;
5133 }
5134
5135 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
5136 List<Conversation> findings = new ArrayList<>();
5137 for (Conversation c : getConversations()) {
5138 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid().asBareJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
5139 findings.add(c);
5140 }
5141 }
5142 return findings.size() == 1 ? findings.get(0) : null;
5143 }
5144
5145 public boolean markRead(final Conversation conversation, boolean dismiss) {
5146 return markRead(conversation, null, dismiss).size() > 0;
5147 }
5148
5149 public void markRead(final Conversation conversation) {
5150 markRead(conversation, null, true);
5151 }
5152
5153 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
5154 if (dismiss) {
5155 mNotificationService.clear(conversation);
5156 }
5157 final List<Message> readMessages = conversation.markRead(upToUuid);
5158 if (readMessages.size() > 0) {
5159 Runnable runnable = () -> {
5160 for (Message message : readMessages) {
5161 databaseBackend.updateMessage(message, false);
5162 }
5163 };
5164 mDatabaseWriterExecutor.execute(runnable);
5165 updateConversationUi();
5166 updateUnreadCountBadge();
5167 return readMessages;
5168 } else {
5169 return readMessages;
5170 }
5171 }
5172
5173 public synchronized void updateUnreadCountBadge() {
5174 int count = unreadCount();
5175 if (unreadCount != count) {
5176 Log.d(Config.LOGTAG, "update unread count to " + count);
5177 if (count > 0) {
5178 ShortcutBadger.applyCount(getApplicationContext(), count);
5179 } else {
5180 ShortcutBadger.removeCount(getApplicationContext());
5181 }
5182 unreadCount = count;
5183 }
5184 }
5185
5186 public void sendReadMarker(final Conversation conversation, final String upToUuid) {
5187 final boolean isPrivateAndNonAnonymousMuc =
5188 conversation.getMode() == Conversation.MODE_MULTI
5189 && conversation.isPrivateAndNonAnonymous();
5190 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
5191 if (readMessages.isEmpty()) {
5192 return;
5193 }
5194 final var account = conversation.getAccount();
5195 final var connection = account.getXmppConnection();
5196 updateConversationUi();
5197 final var last =
5198 Iterables.getLast(
5199 Collections2.filter(
5200 readMessages,
5201 m ->
5202 !m.isPrivateMessage()
5203 && m.getStatus() == Message.STATUS_RECEIVED),
5204 null);
5205 if (last == null) {
5206 return;
5207 }
5208
5209 final boolean sendDisplayedMarker =
5210 confirmMessages()
5211 && (last.trusted() || isPrivateAndNonAnonymousMuc)
5212 && last.getRemoteMsgId() != null
5213 && (last.markable || isPrivateAndNonAnonymousMuc);
5214 final boolean serverAssist =
5215 connection != null && connection.getFeatures().mdsServerAssist();
5216
5217 final String stanzaId = last.getServerMsgId();
5218
5219 if (sendDisplayedMarker && serverAssist) {
5220 final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5221 final var packet = mMessageGenerator.confirm(last);
5222 packet.addChild(mdsDisplayed);
5223 if (!last.isPrivateMessage()) {
5224 packet.setTo(packet.getTo().asBareJid());
5225 }
5226 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": server assisted "+packet);
5227 this.sendMessagePacket(account, packet);
5228 } else {
5229 publishMds(last);
5230 // read markers will be sent after MDS to flush the CSI stanza queue
5231 if (sendDisplayedMarker) {
5232 Log.d(
5233 Config.LOGTAG,
5234 conversation.getAccount().getJid().asBareJid()
5235 + ": sending displayed marker to "
5236 + last.getCounterpart().toString());
5237 final var packet = mMessageGenerator.confirm(last);
5238 this.sendMessagePacket(account, packet);
5239 }
5240 }
5241 }
5242
5243 private void publishMds(@Nullable final Message message) {
5244 final String stanzaId = message == null ? null : message.getServerMsgId();
5245 if (Strings.isNullOrEmpty(stanzaId)) {
5246 return;
5247 }
5248 final Conversation conversation;
5249 final var conversational = message.getConversation();
5250 if (conversational instanceof Conversation c) {
5251 conversation = c;
5252 } else {
5253 return;
5254 }
5255 final var account = conversation.getAccount();
5256 final var connection = account.getXmppConnection();
5257 if (connection == null || !connection.getFeatures().mds()) {
5258 return;
5259 }
5260 final Jid itemId;
5261 if (message.isPrivateMessage()) {
5262 itemId = message.getCounterpart();
5263 } else {
5264 itemId = conversation.getJid().asBareJid();
5265 }
5266 Log.d(Config.LOGTAG,"publishing mds for "+itemId+"/"+stanzaId);
5267 publishMds(account, itemId, stanzaId, conversation);
5268 }
5269
5270 private void publishMds(
5271 final Account account, final Jid itemId, final String stanzaId, final Conversation conversation) {
5272 final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5273 pushNodeAndEnforcePublishOptions(
5274 account,
5275 Namespace.MDS_DISPLAYED,
5276 item,
5277 itemId.toEscapedString(),
5278 PublishOptions.persistentWhitelistAccessMaxItems());
5279 }
5280
5281 public boolean sendReactions(final Message message, final Collection<String> reactions) {
5282 if (message.getConversation() instanceof Conversation conversation) {
5283 final String reactToId;
5284 final Collection<Reaction> combinedReactions;
5285 final var newReactions = new HashSet<>(reactions);
5286 newReactions.removeAll(message.getAggregatedReactions().ourReactions);
5287 if (conversation.getMode() == Conversational.MODE_MULTI) {
5288 final var self = conversation.getMucOptions().getSelf();
5289 final String occupantId = self.getOccupantId();
5290 reactToId = message.getServerMsgId();
5291 combinedReactions =
5292 Reaction.withMine(
5293 message.getReactions(),
5294 reactions,
5295 false,
5296 self.getFullJid(),
5297 conversation.getAccount().getJid(),
5298 occupantId,
5299 null);
5300 } else {
5301 if (message.isCarbon() || message.getStatus() == Message.STATUS_RECEIVED) {
5302 reactToId = message.getRemoteMsgId();
5303 } else {
5304 reactToId = message.getUuid();
5305 }
5306 combinedReactions =
5307 Reaction.withFrom(
5308 message.getReactions(),
5309 reactions,
5310 false,
5311 conversation.getAccount().getJid(),
5312 null);
5313 }
5314 if (Strings.isNullOrEmpty(reactToId)) {
5315 return false;
5316 }
5317 final var packet =
5318 mMessageGenerator.reaction(conversation, message, reactToId, reactions);
5319
5320 final var quote = QuoteHelper.quote(MessageUtils.prepareQuote(message)) + "\n";
5321 final var body = quote + String.join(" ", newReactions);
5322 if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && newReactions.size() > 0) {
5323 FILE_ATTACHMENT_EXECUTOR.execute(() -> {
5324 XmppAxolotlMessage axolotlMessage = conversation.getAccount().getAxolotlService().encrypt(body, conversation);
5325 packet.setAxolotlMessage(axolotlMessage.toElement());
5326 packet.addChild("encryption", "urn:xmpp:eme:0")
5327 .setAttribute("name", "OMEMO")
5328 .setAttribute("namespace", AxolotlService.PEP_PREFIX);
5329 sendMessagePacket(conversation.getAccount(), packet);
5330 message.setReactions(combinedReactions);
5331 updateMessage(message, false);
5332 });
5333 } else if (conversation.getNextEncryption() == Message.ENCRYPTION_NONE || newReactions.size() < 1) {
5334 if (newReactions.size() > 0) {
5335 packet.setBody(body);
5336
5337 packet.addChild("reply", "urn:xmpp:reply:0")
5338 .setAttribute("to", message.getCounterpart())
5339 .setAttribute("id", reactToId);
5340 final var replyFallback = packet.addChild("fallback", "urn:xmpp:fallback:0").setAttribute("for", "urn:xmpp:reply:0");
5341 replyFallback.addChild("body", "urn:xmpp:fallback:0")
5342 .setAttribute("start", "0")
5343 .setAttribute("end", "" + quote.codePointCount(0, quote.length()));
5344
5345 final var fallback = packet.addChild("fallback", "urn:xmpp:fallback:0").setAttribute("for", "urn:xmpp:reactions:0");
5346 fallback.addChild("body", "urn:xmpp:fallback:0");
5347 }
5348
5349 sendMessagePacket(conversation.getAccount(), packet);
5350 message.setReactions(combinedReactions);
5351 updateMessage(message, false);
5352 }
5353
5354 return true;
5355 } else {
5356 return false;
5357 }
5358 }
5359
5360 public MemorizingTrustManager getMemorizingTrustManager() {
5361 return this.mMemorizingTrustManager;
5362 }
5363
5364 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
5365 this.mMemorizingTrustManager = trustManager;
5366 }
5367
5368 public void updateMemorizingTrustManager() {
5369 final MemorizingTrustManager trustManager;
5370 if (appSettings.isTrustSystemCAStore()) {
5371 trustManager = new MemorizingTrustManager(getApplicationContext());
5372 } else {
5373 trustManager = new MemorizingTrustManager(getApplicationContext(), null);
5374 }
5375 setMemorizingTrustManager(trustManager);
5376 }
5377
5378 public LruCache<String, Drawable> getDrawableCache() {
5379 return this.mDrawableCache;
5380 }
5381
5382 public Collection<String> getKnownHosts() {
5383 final Set<String> hosts = new HashSet<>();
5384 for (final Account account : getAccounts()) {
5385 hosts.add(account.getServer());
5386 for (final Contact contact : account.getRoster().getContacts()) {
5387 if (contact.showInRoster()) {
5388 final String server = contact.getServer();
5389 if (server != null) {
5390 hosts.add(server);
5391 }
5392 }
5393 }
5394 }
5395 if (Config.QUICKSY_DOMAIN != null) {
5396 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
5397 }
5398 if (Config.MAGIC_CREATE_DOMAIN != null) {
5399 hosts.add(Config.MAGIC_CREATE_DOMAIN);
5400 }
5401 hosts.add("chat.above.im");
5402 return hosts;
5403 }
5404
5405 public Collection<String> getKnownConferenceHosts() {
5406 final Set<String> mucServers = new HashSet<>();
5407 for (final Account account : accounts) {
5408 if (account.getXmppConnection() != null) {
5409 mucServers.addAll(account.getXmppConnection().getMucServers());
5410 for (final Bookmark bookmark : account.getBookmarks()) {
5411 final Jid jid = bookmark.getJid();
5412 final String s = jid == null ? null : jid.getDomain().toEscapedString();
5413 if (s != null) {
5414 mucServers.add(s);
5415 }
5416 }
5417 }
5418 }
5419 return mucServers;
5420 }
5421
5422 public void sendMessagePacket(final Account account, final im.conversations.android.xmpp.model.stanza.Message packet) {
5423 final XmppConnection connection = account.getXmppConnection();
5424 if (connection != null) {
5425 connection.sendMessagePacket(packet);
5426 }
5427 }
5428
5429 public void sendPresencePacket(final Account account, final im.conversations.android.xmpp.model.stanza.Presence packet) {
5430 final XmppConnection connection = account.getXmppConnection();
5431 if (connection != null) {
5432 connection.sendPresencePacket(packet);
5433 }
5434 }
5435
5436 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5437 final XmppConnection connection = account.getXmppConnection();
5438 if (connection == null) {
5439 return;
5440 }
5441 connection.sendCreateAccountWithCaptchaPacket(id, data);
5442 }
5443
5444 public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback) {
5445 sendIqPacket(account, packet, callback, null);
5446 }
5447
5448 public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback, Long timeout) {
5449 final XmppConnection connection = account.getXmppConnection();
5450 if (connection != null) {
5451 connection.sendIqPacket(packet, callback, timeout);
5452 } else if (callback != null) {
5453 callback.accept(Iq.TIMEOUT);
5454 }
5455 }
5456
5457 public void sendPresence(final Account account) {
5458 sendPresence(account, checkListeners() && broadcastLastActivity());
5459 }
5460
5461 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
5462 final Presence.Status status;
5463 if (manuallyChangePresence()) {
5464 status = account.getPresenceStatus();
5465 } else {
5466 status = getTargetPresence();
5467 }
5468 final var packet = mPresenceGenerator.selfPresence(account, status);
5469 if (mLastActivity > 0 && includeIdleTimestamp) {
5470 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
5471 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
5472 }
5473 sendPresencePacket(account, packet);
5474 }
5475
5476 private void deactivateGracePeriod() {
5477 for (Account account : getAccounts()) {
5478 account.deactivateGracePeriod();
5479 }
5480 }
5481
5482 public void refreshAllPresences() {
5483 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
5484 for (Account account : getAccounts()) {
5485 if (account.isConnectionEnabled()) {
5486 sendPresence(account, includeIdleTimestamp);
5487 }
5488 }
5489 }
5490
5491 private void refreshAllFcmTokens() {
5492 for (Account account : getAccounts()) {
5493 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
5494 mPushManagementService.registerPushTokenOnServer(account);
5495 }
5496 }
5497 }
5498
5499
5500
5501 private void sendOfflinePresence(final Account account) {
5502 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
5503 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
5504 }
5505
5506 public MessageGenerator getMessageGenerator() {
5507 return this.mMessageGenerator;
5508 }
5509
5510 public PresenceGenerator getPresenceGenerator() {
5511 return this.mPresenceGenerator;
5512 }
5513
5514 public IqGenerator getIqGenerator() {
5515 return this.mIqGenerator;
5516 }
5517
5518 public JingleConnectionManager getJingleConnectionManager() {
5519 return this.mJingleConnectionManager;
5520 }
5521
5522 private boolean hasJingleRtpConnection(final Account account) {
5523 return this.mJingleConnectionManager.hasJingleRtpConnection(account);
5524 }
5525
5526 public MessageArchiveService getMessageArchiveService() {
5527 return this.mMessageArchiveService;
5528 }
5529
5530 public QuickConversationsService getQuickConversationsService() {
5531 return this.mQuickConversationsService;
5532 }
5533
5534 public List<Contact> findContacts(Jid jid, String accountJid) {
5535 ArrayList<Contact> contacts = new ArrayList<>();
5536 for (Account account : getAccounts()) {
5537 if ((account.isEnabled() || accountJid != null)
5538 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
5539 Contact contact = account.getRoster().getContactFromContactList(jid);
5540 if (contact != null) {
5541 contacts.add(contact);
5542 }
5543 }
5544 }
5545 return contacts;
5546 }
5547
5548 public Conversation findFirstMuc(Jid jid) {
5549 return findFirstMuc(jid, null);
5550 }
5551
5552 public Conversation findFirstMuc(Jid jid, String accountJid) {
5553 for (Conversation conversation : getConversations()) {
5554 if ((conversation.getAccount().isEnabled() || accountJid != null)
5555 && (accountJid == null || accountJid.equals(conversation.getAccount().getJid().asBareJid().toString()))
5556 && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
5557 return conversation;
5558 }
5559 }
5560 return null;
5561 }
5562
5563 public NotificationService getNotificationService() {
5564 return this.mNotificationService;
5565 }
5566
5567 public HttpConnectionManager getHttpConnectionManager() {
5568 return this.mHttpConnectionManager;
5569 }
5570
5571 public void resendFailedMessages(final Message message) {
5572 final Collection<Message> messages = new ArrayList<>();
5573 Message current = message;
5574 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
5575 messages.add(current);
5576 if (current.mergeable(current.next())) {
5577 current = current.next();
5578 } else {
5579 break;
5580 }
5581 }
5582 for (final Message msg : messages) {
5583 msg.setTime(System.currentTimeMillis());
5584 markMessage(msg, Message.STATUS_WAITING);
5585 this.resendMessage(msg, false);
5586 }
5587 if (message.getConversation() instanceof Conversation) {
5588 ((Conversation) message.getConversation()).sort();
5589 }
5590 updateConversationUi();
5591 }
5592
5593 public void clearConversationHistory(final Conversation conversation) {
5594 final long clearDate;
5595 final String reference;
5596 if (conversation.countMessages() > 0) {
5597 Message latestMessage = conversation.getLatestMessage();
5598 clearDate = latestMessage.getTimeSent() + 1000;
5599 reference = latestMessage.getServerMsgId();
5600 } else {
5601 clearDate = System.currentTimeMillis();
5602 reference = null;
5603 }
5604 conversation.clearMessages();
5605 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
5606 conversation.setLastClearHistory(clearDate, reference);
5607 Runnable runnable = () -> {
5608 databaseBackend.deleteMessagesInConversation(conversation);
5609 databaseBackend.updateConversation(conversation);
5610 };
5611 mDatabaseWriterExecutor.execute(runnable);
5612 }
5613
5614 public boolean sendBlockRequest(final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
5615 if (blockable != null && blockable.getBlockedJid() != null) {
5616 final var account = blockable.getAccount();
5617 final Jid jid = blockable.getBlockedJid();
5618 this.sendIqPacket(account, getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId), (response) -> {
5619 if (response.getType() == Iq.Type.RESULT) {
5620 account.getBlocklist().add(jid);
5621 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
5622 }
5623 });
5624 if (blockable.getBlockedJid().isFullJid()) {
5625 return false;
5626 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
5627 updateConversationUi();
5628 return true;
5629 } else {
5630 return false;
5631 }
5632 } else {
5633 return false;
5634 }
5635 }
5636
5637 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
5638 boolean removed = false;
5639 synchronized (this.conversations) {
5640 boolean domainJid = blockedJid.getLocal() == null;
5641 for (Conversation conversation : this.conversations) {
5642 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
5643 || blockedJid.equals(conversation.getJid().asBareJid());
5644 if (conversation.getAccount() == account
5645 && conversation.getMode() == Conversation.MODE_SINGLE
5646 && jidMatches) {
5647 this.conversations.remove(conversation);
5648 markRead(conversation);
5649 conversation.setStatus(Conversation.STATUS_ARCHIVED);
5650 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
5651 updateConversation(conversation);
5652 removed = true;
5653 }
5654 }
5655 }
5656 return removed;
5657 }
5658
5659 public void sendUnblockRequest(final Blockable blockable) {
5660 if (blockable != null && blockable.getJid() != null) {
5661 final var account = blockable.getAccount();
5662 final Jid jid = blockable.getBlockedJid();
5663 this.sendIqPacket(account, getIqGenerator().generateSetUnblockRequest(jid), response -> {
5664 if (response.getType() == Iq.Type.RESULT) {
5665 account.getBlocklist().remove(jid);
5666 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
5667 }
5668 });
5669 }
5670 }
5671
5672 public void publishDisplayName(final Account account) {
5673 String displayName = account.getDisplayName();
5674 final Iq request;
5675 if (TextUtils.isEmpty(displayName)) {
5676 request = mIqGenerator.deleteNode(Namespace.NICK);
5677 } else {
5678 request = mIqGenerator.publishNick(displayName);
5679 }
5680 mAvatarService.clear(account);
5681 sendIqPacket(account, request, (packet) -> {
5682 if (packet.getType() == Iq.Type.ERROR) {
5683 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to modify nick name " + packet);
5684 }
5685 });
5686 }
5687
5688 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
5689 ServiceDiscoveryResult result = discoCache.get(key);
5690 if (result != null) {
5691 return result;
5692 } else {
5693 if (key.first == null || key.second == null) return null;
5694 result = databaseBackend.findDiscoveryResult(key.first, key.second);
5695 if (result != null) {
5696 discoCache.put(key, result);
5697 }
5698 return result;
5699 }
5700 }
5701
5702 public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
5703 final var request = new Iq(input == null ? Iq.Type.GET : Iq.Type.SET);
5704 request.setTo(jid);
5705 Element query = request.query("jabber:iq:gateway");
5706 if (input != null) {
5707 Element prompt = query.addChild("prompt");
5708 prompt.setContent(input);
5709 }
5710 sendIqPacket(account, request, packet -> {
5711 if (packet.getType() == Iq.Type.RESULT) {
5712 callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
5713 } else {
5714 Element error = packet.findChild("error");
5715 callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
5716 }
5717 });
5718 }
5719
5720 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
5721 fetchCaps(account, jid, presence, null);
5722 }
5723
5724 public void fetchCaps(Account account, final Jid jid, final Presence presence, Runnable cb) {
5725 final Pair<String, String> key = presence == null ? null : new Pair<>(presence.getHash(), presence.getVer());
5726 final ServiceDiscoveryResult disco = key == null ? null : getCachedServiceDiscoveryResult(key);
5727
5728 if (disco != null) {
5729 presence.setServiceDiscoveryResult(disco);
5730 final Contact contact = account.getRoster().getContact(jid);
5731 if (contact.refreshRtpCapability()) {
5732 syncRoster(account);
5733 }
5734 contact.refreshCaps();
5735 if (disco.hasIdentity("gateway", "pstn")) {
5736 contact.registerAsPhoneAccount(this);
5737 mQuickConversationsService.considerSyncBackground(false);
5738 }
5739 updateConversationUi(true);
5740 } else {
5741 final Iq request = new Iq(Iq.Type.GET);
5742 request.setTo(jid);
5743 final String node = presence == null ? null : presence.getNode();
5744 final String ver = presence == null ? null : presence.getVer();
5745 final Element query = request.query(Namespace.DISCO_INFO);
5746 if (node != null && ver != null) {
5747 query.setAttribute("node", node + "#" + ver);
5748 }
5749 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + (key == null ? "" : key.second) + " to " + jid);
5750 sendIqPacket(account, request, (response) -> {
5751 if (response.getType() == Iq.Type.RESULT) {
5752 final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
5753 if (presence == null || presence.getVer() == null || presence.getVer().equals(discoveryResult.getVer())) {
5754 databaseBackend.insertDiscoveryResult(discoveryResult);
5755 injectServiceDiscoveryResult(account.getRoster(), presence == null ? null : presence.getHash(), presence == null ? null : presence.getVer(), jid.getResource(), discoveryResult);
5756 if (discoveryResult.hasIdentity("gateway", "pstn")) {
5757 final Contact contact = account.getRoster().getContact(jid);
5758 contact.registerAsPhoneAccount(this);
5759 mQuickConversationsService.considerSyncBackground(false);
5760 }
5761 updateConversationUi(true);
5762 if (cb != null) cb.run();
5763 } else {
5764 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
5765 }
5766 } else {
5767 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
5768 }
5769 });
5770 }
5771 }
5772
5773 public void fetchCommands(Account account, final Jid jid, Consumer<Iq> callback) {
5774 final var request = mIqGenerator.queryDiscoItems(jid, "http://jabber.org/protocol/commands");
5775 sendIqPacket(account, request, callback);
5776 }
5777
5778 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, String resource, ServiceDiscoveryResult disco) {
5779 boolean rosterNeedsSync = false;
5780 for (final Contact contact : roster.getContacts()) {
5781 boolean serviceDiscoverySet = false;
5782 Presence onePresence = contact.getPresences().get(resource == null ? "" : resource);
5783 if (onePresence != null) {
5784 onePresence.setServiceDiscoveryResult(disco);
5785 serviceDiscoverySet = true;
5786 } else if (resource == null && hash == null && ver == null) {
5787 Presence p = new Presence(Presence.Status.OFFLINE, null, null, null, "");
5788 p.setServiceDiscoveryResult(disco);
5789 contact.updatePresence("", p);
5790 serviceDiscoverySet = true;
5791 }
5792 if (hash != null && ver != null) {
5793 for (final Presence presence : contact.getPresences().getPresences()) {
5794 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
5795 presence.setServiceDiscoveryResult(disco);
5796 serviceDiscoverySet = true;
5797 }
5798 }
5799 }
5800 if (serviceDiscoverySet) {
5801 rosterNeedsSync |= contact.refreshRtpCapability();
5802 contact.refreshCaps();
5803 }
5804 }
5805 if (rosterNeedsSync) {
5806 syncRoster(roster.getAccount());
5807 }
5808 }
5809
5810 public void fetchMamPreferences(final Account account, final OnMamPreferencesFetched callback) {
5811 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5812 final Iq request = new Iq(Iq.Type.GET);
5813 request.addChild("prefs", version.namespace);
5814 sendIqPacket(account, request, (packet) -> {
5815 final Element prefs = packet.findChild("prefs", version.namespace);
5816 if (packet.getType() == Iq.Type.RESULT && prefs != null) {
5817 callback.onPreferencesFetched(prefs);
5818 } else {
5819 callback.onPreferencesFetchFailed();
5820 }
5821 });
5822 }
5823
5824 public PushManagementService getPushManagementService() {
5825 return mPushManagementService;
5826 }
5827
5828 public void changeStatus(Account account, PresenceTemplate template, String signature) {
5829 if (!template.getStatusMessage().isEmpty()) {
5830 databaseBackend.insertPresenceTemplate(template);
5831 }
5832 account.setPgpSignature(signature);
5833 account.setPresenceStatus(template.getStatus());
5834 account.setPresenceStatusMessage(template.getStatusMessage());
5835 databaseBackend.updateAccount(account);
5836 sendPresence(account);
5837 }
5838
5839 public List<PresenceTemplate> getPresenceTemplates(Account account) {
5840 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5841 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5842 if (!templates.contains(template)) {
5843 templates.add(0, template);
5844 }
5845 }
5846 return templates;
5847 }
5848
5849 public void saveConversationAsBookmark(final Conversation conversation, final String name) {
5850 final Account account = conversation.getAccount();
5851 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5852 String nick = conversation.getMucOptions().getActualNick();
5853 if (nick == null) nick = conversation.getJid().getResource();
5854 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5855 bookmark.setNick(nick);
5856 }
5857 if (!TextUtils.isEmpty(name)) {
5858 bookmark.setBookmarkName(name);
5859 }
5860 bookmark.setAutojoin(true);
5861 createBookmark(account, bookmark);
5862 bookmark.setConversation(conversation);
5863 }
5864
5865 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5866 boolean performedVerification = false;
5867 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5868 for (XmppUri.Fingerprint fp : fingerprints) {
5869 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5870 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5871 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5872 if (fingerprintStatus != null) {
5873 if (!fingerprintStatus.isVerified()) {
5874 performedVerification = true;
5875 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5876 }
5877 } else {
5878 axolotlService.preVerifyFingerprint(contact, fingerprint);
5879 }
5880 }
5881 }
5882 return performedVerification;
5883 }
5884
5885 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5886 final AxolotlService axolotlService = account.getAxolotlService();
5887 boolean verifiedSomething = false;
5888 for (XmppUri.Fingerprint fp : fingerprints) {
5889 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5890 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5891 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5892 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5893 if (fingerprintStatus != null) {
5894 if (!fingerprintStatus.isVerified()) {
5895 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5896 verifiedSomething = true;
5897 }
5898 } else {
5899 axolotlService.preVerifyFingerprint(account, fingerprint);
5900 verifiedSomething = true;
5901 }
5902 }
5903 }
5904 return verifiedSomething;
5905 }
5906
5907 public boolean blindTrustBeforeVerification() {
5908 return getBooleanPreference(AppSettings.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
5909 }
5910
5911 public ShortcutService getShortcutService() {
5912 return mShortcutService;
5913 }
5914
5915 public void pushMamPreferences(Account account, Element prefs) {
5916 final Iq set = new Iq(Iq.Type.SET);
5917 set.addChild(prefs);
5918 sendIqPacket(account, set, null);
5919 }
5920
5921 public void evictPreview(File f) {
5922 if (f == null) return;
5923
5924 if (mDrawableCache.remove(f.getAbsolutePath()) != null) {
5925 Log.d(Config.LOGTAG, "deleted cached preview");
5926 }
5927 }
5928
5929 public void evictPreview(String uuid) {
5930 if (mDrawableCache.remove(uuid) != null) {
5931 Log.d(Config.LOGTAG, "deleted cached preview");
5932 }
5933 }
5934
5935 public interface OnMamPreferencesFetched {
5936 void onPreferencesFetched(Element prefs);
5937
5938 void onPreferencesFetchFailed();
5939 }
5940
5941 public interface OnAccountCreated {
5942 void onAccountCreated(Account account);
5943
5944 void informUser(int r);
5945 }
5946
5947 public interface OnMoreMessagesLoaded {
5948 void onMoreMessagesLoaded(int count, Conversation conversation);
5949
5950 void informUser(int r);
5951 }
5952
5953 public interface OnAccountPasswordChanged {
5954 void onPasswordChangeSucceeded();
5955
5956 void onPasswordChangeFailed();
5957 }
5958
5959 public interface OnRoomDestroy {
5960 void onRoomDestroySucceeded();
5961
5962 void onRoomDestroyFailed();
5963 }
5964
5965 public interface OnAffiliationChanged {
5966 void onAffiliationChangedSuccessful(Jid jid);
5967
5968 void onAffiliationChangeFailed(Jid jid, int resId);
5969 }
5970
5971 public interface OnConversationUpdate {
5972 default void onConversationUpdate() { onConversationUpdate(false); }
5973 default void onConversationUpdate(boolean newCaps) { onConversationUpdate(); }
5974 }
5975
5976 public interface OnJingleRtpConnectionUpdate {
5977 void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5978
5979 void onAudioDeviceChanged(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices);
5980 }
5981
5982 public interface OnAccountUpdate {
5983 void onAccountUpdate();
5984 }
5985
5986 public interface OnCaptchaRequested {
5987 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5988 }
5989
5990 public interface OnRosterUpdate {
5991 void onRosterUpdate(final UpdateRosterReason reason, final Contact contact);
5992 }
5993
5994 public interface OnMucRosterUpdate {
5995 void onMucRosterUpdate();
5996 }
5997
5998 public interface OnConferenceConfigurationFetched {
5999 void onConferenceConfigurationFetched(Conversation conversation);
6000
6001 void onFetchFailed(Conversation conversation, String errorCondition);
6002 }
6003
6004 public interface OnConferenceJoined {
6005 void onConferenceJoined(Conversation conversation);
6006 }
6007
6008 public interface OnConfigurationPushed {
6009 void onPushSucceeded();
6010
6011 void onPushFailed();
6012 }
6013
6014 public interface OnShowErrorToast {
6015 void onShowErrorToast(int resId);
6016 }
6017
6018 public class XmppConnectionBinder extends Binder {
6019 public XmppConnectionService getService() {
6020 return XmppConnectionService.this;
6021 }
6022 }
6023
6024 private class InternalEventReceiver extends BroadcastReceiver {
6025
6026 @Override
6027 public void onReceive(final Context context, final Intent intent) {
6028 onStartCommand(intent, 0, 0);
6029 }
6030 }
6031
6032 private class RestrictedEventReceiver extends BroadcastReceiver {
6033
6034 private final Collection<String> allowedActions;
6035
6036 private RestrictedEventReceiver(final Collection<String> allowedActions) {
6037 this.allowedActions = allowedActions;
6038 }
6039
6040 @Override
6041 public void onReceive(final Context context, final Intent intent) {
6042 final String action = intent == null ? null : intent.getAction();
6043 if (allowedActions.contains(action)) {
6044 onStartCommand(intent,0,0);
6045 } else {
6046 Log.e(Config.LOGTAG,"restricting broadcast of event "+action);
6047 }
6048 }
6049 }
6050
6051 public static class OngoingCall {
6052 public final AbstractJingleConnection.Id id;
6053 public final Set<Media> media;
6054 public final boolean reconnecting;
6055
6056 public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
6057 this.id = id;
6058 this.media = media;
6059 this.reconnecting = reconnecting;
6060 }
6061
6062 @Override
6063 public boolean equals(Object o) {
6064 if (this == o) return true;
6065 if (o == null || getClass() != o.getClass()) return false;
6066 OngoingCall that = (OngoingCall) o;
6067 return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
6068 }
6069
6070 @Override
6071 public int hashCode() {
6072 return Objects.hashCode(id, media, reconnecting);
6073 }
6074 }
6075
6076 public static void toggleForegroundService(final XmppConnectionService service) {
6077 if (service == null) {
6078 return;
6079 }
6080 service.toggleForegroundService();
6081 }
6082
6083 public static void toggleForegroundService(final ConversationsActivity activity) {
6084 if (activity == null) {
6085 return;
6086 }
6087 toggleForegroundService(activity.xmppConnectionService);
6088 }
6089
6090 public static class BlockedMediaException extends Exception { }
6091
6092 public static enum UpdateRosterReason {
6093 INIT,
6094 AVATAR,
6095 PUSH,
6096 PRESENCE
6097 }
6098}