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