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 if (Compatibility.runsTwentySix()) {
1682 mNotificationService.initializeChannels();
1683 }
1684 final Notification notification;
1685 if (ongoing != null && !diallerIntegrationActive.get()) {
1686 notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1687 id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1688 startForegroundOrCatch(id, notification, true);
1689 } else if (ongoingVideoTranscoding) {
1690 notification = this.mNotificationService.getIndeterminateVideoTranscoding();
1691 id = NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID;
1692 startForegroundOrCatch(id, notification, false);
1693 } else {
1694 notification = this.mNotificationService.createForegroundNotification();
1695 id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1696 startForegroundOrCatch(id, notification, needMic || ongoing != null || diallerIntegrationActive.get());
1697 }
1698 mNotificationService.notify(id, notification);
1699 status = true;
1700 } else {
1701 id = 0;
1702 stopForeground(true);
1703 status = false;
1704 }
1705
1706 for (final int toBeRemoved :
1707 Collections2.filter(
1708 Arrays.asList(
1709 NotificationService.FOREGROUND_NOTIFICATION_ID,
1710 NotificationService.ONGOING_CALL_NOTIFICATION_ID,
1711 NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID),
1712 i -> i != id)) {
1713 mNotificationService.cancel(toBeRemoved);
1714 }
1715 Log.d(
1716 Config.LOGTAG,
1717 "ForegroundService: " + (status ? "on" : "off") + ", notification: " + id);
1718 }
1719
1720 private void startForegroundOrCatch(
1721 final int id, final Notification notification, final boolean requireMicrophone) {
1722 try {
1723 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
1724 final int foregroundServiceType;
1725 if (requireMicrophone
1726 && ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1727 == PackageManager.PERMISSION_GRANTED) {
1728 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1729 Log.d(Config.LOGTAG, "defaulting to microphone foreground service type");
1730 } else if (getSystemService(PowerManager.class)
1731 .isIgnoringBatteryOptimizations(getPackageName())) {
1732 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED;
1733 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1734 == PackageManager.PERMISSION_GRANTED) {
1735 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1736 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
1737 == PackageManager.PERMISSION_GRANTED) {
1738 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;
1739 } else {
1740 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
1741 Log.w(Config.LOGTAG, "falling back to special use foreground service type");
1742 }
1743
1744 startForeground(id, notification, foregroundServiceType);
1745 } else {
1746 startForeground(id, notification);
1747 }
1748 } catch (final IllegalStateException | SecurityException e) {
1749 Log.e(Config.LOGTAG, "Could not start foreground service", e);
1750 }
1751 }
1752
1753 public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1754 return !mOngoingVideoTranscoding.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1755 }
1756
1757 @Override
1758 public void onTaskRemoved(final Intent rootIntent) {
1759 super.onTaskRemoved(rootIntent);
1760 if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mOngoingVideoTranscoding.get() || ongoingCall.get() != null) {
1761 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1762 } else {
1763 this.logoutAndSave(false);
1764 }
1765 }
1766
1767 private void logoutAndSave(boolean stop) {
1768 int activeAccounts = 0;
1769 for (final Account account : accounts) {
1770 if (account.isConnectionEnabled()) {
1771 databaseBackend.writeRoster(account.getRoster());
1772 activeAccounts++;
1773 }
1774 if (account.getXmppConnection() != null) {
1775 new Thread(() -> disconnect(account, false)).start();
1776 }
1777 }
1778 if (stop || activeAccounts == 0) {
1779 Log.d(Config.LOGTAG, "good bye");
1780 stopSelf();
1781 }
1782 }
1783
1784 private void schedulePostConnectivityChange() {
1785 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1786 if (alarmManager == null) {
1787 return;
1788 }
1789 final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1790 final Intent intent = new Intent(this, SystemEventReceiver.class);
1791 intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1792 try {
1793 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, s()
1794 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1795 : PendingIntent.FLAG_UPDATE_CURRENT);
1796 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1797 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1798 } else {
1799 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1800 }
1801 } catch (RuntimeException e) {
1802 Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1803 }
1804 }
1805
1806 public void scheduleWakeUpCall(final int seconds, final int requestCode) {
1807 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000L;
1808 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1809 if (alarmManager == null) {
1810 return;
1811 }
1812 final Intent intent = new Intent(this, SystemEventReceiver.class);
1813 intent.setAction(ACTION_PING);
1814 try {
1815 final PendingIntent pendingIntent =
1816 PendingIntent.getBroadcast(
1817 this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1818 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1819 } catch (RuntimeException e) {
1820 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1821 }
1822 }
1823
1824 @TargetApi(Build.VERSION_CODES.M)
1825 private void scheduleNextIdlePing() {
1826 long timeUntilWake = Config.IDLE_PING_INTERVAL * 1000;
1827 final var now = System.currentTimeMillis();
1828 for (final var message : mScheduledMessages.values()) {
1829 if (message.getTimeSent() <= now) continue; // Just in case
1830 if (message.getTimeSent() - now < timeUntilWake) timeUntilWake = message.getTimeSent() - now;
1831 }
1832 final var timeToWake = SystemClock.elapsedRealtime() + timeUntilWake;
1833 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1834 if (alarmManager == null) {
1835 Log.d(Config.LOGTAG, "no alarm manager?");
1836 return;
1837 }
1838 final Intent intent = new Intent(this, SystemEventReceiver.class);
1839 intent.setAction(ACTION_IDLE_PING);
1840 try {
1841 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, s()
1842 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1843 : PendingIntent.FLAG_UPDATE_CURRENT);
1844 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1845 } catch (RuntimeException e) {
1846 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1847 }
1848 }
1849
1850 public XmppConnection createConnection(final Account account) {
1851 final XmppConnection connection = new XmppConnection(account, this);
1852 connection.setOnStatusChangedListener(this.statusListener);
1853 connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1854 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1855 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1856 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1857 AxolotlService axolotlService = account.getAxolotlService();
1858 if (axolotlService != null) {
1859 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1860 }
1861 return connection;
1862 }
1863
1864 public void sendChatState(Conversation conversation) {
1865 if (sendChatStates()) {
1866 final var packet = mMessageGenerator.generateChatState(conversation);
1867 sendMessagePacket(conversation.getAccount(), packet);
1868 }
1869 }
1870
1871 private void sendFileMessage(final Message message, final boolean delay) {
1872 Log.d(Config.LOGTAG, "send file message");
1873 final Account account = message.getConversation().getAccount();
1874 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1875 || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1876 mHttpConnectionManager.createNewUploadConnection(message, delay);
1877 } else {
1878 mJingleConnectionManager.startJingleFileTransfer(message);
1879 }
1880 }
1881
1882 public void sendMessage(final Message message) {
1883 sendMessage(message, false, false, false);
1884 }
1885
1886 private void sendMessage(final Message message, final boolean resend, final boolean previewedLinks, final boolean delay) {
1887 final Account account = message.getConversation().getAccount();
1888 if (account.setShowErrorNotification(true)) {
1889 databaseBackend.updateAccount(account);
1890 mNotificationService.updateErrorNotification();
1891 }
1892 final Conversation conversation = (Conversation) message.getConversation();
1893 account.deactivateGracePeriod();
1894
1895
1896 if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1897 final Contact contact = conversation.getContact();
1898 if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1899 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1900 createContact(contact, true);
1901 }
1902 }
1903
1904 im.conversations.android.xmpp.model.stanza.Message packet = null;
1905 final boolean addToConversation = !message.edited() && message.getRawBody() != null;
1906 boolean saveInDb = addToConversation;
1907 message.setStatus(Message.STATUS_WAITING);
1908
1909 if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1910 if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1911 databaseBackend.updateConversation(conversation);
1912 }
1913 }
1914
1915 final boolean inProgressJoin = isJoinInProgress(conversation);
1916
1917 if (message.getCounterpart() == null && !message.isPrivateMessage()) {
1918 message.setCounterpart(message.getConversation().getJid().asBareJid());
1919 }
1920
1921 boolean waitForPreview = false;
1922 if (getPreferences().getBoolean("send_link_previews", true) && !previewedLinks && !message.needsUploading() && message.getEncryption() != Message.ENCRYPTION_AXOLOTL) {
1923 message.clearLinkDescriptions();
1924 final List<URI> links = message.getLinks();
1925 if (!links.isEmpty()) {
1926 waitForPreview = true;
1927 if (account.isOnlineAndConnected()) {
1928 FILE_ATTACHMENT_EXECUTOR.execute(() -> {
1929 for (URI link : links) {
1930 if ("https".equals(link.getScheme())) {
1931 try {
1932 HttpUrl url = HttpUrl.parse(link.toString());
1933 OkHttpClient http = getHttpConnectionManager().buildHttpClient(url, account, 5, false);
1934 okhttp3.Response response = http.newCall(new okhttp3.Request.Builder().url(url).head().build()).execute();
1935 final String mimeType = response.header("Content-Type") == null ? "" : response.header("Content-Type");
1936 final boolean image = mimeType.startsWith("image/");
1937 final boolean audio = mimeType.startsWith("audio/");
1938 final boolean video = mimeType.startsWith("video/");
1939 final boolean pdf = mimeType.equals("application/pdf");
1940 final boolean html = mimeType.startsWith("text/html") || mimeType.startsWith("application/xhtml+xml");
1941 if (response.isSuccessful() && (image || audio || video || pdf)) {
1942 Message.FileParams params = message.getFileParams();
1943 params.url = url.toString();
1944 if (response.header("Content-Length") != null) params.size = Long.parseLong(response.header("Content-Length"), 10);
1945 if (!Message.configurePrivateFileMessage(message)) {
1946 message.setType(image ? Message.TYPE_IMAGE : Message.TYPE_FILE);
1947 }
1948 params.setName(HttpConnectionManager.extractFilenameFromResponse(response));
1949
1950 if (link.toString().equals(message.getRawBody())) {
1951 Element fallback = new Element("fallback", "urn:xmpp:fallback:0").setAttribute("for", Namespace.OOB);
1952 fallback.addChild("body", "urn:xmpp:fallback:0");
1953 message.addPayload(fallback);
1954 } else if (message.getRawBody().indexOf(link.toString()) >= 0) {
1955 // Part of the real body, not just a fallback
1956 Element fallback = new Element("fallback", "urn:xmpp:fallback:0").setAttribute("for", Namespace.OOB);
1957 fallback.addChild("body", "urn:xmpp:fallback:0")
1958 .setAttribute("start", "0")
1959 .setAttribute("end", "0");
1960 message.addPayload(fallback);
1961 }
1962
1963 final int encryption = message.getEncryption();
1964 getHttpConnectionManager().createNewDownloadConnection(message, false, (file) -> {
1965 message.setEncryption(encryption);
1966 synchronized (message.getConversation()) {
1967 if (message.getStatus() == Message.STATUS_WAITING) sendMessage(message, true, true, false);
1968 }
1969 });
1970 return;
1971 } else if (response.isSuccessful() && html) {
1972 Semaphore waiter = new Semaphore(0);
1973 OpenGraphParser.Builder openGraphBuilder = new OpenGraphParser.Builder(new OpenGraphCallback() {
1974 @Override
1975 public void onPostResponse(OpenGraphResult result) {
1976 Element rdf = new Element("Description", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
1977 rdf.setAttribute("xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
1978 rdf.setAttribute("rdf:about", link.toString());
1979 if (result.getTitle() != null && !"".equals(result.getTitle())) {
1980 rdf.addChild("title", "https://ogp.me/ns#").setContent(result.getTitle());
1981 }
1982 if (result.getDescription() != null && !"".equals(result.getDescription())) {
1983 rdf.addChild("description", "https://ogp.me/ns#").setContent(result.getDescription());
1984 }
1985 if (result.getUrl() != null) {
1986 rdf.addChild("url", "https://ogp.me/ns#").setContent(result.getUrl());
1987 }
1988 if (result.getImage() != null) {
1989 rdf.addChild("image", "https://ogp.me/ns#").setContent(result.getImage());
1990 }
1991 if (result.getType() != null) {
1992 rdf.addChild("type", "https://ogp.me/ns#").setContent(result.getType());
1993 }
1994 if (result.getSiteName() != null) {
1995 rdf.addChild("site_name", "https://ogp.me/ns#").setContent(result.getSiteName());
1996 }
1997 if (result.getVideo() != null) {
1998 rdf.addChild("video", "https://ogp.me/ns#").setContent(result.getVideo());
1999 }
2000 message.addPayload(rdf);
2001 waiter.release();
2002 }
2003
2004 public void onError(String error) {
2005 waiter.release();
2006 }
2007 })
2008 .showNullOnEmpty(true)
2009 .maxBodySize(90000)
2010 .timeout(5000);
2011 if (useTorToConnect()) {
2012 openGraphBuilder = openGraphBuilder.jsoupProxy(new JsoupProxy("127.0.0.1", 8118));
2013 }
2014 openGraphBuilder.build().parse(link.toString());
2015 waiter.tryAcquire(10L, TimeUnit.SECONDS);
2016 }
2017 } catch (final IOException | InterruptedException e) { }
2018 }
2019 }
2020 synchronized (message.getConversation()) {
2021 if (message.getStatus() == Message.STATUS_WAITING) sendMessage(message, true, true, false);
2022 }
2023 });
2024 }
2025 }
2026 }
2027
2028 if (account.isOnlineAndConnected() && !inProgressJoin && !waitForPreview && message.getTimeSent() <= System.currentTimeMillis()) {
2029 switch (message.getEncryption()) {
2030 case Message.ENCRYPTION_NONE:
2031 if (message.needsUploading()) {
2032 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
2033 || conversation.getMode() == Conversation.MODE_MULTI
2034 || message.fixCounterpart()) {
2035 this.sendFileMessage(message, delay);
2036 } else {
2037 break;
2038 }
2039 } else {
2040 packet = mMessageGenerator.generateChat(message);
2041 }
2042 break;
2043 case Message.ENCRYPTION_PGP:
2044 case Message.ENCRYPTION_DECRYPTED:
2045 if (message.needsUploading()) {
2046 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
2047 || conversation.getMode() == Conversation.MODE_MULTI
2048 || message.fixCounterpart()) {
2049 this.sendFileMessage(message, delay);
2050 } else {
2051 break;
2052 }
2053 } else {
2054 packet = mMessageGenerator.generatePgpChat(message);
2055 }
2056 break;
2057 case Message.ENCRYPTION_AXOLOTL:
2058 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
2059 if (message.needsUploading()) {
2060 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
2061 || conversation.getMode() == Conversation.MODE_MULTI
2062 || message.fixCounterpart()) {
2063 this.sendFileMessage(message, delay);
2064 } else {
2065 break;
2066 }
2067 } else {
2068 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
2069 if (axolotlMessage == null) {
2070 account.getAxolotlService().preparePayloadMessage(message, delay);
2071 } else {
2072 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
2073 }
2074 }
2075 break;
2076
2077 }
2078 if (packet != null) {
2079 if (account.getXmppConnection().getFeatures().sm()
2080 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
2081 message.setStatus(Message.STATUS_UNSEND);
2082 } else {
2083 message.setStatus(Message.STATUS_SEND);
2084 }
2085 }
2086 } else {
2087 switch (message.getEncryption()) {
2088 case Message.ENCRYPTION_DECRYPTED:
2089 if (!message.needsUploading()) {
2090 String pgpBody = message.getEncryptedBody();
2091 String decryptedBody = message.getBody();
2092 message.setBody(pgpBody); //TODO might throw NPE
2093 message.setEncryption(Message.ENCRYPTION_PGP);
2094 if (message.edited()) {
2095 message.setBody(decryptedBody);
2096 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
2097 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
2098 Log.e(Config.LOGTAG, "error updated message in DB after edit");
2099 }
2100 updateConversationUi();
2101 return;
2102 } else {
2103 databaseBackend.createMessage(message);
2104 saveInDb = false;
2105 message.setBody(decryptedBody);
2106 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
2107 }
2108 }
2109 break;
2110 case Message.ENCRYPTION_AXOLOTL:
2111 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
2112 break;
2113 }
2114 }
2115
2116 synchronized (mScheduledMessages) {
2117 if (message.getTimeSent() > System.currentTimeMillis()) {
2118 mScheduledMessages.put(message.getUuid(), message);
2119 scheduleNextIdlePing();
2120 } else {
2121 mScheduledMessages.remove(message.getUuid());
2122 }
2123 }
2124
2125 boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
2126 if (mucMessage) {
2127 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
2128 }
2129
2130 if (resend) {
2131 if (packet != null && addToConversation) {
2132 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
2133 markMessage(message, Message.STATUS_UNSEND);
2134 } else {
2135 markMessage(message, Message.STATUS_SEND);
2136 }
2137 }
2138 } else {
2139 if (addToConversation) {
2140 conversation.add(message);
2141 }
2142 if (saveInDb) {
2143 databaseBackend.createMessage(message);
2144 } else if (message.edited()) {
2145 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
2146 Log.e(Config.LOGTAG, "error updated message in DB after edit");
2147 }
2148 }
2149 updateConversationUi();
2150 }
2151 if (packet != null) {
2152 if (delay) {
2153 mMessageGenerator.addDelay(packet, message.getTimeSent());
2154 }
2155 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2156 if (this.sendChatStates()) {
2157 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
2158 }
2159 }
2160 sendMessagePacket(account, packet);
2161 if (message.getConversation().getMode() == Conversation.MODE_MULTI && message.hasCustomEmoji()) {
2162 if (message.getConversation() instanceof Conversation) presenceToMuc((Conversation) message.getConversation());
2163 }
2164 }
2165 }
2166
2167 private boolean isJoinInProgress(final Conversation conversation) {
2168 final Account account = conversation.getAccount();
2169 synchronized (account.inProgressConferenceJoins) {
2170 if (conversation.getMode() == Conversational.MODE_MULTI) {
2171 final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
2172 final boolean pending = account.pendingConferenceJoins.contains(conversation);
2173 final boolean inProgressJoin = inProgress || pending;
2174 if (inProgressJoin) {
2175 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
2176 }
2177 return inProgressJoin;
2178 } else {
2179 return false;
2180 }
2181 }
2182 }
2183
2184 private void sendUnsentMessages(final Conversation conversation) {
2185 synchronized (conversation) {
2186 conversation.findWaitingMessages(message -> resendMessage(message, true));
2187 }
2188 }
2189
2190 public void resendMessage(final Message message, final boolean delay) {
2191 sendMessage(message, true, false, delay);
2192 }
2193
2194 public void resendMessage(final Message message, final boolean delay, final boolean previewedLinks) {
2195 sendMessage(message, true, previewedLinks, delay);
2196 }
2197
2198 public Pair<Account,Account> onboardingIncomplete() {
2199 if (getAccounts().size() != 2) return null;
2200 Account onboarding = null;
2201 Account newAccount = null;
2202 for (final Account account : getAccounts()) {
2203 if (account.getJid().getDomain().equals(Config.ONBOARDING_DOMAIN)) {
2204 onboarding = account;
2205 } else {
2206 newAccount = account;
2207 }
2208 }
2209
2210 if (onboarding != null && newAccount != null) {
2211 return new Pair<>(onboarding, newAccount);
2212 }
2213
2214 return null;
2215 }
2216
2217 public boolean isOnboarding() {
2218 return getAccounts().size() == 1 && getAccounts().get(0).getJid().getDomain().equals(Config.ONBOARDING_DOMAIN);
2219 }
2220
2221 public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
2222 final XmppConnection connection = account.getXmppConnection();
2223 final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
2224 if (jid == null) {
2225 callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
2226 return;
2227 }
2228 final Iq request = new Iq(Iq.Type.SET);
2229 request.setTo(jid);
2230 final Element command = request.addChild("command", Namespace.COMMANDS);
2231 command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
2232 command.setAttribute("action", "execute");
2233 sendIqPacket(account, request, (response) -> {
2234 if (response.getType() == Iq.Type.RESULT) {
2235 final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
2236 final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
2237 if (x != null) {
2238 final Data data = Data.parse(x);
2239 final String uri = data.getValue("uri");
2240 final String landingUrl = data.getValue("landing-url");
2241 if (uri != null) {
2242 final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
2243 callback.inviteRequested(invite);
2244 return;
2245 }
2246 }
2247 callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
2248 Log.d(Config.LOGTAG, response.toString());
2249 } else if (response.getType() == Iq.Type.ERROR) {
2250 callback.inviteRequestFailed(IqParser.errorMessage(response));
2251 } else {
2252 callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
2253 }
2254 });
2255
2256 }
2257
2258 public void fetchBookmarks(final Account account) {
2259 final Iq iqPacket = new Iq(Iq.Type.GET);
2260 final Element query = iqPacket.query("jabber:iq:private");
2261 query.addChild("storage", Namespace.BOOKMARKS);
2262 final Consumer<Iq> callback = (response) -> {
2263 if (response.getType() == Iq.Type.RESULT) {
2264 final Element query1 = response.query();
2265 final Element storage = query1.findChild("storage", "storage:bookmarks");
2266 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
2267 processBookmarksInitial(account, bookmarks, false);
2268 } else {
2269 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not fetch bookmarks");
2270 }
2271 };
2272 sendIqPacket(account, iqPacket, callback);
2273 }
2274
2275 public void fetchBookmarks2(final Account account) {
2276 final Iq retrieve = mIqGenerator.retrieveBookmarks();
2277 sendIqPacket(account, retrieve, (response) -> {
2278 if (response.getType() == Iq.Type.RESULT) {
2279 final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
2280 final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubSub(pubsub, account);
2281 processBookmarksInitial(account, bookmarks, true);
2282 }
2283 });
2284 }
2285
2286 public void fetchMessageDisplayedSynchronization(final Account account) {
2287 Log.d(Config.LOGTAG, account.getJid() + ": retrieve mds");
2288 final var retrieve = mIqGenerator.retrieveMds();
2289 sendIqPacket(
2290 account,
2291 retrieve,
2292 (response) -> {
2293 if (response.getType() != Iq.Type.RESULT) {
2294 return;
2295 }
2296 final var pubSub = response.findChild("pubsub", Namespace.PUBSUB);
2297 final Element items = pubSub == null ? null : pubSub.findChild("items");
2298 if (items == null
2299 || !Namespace.MDS_DISPLAYED.equals(items.getAttribute("node"))) {
2300 return;
2301 }
2302 for (final Element child : items.getChildren()) {
2303 if ("item".equals(child.getName())) {
2304 processMdsItem(account, child);
2305 }
2306 }
2307 });
2308 }
2309
2310 public void processMdsItem(final Account account, final Element item) {
2311 final Jid jid =
2312 item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("id"));
2313 if (jid == null) {
2314 return;
2315 }
2316 final Element displayed = item.findChild("displayed", Namespace.MDS_DISPLAYED);
2317 final Element stanzaId =
2318 displayed == null ? null : displayed.findChild("stanza-id", Namespace.STANZA_IDS);
2319 final String id = stanzaId == null ? null : stanzaId.getAttribute("id");
2320 final Conversation conversation = find(account, jid);
2321 if (id != null && conversation != null) {
2322 conversation.setDisplayState(id);
2323 markReadUpToStanzaId(conversation, id);
2324 }
2325 }
2326
2327 public void markReadUpToStanzaId(final Conversation conversation, final String stanzaId) {
2328 final Message message = conversation.findMessageWithServerMsgId(stanzaId);
2329 if (message == null) { // do we want to check if isRead?
2330 return;
2331 }
2332 markReadUpTo(conversation, message);
2333 }
2334
2335 public void markReadUpTo(final Conversation conversation, final Message message) {
2336 final boolean isDismissNotification = isDismissNotification(message);
2337 final var uuid = message.getUuid();
2338 Log.d(
2339 Config.LOGTAG,
2340 conversation.getAccount().getJid().asBareJid()
2341 + ": mark "
2342 + conversation.getJid().asBareJid()
2343 + " as read up to "
2344 + uuid);
2345 markRead(conversation, uuid, isDismissNotification);
2346 }
2347
2348 private static boolean isDismissNotification(final Message message) {
2349 Message next = message.next();
2350 while (next != null) {
2351 if (message.getStatus() == Message.STATUS_RECEIVED) {
2352 return false;
2353 }
2354 next = next.next();
2355 }
2356 return true;
2357 }
2358
2359 public void processBookmarksInitial(final Account account, final Map<Jid, Bookmark> bookmarks, final boolean pep) {
2360 final Set<Jid> previousBookmarks = account.getBookmarkedJids();
2361 for (final Bookmark bookmark : bookmarks.values()) {
2362 previousBookmarks.remove(bookmark.getJid().asBareJid());
2363 processModifiedBookmark(bookmark, pep);
2364 }
2365 if (pep) {
2366 processDeletedBookmarks(account, previousBookmarks);
2367 }
2368 account.setBookmarks(bookmarks);
2369 }
2370
2371 public void processDeletedBookmarks(final Account account, final Collection<Jid> bookmarks) {
2372 Log.d(
2373 Config.LOGTAG,
2374 account.getJid().asBareJid()
2375 + ": "
2376 + bookmarks.size()
2377 + " bookmarks have been removed");
2378 for (final Jid bookmark : bookmarks) {
2379 processDeletedBookmark(account, bookmark);
2380 }
2381 }
2382
2383 public void processDeletedBookmark(final Account account, final Jid jid) {
2384 final Conversation conversation = find(account, jid);
2385 if (conversation == null) {
2386 return;
2387 }
2388 Log.d(
2389 Config.LOGTAG,
2390 account.getJid().asBareJid() + ": archiving MUC " + jid + " after PEP update");
2391 archiveConversation(conversation, false);
2392 }
2393
2394 private void processModifiedBookmark(final Bookmark bookmark, final boolean pep) {
2395 final Account account = bookmark.getAccount();
2396 Conversation conversation = find(bookmark);
2397 if (conversation != null) {
2398 if (conversation.getMode() != Conversation.MODE_MULTI) {
2399 return;
2400 }
2401 bookmark.setConversation(conversation);
2402 if (pep && !bookmark.autojoin()) {
2403 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
2404 archiveConversation(conversation, false);
2405 } else {
2406 final MucOptions mucOptions = conversation.getMucOptions();
2407 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
2408 final String current = mucOptions.getActualNick();
2409 final String proposed = mucOptions.getProposedNick();
2410 if (current != null && !current.equals(proposed)) {
2411 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
2412 joinMuc(conversation);
2413 }
2414 }
2415 }
2416 } else if (bookmark.autojoin()) {
2417 conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
2418 bookmark.setConversation(conversation);
2419 }
2420 }
2421
2422 public void processModifiedBookmark(final Bookmark bookmark) {
2423 processModifiedBookmark(bookmark, true);
2424 }
2425
2426 public void createBookmark(final Account account, final Bookmark bookmark) {
2427 account.putBookmark(bookmark);
2428 final XmppConnection connection = account.getXmppConnection();
2429 if (connection == null) {
2430 Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
2431 } else if (connection.getFeatures().bookmarks2()) {
2432 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": pushing bookmark via Bookmarks 2");
2433 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
2434 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
2435 } else if (connection.getFeatures().bookmarksConversion()) {
2436 pushBookmarksPep(account);
2437 } else {
2438 pushBookmarksPrivateXml(account);
2439 }
2440 }
2441
2442 public void deleteBookmark(final Account account, final Bookmark bookmark) {
2443 if (bookmark.getJid().toString().equals("discuss@conference.soprani.ca")) {
2444 getPreferences().edit().putBoolean("cheogram_sopranica_bookmark_deleted", true).apply();
2445 }
2446 account.removeBookmark(bookmark);
2447 final XmppConnection connection = account.getXmppConnection();
2448 if (connection == null) return;
2449
2450 if (connection.getFeatures().bookmarks2()) {
2451 final Iq request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
2452 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": removing bookmark via Bookmarks 2");
2453 sendIqPacket(account, request, (response) -> {
2454 if (response.getType() == Iq.Type.ERROR) {
2455 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
2456 }
2457 });
2458 } else if (connection.getFeatures().bookmarksConversion()) {
2459 pushBookmarksPep(account);
2460 } else {
2461 pushBookmarksPrivateXml(account);
2462 }
2463 }
2464
2465 private void pushBookmarksPrivateXml(Account account) {
2466 if (!account.areBookmarksLoaded()) return;
2467
2468 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
2469 final Iq iqPacket = new Iq(Iq.Type.SET);
2470 Element query = iqPacket.query("jabber:iq:private");
2471 Element storage = query.addChild("storage", "storage:bookmarks");
2472 for (final Bookmark bookmark : account.getBookmarks()) {
2473 storage.addChild(bookmark);
2474 }
2475 sendIqPacket(account, iqPacket, mDefaultIqHandler);
2476 }
2477
2478 private void pushBookmarksPep(Account account) {
2479 if (!account.areBookmarksLoaded()) return;
2480
2481 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
2482 final Element storage = new Element("storage", "storage:bookmarks");
2483 for (final Bookmark bookmark : account.getBookmarks()) {
2484 storage.addChild(bookmark);
2485 }
2486 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
2487
2488 }
2489
2490 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
2491 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2492
2493 }
2494
2495 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
2496 final Iq packet = mIqGenerator.publishElement(node, element, id, options);
2497 sendIqPacket(account, packet, (response) -> {
2498 if (response.getType() == Iq.Type.RESULT) {
2499 return;
2500 }
2501 if (retry && PublishOptions.preconditionNotMet(response)) {
2502 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
2503 @Override
2504 public void onPushSucceeded() {
2505 pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
2506 }
2507
2508 @Override
2509 public void onPushFailed() {
2510 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
2511 }
2512 });
2513 } else {
2514 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing "+node+" (retry=" + retry + ") " + response);
2515 }
2516 });
2517 }
2518
2519 private void restoreFromDatabase() {
2520 synchronized (this.conversations) {
2521 final Map<String, Account> accountLookupTable = new Hashtable<>();
2522 for (Account account : this.accounts) {
2523 accountLookupTable.put(account.getUuid(), account);
2524 }
2525 Log.d(Config.LOGTAG, "restoring conversations...");
2526 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2527 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2528 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
2529 Conversation conversation = iterator.next();
2530 Account account = accountLookupTable.get(conversation.getAccountUuid());
2531 if (account != null) {
2532 conversation.setAccount(account);
2533 } else {
2534 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
2535 conversations.remove(conversation);
2536 }
2537 }
2538 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2539 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
2540 Runnable runnable = () -> {
2541 if (DatabaseBackend.requiresMessageIndexRebuild()) {
2542 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2543 }
2544 mutedMucUsers = databaseBackend.loadMutedMucUsers();
2545 final long deletionDate = getAutomaticMessageDeletionDate();
2546 mLastExpiryRun.set(SystemClock.elapsedRealtime());
2547 if (deletionDate > 0) {
2548 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
2549 databaseBackend.expireOldMessages(deletionDate);
2550 }
2551 Log.d(Config.LOGTAG, "restoring roster...");
2552 for (final Account account : accounts) {
2553 databaseBackend.readRoster(account.getRoster());
2554 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
2555 }
2556 getDrawableCache().evictAll();
2557 loadPhoneContacts();
2558 Log.d(Config.LOGTAG, "restoring messages...");
2559 final long startMessageRestore = SystemClock.elapsedRealtime();
2560 final Conversation quickLoad = QuickLoader.get(this.conversations);
2561 if (quickLoad != null) {
2562 restoreMessages(quickLoad);
2563 updateConversationUi();
2564 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2565 Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
2566 }
2567 for (Conversation conversation : this.conversations) {
2568 if (quickLoad != conversation) {
2569 restoreMessages(conversation);
2570 }
2571 }
2572 mNotificationService.finishBacklog();
2573 restoredFromDatabaseLatch.countDown();
2574 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2575 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2576 updateConversationUi();
2577 };
2578 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2579 }
2580 }
2581
2582 private void restoreMessages(Conversation conversation) {
2583 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2584 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2585 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2586 }
2587
2588 public void loadPhoneContacts() {
2589 mContactMergerExecutor.execute(() -> {
2590 final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2591 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2592 for (final Account account : accounts) {
2593 final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2594 for (final JabberIdContact jidContact : contacts.values()) {
2595 final Contact contact = account.getRoster().getContact(jidContact.getJid());
2596 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2597 if (needsCacheClean) {
2598 getAvatarService().clear(contact);
2599 }
2600 withSystemAccounts.remove(contact);
2601 }
2602 for (final Contact contact : withSystemAccounts) {
2603 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2604 if (needsCacheClean) {
2605 getAvatarService().clear(contact);
2606 }
2607 }
2608 }
2609 Log.d(Config.LOGTAG, "finished merging phone contacts");
2610 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2611 updateRosterUi(UpdateRosterReason.INIT);
2612 mQuickConversationsService.considerSync();
2613 });
2614 }
2615
2616
2617 public void syncRoster(final Account account) {
2618 mRosterSyncTaskManager.execute(account, () -> {
2619 unregisterPhoneAccounts(account);
2620 databaseBackend.writeRoster(account.getRoster());
2621 try { Thread.sleep(500); } catch (InterruptedException e) { }
2622 });
2623 }
2624
2625 public List<Conversation> getConversations() {
2626 return this.conversations;
2627 }
2628
2629 private void markFileDeleted(final File file) {
2630 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2631 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2632 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2633 return;
2634 }
2635 }
2636 final boolean isInternalFile = fileBackend.isInternalFile(file);
2637 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2638 Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2639 markUuidsAsDeletedFiles(uuids);
2640 }
2641
2642 private void markUuidsAsDeletedFiles(List<String> uuids) {
2643 boolean deleted = false;
2644 for (Conversation conversation : getConversations()) {
2645 deleted |= conversation.markAsDeleted(uuids);
2646 }
2647 for (final String uuid : uuids) {
2648 evictPreview(uuid);
2649 }
2650 if (deleted) {
2651 updateConversationUi();
2652 }
2653 }
2654
2655 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2656 boolean changed = false;
2657 for (Conversation conversation : getConversations()) {
2658 changed |= conversation.markAsChanged(infos);
2659 }
2660 if (changed) {
2661 updateConversationUi();
2662 }
2663 }
2664
2665 public void populateWithOrderedConversations(final List<Conversation> list) {
2666 populateWithOrderedConversations(list, true, true);
2667 }
2668
2669 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2670 populateWithOrderedConversations(list, includeNoFileUpload, true);
2671 }
2672
2673 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2674 final List<String> orderedUuids;
2675 if (sort) {
2676 orderedUuids = null;
2677 } else {
2678 orderedUuids = new ArrayList<>();
2679 for (Conversation conversation : list) {
2680 orderedUuids.add(conversation.getUuid());
2681 }
2682 }
2683 list.clear();
2684 if (includeNoFileUpload) {
2685 list.addAll(getConversations());
2686 } else {
2687 for (Conversation conversation : getConversations()) {
2688 if (conversation.getMode() == Conversation.MODE_SINGLE
2689 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2690 list.add(conversation);
2691 }
2692 }
2693 }
2694 try {
2695 if (orderedUuids != null) {
2696 Collections.sort(list, (a, b) -> {
2697 final int indexA = orderedUuids.indexOf(a.getUuid());
2698 final int indexB = orderedUuids.indexOf(b.getUuid());
2699 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2700 return a.compareTo(b);
2701 }
2702 return indexA - indexB;
2703 });
2704 } else {
2705 Collections.sort(list);
2706 }
2707 } catch (IllegalArgumentException e) {
2708 //ignore
2709 }
2710 }
2711
2712 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2713 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback) || conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2714 return;
2715 } else if (timestamp == 0) {
2716 return;
2717 }
2718 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2719 final Runnable runnable = () -> {
2720 final Account account = conversation.getAccount();
2721 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2722 if (messages.size() > 0) {
2723 conversation.addAll(0, messages);
2724 callback.onMoreMessagesLoaded(messages.size(), conversation);
2725 } else if (conversation.hasMessagesLeftOnServer()
2726 && account.isOnlineAndConnected()
2727 && conversation.getLastClearHistory().getTimestamp() == 0) {
2728 final boolean mamAvailable;
2729 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2730 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2731 } else {
2732 mamAvailable = conversation.getMucOptions().mamSupport();
2733 }
2734 if (mamAvailable) {
2735 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2736 if (query != null) {
2737 query.setCallback(callback);
2738 callback.informUser(R.string.fetching_history_from_server);
2739 } else {
2740 callback.informUser(R.string.not_fetching_history_retention_period);
2741 }
2742
2743 }
2744 }
2745 };
2746 mDatabaseReaderExecutor.execute(runnable);
2747 }
2748
2749 public List<Account> getAccounts() {
2750 return this.accounts;
2751 }
2752
2753
2754 /**
2755 * 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)
2756 */
2757 public List<Conversation> findAllConferencesWith(Contact contact) {
2758 final ArrayList<Conversation> results = new ArrayList<>();
2759 for (final Conversation c : conversations) {
2760 if (c.getMode() != Conversation.MODE_MULTI) {
2761 continue;
2762 }
2763 final MucOptions mucOptions = c.getMucOptions();
2764 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2765 results.add(c);
2766 }
2767 }
2768 return results;
2769 }
2770
2771 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2772 for (final Conversation conversation : haystack) {
2773 if (conversation.getContact() == contact) {
2774 return conversation;
2775 }
2776 }
2777 return null;
2778 }
2779
2780 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2781 if (jid == null) {
2782 return null;
2783 }
2784 for (final Conversation conversation : haystack) {
2785 if ((account == null || conversation.getAccount() == account)
2786 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2787 return conversation;
2788 }
2789 }
2790 return null;
2791 }
2792
2793 public boolean isConversationsListEmpty(final Conversation ignore) {
2794 synchronized (this.conversations) {
2795 final int size = this.conversations.size();
2796 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2797 }
2798 }
2799
2800 public boolean isConversationStillOpen(final Conversation conversation) {
2801 synchronized (this.conversations) {
2802 for (Conversation current : this.conversations) {
2803 if (current == conversation) {
2804 return true;
2805 }
2806 }
2807 }
2808 return false;
2809 }
2810
2811 public void maybeRegisterWithMuc(Conversation c, String nickArg) {
2812 final var nick = nickArg == null ? c.getMucOptions().getSelf().getFullJid().getResource() : nickArg;
2813 final var register = new Iq(Iq.Type.GET);
2814 register.query(Namespace.REGISTER);
2815 register.setTo(c.getJid().asBareJid());
2816 sendIqPacket(c.getAccount(), register, (response) -> {
2817 if (response.getType() == Iq.Type.RESULT) {
2818 final Element query = response.query(Namespace.REGISTER);
2819 String username = query.findChildContent("username", Namespace.REGISTER);
2820 if (username == null) username = query.findChildContent("nick", Namespace.REGISTER);
2821 if (username != null && username.equals(nick)) {
2822 // Already registered with this nick, done
2823 Log.d(Config.LOGTAG, "Already registered with " + c.getJid().asBareJid() + " as " + username);
2824 return;
2825 }
2826 Data form = Data.parse(query.findChild("x", Namespace.DATA));
2827 if (form != null) {
2828 final var field = form.getFieldByName("muc#register_roomnick");
2829 if (field != null && nick.equals(field.getValue())) {
2830 Log.d(Config.LOGTAG, "Already registered with " + c.getJid().asBareJid() + " as " + field.getValue());
2831 return;
2832 }
2833 }
2834 if (form == null || !"form".equals(form.getFormType()) || !form.getFields().stream().anyMatch(f -> f.isRequired() && !"muc#register_roomnick".equals(f.getFieldName()))) {
2835 // No form, result form, or no required fields other than nickname, let's just send nickname
2836 if (form == null || !"form".equals(form.getFormType())) {
2837 form = new Data();
2838 form.put("FORM_TYPE", "http://jabber.org/protocol/muc#register");
2839 }
2840 form.put("muc#register_roomnick", nick);
2841 form.submit();
2842 final var finish = new Iq(Iq.Type.SET);
2843 finish.query(Namespace.REGISTER).addChild(form);
2844 finish.setTo(c.getJid().asBareJid());
2845 sendIqPacket(c.getAccount(), finish, (response2) -> {
2846 if (response.getType() == Iq.Type.RESULT) {
2847 Log.w(Config.LOGTAG, "Success registering with channel " + c.getJid().asBareJid() + "/" + nick);
2848 } else {
2849 Log.w(Config.LOGTAG, "Error registering with channel: " + response2);
2850 }
2851 });
2852 } else {
2853 // TODO: offer registration form to user
2854 Log.d(Config.LOGTAG, "Complex registration form for " + c.getJid().asBareJid() + ": " + response);
2855 }
2856 } else {
2857 // We said maybe. Guess not
2858 Log.d(Config.LOGTAG, "Could not register with " + c.getJid().asBareJid() + ": " + response);
2859 }
2860 });
2861 }
2862
2863 public void deregisterWithMuc(Conversation c) {
2864 final Iq register = new Iq(Iq.Type.GET);
2865 register.query(Namespace.REGISTER).addChild("remove");
2866 register.setTo(c.getJid().asBareJid());
2867 sendIqPacket(c.getAccount(), register, (response) -> {
2868 if (response.getType() == Iq.Type.RESULT) {
2869 Log.d(Config.LOGTAG, "deregistered with " + c.getJid().asBareJid());
2870 } else {
2871 Log.w(Config.LOGTAG, "Could not deregister with " + c.getJid().asBareJid() + ": " + response);
2872 }
2873 });
2874 }
2875
2876 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2877 return this.findOrCreateConversation(account, jid, muc, false, async);
2878 }
2879
2880 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2881 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async, null);
2882 }
2883
2884 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2885 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, query, async, null);
2886 }
2887
2888 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) {
2889 synchronized (this.conversations) {
2890 Conversation conversation = find(account, jid);
2891 if (conversation != null) {
2892 return conversation;
2893 }
2894 conversation = databaseBackend.findConversation(account, jid);
2895 final boolean loadMessagesFromDb;
2896 if (conversation != null) {
2897 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2898 conversation.setAccount(account);
2899 if (muc) {
2900 conversation.setMode(Conversation.MODE_MULTI);
2901 conversation.setContactJid(jid);
2902 if (password != null) conversation.getMucOptions().setPassword(password);
2903 } else {
2904 conversation.setMode(Conversation.MODE_SINGLE);
2905 conversation.setContactJid(jid.asBareJid());
2906 }
2907 databaseBackend.updateConversation(conversation);
2908 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2909 } else {
2910 String conversationName;
2911 Contact contact = account.getRoster().getContact(jid);
2912 if (contact != null) {
2913 conversationName = contact.getDisplayName();
2914 } else {
2915 conversationName = jid.getLocal();
2916 }
2917 if (muc) {
2918 conversation = new Conversation(conversationName, account, jid,
2919 Conversation.MODE_MULTI);
2920 if (password != null) conversation.getMucOptions().setPassword(password);
2921 } else {
2922 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2923 Conversation.MODE_SINGLE);
2924 }
2925 this.databaseBackend.createConversation(conversation);
2926 loadMessagesFromDb = false;
2927 }
2928 final Conversation c = conversation;
2929 final Runnable runnable = () -> {
2930 if (loadMessagesFromDb) {
2931 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2932 updateConversationUi();
2933 c.messagesLoaded.set(true);
2934 }
2935 if (account.getXmppConnection() != null
2936 && !c.getContact().isBlocked()
2937 && account.getXmppConnection().getFeatures().mam()
2938 && !muc) {
2939 if (query == null) {
2940 mMessageArchiveService.query(c);
2941 } else {
2942 if (query.getConversation() == null) {
2943 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2944 }
2945 }
2946 }
2947 if (joinAfterCreate) {
2948 joinMuc(c);
2949 }
2950 };
2951 if (async) {
2952 mDatabaseReaderExecutor.execute(runnable);
2953 } else {
2954 runnable.run();
2955 }
2956 this.conversations.add(conversation);
2957 updateConversationUi();
2958 return conversation;
2959 }
2960 }
2961
2962 public void archiveConversation(Conversation conversation) {
2963 archiveConversation(conversation, true);
2964 }
2965
2966 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2967 if (isOnboarding()) return;
2968
2969 getNotificationService().clear(conversation);
2970 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2971 conversation.setNextMessage(null);
2972 synchronized (this.conversations) {
2973 getMessageArchiveService().kill(conversation);
2974 if (conversation.getMode() == Conversation.MODE_MULTI) {
2975 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2976 final Bookmark bookmark = conversation.getBookmark();
2977 if (maySynchronizeWithBookmarks && bookmark != null) {
2978 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2979 Account account = bookmark.getAccount();
2980 bookmark.setConversation(null);
2981 deleteBookmark(account, bookmark);
2982 } else if (bookmark.autojoin()) {
2983 bookmark.setAutojoin(false);
2984 createBookmark(bookmark.getAccount(), bookmark);
2985 }
2986 }
2987 }
2988 deregisterWithMuc(conversation);
2989 leaveMuc(conversation);
2990 } else {
2991 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2992 stopPresenceUpdatesTo(conversation.getContact());
2993 }
2994 }
2995 updateConversation(conversation);
2996 this.conversations.remove(conversation);
2997 updateConversationUi();
2998 }
2999 }
3000
3001 public void stopPresenceUpdatesTo(Contact contact) {
3002 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
3003 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
3004 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3005 }
3006
3007 public void createAccount(final Account account) {
3008 account.initAccountServices(this);
3009 databaseBackend.createAccount(account);
3010 if (CallIntegration.hasSystemFeature(this)) {
3011 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
3012 }
3013 this.accounts.add(account);
3014 this.reconnectAccountInBackground(account);
3015 updateAccountUi();
3016 syncEnabledAccountSetting();
3017 toggleForegroundService();
3018 }
3019
3020 private void syncEnabledAccountSetting() {
3021 final boolean hasEnabledAccounts = hasEnabledAccounts();
3022 getPreferences().edit().putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
3023 toggleSetProfilePictureActivity(hasEnabledAccounts);
3024 }
3025
3026 private void toggleSetProfilePictureActivity(final boolean enabled) {
3027 try {
3028 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
3029 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
3030 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
3031 } catch (IllegalStateException e) {
3032 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
3033 }
3034 }
3035
3036 public boolean reconfigurePushDistributor() {
3037 return this.unifiedPushBroker.reconfigurePushDistributor();
3038 }
3039
3040 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
3041 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
3042 }
3043
3044 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
3045 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
3046 }
3047
3048 public UnifiedPushBroker getUnifiedPushBroker() {
3049 return this.unifiedPushBroker;
3050 }
3051
3052 private void provisionAccount(final String address, final String password) {
3053 final Jid jid = Jid.ofEscaped(address);
3054 final Account account = new Account(jid, password);
3055 account.setOption(Account.OPTION_DISABLED, true);
3056 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
3057 createAccount(account);
3058 }
3059
3060 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
3061 new Thread(() -> {
3062 try {
3063 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
3064 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
3065 if (cert == null) {
3066 callback.informUser(R.string.unable_to_parse_certificate);
3067 return;
3068 }
3069 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
3070 if (info == null) {
3071 callback.informUser(R.string.certificate_does_not_contain_jid);
3072 return;
3073 }
3074 if (findAccountByJid(info.first) == null) {
3075 final Account account = new Account(info.first, "");
3076 account.setPrivateKeyAlias(alias);
3077 account.setOption(Account.OPTION_DISABLED, true);
3078 account.setOption(Account.OPTION_FIXED_USERNAME, true);
3079 account.setDisplayName(info.second);
3080 createAccount(account);
3081 callback.onAccountCreated(account);
3082 if (Config.X509_VERIFICATION) {
3083 try {
3084 getMemorizingTrustManager().getNonInteractive(account.getServer(), null, 0, null).checkClientTrusted(chain, "RSA");
3085 } catch (CertificateException e) {
3086 callback.informUser(R.string.certificate_chain_is_not_trusted);
3087 }
3088 }
3089 } else {
3090 callback.informUser(R.string.account_already_exists);
3091 }
3092 } catch (Exception e) {
3093 callback.informUser(R.string.unable_to_parse_certificate);
3094 }
3095 }).start();
3096
3097 }
3098
3099 public void updateKeyInAccount(final Account account, final String alias) {
3100 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
3101 try {
3102 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
3103 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
3104 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
3105 if (info == null) {
3106 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
3107 return;
3108 }
3109 if (account.getJid().asBareJid().equals(info.first)) {
3110 account.setPrivateKeyAlias(alias);
3111 account.setDisplayName(info.second);
3112 databaseBackend.updateAccount(account);
3113 if (Config.X509_VERIFICATION) {
3114 try {
3115 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
3116 } catch (CertificateException e) {
3117 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
3118 }
3119 account.getAxolotlService().regenerateKeys(true);
3120 }
3121 } else {
3122 showErrorToastInUi(R.string.jid_does_not_match_certificate);
3123 }
3124 } catch (Exception e) {
3125 e.printStackTrace();
3126 }
3127 }
3128
3129 public boolean updateAccount(final Account account) {
3130 if (databaseBackend.updateAccount(account)) {
3131 Integer color = account.getColorToSave();
3132 if (color == null) {
3133 getPreferences().edit().remove("account_color:" + account.getUuid()).commit();
3134 } else {
3135 getPreferences().edit().putInt("account_color:" + account.getUuid(), color.intValue()).commit();
3136 }
3137 account.setShowErrorNotification(true);
3138 this.statusListener.onStatusChanged(account);
3139 databaseBackend.updateAccount(account);
3140 reconnectAccountInBackground(account);
3141 updateAccountUi();
3142 getNotificationService().updateErrorNotification();
3143 toggleForegroundService();
3144 syncEnabledAccountSetting();
3145 mChannelDiscoveryService.cleanCache();
3146 if (CallIntegration.hasSystemFeature(this)) {
3147 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
3148 }
3149 return true;
3150 } else {
3151 return false;
3152 }
3153 }
3154
3155 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
3156 final Iq iq = getIqGenerator().generateSetPassword(account, newPassword);
3157 sendIqPacket(account, iq, (packet) -> {
3158 if (packet.getType() == Iq.Type.RESULT) {
3159 account.setPassword(newPassword);
3160 account.setOption(Account.OPTION_MAGIC_CREATE, false);
3161 databaseBackend.updateAccount(account);
3162 callback.onPasswordChangeSucceeded();
3163 } else {
3164 callback.onPasswordChangeFailed();
3165 }
3166 });
3167 }
3168
3169 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
3170 final Iq iqPacket = new Iq(Iq.Type.SET);
3171 final Element query = iqPacket.addChild("query",Namespace.REGISTER);
3172 query.addChild("remove");
3173 sendIqPacket(account, iqPacket, (response) -> {
3174 if (response.getType() == Iq.Type.RESULT) {
3175 deleteAccount(account);
3176 callback.accept(true);
3177 } else {
3178 callback.accept(false);
3179 }
3180 });
3181 }
3182
3183 public void deleteAccount(final Account account) {
3184 getPreferences().edit().remove("onboarding_continued").commit();
3185 final boolean connected = account.getStatus() == Account.State.ONLINE;
3186 synchronized (this.conversations) {
3187 if (connected) {
3188 account.getAxolotlService().deleteOmemoIdentity();
3189 }
3190 for (final Conversation conversation : conversations) {
3191 if (conversation.getAccount() == account) {
3192 if (conversation.getMode() == Conversation.MODE_MULTI) {
3193 if (connected) {
3194 leaveMuc(conversation);
3195 }
3196 }
3197 conversations.remove(conversation);
3198 mNotificationService.clear(conversation);
3199 }
3200 }
3201 new Thread(() -> {
3202 for (final Contact contact : account.getRoster().getContacts()) {
3203 contact.unregisterAsPhoneAccount(this);
3204 }
3205 }).start();
3206 if (account.getXmppConnection() != null) {
3207 new Thread(() -> disconnect(account, !connected)).start();
3208 }
3209 final Runnable runnable = () -> {
3210 if (!databaseBackend.deleteAccount(account)) {
3211 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
3212 }
3213 };
3214 mDatabaseWriterExecutor.execute(runnable);
3215 this.accounts.remove(account);
3216 if (CallIntegration.hasSystemFeature(this)) {
3217 CallIntegrationConnectionService.unregisterPhoneAccount(this, account);
3218 }
3219 this.mRosterSyncTaskManager.clear(account);
3220 updateAccountUi();
3221 mNotificationService.updateErrorNotification();
3222 syncEnabledAccountSetting();
3223 toggleForegroundService();
3224 }
3225 }
3226
3227 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
3228 final boolean remainingListeners;
3229 synchronized (LISTENER_LOCK) {
3230 remainingListeners = checkListeners();
3231 if (!this.mOnConversationUpdates.add(listener)) {
3232 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
3233 }
3234 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3235 }
3236 if (remainingListeners) {
3237 switchToForeground();
3238 }
3239 }
3240
3241 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
3242 final boolean remainingListeners;
3243 synchronized (LISTENER_LOCK) {
3244 this.mOnConversationUpdates.remove(listener);
3245 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3246 remainingListeners = checkListeners();
3247 }
3248 if (remainingListeners) {
3249 switchToBackground();
3250 }
3251 }
3252
3253 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
3254 final boolean remainingListeners;
3255 synchronized (LISTENER_LOCK) {
3256 remainingListeners = checkListeners();
3257 if (!this.mOnShowErrorToasts.add(listener)) {
3258 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
3259 }
3260 }
3261 if (remainingListeners) {
3262 switchToForeground();
3263 }
3264 }
3265
3266 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
3267 final boolean remainingListeners;
3268 synchronized (LISTENER_LOCK) {
3269 this.mOnShowErrorToasts.remove(onShowErrorToast);
3270 remainingListeners = checkListeners();
3271 }
3272 if (remainingListeners) {
3273 switchToBackground();
3274 }
3275 }
3276
3277 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
3278 final boolean remainingListeners;
3279 synchronized (LISTENER_LOCK) {
3280 remainingListeners = checkListeners();
3281 if (!this.mOnAccountUpdates.add(listener)) {
3282 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
3283 }
3284 }
3285 if (remainingListeners) {
3286 switchToForeground();
3287 }
3288 }
3289
3290 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
3291 final boolean remainingListeners;
3292 synchronized (LISTENER_LOCK) {
3293 this.mOnAccountUpdates.remove(listener);
3294 remainingListeners = checkListeners();
3295 }
3296 if (remainingListeners) {
3297 switchToBackground();
3298 }
3299 }
3300
3301 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3302 final boolean remainingListeners;
3303 synchronized (LISTENER_LOCK) {
3304 remainingListeners = checkListeners();
3305 if (!this.mOnCaptchaRequested.add(listener)) {
3306 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
3307 }
3308 }
3309 if (remainingListeners) {
3310 switchToForeground();
3311 }
3312 }
3313
3314 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3315 final boolean remainingListeners;
3316 synchronized (LISTENER_LOCK) {
3317 this.mOnCaptchaRequested.remove(listener);
3318 remainingListeners = checkListeners();
3319 }
3320 if (remainingListeners) {
3321 switchToBackground();
3322 }
3323 }
3324
3325 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
3326 final boolean remainingListeners;
3327 synchronized (LISTENER_LOCK) {
3328 remainingListeners = checkListeners();
3329 if (!this.mOnRosterUpdates.add(listener)) {
3330 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
3331 }
3332 }
3333 if (remainingListeners) {
3334 switchToForeground();
3335 }
3336 }
3337
3338 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
3339 final boolean remainingListeners;
3340 synchronized (LISTENER_LOCK) {
3341 this.mOnRosterUpdates.remove(listener);
3342 remainingListeners = checkListeners();
3343 }
3344 if (remainingListeners) {
3345 switchToBackground();
3346 }
3347 }
3348
3349 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3350 final boolean remainingListeners;
3351 synchronized (LISTENER_LOCK) {
3352 remainingListeners = checkListeners();
3353 if (!this.mOnUpdateBlocklist.add(listener)) {
3354 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
3355 }
3356 }
3357 if (remainingListeners) {
3358 switchToForeground();
3359 }
3360 }
3361
3362 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3363 final boolean remainingListeners;
3364 synchronized (LISTENER_LOCK) {
3365 this.mOnUpdateBlocklist.remove(listener);
3366 remainingListeners = checkListeners();
3367 }
3368 if (remainingListeners) {
3369 switchToBackground();
3370 }
3371 }
3372
3373 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
3374 final boolean remainingListeners;
3375 synchronized (LISTENER_LOCK) {
3376 remainingListeners = checkListeners();
3377 if (!this.mOnKeyStatusUpdated.add(listener)) {
3378 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
3379 }
3380 }
3381 if (remainingListeners) {
3382 switchToForeground();
3383 }
3384 }
3385
3386 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
3387 final boolean remainingListeners;
3388 synchronized (LISTENER_LOCK) {
3389 this.mOnKeyStatusUpdated.remove(listener);
3390 remainingListeners = checkListeners();
3391 }
3392 if (remainingListeners) {
3393 switchToBackground();
3394 }
3395 }
3396
3397 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3398 final boolean remainingListeners;
3399 synchronized (LISTENER_LOCK) {
3400 remainingListeners = checkListeners();
3401 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
3402 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
3403 }
3404 }
3405 if (remainingListeners) {
3406 switchToForeground();
3407 }
3408 }
3409
3410 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3411 final boolean remainingListeners;
3412 synchronized (LISTENER_LOCK) {
3413 this.onJingleRtpConnectionUpdate.remove(listener);
3414 remainingListeners = checkListeners();
3415 }
3416 if (remainingListeners) {
3417 switchToBackground();
3418 }
3419 }
3420
3421 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
3422 final boolean remainingListeners;
3423 synchronized (LISTENER_LOCK) {
3424 remainingListeners = checkListeners();
3425 if (!this.mOnMucRosterUpdate.add(listener)) {
3426 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
3427 }
3428 }
3429 if (remainingListeners) {
3430 switchToForeground();
3431 }
3432 }
3433
3434 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
3435 final boolean remainingListeners;
3436 synchronized (LISTENER_LOCK) {
3437 this.mOnMucRosterUpdate.remove(listener);
3438 remainingListeners = checkListeners();
3439 }
3440 if (remainingListeners) {
3441 switchToBackground();
3442 }
3443 }
3444
3445 public boolean checkListeners() {
3446 return (this.mOnAccountUpdates.size() == 0
3447 && this.mOnConversationUpdates.size() == 0
3448 && this.mOnRosterUpdates.size() == 0
3449 && this.mOnCaptchaRequested.size() == 0
3450 && this.mOnMucRosterUpdate.size() == 0
3451 && this.mOnUpdateBlocklist.size() == 0
3452 && this.mOnShowErrorToasts.size() == 0
3453 && this.onJingleRtpConnectionUpdate.size() == 0
3454 && this.mOnKeyStatusUpdated.size() == 0);
3455 }
3456
3457 private void switchToForeground() {
3458 toggleSoftDisabled(false);
3459 final boolean broadcastLastActivity = broadcastLastActivity();
3460 for (Conversation conversation : getConversations()) {
3461 if (conversation.getMode() == Conversation.MODE_MULTI) {
3462 conversation.getMucOptions().resetChatState();
3463 } else {
3464 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
3465 }
3466 }
3467 for (Account account : getAccounts()) {
3468 if (account.getStatus() == Account.State.ONLINE) {
3469 account.deactivateGracePeriod();
3470 final XmppConnection connection = account.getXmppConnection();
3471 if (connection != null) {
3472 if (connection.getFeatures().csi()) {
3473 connection.sendActive();
3474 }
3475 if (broadcastLastActivity) {
3476 sendPresence(account, false); //send new presence but don't include idle because we are not
3477 }
3478 }
3479 }
3480 }
3481 Log.d(Config.LOGTAG, "app switched into foreground");
3482 }
3483
3484 private void switchToBackground() {
3485 final boolean broadcastLastActivity = broadcastLastActivity();
3486 if (broadcastLastActivity) {
3487 mLastActivity = System.currentTimeMillis();
3488 final SharedPreferences.Editor editor = getPreferences().edit();
3489 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3490 editor.apply();
3491 }
3492 for (Account account : getAccounts()) {
3493 if (account.getStatus() == Account.State.ONLINE) {
3494 XmppConnection connection = account.getXmppConnection();
3495 if (connection != null) {
3496 if (broadcastLastActivity) {
3497 sendPresence(account, true);
3498 }
3499 if (connection.getFeatures().csi()) {
3500 connection.sendInactive();
3501 }
3502 }
3503 }
3504 }
3505 this.mNotificationService.setIsInForeground(false);
3506 Log.d(Config.LOGTAG, "app switched into background");
3507 }
3508
3509 public void connectMultiModeConversations(Account account) {
3510 List<Conversation> conversations = getConversations();
3511 for (Conversation conversation : conversations) {
3512 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
3513 joinMuc(conversation);
3514 }
3515 }
3516 }
3517
3518 public void mucSelfPingAndRejoin(final Conversation conversation) {
3519 final Account account = conversation.getAccount();
3520 synchronized (account.inProgressConferenceJoins) {
3521 if (account.inProgressConferenceJoins.contains(conversation)) {
3522 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
3523 return;
3524 }
3525 }
3526 synchronized (account.inProgressConferencePings) {
3527 if (!account.inProgressConferencePings.add(conversation)) {
3528 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
3529 return;
3530 }
3531 }
3532 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3533 final Iq ping = new Iq(Iq.Type.GET);
3534 ping.setTo(self);
3535 ping.addChild("ping", Namespace.PING);
3536 sendIqPacket(conversation.getAccount(), ping, (response) -> {
3537 if (response.getType() == Iq.Type.ERROR) {
3538 final var error = response.getError();
3539 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
3540 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
3541 } else {
3542 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
3543 joinMuc(conversation);
3544 }
3545 } else if (response.getType() == Iq.Type.RESULT) {
3546 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping to " + self + " came back fine");
3547 }
3548 synchronized (account.inProgressConferencePings) {
3549 account.inProgressConferencePings.remove(conversation);
3550 }
3551 });
3552 }
3553 public void joinMuc(Conversation conversation) {
3554 joinMuc(conversation, null, false);
3555 }
3556
3557 public void joinMuc(Conversation conversation, boolean followedInvite) {
3558 joinMuc(conversation, null, followedInvite);
3559 }
3560
3561 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3562 joinMuc(conversation, onConferenceJoined, false);
3563 }
3564
3565 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
3566 final Account account = conversation.getAccount();
3567 synchronized (account.pendingConferenceJoins) {
3568 account.pendingConferenceJoins.remove(conversation);
3569 }
3570 synchronized (account.pendingConferenceLeaves) {
3571 account.pendingConferenceLeaves.remove(conversation);
3572 }
3573 if (account.getStatus() == Account.State.ONLINE) {
3574 synchronized (account.inProgressConferenceJoins) {
3575 account.inProgressConferenceJoins.add(conversation);
3576 }
3577 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3578 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3579 }
3580 conversation.resetMucOptions();
3581 if (onConferenceJoined != null) {
3582 conversation.getMucOptions().flagNoAutoPushConfiguration();
3583 }
3584 conversation.setHasMessagesLeftOnServer(false);
3585 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
3586
3587 private void join(Conversation conversation) {
3588 Account account = conversation.getAccount();
3589 final MucOptions mucOptions = conversation.getMucOptions();
3590
3591 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
3592 synchronized (account.inProgressConferenceJoins) {
3593 account.inProgressConferenceJoins.remove(conversation);
3594 }
3595 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3596 updateConversationUi();
3597 if (onConferenceJoined != null) {
3598 onConferenceJoined.onConferenceJoined(conversation);
3599 }
3600 return;
3601 }
3602
3603 final Jid joinJid = mucOptions.getSelf().getFullJid();
3604 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
3605 final var packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null, mucOptions.getSelf().getNick());
3606 packet.setTo(joinJid);
3607 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3608 if (conversation.getMucOptions().getPassword() != null) {
3609 x.addChild("password").setContent(mucOptions.getPassword());
3610 }
3611
3612 if (mucOptions.mamSupport()) {
3613 // Use MAM instead of the limited muc history to get history
3614 x.addChild("history").setAttribute("maxchars", "0");
3615 } else {
3616 // Fallback to muc history
3617 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
3618 }
3619 sendPresencePacket(account, packet);
3620 if (onConferenceJoined != null) {
3621 onConferenceJoined.onConferenceJoined(conversation);
3622 }
3623 if (!joinJid.equals(conversation.getJid())) {
3624 conversation.setContactJid(joinJid);
3625 databaseBackend.updateConversation(conversation);
3626 }
3627
3628 maybeRegisterWithMuc(conversation, null);
3629
3630 if (mucOptions.mamSupport()) {
3631 getMessageArchiveService().catchupMUC(conversation);
3632 }
3633 fetchConferenceMembers(conversation);
3634 if (mucOptions.isPrivateAndNonAnonymous()) {
3635 if (followedInvite) {
3636 final Bookmark bookmark = conversation.getBookmark();
3637 if (bookmark != null) {
3638 if (!bookmark.autojoin()) {
3639 bookmark.setAutojoin(true);
3640 createBookmark(account, bookmark);
3641 }
3642 } else {
3643 saveConversationAsBookmark(conversation, null);
3644 }
3645 }
3646 }
3647 synchronized (account.inProgressConferenceJoins) {
3648 account.inProgressConferenceJoins.remove(conversation);
3649 sendUnsentMessages(conversation);
3650 }
3651 }
3652
3653 @Override
3654 public void onConferenceConfigurationFetched(Conversation conversation) {
3655 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3656 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3657 return;
3658 }
3659 join(conversation);
3660 }
3661
3662 @Override
3663 public void onFetchFailed(final Conversation conversation, final String errorCondition) {
3664 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3665 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3666 return;
3667 }
3668 if ("remote-server-not-found".equals(errorCondition)) {
3669 synchronized (account.inProgressConferenceJoins) {
3670 account.inProgressConferenceJoins.remove(conversation);
3671 }
3672 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
3673 updateConversationUi();
3674 } else {
3675 join(conversation);
3676 fetchConferenceConfiguration(conversation);
3677 }
3678 }
3679 });
3680 updateConversationUi();
3681 } else {
3682 synchronized (account.pendingConferenceJoins) {
3683 account.pendingConferenceJoins.add(conversation);
3684 }
3685 conversation.resetMucOptions();
3686 conversation.setHasMessagesLeftOnServer(false);
3687 updateConversationUi();
3688 }
3689 }
3690
3691 private void fetchConferenceMembers(final Conversation conversation) {
3692 final Account account = conversation.getAccount();
3693 final AxolotlService axolotlService = account.getAxolotlService();
3694 final var affiliations = new ArrayList<String>();
3695 affiliations.add("outcast");
3696 if (conversation.getMucOptions().isPrivateAndNonAnonymous()) affiliations.addAll(List.of("member", "admin", "owner"));
3697 final Consumer<Iq> callback = new Consumer<Iq>() {
3698
3699 private int i = 0;
3700 private boolean success = true;
3701
3702 @Override
3703 public void accept(Iq response) {
3704 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3705 Element query = response.query("http://jabber.org/protocol/muc#admin");
3706 if (response.getType() == Iq.Type.RESULT && query != null) {
3707 for (Element child : query.getChildren()) {
3708 if ("item".equals(child.getName())) {
3709 MucOptions.User user = AbstractParser.parseItem(conversation, child);
3710 user.setOnline(false);
3711 if (!user.realJidMatchesAccount()) {
3712 boolean isNew = conversation.getMucOptions().updateUser(user);
3713 Contact contact = user.getContact();
3714 if (omemoEnabled
3715 && isNew
3716 && user.getRealJid() != null
3717 && (contact == null || !contact.mutualPresenceSubscription())
3718 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3719 axolotlService.fetchDeviceIds(user.getRealJid());
3720 }
3721 }
3722 }
3723 }
3724 } else {
3725 success = false;
3726 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations.get(i) + " in " + conversation.getJid().asBareJid());
3727 }
3728 ++i;
3729 if (i >= affiliations.size()) {
3730 List<Jid> members = conversation.getMucOptions().getMembers(true);
3731 if (success) {
3732 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3733 boolean changed = false;
3734 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3735 Jid jid = iterator.next();
3736 if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3737 iterator.remove();
3738 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3739 changed = true;
3740 }
3741 }
3742 if (changed) {
3743 conversation.setAcceptedCryptoTargets(cryptoTargets);
3744 updateConversation(conversation);
3745 }
3746 }
3747 getAvatarService().clear(conversation);
3748 updateMucRosterUi();
3749 updateConversationUi();
3750 }
3751 }
3752 };
3753 for (String affiliation : affiliations) {
3754 final var x = mIqGenerator.queryAffiliation(conversation, affiliation);
3755 sendIqPacket(account, x, callback);
3756 }
3757 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3758 }
3759
3760 public void providePasswordForMuc(final Conversation conversation, final String password) {
3761 if (conversation.getMode() == Conversation.MODE_MULTI) {
3762 conversation.getMucOptions().setPassword(password);
3763 if (conversation.getBookmark() != null) {
3764 final Bookmark bookmark = conversation.getBookmark();
3765 bookmark.setAutojoin(true);
3766 createBookmark(conversation.getAccount(), bookmark);
3767 }
3768 updateConversation(conversation);
3769 joinMuc(conversation);
3770 }
3771 }
3772
3773 public void deleteAvatar(final Account account) {
3774 final AtomicBoolean executed = new AtomicBoolean(false);
3775 final Runnable onDeleted =
3776 () -> {
3777 if (executed.compareAndSet(false, true)) {
3778 account.setAvatar(null);
3779 databaseBackend.updateAccount(account);
3780 getAvatarService().clear(account);
3781 updateAccountUi();
3782 }
3783 };
3784 deleteVcardAvatar(account, onDeleted);
3785 deletePepNode(account, Namespace.AVATAR_DATA);
3786 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3787 }
3788
3789 public void deletePepNode(final Account account, final String node) {
3790 deletePepNode(account, node, null);
3791 }
3792
3793 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3794 final Iq request = mIqGenerator.deleteNode(node);
3795 sendIqPacket(account, request, (packet) -> {
3796 if (packet.getType() == Iq.Type.RESULT) {
3797 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully deleted pep node "+node);
3798 if (runnable != null) {
3799 runnable.run();
3800 }
3801 } else {
3802 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": failed to delete "+ packet);
3803 }
3804 });
3805 }
3806
3807 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3808 final Iq retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3809 sendIqPacket(account, retrieveVcard, (response) -> {
3810 if (response.getType() != Iq.Type.RESULT) {
3811 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": no vCard set. nothing to do");
3812 return;
3813 }
3814 final Element vcard = response.findChild("vCard", "vcard-temp");
3815 if (vcard == null) {
3816 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": no vCard set. nothing to do");
3817 return;
3818 }
3819 Element photo = vcard.findChild("PHOTO");
3820 if (photo == null) {
3821 photo = vcard.addChild("PHOTO");
3822 }
3823 photo.clearChildren();
3824 final Iq publication = new Iq(Iq.Type.SET);
3825 publication.setTo(account.getJid().asBareJid());
3826 publication.addChild(vcard);
3827 sendIqPacket(account, publication, (publicationResponse) -> {
3828 if (publicationResponse.getType() == Iq.Type.RESULT) {
3829 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully deleted vcard avatar");
3830 runnable.run();
3831 } else {
3832 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3833 }
3834 });
3835 });
3836 }
3837
3838 private boolean hasEnabledAccounts() {
3839 if (this.accounts == null) {
3840 return false;
3841 }
3842 for (final Account account : this.accounts) {
3843 if (account.isConnectionEnabled()) {
3844 return true;
3845 }
3846 }
3847 return false;
3848 }
3849
3850
3851 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3852 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3853 }
3854
3855 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3856 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3857 }
3858
3859
3860 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3861 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3862 }
3863
3864 public void persistSelfNick(final MucOptions.User self) {
3865 final Conversation conversation = self.getConversation();
3866 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3867 Jid full = self.getFullJid();
3868 if (!full.equals(conversation.getJid())) {
3869 Log.d(Config.LOGTAG, "nick changed. updating");
3870 conversation.setContactJid(full);
3871 databaseBackend.updateConversation(conversation);
3872 }
3873
3874 final String nick = self.getNick();
3875 final Bookmark bookmark = conversation.getBookmark();
3876 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3877 if (bookmark != null && (tookProposedNickFromBookmark || Strings.isNullOrEmpty(bookmarkedNick)) && !nick.equals(bookmarkedNick)) {
3878 final Account account = conversation.getAccount();
3879 final String defaultNick = MucOptions.defaultNick(account);
3880 if (Strings.isNullOrEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3881 return;
3882 }
3883 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + nick + "' into bookmark for " + conversation.getJid().asBareJid());
3884 bookmark.setNick(nick);
3885 createBookmark(bookmark.getAccount(), bookmark);
3886 }
3887 }
3888
3889 public void presenceToMuc(final Conversation conversation) {
3890 final MucOptions options = conversation.getMucOptions();
3891 if (options.online()) {
3892 Account account = conversation.getAccount();
3893 final Jid joinJid = options.getSelf().getFullJid();
3894 final var packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), options.getSelf().getNick());
3895 packet.setTo(joinJid);
3896 sendPresencePacket(account, packet);
3897 }
3898 }
3899
3900 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3901 final MucOptions options = conversation.getMucOptions();
3902 final Jid joinJid = options.createJoinJid(nick);
3903 if (joinJid == null) {
3904 return false;
3905 }
3906 if (options.online()) {
3907 maybeRegisterWithMuc(conversation, nick);
3908
3909 Account account = conversation.getAccount();
3910 options.setOnRenameListener(new OnRenameListener() {
3911
3912 @Override
3913 public void onSuccess() {
3914 final var packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3915 packet.setTo(joinJid);
3916 sendPresencePacket(account, packet);
3917 callback.success(conversation);
3918 }
3919
3920 @Override
3921 public void onFailure() {
3922 callback.error(R.string.nick_in_use, conversation);
3923 }
3924 });
3925
3926 final var packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3927 packet.setTo(joinJid);
3928 sendPresencePacket(account, packet);
3929 } else {
3930 conversation.setContactJid(joinJid);
3931 databaseBackend.updateConversation(conversation);
3932 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3933 Bookmark bookmark = conversation.getBookmark();
3934 if (bookmark != null) {
3935 bookmark.setNick(nick);
3936 createBookmark(bookmark.getAccount(), bookmark);
3937 }
3938 joinMuc(conversation);
3939 }
3940 }
3941 return true;
3942 }
3943
3944 public void leaveMuc(Conversation conversation) {
3945 leaveMuc(conversation, false);
3946 }
3947
3948 private void leaveMuc(Conversation conversation, boolean now) {
3949 final Account account = conversation.getAccount();
3950 synchronized (account.pendingConferenceJoins) {
3951 account.pendingConferenceJoins.remove(conversation);
3952 }
3953 synchronized (account.pendingConferenceLeaves) {
3954 account.pendingConferenceLeaves.remove(conversation);
3955 }
3956 if (account.getStatus() == Account.State.ONLINE || now) {
3957 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3958 conversation.getMucOptions().setOffline();
3959 Bookmark bookmark = conversation.getBookmark();
3960 if (bookmark != null) {
3961 bookmark.setConversation(null);
3962 }
3963 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3964 } else {
3965 synchronized (account.pendingConferenceLeaves) {
3966 account.pendingConferenceLeaves.add(conversation);
3967 }
3968 }
3969 }
3970
3971 public String findConferenceServer(final Account account) {
3972 String server;
3973 if (account.getXmppConnection() != null) {
3974 server = account.getXmppConnection().getMucServer();
3975 if (server != null) {
3976 return server;
3977 }
3978 }
3979 for (Account other : getAccounts()) {
3980 if (other != account && other.getXmppConnection() != null) {
3981 server = other.getXmppConnection().getMucServer();
3982 if (server != null) {
3983 return server;
3984 }
3985 }
3986 }
3987 return null;
3988 }
3989
3990
3991 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3992 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3993 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3994 if (!TextUtils.isEmpty(name)) {
3995 configuration.putString("muc#roomconfig_roomname", name);
3996 }
3997 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3998 @Override
3999 public void onPushSucceeded() {
4000 saveConversationAsBookmark(conversation, name);
4001 callback.success(conversation);
4002 }
4003
4004 @Override
4005 public void onPushFailed() {
4006 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
4007 callback.error(R.string.unable_to_set_channel_configuration, conversation);
4008 } else {
4009 callback.error(R.string.joined_an_existing_channel, conversation);
4010 }
4011 }
4012 });
4013 });
4014 }
4015
4016 public boolean createAdhocConference(final Account account,
4017 final String name,
4018 final Iterable<Jid> jids,
4019 final UiCallback<Conversation> callback) {
4020 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
4021 if (account.getStatus() == Account.State.ONLINE) {
4022 try {
4023 String server = findConferenceServer(account);
4024 if (server == null) {
4025 if (callback != null) {
4026 callback.error(R.string.no_conference_server_found, null);
4027 }
4028 return false;
4029 }
4030 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
4031 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
4032 joinMuc(conversation, new OnConferenceJoined() {
4033 @Override
4034 public void onConferenceJoined(final Conversation conversation) {
4035 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
4036 if (!TextUtils.isEmpty(name)) {
4037 configuration.putString("muc#roomconfig_roomname", name);
4038 }
4039 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
4040 @Override
4041 public void onPushSucceeded() {
4042 for (Jid invite : jids) {
4043 invite(conversation, invite);
4044 }
4045 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
4046 if (resource == null || "".equals(resource)) continue;
4047 Jid other = account.getJid().withResource(resource);
4048 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
4049 directInvite(conversation, other);
4050 }
4051 saveConversationAsBookmark(conversation, name);
4052 if (callback != null) {
4053 callback.success(conversation);
4054 }
4055 }
4056
4057 @Override
4058 public void onPushFailed() {
4059 archiveConversation(conversation);
4060 if (callback != null) {
4061 callback.error(R.string.conference_creation_failed, conversation);
4062 }
4063 }
4064 });
4065 }
4066 });
4067 return true;
4068 } catch (IllegalArgumentException e) {
4069 if (callback != null) {
4070 callback.error(R.string.conference_creation_failed, null);
4071 }
4072 return false;
4073 }
4074 } else {
4075 if (callback != null) {
4076 callback.error(R.string.not_connected_try_again, null);
4077 }
4078 return false;
4079 }
4080 }
4081
4082 public void checkIfMuc(final Account account, final Jid jid, Consumer<Boolean> cb) {
4083 if (jid.isDomainJid()) {
4084 // Spec basically says MUC needs to have a node
4085 // And also specifies that MUC and MUC service should have the same identity...
4086 cb.accept(false);
4087 return;
4088 }
4089
4090 final var request = mIqGenerator.queryDiscoInfo(jid.asBareJid());
4091 sendIqPacket(account, request, (reply) -> {
4092 final var result = new ServiceDiscoveryResult(reply);
4093 cb.accept(
4094 result.getFeatures().contains("http://jabber.org/protocol/muc") &&
4095 result.hasIdentity("conference", null)
4096 );
4097 });
4098 }
4099
4100 public void fetchConferenceConfiguration(final Conversation conversation) {
4101 fetchConferenceConfiguration(conversation, null);
4102 }
4103
4104 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
4105 final Iq request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
4106 final var account = conversation.getAccount();
4107 sendIqPacket(account, request, response -> {
4108 if (response.getType() == Iq.Type.RESULT) {
4109 final MucOptions mucOptions = conversation.getMucOptions();
4110 final Bookmark bookmark = conversation.getBookmark();
4111 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
4112
4113 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(response))) {
4114 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
4115 updateConversation(conversation);
4116 }
4117
4118 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
4119 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
4120 createBookmark(account, bookmark);
4121 }
4122 }
4123
4124
4125 if (callback != null) {
4126 callback.onConferenceConfigurationFetched(conversation);
4127 }
4128
4129
4130 updateConversationUi();
4131 } else if (response.getType() == Iq.Type.TIMEOUT) {
4132 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
4133 } else {
4134 if (callback != null) {
4135 callback.onFetchFailed(conversation, response.getErrorCondition());
4136 }
4137 }
4138 });
4139 }
4140
4141 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
4142 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
4143 }
4144
4145 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
4146 Log.d(Config.LOGTAG, "pushing node configuration");
4147 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), responseToRequest -> {
4148 if (responseToRequest.getType() == Iq.Type.RESULT) {
4149 Element pubsub = responseToRequest.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
4150 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
4151 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
4152 if (x != null) {
4153 final Data data = Data.parse(x);
4154 data.submit(options);
4155 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), responseToPublish -> {
4156 if (responseToPublish.getType() == Iq.Type.RESULT && callback != null) {
4157 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
4158 callback.onPushSucceeded();
4159 } else if (responseToPublish.getType() == Iq.Type.ERROR && callback != null) {
4160 callback.onPushFailed();
4161 }
4162 });
4163 } else if (callback != null) {
4164 callback.onPushFailed();
4165 }
4166 } else if (responseToRequest.getType() == Iq.Type.ERROR && callback != null) {
4167 callback.onPushFailed();
4168 }
4169 });
4170 }
4171
4172 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
4173 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
4174 conversation.setAttribute("accept_non_anonymous", true);
4175 updateConversation(conversation);
4176 }
4177 if (options.containsKey("muc#roomconfig_moderatedroom")) {
4178 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
4179 options.putString("members_by_default", moderated ? "0" : "1");
4180 }
4181 if (options.containsKey("muc#roomconfig_allowpm")) {
4182 // ejabberd :-/
4183 final boolean allow = "anyone".equals(options.getString("muc#roomconfig_allowpm"));
4184 options.putString("allow_private_messages", allow ? "1" : "0");
4185 options.putString("allow_private_messages_from_visitors", allow ? "anyone" : "nobody");
4186 }
4187 final var account = conversation.getAccount();
4188 final Iq request = new Iq(Iq.Type.GET);
4189 request.setTo(conversation.getJid().asBareJid());
4190 request.query("http://jabber.org/protocol/muc#owner");
4191 sendIqPacket(account, request, response -> {
4192 if (response.getType() == Iq.Type.RESULT) {
4193 final Data data = Data.parse(response.query().findChild("x", Namespace.DATA));
4194 data.submit(options);
4195 final Iq set = new Iq(Iq.Type.SET);
4196 set.setTo(conversation.getJid().asBareJid());
4197 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
4198 sendIqPacket(account, set, packet -> {
4199 if (callback != null) {
4200 if (packet.getType() == Iq.Type.RESULT) {
4201 callback.onPushSucceeded();
4202 } else {
4203 Log.d(Config.LOGTAG,"failed: "+packet.toString());
4204 callback.onPushFailed();
4205 }
4206 }
4207 });
4208 } else {
4209 if (callback != null) {
4210 callback.onPushFailed();
4211 }
4212 }
4213 });
4214 }
4215
4216 public void pushSubjectToConference(final Conversation conference, final String subject) {
4217 final var packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4218 this.sendMessagePacket(conference.getAccount(), packet);
4219 }
4220
4221 public void requestVoice(final Account account, final Jid jid) {
4222 final var packet = this.getMessageGenerator().requestVoice(jid);
4223 this.sendMessagePacket(account, packet);
4224 }
4225
4226 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
4227 final Jid jid = user.asBareJid();
4228 final Iq request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4229 sendIqPacket(conference.getAccount(), request, (response) -> {
4230 if (response.getType() == Iq.Type.RESULT) {
4231 conference.getMucOptions().changeAffiliation(jid, affiliation);
4232 getAvatarService().clear(conference);
4233 if (callback != null) {
4234 callback.onAffiliationChangedSuccessful(jid);
4235 } else {
4236 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
4237 }
4238 } else if (callback != null) {
4239 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
4240 } else {
4241 Log.d(Config.LOGTAG, "unable to change affiliation");
4242 }
4243 });
4244 }
4245
4246 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
4247 final var account =conference.getAccount();
4248 final Iq request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4249 sendIqPacket(account, request, (packet) -> {
4250 if (packet.getType() != Iq.Type.RESULT) {
4251 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
4252 }
4253 });
4254 }
4255
4256 public void moderateMessage(final Account account, final Message m, final String reason) {
4257 final var request = this.mIqGenerator.moderateMessage(account, m, reason);
4258 sendIqPacket(account, request, (packet) -> {
4259 if (packet.getType() != Iq.Type.RESULT) {
4260 showErrorToastInUi(R.string.unable_to_moderate);
4261 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to moderate: " + packet);
4262 }
4263 });
4264 }
4265
4266 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4267 final Iq request = new Iq(Iq.Type.SET);
4268 request.setTo(conversation.getJid().asBareJid());
4269 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4270 sendIqPacket(conversation.getAccount(), request, response -> {
4271 if (response.getType() == Iq.Type.RESULT) {
4272 if (callback != null) {
4273 callback.onRoomDestroySucceeded();
4274 }
4275 } else if (response.getType() == Iq.Type.ERROR) {
4276 if (callback != null) {
4277 callback.onRoomDestroyFailed();
4278 }
4279 }
4280 });
4281 }
4282
4283 private void disconnect(final Account account, boolean force) {
4284 final XmppConnection connection = account.getXmppConnection();
4285 if (connection == null) {
4286 return;
4287 }
4288 if (!force) {
4289 final List<Conversation> conversations = getConversations();
4290 for (Conversation conversation : conversations) {
4291 if (conversation.getAccount() == account) {
4292 if (conversation.getMode() == Conversation.MODE_MULTI) {
4293 leaveMuc(conversation, true);
4294 }
4295 }
4296 }
4297 sendOfflinePresence(account);
4298 }
4299 connection.disconnect(force);
4300 }
4301
4302 @Override
4303 public IBinder onBind(Intent intent) {
4304 return mBinder;
4305 }
4306
4307 public void deleteMessage(Message message) {
4308 mScheduledMessages.remove(message.getUuid());
4309 databaseBackend.deleteMessage(message.getUuid());
4310 ((Conversation) message.getConversation()).remove(message);
4311 updateConversationUi();
4312 }
4313
4314 public void updateMessage(Message message) {
4315 updateMessage(message, true);
4316 }
4317
4318 public void updateMessage(Message message, boolean includeBody) {
4319 databaseBackend.updateMessage(message, includeBody);
4320 updateConversationUi();
4321 }
4322
4323 public void createMessageAsync(final Message message) {
4324 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4325 }
4326
4327 public void updateMessage(Message message, String uuid) {
4328 if (!databaseBackend.updateMessage(message, uuid)) {
4329 Log.e(Config.LOGTAG, "error updated message in DB after edit");
4330 }
4331 updateConversationUi();
4332 }
4333
4334 public void syncDirtyContacts(Account account) {
4335 for (Contact contact : account.getRoster().getContacts()) {
4336 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
4337 pushContactToServer(contact);
4338 }
4339 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
4340 deleteContactOnServer(contact);
4341 }
4342 }
4343 }
4344
4345 protected void unregisterPhoneAccounts(final Account account) {
4346 for (final Contact contact : account.getRoster().getContacts()) {
4347 if (!contact.showInRoster()) {
4348 contact.unregisterAsPhoneAccount(this);
4349 }
4350 }
4351 }
4352
4353 public void createContact(final Contact contact, final boolean autoGrant) {
4354 createContact(contact, autoGrant, null);
4355 }
4356
4357 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
4358 if (autoGrant) {
4359 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4360 contact.setOption(Contact.Options.ASKING);
4361 }
4362 pushContactToServer(contact, preAuth);
4363 }
4364
4365 public void pushContactToServer(final Contact contact) {
4366 pushContactToServer(contact, null);
4367 }
4368
4369 private void pushContactToServer(final Contact contact, final String preAuth) {
4370 contact.resetOption(Contact.Options.DIRTY_DELETE);
4371 contact.setOption(Contact.Options.DIRTY_PUSH);
4372 final Account account = contact.getAccount();
4373 if (account.getStatus() == Account.State.ONLINE) {
4374 final boolean ask = contact.getOption(Contact.Options.ASKING);
4375 final boolean sendUpdates = contact
4376 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
4377 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
4378 final Iq iq = new Iq(Iq.Type.SET);
4379 iq.query(Namespace.ROSTER).addChild(contact.asElement());
4380 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4381 if (sendUpdates) {
4382 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
4383 }
4384 if (ask) {
4385 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
4386 }
4387 } else {
4388 syncRoster(contact.getAccount());
4389 }
4390 }
4391
4392 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4393 new Thread(() -> {
4394 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4395 final int size = Config.AVATAR_SIZE;
4396 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4397 if (avatar != null) {
4398 if (!getFileBackend().save(avatar)) {
4399 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4400 return;
4401 }
4402 avatar.owner = conversation.getJid().asBareJid();
4403 publishMucAvatar(conversation, avatar, callback);
4404 } else {
4405 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4406 }
4407 }).start();
4408 }
4409
4410 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
4411 new Thread(() -> {
4412 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4413 final int size = Config.AVATAR_SIZE;
4414 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4415 if (avatar != null) {
4416 if (!getFileBackend().save(avatar)) {
4417 Log.d(Config.LOGTAG, "unable to save vcard");
4418 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4419 return;
4420 }
4421 publishAvatar(account, avatar, callback);
4422 } else {
4423 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4424 }
4425 }).start();
4426
4427 }
4428
4429 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4430 final var account = conversation.getAccount();
4431 final Iq retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4432 sendIqPacket(account, retrieve, (response) -> {
4433 boolean itemNotFound = response.getType() == Iq.Type.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
4434 if (response.getType() == Iq.Type.RESULT || itemNotFound) {
4435 Element vcard = response.findChild("vCard", "vcard-temp");
4436 if (vcard == null) {
4437 vcard = new Element("vCard", "vcard-temp");
4438 }
4439 Element photo = vcard.findChild("PHOTO");
4440 if (photo == null) {
4441 photo = vcard.addChild("PHOTO");
4442 }
4443 photo.clearChildren();
4444 photo.addChild("TYPE").setContent(avatar.type);
4445 photo.addChild("BINVAL").setContent(avatar.image);
4446 final Iq publication = new Iq(Iq.Type.SET);
4447 publication.setTo(conversation.getJid().asBareJid());
4448 publication.addChild(vcard);
4449 sendIqPacket(account, publication, (publicationResponse) -> {
4450 if (publicationResponse.getType() == Iq.Type.RESULT) {
4451 callback.onAvatarPublicationSucceeded();
4452 } else {
4453 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
4454 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4455 }
4456 });
4457 } else {
4458 Log.d(Config.LOGTAG, "failed to request vcard " + response);
4459 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
4460 }
4461 });
4462 }
4463
4464 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
4465 final Bundle options;
4466 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4467 options = PublishOptions.openAccess();
4468 } else {
4469 options = null;
4470 }
4471 publishAvatar(account, avatar, options, true, callback);
4472 }
4473
4474 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4475 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4476 final Iq packet = this.mIqGenerator.publishAvatar(avatar, options);
4477 this.sendIqPacket(account, packet, result -> {
4478 if (result.getType() == Iq.Type.RESULT) {
4479 publishAvatarMetadata(account, avatar, options, true, callback);
4480 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4481 pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
4482 @Override
4483 public void onPushSucceeded() {
4484 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
4485 publishAvatar(account, avatar, options, false, callback);
4486 }
4487
4488 @Override
4489 public void onPushFailed() {
4490 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
4491 publishAvatar(account, avatar, null, false, callback);
4492 }
4493 });
4494 } else {
4495 Element error = result.findChild("error");
4496 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
4497 if (callback != null) {
4498 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4499 }
4500 }
4501 });
4502 }
4503
4504 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4505 final Iq packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4506 sendIqPacket(account, packet, result -> {
4507 if (result.getType() == Iq.Type.RESULT) {
4508 if (account.setAvatar(avatar.getFilename())) {
4509 getAvatarService().clear(account);
4510 databaseBackend.updateAccount(account);
4511 notifyAccountAvatarHasChanged(account);
4512 }
4513 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
4514 if (callback != null) {
4515 callback.onAvatarPublicationSucceeded();
4516 }
4517 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4518 pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
4519 @Override
4520 public void onPushSucceeded() {
4521 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
4522 publishAvatarMetadata(account, avatar, options, false, callback);
4523 }
4524
4525 @Override
4526 public void onPushFailed() {
4527 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
4528 publishAvatarMetadata(account, avatar, null, false, callback);
4529 }
4530 });
4531 } else {
4532 if (callback != null) {
4533 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4534 }
4535 }
4536 });
4537 }
4538
4539 public void republishAvatarIfNeeded(Account account) {
4540 if (account.getAxolotlService().isPepBroken()) {
4541 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
4542 return;
4543 }
4544 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4545 this.sendIqPacket(account, packet, new Consumer<Iq>() {
4546
4547 private Avatar parseAvatar(Iq packet) {
4548 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4549 if (pubsub != null) {
4550 Element items = pubsub.findChild("items");
4551 if (items != null) {
4552 return Avatar.parseMetadata(items);
4553 }
4554 }
4555 return null;
4556 }
4557
4558 private boolean errorIsItemNotFound(Iq packet) {
4559 Element error = packet.findChild("error");
4560 return packet.getType() == Iq.Type.ERROR
4561 && error != null
4562 && error.hasChild("item-not-found");
4563 }
4564
4565 @Override
4566 public void accept(final Iq packet) {
4567 if (packet.getType() == Iq.Type.RESULT || errorIsItemNotFound(packet)) {
4568 Avatar serverAvatar = parseAvatar(packet);
4569 if (serverAvatar == null && account.getAvatar() != null) {
4570 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4571 if (avatar != null) {
4572 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
4573 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
4574 } else {
4575 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
4576 }
4577 }
4578 }
4579 }
4580 });
4581 }
4582
4583 public void cancelAvatarFetches(final Account account) {
4584 synchronized (mInProgressAvatarFetches) {
4585 for (final Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
4586 final String KEY = iterator.next();
4587 if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
4588 iterator.remove();
4589 }
4590 }
4591 }
4592 }
4593
4594 public void fetchAvatar(Account account, Avatar avatar) {
4595 fetchAvatar(account, avatar, null);
4596 }
4597
4598 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4599 if (databaseBackend.isBlockedMedia(avatar.cid())) {
4600 if (callback != null) callback.error(0, null);
4601 return;
4602 }
4603
4604 final String KEY = generateFetchKey(account, avatar);
4605 synchronized (this.mInProgressAvatarFetches) {
4606 if (mInProgressAvatarFetches.add(KEY)) {
4607 switch (avatar.origin) {
4608 case PEP:
4609 this.mInProgressAvatarFetches.add(KEY);
4610 fetchAvatarPep(account, avatar, callback);
4611 break;
4612 case VCARD:
4613 this.mInProgressAvatarFetches.add(KEY);
4614 fetchAvatarVcard(account, avatar, callback);
4615 break;
4616 }
4617 } else if (avatar.origin == Avatar.Origin.PEP) {
4618 mOmittedPepAvatarFetches.add(KEY);
4619 } else {
4620 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
4621 }
4622 }
4623 }
4624
4625 private void fetchAvatarPep(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4626 final Iq packet = this.mIqGenerator.retrievePepAvatar(avatar);
4627 sendIqPacket(account, packet, (result) -> {
4628 synchronized (mInProgressAvatarFetches) {
4629 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
4630 }
4631 final String ERROR = account.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
4632 if (result.getType() == Iq.Type.RESULT) {
4633 avatar.image = IqParser.avatarData(result);
4634 if (avatar.image != null) {
4635 if (getFileBackend().save(avatar)) {
4636 if (account.getJid().asBareJid().equals(avatar.owner)) {
4637 if (account.setAvatar(avatar.getFilename())) {
4638 databaseBackend.updateAccount(account);
4639 }
4640 getAvatarService().clear(account);
4641 updateConversationUi();
4642 updateAccountUi();
4643 } else {
4644 final Contact contact = account.getRoster().getContact(avatar.owner);
4645 contact.setAvatar(avatar);
4646 syncRoster(account);
4647 getAvatarService().clear(contact);
4648 updateConversationUi();
4649 updateRosterUi(UpdateRosterReason.AVATAR);
4650 }
4651 if (callback != null) {
4652 callback.success(avatar);
4653 }
4654 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
4655 return;
4656 }
4657 } else {
4658
4659 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4660 }
4661 } else {
4662 Element error = result.findChild("error");
4663 if (error == null) {
4664 Log.d(Config.LOGTAG, ERROR + "(server error)");
4665 } else {
4666 Log.d(Config.LOGTAG, ERROR + error.toString());
4667 }
4668 }
4669 if (callback != null) {
4670 callback.error(0, null);
4671 }
4672
4673 });
4674 }
4675
4676 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4677 final Iq packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4678 this.sendIqPacket(account, packet, response -> {
4679 final boolean previouslyOmittedPepFetch;
4680 synchronized (mInProgressAvatarFetches) {
4681 final String KEY = generateFetchKey(account, avatar);
4682 mInProgressAvatarFetches.remove(KEY);
4683 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4684 }
4685 if (response.getType() == Iq.Type.RESULT) {
4686 Element vCard = response.findChild("vCard", "vcard-temp");
4687 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4688 String image = photo != null ? photo.findChildContent("BINVAL") : null;
4689 if (image != null) {
4690 avatar.image = image;
4691 if (getFileBackend().save(avatar)) {
4692 Log.d(Config.LOGTAG, account.getJid().asBareJid()
4693 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4694 if (avatar.owner.isBareJid()) {
4695 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4696 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4697 account.setAvatar(avatar.getFilename());
4698 databaseBackend.updateAccount(account);
4699 getAvatarService().clear(account);
4700 updateAccountUi();
4701 } else {
4702 final Contact contact = account.getRoster().getContact(avatar.owner);
4703 contact.setAvatar(avatar, previouslyOmittedPepFetch);
4704 syncRoster(account);
4705 getAvatarService().clear(contact);
4706 updateRosterUi(UpdateRosterReason.AVATAR);
4707 }
4708 updateConversationUi();
4709 } else {
4710 Conversation conversation = find(account, avatar.owner.asBareJid());
4711 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4712 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4713 if (user != null) {
4714 if (user.setAvatar(avatar)) {
4715 getAvatarService().clear(user);
4716 updateConversationUi();
4717 updateMucRosterUi();
4718 }
4719 if (user.getRealJid() != null) {
4720 Contact contact = account.getRoster().getContact(user.getRealJid());
4721 contact.setAvatar(avatar);
4722 syncRoster(account);
4723 getAvatarService().clear(contact);
4724 updateRosterUi(UpdateRosterReason.AVATAR);
4725 }
4726 }
4727 }
4728 }
4729 }
4730 }
4731 }
4732 });
4733 }
4734
4735 public void checkForAvatar(final Account account, final UiCallback<Avatar> callback) {
4736 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4737 this.sendIqPacket(account, packet, response -> {
4738 if (response.getType() == Iq.Type.RESULT) {
4739 Element pubsub = response.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4740 if (pubsub != null) {
4741 Element items = pubsub.findChild("items");
4742 if (items != null) {
4743 Avatar avatar = Avatar.parseMetadata(items);
4744 if (avatar != null) {
4745 avatar.owner = account.getJid().asBareJid();
4746 if (fileBackend.isAvatarCached(avatar)) {
4747 if (account.setAvatar(avatar.getFilename())) {
4748 databaseBackend.updateAccount(account);
4749 }
4750 getAvatarService().clear(account);
4751 callback.success(avatar);
4752 } else {
4753 fetchAvatarPep(account, avatar, callback);
4754 }
4755 return;
4756 }
4757 }
4758 }
4759 }
4760 callback.error(0, null);
4761 });
4762 }
4763
4764 public void notifyAccountAvatarHasChanged(final Account account) {
4765 final XmppConnection connection = account.getXmppConnection();
4766 if (connection != null && connection.getFeatures().bookmarksConversion()) {
4767 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4768 for (Conversation conversation : conversations) {
4769 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4770 presenceToMuc(conversation);
4771 }
4772 }
4773 }
4774 }
4775
4776 public void fetchVcard4(Account account, final Contact contact, final Consumer<Element> callback) {
4777 final var packet = this.mIqGenerator.retrieveVcard4(contact.getJid());
4778 sendIqPacket(account, packet, (result) -> {
4779 if (result.getType() == Iq.Type.RESULT) {
4780 final Element item = IqParser.getItem(result);
4781 if (item != null) {
4782 final Element vcard4 = item.findChild("vcard", Namespace.VCARD4);
4783 if (vcard4 != null) {
4784 if (callback != null) {
4785 callback.accept(vcard4);
4786 }
4787 return;
4788 }
4789 }
4790 } else {
4791 Element error = result.findChild("error");
4792 if (error == null) {
4793 Log.d(Config.LOGTAG, "fetchVcard4 (server error)");
4794 } else {
4795 Log.d(Config.LOGTAG, "fetchVcard4 " + error.toString());
4796 }
4797 }
4798 if (callback != null) {
4799 callback.accept(null);
4800 }
4801
4802 });
4803 }
4804
4805 public void deleteContactOnServer(Contact contact) {
4806 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4807 contact.resetOption(Contact.Options.DIRTY_PUSH);
4808 contact.setOption(Contact.Options.DIRTY_DELETE);
4809 Account account = contact.getAccount();
4810 if (account.getStatus() == Account.State.ONLINE) {
4811 final Iq iq = new Iq(Iq.Type.SET);
4812 Element item = iq.query(Namespace.ROSTER).addChild("item");
4813 item.setAttribute("jid", contact.getJid());
4814 item.setAttribute("subscription", "remove");
4815 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4816 }
4817 }
4818
4819 public void updateConversation(final Conversation conversation) {
4820 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4821 }
4822
4823 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4824 synchronized (account) {
4825 final XmppConnection existingConnection = account.getXmppConnection();
4826 final XmppConnection connection;
4827 if (existingConnection != null) {
4828 connection = existingConnection;
4829 } else if (account.isConnectionEnabled()) {
4830 connection = createConnection(account);
4831 account.setXmppConnection(connection);
4832 } else {
4833 return;
4834 }
4835 final boolean hasInternet = hasInternetConnection();
4836 if (account.isConnectionEnabled() && hasInternet) {
4837 if (!force) {
4838 disconnect(account, false);
4839 }
4840 Thread thread = new Thread(connection);
4841 connection.setInteractive(interactive);
4842 connection.prepareNewConnection();
4843 connection.interrupt();
4844 thread.start();
4845 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4846 } else {
4847 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4848 account.getRoster().clearPresences();
4849 connection.resetEverything();
4850 final AxolotlService axolotlService = account.getAxolotlService();
4851 if (axolotlService != null) {
4852 axolotlService.resetBrokenness();
4853 }
4854 if (!hasInternet) {
4855 account.setStatus(Account.State.NO_INTERNET);
4856 }
4857 }
4858 }
4859 }
4860
4861 public void reconnectAccountInBackground(final Account account) {
4862 new Thread(() -> reconnectAccount(account, false, true)).start();
4863 }
4864
4865 public void invite(final Conversation conversation, final Jid contact) {
4866 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4867 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4868 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4869 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4870 }
4871 final var packet = mMessageGenerator.invite(conversation, contact);
4872 sendMessagePacket(conversation.getAccount(), packet);
4873 }
4874
4875 public void directInvite(Conversation conversation, Jid jid) {
4876 final var packet = mMessageGenerator.directInvite(conversation, jid);
4877 sendMessagePacket(conversation.getAccount(), packet);
4878 }
4879
4880 public void resetSendingToWaiting(Account account) {
4881 for (Conversation conversation : getConversations()) {
4882 if (conversation.getAccount() == account) {
4883 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4884 }
4885 }
4886 }
4887
4888 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4889 return markMessage(account, recipient, uuid, status, null);
4890 }
4891
4892 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4893 if (uuid == null) {
4894 return null;
4895 }
4896 for (Conversation conversation : getConversations()) {
4897 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4898 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4899 if (message != null) {
4900 markMessage(message, status, errorMessage);
4901 }
4902 return message;
4903 }
4904 }
4905 return null;
4906 }
4907
4908 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4909 return markMessage(conversation, uuid, status, serverMessageId, null, null, null, null, null);
4910 }
4911
4912 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) {
4913 if (uuid == null) {
4914 return false;
4915 } else {
4916 final Message message = conversation.findSentMessageWithUuid(uuid);
4917 if (message != null) {
4918 if (message.getServerMsgId() == null) {
4919 message.setServerMsgId(serverMessageId);
4920 }
4921 if (message.getEncryption() == Message.ENCRYPTION_NONE && (body != null || html != null || subject != null || thread != null || attachments != null)) {
4922 message.setBody(body.content);
4923 if (body.count > 1) {
4924 message.setBodyLanguage(body.language);
4925 }
4926 message.setHtml(html);
4927 message.setSubject(subject);
4928 message.setThread(thread);
4929 if (attachments != null && attachments.isEmpty()) {
4930 message.setRelativeFilePath(null);
4931 message.resetFileParams();
4932 }
4933 markMessage(message, status, null, true);
4934 } else {
4935 markMessage(message, status);
4936 }
4937 return true;
4938 } else {
4939 return false;
4940 }
4941 }
4942 }
4943
4944 public void markMessage(Message message, int status) {
4945 markMessage(message, status, null);
4946 }
4947
4948
4949 public void markMessage(final Message message, final int status, final String errorMessage) {
4950 markMessage(message, status, errorMessage, false);
4951 }
4952
4953 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4954 final int oldStatus = message.getStatus();
4955 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4956 return;
4957 }
4958 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4959 return;
4960 }
4961 message.setErrorMessage(errorMessage);
4962 message.setStatus(status);
4963 databaseBackend.updateMessage(message, includeBody);
4964 updateConversationUi();
4965 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4966 mNotificationService.pushFailedDelivery(message);
4967 }
4968 }
4969
4970 public SharedPreferences getPreferences() {
4971 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4972 }
4973
4974 public long getAutomaticMessageDeletionDate() {
4975 final long timeout = getLongPreference(AppSettings.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4976 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4977 }
4978
4979 public long getLongPreference(String name, @IntegerRes int res) {
4980 long defaultValue = getResources().getInteger(res);
4981 try {
4982 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4983 } catch (NumberFormatException e) {
4984 return defaultValue;
4985 }
4986 }
4987
4988 public boolean getBooleanPreference(String name, @BoolRes int res) {
4989 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4990 }
4991
4992 public String getStringPreference(String name, @BoolRes int res) {
4993 return getPreferences().getString(name, getResources().getString(res));
4994 }
4995
4996 public boolean confirmMessages() {
4997 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4998 }
4999
5000 public boolean allowMessageCorrection() {
5001 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
5002 }
5003
5004 public boolean sendChatStates() {
5005 return getBooleanPreference("chat_states", R.bool.chat_states);
5006 }
5007
5008 public boolean useTorToConnect() {
5009 return getBooleanPreference("use_tor", R.bool.use_tor);
5010 }
5011
5012 public boolean showExtendedConnectionOptions() {
5013 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
5014 }
5015
5016 public boolean broadcastLastActivity() {
5017 return getBooleanPreference(AppSettings.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
5018 }
5019
5020 public int unreadCount() {
5021 int count = 0;
5022 for (Conversation conversation : getConversations()) {
5023 count += conversation.unreadCount(this);
5024 }
5025 return count;
5026 }
5027
5028
5029 private <T> List<T> threadSafeList(Set<T> set) {
5030 synchronized (LISTENER_LOCK) {
5031 return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
5032 }
5033 }
5034
5035 public void showErrorToastInUi(int resId) {
5036 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
5037 listener.onShowErrorToast(resId);
5038 }
5039 }
5040
5041 public void updateConversationUi() {
5042 updateConversationUi(false);
5043 }
5044
5045 public void updateConversationUi(boolean newCaps) {
5046 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
5047 listener.onConversationUpdate(newCaps);
5048 }
5049 }
5050
5051 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
5052 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
5053 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
5054 }
5055 }
5056
5057 public void notifyJingleRtpConnectionUpdate(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices) {
5058 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
5059 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
5060 }
5061 }
5062
5063 public void updateAccountUi() {
5064 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
5065 listener.onAccountUpdate();
5066 }
5067 }
5068
5069 public void updateRosterUi(final UpdateRosterReason reason) {
5070 if (reason == UpdateRosterReason.PRESENCE) throw new IllegalArgumentException("PRESENCE must also come with a contact");
5071 updateRosterUi(reason, null);
5072 }
5073
5074 public void updateRosterUi(final UpdateRosterReason reason, final Contact contact) {
5075 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
5076 listener.onRosterUpdate(reason, contact);
5077 }
5078 }
5079
5080 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
5081 if (mOnCaptchaRequested.size() > 0) {
5082 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
5083 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
5084 (int) (captcha.getHeight() * metrics.scaledDensity), false);
5085 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
5086 listener.onCaptchaRequested(account, id, data, scaled);
5087 }
5088 return true;
5089 }
5090 return false;
5091 }
5092
5093 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
5094 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
5095 listener.OnUpdateBlocklist(status);
5096 }
5097 }
5098
5099 public void updateMucRosterUi() {
5100 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
5101 listener.onMucRosterUpdate();
5102 }
5103 }
5104
5105 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
5106 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
5107 listener.onKeyStatusUpdated(report);
5108 }
5109 }
5110
5111 public Account findAccountByJid(final Jid jid) {
5112 for (final Account account : this.accounts) {
5113 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
5114 return account;
5115 }
5116 }
5117 return null;
5118 }
5119
5120 public Account findAccountByUuid(final String uuid) {
5121 for (Account account : this.accounts) {
5122 if (account.getUuid().equals(uuid)) {
5123 return account;
5124 }
5125 }
5126 return null;
5127 }
5128
5129 public Conversation findConversationByUuid(String uuid) {
5130 for (Conversation conversation : getConversations()) {
5131 if (conversation.getUuid().equals(uuid)) {
5132 return conversation;
5133 }
5134 }
5135 return null;
5136 }
5137
5138 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
5139 List<Conversation> findings = new ArrayList<>();
5140 for (Conversation c : getConversations()) {
5141 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid().asBareJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
5142 findings.add(c);
5143 }
5144 }
5145 return findings.size() == 1 ? findings.get(0) : null;
5146 }
5147
5148 public boolean markRead(final Conversation conversation, boolean dismiss) {
5149 return markRead(conversation, null, dismiss).size() > 0;
5150 }
5151
5152 public void markRead(final Conversation conversation) {
5153 markRead(conversation, null, true);
5154 }
5155
5156 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
5157 if (dismiss) {
5158 mNotificationService.clear(conversation);
5159 }
5160 final List<Message> readMessages = conversation.markRead(upToUuid);
5161 if (readMessages.size() > 0) {
5162 Runnable runnable = () -> {
5163 for (Message message : readMessages) {
5164 databaseBackend.updateMessage(message, false);
5165 }
5166 };
5167 mDatabaseWriterExecutor.execute(runnable);
5168 updateConversationUi();
5169 updateUnreadCountBadge();
5170 return readMessages;
5171 } else {
5172 return readMessages;
5173 }
5174 }
5175
5176 public synchronized void updateUnreadCountBadge() {
5177 int count = unreadCount();
5178 if (unreadCount != count) {
5179 Log.d(Config.LOGTAG, "update unread count to " + count);
5180 if (count > 0) {
5181 ShortcutBadger.applyCount(getApplicationContext(), count);
5182 } else {
5183 ShortcutBadger.removeCount(getApplicationContext());
5184 }
5185 unreadCount = count;
5186 }
5187 }
5188
5189 public void sendReadMarker(final Conversation conversation, final String upToUuid) {
5190 final boolean isPrivateAndNonAnonymousMuc =
5191 conversation.getMode() == Conversation.MODE_MULTI
5192 && conversation.isPrivateAndNonAnonymous();
5193 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
5194 if (readMessages.isEmpty()) {
5195 return;
5196 }
5197 final var account = conversation.getAccount();
5198 final var connection = account.getXmppConnection();
5199 updateConversationUi();
5200 final var last =
5201 Iterables.getLast(
5202 Collections2.filter(
5203 readMessages,
5204 m ->
5205 !m.isPrivateMessage()
5206 && m.getStatus() == Message.STATUS_RECEIVED),
5207 null);
5208 if (last == null) {
5209 return;
5210 }
5211
5212 final boolean sendDisplayedMarker =
5213 confirmMessages()
5214 && (last.trusted() || isPrivateAndNonAnonymousMuc)
5215 && last.getRemoteMsgId() != null
5216 && (last.markable || isPrivateAndNonAnonymousMuc);
5217 final boolean serverAssist =
5218 connection != null && connection.getFeatures().mdsServerAssist();
5219
5220 final String stanzaId = last.getServerMsgId();
5221
5222 if (sendDisplayedMarker && serverAssist) {
5223 final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5224 final var packet = mMessageGenerator.confirm(last);
5225 packet.addChild(mdsDisplayed);
5226 if (!last.isPrivateMessage()) {
5227 packet.setTo(packet.getTo().asBareJid());
5228 }
5229 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": server assisted "+packet);
5230 this.sendMessagePacket(account, packet);
5231 } else {
5232 publishMds(last);
5233 // read markers will be sent after MDS to flush the CSI stanza queue
5234 if (sendDisplayedMarker) {
5235 Log.d(
5236 Config.LOGTAG,
5237 conversation.getAccount().getJid().asBareJid()
5238 + ": sending displayed marker to "
5239 + last.getCounterpart().toString());
5240 final var packet = mMessageGenerator.confirm(last);
5241 this.sendMessagePacket(account, packet);
5242 }
5243 }
5244 }
5245
5246 private void publishMds(@Nullable final Message message) {
5247 final String stanzaId = message == null ? null : message.getServerMsgId();
5248 if (Strings.isNullOrEmpty(stanzaId)) {
5249 return;
5250 }
5251 final Conversation conversation;
5252 final var conversational = message.getConversation();
5253 if (conversational instanceof Conversation c) {
5254 conversation = c;
5255 } else {
5256 return;
5257 }
5258 final var account = conversation.getAccount();
5259 final var connection = account.getXmppConnection();
5260 if (connection == null || !connection.getFeatures().mds()) {
5261 return;
5262 }
5263 final Jid itemId;
5264 if (message.isPrivateMessage()) {
5265 itemId = message.getCounterpart();
5266 } else {
5267 itemId = conversation.getJid().asBareJid();
5268 }
5269 Log.d(Config.LOGTAG,"publishing mds for "+itemId+"/"+stanzaId);
5270 publishMds(account, itemId, stanzaId, conversation);
5271 }
5272
5273 private void publishMds(
5274 final Account account, final Jid itemId, final String stanzaId, final Conversation conversation) {
5275 final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5276 pushNodeAndEnforcePublishOptions(
5277 account,
5278 Namespace.MDS_DISPLAYED,
5279 item,
5280 itemId.toEscapedString(),
5281 PublishOptions.persistentWhitelistAccessMaxItems());
5282 }
5283
5284 public boolean sendReactions(final Message message, final Collection<String> reactions) {
5285 if (message.getConversation() instanceof Conversation conversation) {
5286 final String reactToId;
5287 final Collection<Reaction> combinedReactions;
5288 final var newReactions = new HashSet<>(reactions);
5289 newReactions.removeAll(message.getAggregatedReactions().ourReactions);
5290 if (conversation.getMode() == Conversational.MODE_MULTI) {
5291 final var self = conversation.getMucOptions().getSelf();
5292 final String occupantId = self.getOccupantId();
5293 reactToId = message.getServerMsgId();
5294 combinedReactions =
5295 Reaction.withMine(
5296 message.getReactions(),
5297 reactions,
5298 false,
5299 self.getFullJid(),
5300 conversation.getAccount().getJid(),
5301 occupantId,
5302 null);
5303 } else {
5304 if (message.isCarbon() || message.getStatus() == Message.STATUS_RECEIVED) {
5305 reactToId = message.getRemoteMsgId();
5306 } else {
5307 reactToId = message.getUuid();
5308 }
5309 combinedReactions =
5310 Reaction.withFrom(
5311 message.getReactions(),
5312 reactions,
5313 false,
5314 conversation.getAccount().getJid(),
5315 null);
5316 }
5317 if (Strings.isNullOrEmpty(reactToId)) {
5318 return false;
5319 }
5320 final var packet =
5321 mMessageGenerator.reaction(conversation, message, reactToId, reactions);
5322
5323 final var quote = QuoteHelper.quote(MessageUtils.prepareQuote(message)) + "\n";
5324 final var body = quote + String.join(" ", newReactions);
5325 if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && newReactions.size() > 0) {
5326 FILE_ATTACHMENT_EXECUTOR.execute(() -> {
5327 XmppAxolotlMessage axolotlMessage = conversation.getAccount().getAxolotlService().encrypt(body, conversation);
5328 packet.setAxolotlMessage(axolotlMessage.toElement());
5329 packet.addChild("encryption", "urn:xmpp:eme:0")
5330 .setAttribute("name", "OMEMO")
5331 .setAttribute("namespace", AxolotlService.PEP_PREFIX);
5332 sendMessagePacket(conversation.getAccount(), packet);
5333 message.setReactions(combinedReactions);
5334 updateMessage(message, false);
5335 });
5336 } else if (conversation.getNextEncryption() == Message.ENCRYPTION_NONE || newReactions.size() < 1) {
5337 if (newReactions.size() > 0) {
5338 packet.setBody(body);
5339
5340 packet.addChild("reply", "urn:xmpp:reply:0")
5341 .setAttribute("to", message.getCounterpart())
5342 .setAttribute("id", reactToId);
5343 final var replyFallback = packet.addChild("fallback", "urn:xmpp:fallback:0").setAttribute("for", "urn:xmpp:reply:0");
5344 replyFallback.addChild("body", "urn:xmpp:fallback:0")
5345 .setAttribute("start", "0")
5346 .setAttribute("end", "" + quote.codePointCount(0, quote.length()));
5347
5348 final var fallback = packet.addChild("fallback", "urn:xmpp:fallback:0").setAttribute("for", "urn:xmpp:reactions:0");
5349 fallback.addChild("body", "urn:xmpp:fallback:0");
5350 }
5351
5352 sendMessagePacket(conversation.getAccount(), packet);
5353 message.setReactions(combinedReactions);
5354 updateMessage(message, false);
5355 }
5356
5357 return true;
5358 } else {
5359 return false;
5360 }
5361 }
5362
5363 public MemorizingTrustManager getMemorizingTrustManager() {
5364 return this.mMemorizingTrustManager;
5365 }
5366
5367 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
5368 this.mMemorizingTrustManager = trustManager;
5369 }
5370
5371 public void updateMemorizingTrustManager() {
5372 final MemorizingTrustManager trustManager;
5373 if (appSettings.isTrustSystemCAStore()) {
5374 trustManager = new MemorizingTrustManager(getApplicationContext());
5375 } else {
5376 trustManager = new MemorizingTrustManager(getApplicationContext(), null);
5377 }
5378 setMemorizingTrustManager(trustManager);
5379 }
5380
5381 public LruCache<String, Drawable> getDrawableCache() {
5382 return this.mDrawableCache;
5383 }
5384
5385 public Collection<String> getKnownHosts() {
5386 final Set<String> hosts = new HashSet<>();
5387 for (final Account account : getAccounts()) {
5388 hosts.add(account.getServer());
5389 for (final Contact contact : account.getRoster().getContacts()) {
5390 if (contact.showInRoster()) {
5391 final String server = contact.getServer();
5392 if (server != null) {
5393 hosts.add(server);
5394 }
5395 }
5396 }
5397 }
5398 if (Config.QUICKSY_DOMAIN != null) {
5399 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
5400 }
5401 if (Config.MAGIC_CREATE_DOMAIN != null) {
5402 hosts.add(Config.MAGIC_CREATE_DOMAIN);
5403 }
5404 hosts.add("chat.above.im");
5405 return hosts;
5406 }
5407
5408 public Collection<String> getKnownConferenceHosts() {
5409 final Set<String> mucServers = new HashSet<>();
5410 for (final Account account : accounts) {
5411 if (account.getXmppConnection() != null) {
5412 mucServers.addAll(account.getXmppConnection().getMucServers());
5413 for (final Bookmark bookmark : account.getBookmarks()) {
5414 final Jid jid = bookmark.getJid();
5415 final String s = jid == null ? null : jid.getDomain().toEscapedString();
5416 if (s != null) {
5417 mucServers.add(s);
5418 }
5419 }
5420 }
5421 }
5422 return mucServers;
5423 }
5424
5425 public void sendMessagePacket(final Account account, final im.conversations.android.xmpp.model.stanza.Message packet) {
5426 final XmppConnection connection = account.getXmppConnection();
5427 if (connection != null) {
5428 connection.sendMessagePacket(packet);
5429 }
5430 }
5431
5432 public void sendPresencePacket(final Account account, final im.conversations.android.xmpp.model.stanza.Presence packet) {
5433 final XmppConnection connection = account.getXmppConnection();
5434 if (connection != null) {
5435 connection.sendPresencePacket(packet);
5436 }
5437 }
5438
5439 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5440 final XmppConnection connection = account.getXmppConnection();
5441 if (connection == null) {
5442 return;
5443 }
5444 connection.sendCreateAccountWithCaptchaPacket(id, data);
5445 }
5446
5447 public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback) {
5448 sendIqPacket(account, packet, callback, null);
5449 }
5450
5451 public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback, Long timeout) {
5452 final XmppConnection connection = account.getXmppConnection();
5453 if (connection != null) {
5454 connection.sendIqPacket(packet, callback, timeout);
5455 } else if (callback != null) {
5456 callback.accept(Iq.TIMEOUT);
5457 }
5458 }
5459
5460 public void sendPresence(final Account account) {
5461 sendPresence(account, checkListeners() && broadcastLastActivity());
5462 }
5463
5464 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
5465 final Presence.Status status;
5466 if (manuallyChangePresence()) {
5467 status = account.getPresenceStatus();
5468 } else {
5469 status = getTargetPresence();
5470 }
5471 final var packet = mPresenceGenerator.selfPresence(account, status);
5472 if (mLastActivity > 0 && includeIdleTimestamp) {
5473 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
5474 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
5475 }
5476 sendPresencePacket(account, packet);
5477 }
5478
5479 private void deactivateGracePeriod() {
5480 for (Account account : getAccounts()) {
5481 account.deactivateGracePeriod();
5482 }
5483 }
5484
5485 public void refreshAllPresences() {
5486 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
5487 for (Account account : getAccounts()) {
5488 if (account.isConnectionEnabled()) {
5489 sendPresence(account, includeIdleTimestamp);
5490 }
5491 }
5492 }
5493
5494 private void refreshAllFcmTokens() {
5495 for (Account account : getAccounts()) {
5496 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
5497 mPushManagementService.registerPushTokenOnServer(account);
5498 }
5499 }
5500 }
5501
5502
5503
5504 private void sendOfflinePresence(final Account account) {
5505 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
5506 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
5507 }
5508
5509 public MessageGenerator getMessageGenerator() {
5510 return this.mMessageGenerator;
5511 }
5512
5513 public PresenceGenerator getPresenceGenerator() {
5514 return this.mPresenceGenerator;
5515 }
5516
5517 public IqGenerator getIqGenerator() {
5518 return this.mIqGenerator;
5519 }
5520
5521 public JingleConnectionManager getJingleConnectionManager() {
5522 return this.mJingleConnectionManager;
5523 }
5524
5525 private boolean hasJingleRtpConnection(final Account account) {
5526 return this.mJingleConnectionManager.hasJingleRtpConnection(account);
5527 }
5528
5529 public MessageArchiveService getMessageArchiveService() {
5530 return this.mMessageArchiveService;
5531 }
5532
5533 public QuickConversationsService getQuickConversationsService() {
5534 return this.mQuickConversationsService;
5535 }
5536
5537 public List<Contact> findContacts(Jid jid, String accountJid) {
5538 ArrayList<Contact> contacts = new ArrayList<>();
5539 for (Account account : getAccounts()) {
5540 if ((account.isEnabled() || accountJid != null)
5541 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
5542 Contact contact = account.getRoster().getContactFromContactList(jid);
5543 if (contact != null) {
5544 contacts.add(contact);
5545 }
5546 }
5547 }
5548 return contacts;
5549 }
5550
5551 public Conversation findFirstMuc(Jid jid) {
5552 return findFirstMuc(jid, null);
5553 }
5554
5555 public Conversation findFirstMuc(Jid jid, String accountJid) {
5556 for (Conversation conversation : getConversations()) {
5557 if ((conversation.getAccount().isEnabled() || accountJid != null)
5558 && (accountJid == null || accountJid.equals(conversation.getAccount().getJid().asBareJid().toString()))
5559 && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
5560 return conversation;
5561 }
5562 }
5563 return null;
5564 }
5565
5566 public NotificationService getNotificationService() {
5567 return this.mNotificationService;
5568 }
5569
5570 public HttpConnectionManager getHttpConnectionManager() {
5571 return this.mHttpConnectionManager;
5572 }
5573
5574 public void resendFailedMessages(final Message message) {
5575 final Collection<Message> messages = new ArrayList<>();
5576 Message current = message;
5577 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
5578 messages.add(current);
5579 if (current.mergeable(current.next())) {
5580 current = current.next();
5581 } else {
5582 break;
5583 }
5584 }
5585 for (final Message msg : messages) {
5586 msg.setTime(System.currentTimeMillis());
5587 markMessage(msg, Message.STATUS_WAITING);
5588 this.resendMessage(msg, false);
5589 }
5590 if (message.getConversation() instanceof Conversation) {
5591 ((Conversation) message.getConversation()).sort();
5592 }
5593 updateConversationUi();
5594 }
5595
5596 public void clearConversationHistory(final Conversation conversation) {
5597 final long clearDate;
5598 final String reference;
5599 if (conversation.countMessages() > 0) {
5600 Message latestMessage = conversation.getLatestMessage();
5601 clearDate = latestMessage.getTimeSent() + 1000;
5602 reference = latestMessage.getServerMsgId();
5603 } else {
5604 clearDate = System.currentTimeMillis();
5605 reference = null;
5606 }
5607 conversation.clearMessages();
5608 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
5609 conversation.setLastClearHistory(clearDate, reference);
5610 Runnable runnable = () -> {
5611 databaseBackend.deleteMessagesInConversation(conversation);
5612 databaseBackend.updateConversation(conversation);
5613 };
5614 mDatabaseWriterExecutor.execute(runnable);
5615 }
5616
5617 public boolean sendBlockRequest(final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
5618 if (blockable != null && blockable.getBlockedJid() != null) {
5619 final var account = blockable.getAccount();
5620 final Jid jid = blockable.getBlockedJid();
5621 this.sendIqPacket(account, getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId), (response) -> {
5622 if (response.getType() == Iq.Type.RESULT) {
5623 account.getBlocklist().add(jid);
5624 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
5625 }
5626 });
5627 if (blockable.getBlockedJid().isFullJid()) {
5628 return false;
5629 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
5630 updateConversationUi();
5631 return true;
5632 } else {
5633 return false;
5634 }
5635 } else {
5636 return false;
5637 }
5638 }
5639
5640 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
5641 boolean removed = false;
5642 synchronized (this.conversations) {
5643 boolean domainJid = blockedJid.getLocal() == null;
5644 for (Conversation conversation : this.conversations) {
5645 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
5646 || blockedJid.equals(conversation.getJid().asBareJid());
5647 if (conversation.getAccount() == account
5648 && conversation.getMode() == Conversation.MODE_SINGLE
5649 && jidMatches) {
5650 this.conversations.remove(conversation);
5651 markRead(conversation);
5652 conversation.setStatus(Conversation.STATUS_ARCHIVED);
5653 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
5654 updateConversation(conversation);
5655 removed = true;
5656 }
5657 }
5658 }
5659 return removed;
5660 }
5661
5662 public void sendUnblockRequest(final Blockable blockable) {
5663 if (blockable != null && blockable.getJid() != null) {
5664 final var account = blockable.getAccount();
5665 final Jid jid = blockable.getBlockedJid();
5666 this.sendIqPacket(account, getIqGenerator().generateSetUnblockRequest(jid), response -> {
5667 if (response.getType() == Iq.Type.RESULT) {
5668 account.getBlocklist().remove(jid);
5669 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
5670 }
5671 });
5672 }
5673 }
5674
5675 public void publishDisplayName(final Account account) {
5676 String displayName = account.getDisplayName();
5677 final Iq request;
5678 if (TextUtils.isEmpty(displayName)) {
5679 request = mIqGenerator.deleteNode(Namespace.NICK);
5680 } else {
5681 request = mIqGenerator.publishNick(displayName);
5682 }
5683 mAvatarService.clear(account);
5684 sendIqPacket(account, request, (packet) -> {
5685 if (packet.getType() == Iq.Type.ERROR) {
5686 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to modify nick name " + packet);
5687 }
5688 });
5689 }
5690
5691 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
5692 ServiceDiscoveryResult result = discoCache.get(key);
5693 if (result != null) {
5694 return result;
5695 } else {
5696 if (key.first == null || key.second == null) return null;
5697 result = databaseBackend.findDiscoveryResult(key.first, key.second);
5698 if (result != null) {
5699 discoCache.put(key, result);
5700 }
5701 return result;
5702 }
5703 }
5704
5705 public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
5706 final var request = new Iq(input == null ? Iq.Type.GET : Iq.Type.SET);
5707 request.setTo(jid);
5708 Element query = request.query("jabber:iq:gateway");
5709 if (input != null) {
5710 Element prompt = query.addChild("prompt");
5711 prompt.setContent(input);
5712 }
5713 sendIqPacket(account, request, packet -> {
5714 if (packet.getType() == Iq.Type.RESULT) {
5715 callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
5716 } else {
5717 Element error = packet.findChild("error");
5718 callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
5719 }
5720 });
5721 }
5722
5723 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
5724 fetchCaps(account, jid, presence, null);
5725 }
5726
5727 public void fetchCaps(Account account, final Jid jid, final Presence presence, Runnable cb) {
5728 final Pair<String, String> key = presence == null ? null : new Pair<>(presence.getHash(), presence.getVer());
5729 final ServiceDiscoveryResult disco = key == null ? null : getCachedServiceDiscoveryResult(key);
5730
5731 if (disco != null) {
5732 presence.setServiceDiscoveryResult(disco);
5733 final Contact contact = account.getRoster().getContact(jid);
5734 if (contact.refreshRtpCapability()) {
5735 syncRoster(account);
5736 }
5737 contact.refreshCaps();
5738 if (disco.hasIdentity("gateway", "pstn")) {
5739 contact.registerAsPhoneAccount(this);
5740 mQuickConversationsService.considerSyncBackground(false);
5741 }
5742 updateConversationUi(true);
5743 } else {
5744 final Iq request = new Iq(Iq.Type.GET);
5745 request.setTo(jid);
5746 final String node = presence == null ? null : presence.getNode();
5747 final String ver = presence == null ? null : presence.getVer();
5748 final Element query = request.query(Namespace.DISCO_INFO);
5749 if (node != null && ver != null) {
5750 query.setAttribute("node", node + "#" + ver);
5751 }
5752 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + (key == null ? "" : key.second) + " to " + jid);
5753 sendIqPacket(account, request, (response) -> {
5754 if (response.getType() == Iq.Type.RESULT) {
5755 final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
5756 if (presence == null || presence.getVer() == null || presence.getVer().equals(discoveryResult.getVer())) {
5757 databaseBackend.insertDiscoveryResult(discoveryResult);
5758 injectServiceDiscoveryResult(account.getRoster(), presence == null ? null : presence.getHash(), presence == null ? null : presence.getVer(), jid.getResource(), discoveryResult);
5759 if (discoveryResult.hasIdentity("gateway", "pstn")) {
5760 final Contact contact = account.getRoster().getContact(jid);
5761 contact.registerAsPhoneAccount(this);
5762 mQuickConversationsService.considerSyncBackground(false);
5763 }
5764 updateConversationUi(true);
5765 if (cb != null) cb.run();
5766 } else {
5767 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
5768 }
5769 } else {
5770 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
5771 }
5772 });
5773 }
5774 }
5775
5776 public void fetchCommands(Account account, final Jid jid, Consumer<Iq> callback) {
5777 final var request = mIqGenerator.queryDiscoItems(jid, "http://jabber.org/protocol/commands");
5778 sendIqPacket(account, request, callback);
5779 }
5780
5781 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, String resource, ServiceDiscoveryResult disco) {
5782 boolean rosterNeedsSync = false;
5783 for (final Contact contact : roster.getContacts()) {
5784 boolean serviceDiscoverySet = false;
5785 Presence onePresence = contact.getPresences().get(resource == null ? "" : resource);
5786 if (onePresence != null) {
5787 onePresence.setServiceDiscoveryResult(disco);
5788 serviceDiscoverySet = true;
5789 } else if (resource == null && hash == null && ver == null) {
5790 Presence p = new Presence(Presence.Status.OFFLINE, null, null, null, "");
5791 p.setServiceDiscoveryResult(disco);
5792 contact.updatePresence("", p);
5793 serviceDiscoverySet = true;
5794 }
5795 if (hash != null && ver != null) {
5796 for (final Presence presence : contact.getPresences().getPresences()) {
5797 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
5798 presence.setServiceDiscoveryResult(disco);
5799 serviceDiscoverySet = true;
5800 }
5801 }
5802 }
5803 if (serviceDiscoverySet) {
5804 rosterNeedsSync |= contact.refreshRtpCapability();
5805 contact.refreshCaps();
5806 }
5807 }
5808 if (rosterNeedsSync) {
5809 syncRoster(roster.getAccount());
5810 }
5811 }
5812
5813 public void fetchMamPreferences(final Account account, final OnMamPreferencesFetched callback) {
5814 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5815 final Iq request = new Iq(Iq.Type.GET);
5816 request.addChild("prefs", version.namespace);
5817 sendIqPacket(account, request, (packet) -> {
5818 final Element prefs = packet.findChild("prefs", version.namespace);
5819 if (packet.getType() == Iq.Type.RESULT && prefs != null) {
5820 callback.onPreferencesFetched(prefs);
5821 } else {
5822 callback.onPreferencesFetchFailed();
5823 }
5824 });
5825 }
5826
5827 public PushManagementService getPushManagementService() {
5828 return mPushManagementService;
5829 }
5830
5831 public void changeStatus(Account account, PresenceTemplate template, String signature) {
5832 if (!template.getStatusMessage().isEmpty()) {
5833 databaseBackend.insertPresenceTemplate(template);
5834 }
5835 account.setPgpSignature(signature);
5836 account.setPresenceStatus(template.getStatus());
5837 account.setPresenceStatusMessage(template.getStatusMessage());
5838 databaseBackend.updateAccount(account);
5839 sendPresence(account);
5840 }
5841
5842 public List<PresenceTemplate> getPresenceTemplates(Account account) {
5843 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5844 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5845 if (!templates.contains(template)) {
5846 templates.add(0, template);
5847 }
5848 }
5849 return templates;
5850 }
5851
5852 public void saveConversationAsBookmark(final Conversation conversation, final String name) {
5853 final Account account = conversation.getAccount();
5854 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5855 String nick = conversation.getMucOptions().getActualNick();
5856 if (nick == null) nick = conversation.getJid().getResource();
5857 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5858 bookmark.setNick(nick);
5859 }
5860 if (!TextUtils.isEmpty(name)) {
5861 bookmark.setBookmarkName(name);
5862 }
5863 bookmark.setAutojoin(true);
5864 createBookmark(account, bookmark);
5865 bookmark.setConversation(conversation);
5866 }
5867
5868 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5869 boolean performedVerification = false;
5870 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5871 for (XmppUri.Fingerprint fp : fingerprints) {
5872 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5873 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5874 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5875 if (fingerprintStatus != null) {
5876 if (!fingerprintStatus.isVerified()) {
5877 performedVerification = true;
5878 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5879 }
5880 } else {
5881 axolotlService.preVerifyFingerprint(contact, fingerprint);
5882 }
5883 }
5884 }
5885 return performedVerification;
5886 }
5887
5888 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5889 final AxolotlService axolotlService = account.getAxolotlService();
5890 boolean verifiedSomething = false;
5891 for (XmppUri.Fingerprint fp : fingerprints) {
5892 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5893 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5894 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5895 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5896 if (fingerprintStatus != null) {
5897 if (!fingerprintStatus.isVerified()) {
5898 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5899 verifiedSomething = true;
5900 }
5901 } else {
5902 axolotlService.preVerifyFingerprint(account, fingerprint);
5903 verifiedSomething = true;
5904 }
5905 }
5906 }
5907 return verifiedSomething;
5908 }
5909
5910 public boolean blindTrustBeforeVerification() {
5911 return getBooleanPreference(AppSettings.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
5912 }
5913
5914 public ShortcutService getShortcutService() {
5915 return mShortcutService;
5916 }
5917
5918 public void pushMamPreferences(Account account, Element prefs) {
5919 final Iq set = new Iq(Iq.Type.SET);
5920 set.addChild(prefs);
5921 sendIqPacket(account, set, null);
5922 }
5923
5924 public void evictPreview(File f) {
5925 if (f == null) return;
5926
5927 if (mDrawableCache.remove(f.getAbsolutePath()) != null) {
5928 Log.d(Config.LOGTAG, "deleted cached preview");
5929 }
5930 }
5931
5932 public void evictPreview(String uuid) {
5933 if (mDrawableCache.remove(uuid) != null) {
5934 Log.d(Config.LOGTAG, "deleted cached preview");
5935 }
5936 }
5937
5938 public interface OnMamPreferencesFetched {
5939 void onPreferencesFetched(Element prefs);
5940
5941 void onPreferencesFetchFailed();
5942 }
5943
5944 public interface OnAccountCreated {
5945 void onAccountCreated(Account account);
5946
5947 void informUser(int r);
5948 }
5949
5950 public interface OnMoreMessagesLoaded {
5951 void onMoreMessagesLoaded(int count, Conversation conversation);
5952
5953 void informUser(int r);
5954 }
5955
5956 public interface OnAccountPasswordChanged {
5957 void onPasswordChangeSucceeded();
5958
5959 void onPasswordChangeFailed();
5960 }
5961
5962 public interface OnRoomDestroy {
5963 void onRoomDestroySucceeded();
5964
5965 void onRoomDestroyFailed();
5966 }
5967
5968 public interface OnAffiliationChanged {
5969 void onAffiliationChangedSuccessful(Jid jid);
5970
5971 void onAffiliationChangeFailed(Jid jid, int resId);
5972 }
5973
5974 public interface OnConversationUpdate {
5975 default void onConversationUpdate() { onConversationUpdate(false); }
5976 default void onConversationUpdate(boolean newCaps) { onConversationUpdate(); }
5977 }
5978
5979 public interface OnJingleRtpConnectionUpdate {
5980 void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5981
5982 void onAudioDeviceChanged(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices);
5983 }
5984
5985 public interface OnAccountUpdate {
5986 void onAccountUpdate();
5987 }
5988
5989 public interface OnCaptchaRequested {
5990 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5991 }
5992
5993 public interface OnRosterUpdate {
5994 void onRosterUpdate(final UpdateRosterReason reason, final Contact contact);
5995 }
5996
5997 public interface OnMucRosterUpdate {
5998 void onMucRosterUpdate();
5999 }
6000
6001 public interface OnConferenceConfigurationFetched {
6002 void onConferenceConfigurationFetched(Conversation conversation);
6003
6004 void onFetchFailed(Conversation conversation, String errorCondition);
6005 }
6006
6007 public interface OnConferenceJoined {
6008 void onConferenceJoined(Conversation conversation);
6009 }
6010
6011 public interface OnConfigurationPushed {
6012 void onPushSucceeded();
6013
6014 void onPushFailed();
6015 }
6016
6017 public interface OnShowErrorToast {
6018 void onShowErrorToast(int resId);
6019 }
6020
6021 public class XmppConnectionBinder extends Binder {
6022 public XmppConnectionService getService() {
6023 return XmppConnectionService.this;
6024 }
6025 }
6026
6027 private class InternalEventReceiver extends BroadcastReceiver {
6028
6029 @Override
6030 public void onReceive(final Context context, final Intent intent) {
6031 onStartCommand(intent, 0, 0);
6032 }
6033 }
6034
6035 private class RestrictedEventReceiver extends BroadcastReceiver {
6036
6037 private final Collection<String> allowedActions;
6038
6039 private RestrictedEventReceiver(final Collection<String> allowedActions) {
6040 this.allowedActions = allowedActions;
6041 }
6042
6043 @Override
6044 public void onReceive(final Context context, final Intent intent) {
6045 final String action = intent == null ? null : intent.getAction();
6046 if (allowedActions.contains(action)) {
6047 onStartCommand(intent,0,0);
6048 } else {
6049 Log.e(Config.LOGTAG,"restricting broadcast of event "+action);
6050 }
6051 }
6052 }
6053
6054 public static class OngoingCall {
6055 public final AbstractJingleConnection.Id id;
6056 public final Set<Media> media;
6057 public final boolean reconnecting;
6058
6059 public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
6060 this.id = id;
6061 this.media = media;
6062 this.reconnecting = reconnecting;
6063 }
6064
6065 @Override
6066 public boolean equals(Object o) {
6067 if (this == o) return true;
6068 if (o == null || getClass() != o.getClass()) return false;
6069 OngoingCall that = (OngoingCall) o;
6070 return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
6071 }
6072
6073 @Override
6074 public int hashCode() {
6075 return Objects.hashCode(id, media, reconnecting);
6076 }
6077 }
6078
6079 public static void toggleForegroundService(final XmppConnectionService service) {
6080 if (service == null) {
6081 return;
6082 }
6083 service.toggleForegroundService();
6084 }
6085
6086 public static void toggleForegroundService(final ConversationsActivity activity) {
6087 if (activity == null) {
6088 return;
6089 }
6090 toggleForegroundService(activity.xmppConnectionService);
6091 }
6092
6093 public static class BlockedMediaException extends Exception { }
6094
6095 public static enum UpdateRosterReason {
6096 INIT,
6097 AVATAR,
6098 PUSH,
6099 PRESENCE
6100 }
6101}