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