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