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