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