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 mForceForegroundService = 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 startForcingForegroundNotification() {
530 mForceForegroundService.set(true);
531 toggleForegroundService();
532 }
533
534 public void stopForcingForegroundNotification() {
535 mForceForegroundService.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 if (force || mForceDuringOnCreate.get() || mForceForegroundService.get() || ongoing != null || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1471 final Notification notification;
1472 final int id;
1473 if (ongoing != null) {
1474 notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1475 id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1476 startForegroundOrCatch(id, notification, true);
1477 mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1478 } else {
1479 notification = this.mNotificationService.createForegroundNotification();
1480 id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1481 startForegroundOrCatch(id, notification, false);
1482 }
1483
1484 if (!mForceForegroundService.get()) {
1485 mNotificationService.notify(id, notification);
1486 }
1487 status = true;
1488 } else {
1489 stopForeground(true);
1490 status = false;
1491 }
1492 if (!mForceForegroundService.get()) {
1493 mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1494 }
1495 if (ongoing == null) {
1496 mNotificationService.cancel(NotificationService.ONGOING_CALL_NOTIFICATION_ID);
1497 }
1498 Log.d(Config.LOGTAG, "ForegroundService: " + (status ? "on" : "off"));
1499 }
1500
1501 private void startForegroundOrCatch(
1502 final int id, final Notification notification, final boolean requireMicrophone) {
1503 try {
1504 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
1505 final int foregroundServiceType;
1506 if (requireMicrophone
1507 && ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1508 == PackageManager.PERMISSION_GRANTED) {
1509 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1510 Log.d(Config.LOGTAG, "defaulting to microphone foreground service type");
1511 } else if (getSystemService(PowerManager.class)
1512 .isIgnoringBatteryOptimizations(getPackageName())) {
1513 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED;
1514 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1515 == PackageManager.PERMISSION_GRANTED) {
1516 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1517 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
1518 == PackageManager.PERMISSION_GRANTED) {
1519 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;
1520 } else {
1521 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
1522 Log.w(Config.LOGTAG, "falling back to special use foreground service type");
1523 }
1524 startForeground(id, notification, foregroundServiceType);
1525 } else {
1526 startForeground(id, notification);
1527 }
1528 } catch (final IllegalStateException | SecurityException e) {
1529 Log.e(Config.LOGTAG, "Could not start foreground service", e);
1530 }
1531 }
1532
1533 public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1534 return !mForceForegroundService.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1535 }
1536
1537 @Override
1538 public void onTaskRemoved(final Intent rootIntent) {
1539 super.onTaskRemoved(rootIntent);
1540 if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get() || ongoingCall.get() != null) {
1541 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1542 } else {
1543 this.logoutAndSave(false);
1544 }
1545 }
1546
1547 private void logoutAndSave(boolean stop) {
1548 int activeAccounts = 0;
1549 for (final Account account : accounts) {
1550 if (account.isConnectionEnabled()) {
1551 databaseBackend.writeRoster(account.getRoster());
1552 activeAccounts++;
1553 }
1554 if (account.getXmppConnection() != null) {
1555 new Thread(() -> disconnect(account, false)).start();
1556 }
1557 }
1558 if (stop || activeAccounts == 0) {
1559 Log.d(Config.LOGTAG, "good bye");
1560 stopSelf();
1561 }
1562 }
1563
1564 private void schedulePostConnectivityChange() {
1565 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1566 if (alarmManager == null) {
1567 return;
1568 }
1569 final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1570 final Intent intent = new Intent(this, EventReceiver.class);
1571 intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1572 try {
1573 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, s()
1574 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1575 : PendingIntent.FLAG_UPDATE_CURRENT);
1576 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1577 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1578 } else {
1579 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1580 }
1581 } catch (RuntimeException e) {
1582 Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1583 }
1584 }
1585
1586 public void scheduleWakeUpCall(final int seconds, final int requestCode) {
1587 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000L;
1588 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1589 if (alarmManager == null) {
1590 return;
1591 }
1592 final Intent intent = new Intent(this, EventReceiver.class);
1593 intent.setAction(ACTION_PING);
1594 try {
1595 final PendingIntent pendingIntent =
1596 PendingIntent.getBroadcast(
1597 this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1598 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1599 } catch (RuntimeException e) {
1600 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1601 }
1602 }
1603
1604 @TargetApi(Build.VERSION_CODES.M)
1605 private void scheduleNextIdlePing() {
1606 final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1607 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1608 if (alarmManager == null) {
1609 return;
1610 }
1611 final Intent intent = new Intent(this, EventReceiver.class);
1612 intent.setAction(ACTION_IDLE_PING);
1613 try {
1614 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, s()
1615 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1616 : PendingIntent.FLAG_UPDATE_CURRENT);
1617 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1618 } catch (RuntimeException e) {
1619 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1620 }
1621 }
1622
1623 public XmppConnection createConnection(final Account account) {
1624 final XmppConnection connection = new XmppConnection(account, this);
1625 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1626 connection.setOnStatusChangedListener(this.statusListener);
1627 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1628 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1629 connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1630 connection.setOnBindListener(this.mOnBindListener);
1631 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1632 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1633 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1634 AxolotlService axolotlService = account.getAxolotlService();
1635 if (axolotlService != null) {
1636 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1637 }
1638 return connection;
1639 }
1640
1641 public void sendChatState(Conversation conversation) {
1642 if (sendChatStates()) {
1643 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1644 sendMessagePacket(conversation.getAccount(), packet);
1645 }
1646 }
1647
1648 private void sendFileMessage(final Message message, final boolean delay) {
1649 Log.d(Config.LOGTAG, "send file message");
1650 final Account account = message.getConversation().getAccount();
1651 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1652 || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1653 mHttpConnectionManager.createNewUploadConnection(message, delay);
1654 } else {
1655 mJingleConnectionManager.startJingleFileTransfer(message);
1656 }
1657 }
1658
1659 public void sendMessage(final Message message) {
1660 sendMessage(message, false, false);
1661 }
1662
1663 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1664 final Account account = message.getConversation().getAccount();
1665 if (account.setShowErrorNotification(true)) {
1666 databaseBackend.updateAccount(account);
1667 mNotificationService.updateErrorNotification();
1668 }
1669 final Conversation conversation = (Conversation) message.getConversation();
1670 account.deactivateGracePeriod();
1671
1672
1673 if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1674 final Contact contact = conversation.getContact();
1675 if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1676 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1677 createContact(contact, true);
1678 }
1679 }
1680
1681 MessagePacket packet = null;
1682 final boolean addToConversation = !message.edited();
1683 boolean saveInDb = addToConversation;
1684 message.setStatus(Message.STATUS_WAITING);
1685
1686 if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1687 if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1688 databaseBackend.updateConversation(conversation);
1689 }
1690 }
1691
1692 final boolean inProgressJoin = isJoinInProgress(conversation);
1693
1694
1695 if (account.isOnlineAndConnected() && !inProgressJoin) {
1696 switch (message.getEncryption()) {
1697 case Message.ENCRYPTION_NONE:
1698 if (message.needsUploading()) {
1699 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1700 || conversation.getMode() == Conversation.MODE_MULTI
1701 || message.fixCounterpart()) {
1702 this.sendFileMessage(message, delay);
1703 } else {
1704 break;
1705 }
1706 } else {
1707 packet = mMessageGenerator.generateChat(message);
1708 }
1709 break;
1710 case Message.ENCRYPTION_PGP:
1711 case Message.ENCRYPTION_DECRYPTED:
1712 if (message.needsUploading()) {
1713 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1714 || conversation.getMode() == Conversation.MODE_MULTI
1715 || message.fixCounterpart()) {
1716 this.sendFileMessage(message, delay);
1717 } else {
1718 break;
1719 }
1720 } else {
1721 packet = mMessageGenerator.generatePgpChat(message);
1722 }
1723 break;
1724 case Message.ENCRYPTION_AXOLOTL:
1725 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1726 if (message.needsUploading()) {
1727 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1728 || conversation.getMode() == Conversation.MODE_MULTI
1729 || message.fixCounterpart()) {
1730 this.sendFileMessage(message, delay);
1731 } else {
1732 break;
1733 }
1734 } else {
1735 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1736 if (axolotlMessage == null) {
1737 account.getAxolotlService().preparePayloadMessage(message, delay);
1738 } else {
1739 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1740 }
1741 }
1742 break;
1743
1744 }
1745 if (packet != null) {
1746 if (account.getXmppConnection().getFeatures().sm()
1747 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1748 message.setStatus(Message.STATUS_UNSEND);
1749 } else {
1750 message.setStatus(Message.STATUS_SEND);
1751 }
1752 }
1753 } else {
1754 switch (message.getEncryption()) {
1755 case Message.ENCRYPTION_DECRYPTED:
1756 if (!message.needsUploading()) {
1757 String pgpBody = message.getEncryptedBody();
1758 String decryptedBody = message.getBody();
1759 message.setBody(pgpBody); //TODO might throw NPE
1760 message.setEncryption(Message.ENCRYPTION_PGP);
1761 if (message.edited()) {
1762 message.setBody(decryptedBody);
1763 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1764 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1765 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1766 }
1767 updateConversationUi();
1768 return;
1769 } else {
1770 databaseBackend.createMessage(message);
1771 saveInDb = false;
1772 message.setBody(decryptedBody);
1773 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1774 }
1775 }
1776 break;
1777 case Message.ENCRYPTION_AXOLOTL:
1778 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1779 break;
1780 }
1781 }
1782
1783
1784 boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1785 if (mucMessage) {
1786 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1787 }
1788
1789 if (resend) {
1790 if (packet != null && addToConversation) {
1791 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1792 markMessage(message, Message.STATUS_UNSEND);
1793 } else {
1794 markMessage(message, Message.STATUS_SEND);
1795 }
1796 }
1797 } else {
1798 if (addToConversation) {
1799 conversation.add(message);
1800 }
1801 if (saveInDb) {
1802 databaseBackend.createMessage(message);
1803 } else if (message.edited()) {
1804 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1805 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1806 }
1807 }
1808 updateConversationUi();
1809 }
1810 if (packet != null) {
1811 if (delay) {
1812 mMessageGenerator.addDelay(packet, message.getTimeSent());
1813 }
1814 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1815 if (this.sendChatStates()) {
1816 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1817 }
1818 }
1819 sendMessagePacket(account, packet);
1820 }
1821 }
1822
1823 private boolean isJoinInProgress(final Conversation conversation) {
1824 final Account account = conversation.getAccount();
1825 synchronized (account.inProgressConferenceJoins) {
1826 if (conversation.getMode() == Conversational.MODE_MULTI) {
1827 final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1828 final boolean pending = account.pendingConferenceJoins.contains(conversation);
1829 final boolean inProgressJoin = inProgress || pending;
1830 if (inProgressJoin) {
1831 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
1832 }
1833 return inProgressJoin;
1834 } else {
1835 return false;
1836 }
1837 }
1838 }
1839
1840 private void sendUnsentMessages(final Conversation conversation) {
1841 conversation.findWaitingMessages(message -> resendMessage(message, true));
1842 }
1843
1844 public void resendMessage(final Message message, final boolean delay) {
1845 sendMessage(message, true, delay);
1846 }
1847
1848 public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
1849 final XmppConnection connection = account.getXmppConnection();
1850 final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
1851 if (jid == null) {
1852 callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
1853 return;
1854 }
1855 final IqPacket request = new IqPacket(IqPacket.TYPE.SET);
1856 request.setTo(jid);
1857 final Element command = request.addChild("command", Namespace.COMMANDS);
1858 command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
1859 command.setAttribute("action", "execute");
1860 sendIqPacket(account, request, (a, response) -> {
1861 if (response.getType() == IqPacket.TYPE.RESULT) {
1862 final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
1863 final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
1864 if (x != null) {
1865 final Data data = Data.parse(x);
1866 final String uri = data.getValue("uri");
1867 final String landingUrl = data.getValue("landing-url");
1868 if (uri != null) {
1869 final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
1870 callback.inviteRequested(invite);
1871 return;
1872 }
1873 }
1874 callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
1875 Log.d(Config.LOGTAG, response.toString());
1876 } else if (response.getType() == IqPacket.TYPE.ERROR) {
1877 callback.inviteRequestFailed(IqParser.errorMessage(response));
1878 } else {
1879 callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
1880 }
1881 });
1882
1883 }
1884
1885 public void fetchRosterFromServer(final Account account) {
1886 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1887 if (!"".equals(account.getRosterVersion())) {
1888 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1889 + ": fetching roster version " + account.getRosterVersion());
1890 } else {
1891 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1892 }
1893 iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1894 sendIqPacket(account, iqPacket, mIqParser);
1895 }
1896
1897 public void fetchBookmarks(final Account account) {
1898 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1899 final Element query = iqPacket.query("jabber:iq:private");
1900 query.addChild("storage", Namespace.BOOKMARKS);
1901 final OnIqPacketReceived callback = (a, response) -> {
1902 if (response.getType() == IqPacket.TYPE.RESULT) {
1903 final Element query1 = response.query();
1904 final Element storage = query1.findChild("storage", "storage:bookmarks");
1905 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
1906 processBookmarksInitial(a, bookmarks, false);
1907 } else {
1908 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1909 }
1910 };
1911 sendIqPacket(account, iqPacket, callback);
1912 }
1913
1914 public void fetchBookmarks2(final Account account) {
1915 final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
1916 sendIqPacket(account, retrieve, (a, response) -> {
1917 if (response.getType() == IqPacket.TYPE.RESULT) {
1918 final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
1919 final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, a);
1920 processBookmarksInitial(a, bookmarks, true);
1921 }
1922 });
1923 }
1924
1925 private void fetchMessageDisplayedSynchronization(final Account account) {
1926 Log.d(Config.LOGTAG, account.getJid() + ": retrieve mds");
1927 final var retrieve = mIqGenerator.retrieveMds();
1928 sendIqPacket(
1929 account,
1930 retrieve,
1931 (a, response) -> {
1932 if (response.getType() != IqPacket.TYPE.RESULT) {
1933 return;
1934 }
1935 final var pubSub = response.findChild("pubsub", Namespace.PUBSUB);
1936 final Element items = pubSub == null ? null : pubSub.findChild("items");
1937 if (items == null
1938 || !Namespace.MDS_DISPLAYED.equals(items.getAttribute("node"))) {
1939 return;
1940 }
1941 for (final Element child : items.getChildren()) {
1942 if ("item".equals(child.getName())) {
1943 processMdsItem(account, child);
1944 }
1945 }
1946 });
1947 }
1948
1949 public void processMdsItem(final Account account, final Element item) {
1950 final Jid jid =
1951 item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("id"));
1952 if (jid == null) {
1953 return;
1954 }
1955 final Element displayed = item.findChild("displayed", Namespace.MDS_DISPLAYED);
1956 final Element stanzaId =
1957 displayed == null ? null : displayed.findChild("stanza-id", Namespace.STANZA_IDS);
1958 final String id = stanzaId == null ? null : stanzaId.getAttribute("id");
1959 final Conversation conversation = find(account, jid);
1960 if (id != null && conversation != null) {
1961 conversation.setDisplayState(id);
1962 markReadUpToStanzaId(conversation, id);
1963 }
1964 }
1965
1966 public void markReadUpToStanzaId(final Conversation conversation, final String stanzaId) {
1967 final Message message = conversation.findMessageWithServerMsgId(stanzaId);
1968 if (message == null) { // do we want to check if isRead?
1969 return;
1970 }
1971 markReadUpTo(conversation, message);
1972 }
1973
1974 public void markReadUpTo(final Conversation conversation, final Message message) {
1975 final boolean isDismissNotification = isDismissNotification(message);
1976 final var uuid = message.getUuid();
1977 Log.d(
1978 Config.LOGTAG,
1979 conversation.getAccount().getJid().asBareJid()
1980 + ": mark "
1981 + conversation.getJid().asBareJid()
1982 + " as read up to "
1983 + uuid);
1984 markRead(conversation, uuid, isDismissNotification);
1985 }
1986
1987 private static boolean isDismissNotification(final Message message) {
1988 Message next = message.next();
1989 while (next != null) {
1990 if (message.getStatus() == Message.STATUS_RECEIVED) {
1991 return false;
1992 }
1993 next = next.next();
1994 }
1995 return true;
1996 }
1997
1998 public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
1999 final Set<Jid> previousBookmarks = account.getBookmarkedJids();
2000 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
2001 for (Bookmark bookmark : bookmarks.values()) {
2002 previousBookmarks.remove(bookmark.getJid().asBareJid());
2003 processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
2004 }
2005 if (pep && synchronizeWithBookmarks) {
2006 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
2007 for (Jid jid : previousBookmarks) {
2008 processDeletedBookmark(account, jid);
2009 }
2010 }
2011 account.setBookmarks(bookmarks);
2012 }
2013
2014 public void processDeletedBookmark(Account account, Jid jid) {
2015 final Conversation conversation = find(account, jid);
2016 if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2017 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
2018 archiveConversation(conversation, false);
2019 }
2020 }
2021
2022 private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
2023 final Account account = bookmark.getAccount();
2024 Conversation conversation = find(bookmark);
2025 if (conversation != null) {
2026 if (conversation.getMode() != Conversation.MODE_MULTI) {
2027 return;
2028 }
2029 bookmark.setConversation(conversation);
2030 if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
2031 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
2032 archiveConversation(conversation, false);
2033 } else {
2034 final MucOptions mucOptions = conversation.getMucOptions();
2035 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
2036 final String current = mucOptions.getActualNick();
2037 final String proposed = mucOptions.getProposedNick();
2038 if (current != null && !current.equals(proposed)) {
2039 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
2040 joinMuc(conversation);
2041 }
2042 }
2043 }
2044 } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
2045 conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
2046 bookmark.setConversation(conversation);
2047 }
2048 }
2049
2050 public void processModifiedBookmark(Bookmark bookmark) {
2051 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
2052 processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
2053 }
2054
2055 public void createBookmark(final Account account, final Bookmark bookmark) {
2056 account.putBookmark(bookmark);
2057 final XmppConnection connection = account.getXmppConnection();
2058 if (connection == null) {
2059 Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
2060 } else if (connection.getFeatures().bookmarks2()) {
2061 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": pushing bookmark via Bookmarks 2");
2062 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
2063 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
2064 } else if (connection.getFeatures().bookmarksConversion()) {
2065 pushBookmarksPep(account);
2066 } else {
2067 pushBookmarksPrivateXml(account);
2068 }
2069 }
2070
2071 public void deleteBookmark(final Account account, final Bookmark bookmark) {
2072 account.removeBookmark(bookmark);
2073 final XmppConnection connection = account.getXmppConnection();
2074 if (connection.getFeatures().bookmarks2()) {
2075 final IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
2076 Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": removing bookmark via Bookmarks 2");
2077 sendIqPacket(account, request, (a, response) -> {
2078 if (response.getType() == IqPacket.TYPE.ERROR) {
2079 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
2080 }
2081 });
2082 } else if (connection.getFeatures().bookmarksConversion()) {
2083 pushBookmarksPep(account);
2084 } else {
2085 pushBookmarksPrivateXml(account);
2086 }
2087 }
2088
2089 private void pushBookmarksPrivateXml(Account account) {
2090 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
2091 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2092 Element query = iqPacket.query("jabber:iq:private");
2093 Element storage = query.addChild("storage", "storage:bookmarks");
2094 for (final Bookmark bookmark : account.getBookmarks()) {
2095 storage.addChild(bookmark);
2096 }
2097 sendIqPacket(account, iqPacket, mDefaultIqHandler);
2098 }
2099
2100 private void pushBookmarksPep(Account account) {
2101 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
2102 final Element storage = new Element("storage", "storage:bookmarks");
2103 for (final Bookmark bookmark : account.getBookmarks()) {
2104 storage.addChild(bookmark);
2105 }
2106 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
2107
2108 }
2109
2110 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
2111 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2112
2113 }
2114
2115 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
2116 final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
2117 sendIqPacket(account, packet, (a, response) -> {
2118 if (response.getType() == IqPacket.TYPE.RESULT) {
2119 return;
2120 }
2121 if (retry && PublishOptions.preconditionNotMet(response)) {
2122 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
2123 @Override
2124 public void onPushSucceeded() {
2125 pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
2126 }
2127
2128 @Override
2129 public void onPushFailed() {
2130 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
2131 }
2132 });
2133 } else {
2134 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing "+node+" (retry=" + retry + ") " + response);
2135 }
2136 });
2137 }
2138
2139 private void restoreFromDatabase() {
2140 synchronized (this.conversations) {
2141 final Map<String, Account> accountLookupTable = new Hashtable<>();
2142 for (Account account : this.accounts) {
2143 accountLookupTable.put(account.getUuid(), account);
2144 }
2145 Log.d(Config.LOGTAG, "restoring conversations...");
2146 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2147 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2148 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
2149 Conversation conversation = iterator.next();
2150 Account account = accountLookupTable.get(conversation.getAccountUuid());
2151 if (account != null) {
2152 conversation.setAccount(account);
2153 } else {
2154 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
2155 iterator.remove();
2156 }
2157 }
2158 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2159 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
2160 Runnable runnable = () -> {
2161 if (DatabaseBackend.requiresMessageIndexRebuild()) {
2162 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2163 }
2164 final long deletionDate = getAutomaticMessageDeletionDate();
2165 mLastExpiryRun.set(SystemClock.elapsedRealtime());
2166 if (deletionDate > 0) {
2167 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
2168 databaseBackend.expireOldMessages(deletionDate);
2169 }
2170 Log.d(Config.LOGTAG, "restoring roster...");
2171 for (final Account account : accounts) {
2172 databaseBackend.readRoster(account.getRoster());
2173 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
2174 }
2175 getBitmapCache().evictAll();
2176 loadPhoneContacts();
2177 Log.d(Config.LOGTAG, "restoring messages...");
2178 final long startMessageRestore = SystemClock.elapsedRealtime();
2179 final Conversation quickLoad = QuickLoader.get(this.conversations);
2180 if (quickLoad != null) {
2181 restoreMessages(quickLoad);
2182 updateConversationUi();
2183 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2184 Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
2185 }
2186 for (Conversation conversation : this.conversations) {
2187 if (quickLoad != conversation) {
2188 restoreMessages(conversation);
2189 }
2190 }
2191 mNotificationService.finishBacklog();
2192 restoredFromDatabaseLatch.countDown();
2193 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2194 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2195 updateConversationUi();
2196 };
2197 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2198 }
2199 }
2200
2201 private void restoreMessages(Conversation conversation) {
2202 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2203 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2204 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2205 }
2206
2207 public void loadPhoneContacts() {
2208 mContactMergerExecutor.execute(() -> {
2209 final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2210 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2211 for (final Account account : accounts) {
2212 final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2213 for (final JabberIdContact jidContact : contacts.values()) {
2214 final Contact contact = account.getRoster().getContact(jidContact.getJid());
2215 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2216 if (needsCacheClean) {
2217 getAvatarService().clear(contact);
2218 }
2219 withSystemAccounts.remove(contact);
2220 }
2221 for (final Contact contact : withSystemAccounts) {
2222 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2223 if (needsCacheClean) {
2224 getAvatarService().clear(contact);
2225 }
2226 }
2227 }
2228 Log.d(Config.LOGTAG, "finished merging phone contacts");
2229 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2230 updateRosterUi();
2231 mQuickConversationsService.considerSync();
2232 });
2233 }
2234
2235
2236 public void syncRoster(final Account account) {
2237 mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
2238 }
2239
2240 public List<Conversation> getConversations() {
2241 return this.conversations;
2242 }
2243
2244 private void markFileDeleted(final File file) {
2245 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2246 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2247 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2248 return;
2249 }
2250 }
2251 final boolean isInternalFile = fileBackend.isInternalFile(file);
2252 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2253 Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2254 markUuidsAsDeletedFiles(uuids);
2255 }
2256
2257 private void markUuidsAsDeletedFiles(List<String> uuids) {
2258 boolean deleted = false;
2259 for (Conversation conversation : getConversations()) {
2260 deleted |= conversation.markAsDeleted(uuids);
2261 }
2262 for (final String uuid : uuids) {
2263 evictPreview(uuid);
2264 }
2265 if (deleted) {
2266 updateConversationUi();
2267 }
2268 }
2269
2270 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2271 boolean changed = false;
2272 for (Conversation conversation : getConversations()) {
2273 changed |= conversation.markAsChanged(infos);
2274 }
2275 if (changed) {
2276 updateConversationUi();
2277 }
2278 }
2279
2280 public void populateWithOrderedConversations(final List<Conversation> list) {
2281 populateWithOrderedConversations(list, true, true);
2282 }
2283
2284 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2285 populateWithOrderedConversations(list, includeNoFileUpload, true);
2286 }
2287
2288 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2289 final List<String> orderedUuids;
2290 if (sort) {
2291 orderedUuids = null;
2292 } else {
2293 orderedUuids = new ArrayList<>();
2294 for (Conversation conversation : list) {
2295 orderedUuids.add(conversation.getUuid());
2296 }
2297 }
2298 list.clear();
2299 if (includeNoFileUpload) {
2300 list.addAll(getConversations());
2301 } else {
2302 for (Conversation conversation : getConversations()) {
2303 if (conversation.getMode() == Conversation.MODE_SINGLE
2304 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2305 list.add(conversation);
2306 }
2307 }
2308 }
2309 try {
2310 if (orderedUuids != null) {
2311 Collections.sort(list, (a, b) -> {
2312 final int indexA = orderedUuids.indexOf(a.getUuid());
2313 final int indexB = orderedUuids.indexOf(b.getUuid());
2314 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2315 return a.compareTo(b);
2316 }
2317 return indexA - indexB;
2318 });
2319 } else {
2320 Collections.sort(list);
2321 }
2322 } catch (IllegalArgumentException e) {
2323 //ignore
2324 }
2325 }
2326
2327 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2328 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2329 return;
2330 } else if (timestamp == 0) {
2331 return;
2332 }
2333 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2334 final Runnable runnable = () -> {
2335 final Account account = conversation.getAccount();
2336 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2337 if (messages.size() > 0) {
2338 conversation.addAll(0, messages);
2339 callback.onMoreMessagesLoaded(messages.size(), conversation);
2340 } else if (conversation.hasMessagesLeftOnServer()
2341 && account.isOnlineAndConnected()
2342 && conversation.getLastClearHistory().getTimestamp() == 0) {
2343 final boolean mamAvailable;
2344 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2345 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2346 } else {
2347 mamAvailable = conversation.getMucOptions().mamSupport();
2348 }
2349 if (mamAvailable) {
2350 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2351 if (query != null) {
2352 query.setCallback(callback);
2353 callback.informUser(R.string.fetching_history_from_server);
2354 } else {
2355 callback.informUser(R.string.not_fetching_history_retention_period);
2356 }
2357
2358 }
2359 }
2360 };
2361 mDatabaseReaderExecutor.execute(runnable);
2362 }
2363
2364 public List<Account> getAccounts() {
2365 return this.accounts;
2366 }
2367
2368
2369 /**
2370 * 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)
2371 */
2372 public List<Conversation> findAllConferencesWith(Contact contact) {
2373 final ArrayList<Conversation> results = new ArrayList<>();
2374 for (final Conversation c : conversations) {
2375 if (c.getMode() != Conversation.MODE_MULTI) {
2376 continue;
2377 }
2378 final MucOptions mucOptions = c.getMucOptions();
2379 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2380 results.add(c);
2381 }
2382 }
2383 return results;
2384 }
2385
2386 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2387 for (final Conversation conversation : haystack) {
2388 if (conversation.getContact() == contact) {
2389 return conversation;
2390 }
2391 }
2392 return null;
2393 }
2394
2395 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2396 if (jid == null) {
2397 return null;
2398 }
2399 for (final Conversation conversation : haystack) {
2400 if ((account == null || conversation.getAccount() == account)
2401 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2402 return conversation;
2403 }
2404 }
2405 return null;
2406 }
2407
2408 public boolean isConversationsListEmpty(final Conversation ignore) {
2409 synchronized (this.conversations) {
2410 final int size = this.conversations.size();
2411 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2412 }
2413 }
2414
2415 public boolean isConversationStillOpen(final Conversation conversation) {
2416 synchronized (this.conversations) {
2417 for (Conversation current : this.conversations) {
2418 if (current == conversation) {
2419 return true;
2420 }
2421 }
2422 }
2423 return false;
2424 }
2425
2426 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2427 return this.findOrCreateConversation(account, jid, muc, false, async);
2428 }
2429
2430 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2431 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2432 }
2433
2434 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2435 synchronized (this.conversations) {
2436 Conversation conversation = find(account, jid);
2437 if (conversation != null) {
2438 return conversation;
2439 }
2440 conversation = databaseBackend.findConversation(account, jid);
2441 final boolean loadMessagesFromDb;
2442 if (conversation != null) {
2443 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2444 conversation.setAccount(account);
2445 if (muc) {
2446 conversation.setMode(Conversation.MODE_MULTI);
2447 conversation.setContactJid(jid);
2448 } else {
2449 conversation.setMode(Conversation.MODE_SINGLE);
2450 conversation.setContactJid(jid.asBareJid());
2451 }
2452 databaseBackend.updateConversation(conversation);
2453 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2454 } else {
2455 String conversationName;
2456 Contact contact = account.getRoster().getContact(jid);
2457 if (contact != null) {
2458 conversationName = contact.getDisplayName();
2459 } else {
2460 conversationName = jid.getLocal();
2461 }
2462 if (muc) {
2463 conversation = new Conversation(conversationName, account, jid,
2464 Conversation.MODE_MULTI);
2465 } else {
2466 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2467 Conversation.MODE_SINGLE);
2468 }
2469 this.databaseBackend.createConversation(conversation);
2470 loadMessagesFromDb = false;
2471 }
2472 final Conversation c = conversation;
2473 final Runnable runnable = () -> {
2474 if (loadMessagesFromDb) {
2475 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2476 updateConversationUi();
2477 c.messagesLoaded.set(true);
2478 }
2479 if (account.getXmppConnection() != null
2480 && !c.getContact().isBlocked()
2481 && account.getXmppConnection().getFeatures().mam()
2482 && !muc) {
2483 if (query == null) {
2484 mMessageArchiveService.query(c);
2485 } else {
2486 if (query.getConversation() == null) {
2487 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2488 }
2489 }
2490 }
2491 if (joinAfterCreate) {
2492 joinMuc(c);
2493 }
2494 };
2495 if (async) {
2496 mDatabaseReaderExecutor.execute(runnable);
2497 } else {
2498 runnable.run();
2499 }
2500 this.conversations.add(conversation);
2501 updateConversationUi();
2502 return conversation;
2503 }
2504 }
2505
2506 public void archiveConversation(Conversation conversation) {
2507 archiveConversation(conversation, true);
2508 }
2509
2510 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2511 getNotificationService().clear(conversation);
2512 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2513 conversation.setNextMessage(null);
2514 synchronized (this.conversations) {
2515 getMessageArchiveService().kill(conversation);
2516 if (conversation.getMode() == Conversation.MODE_MULTI) {
2517 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2518 final Bookmark bookmark = conversation.getBookmark();
2519 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2520 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2521 Account account = bookmark.getAccount();
2522 bookmark.setConversation(null);
2523 deleteBookmark(account, bookmark);
2524 } else if (bookmark.autojoin()) {
2525 bookmark.setAutojoin(false);
2526 createBookmark(bookmark.getAccount(), bookmark);
2527 }
2528 }
2529 }
2530 leaveMuc(conversation);
2531 } else {
2532 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2533 stopPresenceUpdatesTo(conversation.getContact());
2534 }
2535 }
2536 updateConversation(conversation);
2537 this.conversations.remove(conversation);
2538 updateConversationUi();
2539 }
2540 }
2541
2542 public void stopPresenceUpdatesTo(Contact contact) {
2543 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2544 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2545 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2546 }
2547
2548 public void createAccount(final Account account) {
2549 account.initAccountServices(this);
2550 databaseBackend.createAccount(account);
2551 if (CallIntegration.hasSystemFeature(this)) {
2552 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2553 }
2554 this.accounts.add(account);
2555 this.reconnectAccountInBackground(account);
2556 updateAccountUi();
2557 syncEnabledAccountSetting();
2558 toggleForegroundService();
2559 }
2560
2561 private void syncEnabledAccountSetting() {
2562 final boolean hasEnabledAccounts = hasEnabledAccounts();
2563 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2564 toggleSetProfilePictureActivity(hasEnabledAccounts);
2565 }
2566
2567 private void toggleSetProfilePictureActivity(final boolean enabled) {
2568 try {
2569 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2570 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2571 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2572 } catch (IllegalStateException e) {
2573 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
2574 }
2575 }
2576
2577 public boolean reconfigurePushDistributor() {
2578 return this.unifiedPushBroker.reconfigurePushDistributor();
2579 }
2580
2581 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
2582 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
2583 }
2584
2585 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
2586 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
2587 }
2588
2589 private void provisionAccount(final String address, final String password) {
2590 final Jid jid = Jid.ofEscaped(address);
2591 final Account account = new Account(jid, password);
2592 account.setOption(Account.OPTION_DISABLED, true);
2593 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2594 createAccount(account);
2595 }
2596
2597 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2598 new Thread(() -> {
2599 try {
2600 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2601 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2602 if (cert == null) {
2603 callback.informUser(R.string.unable_to_parse_certificate);
2604 return;
2605 }
2606 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2607 if (info == null) {
2608 callback.informUser(R.string.certificate_does_not_contain_jid);
2609 return;
2610 }
2611 if (findAccountByJid(info.first) == null) {
2612 final Account account = new Account(info.first, "");
2613 account.setPrivateKeyAlias(alias);
2614 account.setOption(Account.OPTION_DISABLED, true);
2615 account.setOption(Account.OPTION_FIXED_USERNAME, true);
2616 account.setDisplayName(info.second);
2617 createAccount(account);
2618 callback.onAccountCreated(account);
2619 if (Config.X509_VERIFICATION) {
2620 try {
2621 getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2622 } catch (CertificateException e) {
2623 callback.informUser(R.string.certificate_chain_is_not_trusted);
2624 }
2625 }
2626 } else {
2627 callback.informUser(R.string.account_already_exists);
2628 }
2629 } catch (Exception e) {
2630 callback.informUser(R.string.unable_to_parse_certificate);
2631 }
2632 }).start();
2633
2634 }
2635
2636 public void updateKeyInAccount(final Account account, final String alias) {
2637 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2638 try {
2639 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2640 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2641 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2642 if (info == null) {
2643 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2644 return;
2645 }
2646 if (account.getJid().asBareJid().equals(info.first)) {
2647 account.setPrivateKeyAlias(alias);
2648 account.setDisplayName(info.second);
2649 databaseBackend.updateAccount(account);
2650 if (Config.X509_VERIFICATION) {
2651 try {
2652 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2653 } catch (CertificateException e) {
2654 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2655 }
2656 account.getAxolotlService().regenerateKeys(true);
2657 }
2658 } else {
2659 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2660 }
2661 } catch (Exception e) {
2662 e.printStackTrace();
2663 }
2664 }
2665
2666 public boolean updateAccount(final Account account) {
2667 if (databaseBackend.updateAccount(account)) {
2668 account.setShowErrorNotification(true);
2669 this.statusListener.onStatusChanged(account);
2670 databaseBackend.updateAccount(account);
2671 reconnectAccountInBackground(account);
2672 updateAccountUi();
2673 getNotificationService().updateErrorNotification();
2674 toggleForegroundService();
2675 syncEnabledAccountSetting();
2676 mChannelDiscoveryService.cleanCache();
2677 if (CallIntegration.hasSystemFeature(this)) {
2678 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2679 }
2680 return true;
2681 } else {
2682 return false;
2683 }
2684 }
2685
2686 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2687 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2688 sendIqPacket(account, iq, (a, packet) -> {
2689 if (packet.getType() == IqPacket.TYPE.RESULT) {
2690 a.setPassword(newPassword);
2691 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2692 databaseBackend.updateAccount(a);
2693 callback.onPasswordChangeSucceeded();
2694 } else {
2695 callback.onPasswordChangeFailed();
2696 }
2697 });
2698 }
2699
2700 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
2701 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2702 final Element query = iqPacket.addChild("query",Namespace.REGISTER);
2703 query.addChild("remove");
2704 sendIqPacket(account, iqPacket, (a, response) -> {
2705 if (response.getType() == IqPacket.TYPE.RESULT) {
2706 deleteAccount(a);
2707 callback.accept(true);
2708 } else {
2709 callback.accept(false);
2710 }
2711 });
2712 }
2713
2714 public void deleteAccount(final Account account) {
2715 final boolean connected = account.getStatus() == Account.State.ONLINE;
2716 synchronized (this.conversations) {
2717 if (connected) {
2718 account.getAxolotlService().deleteOmemoIdentity();
2719 }
2720 for (final Conversation conversation : conversations) {
2721 if (conversation.getAccount() == account) {
2722 if (conversation.getMode() == Conversation.MODE_MULTI) {
2723 if (connected) {
2724 leaveMuc(conversation);
2725 }
2726 }
2727 conversations.remove(conversation);
2728 mNotificationService.clear(conversation);
2729 }
2730 }
2731 if (account.getXmppConnection() != null) {
2732 new Thread(() -> disconnect(account, !connected)).start();
2733 }
2734 final Runnable runnable = () -> {
2735 if (!databaseBackend.deleteAccount(account)) {
2736 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2737 }
2738 };
2739 mDatabaseWriterExecutor.execute(runnable);
2740 this.accounts.remove(account);
2741 CallIntegrationConnectionService.unregisterPhoneAccount(this, account);
2742 this.mRosterSyncTaskManager.clear(account);
2743 updateAccountUi();
2744 mNotificationService.updateErrorNotification();
2745 syncEnabledAccountSetting();
2746 toggleForegroundService();
2747 }
2748 }
2749
2750 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2751 final boolean remainingListeners;
2752 synchronized (LISTENER_LOCK) {
2753 remainingListeners = checkListeners();
2754 if (!this.mOnConversationUpdates.add(listener)) {
2755 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2756 }
2757 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2758 }
2759 if (remainingListeners) {
2760 switchToForeground();
2761 }
2762 }
2763
2764 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2765 final boolean remainingListeners;
2766 synchronized (LISTENER_LOCK) {
2767 this.mOnConversationUpdates.remove(listener);
2768 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2769 remainingListeners = checkListeners();
2770 }
2771 if (remainingListeners) {
2772 switchToBackground();
2773 }
2774 }
2775
2776 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2777 final boolean remainingListeners;
2778 synchronized (LISTENER_LOCK) {
2779 remainingListeners = checkListeners();
2780 if (!this.mOnShowErrorToasts.add(listener)) {
2781 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2782 }
2783 }
2784 if (remainingListeners) {
2785 switchToForeground();
2786 }
2787 }
2788
2789 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2790 final boolean remainingListeners;
2791 synchronized (LISTENER_LOCK) {
2792 this.mOnShowErrorToasts.remove(onShowErrorToast);
2793 remainingListeners = checkListeners();
2794 }
2795 if (remainingListeners) {
2796 switchToBackground();
2797 }
2798 }
2799
2800 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2801 final boolean remainingListeners;
2802 synchronized (LISTENER_LOCK) {
2803 remainingListeners = checkListeners();
2804 if (!this.mOnAccountUpdates.add(listener)) {
2805 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2806 }
2807 }
2808 if (remainingListeners) {
2809 switchToForeground();
2810 }
2811 }
2812
2813 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2814 final boolean remainingListeners;
2815 synchronized (LISTENER_LOCK) {
2816 this.mOnAccountUpdates.remove(listener);
2817 remainingListeners = checkListeners();
2818 }
2819 if (remainingListeners) {
2820 switchToBackground();
2821 }
2822 }
2823
2824 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2825 final boolean remainingListeners;
2826 synchronized (LISTENER_LOCK) {
2827 remainingListeners = checkListeners();
2828 if (!this.mOnCaptchaRequested.add(listener)) {
2829 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2830 }
2831 }
2832 if (remainingListeners) {
2833 switchToForeground();
2834 }
2835 }
2836
2837 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2838 final boolean remainingListeners;
2839 synchronized (LISTENER_LOCK) {
2840 this.mOnCaptchaRequested.remove(listener);
2841 remainingListeners = checkListeners();
2842 }
2843 if (remainingListeners) {
2844 switchToBackground();
2845 }
2846 }
2847
2848 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2849 final boolean remainingListeners;
2850 synchronized (LISTENER_LOCK) {
2851 remainingListeners = checkListeners();
2852 if (!this.mOnRosterUpdates.add(listener)) {
2853 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2854 }
2855 }
2856 if (remainingListeners) {
2857 switchToForeground();
2858 }
2859 }
2860
2861 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2862 final boolean remainingListeners;
2863 synchronized (LISTENER_LOCK) {
2864 this.mOnRosterUpdates.remove(listener);
2865 remainingListeners = checkListeners();
2866 }
2867 if (remainingListeners) {
2868 switchToBackground();
2869 }
2870 }
2871
2872 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2873 final boolean remainingListeners;
2874 synchronized (LISTENER_LOCK) {
2875 remainingListeners = checkListeners();
2876 if (!this.mOnUpdateBlocklist.add(listener)) {
2877 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2878 }
2879 }
2880 if (remainingListeners) {
2881 switchToForeground();
2882 }
2883 }
2884
2885 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2886 final boolean remainingListeners;
2887 synchronized (LISTENER_LOCK) {
2888 this.mOnUpdateBlocklist.remove(listener);
2889 remainingListeners = checkListeners();
2890 }
2891 if (remainingListeners) {
2892 switchToBackground();
2893 }
2894 }
2895
2896 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2897 final boolean remainingListeners;
2898 synchronized (LISTENER_LOCK) {
2899 remainingListeners = checkListeners();
2900 if (!this.mOnKeyStatusUpdated.add(listener)) {
2901 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2902 }
2903 }
2904 if (remainingListeners) {
2905 switchToForeground();
2906 }
2907 }
2908
2909 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2910 final boolean remainingListeners;
2911 synchronized (LISTENER_LOCK) {
2912 this.mOnKeyStatusUpdated.remove(listener);
2913 remainingListeners = checkListeners();
2914 }
2915 if (remainingListeners) {
2916 switchToBackground();
2917 }
2918 }
2919
2920 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2921 final boolean remainingListeners;
2922 synchronized (LISTENER_LOCK) {
2923 remainingListeners = checkListeners();
2924 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
2925 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
2926 }
2927 }
2928 if (remainingListeners) {
2929 switchToForeground();
2930 }
2931 }
2932
2933 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2934 final boolean remainingListeners;
2935 synchronized (LISTENER_LOCK) {
2936 this.onJingleRtpConnectionUpdate.remove(listener);
2937 remainingListeners = checkListeners();
2938 }
2939 if (remainingListeners) {
2940 switchToBackground();
2941 }
2942 }
2943
2944 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2945 final boolean remainingListeners;
2946 synchronized (LISTENER_LOCK) {
2947 remainingListeners = checkListeners();
2948 if (!this.mOnMucRosterUpdate.add(listener)) {
2949 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2950 }
2951 }
2952 if (remainingListeners) {
2953 switchToForeground();
2954 }
2955 }
2956
2957 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2958 final boolean remainingListeners;
2959 synchronized (LISTENER_LOCK) {
2960 this.mOnMucRosterUpdate.remove(listener);
2961 remainingListeners = checkListeners();
2962 }
2963 if (remainingListeners) {
2964 switchToBackground();
2965 }
2966 }
2967
2968 public boolean checkListeners() {
2969 return (this.mOnAccountUpdates.size() == 0
2970 && this.mOnConversationUpdates.size() == 0
2971 && this.mOnRosterUpdates.size() == 0
2972 && this.mOnCaptchaRequested.size() == 0
2973 && this.mOnMucRosterUpdate.size() == 0
2974 && this.mOnUpdateBlocklist.size() == 0
2975 && this.mOnShowErrorToasts.size() == 0
2976 && this.onJingleRtpConnectionUpdate.size() == 0
2977 && this.mOnKeyStatusUpdated.size() == 0);
2978 }
2979
2980 private void switchToForeground() {
2981 toggleSoftDisabled(false);
2982 final boolean broadcastLastActivity = broadcastLastActivity();
2983 for (Conversation conversation : getConversations()) {
2984 if (conversation.getMode() == Conversation.MODE_MULTI) {
2985 conversation.getMucOptions().resetChatState();
2986 } else {
2987 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
2988 }
2989 }
2990 for (Account account : getAccounts()) {
2991 if (account.getStatus() == Account.State.ONLINE) {
2992 account.deactivateGracePeriod();
2993 final XmppConnection connection = account.getXmppConnection();
2994 if (connection != null) {
2995 if (connection.getFeatures().csi()) {
2996 connection.sendActive();
2997 }
2998 if (broadcastLastActivity) {
2999 sendPresence(account, false); //send new presence but don't include idle because we are not
3000 }
3001 }
3002 }
3003 }
3004 Log.d(Config.LOGTAG, "app switched into foreground");
3005 }
3006
3007 private void switchToBackground() {
3008 final boolean broadcastLastActivity = broadcastLastActivity();
3009 if (broadcastLastActivity) {
3010 mLastActivity = System.currentTimeMillis();
3011 final SharedPreferences.Editor editor = getPreferences().edit();
3012 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3013 editor.apply();
3014 }
3015 for (Account account : getAccounts()) {
3016 if (account.getStatus() == Account.State.ONLINE) {
3017 XmppConnection connection = account.getXmppConnection();
3018 if (connection != null) {
3019 if (broadcastLastActivity) {
3020 sendPresence(account, true);
3021 }
3022 if (connection.getFeatures().csi()) {
3023 connection.sendInactive();
3024 }
3025 }
3026 }
3027 }
3028 this.mNotificationService.setIsInForeground(false);
3029 Log.d(Config.LOGTAG, "app switched into background");
3030 }
3031
3032 private void connectMultiModeConversations(Account account) {
3033 List<Conversation> conversations = getConversations();
3034 for (Conversation conversation : conversations) {
3035 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
3036 joinMuc(conversation);
3037 }
3038 }
3039 }
3040
3041 public void mucSelfPingAndRejoin(final Conversation conversation) {
3042 final Account account = conversation.getAccount();
3043 synchronized (account.inProgressConferenceJoins) {
3044 if (account.inProgressConferenceJoins.contains(conversation)) {
3045 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
3046 return;
3047 }
3048 }
3049 synchronized (account.inProgressConferencePings) {
3050 if (!account.inProgressConferencePings.add(conversation)) {
3051 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
3052 return;
3053 }
3054 }
3055 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3056 final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
3057 ping.setTo(self);
3058 ping.addChild("ping", Namespace.PING);
3059 sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
3060 if (response.getType() == IqPacket.TYPE.ERROR) {
3061 Element error = response.findChild("error");
3062 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
3063 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
3064 } else {
3065 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
3066 joinMuc(conversation);
3067 }
3068 } else if (response.getType() == IqPacket.TYPE.RESULT) {
3069 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
3070 }
3071 synchronized (account.inProgressConferencePings) {
3072 account.inProgressConferencePings.remove(conversation);
3073 }
3074 });
3075 }
3076 public void joinMuc(Conversation conversation) {
3077 joinMuc(conversation, null, false);
3078 }
3079
3080 public void joinMuc(Conversation conversation, boolean followedInvite) {
3081 joinMuc(conversation, null, followedInvite);
3082 }
3083
3084 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3085 joinMuc(conversation, onConferenceJoined, false);
3086 }
3087
3088 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
3089 final Account account = conversation.getAccount();
3090 synchronized (account.pendingConferenceJoins) {
3091 account.pendingConferenceJoins.remove(conversation);
3092 }
3093 synchronized (account.pendingConferenceLeaves) {
3094 account.pendingConferenceLeaves.remove(conversation);
3095 }
3096 if (account.getStatus() == Account.State.ONLINE) {
3097 synchronized (account.inProgressConferenceJoins) {
3098 account.inProgressConferenceJoins.add(conversation);
3099 }
3100 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3101 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3102 }
3103 conversation.resetMucOptions();
3104 if (onConferenceJoined != null) {
3105 conversation.getMucOptions().flagNoAutoPushConfiguration();
3106 }
3107 conversation.setHasMessagesLeftOnServer(false);
3108 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
3109
3110 private void join(Conversation conversation) {
3111 Account account = conversation.getAccount();
3112 final MucOptions mucOptions = conversation.getMucOptions();
3113
3114 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
3115 synchronized (account.inProgressConferenceJoins) {
3116 account.inProgressConferenceJoins.remove(conversation);
3117 }
3118 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3119 updateConversationUi();
3120 if (onConferenceJoined != null) {
3121 onConferenceJoined.onConferenceJoined(conversation);
3122 }
3123 return;
3124 }
3125
3126 final Jid joinJid = mucOptions.getSelf().getFullJid();
3127 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
3128 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
3129 packet.setTo(joinJid);
3130 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3131 if (conversation.getMucOptions().getPassword() != null) {
3132 x.addChild("password").setContent(mucOptions.getPassword());
3133 }
3134
3135 if (mucOptions.mamSupport()) {
3136 // Use MAM instead of the limited muc history to get history
3137 x.addChild("history").setAttribute("maxchars", "0");
3138 } else {
3139 // Fallback to muc history
3140 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
3141 }
3142 sendPresencePacket(account, packet);
3143 if (onConferenceJoined != null) {
3144 onConferenceJoined.onConferenceJoined(conversation);
3145 }
3146 if (!joinJid.equals(conversation.getJid())) {
3147 conversation.setContactJid(joinJid);
3148 databaseBackend.updateConversation(conversation);
3149 }
3150
3151 if (mucOptions.mamSupport()) {
3152 getMessageArchiveService().catchupMUC(conversation);
3153 }
3154 if (mucOptions.isPrivateAndNonAnonymous()) {
3155 fetchConferenceMembers(conversation);
3156
3157 if (followedInvite) {
3158 final Bookmark bookmark = conversation.getBookmark();
3159 if (bookmark != null) {
3160 if (!bookmark.autojoin()) {
3161 bookmark.setAutojoin(true);
3162 createBookmark(account, bookmark);
3163 }
3164 } else {
3165 saveConversationAsBookmark(conversation, null);
3166 }
3167 }
3168 }
3169 synchronized (account.inProgressConferenceJoins) {
3170 account.inProgressConferenceJoins.remove(conversation);
3171 sendUnsentMessages(conversation);
3172 }
3173 }
3174
3175 @Override
3176 public void onConferenceConfigurationFetched(Conversation conversation) {
3177 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3178 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3179 return;
3180 }
3181 join(conversation);
3182 }
3183
3184 @Override
3185 public void onFetchFailed(final Conversation conversation, final String errorCondition) {
3186 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3187 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3188 return;
3189 }
3190 if ("remote-server-not-found".equals(errorCondition)) {
3191 synchronized (account.inProgressConferenceJoins) {
3192 account.inProgressConferenceJoins.remove(conversation);
3193 }
3194 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
3195 updateConversationUi();
3196 } else {
3197 join(conversation);
3198 fetchConferenceConfiguration(conversation);
3199 }
3200 }
3201 });
3202 updateConversationUi();
3203 } else {
3204 synchronized (account.pendingConferenceJoins) {
3205 account.pendingConferenceJoins.add(conversation);
3206 }
3207 conversation.resetMucOptions();
3208 conversation.setHasMessagesLeftOnServer(false);
3209 updateConversationUi();
3210 }
3211 }
3212
3213 private void fetchConferenceMembers(final Conversation conversation) {
3214 final Account account = conversation.getAccount();
3215 final AxolotlService axolotlService = account.getAxolotlService();
3216 final String[] affiliations = {"member", "admin", "owner"};
3217 OnIqPacketReceived callback = new OnIqPacketReceived() {
3218
3219 private int i = 0;
3220 private boolean success = true;
3221
3222 @Override
3223 public void onIqPacketReceived(Account account, IqPacket packet) {
3224 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3225 Element query = packet.query("http://jabber.org/protocol/muc#admin");
3226 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
3227 for (Element child : query.getChildren()) {
3228 if ("item".equals(child.getName())) {
3229 MucOptions.User user = AbstractParser.parseItem(conversation, child);
3230 if (!user.realJidMatchesAccount()) {
3231 boolean isNew = conversation.getMucOptions().updateUser(user);
3232 Contact contact = user.getContact();
3233 if (omemoEnabled
3234 && isNew
3235 && user.getRealJid() != null
3236 && (contact == null || !contact.mutualPresenceSubscription())
3237 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3238 axolotlService.fetchDeviceIds(user.getRealJid());
3239 }
3240 }
3241 }
3242 }
3243 } else {
3244 success = false;
3245 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
3246 }
3247 ++i;
3248 if (i >= affiliations.length) {
3249 List<Jid> members = conversation.getMucOptions().getMembers(true);
3250 if (success) {
3251 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3252 boolean changed = false;
3253 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3254 Jid jid = iterator.next();
3255 if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3256 iterator.remove();
3257 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3258 changed = true;
3259 }
3260 }
3261 if (changed) {
3262 conversation.setAcceptedCryptoTargets(cryptoTargets);
3263 updateConversation(conversation);
3264 }
3265 }
3266 getAvatarService().clear(conversation);
3267 updateMucRosterUi();
3268 updateConversationUi();
3269 }
3270 }
3271 };
3272 for (String affiliation : affiliations) {
3273 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3274 }
3275 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3276 }
3277
3278 public void providePasswordForMuc(Conversation conversation, String password) {
3279 if (conversation.getMode() == Conversation.MODE_MULTI) {
3280 conversation.getMucOptions().setPassword(password);
3281 if (conversation.getBookmark() != null) {
3282 final Bookmark bookmark = conversation.getBookmark();
3283 if (synchronizeWithBookmarks()) {
3284 bookmark.setAutojoin(true);
3285 }
3286 createBookmark(conversation.getAccount(), bookmark);
3287 }
3288 updateConversation(conversation);
3289 joinMuc(conversation);
3290 }
3291 }
3292
3293 public void deleteAvatar(final Account account) {
3294 final AtomicBoolean executed = new AtomicBoolean(false);
3295 final Runnable onDeleted =
3296 () -> {
3297 if (executed.compareAndSet(false, true)) {
3298 account.setAvatar(null);
3299 databaseBackend.updateAccount(account);
3300 getAvatarService().clear(account);
3301 updateAccountUi();
3302 }
3303 };
3304 deleteVcardAvatar(account, onDeleted);
3305 deletePepNode(account, Namespace.AVATAR_DATA);
3306 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3307 }
3308
3309 public void deletePepNode(final Account account, final String node) {
3310 deletePepNode(account, node, null);
3311 }
3312
3313 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3314 final IqPacket request = mIqGenerator.deleteNode(node);
3315 sendIqPacket(account, request, (a, packet) -> {
3316 if (packet.getType() == IqPacket.TYPE.RESULT) {
3317 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": successfully deleted pep node "+node);
3318 if (runnable != null) {
3319 runnable.run();
3320 }
3321 } else {
3322 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": failed to delete "+ packet);
3323 }
3324 });
3325 }
3326
3327 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3328 final IqPacket retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3329 sendIqPacket(account, retrieveVcard, (a, response) -> {
3330 if (response.getType() != IqPacket.TYPE.RESULT) {
3331 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3332 return;
3333 }
3334 final Element vcard = response.findChild("vCard", "vcard-temp");
3335 if (vcard == null) {
3336 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3337 return;
3338 }
3339 Element photo = vcard.findChild("PHOTO");
3340 if (photo == null) {
3341 photo = vcard.addChild("PHOTO");
3342 }
3343 photo.clearChildren();
3344 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3345 publication.setTo(a.getJid().asBareJid());
3346 publication.addChild(vcard);
3347 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3348 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3349 Log.d(Config.LOGTAG,a1.getJid().asBareJid()+": successfully deleted vcard avatar");
3350 runnable.run();
3351 } else {
3352 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3353 }
3354 });
3355 });
3356 }
3357
3358 private boolean hasEnabledAccounts() {
3359 if (this.accounts == null) {
3360 return false;
3361 }
3362 for (final Account account : this.accounts) {
3363 if (account.isConnectionEnabled()) {
3364 return true;
3365 }
3366 }
3367 return false;
3368 }
3369
3370
3371 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3372 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3373 }
3374
3375 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3376 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3377 }
3378
3379
3380 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3381 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3382 }
3383
3384 public void persistSelfNick(final MucOptions.User self) {
3385 final Conversation conversation = self.getConversation();
3386 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3387 Jid full = self.getFullJid();
3388 if (!full.equals(conversation.getJid())) {
3389 Log.d(Config.LOGTAG, "nick changed. updating");
3390 conversation.setContactJid(full);
3391 databaseBackend.updateConversation(conversation);
3392 }
3393
3394 final Bookmark bookmark = conversation.getBookmark();
3395 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3396 if (bookmark != null && (tookProposedNickFromBookmark || Strings.isNullOrEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
3397 final Account account = conversation.getAccount();
3398 final String defaultNick = MucOptions.defaultNick(account);
3399 if (Strings.isNullOrEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3400 return;
3401 }
3402 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
3403 bookmark.setNick(full.getResource());
3404 createBookmark(bookmark.getAccount(), bookmark);
3405 }
3406 }
3407
3408 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3409 final MucOptions options = conversation.getMucOptions();
3410 final Jid joinJid = options.createJoinJid(nick);
3411 if (joinJid == null) {
3412 return false;
3413 }
3414 if (options.online()) {
3415 Account account = conversation.getAccount();
3416 options.setOnRenameListener(new OnRenameListener() {
3417
3418 @Override
3419 public void onSuccess() {
3420 callback.success(conversation);
3421 }
3422
3423 @Override
3424 public void onFailure() {
3425 callback.error(R.string.nick_in_use, conversation);
3426 }
3427 });
3428
3429 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
3430 packet.setTo(joinJid);
3431 sendPresencePacket(account, packet);
3432 } else {
3433 conversation.setContactJid(joinJid);
3434 databaseBackend.updateConversation(conversation);
3435 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3436 Bookmark bookmark = conversation.getBookmark();
3437 if (bookmark != null) {
3438 bookmark.setNick(nick);
3439 createBookmark(bookmark.getAccount(), bookmark);
3440 }
3441 joinMuc(conversation);
3442 }
3443 }
3444 return true;
3445 }
3446
3447 public void leaveMuc(Conversation conversation) {
3448 leaveMuc(conversation, false);
3449 }
3450
3451 private void leaveMuc(Conversation conversation, boolean now) {
3452 final Account account = conversation.getAccount();
3453 synchronized (account.pendingConferenceJoins) {
3454 account.pendingConferenceJoins.remove(conversation);
3455 }
3456 synchronized (account.pendingConferenceLeaves) {
3457 account.pendingConferenceLeaves.remove(conversation);
3458 }
3459 if (account.getStatus() == Account.State.ONLINE || now) {
3460 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3461 conversation.getMucOptions().setOffline();
3462 Bookmark bookmark = conversation.getBookmark();
3463 if (bookmark != null) {
3464 bookmark.setConversation(null);
3465 }
3466 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3467 } else {
3468 synchronized (account.pendingConferenceLeaves) {
3469 account.pendingConferenceLeaves.add(conversation);
3470 }
3471 }
3472 }
3473
3474 public String findConferenceServer(final Account account) {
3475 String server;
3476 if (account.getXmppConnection() != null) {
3477 server = account.getXmppConnection().getMucServer();
3478 if (server != null) {
3479 return server;
3480 }
3481 }
3482 for (Account other : getAccounts()) {
3483 if (other != account && other.getXmppConnection() != null) {
3484 server = other.getXmppConnection().getMucServer();
3485 if (server != null) {
3486 return server;
3487 }
3488 }
3489 }
3490 return null;
3491 }
3492
3493
3494 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3495 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3496 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3497 if (!TextUtils.isEmpty(name)) {
3498 configuration.putString("muc#roomconfig_roomname", name);
3499 }
3500 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3501 @Override
3502 public void onPushSucceeded() {
3503 saveConversationAsBookmark(conversation, name);
3504 callback.success(conversation);
3505 }
3506
3507 @Override
3508 public void onPushFailed() {
3509 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3510 callback.error(R.string.unable_to_set_channel_configuration, conversation);
3511 } else {
3512 callback.error(R.string.joined_an_existing_channel, conversation);
3513 }
3514 }
3515 });
3516 });
3517 }
3518
3519 public boolean createAdhocConference(final Account account,
3520 final String name,
3521 final Iterable<Jid> jids,
3522 final UiCallback<Conversation> callback) {
3523 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3524 if (account.getStatus() == Account.State.ONLINE) {
3525 try {
3526 String server = findConferenceServer(account);
3527 if (server == null) {
3528 if (callback != null) {
3529 callback.error(R.string.no_conference_server_found, null);
3530 }
3531 return false;
3532 }
3533 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
3534 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3535 joinMuc(conversation, new OnConferenceJoined() {
3536 @Override
3537 public void onConferenceJoined(final Conversation conversation) {
3538 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3539 if (!TextUtils.isEmpty(name)) {
3540 configuration.putString("muc#roomconfig_roomname", name);
3541 }
3542 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3543 @Override
3544 public void onPushSucceeded() {
3545 for (Jid invite : jids) {
3546 invite(conversation, invite);
3547 }
3548 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3549 Jid other = account.getJid().withResource(resource);
3550 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3551 directInvite(conversation, other);
3552 }
3553 saveConversationAsBookmark(conversation, name);
3554 if (callback != null) {
3555 callback.success(conversation);
3556 }
3557 }
3558
3559 @Override
3560 public void onPushFailed() {
3561 archiveConversation(conversation);
3562 if (callback != null) {
3563 callback.error(R.string.conference_creation_failed, conversation);
3564 }
3565 }
3566 });
3567 }
3568 });
3569 return true;
3570 } catch (IllegalArgumentException e) {
3571 if (callback != null) {
3572 callback.error(R.string.conference_creation_failed, null);
3573 }
3574 return false;
3575 }
3576 } else {
3577 if (callback != null) {
3578 callback.error(R.string.not_connected_try_again, null);
3579 }
3580 return false;
3581 }
3582 }
3583
3584 public void fetchConferenceConfiguration(final Conversation conversation) {
3585 fetchConferenceConfiguration(conversation, null);
3586 }
3587
3588 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3589 IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3590 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3591 @Override
3592 public void onIqPacketReceived(Account account, IqPacket packet) {
3593 if (packet.getType() == IqPacket.TYPE.RESULT) {
3594 final MucOptions mucOptions = conversation.getMucOptions();
3595 final Bookmark bookmark = conversation.getBookmark();
3596 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3597
3598 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3599 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3600 updateConversation(conversation);
3601 }
3602
3603 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3604 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3605 createBookmark(account, bookmark);
3606 }
3607 }
3608
3609
3610 if (callback != null) {
3611 callback.onConferenceConfigurationFetched(conversation);
3612 }
3613
3614
3615 updateConversationUi();
3616 } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3617 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3618 } else {
3619 if (callback != null) {
3620 callback.onFetchFailed(conversation, packet.getErrorCondition());
3621 }
3622 }
3623 }
3624 });
3625 }
3626
3627 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3628 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3629 }
3630
3631 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3632 Log.d(Config.LOGTAG, "pushing node configuration");
3633 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3634 @Override
3635 public void onIqPacketReceived(Account account, IqPacket packet) {
3636 if (packet.getType() == IqPacket.TYPE.RESULT) {
3637 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3638 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3639 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3640 if (x != null) {
3641 Data data = Data.parse(x);
3642 data.submit(options);
3643 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3644 @Override
3645 public void onIqPacketReceived(Account account, IqPacket packet) {
3646 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3647 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3648 callback.onPushSucceeded();
3649 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3650 callback.onPushFailed();
3651 }
3652 }
3653 });
3654 } else if (callback != null) {
3655 callback.onPushFailed();
3656 }
3657 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3658 callback.onPushFailed();
3659 }
3660 }
3661 });
3662 }
3663
3664 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3665 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3666 conversation.setAttribute("accept_non_anonymous", true);
3667 updateConversation(conversation);
3668 }
3669 if (options.containsKey("muc#roomconfig_moderatedroom")) {
3670 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3671 options.putString("members_by_default", moderated ? "0" : "1");
3672 }
3673 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3674 request.setTo(conversation.getJid().asBareJid());
3675 request.query("http://jabber.org/protocol/muc#owner");
3676 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3677 @Override
3678 public void onIqPacketReceived(Account account, IqPacket packet) {
3679 if (packet.getType() == IqPacket.TYPE.RESULT) {
3680 final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3681 data.submit(options);
3682 final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3683 set.setTo(conversation.getJid().asBareJid());
3684 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3685 sendIqPacket(account, set, new OnIqPacketReceived() {
3686 @Override
3687 public void onIqPacketReceived(Account account, IqPacket packet) {
3688 if (callback != null) {
3689 if (packet.getType() == IqPacket.TYPE.RESULT) {
3690 callback.onPushSucceeded();
3691 } else {
3692 callback.onPushFailed();
3693 }
3694 }
3695 }
3696 });
3697 } else {
3698 if (callback != null) {
3699 callback.onPushFailed();
3700 }
3701 }
3702 }
3703 });
3704 }
3705
3706 public void pushSubjectToConference(final Conversation conference, final String subject) {
3707 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3708 this.sendMessagePacket(conference.getAccount(), packet);
3709 }
3710
3711 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3712 final Jid jid = user.asBareJid();
3713 final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3714 sendIqPacket(conference.getAccount(), request, (account, response) -> {
3715 if (response.getType() == IqPacket.TYPE.RESULT) {
3716 conference.getMucOptions().changeAffiliation(jid, affiliation);
3717 getAvatarService().clear(conference);
3718 if (callback != null) {
3719 callback.onAffiliationChangedSuccessful(jid);
3720 } else {
3721 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3722 }
3723 } else if (callback != null) {
3724 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3725 } else {
3726 Log.d(Config.LOGTAG, "unable to change affiliation");
3727 }
3728 });
3729 }
3730
3731 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3732 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3733 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3734 if (packet.getType() != IqPacket.TYPE.RESULT) {
3735 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3736 }
3737 });
3738 }
3739
3740 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3741 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3742 request.setTo(conversation.getJid().asBareJid());
3743 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3744 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3745 @Override
3746 public void onIqPacketReceived(Account account, IqPacket packet) {
3747 if (packet.getType() == IqPacket.TYPE.RESULT) {
3748 if (callback != null) {
3749 callback.onRoomDestroySucceeded();
3750 }
3751 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3752 if (callback != null) {
3753 callback.onRoomDestroyFailed();
3754 }
3755 }
3756 }
3757 });
3758 }
3759
3760 private void disconnect(final Account account, boolean force) {
3761 final XmppConnection connection = account.getXmppConnection();
3762 if (connection == null) {
3763 return;
3764 }
3765 if (!force) {
3766 final List<Conversation> conversations = getConversations();
3767 for (Conversation conversation : conversations) {
3768 if (conversation.getAccount() == account) {
3769 if (conversation.getMode() == Conversation.MODE_MULTI) {
3770 leaveMuc(conversation, true);
3771 }
3772 }
3773 }
3774 sendOfflinePresence(account);
3775 }
3776 connection.disconnect(force);
3777 }
3778
3779 @Override
3780 public IBinder onBind(Intent intent) {
3781 return mBinder;
3782 }
3783
3784 public void updateMessage(Message message) {
3785 updateMessage(message, true);
3786 }
3787
3788 public void updateMessage(Message message, boolean includeBody) {
3789 databaseBackend.updateMessage(message, includeBody);
3790 updateConversationUi();
3791 }
3792
3793 public void createMessageAsync(final Message message) {
3794 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3795 }
3796
3797 public void updateMessage(Message message, String uuid) {
3798 if (!databaseBackend.updateMessage(message, uuid)) {
3799 Log.e(Config.LOGTAG, "error updated message in DB after edit");
3800 }
3801 updateConversationUi();
3802 }
3803
3804 protected void syncDirtyContacts(Account account) {
3805 for (Contact contact : account.getRoster().getContacts()) {
3806 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3807 pushContactToServer(contact);
3808 }
3809 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3810 deleteContactOnServer(contact);
3811 }
3812 }
3813 }
3814
3815 public void createContact(final Contact contact, final boolean autoGrant) {
3816 createContact(contact, autoGrant, null);
3817 }
3818
3819 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3820 if (autoGrant) {
3821 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3822 contact.setOption(Contact.Options.ASKING);
3823 }
3824 pushContactToServer(contact, preAuth);
3825 }
3826
3827 public void pushContactToServer(final Contact contact) {
3828 pushContactToServer(contact, null);
3829 }
3830
3831 private void pushContactToServer(final Contact contact, final String preAuth) {
3832 contact.resetOption(Contact.Options.DIRTY_DELETE);
3833 contact.setOption(Contact.Options.DIRTY_PUSH);
3834 final Account account = contact.getAccount();
3835 if (account.getStatus() == Account.State.ONLINE) {
3836 final boolean ask = contact.getOption(Contact.Options.ASKING);
3837 final boolean sendUpdates = contact
3838 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3839 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3840 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3841 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3842 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3843 if (sendUpdates) {
3844 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3845 }
3846 if (ask) {
3847 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3848 }
3849 } else {
3850 syncRoster(contact.getAccount());
3851 }
3852 }
3853
3854 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3855 new Thread(() -> {
3856 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3857 final int size = Config.AVATAR_SIZE;
3858 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3859 if (avatar != null) {
3860 if (!getFileBackend().save(avatar)) {
3861 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3862 return;
3863 }
3864 avatar.owner = conversation.getJid().asBareJid();
3865 publishMucAvatar(conversation, avatar, callback);
3866 } else {
3867 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3868 }
3869 }).start();
3870 }
3871
3872 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3873 new Thread(() -> {
3874 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3875 final int size = Config.AVATAR_SIZE;
3876 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3877 if (avatar != null) {
3878 if (!getFileBackend().save(avatar)) {
3879 Log.d(Config.LOGTAG, "unable to save vcard");
3880 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3881 return;
3882 }
3883 publishAvatar(account, avatar, callback);
3884 } else {
3885 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3886 }
3887 }).start();
3888
3889 }
3890
3891 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3892 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3893 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3894 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3895 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3896 Element vcard = response.findChild("vCard", "vcard-temp");
3897 if (vcard == null) {
3898 vcard = new Element("vCard", "vcard-temp");
3899 }
3900 Element photo = vcard.findChild("PHOTO");
3901 if (photo == null) {
3902 photo = vcard.addChild("PHOTO");
3903 }
3904 photo.clearChildren();
3905 photo.addChild("TYPE").setContent(avatar.type);
3906 photo.addChild("BINVAL").setContent(avatar.image);
3907 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3908 publication.setTo(conversation.getJid().asBareJid());
3909 publication.addChild(vcard);
3910 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3911 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3912 callback.onAvatarPublicationSucceeded();
3913 } else {
3914 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3915 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3916 }
3917 });
3918 } else {
3919 Log.d(Config.LOGTAG, "failed to request vcard " + response);
3920 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3921 }
3922 });
3923 }
3924
3925 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3926 final Bundle options;
3927 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3928 options = PublishOptions.openAccess();
3929 } else {
3930 options = null;
3931 }
3932 publishAvatar(account, avatar, options, true, callback);
3933 }
3934
3935 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3936 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3937 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3938 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3939
3940 @Override
3941 public void onIqPacketReceived(Account account, IqPacket result) {
3942 if (result.getType() == IqPacket.TYPE.RESULT) {
3943 publishAvatarMetadata(account, avatar, options, true, callback);
3944 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3945 pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
3946 @Override
3947 public void onPushSucceeded() {
3948 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3949 publishAvatar(account, avatar, options, false, callback);
3950 }
3951
3952 @Override
3953 public void onPushFailed() {
3954 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3955 publishAvatar(account, avatar, null, false, callback);
3956 }
3957 });
3958 } else {
3959 Element error = result.findChild("error");
3960 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3961 if (callback != null) {
3962 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3963 }
3964 }
3965 }
3966 });
3967 }
3968
3969 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3970 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3971 sendIqPacket(account, packet, new OnIqPacketReceived() {
3972 @Override
3973 public void onIqPacketReceived(Account account, IqPacket result) {
3974 if (result.getType() == IqPacket.TYPE.RESULT) {
3975 if (account.setAvatar(avatar.getFilename())) {
3976 getAvatarService().clear(account);
3977 databaseBackend.updateAccount(account);
3978 notifyAccountAvatarHasChanged(account);
3979 }
3980 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3981 if (callback != null) {
3982 callback.onAvatarPublicationSucceeded();
3983 }
3984 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3985 pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
3986 @Override
3987 public void onPushSucceeded() {
3988 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3989 publishAvatarMetadata(account, avatar, options, false, callback);
3990 }
3991
3992 @Override
3993 public void onPushFailed() {
3994 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3995 publishAvatarMetadata(account, avatar, null, false, callback);
3996 }
3997 });
3998 } else {
3999 if (callback != null) {
4000 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4001 }
4002 }
4003 }
4004 });
4005 }
4006
4007 public void republishAvatarIfNeeded(Account account) {
4008 if (account.getAxolotlService().isPepBroken()) {
4009 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
4010 return;
4011 }
4012 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4013 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4014
4015 private Avatar parseAvatar(IqPacket packet) {
4016 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4017 if (pubsub != null) {
4018 Element items = pubsub.findChild("items");
4019 if (items != null) {
4020 return Avatar.parseMetadata(items);
4021 }
4022 }
4023 return null;
4024 }
4025
4026 private boolean errorIsItemNotFound(IqPacket packet) {
4027 Element error = packet.findChild("error");
4028 return packet.getType() == IqPacket.TYPE.ERROR
4029 && error != null
4030 && error.hasChild("item-not-found");
4031 }
4032
4033 @Override
4034 public void onIqPacketReceived(Account account, IqPacket packet) {
4035 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
4036 Avatar serverAvatar = parseAvatar(packet);
4037 if (serverAvatar == null && account.getAvatar() != null) {
4038 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4039 if (avatar != null) {
4040 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
4041 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
4042 } else {
4043 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
4044 }
4045 }
4046 }
4047 }
4048 });
4049 }
4050
4051 public void fetchAvatar(Account account, Avatar avatar) {
4052 fetchAvatar(account, avatar, null);
4053 }
4054
4055 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4056 final String KEY = generateFetchKey(account, avatar);
4057 synchronized (this.mInProgressAvatarFetches) {
4058 if (mInProgressAvatarFetches.add(KEY)) {
4059 switch (avatar.origin) {
4060 case PEP:
4061 this.mInProgressAvatarFetches.add(KEY);
4062 fetchAvatarPep(account, avatar, callback);
4063 break;
4064 case VCARD:
4065 this.mInProgressAvatarFetches.add(KEY);
4066 fetchAvatarVcard(account, avatar, callback);
4067 break;
4068 }
4069 } else if (avatar.origin == Avatar.Origin.PEP) {
4070 mOmittedPepAvatarFetches.add(KEY);
4071 } else {
4072 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
4073 }
4074 }
4075 }
4076
4077 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4078 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
4079 sendIqPacket(account, packet, (a, result) -> {
4080 synchronized (mInProgressAvatarFetches) {
4081 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
4082 }
4083 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
4084 if (result.getType() == IqPacket.TYPE.RESULT) {
4085 avatar.image = mIqParser.avatarData(result);
4086 if (avatar.image != null) {
4087 if (getFileBackend().save(avatar)) {
4088 if (a.getJid().asBareJid().equals(avatar.owner)) {
4089 if (a.setAvatar(avatar.getFilename())) {
4090 databaseBackend.updateAccount(a);
4091 }
4092 getAvatarService().clear(a);
4093 updateConversationUi();
4094 updateAccountUi();
4095 } else {
4096 final Contact contact = a.getRoster().getContact(avatar.owner);
4097 contact.setAvatar(avatar);
4098 syncRoster(account);
4099 getAvatarService().clear(contact);
4100 updateConversationUi();
4101 updateRosterUi();
4102 }
4103 if (callback != null) {
4104 callback.success(avatar);
4105 }
4106 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
4107 return;
4108 }
4109 } else {
4110
4111 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4112 }
4113 } else {
4114 Element error = result.findChild("error");
4115 if (error == null) {
4116 Log.d(Config.LOGTAG, ERROR + "(server error)");
4117 } else {
4118 Log.d(Config.LOGTAG, ERROR + error.toString());
4119 }
4120 }
4121 if (callback != null) {
4122 callback.error(0, null);
4123 }
4124
4125 });
4126 }
4127
4128 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4129 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4130 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4131 @Override
4132 public void onIqPacketReceived(Account account, IqPacket packet) {
4133 final boolean previouslyOmittedPepFetch;
4134 synchronized (mInProgressAvatarFetches) {
4135 final String KEY = generateFetchKey(account, avatar);
4136 mInProgressAvatarFetches.remove(KEY);
4137 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4138 }
4139 if (packet.getType() == IqPacket.TYPE.RESULT) {
4140 Element vCard = packet.findChild("vCard", "vcard-temp");
4141 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4142 String image = photo != null ? photo.findChildContent("BINVAL") : null;
4143 if (image != null) {
4144 avatar.image = image;
4145 if (getFileBackend().save(avatar)) {
4146 Log.d(Config.LOGTAG, account.getJid().asBareJid()
4147 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4148 if (avatar.owner.isBareJid()) {
4149 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4150 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4151 account.setAvatar(avatar.getFilename());
4152 databaseBackend.updateAccount(account);
4153 getAvatarService().clear(account);
4154 updateAccountUi();
4155 } else {
4156 final Contact contact = account.getRoster().getContact(avatar.owner);
4157 contact.setAvatar(avatar, previouslyOmittedPepFetch);
4158 syncRoster(account);
4159 getAvatarService().clear(contact);
4160 updateRosterUi();
4161 }
4162 updateConversationUi();
4163 } else {
4164 Conversation conversation = find(account, avatar.owner.asBareJid());
4165 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4166 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4167 if (user != null) {
4168 if (user.setAvatar(avatar)) {
4169 getAvatarService().clear(user);
4170 updateConversationUi();
4171 updateMucRosterUi();
4172 }
4173 if (user.getRealJid() != null) {
4174 Contact contact = account.getRoster().getContact(user.getRealJid());
4175 contact.setAvatar(avatar);
4176 syncRoster(account);
4177 getAvatarService().clear(contact);
4178 updateRosterUi();
4179 }
4180 }
4181 }
4182 }
4183 }
4184 }
4185 }
4186 }
4187 });
4188 }
4189
4190 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
4191 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4192 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4193
4194 @Override
4195 public void onIqPacketReceived(Account account, IqPacket packet) {
4196 if (packet.getType() == IqPacket.TYPE.RESULT) {
4197 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4198 if (pubsub != null) {
4199 Element items = pubsub.findChild("items");
4200 if (items != null) {
4201 Avatar avatar = Avatar.parseMetadata(items);
4202 if (avatar != null) {
4203 avatar.owner = account.getJid().asBareJid();
4204 if (fileBackend.isAvatarCached(avatar)) {
4205 if (account.setAvatar(avatar.getFilename())) {
4206 databaseBackend.updateAccount(account);
4207 }
4208 getAvatarService().clear(account);
4209 callback.success(avatar);
4210 } else {
4211 fetchAvatarPep(account, avatar, callback);
4212 }
4213 return;
4214 }
4215 }
4216 }
4217 }
4218 callback.error(0, null);
4219 }
4220 });
4221 }
4222
4223 public void notifyAccountAvatarHasChanged(final Account account) {
4224 final XmppConnection connection = account.getXmppConnection();
4225 if (connection != null && connection.getFeatures().bookmarksConversion()) {
4226 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4227 for (Conversation conversation : conversations) {
4228 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4229 final MucOptions mucOptions = conversation.getMucOptions();
4230 if (mucOptions.online()) {
4231 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
4232 packet.setTo(mucOptions.getSelf().getFullJid());
4233 connection.sendPresencePacket(packet);
4234 }
4235 }
4236 }
4237 }
4238 }
4239
4240 public void deleteContactOnServer(Contact contact) {
4241 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4242 contact.resetOption(Contact.Options.DIRTY_PUSH);
4243 contact.setOption(Contact.Options.DIRTY_DELETE);
4244 Account account = contact.getAccount();
4245 if (account.getStatus() == Account.State.ONLINE) {
4246 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4247 Element item = iq.query(Namespace.ROSTER).addChild("item");
4248 item.setAttribute("jid", contact.getJid());
4249 item.setAttribute("subscription", "remove");
4250 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4251 }
4252 }
4253
4254 public void updateConversation(final Conversation conversation) {
4255 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4256 }
4257
4258 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4259 synchronized (account) {
4260 final XmppConnection existingConnection = account.getXmppConnection();
4261 final XmppConnection connection;
4262 if (existingConnection != null) {
4263 connection = existingConnection;
4264 } else if (account.isConnectionEnabled()) {
4265 connection = createConnection(account);
4266 account.setXmppConnection(connection);
4267 } else {
4268 return;
4269 }
4270 final boolean hasInternet = hasInternetConnection();
4271 if (account.isConnectionEnabled() && hasInternet) {
4272 if (!force) {
4273 disconnect(account, false);
4274 }
4275 Thread thread = new Thread(connection);
4276 connection.setInteractive(interactive);
4277 connection.prepareNewConnection();
4278 connection.interrupt();
4279 thread.start();
4280 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4281 } else {
4282 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4283 account.getRoster().clearPresences();
4284 connection.resetEverything();
4285 final AxolotlService axolotlService = account.getAxolotlService();
4286 if (axolotlService != null) {
4287 axolotlService.resetBrokenness();
4288 }
4289 if (!hasInternet) {
4290 account.setStatus(Account.State.NO_INTERNET);
4291 }
4292 }
4293 }
4294 }
4295
4296 public void reconnectAccountInBackground(final Account account) {
4297 new Thread(() -> reconnectAccount(account, false, true)).start();
4298 }
4299
4300 public void invite(final Conversation conversation, final Jid contact) {
4301 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4302 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4303 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4304 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4305 }
4306 final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4307 sendMessagePacket(conversation.getAccount(), packet);
4308 }
4309
4310 public void directInvite(Conversation conversation, Jid jid) {
4311 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4312 sendMessagePacket(conversation.getAccount(), packet);
4313 }
4314
4315 public void resetSendingToWaiting(Account account) {
4316 for (Conversation conversation : getConversations()) {
4317 if (conversation.getAccount() == account) {
4318 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4319 }
4320 }
4321 }
4322
4323 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4324 return markMessage(account, recipient, uuid, status, null);
4325 }
4326
4327 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4328 if (uuid == null) {
4329 return null;
4330 }
4331 for (Conversation conversation : getConversations()) {
4332 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4333 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4334 if (message != null) {
4335 markMessage(message, status, errorMessage);
4336 }
4337 return message;
4338 }
4339 }
4340 return null;
4341 }
4342
4343 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4344 return markMessage(conversation, uuid, status, serverMessageId, null);
4345 }
4346
4347 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4348 if (uuid == null) {
4349 return false;
4350 } else {
4351 final Message message = conversation.findSentMessageWithUuid(uuid);
4352 if (message != null) {
4353 if (message.getServerMsgId() == null) {
4354 message.setServerMsgId(serverMessageId);
4355 }
4356 if (message.getEncryption() == Message.ENCRYPTION_NONE
4357 && message.isTypeText()
4358 && isBodyModified(message, body)) {
4359 message.setBody(body.content);
4360 if (body.count > 1) {
4361 message.setBodyLanguage(body.language);
4362 }
4363 markMessage(message, status, null, true);
4364 } else {
4365 markMessage(message, status);
4366 }
4367 return true;
4368 } else {
4369 return false;
4370 }
4371 }
4372 }
4373
4374 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4375 if (body == null || body.content == null) {
4376 return false;
4377 }
4378 return !body.content.equals(message.getBody());
4379 }
4380
4381 public void markMessage(Message message, int status) {
4382 markMessage(message, status, null);
4383 }
4384
4385
4386 public void markMessage(final Message message, final int status, final String errorMessage) {
4387 markMessage(message, status, errorMessage, false);
4388 }
4389
4390 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4391 final int oldStatus = message.getStatus();
4392 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4393 return;
4394 }
4395 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4396 return;
4397 }
4398 message.setErrorMessage(errorMessage);
4399 message.setStatus(status);
4400 databaseBackend.updateMessage(message, includeBody);
4401 updateConversationUi();
4402 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4403 mNotificationService.pushFailedDelivery(message);
4404 }
4405 }
4406
4407 private SharedPreferences getPreferences() {
4408 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4409 }
4410
4411 public long getAutomaticMessageDeletionDate() {
4412 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4413 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4414 }
4415
4416 public long getLongPreference(String name, @IntegerRes int res) {
4417 long defaultValue = getResources().getInteger(res);
4418 try {
4419 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4420 } catch (NumberFormatException e) {
4421 return defaultValue;
4422 }
4423 }
4424
4425 public boolean getBooleanPreference(String name, @BoolRes int res) {
4426 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4427 }
4428
4429 public boolean confirmMessages() {
4430 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4431 }
4432
4433 public boolean allowMessageCorrection() {
4434 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4435 }
4436
4437 public boolean sendChatStates() {
4438 return getBooleanPreference("chat_states", R.bool.chat_states);
4439 }
4440
4441 private boolean synchronizeWithBookmarks() {
4442 return getBooleanPreference("autojoin", R.bool.autojoin);
4443 }
4444
4445 public boolean useTorToConnect() {
4446 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
4447 }
4448
4449 public boolean showExtendedConnectionOptions() {
4450 return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4451 }
4452
4453 public boolean broadcastLastActivity() {
4454 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4455 }
4456
4457 public int unreadCount() {
4458 int count = 0;
4459 for (Conversation conversation : getConversations()) {
4460 count += conversation.unreadCount();
4461 }
4462 return count;
4463 }
4464
4465
4466 private <T> List<T> threadSafeList(Set<T> set) {
4467 synchronized (LISTENER_LOCK) {
4468 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4469 }
4470 }
4471
4472 public void showErrorToastInUi(int resId) {
4473 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4474 listener.onShowErrorToast(resId);
4475 }
4476 }
4477
4478 public void updateConversationUi() {
4479 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4480 listener.onConversationUpdate();
4481 }
4482 }
4483
4484 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4485 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4486 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4487 }
4488 }
4489
4490 public void notifyJingleRtpConnectionUpdate(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices) {
4491 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4492 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4493 }
4494 }
4495
4496 public void updateAccountUi() {
4497 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4498 listener.onAccountUpdate();
4499 }
4500 }
4501
4502 public void updateRosterUi() {
4503 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4504 listener.onRosterUpdate();
4505 }
4506 }
4507
4508 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4509 if (mOnCaptchaRequested.size() > 0) {
4510 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4511 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4512 (int) (captcha.getHeight() * metrics.scaledDensity), false);
4513 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4514 listener.onCaptchaRequested(account, id, data, scaled);
4515 }
4516 return true;
4517 }
4518 return false;
4519 }
4520
4521 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4522 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4523 listener.OnUpdateBlocklist(status);
4524 }
4525 }
4526
4527 public void updateMucRosterUi() {
4528 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4529 listener.onMucRosterUpdate();
4530 }
4531 }
4532
4533 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4534 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4535 listener.onKeyStatusUpdated(report);
4536 }
4537 }
4538
4539 public Account findAccountByJid(final Jid jid) {
4540 for (final Account account : this.accounts) {
4541 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4542 return account;
4543 }
4544 }
4545 return null;
4546 }
4547
4548 public Account findAccountByUuid(final String uuid) {
4549 for (Account account : this.accounts) {
4550 if (account.getUuid().equals(uuid)) {
4551 return account;
4552 }
4553 }
4554 return null;
4555 }
4556
4557 public Conversation findConversationByUuid(String uuid) {
4558 for (Conversation conversation : getConversations()) {
4559 if (conversation.getUuid().equals(uuid)) {
4560 return conversation;
4561 }
4562 }
4563 return null;
4564 }
4565
4566 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4567 List<Conversation> findings = new ArrayList<>();
4568 for (Conversation c : getConversations()) {
4569 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4570 findings.add(c);
4571 }
4572 }
4573 return findings.size() == 1 ? findings.get(0) : null;
4574 }
4575
4576 public boolean markRead(final Conversation conversation, boolean dismiss) {
4577 return markRead(conversation, null, dismiss).size() > 0;
4578 }
4579
4580 public void markRead(final Conversation conversation) {
4581 markRead(conversation, null, true);
4582 }
4583
4584 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4585 if (dismiss) {
4586 mNotificationService.clear(conversation);
4587 }
4588 final List<Message> readMessages = conversation.markRead(upToUuid);
4589 if (readMessages.size() > 0) {
4590 Runnable runnable = () -> {
4591 for (Message message : readMessages) {
4592 databaseBackend.updateMessage(message, false);
4593 }
4594 };
4595 mDatabaseWriterExecutor.execute(runnable);
4596 updateConversationUi();
4597 updateUnreadCountBadge();
4598 return readMessages;
4599 } else {
4600 return readMessages;
4601 }
4602 }
4603
4604 public synchronized void updateUnreadCountBadge() {
4605 int count = unreadCount();
4606 if (unreadCount != count) {
4607 Log.d(Config.LOGTAG, "update unread count to " + count);
4608 if (count > 0) {
4609 ShortcutBadger.applyCount(getApplicationContext(), count);
4610 } else {
4611 ShortcutBadger.removeCount(getApplicationContext());
4612 }
4613 unreadCount = count;
4614 }
4615 }
4616
4617 public void sendReadMarker(final Conversation conversation, final String upToUuid) {
4618 final boolean isPrivateAndNonAnonymousMuc =
4619 conversation.getMode() == Conversation.MODE_MULTI
4620 && conversation.isPrivateAndNonAnonymous();
4621 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4622 if (readMessages.isEmpty()) {
4623 return;
4624 }
4625 final var account = conversation.getAccount();
4626 final var connection = account.getXmppConnection();
4627 updateConversationUi();
4628 final var last =
4629 Iterables.getLast(
4630 Collections2.filter(
4631 readMessages,
4632 m ->
4633 !m.isPrivateMessage()
4634 && m.getStatus() == Message.STATUS_RECEIVED),
4635 null);
4636 if (last == null) {
4637 return;
4638 }
4639
4640 final boolean sendDisplayedMarker =
4641 confirmMessages()
4642 && (last.trusted() || isPrivateAndNonAnonymousMuc)
4643 && last.getRemoteMsgId() != null
4644 && (last.markable || isPrivateAndNonAnonymousMuc);
4645 final boolean serverAssist =
4646 connection != null && connection.getFeatures().mdsServerAssist();
4647
4648 final String stanzaId = last.getServerMsgId();
4649
4650 if (sendDisplayedMarker && serverAssist) {
4651 final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
4652 final MessagePacket packet = mMessageGenerator.confirm(last);
4653 packet.addChild(mdsDisplayed);
4654 if (!last.isPrivateMessage()) {
4655 packet.setTo(packet.getTo().asBareJid());
4656 }
4657 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": server assisted "+packet);
4658 this.sendMessagePacket(account, packet);
4659 } else {
4660 publishMds(last);
4661 // read markers will be sent after MDS to flush the CSI stanza queue
4662 if (sendDisplayedMarker) {
4663 Log.d(
4664 Config.LOGTAG,
4665 conversation.getAccount().getJid().asBareJid()
4666 + ": sending displayed marker to "
4667 + last.getCounterpart().toString());
4668 final MessagePacket packet = mMessageGenerator.confirm(last);
4669 this.sendMessagePacket(account, packet);
4670 }
4671 }
4672 }
4673
4674 private void publishMds(@Nullable final Message message) {
4675 final String stanzaId = message == null ? null : message.getServerMsgId();
4676 if (Strings.isNullOrEmpty(stanzaId)) {
4677 return;
4678 }
4679 final Conversation conversation;
4680 final var conversational = message.getConversation();
4681 if (conversational instanceof Conversation c) {
4682 conversation = c;
4683 } else {
4684 return;
4685 }
4686 final var account = conversation.getAccount();
4687 final var connection = account.getXmppConnection();
4688 if (connection == null || !connection.getFeatures().mds()) {
4689 return;
4690 }
4691 final Jid itemId;
4692 if (message.isPrivateMessage()) {
4693 itemId = message.getCounterpart();
4694 } else {
4695 itemId = conversation.getJid().asBareJid();
4696 }
4697 Log.d(Config.LOGTAG,"publishing mds for "+itemId+"/"+stanzaId);
4698 publishMds(account, itemId, stanzaId, conversation);
4699 }
4700
4701 private void publishMds(
4702 final Account account, final Jid itemId, final String stanzaId, final Conversation conversation) {
4703 final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
4704 pushNodeAndEnforcePublishOptions(
4705 account,
4706 Namespace.MDS_DISPLAYED,
4707 item,
4708 itemId.toEscapedString(),
4709 PublishOptions.persistentWhitelistAccessMaxItems());
4710 }
4711
4712 public MemorizingTrustManager getMemorizingTrustManager() {
4713 return this.mMemorizingTrustManager;
4714 }
4715
4716 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4717 this.mMemorizingTrustManager = trustManager;
4718 }
4719
4720 public void updateMemorizingTrustmanager() {
4721 final MemorizingTrustManager tm;
4722 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4723 if (dontTrustSystemCAs) {
4724 tm = new MemorizingTrustManager(getApplicationContext(), null);
4725 } else {
4726 tm = new MemorizingTrustManager(getApplicationContext());
4727 }
4728 setMemorizingTrustManager(tm);
4729 }
4730
4731 public LruCache<String, Bitmap> getBitmapCache() {
4732 return this.mBitmapCache;
4733 }
4734
4735 public Collection<String> getKnownHosts() {
4736 final Set<String> hosts = new HashSet<>();
4737 for (final Account account : getAccounts()) {
4738 hosts.add(account.getServer());
4739 for (final Contact contact : account.getRoster().getContacts()) {
4740 if (contact.showInRoster()) {
4741 final String server = contact.getServer();
4742 if (server != null) {
4743 hosts.add(server);
4744 }
4745 }
4746 }
4747 }
4748 if (Config.QUICKSY_DOMAIN != null) {
4749 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4750 }
4751 if (Config.DOMAIN_LOCK != null) {
4752 hosts.add(Config.DOMAIN_LOCK);
4753 }
4754 if (Config.MAGIC_CREATE_DOMAIN != null) {
4755 hosts.add(Config.MAGIC_CREATE_DOMAIN);
4756 }
4757 return hosts;
4758 }
4759
4760 public Collection<String> getKnownConferenceHosts() {
4761 final Set<String> mucServers = new HashSet<>();
4762 for (final Account account : accounts) {
4763 if (account.getXmppConnection() != null) {
4764 mucServers.addAll(account.getXmppConnection().getMucServers());
4765 for (final Bookmark bookmark : account.getBookmarks()) {
4766 final Jid jid = bookmark.getJid();
4767 final String s = jid == null ? null : jid.getDomain().toEscapedString();
4768 if (s != null) {
4769 mucServers.add(s);
4770 }
4771 }
4772 }
4773 }
4774 return mucServers;
4775 }
4776
4777 public void sendMessagePacket(Account account, MessagePacket packet) {
4778 final XmppConnection connection = account.getXmppConnection();
4779 if (connection != null) {
4780 connection.sendMessagePacket(packet);
4781 }
4782 }
4783
4784 public void sendPresencePacket(Account account, PresencePacket packet) {
4785 XmppConnection connection = account.getXmppConnection();
4786 if (connection != null) {
4787 connection.sendPresencePacket(packet);
4788 }
4789 }
4790
4791 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4792 final XmppConnection connection = account.getXmppConnection();
4793 if (connection != null) {
4794 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4795 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4796 }
4797 }
4798
4799 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4800 final XmppConnection connection = account.getXmppConnection();
4801 if (connection != null) {
4802 connection.sendIqPacket(packet, callback);
4803 } else if (callback != null) {
4804 callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4805 }
4806 }
4807
4808 public void sendPresence(final Account account) {
4809 sendPresence(account, checkListeners() && broadcastLastActivity());
4810 }
4811
4812 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4813 final Presence.Status status;
4814 if (manuallyChangePresence()) {
4815 status = account.getPresenceStatus();
4816 } else {
4817 status = getTargetPresence();
4818 }
4819 final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4820 if (mLastActivity > 0 && includeIdleTimestamp) {
4821 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4822 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4823 }
4824 sendPresencePacket(account, packet);
4825 }
4826
4827 private void deactivateGracePeriod() {
4828 for (Account account : getAccounts()) {
4829 account.deactivateGracePeriod();
4830 }
4831 }
4832
4833 public void refreshAllPresences() {
4834 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4835 for (Account account : getAccounts()) {
4836 if (account.isConnectionEnabled()) {
4837 sendPresence(account, includeIdleTimestamp);
4838 }
4839 }
4840 }
4841
4842 private void refreshAllFcmTokens() {
4843 for (Account account : getAccounts()) {
4844 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4845 mPushManagementService.registerPushTokenOnServer(account);
4846 }
4847 }
4848 }
4849
4850
4851
4852 private void sendOfflinePresence(final Account account) {
4853 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4854 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4855 }
4856
4857 public MessageGenerator getMessageGenerator() {
4858 return this.mMessageGenerator;
4859 }
4860
4861 public PresenceGenerator getPresenceGenerator() {
4862 return this.mPresenceGenerator;
4863 }
4864
4865 public IqGenerator getIqGenerator() {
4866 return this.mIqGenerator;
4867 }
4868
4869 public IqParser getIqParser() {
4870 return this.mIqParser;
4871 }
4872
4873 public JingleConnectionManager getJingleConnectionManager() {
4874 return this.mJingleConnectionManager;
4875 }
4876
4877 private boolean hasJingleRtpConnection(final Account account) {
4878 return this.mJingleConnectionManager.hasJingleRtpConnection(account);
4879 }
4880
4881 public MessageArchiveService getMessageArchiveService() {
4882 return this.mMessageArchiveService;
4883 }
4884
4885 public QuickConversationsService getQuickConversationsService() {
4886 return this.mQuickConversationsService;
4887 }
4888
4889 public List<Contact> findContacts(Jid jid, String accountJid) {
4890 ArrayList<Contact> contacts = new ArrayList<>();
4891 for (Account account : getAccounts()) {
4892 if ((account.isEnabled() || accountJid != null)
4893 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4894 Contact contact = account.getRoster().getContactFromContactList(jid);
4895 if (contact != null) {
4896 contacts.add(contact);
4897 }
4898 }
4899 }
4900 return contacts;
4901 }
4902
4903 public Conversation findFirstMuc(Jid jid) {
4904 for (Conversation conversation : getConversations()) {
4905 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4906 return conversation;
4907 }
4908 }
4909 return null;
4910 }
4911
4912 public NotificationService getNotificationService() {
4913 return this.mNotificationService;
4914 }
4915
4916 public HttpConnectionManager getHttpConnectionManager() {
4917 return this.mHttpConnectionManager;
4918 }
4919
4920 public void resendFailedMessages(final Message message) {
4921 final Collection<Message> messages = new ArrayList<>();
4922 Message current = message;
4923 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4924 messages.add(current);
4925 if (current.mergeable(current.next())) {
4926 current = current.next();
4927 } else {
4928 break;
4929 }
4930 }
4931 for (final Message msg : messages) {
4932 msg.setTime(System.currentTimeMillis());
4933 markMessage(msg, Message.STATUS_WAITING);
4934 this.resendMessage(msg, false);
4935 }
4936 if (message.getConversation() instanceof Conversation) {
4937 ((Conversation) message.getConversation()).sort();
4938 }
4939 updateConversationUi();
4940 }
4941
4942 public void clearConversationHistory(final Conversation conversation) {
4943 final long clearDate;
4944 final String reference;
4945 if (conversation.countMessages() > 0) {
4946 Message latestMessage = conversation.getLatestMessage();
4947 clearDate = latestMessage.getTimeSent() + 1000;
4948 reference = latestMessage.getServerMsgId();
4949 } else {
4950 clearDate = System.currentTimeMillis();
4951 reference = null;
4952 }
4953 conversation.clearMessages();
4954 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4955 conversation.setLastClearHistory(clearDate, reference);
4956 Runnable runnable = () -> {
4957 databaseBackend.deleteMessagesInConversation(conversation);
4958 databaseBackend.updateConversation(conversation);
4959 };
4960 mDatabaseWriterExecutor.execute(runnable);
4961 }
4962
4963 public boolean sendBlockRequest(final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
4964 if (blockable != null && blockable.getBlockedJid() != null) {
4965 final Jid jid = blockable.getBlockedJid();
4966 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId), (a, response) -> {
4967 if (response.getType() == IqPacket.TYPE.RESULT) {
4968 a.getBlocklist().add(jid);
4969 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4970 }
4971 });
4972 if (blockable.getBlockedJid().isFullJid()) {
4973 return false;
4974 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4975 updateConversationUi();
4976 return true;
4977 } else {
4978 return false;
4979 }
4980 } else {
4981 return false;
4982 }
4983 }
4984
4985 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4986 boolean removed = false;
4987 synchronized (this.conversations) {
4988 boolean domainJid = blockedJid.getLocal() == null;
4989 for (Conversation conversation : this.conversations) {
4990 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4991 || blockedJid.equals(conversation.getJid().asBareJid());
4992 if (conversation.getAccount() == account
4993 && conversation.getMode() == Conversation.MODE_SINGLE
4994 && jidMatches) {
4995 this.conversations.remove(conversation);
4996 markRead(conversation);
4997 conversation.setStatus(Conversation.STATUS_ARCHIVED);
4998 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4999 updateConversation(conversation);
5000 removed = true;
5001 }
5002 }
5003 }
5004 return removed;
5005 }
5006
5007 public void sendUnblockRequest(final Blockable blockable) {
5008 if (blockable != null && blockable.getJid() != null) {
5009 final Jid jid = blockable.getBlockedJid();
5010 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
5011 @Override
5012 public void onIqPacketReceived(final Account account, final IqPacket packet) {
5013 if (packet.getType() == IqPacket.TYPE.RESULT) {
5014 account.getBlocklist().remove(jid);
5015 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
5016 }
5017 }
5018 });
5019 }
5020 }
5021
5022 public void publishDisplayName(Account account) {
5023 String displayName = account.getDisplayName();
5024 final IqPacket request;
5025 if (TextUtils.isEmpty(displayName)) {
5026 request = mIqGenerator.deleteNode(Namespace.NICK);
5027 } else {
5028 request = mIqGenerator.publishNick(displayName);
5029 }
5030 mAvatarService.clear(account);
5031 sendIqPacket(account, request, (account1, packet) -> {
5032 if (packet.getType() == IqPacket.TYPE.ERROR) {
5033 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet);
5034 }
5035 });
5036 }
5037
5038 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
5039 ServiceDiscoveryResult result = discoCache.get(key);
5040 if (result != null) {
5041 return result;
5042 } else {
5043 result = databaseBackend.findDiscoveryResult(key.first, key.second);
5044 if (result != null) {
5045 discoCache.put(key, result);
5046 }
5047 return result;
5048 }
5049 }
5050
5051 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
5052 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
5053 final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
5054 if (disco != null) {
5055 presence.setServiceDiscoveryResult(disco);
5056 final Contact contact = account.getRoster().getContact(jid);
5057 if (contact.refreshRtpCapability()) {
5058 syncRoster(account);
5059 }
5060 } else {
5061 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5062 request.setTo(jid);
5063 final String node = presence.getNode();
5064 final String ver = presence.getVer();
5065 final Element query = request.query(Namespace.DISCO_INFO);
5066 if (node != null && ver != null) {
5067 query.setAttribute("node", node + "#" + ver);
5068 }
5069 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
5070 sendIqPacket(account, request, (a, response) -> {
5071 if (response.getType() == IqPacket.TYPE.RESULT) {
5072 final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
5073 if (presence.getVer().equals(discoveryResult.getVer())) {
5074 databaseBackend.insertDiscoveryResult(discoveryResult);
5075 injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
5076 } else {
5077 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
5078 }
5079 } else {
5080 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
5081 }
5082 });
5083 }
5084 }
5085
5086 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
5087 boolean rosterNeedsSync = false;
5088 for (final Contact contact : roster.getContacts()) {
5089 boolean serviceDiscoverySet = false;
5090 for (final Presence presence : contact.getPresences().getPresences()) {
5091 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
5092 presence.setServiceDiscoveryResult(disco);
5093 serviceDiscoverySet = true;
5094 }
5095 }
5096 if (serviceDiscoverySet) {
5097 rosterNeedsSync |= contact.refreshRtpCapability();
5098 }
5099 }
5100 if (rosterNeedsSync) {
5101 syncRoster(roster.getAccount());
5102 }
5103 }
5104
5105 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
5106 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5107 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5108 request.addChild("prefs", version.namespace);
5109 sendIqPacket(account, request, (account1, packet) -> {
5110 Element prefs = packet.findChild("prefs", version.namespace);
5111 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
5112 callback.onPreferencesFetched(prefs);
5113 } else {
5114 callback.onPreferencesFetchFailed();
5115 }
5116 });
5117 }
5118
5119 public PushManagementService getPushManagementService() {
5120 return mPushManagementService;
5121 }
5122
5123 public void changeStatus(Account account, PresenceTemplate template, String signature) {
5124 if (!template.getStatusMessage().isEmpty()) {
5125 databaseBackend.insertPresenceTemplate(template);
5126 }
5127 account.setPgpSignature(signature);
5128 account.setPresenceStatus(template.getStatus());
5129 account.setPresenceStatusMessage(template.getStatusMessage());
5130 databaseBackend.updateAccount(account);
5131 sendPresence(account);
5132 }
5133
5134 public List<PresenceTemplate> getPresenceTemplates(Account account) {
5135 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5136 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5137 if (!templates.contains(template)) {
5138 templates.add(0, template);
5139 }
5140 }
5141 return templates;
5142 }
5143
5144 public void saveConversationAsBookmark(Conversation conversation, String name) {
5145 final Account account = conversation.getAccount();
5146 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5147 final String nick = conversation.getJid().getResource();
5148 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5149 bookmark.setNick(nick);
5150 }
5151 if (!TextUtils.isEmpty(name)) {
5152 bookmark.setBookmarkName(name);
5153 }
5154 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
5155 createBookmark(account, bookmark);
5156 bookmark.setConversation(conversation);
5157 }
5158
5159 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5160 boolean performedVerification = false;
5161 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5162 for (XmppUri.Fingerprint fp : fingerprints) {
5163 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5164 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5165 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5166 if (fingerprintStatus != null) {
5167 if (!fingerprintStatus.isVerified()) {
5168 performedVerification = true;
5169 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5170 }
5171 } else {
5172 axolotlService.preVerifyFingerprint(contact, fingerprint);
5173 }
5174 }
5175 }
5176 return performedVerification;
5177 }
5178
5179 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5180 final AxolotlService axolotlService = account.getAxolotlService();
5181 boolean verifiedSomething = false;
5182 for (XmppUri.Fingerprint fp : fingerprints) {
5183 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5184 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5185 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5186 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5187 if (fingerprintStatus != null) {
5188 if (!fingerprintStatus.isVerified()) {
5189 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5190 verifiedSomething = true;
5191 }
5192 } else {
5193 axolotlService.preVerifyFingerprint(account, fingerprint);
5194 verifiedSomething = true;
5195 }
5196 }
5197 }
5198 return verifiedSomething;
5199 }
5200
5201 public boolean blindTrustBeforeVerification() {
5202 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
5203 }
5204
5205 public ShortcutService getShortcutService() {
5206 return mShortcutService;
5207 }
5208
5209 public void pushMamPreferences(Account account, Element prefs) {
5210 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
5211 set.addChild(prefs);
5212 sendIqPacket(account, set, null);
5213 }
5214
5215 public void evictPreview(String uuid) {
5216 if (mBitmapCache.remove(uuid) != null) {
5217 Log.d(Config.LOGTAG, "deleted cached preview");
5218 }
5219 }
5220
5221 public interface OnMamPreferencesFetched {
5222 void onPreferencesFetched(Element prefs);
5223
5224 void onPreferencesFetchFailed();
5225 }
5226
5227 public interface OnAccountCreated {
5228 void onAccountCreated(Account account);
5229
5230 void informUser(int r);
5231 }
5232
5233 public interface OnMoreMessagesLoaded {
5234 void onMoreMessagesLoaded(int count, Conversation conversation);
5235
5236 void informUser(int r);
5237 }
5238
5239 public interface OnAccountPasswordChanged {
5240 void onPasswordChangeSucceeded();
5241
5242 void onPasswordChangeFailed();
5243 }
5244
5245 public interface OnRoomDestroy {
5246 void onRoomDestroySucceeded();
5247
5248 void onRoomDestroyFailed();
5249 }
5250
5251 public interface OnAffiliationChanged {
5252 void onAffiliationChangedSuccessful(Jid jid);
5253
5254 void onAffiliationChangeFailed(Jid jid, int resId);
5255 }
5256
5257 public interface OnConversationUpdate {
5258 void onConversationUpdate();
5259 }
5260
5261 public interface OnJingleRtpConnectionUpdate {
5262 void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5263
5264 void onAudioDeviceChanged(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices);
5265 }
5266
5267 public interface OnAccountUpdate {
5268 void onAccountUpdate();
5269 }
5270
5271 public interface OnCaptchaRequested {
5272 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5273 }
5274
5275 public interface OnRosterUpdate {
5276 void onRosterUpdate();
5277 }
5278
5279 public interface OnMucRosterUpdate {
5280 void onMucRosterUpdate();
5281 }
5282
5283 public interface OnConferenceConfigurationFetched {
5284 void onConferenceConfigurationFetched(Conversation conversation);
5285
5286 void onFetchFailed(Conversation conversation, String errorCondition);
5287 }
5288
5289 public interface OnConferenceJoined {
5290 void onConferenceJoined(Conversation conversation);
5291 }
5292
5293 public interface OnConfigurationPushed {
5294 void onPushSucceeded();
5295
5296 void onPushFailed();
5297 }
5298
5299 public interface OnShowErrorToast {
5300 void onShowErrorToast(int resId);
5301 }
5302
5303 public class XmppConnectionBinder extends Binder {
5304 public XmppConnectionService getService() {
5305 return XmppConnectionService.this;
5306 }
5307 }
5308
5309 private class InternalEventReceiver extends BroadcastReceiver {
5310
5311 @Override
5312 public void onReceive(final Context context, final Intent intent) {
5313 onStartCommand(intent, 0, 0);
5314 }
5315 }
5316
5317 private class RestrictedEventReceiver extends BroadcastReceiver {
5318
5319 private final Collection<String> allowedActions;
5320
5321 private RestrictedEventReceiver(final Collection<String> allowedActions) {
5322 this.allowedActions = allowedActions;
5323 }
5324
5325 @Override
5326 public void onReceive(final Context context, final Intent intent) {
5327 final String action = intent == null ? null : intent.getAction();
5328 if (allowedActions.contains(action)) {
5329 onStartCommand(intent,0,0);
5330 } else {
5331 Log.e(Config.LOGTAG,"restricting broadcast of event "+action);
5332 }
5333 }
5334 }
5335
5336 public static class OngoingCall {
5337 public final AbstractJingleConnection.Id id;
5338 public final Set<Media> media;
5339 public final boolean reconnecting;
5340
5341 public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5342 this.id = id;
5343 this.media = media;
5344 this.reconnecting = reconnecting;
5345 }
5346
5347 @Override
5348 public boolean equals(Object o) {
5349 if (this == o) return true;
5350 if (o == null || getClass() != o.getClass()) return false;
5351 OngoingCall that = (OngoingCall) o;
5352 return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
5353 }
5354
5355 @Override
5356 public int hashCode() {
5357 return Objects.hashCode(id, media, reconnecting);
5358 }
5359 }
5360
5361 public static void toggleForegroundService(final XmppConnectionService service) {
5362 if (service == null) {
5363 return;
5364 }
5365 service.toggleForegroundService();
5366 }
5367
5368 public static void toggleForegroundService(final ConversationsActivity activity) {
5369 if (activity == null) {
5370 return;
5371 }
5372 toggleForegroundService(activity.xmppConnectionService);
5373 }
5374}