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(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
2014 final Set<Jid> previousBookmarks = account.getBookmarkedJids();
2015 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
2016 for (Bookmark bookmark : bookmarks.values()) {
2017 previousBookmarks.remove(bookmark.getJid().asBareJid());
2018 processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
2019 }
2020 if (pep && synchronizeWithBookmarks) {
2021 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
2022 for (Jid jid : previousBookmarks) {
2023 processDeletedBookmark(account, jid);
2024 }
2025 }
2026 account.setBookmarks(bookmarks);
2027 }
2028
2029 public void processDeletedBookmark(Account account, Jid jid) {
2030 final Conversation conversation = find(account, jid);
2031 if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2032 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
2033 archiveConversation(conversation, false);
2034 }
2035 }
2036
2037 private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
2038 final Account account = bookmark.getAccount();
2039 Conversation conversation = find(bookmark);
2040 if (conversation != null) {
2041 if (conversation.getMode() != Conversation.MODE_MULTI) {
2042 return;
2043 }
2044 bookmark.setConversation(conversation);
2045 if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
2046 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
2047 archiveConversation(conversation, false);
2048 } else {
2049 final MucOptions mucOptions = conversation.getMucOptions();
2050 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
2051 final String current = mucOptions.getActualNick();
2052 final String proposed = mucOptions.getProposedNick();
2053 if (current != null && !current.equals(proposed)) {
2054 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
2055 joinMuc(conversation);
2056 }
2057 }
2058 }
2059 } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
2060 conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
2061 bookmark.setConversation(conversation);
2062 }
2063 }
2064
2065 public void processModifiedBookmark(Bookmark bookmark) {
2066 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
2067 processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
2068 }
2069
2070 public void createBookmark(final Account account, final Bookmark bookmark) {
2071 account.putBookmark(bookmark);
2072 final XmppConnection connection = account.getXmppConnection();
2073 if (connection == null) {
2074 Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
2075 } else if (connection.getFeatures().bookmarks2()) {
2076 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": pushing bookmark via Bookmarks 2");
2077 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
2078 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
2079 } else if (connection.getFeatures().bookmarksConversion()) {
2080 pushBookmarksPep(account);
2081 } else {
2082 pushBookmarksPrivateXml(account);
2083 }
2084 }
2085
2086 public void deleteBookmark(final Account account, final Bookmark bookmark) {
2087 account.removeBookmark(bookmark);
2088 final XmppConnection connection = account.getXmppConnection();
2089 if (connection.getFeatures().bookmarks2()) {
2090 final IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
2091 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": removing bookmark via Bookmarks 2");
2092 sendIqPacket(account, request, (a, response) -> {
2093 if (response.getType() == IqPacket.TYPE.ERROR) {
2094 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
2095 }
2096 });
2097 } else if (connection.getFeatures().bookmarksConversion()) {
2098 pushBookmarksPep(account);
2099 } else {
2100 pushBookmarksPrivateXml(account);
2101 }
2102 }
2103
2104 private void pushBookmarksPrivateXml(Account account) {
2105 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
2106 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2107 Element query = iqPacket.query("jabber:iq:private");
2108 Element storage = query.addChild("storage", "storage:bookmarks");
2109 for (final Bookmark bookmark : account.getBookmarks()) {
2110 storage.addChild(bookmark);
2111 }
2112 sendIqPacket(account, iqPacket, mDefaultIqHandler);
2113 }
2114
2115 private void pushBookmarksPep(Account account) {
2116 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
2117 final Element storage = new Element("storage", "storage:bookmarks");
2118 for (final Bookmark bookmark : account.getBookmarks()) {
2119 storage.addChild(bookmark);
2120 }
2121 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
2122
2123 }
2124
2125 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
2126 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2127
2128 }
2129
2130 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
2131 final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
2132 sendIqPacket(account, packet, (a, response) -> {
2133 if (response.getType() == IqPacket.TYPE.RESULT) {
2134 return;
2135 }
2136 if (retry && PublishOptions.preconditionNotMet(response)) {
2137 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
2138 @Override
2139 public void onPushSucceeded() {
2140 pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
2141 }
2142
2143 @Override
2144 public void onPushFailed() {
2145 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
2146 }
2147 });
2148 } else {
2149 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing "+node+" (retry=" + retry + ") " + response);
2150 }
2151 });
2152 }
2153
2154 private void restoreFromDatabase() {
2155 synchronized (this.conversations) {
2156 final Map<String, Account> accountLookupTable = new Hashtable<>();
2157 for (Account account : this.accounts) {
2158 accountLookupTable.put(account.getUuid(), account);
2159 }
2160 Log.d(Config.LOGTAG, "restoring conversations...");
2161 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2162 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2163 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
2164 Conversation conversation = iterator.next();
2165 Account account = accountLookupTable.get(conversation.getAccountUuid());
2166 if (account != null) {
2167 conversation.setAccount(account);
2168 } else {
2169 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
2170 iterator.remove();
2171 }
2172 }
2173 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2174 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
2175 Runnable runnable = () -> {
2176 if (DatabaseBackend.requiresMessageIndexRebuild()) {
2177 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2178 }
2179 final long deletionDate = getAutomaticMessageDeletionDate();
2180 mLastExpiryRun.set(SystemClock.elapsedRealtime());
2181 if (deletionDate > 0) {
2182 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
2183 databaseBackend.expireOldMessages(deletionDate);
2184 }
2185 Log.d(Config.LOGTAG, "restoring roster...");
2186 for (final Account account : accounts) {
2187 databaseBackend.readRoster(account.getRoster());
2188 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
2189 }
2190 getBitmapCache().evictAll();
2191 loadPhoneContacts();
2192 Log.d(Config.LOGTAG, "restoring messages...");
2193 final long startMessageRestore = SystemClock.elapsedRealtime();
2194 final Conversation quickLoad = QuickLoader.get(this.conversations);
2195 if (quickLoad != null) {
2196 restoreMessages(quickLoad);
2197 updateConversationUi();
2198 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2199 Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
2200 }
2201 for (Conversation conversation : this.conversations) {
2202 if (quickLoad != conversation) {
2203 restoreMessages(conversation);
2204 }
2205 }
2206 mNotificationService.finishBacklog();
2207 restoredFromDatabaseLatch.countDown();
2208 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2209 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2210 updateConversationUi();
2211 };
2212 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2213 }
2214 }
2215
2216 private void restoreMessages(Conversation conversation) {
2217 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2218 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2219 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2220 }
2221
2222 public void loadPhoneContacts() {
2223 mContactMergerExecutor.execute(() -> {
2224 final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2225 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2226 for (final Account account : accounts) {
2227 final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2228 for (final JabberIdContact jidContact : contacts.values()) {
2229 final Contact contact = account.getRoster().getContact(jidContact.getJid());
2230 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2231 if (needsCacheClean) {
2232 getAvatarService().clear(contact);
2233 }
2234 withSystemAccounts.remove(contact);
2235 }
2236 for (final Contact contact : withSystemAccounts) {
2237 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2238 if (needsCacheClean) {
2239 getAvatarService().clear(contact);
2240 }
2241 }
2242 }
2243 Log.d(Config.LOGTAG, "finished merging phone contacts");
2244 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2245 updateRosterUi();
2246 mQuickConversationsService.considerSync();
2247 });
2248 }
2249
2250
2251 public void syncRoster(final Account account) {
2252 mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
2253 }
2254
2255 public List<Conversation> getConversations() {
2256 return this.conversations;
2257 }
2258
2259 private void markFileDeleted(final File file) {
2260 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2261 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2262 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2263 return;
2264 }
2265 }
2266 final boolean isInternalFile = fileBackend.isInternalFile(file);
2267 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2268 Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2269 markUuidsAsDeletedFiles(uuids);
2270 }
2271
2272 private void markUuidsAsDeletedFiles(List<String> uuids) {
2273 boolean deleted = false;
2274 for (Conversation conversation : getConversations()) {
2275 deleted |= conversation.markAsDeleted(uuids);
2276 }
2277 for (final String uuid : uuids) {
2278 evictPreview(uuid);
2279 }
2280 if (deleted) {
2281 updateConversationUi();
2282 }
2283 }
2284
2285 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2286 boolean changed = false;
2287 for (Conversation conversation : getConversations()) {
2288 changed |= conversation.markAsChanged(infos);
2289 }
2290 if (changed) {
2291 updateConversationUi();
2292 }
2293 }
2294
2295 public void populateWithOrderedConversations(final List<Conversation> list) {
2296 populateWithOrderedConversations(list, true, true);
2297 }
2298
2299 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2300 populateWithOrderedConversations(list, includeNoFileUpload, true);
2301 }
2302
2303 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2304 final List<String> orderedUuids;
2305 if (sort) {
2306 orderedUuids = null;
2307 } else {
2308 orderedUuids = new ArrayList<>();
2309 for (Conversation conversation : list) {
2310 orderedUuids.add(conversation.getUuid());
2311 }
2312 }
2313 list.clear();
2314 if (includeNoFileUpload) {
2315 list.addAll(getConversations());
2316 } else {
2317 for (Conversation conversation : getConversations()) {
2318 if (conversation.getMode() == Conversation.MODE_SINGLE
2319 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2320 list.add(conversation);
2321 }
2322 }
2323 }
2324 try {
2325 if (orderedUuids != null) {
2326 Collections.sort(list, (a, b) -> {
2327 final int indexA = orderedUuids.indexOf(a.getUuid());
2328 final int indexB = orderedUuids.indexOf(b.getUuid());
2329 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2330 return a.compareTo(b);
2331 }
2332 return indexA - indexB;
2333 });
2334 } else {
2335 Collections.sort(list);
2336 }
2337 } catch (IllegalArgumentException e) {
2338 //ignore
2339 }
2340 }
2341
2342 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2343 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2344 return;
2345 } else if (timestamp == 0) {
2346 return;
2347 }
2348 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2349 final Runnable runnable = () -> {
2350 final Account account = conversation.getAccount();
2351 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2352 if (messages.size() > 0) {
2353 conversation.addAll(0, messages);
2354 callback.onMoreMessagesLoaded(messages.size(), conversation);
2355 } else if (conversation.hasMessagesLeftOnServer()
2356 && account.isOnlineAndConnected()
2357 && conversation.getLastClearHistory().getTimestamp() == 0) {
2358 final boolean mamAvailable;
2359 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2360 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2361 } else {
2362 mamAvailable = conversation.getMucOptions().mamSupport();
2363 }
2364 if (mamAvailable) {
2365 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2366 if (query != null) {
2367 query.setCallback(callback);
2368 callback.informUser(R.string.fetching_history_from_server);
2369 } else {
2370 callback.informUser(R.string.not_fetching_history_retention_period);
2371 }
2372
2373 }
2374 }
2375 };
2376 mDatabaseReaderExecutor.execute(runnable);
2377 }
2378
2379 public List<Account> getAccounts() {
2380 return this.accounts;
2381 }
2382
2383
2384 /**
2385 * 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)
2386 */
2387 public List<Conversation> findAllConferencesWith(Contact contact) {
2388 final ArrayList<Conversation> results = new ArrayList<>();
2389 for (final Conversation c : conversations) {
2390 if (c.getMode() != Conversation.MODE_MULTI) {
2391 continue;
2392 }
2393 final MucOptions mucOptions = c.getMucOptions();
2394 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2395 results.add(c);
2396 }
2397 }
2398 return results;
2399 }
2400
2401 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2402 for (final Conversation conversation : haystack) {
2403 if (conversation.getContact() == contact) {
2404 return conversation;
2405 }
2406 }
2407 return null;
2408 }
2409
2410 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2411 if (jid == null) {
2412 return null;
2413 }
2414 for (final Conversation conversation : haystack) {
2415 if ((account == null || conversation.getAccount() == account)
2416 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2417 return conversation;
2418 }
2419 }
2420 return null;
2421 }
2422
2423 public boolean isConversationsListEmpty(final Conversation ignore) {
2424 synchronized (this.conversations) {
2425 final int size = this.conversations.size();
2426 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2427 }
2428 }
2429
2430 public boolean isConversationStillOpen(final Conversation conversation) {
2431 synchronized (this.conversations) {
2432 for (Conversation current : this.conversations) {
2433 if (current == conversation) {
2434 return true;
2435 }
2436 }
2437 }
2438 return false;
2439 }
2440
2441 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2442 return this.findOrCreateConversation(account, jid, muc, false, async);
2443 }
2444
2445 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2446 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2447 }
2448
2449 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2450 synchronized (this.conversations) {
2451 Conversation conversation = find(account, jid);
2452 if (conversation != null) {
2453 return conversation;
2454 }
2455 conversation = databaseBackend.findConversation(account, jid);
2456 final boolean loadMessagesFromDb;
2457 if (conversation != null) {
2458 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2459 conversation.setAccount(account);
2460 if (muc) {
2461 conversation.setMode(Conversation.MODE_MULTI);
2462 conversation.setContactJid(jid);
2463 } else {
2464 conversation.setMode(Conversation.MODE_SINGLE);
2465 conversation.setContactJid(jid.asBareJid());
2466 }
2467 databaseBackend.updateConversation(conversation);
2468 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2469 } else {
2470 String conversationName;
2471 Contact contact = account.getRoster().getContact(jid);
2472 if (contact != null) {
2473 conversationName = contact.getDisplayName();
2474 } else {
2475 conversationName = jid.getLocal();
2476 }
2477 if (muc) {
2478 conversation = new Conversation(conversationName, account, jid,
2479 Conversation.MODE_MULTI);
2480 } else {
2481 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2482 Conversation.MODE_SINGLE);
2483 }
2484 this.databaseBackend.createConversation(conversation);
2485 loadMessagesFromDb = false;
2486 }
2487 final Conversation c = conversation;
2488 final Runnable runnable = () -> {
2489 if (loadMessagesFromDb) {
2490 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2491 updateConversationUi();
2492 c.messagesLoaded.set(true);
2493 }
2494 if (account.getXmppConnection() != null
2495 && !c.getContact().isBlocked()
2496 && account.getXmppConnection().getFeatures().mam()
2497 && !muc) {
2498 if (query == null) {
2499 mMessageArchiveService.query(c);
2500 } else {
2501 if (query.getConversation() == null) {
2502 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2503 }
2504 }
2505 }
2506 if (joinAfterCreate) {
2507 joinMuc(c);
2508 }
2509 };
2510 if (async) {
2511 mDatabaseReaderExecutor.execute(runnable);
2512 } else {
2513 runnable.run();
2514 }
2515 this.conversations.add(conversation);
2516 updateConversationUi();
2517 return conversation;
2518 }
2519 }
2520
2521 public void archiveConversation(Conversation conversation) {
2522 archiveConversation(conversation, true);
2523 }
2524
2525 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2526 getNotificationService().clear(conversation);
2527 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2528 conversation.setNextMessage(null);
2529 synchronized (this.conversations) {
2530 getMessageArchiveService().kill(conversation);
2531 if (conversation.getMode() == Conversation.MODE_MULTI) {
2532 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2533 final Bookmark bookmark = conversation.getBookmark();
2534 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2535 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2536 Account account = bookmark.getAccount();
2537 bookmark.setConversation(null);
2538 deleteBookmark(account, bookmark);
2539 } else if (bookmark.autojoin()) {
2540 bookmark.setAutojoin(false);
2541 createBookmark(bookmark.getAccount(), bookmark);
2542 }
2543 }
2544 }
2545 leaveMuc(conversation);
2546 } else {
2547 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2548 stopPresenceUpdatesTo(conversation.getContact());
2549 }
2550 }
2551 updateConversation(conversation);
2552 this.conversations.remove(conversation);
2553 updateConversationUi();
2554 }
2555 }
2556
2557 public void stopPresenceUpdatesTo(Contact contact) {
2558 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2559 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2560 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2561 }
2562
2563 public void createAccount(final Account account) {
2564 account.initAccountServices(this);
2565 databaseBackend.createAccount(account);
2566 if (CallIntegration.hasSystemFeature(this)) {
2567 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2568 }
2569 this.accounts.add(account);
2570 this.reconnectAccountInBackground(account);
2571 updateAccountUi();
2572 syncEnabledAccountSetting();
2573 toggleForegroundService();
2574 }
2575
2576 private void syncEnabledAccountSetting() {
2577 final boolean hasEnabledAccounts = hasEnabledAccounts();
2578 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2579 toggleSetProfilePictureActivity(hasEnabledAccounts);
2580 }
2581
2582 private void toggleSetProfilePictureActivity(final boolean enabled) {
2583 try {
2584 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2585 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2586 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2587 } catch (IllegalStateException e) {
2588 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
2589 }
2590 }
2591
2592 public boolean reconfigurePushDistributor() {
2593 return this.unifiedPushBroker.reconfigurePushDistributor();
2594 }
2595
2596 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
2597 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
2598 }
2599
2600 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
2601 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
2602 }
2603
2604 private void provisionAccount(final String address, final String password) {
2605 final Jid jid = Jid.ofEscaped(address);
2606 final Account account = new Account(jid, password);
2607 account.setOption(Account.OPTION_DISABLED, true);
2608 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2609 createAccount(account);
2610 }
2611
2612 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2613 new Thread(() -> {
2614 try {
2615 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2616 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2617 if (cert == null) {
2618 callback.informUser(R.string.unable_to_parse_certificate);
2619 return;
2620 }
2621 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2622 if (info == null) {
2623 callback.informUser(R.string.certificate_does_not_contain_jid);
2624 return;
2625 }
2626 if (findAccountByJid(info.first) == null) {
2627 final Account account = new Account(info.first, "");
2628 account.setPrivateKeyAlias(alias);
2629 account.setOption(Account.OPTION_DISABLED, true);
2630 account.setOption(Account.OPTION_FIXED_USERNAME, true);
2631 account.setDisplayName(info.second);
2632 createAccount(account);
2633 callback.onAccountCreated(account);
2634 if (Config.X509_VERIFICATION) {
2635 try {
2636 getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2637 } catch (CertificateException e) {
2638 callback.informUser(R.string.certificate_chain_is_not_trusted);
2639 }
2640 }
2641 } else {
2642 callback.informUser(R.string.account_already_exists);
2643 }
2644 } catch (Exception e) {
2645 callback.informUser(R.string.unable_to_parse_certificate);
2646 }
2647 }).start();
2648
2649 }
2650
2651 public void updateKeyInAccount(final Account account, final String alias) {
2652 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2653 try {
2654 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2655 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2656 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2657 if (info == null) {
2658 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2659 return;
2660 }
2661 if (account.getJid().asBareJid().equals(info.first)) {
2662 account.setPrivateKeyAlias(alias);
2663 account.setDisplayName(info.second);
2664 databaseBackend.updateAccount(account);
2665 if (Config.X509_VERIFICATION) {
2666 try {
2667 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2668 } catch (CertificateException e) {
2669 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2670 }
2671 account.getAxolotlService().regenerateKeys(true);
2672 }
2673 } else {
2674 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2675 }
2676 } catch (Exception e) {
2677 e.printStackTrace();
2678 }
2679 }
2680
2681 public boolean updateAccount(final Account account) {
2682 if (databaseBackend.updateAccount(account)) {
2683 account.setShowErrorNotification(true);
2684 this.statusListener.onStatusChanged(account);
2685 databaseBackend.updateAccount(account);
2686 reconnectAccountInBackground(account);
2687 updateAccountUi();
2688 getNotificationService().updateErrorNotification();
2689 toggleForegroundService();
2690 syncEnabledAccountSetting();
2691 mChannelDiscoveryService.cleanCache();
2692 if (CallIntegration.hasSystemFeature(this)) {
2693 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2694 }
2695 return true;
2696 } else {
2697 return false;
2698 }
2699 }
2700
2701 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2702 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2703 sendIqPacket(account, iq, (a, packet) -> {
2704 if (packet.getType() == IqPacket.TYPE.RESULT) {
2705 a.setPassword(newPassword);
2706 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2707 databaseBackend.updateAccount(a);
2708 callback.onPasswordChangeSucceeded();
2709 } else {
2710 callback.onPasswordChangeFailed();
2711 }
2712 });
2713 }
2714
2715 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
2716 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2717 final Element query = iqPacket.addChild("query",Namespace.REGISTER);
2718 query.addChild("remove");
2719 sendIqPacket(account, iqPacket, (a, response) -> {
2720 if (response.getType() == IqPacket.TYPE.RESULT) {
2721 deleteAccount(a);
2722 callback.accept(true);
2723 } else {
2724 callback.accept(false);
2725 }
2726 });
2727 }
2728
2729 public void deleteAccount(final Account account) {
2730 final boolean connected = account.getStatus() == Account.State.ONLINE;
2731 synchronized (this.conversations) {
2732 if (connected) {
2733 account.getAxolotlService().deleteOmemoIdentity();
2734 }
2735 for (final Conversation conversation : conversations) {
2736 if (conversation.getAccount() == account) {
2737 if (conversation.getMode() == Conversation.MODE_MULTI) {
2738 if (connected) {
2739 leaveMuc(conversation);
2740 }
2741 }
2742 conversations.remove(conversation);
2743 mNotificationService.clear(conversation);
2744 }
2745 }
2746 if (account.getXmppConnection() != null) {
2747 new Thread(() -> disconnect(account, !connected)).start();
2748 }
2749 final Runnable runnable = () -> {
2750 if (!databaseBackend.deleteAccount(account)) {
2751 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2752 }
2753 };
2754 mDatabaseWriterExecutor.execute(runnable);
2755 this.accounts.remove(account);
2756 CallIntegrationConnectionService.unregisterPhoneAccount(this, account);
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(Conversation conversation, 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 if (synchronizeWithBookmarks()) {
3299 bookmark.setAutojoin(true);
3300 }
3301 createBookmark(conversation.getAccount(), bookmark);
3302 }
3303 updateConversation(conversation);
3304 joinMuc(conversation);
3305 }
3306 }
3307
3308 public void deleteAvatar(final Account account) {
3309 final AtomicBoolean executed = new AtomicBoolean(false);
3310 final Runnable onDeleted =
3311 () -> {
3312 if (executed.compareAndSet(false, true)) {
3313 account.setAvatar(null);
3314 databaseBackend.updateAccount(account);
3315 getAvatarService().clear(account);
3316 updateAccountUi();
3317 }
3318 };
3319 deleteVcardAvatar(account, onDeleted);
3320 deletePepNode(account, Namespace.AVATAR_DATA);
3321 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3322 }
3323
3324 public void deletePepNode(final Account account, final String node) {
3325 deletePepNode(account, node, null);
3326 }
3327
3328 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3329 final IqPacket request = mIqGenerator.deleteNode(node);
3330 sendIqPacket(account, request, (a, packet) -> {
3331 if (packet.getType() == IqPacket.TYPE.RESULT) {
3332 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": successfully deleted pep node "+node);
3333 if (runnable != null) {
3334 runnable.run();
3335 }
3336 } else {
3337 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": failed to delete "+ packet);
3338 }
3339 });
3340 }
3341
3342 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3343 final IqPacket retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3344 sendIqPacket(account, retrieveVcard, (a, response) -> {
3345 if (response.getType() != IqPacket.TYPE.RESULT) {
3346 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3347 return;
3348 }
3349 final Element vcard = response.findChild("vCard", "vcard-temp");
3350 if (vcard == null) {
3351 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3352 return;
3353 }
3354 Element photo = vcard.findChild("PHOTO");
3355 if (photo == null) {
3356 photo = vcard.addChild("PHOTO");
3357 }
3358 photo.clearChildren();
3359 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3360 publication.setTo(a.getJid().asBareJid());
3361 publication.addChild(vcard);
3362 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3363 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3364 Log.d(Config.LOGTAG,a1.getJid().asBareJid()+": successfully deleted vcard avatar");
3365 runnable.run();
3366 } else {
3367 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3368 }
3369 });
3370 });
3371 }
3372
3373 private boolean hasEnabledAccounts() {
3374 if (this.accounts == null) {
3375 return false;
3376 }
3377 for (final Account account : this.accounts) {
3378 if (account.isConnectionEnabled()) {
3379 return true;
3380 }
3381 }
3382 return false;
3383 }
3384
3385
3386 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3387 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3388 }
3389
3390 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3391 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3392 }
3393
3394
3395 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3396 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3397 }
3398
3399 public void persistSelfNick(final MucOptions.User self) {
3400 final Conversation conversation = self.getConversation();
3401 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3402 Jid full = self.getFullJid();
3403 if (!full.equals(conversation.getJid())) {
3404 Log.d(Config.LOGTAG, "nick changed. updating");
3405 conversation.setContactJid(full);
3406 databaseBackend.updateConversation(conversation);
3407 }
3408
3409 final Bookmark bookmark = conversation.getBookmark();
3410 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3411 if (bookmark != null && (tookProposedNickFromBookmark || Strings.isNullOrEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
3412 final Account account = conversation.getAccount();
3413 final String defaultNick = MucOptions.defaultNick(account);
3414 if (Strings.isNullOrEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3415 return;
3416 }
3417 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
3418 bookmark.setNick(full.getResource());
3419 createBookmark(bookmark.getAccount(), bookmark);
3420 }
3421 }
3422
3423 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3424 final MucOptions options = conversation.getMucOptions();
3425 final Jid joinJid = options.createJoinJid(nick);
3426 if (joinJid == null) {
3427 return false;
3428 }
3429 if (options.online()) {
3430 Account account = conversation.getAccount();
3431 options.setOnRenameListener(new OnRenameListener() {
3432
3433 @Override
3434 public void onSuccess() {
3435 callback.success(conversation);
3436 }
3437
3438 @Override
3439 public void onFailure() {
3440 callback.error(R.string.nick_in_use, conversation);
3441 }
3442 });
3443
3444 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
3445 packet.setTo(joinJid);
3446 sendPresencePacket(account, packet);
3447 } else {
3448 conversation.setContactJid(joinJid);
3449 databaseBackend.updateConversation(conversation);
3450 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3451 Bookmark bookmark = conversation.getBookmark();
3452 if (bookmark != null) {
3453 bookmark.setNick(nick);
3454 createBookmark(bookmark.getAccount(), bookmark);
3455 }
3456 joinMuc(conversation);
3457 }
3458 }
3459 return true;
3460 }
3461
3462 public void leaveMuc(Conversation conversation) {
3463 leaveMuc(conversation, false);
3464 }
3465
3466 private void leaveMuc(Conversation conversation, boolean now) {
3467 final Account account = conversation.getAccount();
3468 synchronized (account.pendingConferenceJoins) {
3469 account.pendingConferenceJoins.remove(conversation);
3470 }
3471 synchronized (account.pendingConferenceLeaves) {
3472 account.pendingConferenceLeaves.remove(conversation);
3473 }
3474 if (account.getStatus() == Account.State.ONLINE || now) {
3475 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3476 conversation.getMucOptions().setOffline();
3477 Bookmark bookmark = conversation.getBookmark();
3478 if (bookmark != null) {
3479 bookmark.setConversation(null);
3480 }
3481 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3482 } else {
3483 synchronized (account.pendingConferenceLeaves) {
3484 account.pendingConferenceLeaves.add(conversation);
3485 }
3486 }
3487 }
3488
3489 public String findConferenceServer(final Account account) {
3490 String server;
3491 if (account.getXmppConnection() != null) {
3492 server = account.getXmppConnection().getMucServer();
3493 if (server != null) {
3494 return server;
3495 }
3496 }
3497 for (Account other : getAccounts()) {
3498 if (other != account && other.getXmppConnection() != null) {
3499 server = other.getXmppConnection().getMucServer();
3500 if (server != null) {
3501 return server;
3502 }
3503 }
3504 }
3505 return null;
3506 }
3507
3508
3509 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3510 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3511 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3512 if (!TextUtils.isEmpty(name)) {
3513 configuration.putString("muc#roomconfig_roomname", name);
3514 }
3515 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3516 @Override
3517 public void onPushSucceeded() {
3518 saveConversationAsBookmark(conversation, name);
3519 callback.success(conversation);
3520 }
3521
3522 @Override
3523 public void onPushFailed() {
3524 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3525 callback.error(R.string.unable_to_set_channel_configuration, conversation);
3526 } else {
3527 callback.error(R.string.joined_an_existing_channel, conversation);
3528 }
3529 }
3530 });
3531 });
3532 }
3533
3534 public boolean createAdhocConference(final Account account,
3535 final String name,
3536 final Iterable<Jid> jids,
3537 final UiCallback<Conversation> callback) {
3538 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3539 if (account.getStatus() == Account.State.ONLINE) {
3540 try {
3541 String server = findConferenceServer(account);
3542 if (server == null) {
3543 if (callback != null) {
3544 callback.error(R.string.no_conference_server_found, null);
3545 }
3546 return false;
3547 }
3548 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
3549 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3550 joinMuc(conversation, new OnConferenceJoined() {
3551 @Override
3552 public void onConferenceJoined(final Conversation conversation) {
3553 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3554 if (!TextUtils.isEmpty(name)) {
3555 configuration.putString("muc#roomconfig_roomname", name);
3556 }
3557 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3558 @Override
3559 public void onPushSucceeded() {
3560 for (Jid invite : jids) {
3561 invite(conversation, invite);
3562 }
3563 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3564 Jid other = account.getJid().withResource(resource);
3565 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3566 directInvite(conversation, other);
3567 }
3568 saveConversationAsBookmark(conversation, name);
3569 if (callback != null) {
3570 callback.success(conversation);
3571 }
3572 }
3573
3574 @Override
3575 public void onPushFailed() {
3576 archiveConversation(conversation);
3577 if (callback != null) {
3578 callback.error(R.string.conference_creation_failed, conversation);
3579 }
3580 }
3581 });
3582 }
3583 });
3584 return true;
3585 } catch (IllegalArgumentException e) {
3586 if (callback != null) {
3587 callback.error(R.string.conference_creation_failed, null);
3588 }
3589 return false;
3590 }
3591 } else {
3592 if (callback != null) {
3593 callback.error(R.string.not_connected_try_again, null);
3594 }
3595 return false;
3596 }
3597 }
3598
3599 public void fetchConferenceConfiguration(final Conversation conversation) {
3600 fetchConferenceConfiguration(conversation, null);
3601 }
3602
3603 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3604 IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3605 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3606 @Override
3607 public void onIqPacketReceived(Account account, IqPacket packet) {
3608 if (packet.getType() == IqPacket.TYPE.RESULT) {
3609 final MucOptions mucOptions = conversation.getMucOptions();
3610 final Bookmark bookmark = conversation.getBookmark();
3611 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3612
3613 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3614 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3615 updateConversation(conversation);
3616 }
3617
3618 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3619 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3620 createBookmark(account, bookmark);
3621 }
3622 }
3623
3624
3625 if (callback != null) {
3626 callback.onConferenceConfigurationFetched(conversation);
3627 }
3628
3629
3630 updateConversationUi();
3631 } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3632 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3633 } else {
3634 if (callback != null) {
3635 callback.onFetchFailed(conversation, packet.getErrorCondition());
3636 }
3637 }
3638 }
3639 });
3640 }
3641
3642 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3643 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3644 }
3645
3646 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3647 Log.d(Config.LOGTAG, "pushing node configuration");
3648 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3649 @Override
3650 public void onIqPacketReceived(Account account, IqPacket packet) {
3651 if (packet.getType() == IqPacket.TYPE.RESULT) {
3652 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3653 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3654 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3655 if (x != null) {
3656 Data data = Data.parse(x);
3657 data.submit(options);
3658 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3659 @Override
3660 public void onIqPacketReceived(Account account, IqPacket packet) {
3661 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3662 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3663 callback.onPushSucceeded();
3664 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3665 callback.onPushFailed();
3666 }
3667 }
3668 });
3669 } else if (callback != null) {
3670 callback.onPushFailed();
3671 }
3672 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3673 callback.onPushFailed();
3674 }
3675 }
3676 });
3677 }
3678
3679 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3680 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3681 conversation.setAttribute("accept_non_anonymous", true);
3682 updateConversation(conversation);
3683 }
3684 if (options.containsKey("muc#roomconfig_moderatedroom")) {
3685 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3686 options.putString("members_by_default", moderated ? "0" : "1");
3687 }
3688 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3689 request.setTo(conversation.getJid().asBareJid());
3690 request.query("http://jabber.org/protocol/muc#owner");
3691 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3692 @Override
3693 public void onIqPacketReceived(Account account, IqPacket packet) {
3694 if (packet.getType() == IqPacket.TYPE.RESULT) {
3695 final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3696 data.submit(options);
3697 final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3698 set.setTo(conversation.getJid().asBareJid());
3699 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3700 sendIqPacket(account, set, new OnIqPacketReceived() {
3701 @Override
3702 public void onIqPacketReceived(Account account, IqPacket packet) {
3703 if (callback != null) {
3704 if (packet.getType() == IqPacket.TYPE.RESULT) {
3705 callback.onPushSucceeded();
3706 } else {
3707 callback.onPushFailed();
3708 }
3709 }
3710 }
3711 });
3712 } else {
3713 if (callback != null) {
3714 callback.onPushFailed();
3715 }
3716 }
3717 }
3718 });
3719 }
3720
3721 public void pushSubjectToConference(final Conversation conference, final String subject) {
3722 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3723 this.sendMessagePacket(conference.getAccount(), packet);
3724 }
3725
3726 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3727 final Jid jid = user.asBareJid();
3728 final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3729 sendIqPacket(conference.getAccount(), request, (account, response) -> {
3730 if (response.getType() == IqPacket.TYPE.RESULT) {
3731 conference.getMucOptions().changeAffiliation(jid, affiliation);
3732 getAvatarService().clear(conference);
3733 if (callback != null) {
3734 callback.onAffiliationChangedSuccessful(jid);
3735 } else {
3736 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3737 }
3738 } else if (callback != null) {
3739 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3740 } else {
3741 Log.d(Config.LOGTAG, "unable to change affiliation");
3742 }
3743 });
3744 }
3745
3746 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3747 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3748 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3749 if (packet.getType() != IqPacket.TYPE.RESULT) {
3750 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3751 }
3752 });
3753 }
3754
3755 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3756 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3757 request.setTo(conversation.getJid().asBareJid());
3758 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3759 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3760 @Override
3761 public void onIqPacketReceived(Account account, IqPacket packet) {
3762 if (packet.getType() == IqPacket.TYPE.RESULT) {
3763 if (callback != null) {
3764 callback.onRoomDestroySucceeded();
3765 }
3766 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3767 if (callback != null) {
3768 callback.onRoomDestroyFailed();
3769 }
3770 }
3771 }
3772 });
3773 }
3774
3775 private void disconnect(final Account account, boolean force) {
3776 final XmppConnection connection = account.getXmppConnection();
3777 if (connection == null) {
3778 return;
3779 }
3780 if (!force) {
3781 final List<Conversation> conversations = getConversations();
3782 for (Conversation conversation : conversations) {
3783 if (conversation.getAccount() == account) {
3784 if (conversation.getMode() == Conversation.MODE_MULTI) {
3785 leaveMuc(conversation, true);
3786 }
3787 }
3788 }
3789 sendOfflinePresence(account);
3790 }
3791 connection.disconnect(force);
3792 }
3793
3794 @Override
3795 public IBinder onBind(Intent intent) {
3796 return mBinder;
3797 }
3798
3799 public void updateMessage(Message message) {
3800 updateMessage(message, true);
3801 }
3802
3803 public void updateMessage(Message message, boolean includeBody) {
3804 databaseBackend.updateMessage(message, includeBody);
3805 updateConversationUi();
3806 }
3807
3808 public void createMessageAsync(final Message message) {
3809 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3810 }
3811
3812 public void updateMessage(Message message, String uuid) {
3813 if (!databaseBackend.updateMessage(message, uuid)) {
3814 Log.e(Config.LOGTAG, "error updated message in DB after edit");
3815 }
3816 updateConversationUi();
3817 }
3818
3819 protected void syncDirtyContacts(Account account) {
3820 for (Contact contact : account.getRoster().getContacts()) {
3821 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3822 pushContactToServer(contact);
3823 }
3824 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3825 deleteContactOnServer(contact);
3826 }
3827 }
3828 }
3829
3830 public void createContact(final Contact contact, final boolean autoGrant) {
3831 createContact(contact, autoGrant, null);
3832 }
3833
3834 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3835 if (autoGrant) {
3836 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3837 contact.setOption(Contact.Options.ASKING);
3838 }
3839 pushContactToServer(contact, preAuth);
3840 }
3841
3842 public void pushContactToServer(final Contact contact) {
3843 pushContactToServer(contact, null);
3844 }
3845
3846 private void pushContactToServer(final Contact contact, final String preAuth) {
3847 contact.resetOption(Contact.Options.DIRTY_DELETE);
3848 contact.setOption(Contact.Options.DIRTY_PUSH);
3849 final Account account = contact.getAccount();
3850 if (account.getStatus() == Account.State.ONLINE) {
3851 final boolean ask = contact.getOption(Contact.Options.ASKING);
3852 final boolean sendUpdates = contact
3853 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3854 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3855 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3856 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3857 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3858 if (sendUpdates) {
3859 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3860 }
3861 if (ask) {
3862 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3863 }
3864 } else {
3865 syncRoster(contact.getAccount());
3866 }
3867 }
3868
3869 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3870 new Thread(() -> {
3871 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3872 final int size = Config.AVATAR_SIZE;
3873 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3874 if (avatar != null) {
3875 if (!getFileBackend().save(avatar)) {
3876 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3877 return;
3878 }
3879 avatar.owner = conversation.getJid().asBareJid();
3880 publishMucAvatar(conversation, avatar, callback);
3881 } else {
3882 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3883 }
3884 }).start();
3885 }
3886
3887 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3888 new Thread(() -> {
3889 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3890 final int size = Config.AVATAR_SIZE;
3891 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3892 if (avatar != null) {
3893 if (!getFileBackend().save(avatar)) {
3894 Log.d(Config.LOGTAG, "unable to save vcard");
3895 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3896 return;
3897 }
3898 publishAvatar(account, avatar, callback);
3899 } else {
3900 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3901 }
3902 }).start();
3903
3904 }
3905
3906 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3907 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3908 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3909 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3910 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3911 Element vcard = response.findChild("vCard", "vcard-temp");
3912 if (vcard == null) {
3913 vcard = new Element("vCard", "vcard-temp");
3914 }
3915 Element photo = vcard.findChild("PHOTO");
3916 if (photo == null) {
3917 photo = vcard.addChild("PHOTO");
3918 }
3919 photo.clearChildren();
3920 photo.addChild("TYPE").setContent(avatar.type);
3921 photo.addChild("BINVAL").setContent(avatar.image);
3922 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3923 publication.setTo(conversation.getJid().asBareJid());
3924 publication.addChild(vcard);
3925 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3926 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3927 callback.onAvatarPublicationSucceeded();
3928 } else {
3929 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3930 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3931 }
3932 });
3933 } else {
3934 Log.d(Config.LOGTAG, "failed to request vcard " + response);
3935 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3936 }
3937 });
3938 }
3939
3940 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3941 final Bundle options;
3942 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3943 options = PublishOptions.openAccess();
3944 } else {
3945 options = null;
3946 }
3947 publishAvatar(account, avatar, options, true, callback);
3948 }
3949
3950 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3951 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3952 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3953 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3954
3955 @Override
3956 public void onIqPacketReceived(Account account, IqPacket result) {
3957 if (result.getType() == IqPacket.TYPE.RESULT) {
3958 publishAvatarMetadata(account, avatar, options, true, callback);
3959 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3960 pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
3961 @Override
3962 public void onPushSucceeded() {
3963 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3964 publishAvatar(account, avatar, options, false, callback);
3965 }
3966
3967 @Override
3968 public void onPushFailed() {
3969 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3970 publishAvatar(account, avatar, null, false, callback);
3971 }
3972 });
3973 } else {
3974 Element error = result.findChild("error");
3975 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3976 if (callback != null) {
3977 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3978 }
3979 }
3980 }
3981 });
3982 }
3983
3984 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3985 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3986 sendIqPacket(account, packet, new OnIqPacketReceived() {
3987 @Override
3988 public void onIqPacketReceived(Account account, IqPacket result) {
3989 if (result.getType() == IqPacket.TYPE.RESULT) {
3990 if (account.setAvatar(avatar.getFilename())) {
3991 getAvatarService().clear(account);
3992 databaseBackend.updateAccount(account);
3993 notifyAccountAvatarHasChanged(account);
3994 }
3995 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3996 if (callback != null) {
3997 callback.onAvatarPublicationSucceeded();
3998 }
3999 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4000 pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
4001 @Override
4002 public void onPushSucceeded() {
4003 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
4004 publishAvatarMetadata(account, avatar, options, false, callback);
4005 }
4006
4007 @Override
4008 public void onPushFailed() {
4009 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
4010 publishAvatarMetadata(account, avatar, null, false, callback);
4011 }
4012 });
4013 } else {
4014 if (callback != null) {
4015 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4016 }
4017 }
4018 }
4019 });
4020 }
4021
4022 public void republishAvatarIfNeeded(Account account) {
4023 if (account.getAxolotlService().isPepBroken()) {
4024 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
4025 return;
4026 }
4027 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4028 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4029
4030 private Avatar parseAvatar(IqPacket packet) {
4031 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4032 if (pubsub != null) {
4033 Element items = pubsub.findChild("items");
4034 if (items != null) {
4035 return Avatar.parseMetadata(items);
4036 }
4037 }
4038 return null;
4039 }
4040
4041 private boolean errorIsItemNotFound(IqPacket packet) {
4042 Element error = packet.findChild("error");
4043 return packet.getType() == IqPacket.TYPE.ERROR
4044 && error != null
4045 && error.hasChild("item-not-found");
4046 }
4047
4048 @Override
4049 public void onIqPacketReceived(Account account, IqPacket packet) {
4050 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
4051 Avatar serverAvatar = parseAvatar(packet);
4052 if (serverAvatar == null && account.getAvatar() != null) {
4053 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4054 if (avatar != null) {
4055 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
4056 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
4057 } else {
4058 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
4059 }
4060 }
4061 }
4062 }
4063 });
4064 }
4065
4066 public void fetchAvatar(Account account, Avatar avatar) {
4067 fetchAvatar(account, avatar, null);
4068 }
4069
4070 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4071 final String KEY = generateFetchKey(account, avatar);
4072 synchronized (this.mInProgressAvatarFetches) {
4073 if (mInProgressAvatarFetches.add(KEY)) {
4074 switch (avatar.origin) {
4075 case PEP:
4076 this.mInProgressAvatarFetches.add(KEY);
4077 fetchAvatarPep(account, avatar, callback);
4078 break;
4079 case VCARD:
4080 this.mInProgressAvatarFetches.add(KEY);
4081 fetchAvatarVcard(account, avatar, callback);
4082 break;
4083 }
4084 } else if (avatar.origin == Avatar.Origin.PEP) {
4085 mOmittedPepAvatarFetches.add(KEY);
4086 } else {
4087 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
4088 }
4089 }
4090 }
4091
4092 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4093 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
4094 sendIqPacket(account, packet, (a, result) -> {
4095 synchronized (mInProgressAvatarFetches) {
4096 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
4097 }
4098 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
4099 if (result.getType() == IqPacket.TYPE.RESULT) {
4100 avatar.image = mIqParser.avatarData(result);
4101 if (avatar.image != null) {
4102 if (getFileBackend().save(avatar)) {
4103 if (a.getJid().asBareJid().equals(avatar.owner)) {
4104 if (a.setAvatar(avatar.getFilename())) {
4105 databaseBackend.updateAccount(a);
4106 }
4107 getAvatarService().clear(a);
4108 updateConversationUi();
4109 updateAccountUi();
4110 } else {
4111 final Contact contact = a.getRoster().getContact(avatar.owner);
4112 contact.setAvatar(avatar);
4113 syncRoster(account);
4114 getAvatarService().clear(contact);
4115 updateConversationUi();
4116 updateRosterUi();
4117 }
4118 if (callback != null) {
4119 callback.success(avatar);
4120 }
4121 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
4122 return;
4123 }
4124 } else {
4125
4126 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4127 }
4128 } else {
4129 Element error = result.findChild("error");
4130 if (error == null) {
4131 Log.d(Config.LOGTAG, ERROR + "(server error)");
4132 } else {
4133 Log.d(Config.LOGTAG, ERROR + error.toString());
4134 }
4135 }
4136 if (callback != null) {
4137 callback.error(0, null);
4138 }
4139
4140 });
4141 }
4142
4143 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4144 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4145 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4146 @Override
4147 public void onIqPacketReceived(Account account, IqPacket packet) {
4148 final boolean previouslyOmittedPepFetch;
4149 synchronized (mInProgressAvatarFetches) {
4150 final String KEY = generateFetchKey(account, avatar);
4151 mInProgressAvatarFetches.remove(KEY);
4152 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4153 }
4154 if (packet.getType() == IqPacket.TYPE.RESULT) {
4155 Element vCard = packet.findChild("vCard", "vcard-temp");
4156 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4157 String image = photo != null ? photo.findChildContent("BINVAL") : null;
4158 if (image != null) {
4159 avatar.image = image;
4160 if (getFileBackend().save(avatar)) {
4161 Log.d(Config.LOGTAG, account.getJid().asBareJid()
4162 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4163 if (avatar.owner.isBareJid()) {
4164 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4165 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4166 account.setAvatar(avatar.getFilename());
4167 databaseBackend.updateAccount(account);
4168 getAvatarService().clear(account);
4169 updateAccountUi();
4170 } else {
4171 final Contact contact = account.getRoster().getContact(avatar.owner);
4172 contact.setAvatar(avatar, previouslyOmittedPepFetch);
4173 syncRoster(account);
4174 getAvatarService().clear(contact);
4175 updateRosterUi();
4176 }
4177 updateConversationUi();
4178 } else {
4179 Conversation conversation = find(account, avatar.owner.asBareJid());
4180 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4181 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4182 if (user != null) {
4183 if (user.setAvatar(avatar)) {
4184 getAvatarService().clear(user);
4185 updateConversationUi();
4186 updateMucRosterUi();
4187 }
4188 if (user.getRealJid() != null) {
4189 Contact contact = account.getRoster().getContact(user.getRealJid());
4190 contact.setAvatar(avatar);
4191 syncRoster(account);
4192 getAvatarService().clear(contact);
4193 updateRosterUi();
4194 }
4195 }
4196 }
4197 }
4198 }
4199 }
4200 }
4201 }
4202 });
4203 }
4204
4205 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
4206 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4207 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4208
4209 @Override
4210 public void onIqPacketReceived(Account account, IqPacket packet) {
4211 if (packet.getType() == IqPacket.TYPE.RESULT) {
4212 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4213 if (pubsub != null) {
4214 Element items = pubsub.findChild("items");
4215 if (items != null) {
4216 Avatar avatar = Avatar.parseMetadata(items);
4217 if (avatar != null) {
4218 avatar.owner = account.getJid().asBareJid();
4219 if (fileBackend.isAvatarCached(avatar)) {
4220 if (account.setAvatar(avatar.getFilename())) {
4221 databaseBackend.updateAccount(account);
4222 }
4223 getAvatarService().clear(account);
4224 callback.success(avatar);
4225 } else {
4226 fetchAvatarPep(account, avatar, callback);
4227 }
4228 return;
4229 }
4230 }
4231 }
4232 }
4233 callback.error(0, null);
4234 }
4235 });
4236 }
4237
4238 public void notifyAccountAvatarHasChanged(final Account account) {
4239 final XmppConnection connection = account.getXmppConnection();
4240 if (connection != null && connection.getFeatures().bookmarksConversion()) {
4241 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4242 for (Conversation conversation : conversations) {
4243 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4244 final MucOptions mucOptions = conversation.getMucOptions();
4245 if (mucOptions.online()) {
4246 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
4247 packet.setTo(mucOptions.getSelf().getFullJid());
4248 connection.sendPresencePacket(packet);
4249 }
4250 }
4251 }
4252 }
4253 }
4254
4255 public void deleteContactOnServer(Contact contact) {
4256 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4257 contact.resetOption(Contact.Options.DIRTY_PUSH);
4258 contact.setOption(Contact.Options.DIRTY_DELETE);
4259 Account account = contact.getAccount();
4260 if (account.getStatus() == Account.State.ONLINE) {
4261 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4262 Element item = iq.query(Namespace.ROSTER).addChild("item");
4263 item.setAttribute("jid", contact.getJid());
4264 item.setAttribute("subscription", "remove");
4265 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4266 }
4267 }
4268
4269 public void updateConversation(final Conversation conversation) {
4270 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4271 }
4272
4273 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4274 synchronized (account) {
4275 final XmppConnection existingConnection = account.getXmppConnection();
4276 final XmppConnection connection;
4277 if (existingConnection != null) {
4278 connection = existingConnection;
4279 } else if (account.isConnectionEnabled()) {
4280 connection = createConnection(account);
4281 account.setXmppConnection(connection);
4282 } else {
4283 return;
4284 }
4285 final boolean hasInternet = hasInternetConnection();
4286 if (account.isConnectionEnabled() && hasInternet) {
4287 if (!force) {
4288 disconnect(account, false);
4289 }
4290 Thread thread = new Thread(connection);
4291 connection.setInteractive(interactive);
4292 connection.prepareNewConnection();
4293 connection.interrupt();
4294 thread.start();
4295 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4296 } else {
4297 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4298 account.getRoster().clearPresences();
4299 connection.resetEverything();
4300 final AxolotlService axolotlService = account.getAxolotlService();
4301 if (axolotlService != null) {
4302 axolotlService.resetBrokenness();
4303 }
4304 if (!hasInternet) {
4305 account.setStatus(Account.State.NO_INTERNET);
4306 }
4307 }
4308 }
4309 }
4310
4311 public void reconnectAccountInBackground(final Account account) {
4312 new Thread(() -> reconnectAccount(account, false, true)).start();
4313 }
4314
4315 public void invite(final Conversation conversation, final Jid contact) {
4316 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4317 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4318 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4319 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4320 }
4321 final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4322 sendMessagePacket(conversation.getAccount(), packet);
4323 }
4324
4325 public void directInvite(Conversation conversation, Jid jid) {
4326 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4327 sendMessagePacket(conversation.getAccount(), packet);
4328 }
4329
4330 public void resetSendingToWaiting(Account account) {
4331 for (Conversation conversation : getConversations()) {
4332 if (conversation.getAccount() == account) {
4333 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4334 }
4335 }
4336 }
4337
4338 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4339 return markMessage(account, recipient, uuid, status, null);
4340 }
4341
4342 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4343 if (uuid == null) {
4344 return null;
4345 }
4346 for (Conversation conversation : getConversations()) {
4347 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4348 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4349 if (message != null) {
4350 markMessage(message, status, errorMessage);
4351 }
4352 return message;
4353 }
4354 }
4355 return null;
4356 }
4357
4358 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4359 return markMessage(conversation, uuid, status, serverMessageId, null);
4360 }
4361
4362 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4363 if (uuid == null) {
4364 return false;
4365 } else {
4366 final Message message = conversation.findSentMessageWithUuid(uuid);
4367 if (message != null) {
4368 if (message.getServerMsgId() == null) {
4369 message.setServerMsgId(serverMessageId);
4370 }
4371 if (message.getEncryption() == Message.ENCRYPTION_NONE
4372 && message.isTypeText()
4373 && isBodyModified(message, body)) {
4374 message.setBody(body.content);
4375 if (body.count > 1) {
4376 message.setBodyLanguage(body.language);
4377 }
4378 markMessage(message, status, null, true);
4379 } else {
4380 markMessage(message, status);
4381 }
4382 return true;
4383 } else {
4384 return false;
4385 }
4386 }
4387 }
4388
4389 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4390 if (body == null || body.content == null) {
4391 return false;
4392 }
4393 return !body.content.equals(message.getBody());
4394 }
4395
4396 public void markMessage(Message message, int status) {
4397 markMessage(message, status, null);
4398 }
4399
4400
4401 public void markMessage(final Message message, final int status, final String errorMessage) {
4402 markMessage(message, status, errorMessage, false);
4403 }
4404
4405 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4406 final int oldStatus = message.getStatus();
4407 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4408 return;
4409 }
4410 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4411 return;
4412 }
4413 message.setErrorMessage(errorMessage);
4414 message.setStatus(status);
4415 databaseBackend.updateMessage(message, includeBody);
4416 updateConversationUi();
4417 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4418 mNotificationService.pushFailedDelivery(message);
4419 }
4420 }
4421
4422 private SharedPreferences getPreferences() {
4423 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4424 }
4425
4426 public long getAutomaticMessageDeletionDate() {
4427 final long timeout = getLongPreference(AppSettings.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4428 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4429 }
4430
4431 public long getLongPreference(String name, @IntegerRes int res) {
4432 long defaultValue = getResources().getInteger(res);
4433 try {
4434 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4435 } catch (NumberFormatException e) {
4436 return defaultValue;
4437 }
4438 }
4439
4440 public boolean getBooleanPreference(String name, @BoolRes int res) {
4441 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4442 }
4443
4444 public boolean confirmMessages() {
4445 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4446 }
4447
4448 public boolean allowMessageCorrection() {
4449 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4450 }
4451
4452 public boolean sendChatStates() {
4453 return getBooleanPreference("chat_states", R.bool.chat_states);
4454 }
4455
4456 private boolean synchronizeWithBookmarks() {
4457 return getBooleanPreference("autojoin", R.bool.autojoin);
4458 }
4459
4460 public boolean useTorToConnect() {
4461 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
4462 }
4463
4464 public boolean showExtendedConnectionOptions() {
4465 return QuickConversationsService.isConversations() && getBooleanPreference(AppSettings.SHOW_CONNECTION_OPTIONS, R.bool.show_connection_options);
4466 }
4467
4468 public boolean broadcastLastActivity() {
4469 return getBooleanPreference(AppSettings.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4470 }
4471
4472 public int unreadCount() {
4473 int count = 0;
4474 for (Conversation conversation : getConversations()) {
4475 count += conversation.unreadCount();
4476 }
4477 return count;
4478 }
4479
4480
4481 private <T> List<T> threadSafeList(Set<T> set) {
4482 synchronized (LISTENER_LOCK) {
4483 return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
4484 }
4485 }
4486
4487 public void showErrorToastInUi(int resId) {
4488 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4489 listener.onShowErrorToast(resId);
4490 }
4491 }
4492
4493 public void updateConversationUi() {
4494 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4495 listener.onConversationUpdate();
4496 }
4497 }
4498
4499 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4500 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4501 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4502 }
4503 }
4504
4505 public void notifyJingleRtpConnectionUpdate(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices) {
4506 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4507 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4508 }
4509 }
4510
4511 public void updateAccountUi() {
4512 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4513 listener.onAccountUpdate();
4514 }
4515 }
4516
4517 public void updateRosterUi() {
4518 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4519 listener.onRosterUpdate();
4520 }
4521 }
4522
4523 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4524 if (mOnCaptchaRequested.size() > 0) {
4525 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4526 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4527 (int) (captcha.getHeight() * metrics.scaledDensity), false);
4528 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4529 listener.onCaptchaRequested(account, id, data, scaled);
4530 }
4531 return true;
4532 }
4533 return false;
4534 }
4535
4536 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4537 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4538 listener.OnUpdateBlocklist(status);
4539 }
4540 }
4541
4542 public void updateMucRosterUi() {
4543 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4544 listener.onMucRosterUpdate();
4545 }
4546 }
4547
4548 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4549 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4550 listener.onKeyStatusUpdated(report);
4551 }
4552 }
4553
4554 public Account findAccountByJid(final Jid jid) {
4555 for (final Account account : this.accounts) {
4556 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4557 return account;
4558 }
4559 }
4560 return null;
4561 }
4562
4563 public Account findAccountByUuid(final String uuid) {
4564 for (Account account : this.accounts) {
4565 if (account.getUuid().equals(uuid)) {
4566 return account;
4567 }
4568 }
4569 return null;
4570 }
4571
4572 public Conversation findConversationByUuid(String uuid) {
4573 for (Conversation conversation : getConversations()) {
4574 if (conversation.getUuid().equals(uuid)) {
4575 return conversation;
4576 }
4577 }
4578 return null;
4579 }
4580
4581 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4582 List<Conversation> findings = new ArrayList<>();
4583 for (Conversation c : getConversations()) {
4584 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4585 findings.add(c);
4586 }
4587 }
4588 return findings.size() == 1 ? findings.get(0) : null;
4589 }
4590
4591 public boolean markRead(final Conversation conversation, boolean dismiss) {
4592 return markRead(conversation, null, dismiss).size() > 0;
4593 }
4594
4595 public void markRead(final Conversation conversation) {
4596 markRead(conversation, null, true);
4597 }
4598
4599 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4600 if (dismiss) {
4601 mNotificationService.clear(conversation);
4602 }
4603 final List<Message> readMessages = conversation.markRead(upToUuid);
4604 if (readMessages.size() > 0) {
4605 Runnable runnable = () -> {
4606 for (Message message : readMessages) {
4607 databaseBackend.updateMessage(message, false);
4608 }
4609 };
4610 mDatabaseWriterExecutor.execute(runnable);
4611 updateConversationUi();
4612 updateUnreadCountBadge();
4613 return readMessages;
4614 } else {
4615 return readMessages;
4616 }
4617 }
4618
4619 public synchronized void updateUnreadCountBadge() {
4620 int count = unreadCount();
4621 if (unreadCount != count) {
4622 Log.d(Config.LOGTAG, "update unread count to " + count);
4623 if (count > 0) {
4624 ShortcutBadger.applyCount(getApplicationContext(), count);
4625 } else {
4626 ShortcutBadger.removeCount(getApplicationContext());
4627 }
4628 unreadCount = count;
4629 }
4630 }
4631
4632 public void sendReadMarker(final Conversation conversation, final String upToUuid) {
4633 final boolean isPrivateAndNonAnonymousMuc =
4634 conversation.getMode() == Conversation.MODE_MULTI
4635 && conversation.isPrivateAndNonAnonymous();
4636 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4637 if (readMessages.isEmpty()) {
4638 return;
4639 }
4640 final var account = conversation.getAccount();
4641 final var connection = account.getXmppConnection();
4642 updateConversationUi();
4643 final var last =
4644 Iterables.getLast(
4645 Collections2.filter(
4646 readMessages,
4647 m ->
4648 !m.isPrivateMessage()
4649 && m.getStatus() == Message.STATUS_RECEIVED),
4650 null);
4651 if (last == null) {
4652 return;
4653 }
4654
4655 final boolean sendDisplayedMarker =
4656 confirmMessages()
4657 && (last.trusted() || isPrivateAndNonAnonymousMuc)
4658 && last.getRemoteMsgId() != null
4659 && (last.markable || isPrivateAndNonAnonymousMuc);
4660 final boolean serverAssist =
4661 connection != null && connection.getFeatures().mdsServerAssist();
4662
4663 final String stanzaId = last.getServerMsgId();
4664
4665 if (sendDisplayedMarker && serverAssist) {
4666 final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
4667 final MessagePacket packet = mMessageGenerator.confirm(last);
4668 packet.addChild(mdsDisplayed);
4669 if (!last.isPrivateMessage()) {
4670 packet.setTo(packet.getTo().asBareJid());
4671 }
4672 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": server assisted "+packet);
4673 this.sendMessagePacket(account, packet);
4674 } else {
4675 publishMds(last);
4676 // read markers will be sent after MDS to flush the CSI stanza queue
4677 if (sendDisplayedMarker) {
4678 Log.d(
4679 Config.LOGTAG,
4680 conversation.getAccount().getJid().asBareJid()
4681 + ": sending displayed marker to "
4682 + last.getCounterpart().toString());
4683 final MessagePacket packet = mMessageGenerator.confirm(last);
4684 this.sendMessagePacket(account, packet);
4685 }
4686 }
4687 }
4688
4689 private void publishMds(@Nullable final Message message) {
4690 final String stanzaId = message == null ? null : message.getServerMsgId();
4691 if (Strings.isNullOrEmpty(stanzaId)) {
4692 return;
4693 }
4694 final Conversation conversation;
4695 final var conversational = message.getConversation();
4696 if (conversational instanceof Conversation c) {
4697 conversation = c;
4698 } else {
4699 return;
4700 }
4701 final var account = conversation.getAccount();
4702 final var connection = account.getXmppConnection();
4703 if (connection == null || !connection.getFeatures().mds()) {
4704 return;
4705 }
4706 final Jid itemId;
4707 if (message.isPrivateMessage()) {
4708 itemId = message.getCounterpart();
4709 } else {
4710 itemId = conversation.getJid().asBareJid();
4711 }
4712 Log.d(Config.LOGTAG,"publishing mds for "+itemId+"/"+stanzaId);
4713 publishMds(account, itemId, stanzaId, conversation);
4714 }
4715
4716 private void publishMds(
4717 final Account account, final Jid itemId, final String stanzaId, final Conversation conversation) {
4718 final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
4719 pushNodeAndEnforcePublishOptions(
4720 account,
4721 Namespace.MDS_DISPLAYED,
4722 item,
4723 itemId.toEscapedString(),
4724 PublishOptions.persistentWhitelistAccessMaxItems());
4725 }
4726
4727 public MemorizingTrustManager getMemorizingTrustManager() {
4728 return this.mMemorizingTrustManager;
4729 }
4730
4731 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4732 this.mMemorizingTrustManager = trustManager;
4733 }
4734
4735 public void updateMemorizingTrustmanager() {
4736 final MemorizingTrustManager tm;
4737 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4738 if (dontTrustSystemCAs) {
4739 tm = new MemorizingTrustManager(getApplicationContext(), null);
4740 } else {
4741 tm = new MemorizingTrustManager(getApplicationContext());
4742 }
4743 setMemorizingTrustManager(tm);
4744 }
4745
4746 public LruCache<String, Bitmap> getBitmapCache() {
4747 return this.mBitmapCache;
4748 }
4749
4750 public Collection<String> getKnownHosts() {
4751 final Set<String> hosts = new HashSet<>();
4752 for (final Account account : getAccounts()) {
4753 hosts.add(account.getServer());
4754 for (final Contact contact : account.getRoster().getContacts()) {
4755 if (contact.showInRoster()) {
4756 final String server = contact.getServer();
4757 if (server != null) {
4758 hosts.add(server);
4759 }
4760 }
4761 }
4762 }
4763 if (Config.QUICKSY_DOMAIN != null) {
4764 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4765 }
4766 if (Config.MAGIC_CREATE_DOMAIN != null) {
4767 hosts.add(Config.MAGIC_CREATE_DOMAIN);
4768 }
4769 return hosts;
4770 }
4771
4772 public Collection<String> getKnownConferenceHosts() {
4773 final Set<String> mucServers = new HashSet<>();
4774 for (final Account account : accounts) {
4775 if (account.getXmppConnection() != null) {
4776 mucServers.addAll(account.getXmppConnection().getMucServers());
4777 for (final Bookmark bookmark : account.getBookmarks()) {
4778 final Jid jid = bookmark.getJid();
4779 final String s = jid == null ? null : jid.getDomain().toEscapedString();
4780 if (s != null) {
4781 mucServers.add(s);
4782 }
4783 }
4784 }
4785 }
4786 return mucServers;
4787 }
4788
4789 public void sendMessagePacket(Account account, MessagePacket packet) {
4790 final XmppConnection connection = account.getXmppConnection();
4791 if (connection != null) {
4792 connection.sendMessagePacket(packet);
4793 }
4794 }
4795
4796 public void sendPresencePacket(Account account, PresencePacket packet) {
4797 XmppConnection connection = account.getXmppConnection();
4798 if (connection != null) {
4799 connection.sendPresencePacket(packet);
4800 }
4801 }
4802
4803 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4804 final XmppConnection connection = account.getXmppConnection();
4805 if (connection != null) {
4806 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4807 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4808 }
4809 }
4810
4811 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4812 final XmppConnection connection = account.getXmppConnection();
4813 if (connection != null) {
4814 connection.sendIqPacket(packet, callback);
4815 } else if (callback != null) {
4816 callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4817 }
4818 }
4819
4820 public void sendPresence(final Account account) {
4821 sendPresence(account, checkListeners() && broadcastLastActivity());
4822 }
4823
4824 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4825 final Presence.Status status;
4826 if (manuallyChangePresence()) {
4827 status = account.getPresenceStatus();
4828 } else {
4829 status = getTargetPresence();
4830 }
4831 final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4832 if (mLastActivity > 0 && includeIdleTimestamp) {
4833 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4834 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4835 }
4836 sendPresencePacket(account, packet);
4837 }
4838
4839 private void deactivateGracePeriod() {
4840 for (Account account : getAccounts()) {
4841 account.deactivateGracePeriod();
4842 }
4843 }
4844
4845 public void refreshAllPresences() {
4846 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4847 for (Account account : getAccounts()) {
4848 if (account.isConnectionEnabled()) {
4849 sendPresence(account, includeIdleTimestamp);
4850 }
4851 }
4852 }
4853
4854 private void refreshAllFcmTokens() {
4855 for (Account account : getAccounts()) {
4856 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4857 mPushManagementService.registerPushTokenOnServer(account);
4858 }
4859 }
4860 }
4861
4862
4863
4864 private void sendOfflinePresence(final Account account) {
4865 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4866 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4867 }
4868
4869 public MessageGenerator getMessageGenerator() {
4870 return this.mMessageGenerator;
4871 }
4872
4873 public PresenceGenerator getPresenceGenerator() {
4874 return this.mPresenceGenerator;
4875 }
4876
4877 public IqGenerator getIqGenerator() {
4878 return this.mIqGenerator;
4879 }
4880
4881 public IqParser getIqParser() {
4882 return this.mIqParser;
4883 }
4884
4885 public JingleConnectionManager getJingleConnectionManager() {
4886 return this.mJingleConnectionManager;
4887 }
4888
4889 private boolean hasJingleRtpConnection(final Account account) {
4890 return this.mJingleConnectionManager.hasJingleRtpConnection(account);
4891 }
4892
4893 public MessageArchiveService getMessageArchiveService() {
4894 return this.mMessageArchiveService;
4895 }
4896
4897 public QuickConversationsService getQuickConversationsService() {
4898 return this.mQuickConversationsService;
4899 }
4900
4901 public List<Contact> findContacts(Jid jid, String accountJid) {
4902 ArrayList<Contact> contacts = new ArrayList<>();
4903 for (Account account : getAccounts()) {
4904 if ((account.isEnabled() || accountJid != null)
4905 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4906 Contact contact = account.getRoster().getContactFromContactList(jid);
4907 if (contact != null) {
4908 contacts.add(contact);
4909 }
4910 }
4911 }
4912 return contacts;
4913 }
4914
4915 public Conversation findFirstMuc(Jid jid) {
4916 for (Conversation conversation : getConversations()) {
4917 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4918 return conversation;
4919 }
4920 }
4921 return null;
4922 }
4923
4924 public NotificationService getNotificationService() {
4925 return this.mNotificationService;
4926 }
4927
4928 public HttpConnectionManager getHttpConnectionManager() {
4929 return this.mHttpConnectionManager;
4930 }
4931
4932 public void resendFailedMessages(final Message message) {
4933 final Collection<Message> messages = new ArrayList<>();
4934 Message current = message;
4935 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4936 messages.add(current);
4937 if (current.mergeable(current.next())) {
4938 current = current.next();
4939 } else {
4940 break;
4941 }
4942 }
4943 for (final Message msg : messages) {
4944 msg.setTime(System.currentTimeMillis());
4945 markMessage(msg, Message.STATUS_WAITING);
4946 this.resendMessage(msg, false);
4947 }
4948 if (message.getConversation() instanceof Conversation) {
4949 ((Conversation) message.getConversation()).sort();
4950 }
4951 updateConversationUi();
4952 }
4953
4954 public void clearConversationHistory(final Conversation conversation) {
4955 final long clearDate;
4956 final String reference;
4957 if (conversation.countMessages() > 0) {
4958 Message latestMessage = conversation.getLatestMessage();
4959 clearDate = latestMessage.getTimeSent() + 1000;
4960 reference = latestMessage.getServerMsgId();
4961 } else {
4962 clearDate = System.currentTimeMillis();
4963 reference = null;
4964 }
4965 conversation.clearMessages();
4966 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4967 conversation.setLastClearHistory(clearDate, reference);
4968 Runnable runnable = () -> {
4969 databaseBackend.deleteMessagesInConversation(conversation);
4970 databaseBackend.updateConversation(conversation);
4971 };
4972 mDatabaseWriterExecutor.execute(runnable);
4973 }
4974
4975 public boolean sendBlockRequest(final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
4976 if (blockable != null && blockable.getBlockedJid() != null) {
4977 final Jid jid = blockable.getBlockedJid();
4978 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId), (a, response) -> {
4979 if (response.getType() == IqPacket.TYPE.RESULT) {
4980 a.getBlocklist().add(jid);
4981 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4982 }
4983 });
4984 if (blockable.getBlockedJid().isFullJid()) {
4985 return false;
4986 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4987 updateConversationUi();
4988 return true;
4989 } else {
4990 return false;
4991 }
4992 } else {
4993 return false;
4994 }
4995 }
4996
4997 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4998 boolean removed = false;
4999 synchronized (this.conversations) {
5000 boolean domainJid = blockedJid.getLocal() == null;
5001 for (Conversation conversation : this.conversations) {
5002 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
5003 || blockedJid.equals(conversation.getJid().asBareJid());
5004 if (conversation.getAccount() == account
5005 && conversation.getMode() == Conversation.MODE_SINGLE
5006 && jidMatches) {
5007 this.conversations.remove(conversation);
5008 markRead(conversation);
5009 conversation.setStatus(Conversation.STATUS_ARCHIVED);
5010 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
5011 updateConversation(conversation);
5012 removed = true;
5013 }
5014 }
5015 }
5016 return removed;
5017 }
5018
5019 public void sendUnblockRequest(final Blockable blockable) {
5020 if (blockable != null && blockable.getJid() != null) {
5021 final Jid jid = blockable.getBlockedJid();
5022 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
5023 @Override
5024 public void onIqPacketReceived(final Account account, final IqPacket packet) {
5025 if (packet.getType() == IqPacket.TYPE.RESULT) {
5026 account.getBlocklist().remove(jid);
5027 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
5028 }
5029 }
5030 });
5031 }
5032 }
5033
5034 public void publishDisplayName(Account account) {
5035 String displayName = account.getDisplayName();
5036 final IqPacket request;
5037 if (TextUtils.isEmpty(displayName)) {
5038 request = mIqGenerator.deleteNode(Namespace.NICK);
5039 } else {
5040 request = mIqGenerator.publishNick(displayName);
5041 }
5042 mAvatarService.clear(account);
5043 sendIqPacket(account, request, (account1, packet) -> {
5044 if (packet.getType() == IqPacket.TYPE.ERROR) {
5045 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet);
5046 }
5047 });
5048 }
5049
5050 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
5051 ServiceDiscoveryResult result = discoCache.get(key);
5052 if (result != null) {
5053 return result;
5054 } else {
5055 result = databaseBackend.findDiscoveryResult(key.first, key.second);
5056 if (result != null) {
5057 discoCache.put(key, result);
5058 }
5059 return result;
5060 }
5061 }
5062
5063 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
5064 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
5065 final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
5066 if (disco != null) {
5067 presence.setServiceDiscoveryResult(disco);
5068 final Contact contact = account.getRoster().getContact(jid);
5069 if (contact.refreshRtpCapability()) {
5070 syncRoster(account);
5071 }
5072 } else {
5073 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5074 request.setTo(jid);
5075 final String node = presence.getNode();
5076 final String ver = presence.getVer();
5077 final Element query = request.query(Namespace.DISCO_INFO);
5078 if (node != null && ver != null) {
5079 query.setAttribute("node", node + "#" + ver);
5080 }
5081 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
5082 sendIqPacket(account, request, (a, response) -> {
5083 if (response.getType() == IqPacket.TYPE.RESULT) {
5084 final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
5085 if (presence.getVer().equals(discoveryResult.getVer())) {
5086 databaseBackend.insertDiscoveryResult(discoveryResult);
5087 injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
5088 } else {
5089 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
5090 }
5091 } else {
5092 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
5093 }
5094 });
5095 }
5096 }
5097
5098 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
5099 boolean rosterNeedsSync = false;
5100 for (final Contact contact : roster.getContacts()) {
5101 boolean serviceDiscoverySet = false;
5102 for (final Presence presence : contact.getPresences().getPresences()) {
5103 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
5104 presence.setServiceDiscoveryResult(disco);
5105 serviceDiscoverySet = true;
5106 }
5107 }
5108 if (serviceDiscoverySet) {
5109 rosterNeedsSync |= contact.refreshRtpCapability();
5110 }
5111 }
5112 if (rosterNeedsSync) {
5113 syncRoster(roster.getAccount());
5114 }
5115 }
5116
5117 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
5118 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5119 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5120 request.addChild("prefs", version.namespace);
5121 sendIqPacket(account, request, (account1, packet) -> {
5122 Element prefs = packet.findChild("prefs", version.namespace);
5123 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
5124 callback.onPreferencesFetched(prefs);
5125 } else {
5126 callback.onPreferencesFetchFailed();
5127 }
5128 });
5129 }
5130
5131 public PushManagementService getPushManagementService() {
5132 return mPushManagementService;
5133 }
5134
5135 public void changeStatus(Account account, PresenceTemplate template, String signature) {
5136 if (!template.getStatusMessage().isEmpty()) {
5137 databaseBackend.insertPresenceTemplate(template);
5138 }
5139 account.setPgpSignature(signature);
5140 account.setPresenceStatus(template.getStatus());
5141 account.setPresenceStatusMessage(template.getStatusMessage());
5142 databaseBackend.updateAccount(account);
5143 sendPresence(account);
5144 }
5145
5146 public List<PresenceTemplate> getPresenceTemplates(Account account) {
5147 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5148 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5149 if (!templates.contains(template)) {
5150 templates.add(0, template);
5151 }
5152 }
5153 return templates;
5154 }
5155
5156 public void saveConversationAsBookmark(Conversation conversation, String name) {
5157 final Account account = conversation.getAccount();
5158 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5159 final String nick = conversation.getJid().getResource();
5160 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5161 bookmark.setNick(nick);
5162 }
5163 if (!TextUtils.isEmpty(name)) {
5164 bookmark.setBookmarkName(name);
5165 }
5166 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
5167 createBookmark(account, bookmark);
5168 bookmark.setConversation(conversation);
5169 }
5170
5171 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5172 boolean performedVerification = false;
5173 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5174 for (XmppUri.Fingerprint fp : fingerprints) {
5175 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5176 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5177 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5178 if (fingerprintStatus != null) {
5179 if (!fingerprintStatus.isVerified()) {
5180 performedVerification = true;
5181 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5182 }
5183 } else {
5184 axolotlService.preVerifyFingerprint(contact, fingerprint);
5185 }
5186 }
5187 }
5188 return performedVerification;
5189 }
5190
5191 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5192 final AxolotlService axolotlService = account.getAxolotlService();
5193 boolean verifiedSomething = false;
5194 for (XmppUri.Fingerprint fp : fingerprints) {
5195 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5196 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5197 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5198 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5199 if (fingerprintStatus != null) {
5200 if (!fingerprintStatus.isVerified()) {
5201 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5202 verifiedSomething = true;
5203 }
5204 } else {
5205 axolotlService.preVerifyFingerprint(account, fingerprint);
5206 verifiedSomething = true;
5207 }
5208 }
5209 }
5210 return verifiedSomething;
5211 }
5212
5213 public boolean blindTrustBeforeVerification() {
5214 return getBooleanPreference(AppSettings.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
5215 }
5216
5217 public ShortcutService getShortcutService() {
5218 return mShortcutService;
5219 }
5220
5221 public void pushMamPreferences(Account account, Element prefs) {
5222 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
5223 set.addChild(prefs);
5224 sendIqPacket(account, set, null);
5225 }
5226
5227 public void evictPreview(String uuid) {
5228 if (mBitmapCache.remove(uuid) != null) {
5229 Log.d(Config.LOGTAG, "deleted cached preview");
5230 }
5231 }
5232
5233 public interface OnMamPreferencesFetched {
5234 void onPreferencesFetched(Element prefs);
5235
5236 void onPreferencesFetchFailed();
5237 }
5238
5239 public interface OnAccountCreated {
5240 void onAccountCreated(Account account);
5241
5242 void informUser(int r);
5243 }
5244
5245 public interface OnMoreMessagesLoaded {
5246 void onMoreMessagesLoaded(int count, Conversation conversation);
5247
5248 void informUser(int r);
5249 }
5250
5251 public interface OnAccountPasswordChanged {
5252 void onPasswordChangeSucceeded();
5253
5254 void onPasswordChangeFailed();
5255 }
5256
5257 public interface OnRoomDestroy {
5258 void onRoomDestroySucceeded();
5259
5260 void onRoomDestroyFailed();
5261 }
5262
5263 public interface OnAffiliationChanged {
5264 void onAffiliationChangedSuccessful(Jid jid);
5265
5266 void onAffiliationChangeFailed(Jid jid, int resId);
5267 }
5268
5269 public interface OnConversationUpdate {
5270 void onConversationUpdate();
5271 }
5272
5273 public interface OnJingleRtpConnectionUpdate {
5274 void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5275
5276 void onAudioDeviceChanged(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices);
5277 }
5278
5279 public interface OnAccountUpdate {
5280 void onAccountUpdate();
5281 }
5282
5283 public interface OnCaptchaRequested {
5284 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5285 }
5286
5287 public interface OnRosterUpdate {
5288 void onRosterUpdate();
5289 }
5290
5291 public interface OnMucRosterUpdate {
5292 void onMucRosterUpdate();
5293 }
5294
5295 public interface OnConferenceConfigurationFetched {
5296 void onConferenceConfigurationFetched(Conversation conversation);
5297
5298 void onFetchFailed(Conversation conversation, String errorCondition);
5299 }
5300
5301 public interface OnConferenceJoined {
5302 void onConferenceJoined(Conversation conversation);
5303 }
5304
5305 public interface OnConfigurationPushed {
5306 void onPushSucceeded();
5307
5308 void onPushFailed();
5309 }
5310
5311 public interface OnShowErrorToast {
5312 void onShowErrorToast(int resId);
5313 }
5314
5315 public class XmppConnectionBinder extends Binder {
5316 public XmppConnectionService getService() {
5317 return XmppConnectionService.this;
5318 }
5319 }
5320
5321 private class InternalEventReceiver extends BroadcastReceiver {
5322
5323 @Override
5324 public void onReceive(final Context context, final Intent intent) {
5325 onStartCommand(intent, 0, 0);
5326 }
5327 }
5328
5329 private class RestrictedEventReceiver extends BroadcastReceiver {
5330
5331 private final Collection<String> allowedActions;
5332
5333 private RestrictedEventReceiver(final Collection<String> allowedActions) {
5334 this.allowedActions = allowedActions;
5335 }
5336
5337 @Override
5338 public void onReceive(final Context context, final Intent intent) {
5339 final String action = intent == null ? null : intent.getAction();
5340 if (allowedActions.contains(action)) {
5341 onStartCommand(intent,0,0);
5342 } else {
5343 Log.e(Config.LOGTAG,"restricting broadcast of event "+action);
5344 }
5345 }
5346 }
5347
5348 public static class OngoingCall {
5349 public final AbstractJingleConnection.Id id;
5350 public final Set<Media> media;
5351 public final boolean reconnecting;
5352
5353 public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5354 this.id = id;
5355 this.media = media;
5356 this.reconnecting = reconnecting;
5357 }
5358
5359 @Override
5360 public boolean equals(Object o) {
5361 if (this == o) return true;
5362 if (o == null || getClass() != o.getClass()) return false;
5363 OngoingCall that = (OngoingCall) o;
5364 return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
5365 }
5366
5367 @Override
5368 public int hashCode() {
5369 return Objects.hashCode(id, media, reconnecting);
5370 }
5371 }
5372
5373 public static void toggleForegroundService(final XmppConnectionService service) {
5374 if (service == null) {
5375 return;
5376 }
5377 service.toggleForegroundService();
5378 }
5379
5380 public static void toggleForegroundService(final ConversationsActivity activity) {
5381 if (activity == null) {
5382 return;
5383 }
5384 toggleForegroundService(activity.xmppConnectionService);
5385 }
5386}