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