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