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