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