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