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