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