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