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