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