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