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