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.Config;
97import eu.siacs.conversations.R;
98import eu.siacs.conversations.android.JabberIdContact;
99import eu.siacs.conversations.crypto.OmemoSetting;
100import eu.siacs.conversations.crypto.PgpDecryptionService;
101import eu.siacs.conversations.crypto.PgpEngine;
102import eu.siacs.conversations.crypto.axolotl.AxolotlService;
103import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
104import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
105import eu.siacs.conversations.entities.Account;
106import eu.siacs.conversations.entities.Blockable;
107import eu.siacs.conversations.entities.Bookmark;
108import eu.siacs.conversations.entities.Contact;
109import eu.siacs.conversations.entities.Conversation;
110import eu.siacs.conversations.entities.Conversational;
111import eu.siacs.conversations.entities.Message;
112import eu.siacs.conversations.entities.MucOptions;
113import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
114import eu.siacs.conversations.entities.Presence;
115import eu.siacs.conversations.entities.PresenceTemplate;
116import eu.siacs.conversations.entities.Roster;
117import eu.siacs.conversations.entities.ServiceDiscoveryResult;
118import eu.siacs.conversations.generator.AbstractGenerator;
119import eu.siacs.conversations.generator.IqGenerator;
120import eu.siacs.conversations.generator.MessageGenerator;
121import eu.siacs.conversations.generator.PresenceGenerator;
122import eu.siacs.conversations.http.HttpConnectionManager;
123import eu.siacs.conversations.parser.AbstractParser;
124import eu.siacs.conversations.parser.IqParser;
125import eu.siacs.conversations.parser.MessageParser;
126import eu.siacs.conversations.parser.PresenceParser;
127import eu.siacs.conversations.persistance.DatabaseBackend;
128import eu.siacs.conversations.persistance.FileBackend;
129import eu.siacs.conversations.persistance.UnifiedPushDatabase;
130import eu.siacs.conversations.ui.ChooseAccountForProfilePictureActivity;
131import eu.siacs.conversations.ui.ConversationsActivity;
132import eu.siacs.conversations.ui.RtpSessionActivity;
133import eu.siacs.conversations.ui.SettingsActivity;
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 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
869 scheduleNextIdlePing();
870 }
871 break;
872 case ACTION_FCM_MESSAGE_RECEIVED:
873 Log.d(Config.LOGTAG, "push message arrived in service. account");
874 break;
875 case ACTION_QUICK_LOG:
876 final String message = intent == null ? null : intent.getStringExtra("message");
877 if (message != null && Config.QUICK_LOG) {
878 quickLog(message);
879 }
880 break;
881 case Intent.ACTION_SEND:
882 final Uri uri = intent == null ? null : intent.getData();
883 if (uri != null) {
884 Log.d(Config.LOGTAG, "received uri permission for " + uri);
885 }
886 return START_STICKY;
887 case ACTION_TEMPORARILY_DISABLE:
888 toggleSoftDisabled(true);
889 if (checkListeners()) {
890 stopSelf();
891 }
892 return START_NOT_STICKY;
893 }
894 final var extras = intent == null ? null : intent.getExtras();
895 try {
896 internalPingExecutor.execute(() -> manageAccountConnectionStates(action, extras));
897 } catch (final RejectedExecutionException e) {
898 Log.e(Config.LOGTAG, "can not schedule connection states manager");
899 }
900 if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
901 expireOldMessages();
902 }
903 return START_STICKY;
904 }
905
906 private void quickLog(final String message) {
907 if (Strings.isNullOrEmpty(message)) {
908 return;
909 }
910 final Account account = AccountUtils.getFirstEnabled(this);
911 if (account == null) {
912 return;
913 }
914 final Conversation conversation =
915 findOrCreateConversation(account, Config.BUG_REPORTS, false, true);
916 final Message report = new Message(conversation, message, Message.ENCRYPTION_NONE);
917 report.setStatus(Message.STATUS_RECEIVED);
918 conversation.add(report);
919 databaseBackend.createMessage(report);
920 updateConversationUi();
921 }
922
923 private void manageAccountConnectionStatesInternal() {
924 manageAccountConnectionStates(ACTION_INTERNAL_PING, null);
925 }
926
927 private synchronized void manageAccountConnectionStates(
928 final String action, final Bundle extras) {
929 final String pushedAccountHash = extras == null ? null : extras.getString("account");
930 final boolean interactive = java.util.Objects.equals(ACTION_TRY_AGAIN, action);
931 WakeLockHelper.acquire(wakeLock);
932 boolean pingNow =
933 ConnectivityManager.CONNECTIVITY_ACTION.equals(action)
934 || (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0
935 && ACTION_POST_CONNECTIVITY_CHANGE.equals(action));
936 final HashSet<Account> pingCandidates = new HashSet<>();
937 final String androidId = pushedAccountHash == null ? null : PhoneHelper.getAndroidId(this);
938 for (final Account account : accounts) {
939 final boolean pushWasMeantForThisAccount =
940 androidId != null
941 && CryptoHelper.getAccountFingerprint(account, androidId)
942 .equals(pushedAccountHash);
943 pingNow |=
944 processAccountState(
945 account,
946 interactive,
947 "ui".equals(action),
948 pushWasMeantForThisAccount,
949 pingCandidates);
950 }
951 if (pingNow) {
952 for (final Account account : pingCandidates) {
953 final boolean lowTimeout = isInLowPingTimeoutMode(account);
954 account.getXmppConnection().sendPing();
955 Log.d(
956 Config.LOGTAG,
957 account.getJid().asBareJid()
958 + " send ping (action="
959 + action
960 + ",lowTimeout="
961 + lowTimeout
962 + ")");
963 scheduleWakeUpCall(
964 lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT,
965 account.getUuid().hashCode());
966 }
967 }
968 WakeLockHelper.release(wakeLock);
969 }
970
971 private void handleOrbotStartedEvent() {
972 for (final Account account : accounts) {
973 if (account.getStatus() == Account.State.TOR_NOT_AVAILABLE) {
974 reconnectAccount(account, true, false);
975 }
976 }
977 }
978
979 private boolean processAccountState(final Account account, final boolean interactive, final boolean isUiAction, final boolean isAccountPushed, final HashSet<Account> pingCandidates) {
980 if (!account.getStatus().isAttemptReconnect()) {
981 return false;
982 }
983 if (!hasInternetConnection()) {
984 account.setStatus(Account.State.NO_INTERNET);
985 statusListener.onStatusChanged(account);
986 } else {
987 if (account.getStatus() == Account.State.NO_INTERNET) {
988 account.setStatus(Account.State.OFFLINE);
989 statusListener.onStatusChanged(account);
990 }
991 if (account.getStatus() == Account.State.ONLINE) {
992 synchronized (mLowPingTimeoutMode) {
993 long lastReceived = account.getXmppConnection().getLastPacketReceived();
994 long lastSent = account.getXmppConnection().getLastPingSent();
995 long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
996 long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
997 int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().asBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
998 long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
999 if (lastSent > lastReceived) {
1000 if (pingTimeoutIn < 0) {
1001 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
1002 this.reconnectAccount(account, true, interactive);
1003 } else {
1004 int secs = (int) (pingTimeoutIn / 1000);
1005 this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
1006 }
1007 } else {
1008 pingCandidates.add(account);
1009 if (isAccountPushed) {
1010 if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
1011 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": entering low ping timeout mode");
1012 }
1013 return true;
1014 } else if (msToNextPing <= 0) {
1015 return true;
1016 } else {
1017 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
1018 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
1019 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
1020 }
1021 }
1022 }
1023 }
1024 } else if (account.getStatus() == Account.State.OFFLINE) {
1025 reconnectAccount(account, true, interactive);
1026 } else if (account.getStatus() == Account.State.CONNECTING) {
1027 long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
1028 long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
1029 long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
1030 long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
1031 if (timeout < 0) {
1032 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast=" + secondsSinceLastConnect + ")");
1033 account.getXmppConnection().resetAttemptCount(false);
1034 reconnectAccount(account, true, interactive);
1035 } else if (discoTimeout < 0) {
1036 account.getXmppConnection().sendDiscoTimeout();
1037 scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
1038 } else {
1039 scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
1040 }
1041 } else {
1042 final boolean aggressive = account.getStatus() == Account.State.SEE_OTHER_HOST || hasJingleRtpConnection(account);
1043 if (account.getXmppConnection().getTimeToNextAttempt(aggressive) <= 0) {
1044 reconnectAccount(account, true, interactive);
1045 }
1046 }
1047 }
1048 return false;
1049 }
1050
1051 private void toggleSoftDisabled(final boolean softDisabled) {
1052 for(final Account account : this.accounts) {
1053 if (account.isEnabled()) {
1054 if (account.setOption(Account.OPTION_SOFT_DISABLED, softDisabled)) {
1055 updateAccount(account);
1056 }
1057 }
1058 }
1059 }
1060
1061 public boolean processUnifiedPushMessage(final Account account, final Jid transport, final Element push) {
1062 return unifiedPushBroker.processPushMessage(account, transport, push);
1063 }
1064
1065 public void reinitializeMuclumbusService() {
1066 mChannelDiscoveryService.initializeMuclumbusService();
1067 }
1068
1069 public void discoverChannels(String query, ChannelDiscoveryService.Method method, ChannelDiscoveryService.OnChannelSearchResultsFound onChannelSearchResultsFound) {
1070 mChannelDiscoveryService.discover(Strings.nullToEmpty(query).trim(), method, onChannelSearchResultsFound);
1071 }
1072
1073 public boolean isDataSaverDisabled() {
1074 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
1075 return true;
1076 }
1077 final ConnectivityManager connectivityManager = getSystemService(ConnectivityManager.class);
1078 return !Compatibility.isActiveNetworkMetered(connectivityManager)
1079 || Compatibility.getRestrictBackgroundStatus(connectivityManager)
1080 == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
1081 }
1082
1083 private void directReply(final Conversation conversation, final String body, final String lastMessageUuid, final boolean dismissAfterReply) {
1084 final Message inReplyTo = lastMessageUuid == null ? null : conversation.findMessageWithUuid(lastMessageUuid);
1085 final Message message = new Message(conversation, body, conversation.getNextEncryption());
1086 if (inReplyTo != null && inReplyTo.isPrivateMessage()) {
1087 Message.configurePrivateMessage(message, inReplyTo.getCounterpart());
1088 }
1089 message.markUnread();
1090 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
1091 getPgpEngine().encrypt(message, new UiCallback<Message>() {
1092 @Override
1093 public void success(Message message) {
1094 if (dismissAfterReply) {
1095 markRead((Conversation) message.getConversation(), true);
1096 } else {
1097 mNotificationService.pushFromDirectReply(message);
1098 }
1099 }
1100
1101 @Override
1102 public void error(int errorCode, Message object) {
1103
1104 }
1105
1106 @Override
1107 public void userInputRequired(PendingIntent pi, Message object) {
1108
1109 }
1110 });
1111 } else {
1112 sendMessage(message);
1113 if (dismissAfterReply) {
1114 markRead(conversation, true);
1115 } else {
1116 mNotificationService.pushFromDirectReply(message);
1117 }
1118 }
1119 }
1120
1121 private boolean dndOnSilentMode() {
1122 return getBooleanPreference(SettingsActivity.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
1123 }
1124
1125 private boolean manuallyChangePresence() {
1126 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
1127 }
1128
1129 private boolean treatVibrateAsSilent() {
1130 return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
1131 }
1132
1133 private boolean awayWhenScreenLocked() {
1134 return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
1135 }
1136
1137 private String getCompressPicturesPreference() {
1138 return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
1139 }
1140
1141 private Presence.Status getTargetPresence() {
1142 if (dndOnSilentMode() && isPhoneSilenced()) {
1143 return Presence.Status.DND;
1144 } else if (awayWhenScreenLocked() && isScreenLocked()) {
1145 return Presence.Status.AWAY;
1146 } else {
1147 return Presence.Status.ONLINE;
1148 }
1149 }
1150
1151 public boolean isScreenLocked() {
1152 final KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
1153 final PowerManager powerManager = getSystemService(PowerManager.class);
1154 final boolean locked = keyguardManager != null && keyguardManager.isKeyguardLocked();
1155 final boolean interactive;
1156 try {
1157 interactive = powerManager != null && powerManager.isInteractive();
1158 } catch (final Exception e) {
1159 return false;
1160 }
1161 return locked || !interactive;
1162 }
1163
1164 private boolean isPhoneSilenced() {
1165 final NotificationManager notificationManager = getSystemService(NotificationManager.class);
1166 final int filter = notificationManager == null ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN : notificationManager.getCurrentInterruptionFilter();
1167 final boolean notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
1168 final AudioManager audioManager = getSystemService(AudioManager.class);
1169 final int ringerMode = audioManager == null ? AudioManager.RINGER_MODE_NORMAL : audioManager.getRingerMode();
1170 try {
1171 if (treatVibrateAsSilent()) {
1172 return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
1173 } else {
1174 return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
1175 }
1176 } catch (final Throwable throwable) {
1177 Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
1178 return notificationDnd;
1179 }
1180 }
1181
1182 private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
1183 Log.d(Config.LOGTAG, "resetting all attempt counts");
1184 for (Account account : accounts) {
1185 if (account.hasErrorStatus() || reallyAll) {
1186 final XmppConnection connection = account.getXmppConnection();
1187 if (connection != null) {
1188 connection.resetAttemptCount(retryImmediately);
1189 }
1190 }
1191 if (account.setShowErrorNotification(true)) {
1192 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1193 }
1194 }
1195 mNotificationService.updateErrorNotification();
1196 }
1197
1198 private void dismissErrorNotifications() {
1199 for (final Account account : this.accounts) {
1200 if (account.hasErrorStatus()) {
1201 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
1202 if (account.setShowErrorNotification(false)) {
1203 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1204 }
1205 }
1206 }
1207 }
1208
1209 private void expireOldMessages() {
1210 expireOldMessages(false);
1211 }
1212
1213 public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
1214 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1215 mDatabaseWriterExecutor.execute(() -> {
1216 long timestamp = getAutomaticMessageDeletionDate();
1217 if (timestamp > 0) {
1218 databaseBackend.expireOldMessages(timestamp);
1219 synchronized (XmppConnectionService.this.conversations) {
1220 for (Conversation conversation : XmppConnectionService.this.conversations) {
1221 conversation.expireOldMessages(timestamp);
1222 if (resetHasMessagesLeftOnServer) {
1223 conversation.messagesLoaded.set(true);
1224 conversation.setHasMessagesLeftOnServer(true);
1225 }
1226 }
1227 }
1228 updateConversationUi();
1229 }
1230 });
1231 }
1232
1233 public boolean hasInternetConnection() {
1234 final ConnectivityManager cm = ContextCompat.getSystemService(this, ConnectivityManager.class);
1235 if (cm == null) {
1236 return true; //if internet connection can not be checked it is probably best to just try
1237 }
1238 try {
1239 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
1240 final Network activeNetwork = cm.getActiveNetwork();
1241 final NetworkCapabilities capabilities = activeNetwork == null ? null : cm.getNetworkCapabilities(activeNetwork);
1242 return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1243 } else {
1244 final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
1245 return networkInfo != null && (networkInfo.isConnected() || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET);
1246 }
1247 } catch (final RuntimeException e) {
1248 Log.d(Config.LOGTAG, "unable to check for internet connection", e);
1249 return true; //if internet connection can not be checked it is probably best to just try
1250 }
1251 }
1252
1253 @SuppressLint("TrulyRandom")
1254 @Override
1255 public void onCreate() {
1256 LibIdnXmppStringprep.setup();
1257 if (Compatibility.runsTwentySix()) {
1258 mNotificationService.initializeChannels();
1259 }
1260 mChannelDiscoveryService.initializeMuclumbusService();
1261 mForceDuringOnCreate.set(Compatibility.runsAndTargetsTwentySix(this));
1262 toggleForegroundService();
1263 this.destroyed = false;
1264 OmemoSetting.load(this);
1265 ExceptionHelper.init(getApplicationContext());
1266 try {
1267 Security.insertProviderAt(Conscrypt.newProvider(), 1);
1268 } catch (Throwable throwable) {
1269 Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
1270 }
1271 Resolver.init(this);
1272 updateMemorizingTrustmanager();
1273 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
1274 final int cacheSize = maxMemory / 8;
1275 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
1276 @Override
1277 protected int sizeOf(final String key, final Bitmap bitmap) {
1278 return bitmap.getByteCount() / 1024;
1279 }
1280 };
1281 if (mLastActivity == 0) {
1282 mLastActivity = getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
1283 }
1284
1285 Log.d(Config.LOGTAG, "initializing database...");
1286 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
1287 Log.d(Config.LOGTAG, "restoring accounts...");
1288 this.accounts = databaseBackend.getAccounts();
1289 final SharedPreferences.Editor editor = getPreferences().edit();
1290 if (this.accounts.size() == 0 && Arrays.asList("Sony", "Sony Ericsson").contains(Build.MANUFACTURER)) {
1291 editor.putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, true);
1292 Log.d(Config.LOGTAG, Build.MANUFACTURER + " is on blacklist. enabling foreground service");
1293 }
1294 final boolean hasEnabledAccounts = hasEnabledAccounts();
1295 editor.putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
1296 editor.apply();
1297 toggleSetProfilePictureActivity(hasEnabledAccounts);
1298 reconfigurePushDistributor();
1299
1300 if (CallIntegration.hasSystemFeature(this)) {
1301 CallIntegrationConnectionService.togglePhoneAccountsAsync(this, this.accounts);
1302 }
1303
1304 restoreFromDatabase();
1305
1306 if (QuickConversationsService.isContactListIntegration(this)
1307 && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
1308 == PackageManager.PERMISSION_GRANTED) {
1309 startContactObserver();
1310 }
1311 FILE_OBSERVER_EXECUTOR.execute(fileBackend::deleteHistoricAvatarPath);
1312 if (Compatibility.hasStoragePermission(this)) {
1313 Log.d(Config.LOGTAG, "starting file observer");
1314 FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::startWatching);
1315 FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1316 }
1317 if (Config.supportOpenPgp()) {
1318 this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
1319 @Override
1320 public void onBound(final IOpenPgpService2 service) {
1321 for (Account account : accounts) {
1322 final PgpDecryptionService pgp = account.getPgpDecryptionService();
1323 if (pgp != null) {
1324 pgp.continueDecryption(true);
1325 }
1326 }
1327 }
1328
1329 @Override
1330 public void onError(final Exception exception) {
1331 Log.e(Config.LOGTAG,"could not bind to OpenKeyChain", exception);
1332 }
1333 });
1334 this.pgpServiceConnection.bindToService();
1335 }
1336
1337 final PowerManager pm = ContextCompat.getSystemService(this, PowerManager.class);
1338 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1339
1340 toggleForegroundService();
1341 updateUnreadCountBadge();
1342 toggleScreenEventReceiver();
1343 final IntentFilter systemBroadcastFilter = new IntentFilter();
1344 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1345 scheduleNextIdlePing();
1346 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1347 systemBroadcastFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1348 }
1349 systemBroadcastFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1350 }
1351 ContextCompat.registerReceiver(
1352 this,
1353 this.mInternalEventReceiver,
1354 systemBroadcastFilter,
1355 ContextCompat.RECEIVER_NOT_EXPORTED);
1356 final IntentFilter exportedBroadcastFilter = new IntentFilter();
1357 exportedBroadcastFilter.addAction(TorServiceUtils.ACTION_STATUS);
1358 ContextCompat.registerReceiver(
1359 this,
1360 this.mInternalRestrictedEventReceiver,
1361 exportedBroadcastFilter,
1362 ContextCompat.RECEIVER_EXPORTED);
1363 mForceDuringOnCreate.set(false);
1364 toggleForegroundService();
1365 internalPingExecutor.scheduleAtFixedRate(this::manageAccountConnectionStatesInternal,10,10,TimeUnit.SECONDS);
1366 }
1367
1368
1369 private void checkForDeletedFiles() {
1370 if (destroyed) {
1371 Log.d(Config.LOGTAG, "Do not check for deleted files because service has been destroyed");
1372 return;
1373 }
1374 final long start = SystemClock.elapsedRealtime();
1375 final List<DatabaseBackend.FilePathInfo> relativeFilePaths = databaseBackend.getFilePathInfo();
1376 final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1377 for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1378 if (destroyed) {
1379 Log.d(Config.LOGTAG, "Stop checking for deleted files because service has been destroyed");
1380 return;
1381 }
1382 final File file = fileBackend.getFileForPath(filePath.path);
1383 if (filePath.setDeleted(!file.exists())) {
1384 changed.add(filePath);
1385 }
1386 }
1387 final long duration = SystemClock.elapsedRealtime() - start;
1388 Log.d(Config.LOGTAG, "found " + changed.size() + " changed files on start up. total=" + relativeFilePaths.size() + ". (" + duration + "ms)");
1389 if (changed.size() > 0) {
1390 databaseBackend.markFilesAsChanged(changed);
1391 markChangedFiles(changed);
1392 }
1393 }
1394
1395 public void startContactObserver() {
1396 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) {
1397 @Override
1398 public void onChange(boolean selfChange) {
1399 super.onChange(selfChange);
1400 if (restoredFromDatabaseLatch.getCount() == 0) {
1401 loadPhoneContacts();
1402 }
1403 }
1404 });
1405 }
1406
1407 @Override
1408 public void onTrimMemory(int level) {
1409 super.onTrimMemory(level);
1410 if (level >= TRIM_MEMORY_COMPLETE) {
1411 Log.d(Config.LOGTAG, "clear cache due to low memory");
1412 getBitmapCache().evictAll();
1413 }
1414 }
1415
1416 @Override
1417 public void onDestroy() {
1418 try {
1419 unregisterReceiver(this.mInternalEventReceiver);
1420 unregisterReceiver(this.mInternalRestrictedEventReceiver);
1421 unregisterReceiver(this.mInternalScreenEventReceiver);
1422 } catch (final IllegalArgumentException e) {
1423 //ignored
1424 }
1425 destroyed = false;
1426 fileObserver.stopWatching();
1427 internalPingExecutor.shutdown();
1428 super.onDestroy();
1429 }
1430
1431 public void restartFileObserver() {
1432 Log.d(Config.LOGTAG, "restarting file observer");
1433 FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::restartWatching);
1434 FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1435 }
1436
1437 public void toggleScreenEventReceiver() {
1438 if (awayWhenScreenLocked() && !manuallyChangePresence()) {
1439 final IntentFilter filter = new IntentFilter();
1440 filter.addAction(Intent.ACTION_SCREEN_ON);
1441 filter.addAction(Intent.ACTION_SCREEN_OFF);
1442 filter.addAction(Intent.ACTION_USER_PRESENT);
1443 registerReceiver(this.mInternalScreenEventReceiver, filter);
1444 } else {
1445 try {
1446 unregisterReceiver(this.mInternalScreenEventReceiver);
1447 } catch (IllegalArgumentException e) {
1448 //ignored
1449 }
1450 }
1451 }
1452
1453 public void toggleForegroundService() {
1454 toggleForegroundService(false);
1455 }
1456
1457 public void setOngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
1458 ongoingCall.set(new OngoingCall(id, media, reconnecting));
1459 toggleForegroundService(false);
1460 }
1461
1462 public void removeOngoingCall() {
1463 ongoingCall.set(null);
1464 toggleForegroundService(false);
1465 }
1466
1467 private void toggleForegroundService(final boolean force) {
1468 final boolean status;
1469 final OngoingCall ongoing = ongoingCall.get();
1470 final boolean ongoingVideoTranscoding = mOngoingVideoTranscoding.get();
1471 final int id;
1472 if (force
1473 || mForceDuringOnCreate.get()
1474 || ongoingVideoTranscoding
1475 || ongoing != null
1476 || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1477 final Notification notification;
1478 if (ongoing != null) {
1479 notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1480 id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1481 startForegroundOrCatch(id, notification, true);
1482 } else if (ongoingVideoTranscoding) {
1483 notification = this.mNotificationService.getIndeterminateVideoTranscoding();
1484 id = NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID;
1485 startForegroundOrCatch(id, notification, false);
1486 } else {
1487 notification = this.mNotificationService.createForegroundNotification();
1488 id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1489 startForegroundOrCatch(id, notification, false);
1490 }
1491 mNotificationService.notify(id, notification);
1492 status = true;
1493 } else {
1494 id = 0;
1495 stopForeground(true);
1496 status = false;
1497 }
1498
1499 for (final int toBeRemoved :
1500 Collections2.filter(
1501 Arrays.asList(
1502 NotificationService.FOREGROUND_NOTIFICATION_ID,
1503 NotificationService.ONGOING_CALL_NOTIFICATION_ID,
1504 NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID),
1505 i -> i != id)) {
1506 mNotificationService.cancel(toBeRemoved);
1507 }
1508 Log.d(
1509 Config.LOGTAG,
1510 "ForegroundService: " + (status ? "on" : "off") + ", notification: " + id);
1511 }
1512
1513 private void startForegroundOrCatch(
1514 final int id, final Notification notification, final boolean requireMicrophone) {
1515 try {
1516 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
1517 final int foregroundServiceType;
1518 if (requireMicrophone
1519 && ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1520 == PackageManager.PERMISSION_GRANTED) {
1521 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1522 Log.d(Config.LOGTAG, "defaulting to microphone foreground service type");
1523 } else if (getSystemService(PowerManager.class)
1524 .isIgnoringBatteryOptimizations(getPackageName())) {
1525 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED;
1526 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1527 == PackageManager.PERMISSION_GRANTED) {
1528 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1529 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
1530 == PackageManager.PERMISSION_GRANTED) {
1531 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;
1532 } else {
1533 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
1534 Log.w(Config.LOGTAG, "falling back to special use foreground service type");
1535 }
1536 startForeground(id, notification, foregroundServiceType);
1537 } else {
1538 startForeground(id, notification);
1539 }
1540 } catch (final IllegalStateException | SecurityException e) {
1541 Log.e(Config.LOGTAG, "Could not start foreground service", e);
1542 }
1543 }
1544
1545 public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1546 return !mOngoingVideoTranscoding.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1547 }
1548
1549 @Override
1550 public void onTaskRemoved(final Intent rootIntent) {
1551 super.onTaskRemoved(rootIntent);
1552 if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mOngoingVideoTranscoding.get() || ongoingCall.get() != null) {
1553 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1554 } else {
1555 this.logoutAndSave(false);
1556 }
1557 }
1558
1559 private void logoutAndSave(boolean stop) {
1560 int activeAccounts = 0;
1561 for (final Account account : accounts) {
1562 if (account.isConnectionEnabled()) {
1563 databaseBackend.writeRoster(account.getRoster());
1564 activeAccounts++;
1565 }
1566 if (account.getXmppConnection() != null) {
1567 new Thread(() -> disconnect(account, false)).start();
1568 }
1569 }
1570 if (stop || activeAccounts == 0) {
1571 Log.d(Config.LOGTAG, "good bye");
1572 stopSelf();
1573 }
1574 }
1575
1576 private void schedulePostConnectivityChange() {
1577 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1578 if (alarmManager == null) {
1579 return;
1580 }
1581 final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1582 final Intent intent = new Intent(this, EventReceiver.class);
1583 intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1584 try {
1585 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, s()
1586 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1587 : PendingIntent.FLAG_UPDATE_CURRENT);
1588 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1589 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1590 } else {
1591 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1592 }
1593 } catch (RuntimeException e) {
1594 Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1595 }
1596 }
1597
1598 public void scheduleWakeUpCall(final int seconds, final int requestCode) {
1599 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000L;
1600 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1601 if (alarmManager == null) {
1602 return;
1603 }
1604 final Intent intent = new Intent(this, EventReceiver.class);
1605 intent.setAction(ACTION_PING);
1606 try {
1607 final PendingIntent pendingIntent =
1608 PendingIntent.getBroadcast(
1609 this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1610 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1611 } catch (RuntimeException e) {
1612 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1613 }
1614 }
1615
1616 @TargetApi(Build.VERSION_CODES.M)
1617 private void scheduleNextIdlePing() {
1618 final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1619 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1620 if (alarmManager == null) {
1621 return;
1622 }
1623 final Intent intent = new Intent(this, EventReceiver.class);
1624 intent.setAction(ACTION_IDLE_PING);
1625 try {
1626 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, s()
1627 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1628 : PendingIntent.FLAG_UPDATE_CURRENT);
1629 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1630 } catch (RuntimeException e) {
1631 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1632 }
1633 }
1634
1635 public XmppConnection createConnection(final Account account) {
1636 final XmppConnection connection = new XmppConnection(account, this);
1637 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1638 connection.setOnStatusChangedListener(this.statusListener);
1639 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1640 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1641 connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1642 connection.setOnBindListener(this.mOnBindListener);
1643 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1644 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1645 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1646 AxolotlService axolotlService = account.getAxolotlService();
1647 if (axolotlService != null) {
1648 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1649 }
1650 return connection;
1651 }
1652
1653 public void sendChatState(Conversation conversation) {
1654 if (sendChatStates()) {
1655 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1656 sendMessagePacket(conversation.getAccount(), packet);
1657 }
1658 }
1659
1660 private void sendFileMessage(final Message message, final boolean delay) {
1661 Log.d(Config.LOGTAG, "send file message");
1662 final Account account = message.getConversation().getAccount();
1663 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1664 || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1665 mHttpConnectionManager.createNewUploadConnection(message, delay);
1666 } else {
1667 mJingleConnectionManager.startJingleFileTransfer(message);
1668 }
1669 }
1670
1671 public void sendMessage(final Message message) {
1672 sendMessage(message, false, false);
1673 }
1674
1675 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1676 final Account account = message.getConversation().getAccount();
1677 if (account.setShowErrorNotification(true)) {
1678 databaseBackend.updateAccount(account);
1679 mNotificationService.updateErrorNotification();
1680 }
1681 final Conversation conversation = (Conversation) message.getConversation();
1682 account.deactivateGracePeriod();
1683
1684
1685 if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1686 final Contact contact = conversation.getContact();
1687 if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1688 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1689 createContact(contact, true);
1690 }
1691 }
1692
1693 MessagePacket packet = null;
1694 final boolean addToConversation = !message.edited();
1695 boolean saveInDb = addToConversation;
1696 message.setStatus(Message.STATUS_WAITING);
1697
1698 if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1699 if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1700 databaseBackend.updateConversation(conversation);
1701 }
1702 }
1703
1704 final boolean inProgressJoin = isJoinInProgress(conversation);
1705
1706
1707 if (account.isOnlineAndConnected() && !inProgressJoin) {
1708 switch (message.getEncryption()) {
1709 case Message.ENCRYPTION_NONE:
1710 if (message.needsUploading()) {
1711 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1712 || conversation.getMode() == Conversation.MODE_MULTI
1713 || message.fixCounterpart()) {
1714 this.sendFileMessage(message, delay);
1715 } else {
1716 break;
1717 }
1718 } else {
1719 packet = mMessageGenerator.generateChat(message);
1720 }
1721 break;
1722 case Message.ENCRYPTION_PGP:
1723 case Message.ENCRYPTION_DECRYPTED:
1724 if (message.needsUploading()) {
1725 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1726 || conversation.getMode() == Conversation.MODE_MULTI
1727 || message.fixCounterpart()) {
1728 this.sendFileMessage(message, delay);
1729 } else {
1730 break;
1731 }
1732 } else {
1733 packet = mMessageGenerator.generatePgpChat(message);
1734 }
1735 break;
1736 case Message.ENCRYPTION_AXOLOTL:
1737 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1738 if (message.needsUploading()) {
1739 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1740 || conversation.getMode() == Conversation.MODE_MULTI
1741 || message.fixCounterpart()) {
1742 this.sendFileMessage(message, delay);
1743 } else {
1744 break;
1745 }
1746 } else {
1747 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1748 if (axolotlMessage == null) {
1749 account.getAxolotlService().preparePayloadMessage(message, delay);
1750 } else {
1751 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1752 }
1753 }
1754 break;
1755
1756 }
1757 if (packet != null) {
1758 if (account.getXmppConnection().getFeatures().sm()
1759 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1760 message.setStatus(Message.STATUS_UNSEND);
1761 } else {
1762 message.setStatus(Message.STATUS_SEND);
1763 }
1764 }
1765 } else {
1766 switch (message.getEncryption()) {
1767 case Message.ENCRYPTION_DECRYPTED:
1768 if (!message.needsUploading()) {
1769 String pgpBody = message.getEncryptedBody();
1770 String decryptedBody = message.getBody();
1771 message.setBody(pgpBody); //TODO might throw NPE
1772 message.setEncryption(Message.ENCRYPTION_PGP);
1773 if (message.edited()) {
1774 message.setBody(decryptedBody);
1775 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1776 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1777 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1778 }
1779 updateConversationUi();
1780 return;
1781 } else {
1782 databaseBackend.createMessage(message);
1783 saveInDb = false;
1784 message.setBody(decryptedBody);
1785 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1786 }
1787 }
1788 break;
1789 case Message.ENCRYPTION_AXOLOTL:
1790 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1791 break;
1792 }
1793 }
1794
1795
1796 boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1797 if (mucMessage) {
1798 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1799 }
1800
1801 if (resend) {
1802 if (packet != null && addToConversation) {
1803 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1804 markMessage(message, Message.STATUS_UNSEND);
1805 } else {
1806 markMessage(message, Message.STATUS_SEND);
1807 }
1808 }
1809 } else {
1810 if (addToConversation) {
1811 conversation.add(message);
1812 }
1813 if (saveInDb) {
1814 databaseBackend.createMessage(message);
1815 } else if (message.edited()) {
1816 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1817 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1818 }
1819 }
1820 updateConversationUi();
1821 }
1822 if (packet != null) {
1823 if (delay) {
1824 mMessageGenerator.addDelay(packet, message.getTimeSent());
1825 }
1826 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1827 if (this.sendChatStates()) {
1828 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1829 }
1830 }
1831 sendMessagePacket(account, packet);
1832 }
1833 }
1834
1835 private boolean isJoinInProgress(final Conversation conversation) {
1836 final Account account = conversation.getAccount();
1837 synchronized (account.inProgressConferenceJoins) {
1838 if (conversation.getMode() == Conversational.MODE_MULTI) {
1839 final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1840 final boolean pending = account.pendingConferenceJoins.contains(conversation);
1841 final boolean inProgressJoin = inProgress || pending;
1842 if (inProgressJoin) {
1843 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
1844 }
1845 return inProgressJoin;
1846 } else {
1847 return false;
1848 }
1849 }
1850 }
1851
1852 private void sendUnsentMessages(final Conversation conversation) {
1853 conversation.findWaitingMessages(message -> resendMessage(message, true));
1854 }
1855
1856 public void resendMessage(final Message message, final boolean delay) {
1857 sendMessage(message, true, delay);
1858 }
1859
1860 public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
1861 final XmppConnection connection = account.getXmppConnection();
1862 final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
1863 if (jid == null) {
1864 callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
1865 return;
1866 }
1867 final IqPacket request = new IqPacket(IqPacket.TYPE.SET);
1868 request.setTo(jid);
1869 final Element command = request.addChild("command", Namespace.COMMANDS);
1870 command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
1871 command.setAttribute("action", "execute");
1872 sendIqPacket(account, request, (a, response) -> {
1873 if (response.getType() == IqPacket.TYPE.RESULT) {
1874 final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
1875 final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
1876 if (x != null) {
1877 final Data data = Data.parse(x);
1878 final String uri = data.getValue("uri");
1879 final String landingUrl = data.getValue("landing-url");
1880 if (uri != null) {
1881 final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
1882 callback.inviteRequested(invite);
1883 return;
1884 }
1885 }
1886 callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
1887 Log.d(Config.LOGTAG, response.toString());
1888 } else if (response.getType() == IqPacket.TYPE.ERROR) {
1889 callback.inviteRequestFailed(IqParser.errorMessage(response));
1890 } else {
1891 callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
1892 }
1893 });
1894
1895 }
1896
1897 public void fetchRosterFromServer(final Account account) {
1898 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1899 if (!"".equals(account.getRosterVersion())) {
1900 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1901 + ": fetching roster version " + account.getRosterVersion());
1902 } else {
1903 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1904 }
1905 iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1906 sendIqPacket(account, iqPacket, mIqParser);
1907 }
1908
1909 public void fetchBookmarks(final Account account) {
1910 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1911 final Element query = iqPacket.query("jabber:iq:private");
1912 query.addChild("storage", Namespace.BOOKMARKS);
1913 final OnIqPacketReceived callback = (a, response) -> {
1914 if (response.getType() == IqPacket.TYPE.RESULT) {
1915 final Element query1 = response.query();
1916 final Element storage = query1.findChild("storage", "storage:bookmarks");
1917 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
1918 processBookmarksInitial(a, bookmarks, false);
1919 } else {
1920 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1921 }
1922 };
1923 sendIqPacket(account, iqPacket, callback);
1924 }
1925
1926 public void fetchBookmarks2(final Account account) {
1927 final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
1928 sendIqPacket(account, retrieve, (a, response) -> {
1929 if (response.getType() == IqPacket.TYPE.RESULT) {
1930 final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
1931 final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, a);
1932 processBookmarksInitial(a, bookmarks, true);
1933 }
1934 });
1935 }
1936
1937 private void fetchMessageDisplayedSynchronization(final Account account) {
1938 Log.d(Config.LOGTAG, account.getJid() + ": retrieve mds");
1939 final var retrieve = mIqGenerator.retrieveMds();
1940 sendIqPacket(
1941 account,
1942 retrieve,
1943 (a, response) -> {
1944 if (response.getType() != IqPacket.TYPE.RESULT) {
1945 return;
1946 }
1947 final var pubSub = response.findChild("pubsub", Namespace.PUBSUB);
1948 final Element items = pubSub == null ? null : pubSub.findChild("items");
1949 if (items == null
1950 || !Namespace.MDS_DISPLAYED.equals(items.getAttribute("node"))) {
1951 return;
1952 }
1953 for (final Element child : items.getChildren()) {
1954 if ("item".equals(child.getName())) {
1955 processMdsItem(account, child);
1956 }
1957 }
1958 });
1959 }
1960
1961 public void processMdsItem(final Account account, final Element item) {
1962 final Jid jid =
1963 item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("id"));
1964 if (jid == null) {
1965 return;
1966 }
1967 final Element displayed = item.findChild("displayed", Namespace.MDS_DISPLAYED);
1968 final Element stanzaId =
1969 displayed == null ? null : displayed.findChild("stanza-id", Namespace.STANZA_IDS);
1970 final String id = stanzaId == null ? null : stanzaId.getAttribute("id");
1971 final Conversation conversation = find(account, jid);
1972 if (id != null && conversation != null) {
1973 conversation.setDisplayState(id);
1974 markReadUpToStanzaId(conversation, id);
1975 }
1976 }
1977
1978 public void markReadUpToStanzaId(final Conversation conversation, final String stanzaId) {
1979 final Message message = conversation.findMessageWithServerMsgId(stanzaId);
1980 if (message == null) { // do we want to check if isRead?
1981 return;
1982 }
1983 markReadUpTo(conversation, message);
1984 }
1985
1986 public void markReadUpTo(final Conversation conversation, final Message message) {
1987 final boolean isDismissNotification = isDismissNotification(message);
1988 final var uuid = message.getUuid();
1989 Log.d(
1990 Config.LOGTAG,
1991 conversation.getAccount().getJid().asBareJid()
1992 + ": mark "
1993 + conversation.getJid().asBareJid()
1994 + " as read up to "
1995 + uuid);
1996 markRead(conversation, uuid, isDismissNotification);
1997 }
1998
1999 private static boolean isDismissNotification(final Message message) {
2000 Message next = message.next();
2001 while (next != null) {
2002 if (message.getStatus() == Message.STATUS_RECEIVED) {
2003 return false;
2004 }
2005 next = next.next();
2006 }
2007 return true;
2008 }
2009
2010 public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
2011 final Set<Jid> previousBookmarks = account.getBookmarkedJids();
2012 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
2013 for (Bookmark bookmark : bookmarks.values()) {
2014 previousBookmarks.remove(bookmark.getJid().asBareJid());
2015 processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
2016 }
2017 if (pep && synchronizeWithBookmarks) {
2018 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
2019 for (Jid jid : previousBookmarks) {
2020 processDeletedBookmark(account, jid);
2021 }
2022 }
2023 account.setBookmarks(bookmarks);
2024 }
2025
2026 public void processDeletedBookmark(Account account, Jid jid) {
2027 final Conversation conversation = find(account, jid);
2028 if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2029 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
2030 archiveConversation(conversation, false);
2031 }
2032 }
2033
2034 private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
2035 final Account account = bookmark.getAccount();
2036 Conversation conversation = find(bookmark);
2037 if (conversation != null) {
2038 if (conversation.getMode() != Conversation.MODE_MULTI) {
2039 return;
2040 }
2041 bookmark.setConversation(conversation);
2042 if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
2043 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
2044 archiveConversation(conversation, false);
2045 } else {
2046 final MucOptions mucOptions = conversation.getMucOptions();
2047 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
2048 final String current = mucOptions.getActualNick();
2049 final String proposed = mucOptions.getProposedNick();
2050 if (current != null && !current.equals(proposed)) {
2051 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
2052 joinMuc(conversation);
2053 }
2054 }
2055 }
2056 } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
2057 conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
2058 bookmark.setConversation(conversation);
2059 }
2060 }
2061
2062 public void processModifiedBookmark(Bookmark bookmark) {
2063 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
2064 processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
2065 }
2066
2067 public void createBookmark(final Account account, final Bookmark bookmark) {
2068 account.putBookmark(bookmark);
2069 final XmppConnection connection = account.getXmppConnection();
2070 if (connection == null) {
2071 Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
2072 } else if (connection.getFeatures().bookmarks2()) {
2073 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": pushing bookmark via Bookmarks 2");
2074 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
2075 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
2076 } else if (connection.getFeatures().bookmarksConversion()) {
2077 pushBookmarksPep(account);
2078 } else {
2079 pushBookmarksPrivateXml(account);
2080 }
2081 }
2082
2083 public void deleteBookmark(final Account account, final Bookmark bookmark) {
2084 account.removeBookmark(bookmark);
2085 final XmppConnection connection = account.getXmppConnection();
2086 if (connection.getFeatures().bookmarks2()) {
2087 final IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
2088 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": removing bookmark via Bookmarks 2");
2089 sendIqPacket(account, request, (a, response) -> {
2090 if (response.getType() == IqPacket.TYPE.ERROR) {
2091 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
2092 }
2093 });
2094 } else if (connection.getFeatures().bookmarksConversion()) {
2095 pushBookmarksPep(account);
2096 } else {
2097 pushBookmarksPrivateXml(account);
2098 }
2099 }
2100
2101 private void pushBookmarksPrivateXml(Account account) {
2102 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
2103 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2104 Element query = iqPacket.query("jabber:iq:private");
2105 Element storage = query.addChild("storage", "storage:bookmarks");
2106 for (final Bookmark bookmark : account.getBookmarks()) {
2107 storage.addChild(bookmark);
2108 }
2109 sendIqPacket(account, iqPacket, mDefaultIqHandler);
2110 }
2111
2112 private void pushBookmarksPep(Account account) {
2113 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
2114 final Element storage = new Element("storage", "storage:bookmarks");
2115 for (final Bookmark bookmark : account.getBookmarks()) {
2116 storage.addChild(bookmark);
2117 }
2118 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
2119
2120 }
2121
2122 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
2123 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2124
2125 }
2126
2127 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
2128 final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
2129 sendIqPacket(account, packet, (a, response) -> {
2130 if (response.getType() == IqPacket.TYPE.RESULT) {
2131 return;
2132 }
2133 if (retry && PublishOptions.preconditionNotMet(response)) {
2134 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
2135 @Override
2136 public void onPushSucceeded() {
2137 pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
2138 }
2139
2140 @Override
2141 public void onPushFailed() {
2142 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
2143 }
2144 });
2145 } else {
2146 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing "+node+" (retry=" + retry + ") " + response);
2147 }
2148 });
2149 }
2150
2151 private void restoreFromDatabase() {
2152 synchronized (this.conversations) {
2153 final Map<String, Account> accountLookupTable = new Hashtable<>();
2154 for (Account account : this.accounts) {
2155 accountLookupTable.put(account.getUuid(), account);
2156 }
2157 Log.d(Config.LOGTAG, "restoring conversations...");
2158 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2159 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2160 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
2161 Conversation conversation = iterator.next();
2162 Account account = accountLookupTable.get(conversation.getAccountUuid());
2163 if (account != null) {
2164 conversation.setAccount(account);
2165 } else {
2166 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
2167 iterator.remove();
2168 }
2169 }
2170 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2171 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
2172 Runnable runnable = () -> {
2173 if (DatabaseBackend.requiresMessageIndexRebuild()) {
2174 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2175 }
2176 final long deletionDate = getAutomaticMessageDeletionDate();
2177 mLastExpiryRun.set(SystemClock.elapsedRealtime());
2178 if (deletionDate > 0) {
2179 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
2180 databaseBackend.expireOldMessages(deletionDate);
2181 }
2182 Log.d(Config.LOGTAG, "restoring roster...");
2183 for (final Account account : accounts) {
2184 databaseBackend.readRoster(account.getRoster());
2185 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
2186 }
2187 getBitmapCache().evictAll();
2188 loadPhoneContacts();
2189 Log.d(Config.LOGTAG, "restoring messages...");
2190 final long startMessageRestore = SystemClock.elapsedRealtime();
2191 final Conversation quickLoad = QuickLoader.get(this.conversations);
2192 if (quickLoad != null) {
2193 restoreMessages(quickLoad);
2194 updateConversationUi();
2195 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2196 Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
2197 }
2198 for (Conversation conversation : this.conversations) {
2199 if (quickLoad != conversation) {
2200 restoreMessages(conversation);
2201 }
2202 }
2203 mNotificationService.finishBacklog();
2204 restoredFromDatabaseLatch.countDown();
2205 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2206 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2207 updateConversationUi();
2208 };
2209 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2210 }
2211 }
2212
2213 private void restoreMessages(Conversation conversation) {
2214 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2215 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2216 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2217 }
2218
2219 public void loadPhoneContacts() {
2220 mContactMergerExecutor.execute(() -> {
2221 final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2222 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2223 for (final Account account : accounts) {
2224 final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2225 for (final JabberIdContact jidContact : contacts.values()) {
2226 final Contact contact = account.getRoster().getContact(jidContact.getJid());
2227 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2228 if (needsCacheClean) {
2229 getAvatarService().clear(contact);
2230 }
2231 withSystemAccounts.remove(contact);
2232 }
2233 for (final Contact contact : withSystemAccounts) {
2234 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2235 if (needsCacheClean) {
2236 getAvatarService().clear(contact);
2237 }
2238 }
2239 }
2240 Log.d(Config.LOGTAG, "finished merging phone contacts");
2241 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2242 updateRosterUi();
2243 mQuickConversationsService.considerSync();
2244 });
2245 }
2246
2247
2248 public void syncRoster(final Account account) {
2249 mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
2250 }
2251
2252 public List<Conversation> getConversations() {
2253 return this.conversations;
2254 }
2255
2256 private void markFileDeleted(final File file) {
2257 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2258 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2259 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2260 return;
2261 }
2262 }
2263 final boolean isInternalFile = fileBackend.isInternalFile(file);
2264 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2265 Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2266 markUuidsAsDeletedFiles(uuids);
2267 }
2268
2269 private void markUuidsAsDeletedFiles(List<String> uuids) {
2270 boolean deleted = false;
2271 for (Conversation conversation : getConversations()) {
2272 deleted |= conversation.markAsDeleted(uuids);
2273 }
2274 for (final String uuid : uuids) {
2275 evictPreview(uuid);
2276 }
2277 if (deleted) {
2278 updateConversationUi();
2279 }
2280 }
2281
2282 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2283 boolean changed = false;
2284 for (Conversation conversation : getConversations()) {
2285 changed |= conversation.markAsChanged(infos);
2286 }
2287 if (changed) {
2288 updateConversationUi();
2289 }
2290 }
2291
2292 public void populateWithOrderedConversations(final List<Conversation> list) {
2293 populateWithOrderedConversations(list, true, true);
2294 }
2295
2296 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2297 populateWithOrderedConversations(list, includeNoFileUpload, true);
2298 }
2299
2300 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2301 final List<String> orderedUuids;
2302 if (sort) {
2303 orderedUuids = null;
2304 } else {
2305 orderedUuids = new ArrayList<>();
2306 for (Conversation conversation : list) {
2307 orderedUuids.add(conversation.getUuid());
2308 }
2309 }
2310 list.clear();
2311 if (includeNoFileUpload) {
2312 list.addAll(getConversations());
2313 } else {
2314 for (Conversation conversation : getConversations()) {
2315 if (conversation.getMode() == Conversation.MODE_SINGLE
2316 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2317 list.add(conversation);
2318 }
2319 }
2320 }
2321 try {
2322 if (orderedUuids != null) {
2323 Collections.sort(list, (a, b) -> {
2324 final int indexA = orderedUuids.indexOf(a.getUuid());
2325 final int indexB = orderedUuids.indexOf(b.getUuid());
2326 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2327 return a.compareTo(b);
2328 }
2329 return indexA - indexB;
2330 });
2331 } else {
2332 Collections.sort(list);
2333 }
2334 } catch (IllegalArgumentException e) {
2335 //ignore
2336 }
2337 }
2338
2339 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2340 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2341 return;
2342 } else if (timestamp == 0) {
2343 return;
2344 }
2345 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2346 final Runnable runnable = () -> {
2347 final Account account = conversation.getAccount();
2348 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2349 if (messages.size() > 0) {
2350 conversation.addAll(0, messages);
2351 callback.onMoreMessagesLoaded(messages.size(), conversation);
2352 } else if (conversation.hasMessagesLeftOnServer()
2353 && account.isOnlineAndConnected()
2354 && conversation.getLastClearHistory().getTimestamp() == 0) {
2355 final boolean mamAvailable;
2356 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2357 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2358 } else {
2359 mamAvailable = conversation.getMucOptions().mamSupport();
2360 }
2361 if (mamAvailable) {
2362 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2363 if (query != null) {
2364 query.setCallback(callback);
2365 callback.informUser(R.string.fetching_history_from_server);
2366 } else {
2367 callback.informUser(R.string.not_fetching_history_retention_period);
2368 }
2369
2370 }
2371 }
2372 };
2373 mDatabaseReaderExecutor.execute(runnable);
2374 }
2375
2376 public List<Account> getAccounts() {
2377 return this.accounts;
2378 }
2379
2380
2381 /**
2382 * 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)
2383 */
2384 public List<Conversation> findAllConferencesWith(Contact contact) {
2385 final ArrayList<Conversation> results = new ArrayList<>();
2386 for (final Conversation c : conversations) {
2387 if (c.getMode() != Conversation.MODE_MULTI) {
2388 continue;
2389 }
2390 final MucOptions mucOptions = c.getMucOptions();
2391 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2392 results.add(c);
2393 }
2394 }
2395 return results;
2396 }
2397
2398 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2399 for (final Conversation conversation : haystack) {
2400 if (conversation.getContact() == contact) {
2401 return conversation;
2402 }
2403 }
2404 return null;
2405 }
2406
2407 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2408 if (jid == null) {
2409 return null;
2410 }
2411 for (final Conversation conversation : haystack) {
2412 if ((account == null || conversation.getAccount() == account)
2413 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2414 return conversation;
2415 }
2416 }
2417 return null;
2418 }
2419
2420 public boolean isConversationsListEmpty(final Conversation ignore) {
2421 synchronized (this.conversations) {
2422 final int size = this.conversations.size();
2423 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2424 }
2425 }
2426
2427 public boolean isConversationStillOpen(final Conversation conversation) {
2428 synchronized (this.conversations) {
2429 for (Conversation current : this.conversations) {
2430 if (current == conversation) {
2431 return true;
2432 }
2433 }
2434 }
2435 return false;
2436 }
2437
2438 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2439 return this.findOrCreateConversation(account, jid, muc, false, async);
2440 }
2441
2442 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2443 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2444 }
2445
2446 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2447 synchronized (this.conversations) {
2448 Conversation conversation = find(account, jid);
2449 if (conversation != null) {
2450 return conversation;
2451 }
2452 conversation = databaseBackend.findConversation(account, jid);
2453 final boolean loadMessagesFromDb;
2454 if (conversation != null) {
2455 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2456 conversation.setAccount(account);
2457 if (muc) {
2458 conversation.setMode(Conversation.MODE_MULTI);
2459 conversation.setContactJid(jid);
2460 } else {
2461 conversation.setMode(Conversation.MODE_SINGLE);
2462 conversation.setContactJid(jid.asBareJid());
2463 }
2464 databaseBackend.updateConversation(conversation);
2465 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2466 } else {
2467 String conversationName;
2468 Contact contact = account.getRoster().getContact(jid);
2469 if (contact != null) {
2470 conversationName = contact.getDisplayName();
2471 } else {
2472 conversationName = jid.getLocal();
2473 }
2474 if (muc) {
2475 conversation = new Conversation(conversationName, account, jid,
2476 Conversation.MODE_MULTI);
2477 } else {
2478 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2479 Conversation.MODE_SINGLE);
2480 }
2481 this.databaseBackend.createConversation(conversation);
2482 loadMessagesFromDb = false;
2483 }
2484 final Conversation c = conversation;
2485 final Runnable runnable = () -> {
2486 if (loadMessagesFromDb) {
2487 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2488 updateConversationUi();
2489 c.messagesLoaded.set(true);
2490 }
2491 if (account.getXmppConnection() != null
2492 && !c.getContact().isBlocked()
2493 && account.getXmppConnection().getFeatures().mam()
2494 && !muc) {
2495 if (query == null) {
2496 mMessageArchiveService.query(c);
2497 } else {
2498 if (query.getConversation() == null) {
2499 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2500 }
2501 }
2502 }
2503 if (joinAfterCreate) {
2504 joinMuc(c);
2505 }
2506 };
2507 if (async) {
2508 mDatabaseReaderExecutor.execute(runnable);
2509 } else {
2510 runnable.run();
2511 }
2512 this.conversations.add(conversation);
2513 updateConversationUi();
2514 return conversation;
2515 }
2516 }
2517
2518 public void archiveConversation(Conversation conversation) {
2519 archiveConversation(conversation, true);
2520 }
2521
2522 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2523 getNotificationService().clear(conversation);
2524 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2525 conversation.setNextMessage(null);
2526 synchronized (this.conversations) {
2527 getMessageArchiveService().kill(conversation);
2528 if (conversation.getMode() == Conversation.MODE_MULTI) {
2529 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2530 final Bookmark bookmark = conversation.getBookmark();
2531 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2532 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2533 Account account = bookmark.getAccount();
2534 bookmark.setConversation(null);
2535 deleteBookmark(account, bookmark);
2536 } else if (bookmark.autojoin()) {
2537 bookmark.setAutojoin(false);
2538 createBookmark(bookmark.getAccount(), bookmark);
2539 }
2540 }
2541 }
2542 leaveMuc(conversation);
2543 } else {
2544 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2545 stopPresenceUpdatesTo(conversation.getContact());
2546 }
2547 }
2548 updateConversation(conversation);
2549 this.conversations.remove(conversation);
2550 updateConversationUi();
2551 }
2552 }
2553
2554 public void stopPresenceUpdatesTo(Contact contact) {
2555 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2556 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2557 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2558 }
2559
2560 public void createAccount(final Account account) {
2561 account.initAccountServices(this);
2562 databaseBackend.createAccount(account);
2563 if (CallIntegration.hasSystemFeature(this)) {
2564 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2565 }
2566 this.accounts.add(account);
2567 this.reconnectAccountInBackground(account);
2568 updateAccountUi();
2569 syncEnabledAccountSetting();
2570 toggleForegroundService();
2571 }
2572
2573 private void syncEnabledAccountSetting() {
2574 final boolean hasEnabledAccounts = hasEnabledAccounts();
2575 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2576 toggleSetProfilePictureActivity(hasEnabledAccounts);
2577 }
2578
2579 private void toggleSetProfilePictureActivity(final boolean enabled) {
2580 try {
2581 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2582 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2583 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2584 } catch (IllegalStateException e) {
2585 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
2586 }
2587 }
2588
2589 public boolean reconfigurePushDistributor() {
2590 return this.unifiedPushBroker.reconfigurePushDistributor();
2591 }
2592
2593 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
2594 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
2595 }
2596
2597 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
2598 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
2599 }
2600
2601 private void provisionAccount(final String address, final String password) {
2602 final Jid jid = Jid.ofEscaped(address);
2603 final Account account = new Account(jid, password);
2604 account.setOption(Account.OPTION_DISABLED, true);
2605 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2606 createAccount(account);
2607 }
2608
2609 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2610 new Thread(() -> {
2611 try {
2612 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2613 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2614 if (cert == null) {
2615 callback.informUser(R.string.unable_to_parse_certificate);
2616 return;
2617 }
2618 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2619 if (info == null) {
2620 callback.informUser(R.string.certificate_does_not_contain_jid);
2621 return;
2622 }
2623 if (findAccountByJid(info.first) == null) {
2624 final Account account = new Account(info.first, "");
2625 account.setPrivateKeyAlias(alias);
2626 account.setOption(Account.OPTION_DISABLED, true);
2627 account.setOption(Account.OPTION_FIXED_USERNAME, true);
2628 account.setDisplayName(info.second);
2629 createAccount(account);
2630 callback.onAccountCreated(account);
2631 if (Config.X509_VERIFICATION) {
2632 try {
2633 getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2634 } catch (CertificateException e) {
2635 callback.informUser(R.string.certificate_chain_is_not_trusted);
2636 }
2637 }
2638 } else {
2639 callback.informUser(R.string.account_already_exists);
2640 }
2641 } catch (Exception e) {
2642 callback.informUser(R.string.unable_to_parse_certificate);
2643 }
2644 }).start();
2645
2646 }
2647
2648 public void updateKeyInAccount(final Account account, final String alias) {
2649 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2650 try {
2651 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2652 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2653 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2654 if (info == null) {
2655 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2656 return;
2657 }
2658 if (account.getJid().asBareJid().equals(info.first)) {
2659 account.setPrivateKeyAlias(alias);
2660 account.setDisplayName(info.second);
2661 databaseBackend.updateAccount(account);
2662 if (Config.X509_VERIFICATION) {
2663 try {
2664 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2665 } catch (CertificateException e) {
2666 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2667 }
2668 account.getAxolotlService().regenerateKeys(true);
2669 }
2670 } else {
2671 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2672 }
2673 } catch (Exception e) {
2674 e.printStackTrace();
2675 }
2676 }
2677
2678 public boolean updateAccount(final Account account) {
2679 if (databaseBackend.updateAccount(account)) {
2680 account.setShowErrorNotification(true);
2681 this.statusListener.onStatusChanged(account);
2682 databaseBackend.updateAccount(account);
2683 reconnectAccountInBackground(account);
2684 updateAccountUi();
2685 getNotificationService().updateErrorNotification();
2686 toggleForegroundService();
2687 syncEnabledAccountSetting();
2688 mChannelDiscoveryService.cleanCache();
2689 if (CallIntegration.hasSystemFeature(this)) {
2690 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2691 }
2692 return true;
2693 } else {
2694 return false;
2695 }
2696 }
2697
2698 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2699 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2700 sendIqPacket(account, iq, (a, packet) -> {
2701 if (packet.getType() == IqPacket.TYPE.RESULT) {
2702 a.setPassword(newPassword);
2703 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2704 databaseBackend.updateAccount(a);
2705 callback.onPasswordChangeSucceeded();
2706 } else {
2707 callback.onPasswordChangeFailed();
2708 }
2709 });
2710 }
2711
2712 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
2713 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2714 final Element query = iqPacket.addChild("query",Namespace.REGISTER);
2715 query.addChild("remove");
2716 sendIqPacket(account, iqPacket, (a, response) -> {
2717 if (response.getType() == IqPacket.TYPE.RESULT) {
2718 deleteAccount(a);
2719 callback.accept(true);
2720 } else {
2721 callback.accept(false);
2722 }
2723 });
2724 }
2725
2726 public void deleteAccount(final Account account) {
2727 final boolean connected = account.getStatus() == Account.State.ONLINE;
2728 synchronized (this.conversations) {
2729 if (connected) {
2730 account.getAxolotlService().deleteOmemoIdentity();
2731 }
2732 for (final Conversation conversation : conversations) {
2733 if (conversation.getAccount() == account) {
2734 if (conversation.getMode() == Conversation.MODE_MULTI) {
2735 if (connected) {
2736 leaveMuc(conversation);
2737 }
2738 }
2739 conversations.remove(conversation);
2740 mNotificationService.clear(conversation);
2741 }
2742 }
2743 if (account.getXmppConnection() != null) {
2744 new Thread(() -> disconnect(account, !connected)).start();
2745 }
2746 final Runnable runnable = () -> {
2747 if (!databaseBackend.deleteAccount(account)) {
2748 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2749 }
2750 };
2751 mDatabaseWriterExecutor.execute(runnable);
2752 this.accounts.remove(account);
2753 CallIntegrationConnectionService.unregisterPhoneAccount(this, account);
2754 this.mRosterSyncTaskManager.clear(account);
2755 updateAccountUi();
2756 mNotificationService.updateErrorNotification();
2757 syncEnabledAccountSetting();
2758 toggleForegroundService();
2759 }
2760 }
2761
2762 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2763 final boolean remainingListeners;
2764 synchronized (LISTENER_LOCK) {
2765 remainingListeners = checkListeners();
2766 if (!this.mOnConversationUpdates.add(listener)) {
2767 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2768 }
2769 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2770 }
2771 if (remainingListeners) {
2772 switchToForeground();
2773 }
2774 }
2775
2776 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2777 final boolean remainingListeners;
2778 synchronized (LISTENER_LOCK) {
2779 this.mOnConversationUpdates.remove(listener);
2780 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2781 remainingListeners = checkListeners();
2782 }
2783 if (remainingListeners) {
2784 switchToBackground();
2785 }
2786 }
2787
2788 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2789 final boolean remainingListeners;
2790 synchronized (LISTENER_LOCK) {
2791 remainingListeners = checkListeners();
2792 if (!this.mOnShowErrorToasts.add(listener)) {
2793 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2794 }
2795 }
2796 if (remainingListeners) {
2797 switchToForeground();
2798 }
2799 }
2800
2801 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2802 final boolean remainingListeners;
2803 synchronized (LISTENER_LOCK) {
2804 this.mOnShowErrorToasts.remove(onShowErrorToast);
2805 remainingListeners = checkListeners();
2806 }
2807 if (remainingListeners) {
2808 switchToBackground();
2809 }
2810 }
2811
2812 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2813 final boolean remainingListeners;
2814 synchronized (LISTENER_LOCK) {
2815 remainingListeners = checkListeners();
2816 if (!this.mOnAccountUpdates.add(listener)) {
2817 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2818 }
2819 }
2820 if (remainingListeners) {
2821 switchToForeground();
2822 }
2823 }
2824
2825 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2826 final boolean remainingListeners;
2827 synchronized (LISTENER_LOCK) {
2828 this.mOnAccountUpdates.remove(listener);
2829 remainingListeners = checkListeners();
2830 }
2831 if (remainingListeners) {
2832 switchToBackground();
2833 }
2834 }
2835
2836 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2837 final boolean remainingListeners;
2838 synchronized (LISTENER_LOCK) {
2839 remainingListeners = checkListeners();
2840 if (!this.mOnCaptchaRequested.add(listener)) {
2841 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2842 }
2843 }
2844 if (remainingListeners) {
2845 switchToForeground();
2846 }
2847 }
2848
2849 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2850 final boolean remainingListeners;
2851 synchronized (LISTENER_LOCK) {
2852 this.mOnCaptchaRequested.remove(listener);
2853 remainingListeners = checkListeners();
2854 }
2855 if (remainingListeners) {
2856 switchToBackground();
2857 }
2858 }
2859
2860 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2861 final boolean remainingListeners;
2862 synchronized (LISTENER_LOCK) {
2863 remainingListeners = checkListeners();
2864 if (!this.mOnRosterUpdates.add(listener)) {
2865 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2866 }
2867 }
2868 if (remainingListeners) {
2869 switchToForeground();
2870 }
2871 }
2872
2873 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2874 final boolean remainingListeners;
2875 synchronized (LISTENER_LOCK) {
2876 this.mOnRosterUpdates.remove(listener);
2877 remainingListeners = checkListeners();
2878 }
2879 if (remainingListeners) {
2880 switchToBackground();
2881 }
2882 }
2883
2884 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2885 final boolean remainingListeners;
2886 synchronized (LISTENER_LOCK) {
2887 remainingListeners = checkListeners();
2888 if (!this.mOnUpdateBlocklist.add(listener)) {
2889 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2890 }
2891 }
2892 if (remainingListeners) {
2893 switchToForeground();
2894 }
2895 }
2896
2897 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2898 final boolean remainingListeners;
2899 synchronized (LISTENER_LOCK) {
2900 this.mOnUpdateBlocklist.remove(listener);
2901 remainingListeners = checkListeners();
2902 }
2903 if (remainingListeners) {
2904 switchToBackground();
2905 }
2906 }
2907
2908 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2909 final boolean remainingListeners;
2910 synchronized (LISTENER_LOCK) {
2911 remainingListeners = checkListeners();
2912 if (!this.mOnKeyStatusUpdated.add(listener)) {
2913 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2914 }
2915 }
2916 if (remainingListeners) {
2917 switchToForeground();
2918 }
2919 }
2920
2921 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2922 final boolean remainingListeners;
2923 synchronized (LISTENER_LOCK) {
2924 this.mOnKeyStatusUpdated.remove(listener);
2925 remainingListeners = checkListeners();
2926 }
2927 if (remainingListeners) {
2928 switchToBackground();
2929 }
2930 }
2931
2932 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2933 final boolean remainingListeners;
2934 synchronized (LISTENER_LOCK) {
2935 remainingListeners = checkListeners();
2936 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
2937 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
2938 }
2939 }
2940 if (remainingListeners) {
2941 switchToForeground();
2942 }
2943 }
2944
2945 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2946 final boolean remainingListeners;
2947 synchronized (LISTENER_LOCK) {
2948 this.onJingleRtpConnectionUpdate.remove(listener);
2949 remainingListeners = checkListeners();
2950 }
2951 if (remainingListeners) {
2952 switchToBackground();
2953 }
2954 }
2955
2956 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2957 final boolean remainingListeners;
2958 synchronized (LISTENER_LOCK) {
2959 remainingListeners = checkListeners();
2960 if (!this.mOnMucRosterUpdate.add(listener)) {
2961 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2962 }
2963 }
2964 if (remainingListeners) {
2965 switchToForeground();
2966 }
2967 }
2968
2969 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2970 final boolean remainingListeners;
2971 synchronized (LISTENER_LOCK) {
2972 this.mOnMucRosterUpdate.remove(listener);
2973 remainingListeners = checkListeners();
2974 }
2975 if (remainingListeners) {
2976 switchToBackground();
2977 }
2978 }
2979
2980 public boolean checkListeners() {
2981 return (this.mOnAccountUpdates.size() == 0
2982 && this.mOnConversationUpdates.size() == 0
2983 && this.mOnRosterUpdates.size() == 0
2984 && this.mOnCaptchaRequested.size() == 0
2985 && this.mOnMucRosterUpdate.size() == 0
2986 && this.mOnUpdateBlocklist.size() == 0
2987 && this.mOnShowErrorToasts.size() == 0
2988 && this.onJingleRtpConnectionUpdate.size() == 0
2989 && this.mOnKeyStatusUpdated.size() == 0);
2990 }
2991
2992 private void switchToForeground() {
2993 toggleSoftDisabled(false);
2994 final boolean broadcastLastActivity = broadcastLastActivity();
2995 for (Conversation conversation : getConversations()) {
2996 if (conversation.getMode() == Conversation.MODE_MULTI) {
2997 conversation.getMucOptions().resetChatState();
2998 } else {
2999 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
3000 }
3001 }
3002 for (Account account : getAccounts()) {
3003 if (account.getStatus() == Account.State.ONLINE) {
3004 account.deactivateGracePeriod();
3005 final XmppConnection connection = account.getXmppConnection();
3006 if (connection != null) {
3007 if (connection.getFeatures().csi()) {
3008 connection.sendActive();
3009 }
3010 if (broadcastLastActivity) {
3011 sendPresence(account, false); //send new presence but don't include idle because we are not
3012 }
3013 }
3014 }
3015 }
3016 Log.d(Config.LOGTAG, "app switched into foreground");
3017 }
3018
3019 private void switchToBackground() {
3020 final boolean broadcastLastActivity = broadcastLastActivity();
3021 if (broadcastLastActivity) {
3022 mLastActivity = System.currentTimeMillis();
3023 final SharedPreferences.Editor editor = getPreferences().edit();
3024 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3025 editor.apply();
3026 }
3027 for (Account account : getAccounts()) {
3028 if (account.getStatus() == Account.State.ONLINE) {
3029 XmppConnection connection = account.getXmppConnection();
3030 if (connection != null) {
3031 if (broadcastLastActivity) {
3032 sendPresence(account, true);
3033 }
3034 if (connection.getFeatures().csi()) {
3035 connection.sendInactive();
3036 }
3037 }
3038 }
3039 }
3040 this.mNotificationService.setIsInForeground(false);
3041 Log.d(Config.LOGTAG, "app switched into background");
3042 }
3043
3044 private void connectMultiModeConversations(Account account) {
3045 List<Conversation> conversations = getConversations();
3046 for (Conversation conversation : conversations) {
3047 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
3048 joinMuc(conversation);
3049 }
3050 }
3051 }
3052
3053 public void mucSelfPingAndRejoin(final Conversation conversation) {
3054 final Account account = conversation.getAccount();
3055 synchronized (account.inProgressConferenceJoins) {
3056 if (account.inProgressConferenceJoins.contains(conversation)) {
3057 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
3058 return;
3059 }
3060 }
3061 synchronized (account.inProgressConferencePings) {
3062 if (!account.inProgressConferencePings.add(conversation)) {
3063 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
3064 return;
3065 }
3066 }
3067 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3068 final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
3069 ping.setTo(self);
3070 ping.addChild("ping", Namespace.PING);
3071 sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
3072 if (response.getType() == IqPacket.TYPE.ERROR) {
3073 Element error = response.findChild("error");
3074 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
3075 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
3076 } else {
3077 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
3078 joinMuc(conversation);
3079 }
3080 } else if (response.getType() == IqPacket.TYPE.RESULT) {
3081 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
3082 }
3083 synchronized (account.inProgressConferencePings) {
3084 account.inProgressConferencePings.remove(conversation);
3085 }
3086 });
3087 }
3088 public void joinMuc(Conversation conversation) {
3089 joinMuc(conversation, null, false);
3090 }
3091
3092 public void joinMuc(Conversation conversation, boolean followedInvite) {
3093 joinMuc(conversation, null, followedInvite);
3094 }
3095
3096 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3097 joinMuc(conversation, onConferenceJoined, false);
3098 }
3099
3100 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
3101 final Account account = conversation.getAccount();
3102 synchronized (account.pendingConferenceJoins) {
3103 account.pendingConferenceJoins.remove(conversation);
3104 }
3105 synchronized (account.pendingConferenceLeaves) {
3106 account.pendingConferenceLeaves.remove(conversation);
3107 }
3108 if (account.getStatus() == Account.State.ONLINE) {
3109 synchronized (account.inProgressConferenceJoins) {
3110 account.inProgressConferenceJoins.add(conversation);
3111 }
3112 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3113 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3114 }
3115 conversation.resetMucOptions();
3116 if (onConferenceJoined != null) {
3117 conversation.getMucOptions().flagNoAutoPushConfiguration();
3118 }
3119 conversation.setHasMessagesLeftOnServer(false);
3120 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
3121
3122 private void join(Conversation conversation) {
3123 Account account = conversation.getAccount();
3124 final MucOptions mucOptions = conversation.getMucOptions();
3125
3126 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
3127 synchronized (account.inProgressConferenceJoins) {
3128 account.inProgressConferenceJoins.remove(conversation);
3129 }
3130 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3131 updateConversationUi();
3132 if (onConferenceJoined != null) {
3133 onConferenceJoined.onConferenceJoined(conversation);
3134 }
3135 return;
3136 }
3137
3138 final Jid joinJid = mucOptions.getSelf().getFullJid();
3139 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
3140 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
3141 packet.setTo(joinJid);
3142 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3143 if (conversation.getMucOptions().getPassword() != null) {
3144 x.addChild("password").setContent(mucOptions.getPassword());
3145 }
3146
3147 if (mucOptions.mamSupport()) {
3148 // Use MAM instead of the limited muc history to get history
3149 x.addChild("history").setAttribute("maxchars", "0");
3150 } else {
3151 // Fallback to muc history
3152 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
3153 }
3154 sendPresencePacket(account, packet);
3155 if (onConferenceJoined != null) {
3156 onConferenceJoined.onConferenceJoined(conversation);
3157 }
3158 if (!joinJid.equals(conversation.getJid())) {
3159 conversation.setContactJid(joinJid);
3160 databaseBackend.updateConversation(conversation);
3161 }
3162
3163 if (mucOptions.mamSupport()) {
3164 getMessageArchiveService().catchupMUC(conversation);
3165 }
3166 if (mucOptions.isPrivateAndNonAnonymous()) {
3167 fetchConferenceMembers(conversation);
3168
3169 if (followedInvite) {
3170 final Bookmark bookmark = conversation.getBookmark();
3171 if (bookmark != null) {
3172 if (!bookmark.autojoin()) {
3173 bookmark.setAutojoin(true);
3174 createBookmark(account, bookmark);
3175 }
3176 } else {
3177 saveConversationAsBookmark(conversation, null);
3178 }
3179 }
3180 }
3181 synchronized (account.inProgressConferenceJoins) {
3182 account.inProgressConferenceJoins.remove(conversation);
3183 sendUnsentMessages(conversation);
3184 }
3185 }
3186
3187 @Override
3188 public void onConferenceConfigurationFetched(Conversation conversation) {
3189 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3190 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3191 return;
3192 }
3193 join(conversation);
3194 }
3195
3196 @Override
3197 public void onFetchFailed(final Conversation conversation, final String errorCondition) {
3198 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3199 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3200 return;
3201 }
3202 if ("remote-server-not-found".equals(errorCondition)) {
3203 synchronized (account.inProgressConferenceJoins) {
3204 account.inProgressConferenceJoins.remove(conversation);
3205 }
3206 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
3207 updateConversationUi();
3208 } else {
3209 join(conversation);
3210 fetchConferenceConfiguration(conversation);
3211 }
3212 }
3213 });
3214 updateConversationUi();
3215 } else {
3216 synchronized (account.pendingConferenceJoins) {
3217 account.pendingConferenceJoins.add(conversation);
3218 }
3219 conversation.resetMucOptions();
3220 conversation.setHasMessagesLeftOnServer(false);
3221 updateConversationUi();
3222 }
3223 }
3224
3225 private void fetchConferenceMembers(final Conversation conversation) {
3226 final Account account = conversation.getAccount();
3227 final AxolotlService axolotlService = account.getAxolotlService();
3228 final String[] affiliations = {"member", "admin", "owner"};
3229 OnIqPacketReceived callback = new OnIqPacketReceived() {
3230
3231 private int i = 0;
3232 private boolean success = true;
3233
3234 @Override
3235 public void onIqPacketReceived(Account account, IqPacket packet) {
3236 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3237 Element query = packet.query("http://jabber.org/protocol/muc#admin");
3238 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
3239 for (Element child : query.getChildren()) {
3240 if ("item".equals(child.getName())) {
3241 MucOptions.User user = AbstractParser.parseItem(conversation, child);
3242 if (!user.realJidMatchesAccount()) {
3243 boolean isNew = conversation.getMucOptions().updateUser(user);
3244 Contact contact = user.getContact();
3245 if (omemoEnabled
3246 && isNew
3247 && user.getRealJid() != null
3248 && (contact == null || !contact.mutualPresenceSubscription())
3249 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3250 axolotlService.fetchDeviceIds(user.getRealJid());
3251 }
3252 }
3253 }
3254 }
3255 } else {
3256 success = false;
3257 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
3258 }
3259 ++i;
3260 if (i >= affiliations.length) {
3261 List<Jid> members = conversation.getMucOptions().getMembers(true);
3262 if (success) {
3263 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3264 boolean changed = false;
3265 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3266 Jid jid = iterator.next();
3267 if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3268 iterator.remove();
3269 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3270 changed = true;
3271 }
3272 }
3273 if (changed) {
3274 conversation.setAcceptedCryptoTargets(cryptoTargets);
3275 updateConversation(conversation);
3276 }
3277 }
3278 getAvatarService().clear(conversation);
3279 updateMucRosterUi();
3280 updateConversationUi();
3281 }
3282 }
3283 };
3284 for (String affiliation : affiliations) {
3285 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3286 }
3287 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3288 }
3289
3290 public void providePasswordForMuc(Conversation conversation, String password) {
3291 if (conversation.getMode() == Conversation.MODE_MULTI) {
3292 conversation.getMucOptions().setPassword(password);
3293 if (conversation.getBookmark() != null) {
3294 final Bookmark bookmark = conversation.getBookmark();
3295 if (synchronizeWithBookmarks()) {
3296 bookmark.setAutojoin(true);
3297 }
3298 createBookmark(conversation.getAccount(), bookmark);
3299 }
3300 updateConversation(conversation);
3301 joinMuc(conversation);
3302 }
3303 }
3304
3305 public void deleteAvatar(final Account account) {
3306 final AtomicBoolean executed = new AtomicBoolean(false);
3307 final Runnable onDeleted =
3308 () -> {
3309 if (executed.compareAndSet(false, true)) {
3310 account.setAvatar(null);
3311 databaseBackend.updateAccount(account);
3312 getAvatarService().clear(account);
3313 updateAccountUi();
3314 }
3315 };
3316 deleteVcardAvatar(account, onDeleted);
3317 deletePepNode(account, Namespace.AVATAR_DATA);
3318 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3319 }
3320
3321 public void deletePepNode(final Account account, final String node) {
3322 deletePepNode(account, node, null);
3323 }
3324
3325 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3326 final IqPacket request = mIqGenerator.deleteNode(node);
3327 sendIqPacket(account, request, (a, packet) -> {
3328 if (packet.getType() == IqPacket.TYPE.RESULT) {
3329 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": successfully deleted pep node "+node);
3330 if (runnable != null) {
3331 runnable.run();
3332 }
3333 } else {
3334 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": failed to delete "+ packet);
3335 }
3336 });
3337 }
3338
3339 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3340 final IqPacket retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3341 sendIqPacket(account, retrieveVcard, (a, response) -> {
3342 if (response.getType() != IqPacket.TYPE.RESULT) {
3343 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3344 return;
3345 }
3346 final Element vcard = response.findChild("vCard", "vcard-temp");
3347 if (vcard == null) {
3348 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3349 return;
3350 }
3351 Element photo = vcard.findChild("PHOTO");
3352 if (photo == null) {
3353 photo = vcard.addChild("PHOTO");
3354 }
3355 photo.clearChildren();
3356 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3357 publication.setTo(a.getJid().asBareJid());
3358 publication.addChild(vcard);
3359 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3360 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3361 Log.d(Config.LOGTAG,a1.getJid().asBareJid()+": successfully deleted vcard avatar");
3362 runnable.run();
3363 } else {
3364 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3365 }
3366 });
3367 });
3368 }
3369
3370 private boolean hasEnabledAccounts() {
3371 if (this.accounts == null) {
3372 return false;
3373 }
3374 for (final Account account : this.accounts) {
3375 if (account.isConnectionEnabled()) {
3376 return true;
3377 }
3378 }
3379 return false;
3380 }
3381
3382
3383 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3384 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3385 }
3386
3387 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3388 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3389 }
3390
3391
3392 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3393 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3394 }
3395
3396 public void persistSelfNick(final MucOptions.User self) {
3397 final Conversation conversation = self.getConversation();
3398 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3399 Jid full = self.getFullJid();
3400 if (!full.equals(conversation.getJid())) {
3401 Log.d(Config.LOGTAG, "nick changed. updating");
3402 conversation.setContactJid(full);
3403 databaseBackend.updateConversation(conversation);
3404 }
3405
3406 final Bookmark bookmark = conversation.getBookmark();
3407 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3408 if (bookmark != null && (tookProposedNickFromBookmark || Strings.isNullOrEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
3409 final Account account = conversation.getAccount();
3410 final String defaultNick = MucOptions.defaultNick(account);
3411 if (Strings.isNullOrEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3412 return;
3413 }
3414 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
3415 bookmark.setNick(full.getResource());
3416 createBookmark(bookmark.getAccount(), bookmark);
3417 }
3418 }
3419
3420 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3421 final MucOptions options = conversation.getMucOptions();
3422 final Jid joinJid = options.createJoinJid(nick);
3423 if (joinJid == null) {
3424 return false;
3425 }
3426 if (options.online()) {
3427 Account account = conversation.getAccount();
3428 options.setOnRenameListener(new OnRenameListener() {
3429
3430 @Override
3431 public void onSuccess() {
3432 callback.success(conversation);
3433 }
3434
3435 @Override
3436 public void onFailure() {
3437 callback.error(R.string.nick_in_use, conversation);
3438 }
3439 });
3440
3441 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
3442 packet.setTo(joinJid);
3443 sendPresencePacket(account, packet);
3444 } else {
3445 conversation.setContactJid(joinJid);
3446 databaseBackend.updateConversation(conversation);
3447 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3448 Bookmark bookmark = conversation.getBookmark();
3449 if (bookmark != null) {
3450 bookmark.setNick(nick);
3451 createBookmark(bookmark.getAccount(), bookmark);
3452 }
3453 joinMuc(conversation);
3454 }
3455 }
3456 return true;
3457 }
3458
3459 public void leaveMuc(Conversation conversation) {
3460 leaveMuc(conversation, false);
3461 }
3462
3463 private void leaveMuc(Conversation conversation, boolean now) {
3464 final Account account = conversation.getAccount();
3465 synchronized (account.pendingConferenceJoins) {
3466 account.pendingConferenceJoins.remove(conversation);
3467 }
3468 synchronized (account.pendingConferenceLeaves) {
3469 account.pendingConferenceLeaves.remove(conversation);
3470 }
3471 if (account.getStatus() == Account.State.ONLINE || now) {
3472 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3473 conversation.getMucOptions().setOffline();
3474 Bookmark bookmark = conversation.getBookmark();
3475 if (bookmark != null) {
3476 bookmark.setConversation(null);
3477 }
3478 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3479 } else {
3480 synchronized (account.pendingConferenceLeaves) {
3481 account.pendingConferenceLeaves.add(conversation);
3482 }
3483 }
3484 }
3485
3486 public String findConferenceServer(final Account account) {
3487 String server;
3488 if (account.getXmppConnection() != null) {
3489 server = account.getXmppConnection().getMucServer();
3490 if (server != null) {
3491 return server;
3492 }
3493 }
3494 for (Account other : getAccounts()) {
3495 if (other != account && other.getXmppConnection() != null) {
3496 server = other.getXmppConnection().getMucServer();
3497 if (server != null) {
3498 return server;
3499 }
3500 }
3501 }
3502 return null;
3503 }
3504
3505
3506 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3507 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3508 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3509 if (!TextUtils.isEmpty(name)) {
3510 configuration.putString("muc#roomconfig_roomname", name);
3511 }
3512 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3513 @Override
3514 public void onPushSucceeded() {
3515 saveConversationAsBookmark(conversation, name);
3516 callback.success(conversation);
3517 }
3518
3519 @Override
3520 public void onPushFailed() {
3521 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3522 callback.error(R.string.unable_to_set_channel_configuration, conversation);
3523 } else {
3524 callback.error(R.string.joined_an_existing_channel, conversation);
3525 }
3526 }
3527 });
3528 });
3529 }
3530
3531 public boolean createAdhocConference(final Account account,
3532 final String name,
3533 final Iterable<Jid> jids,
3534 final UiCallback<Conversation> callback) {
3535 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3536 if (account.getStatus() == Account.State.ONLINE) {
3537 try {
3538 String server = findConferenceServer(account);
3539 if (server == null) {
3540 if (callback != null) {
3541 callback.error(R.string.no_conference_server_found, null);
3542 }
3543 return false;
3544 }
3545 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
3546 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3547 joinMuc(conversation, new OnConferenceJoined() {
3548 @Override
3549 public void onConferenceJoined(final Conversation conversation) {
3550 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3551 if (!TextUtils.isEmpty(name)) {
3552 configuration.putString("muc#roomconfig_roomname", name);
3553 }
3554 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3555 @Override
3556 public void onPushSucceeded() {
3557 for (Jid invite : jids) {
3558 invite(conversation, invite);
3559 }
3560 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3561 Jid other = account.getJid().withResource(resource);
3562 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3563 directInvite(conversation, other);
3564 }
3565 saveConversationAsBookmark(conversation, name);
3566 if (callback != null) {
3567 callback.success(conversation);
3568 }
3569 }
3570
3571 @Override
3572 public void onPushFailed() {
3573 archiveConversation(conversation);
3574 if (callback != null) {
3575 callback.error(R.string.conference_creation_failed, conversation);
3576 }
3577 }
3578 });
3579 }
3580 });
3581 return true;
3582 } catch (IllegalArgumentException e) {
3583 if (callback != null) {
3584 callback.error(R.string.conference_creation_failed, null);
3585 }
3586 return false;
3587 }
3588 } else {
3589 if (callback != null) {
3590 callback.error(R.string.not_connected_try_again, null);
3591 }
3592 return false;
3593 }
3594 }
3595
3596 public void fetchConferenceConfiguration(final Conversation conversation) {
3597 fetchConferenceConfiguration(conversation, null);
3598 }
3599
3600 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3601 IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3602 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3603 @Override
3604 public void onIqPacketReceived(Account account, IqPacket packet) {
3605 if (packet.getType() == IqPacket.TYPE.RESULT) {
3606 final MucOptions mucOptions = conversation.getMucOptions();
3607 final Bookmark bookmark = conversation.getBookmark();
3608 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3609
3610 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3611 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3612 updateConversation(conversation);
3613 }
3614
3615 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3616 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3617 createBookmark(account, bookmark);
3618 }
3619 }
3620
3621
3622 if (callback != null) {
3623 callback.onConferenceConfigurationFetched(conversation);
3624 }
3625
3626
3627 updateConversationUi();
3628 } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3629 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3630 } else {
3631 if (callback != null) {
3632 callback.onFetchFailed(conversation, packet.getErrorCondition());
3633 }
3634 }
3635 }
3636 });
3637 }
3638
3639 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3640 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3641 }
3642
3643 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3644 Log.d(Config.LOGTAG, "pushing node configuration");
3645 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3646 @Override
3647 public void onIqPacketReceived(Account account, IqPacket packet) {
3648 if (packet.getType() == IqPacket.TYPE.RESULT) {
3649 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3650 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3651 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3652 if (x != null) {
3653 Data data = Data.parse(x);
3654 data.submit(options);
3655 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3656 @Override
3657 public void onIqPacketReceived(Account account, IqPacket packet) {
3658 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3659 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3660 callback.onPushSucceeded();
3661 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3662 callback.onPushFailed();
3663 }
3664 }
3665 });
3666 } else if (callback != null) {
3667 callback.onPushFailed();
3668 }
3669 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3670 callback.onPushFailed();
3671 }
3672 }
3673 });
3674 }
3675
3676 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3677 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3678 conversation.setAttribute("accept_non_anonymous", true);
3679 updateConversation(conversation);
3680 }
3681 if (options.containsKey("muc#roomconfig_moderatedroom")) {
3682 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3683 options.putString("members_by_default", moderated ? "0" : "1");
3684 }
3685 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3686 request.setTo(conversation.getJid().asBareJid());
3687 request.query("http://jabber.org/protocol/muc#owner");
3688 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3689 @Override
3690 public void onIqPacketReceived(Account account, IqPacket packet) {
3691 if (packet.getType() == IqPacket.TYPE.RESULT) {
3692 final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3693 data.submit(options);
3694 final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3695 set.setTo(conversation.getJid().asBareJid());
3696 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3697 sendIqPacket(account, set, new OnIqPacketReceived() {
3698 @Override
3699 public void onIqPacketReceived(Account account, IqPacket packet) {
3700 if (callback != null) {
3701 if (packet.getType() == IqPacket.TYPE.RESULT) {
3702 callback.onPushSucceeded();
3703 } else {
3704 callback.onPushFailed();
3705 }
3706 }
3707 }
3708 });
3709 } else {
3710 if (callback != null) {
3711 callback.onPushFailed();
3712 }
3713 }
3714 }
3715 });
3716 }
3717
3718 public void pushSubjectToConference(final Conversation conference, final String subject) {
3719 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3720 this.sendMessagePacket(conference.getAccount(), packet);
3721 }
3722
3723 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3724 final Jid jid = user.asBareJid();
3725 final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3726 sendIqPacket(conference.getAccount(), request, (account, response) -> {
3727 if (response.getType() == IqPacket.TYPE.RESULT) {
3728 conference.getMucOptions().changeAffiliation(jid, affiliation);
3729 getAvatarService().clear(conference);
3730 if (callback != null) {
3731 callback.onAffiliationChangedSuccessful(jid);
3732 } else {
3733 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3734 }
3735 } else if (callback != null) {
3736 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3737 } else {
3738 Log.d(Config.LOGTAG, "unable to change affiliation");
3739 }
3740 });
3741 }
3742
3743 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3744 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3745 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3746 if (packet.getType() != IqPacket.TYPE.RESULT) {
3747 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3748 }
3749 });
3750 }
3751
3752 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3753 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3754 request.setTo(conversation.getJid().asBareJid());
3755 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3756 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3757 @Override
3758 public void onIqPacketReceived(Account account, IqPacket packet) {
3759 if (packet.getType() == IqPacket.TYPE.RESULT) {
3760 if (callback != null) {
3761 callback.onRoomDestroySucceeded();
3762 }
3763 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3764 if (callback != null) {
3765 callback.onRoomDestroyFailed();
3766 }
3767 }
3768 }
3769 });
3770 }
3771
3772 private void disconnect(final Account account, boolean force) {
3773 final XmppConnection connection = account.getXmppConnection();
3774 if (connection == null) {
3775 return;
3776 }
3777 if (!force) {
3778 final List<Conversation> conversations = getConversations();
3779 for (Conversation conversation : conversations) {
3780 if (conversation.getAccount() == account) {
3781 if (conversation.getMode() == Conversation.MODE_MULTI) {
3782 leaveMuc(conversation, true);
3783 }
3784 }
3785 }
3786 sendOfflinePresence(account);
3787 }
3788 connection.disconnect(force);
3789 }
3790
3791 @Override
3792 public IBinder onBind(Intent intent) {
3793 return mBinder;
3794 }
3795
3796 public void updateMessage(Message message) {
3797 updateMessage(message, true);
3798 }
3799
3800 public void updateMessage(Message message, boolean includeBody) {
3801 databaseBackend.updateMessage(message, includeBody);
3802 updateConversationUi();
3803 }
3804
3805 public void createMessageAsync(final Message message) {
3806 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3807 }
3808
3809 public void updateMessage(Message message, String uuid) {
3810 if (!databaseBackend.updateMessage(message, uuid)) {
3811 Log.e(Config.LOGTAG, "error updated message in DB after edit");
3812 }
3813 updateConversationUi();
3814 }
3815
3816 protected void syncDirtyContacts(Account account) {
3817 for (Contact contact : account.getRoster().getContacts()) {
3818 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3819 pushContactToServer(contact);
3820 }
3821 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3822 deleteContactOnServer(contact);
3823 }
3824 }
3825 }
3826
3827 public void createContact(final Contact contact, final boolean autoGrant) {
3828 createContact(contact, autoGrant, null);
3829 }
3830
3831 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3832 if (autoGrant) {
3833 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3834 contact.setOption(Contact.Options.ASKING);
3835 }
3836 pushContactToServer(contact, preAuth);
3837 }
3838
3839 public void pushContactToServer(final Contact contact) {
3840 pushContactToServer(contact, null);
3841 }
3842
3843 private void pushContactToServer(final Contact contact, final String preAuth) {
3844 contact.resetOption(Contact.Options.DIRTY_DELETE);
3845 contact.setOption(Contact.Options.DIRTY_PUSH);
3846 final Account account = contact.getAccount();
3847 if (account.getStatus() == Account.State.ONLINE) {
3848 final boolean ask = contact.getOption(Contact.Options.ASKING);
3849 final boolean sendUpdates = contact
3850 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3851 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3852 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3853 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3854 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3855 if (sendUpdates) {
3856 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3857 }
3858 if (ask) {
3859 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3860 }
3861 } else {
3862 syncRoster(contact.getAccount());
3863 }
3864 }
3865
3866 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3867 new Thread(() -> {
3868 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3869 final int size = Config.AVATAR_SIZE;
3870 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3871 if (avatar != null) {
3872 if (!getFileBackend().save(avatar)) {
3873 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3874 return;
3875 }
3876 avatar.owner = conversation.getJid().asBareJid();
3877 publishMucAvatar(conversation, avatar, callback);
3878 } else {
3879 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3880 }
3881 }).start();
3882 }
3883
3884 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3885 new Thread(() -> {
3886 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3887 final int size = Config.AVATAR_SIZE;
3888 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3889 if (avatar != null) {
3890 if (!getFileBackend().save(avatar)) {
3891 Log.d(Config.LOGTAG, "unable to save vcard");
3892 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3893 return;
3894 }
3895 publishAvatar(account, avatar, callback);
3896 } else {
3897 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3898 }
3899 }).start();
3900
3901 }
3902
3903 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3904 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3905 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3906 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3907 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3908 Element vcard = response.findChild("vCard", "vcard-temp");
3909 if (vcard == null) {
3910 vcard = new Element("vCard", "vcard-temp");
3911 }
3912 Element photo = vcard.findChild("PHOTO");
3913 if (photo == null) {
3914 photo = vcard.addChild("PHOTO");
3915 }
3916 photo.clearChildren();
3917 photo.addChild("TYPE").setContent(avatar.type);
3918 photo.addChild("BINVAL").setContent(avatar.image);
3919 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3920 publication.setTo(conversation.getJid().asBareJid());
3921 publication.addChild(vcard);
3922 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3923 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3924 callback.onAvatarPublicationSucceeded();
3925 } else {
3926 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3927 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3928 }
3929 });
3930 } else {
3931 Log.d(Config.LOGTAG, "failed to request vcard " + response);
3932 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3933 }
3934 });
3935 }
3936
3937 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3938 final Bundle options;
3939 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3940 options = PublishOptions.openAccess();
3941 } else {
3942 options = null;
3943 }
3944 publishAvatar(account, avatar, options, true, callback);
3945 }
3946
3947 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3948 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3949 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3950 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3951
3952 @Override
3953 public void onIqPacketReceived(Account account, IqPacket result) {
3954 if (result.getType() == IqPacket.TYPE.RESULT) {
3955 publishAvatarMetadata(account, avatar, options, true, callback);
3956 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3957 pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
3958 @Override
3959 public void onPushSucceeded() {
3960 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3961 publishAvatar(account, avatar, options, false, callback);
3962 }
3963
3964 @Override
3965 public void onPushFailed() {
3966 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3967 publishAvatar(account, avatar, null, false, callback);
3968 }
3969 });
3970 } else {
3971 Element error = result.findChild("error");
3972 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3973 if (callback != null) {
3974 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3975 }
3976 }
3977 }
3978 });
3979 }
3980
3981 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3982 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3983 sendIqPacket(account, packet, new OnIqPacketReceived() {
3984 @Override
3985 public void onIqPacketReceived(Account account, IqPacket result) {
3986 if (result.getType() == IqPacket.TYPE.RESULT) {
3987 if (account.setAvatar(avatar.getFilename())) {
3988 getAvatarService().clear(account);
3989 databaseBackend.updateAccount(account);
3990 notifyAccountAvatarHasChanged(account);
3991 }
3992 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3993 if (callback != null) {
3994 callback.onAvatarPublicationSucceeded();
3995 }
3996 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3997 pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
3998 @Override
3999 public void onPushSucceeded() {
4000 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
4001 publishAvatarMetadata(account, avatar, options, false, callback);
4002 }
4003
4004 @Override
4005 public void onPushFailed() {
4006 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
4007 publishAvatarMetadata(account, avatar, null, false, callback);
4008 }
4009 });
4010 } else {
4011 if (callback != null) {
4012 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4013 }
4014 }
4015 }
4016 });
4017 }
4018
4019 public void republishAvatarIfNeeded(Account account) {
4020 if (account.getAxolotlService().isPepBroken()) {
4021 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
4022 return;
4023 }
4024 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4025 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4026
4027 private Avatar parseAvatar(IqPacket packet) {
4028 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4029 if (pubsub != null) {
4030 Element items = pubsub.findChild("items");
4031 if (items != null) {
4032 return Avatar.parseMetadata(items);
4033 }
4034 }
4035 return null;
4036 }
4037
4038 private boolean errorIsItemNotFound(IqPacket packet) {
4039 Element error = packet.findChild("error");
4040 return packet.getType() == IqPacket.TYPE.ERROR
4041 && error != null
4042 && error.hasChild("item-not-found");
4043 }
4044
4045 @Override
4046 public void onIqPacketReceived(Account account, IqPacket packet) {
4047 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
4048 Avatar serverAvatar = parseAvatar(packet);
4049 if (serverAvatar == null && account.getAvatar() != null) {
4050 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4051 if (avatar != null) {
4052 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
4053 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
4054 } else {
4055 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
4056 }
4057 }
4058 }
4059 }
4060 });
4061 }
4062
4063 public void fetchAvatar(Account account, Avatar avatar) {
4064 fetchAvatar(account, avatar, null);
4065 }
4066
4067 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4068 final String KEY = generateFetchKey(account, avatar);
4069 synchronized (this.mInProgressAvatarFetches) {
4070 if (mInProgressAvatarFetches.add(KEY)) {
4071 switch (avatar.origin) {
4072 case PEP:
4073 this.mInProgressAvatarFetches.add(KEY);
4074 fetchAvatarPep(account, avatar, callback);
4075 break;
4076 case VCARD:
4077 this.mInProgressAvatarFetches.add(KEY);
4078 fetchAvatarVcard(account, avatar, callback);
4079 break;
4080 }
4081 } else if (avatar.origin == Avatar.Origin.PEP) {
4082 mOmittedPepAvatarFetches.add(KEY);
4083 } else {
4084 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
4085 }
4086 }
4087 }
4088
4089 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4090 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
4091 sendIqPacket(account, packet, (a, result) -> {
4092 synchronized (mInProgressAvatarFetches) {
4093 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
4094 }
4095 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
4096 if (result.getType() == IqPacket.TYPE.RESULT) {
4097 avatar.image = mIqParser.avatarData(result);
4098 if (avatar.image != null) {
4099 if (getFileBackend().save(avatar)) {
4100 if (a.getJid().asBareJid().equals(avatar.owner)) {
4101 if (a.setAvatar(avatar.getFilename())) {
4102 databaseBackend.updateAccount(a);
4103 }
4104 getAvatarService().clear(a);
4105 updateConversationUi();
4106 updateAccountUi();
4107 } else {
4108 final Contact contact = a.getRoster().getContact(avatar.owner);
4109 contact.setAvatar(avatar);
4110 syncRoster(account);
4111 getAvatarService().clear(contact);
4112 updateConversationUi();
4113 updateRosterUi();
4114 }
4115 if (callback != null) {
4116 callback.success(avatar);
4117 }
4118 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
4119 return;
4120 }
4121 } else {
4122
4123 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4124 }
4125 } else {
4126 Element error = result.findChild("error");
4127 if (error == null) {
4128 Log.d(Config.LOGTAG, ERROR + "(server error)");
4129 } else {
4130 Log.d(Config.LOGTAG, ERROR + error.toString());
4131 }
4132 }
4133 if (callback != null) {
4134 callback.error(0, null);
4135 }
4136
4137 });
4138 }
4139
4140 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4141 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4142 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4143 @Override
4144 public void onIqPacketReceived(Account account, IqPacket packet) {
4145 final boolean previouslyOmittedPepFetch;
4146 synchronized (mInProgressAvatarFetches) {
4147 final String KEY = generateFetchKey(account, avatar);
4148 mInProgressAvatarFetches.remove(KEY);
4149 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4150 }
4151 if (packet.getType() == IqPacket.TYPE.RESULT) {
4152 Element vCard = packet.findChild("vCard", "vcard-temp");
4153 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4154 String image = photo != null ? photo.findChildContent("BINVAL") : null;
4155 if (image != null) {
4156 avatar.image = image;
4157 if (getFileBackend().save(avatar)) {
4158 Log.d(Config.LOGTAG, account.getJid().asBareJid()
4159 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4160 if (avatar.owner.isBareJid()) {
4161 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4162 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4163 account.setAvatar(avatar.getFilename());
4164 databaseBackend.updateAccount(account);
4165 getAvatarService().clear(account);
4166 updateAccountUi();
4167 } else {
4168 final Contact contact = account.getRoster().getContact(avatar.owner);
4169 contact.setAvatar(avatar, previouslyOmittedPepFetch);
4170 syncRoster(account);
4171 getAvatarService().clear(contact);
4172 updateRosterUi();
4173 }
4174 updateConversationUi();
4175 } else {
4176 Conversation conversation = find(account, avatar.owner.asBareJid());
4177 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4178 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4179 if (user != null) {
4180 if (user.setAvatar(avatar)) {
4181 getAvatarService().clear(user);
4182 updateConversationUi();
4183 updateMucRosterUi();
4184 }
4185 if (user.getRealJid() != null) {
4186 Contact contact = account.getRoster().getContact(user.getRealJid());
4187 contact.setAvatar(avatar);
4188 syncRoster(account);
4189 getAvatarService().clear(contact);
4190 updateRosterUi();
4191 }
4192 }
4193 }
4194 }
4195 }
4196 }
4197 }
4198 }
4199 });
4200 }
4201
4202 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
4203 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4204 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4205
4206 @Override
4207 public void onIqPacketReceived(Account account, IqPacket packet) {
4208 if (packet.getType() == IqPacket.TYPE.RESULT) {
4209 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4210 if (pubsub != null) {
4211 Element items = pubsub.findChild("items");
4212 if (items != null) {
4213 Avatar avatar = Avatar.parseMetadata(items);
4214 if (avatar != null) {
4215 avatar.owner = account.getJid().asBareJid();
4216 if (fileBackend.isAvatarCached(avatar)) {
4217 if (account.setAvatar(avatar.getFilename())) {
4218 databaseBackend.updateAccount(account);
4219 }
4220 getAvatarService().clear(account);
4221 callback.success(avatar);
4222 } else {
4223 fetchAvatarPep(account, avatar, callback);
4224 }
4225 return;
4226 }
4227 }
4228 }
4229 }
4230 callback.error(0, null);
4231 }
4232 });
4233 }
4234
4235 public void notifyAccountAvatarHasChanged(final Account account) {
4236 final XmppConnection connection = account.getXmppConnection();
4237 if (connection != null && connection.getFeatures().bookmarksConversion()) {
4238 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4239 for (Conversation conversation : conversations) {
4240 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4241 final MucOptions mucOptions = conversation.getMucOptions();
4242 if (mucOptions.online()) {
4243 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
4244 packet.setTo(mucOptions.getSelf().getFullJid());
4245 connection.sendPresencePacket(packet);
4246 }
4247 }
4248 }
4249 }
4250 }
4251
4252 public void deleteContactOnServer(Contact contact) {
4253 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4254 contact.resetOption(Contact.Options.DIRTY_PUSH);
4255 contact.setOption(Contact.Options.DIRTY_DELETE);
4256 Account account = contact.getAccount();
4257 if (account.getStatus() == Account.State.ONLINE) {
4258 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4259 Element item = iq.query(Namespace.ROSTER).addChild("item");
4260 item.setAttribute("jid", contact.getJid());
4261 item.setAttribute("subscription", "remove");
4262 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4263 }
4264 }
4265
4266 public void updateConversation(final Conversation conversation) {
4267 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4268 }
4269
4270 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4271 synchronized (account) {
4272 final XmppConnection existingConnection = account.getXmppConnection();
4273 final XmppConnection connection;
4274 if (existingConnection != null) {
4275 connection = existingConnection;
4276 } else if (account.isConnectionEnabled()) {
4277 connection = createConnection(account);
4278 account.setXmppConnection(connection);
4279 } else {
4280 return;
4281 }
4282 final boolean hasInternet = hasInternetConnection();
4283 if (account.isConnectionEnabled() && hasInternet) {
4284 if (!force) {
4285 disconnect(account, false);
4286 }
4287 Thread thread = new Thread(connection);
4288 connection.setInteractive(interactive);
4289 connection.prepareNewConnection();
4290 connection.interrupt();
4291 thread.start();
4292 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4293 } else {
4294 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4295 account.getRoster().clearPresences();
4296 connection.resetEverything();
4297 final AxolotlService axolotlService = account.getAxolotlService();
4298 if (axolotlService != null) {
4299 axolotlService.resetBrokenness();
4300 }
4301 if (!hasInternet) {
4302 account.setStatus(Account.State.NO_INTERNET);
4303 }
4304 }
4305 }
4306 }
4307
4308 public void reconnectAccountInBackground(final Account account) {
4309 new Thread(() -> reconnectAccount(account, false, true)).start();
4310 }
4311
4312 public void invite(final Conversation conversation, final Jid contact) {
4313 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4314 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4315 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4316 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4317 }
4318 final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4319 sendMessagePacket(conversation.getAccount(), packet);
4320 }
4321
4322 public void directInvite(Conversation conversation, Jid jid) {
4323 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4324 sendMessagePacket(conversation.getAccount(), packet);
4325 }
4326
4327 public void resetSendingToWaiting(Account account) {
4328 for (Conversation conversation : getConversations()) {
4329 if (conversation.getAccount() == account) {
4330 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4331 }
4332 }
4333 }
4334
4335 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4336 return markMessage(account, recipient, uuid, status, null);
4337 }
4338
4339 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4340 if (uuid == null) {
4341 return null;
4342 }
4343 for (Conversation conversation : getConversations()) {
4344 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4345 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4346 if (message != null) {
4347 markMessage(message, status, errorMessage);
4348 }
4349 return message;
4350 }
4351 }
4352 return null;
4353 }
4354
4355 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4356 return markMessage(conversation, uuid, status, serverMessageId, null);
4357 }
4358
4359 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4360 if (uuid == null) {
4361 return false;
4362 } else {
4363 final Message message = conversation.findSentMessageWithUuid(uuid);
4364 if (message != null) {
4365 if (message.getServerMsgId() == null) {
4366 message.setServerMsgId(serverMessageId);
4367 }
4368 if (message.getEncryption() == Message.ENCRYPTION_NONE
4369 && message.isTypeText()
4370 && isBodyModified(message, body)) {
4371 message.setBody(body.content);
4372 if (body.count > 1) {
4373 message.setBodyLanguage(body.language);
4374 }
4375 markMessage(message, status, null, true);
4376 } else {
4377 markMessage(message, status);
4378 }
4379 return true;
4380 } else {
4381 return false;
4382 }
4383 }
4384 }
4385
4386 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4387 if (body == null || body.content == null) {
4388 return false;
4389 }
4390 return !body.content.equals(message.getBody());
4391 }
4392
4393 public void markMessage(Message message, int status) {
4394 markMessage(message, status, null);
4395 }
4396
4397
4398 public void markMessage(final Message message, final int status, final String errorMessage) {
4399 markMessage(message, status, errorMessage, false);
4400 }
4401
4402 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4403 final int oldStatus = message.getStatus();
4404 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4405 return;
4406 }
4407 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4408 return;
4409 }
4410 message.setErrorMessage(errorMessage);
4411 message.setStatus(status);
4412 databaseBackend.updateMessage(message, includeBody);
4413 updateConversationUi();
4414 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4415 mNotificationService.pushFailedDelivery(message);
4416 }
4417 }
4418
4419 private SharedPreferences getPreferences() {
4420 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4421 }
4422
4423 public long getAutomaticMessageDeletionDate() {
4424 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4425 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4426 }
4427
4428 public long getLongPreference(String name, @IntegerRes int res) {
4429 long defaultValue = getResources().getInteger(res);
4430 try {
4431 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4432 } catch (NumberFormatException e) {
4433 return defaultValue;
4434 }
4435 }
4436
4437 public boolean getBooleanPreference(String name, @BoolRes int res) {
4438 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4439 }
4440
4441 public boolean confirmMessages() {
4442 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4443 }
4444
4445 public boolean allowMessageCorrection() {
4446 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4447 }
4448
4449 public boolean sendChatStates() {
4450 return getBooleanPreference("chat_states", R.bool.chat_states);
4451 }
4452
4453 private boolean synchronizeWithBookmarks() {
4454 return getBooleanPreference("autojoin", R.bool.autojoin);
4455 }
4456
4457 public boolean useTorToConnect() {
4458 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
4459 }
4460
4461 public boolean showExtendedConnectionOptions() {
4462 return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4463 }
4464
4465 public boolean broadcastLastActivity() {
4466 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4467 }
4468
4469 public int unreadCount() {
4470 int count = 0;
4471 for (Conversation conversation : getConversations()) {
4472 count += conversation.unreadCount();
4473 }
4474 return count;
4475 }
4476
4477
4478 private <T> List<T> threadSafeList(Set<T> set) {
4479 synchronized (LISTENER_LOCK) {
4480 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4481 }
4482 }
4483
4484 public void showErrorToastInUi(int resId) {
4485 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4486 listener.onShowErrorToast(resId);
4487 }
4488 }
4489
4490 public void updateConversationUi() {
4491 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4492 listener.onConversationUpdate();
4493 }
4494 }
4495
4496 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4497 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4498 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4499 }
4500 }
4501
4502 public void notifyJingleRtpConnectionUpdate(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices) {
4503 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4504 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4505 }
4506 }
4507
4508 public void updateAccountUi() {
4509 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4510 listener.onAccountUpdate();
4511 }
4512 }
4513
4514 public void updateRosterUi() {
4515 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4516 listener.onRosterUpdate();
4517 }
4518 }
4519
4520 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4521 if (mOnCaptchaRequested.size() > 0) {
4522 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4523 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4524 (int) (captcha.getHeight() * metrics.scaledDensity), false);
4525 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4526 listener.onCaptchaRequested(account, id, data, scaled);
4527 }
4528 return true;
4529 }
4530 return false;
4531 }
4532
4533 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4534 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4535 listener.OnUpdateBlocklist(status);
4536 }
4537 }
4538
4539 public void updateMucRosterUi() {
4540 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4541 listener.onMucRosterUpdate();
4542 }
4543 }
4544
4545 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4546 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4547 listener.onKeyStatusUpdated(report);
4548 }
4549 }
4550
4551 public Account findAccountByJid(final Jid jid) {
4552 for (final Account account : this.accounts) {
4553 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4554 return account;
4555 }
4556 }
4557 return null;
4558 }
4559
4560 public Account findAccountByUuid(final String uuid) {
4561 for (Account account : this.accounts) {
4562 if (account.getUuid().equals(uuid)) {
4563 return account;
4564 }
4565 }
4566 return null;
4567 }
4568
4569 public Conversation findConversationByUuid(String uuid) {
4570 for (Conversation conversation : getConversations()) {
4571 if (conversation.getUuid().equals(uuid)) {
4572 return conversation;
4573 }
4574 }
4575 return null;
4576 }
4577
4578 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4579 List<Conversation> findings = new ArrayList<>();
4580 for (Conversation c : getConversations()) {
4581 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4582 findings.add(c);
4583 }
4584 }
4585 return findings.size() == 1 ? findings.get(0) : null;
4586 }
4587
4588 public boolean markRead(final Conversation conversation, boolean dismiss) {
4589 return markRead(conversation, null, dismiss).size() > 0;
4590 }
4591
4592 public void markRead(final Conversation conversation) {
4593 markRead(conversation, null, true);
4594 }
4595
4596 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4597 if (dismiss) {
4598 mNotificationService.clear(conversation);
4599 }
4600 final List<Message> readMessages = conversation.markRead(upToUuid);
4601 if (readMessages.size() > 0) {
4602 Runnable runnable = () -> {
4603 for (Message message : readMessages) {
4604 databaseBackend.updateMessage(message, false);
4605 }
4606 };
4607 mDatabaseWriterExecutor.execute(runnable);
4608 updateConversationUi();
4609 updateUnreadCountBadge();
4610 return readMessages;
4611 } else {
4612 return readMessages;
4613 }
4614 }
4615
4616 public synchronized void updateUnreadCountBadge() {
4617 int count = unreadCount();
4618 if (unreadCount != count) {
4619 Log.d(Config.LOGTAG, "update unread count to " + count);
4620 if (count > 0) {
4621 ShortcutBadger.applyCount(getApplicationContext(), count);
4622 } else {
4623 ShortcutBadger.removeCount(getApplicationContext());
4624 }
4625 unreadCount = count;
4626 }
4627 }
4628
4629 public void sendReadMarker(final Conversation conversation, final String upToUuid) {
4630 final boolean isPrivateAndNonAnonymousMuc =
4631 conversation.getMode() == Conversation.MODE_MULTI
4632 && conversation.isPrivateAndNonAnonymous();
4633 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4634 if (readMessages.isEmpty()) {
4635 return;
4636 }
4637 final var account = conversation.getAccount();
4638 final var connection = account.getXmppConnection();
4639 updateConversationUi();
4640 final var last =
4641 Iterables.getLast(
4642 Collections2.filter(
4643 readMessages,
4644 m ->
4645 !m.isPrivateMessage()
4646 && m.getStatus() == Message.STATUS_RECEIVED),
4647 null);
4648 if (last == null) {
4649 return;
4650 }
4651
4652 final boolean sendDisplayedMarker =
4653 confirmMessages()
4654 && (last.trusted() || isPrivateAndNonAnonymousMuc)
4655 && last.getRemoteMsgId() != null
4656 && (last.markable || isPrivateAndNonAnonymousMuc);
4657 final boolean serverAssist =
4658 connection != null && connection.getFeatures().mdsServerAssist();
4659
4660 final String stanzaId = last.getServerMsgId();
4661
4662 if (sendDisplayedMarker && serverAssist) {
4663 final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
4664 final MessagePacket packet = mMessageGenerator.confirm(last);
4665 packet.addChild(mdsDisplayed);
4666 if (!last.isPrivateMessage()) {
4667 packet.setTo(packet.getTo().asBareJid());
4668 }
4669 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": server assisted "+packet);
4670 this.sendMessagePacket(account, packet);
4671 } else {
4672 publishMds(last);
4673 // read markers will be sent after MDS to flush the CSI stanza queue
4674 if (sendDisplayedMarker) {
4675 Log.d(
4676 Config.LOGTAG,
4677 conversation.getAccount().getJid().asBareJid()
4678 + ": sending displayed marker to "
4679 + last.getCounterpart().toString());
4680 final MessagePacket packet = mMessageGenerator.confirm(last);
4681 this.sendMessagePacket(account, packet);
4682 }
4683 }
4684 }
4685
4686 private void publishMds(@Nullable final Message message) {
4687 final String stanzaId = message == null ? null : message.getServerMsgId();
4688 if (Strings.isNullOrEmpty(stanzaId)) {
4689 return;
4690 }
4691 final Conversation conversation;
4692 final var conversational = message.getConversation();
4693 if (conversational instanceof Conversation c) {
4694 conversation = c;
4695 } else {
4696 return;
4697 }
4698 final var account = conversation.getAccount();
4699 final var connection = account.getXmppConnection();
4700 if (connection == null || !connection.getFeatures().mds()) {
4701 return;
4702 }
4703 final Jid itemId;
4704 if (message.isPrivateMessage()) {
4705 itemId = message.getCounterpart();
4706 } else {
4707 itemId = conversation.getJid().asBareJid();
4708 }
4709 Log.d(Config.LOGTAG,"publishing mds for "+itemId+"/"+stanzaId);
4710 publishMds(account, itemId, stanzaId, conversation);
4711 }
4712
4713 private void publishMds(
4714 final Account account, final Jid itemId, final String stanzaId, final Conversation conversation) {
4715 final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
4716 pushNodeAndEnforcePublishOptions(
4717 account,
4718 Namespace.MDS_DISPLAYED,
4719 item,
4720 itemId.toEscapedString(),
4721 PublishOptions.persistentWhitelistAccessMaxItems());
4722 }
4723
4724 public MemorizingTrustManager getMemorizingTrustManager() {
4725 return this.mMemorizingTrustManager;
4726 }
4727
4728 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4729 this.mMemorizingTrustManager = trustManager;
4730 }
4731
4732 public void updateMemorizingTrustmanager() {
4733 final MemorizingTrustManager tm;
4734 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4735 if (dontTrustSystemCAs) {
4736 tm = new MemorizingTrustManager(getApplicationContext(), null);
4737 } else {
4738 tm = new MemorizingTrustManager(getApplicationContext());
4739 }
4740 setMemorizingTrustManager(tm);
4741 }
4742
4743 public LruCache<String, Bitmap> getBitmapCache() {
4744 return this.mBitmapCache;
4745 }
4746
4747 public Collection<String> getKnownHosts() {
4748 final Set<String> hosts = new HashSet<>();
4749 for (final Account account : getAccounts()) {
4750 hosts.add(account.getServer());
4751 for (final Contact contact : account.getRoster().getContacts()) {
4752 if (contact.showInRoster()) {
4753 final String server = contact.getServer();
4754 if (server != null) {
4755 hosts.add(server);
4756 }
4757 }
4758 }
4759 }
4760 if (Config.QUICKSY_DOMAIN != null) {
4761 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4762 }
4763 if (Config.DOMAIN_LOCK != null) {
4764 hosts.add(Config.DOMAIN_LOCK);
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(SettingsActivity.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}