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