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 final boolean showOngoing = ongoing != null && !diallerIntegrationActive.get();
1368 if (force || mForceDuringOnCreate.get() || mForceForegroundService.get() || showOngoing || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1369 final Notification notification;
1370 final int id;
1371 if (showOngoing) {
1372 notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1373 id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1374 startForeground(id, notification);
1375 mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1376 } else {
1377 notification = this.mNotificationService.createForegroundNotification();
1378 id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1379 startForeground(id, notification);
1380 }
1381
1382 if (!mForceForegroundService.get()) {
1383 mNotificationService.notify(id, notification);
1384 }
1385 status = true;
1386 } else {
1387 stopForeground(true);
1388 status = false;
1389 }
1390 if (!mForceForegroundService.get()) {
1391 mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1392 }
1393 if (!showOngoing) {
1394 mNotificationService.cancel(NotificationService.ONGOING_CALL_NOTIFICATION_ID);
1395 }
1396 Log.d(Config.LOGTAG, "ForegroundService: " + (status ? "on" : "off"));
1397 }
1398
1399 public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1400 return !mForceForegroundService.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1401 }
1402
1403 @Override
1404 public void onTaskRemoved(final Intent rootIntent) {
1405 super.onTaskRemoved(rootIntent);
1406 if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get() || ongoingCall.get() != null) {
1407 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1408 } else {
1409 this.logoutAndSave(false);
1410 }
1411 }
1412
1413 private void logoutAndSave(boolean stop) {
1414 int activeAccounts = 0;
1415 for (final Account account : accounts) {
1416 if (account.getStatus() != Account.State.DISABLED) {
1417 databaseBackend.writeRoster(account.getRoster());
1418 activeAccounts++;
1419 }
1420 if (account.getXmppConnection() != null) {
1421 new Thread(() -> disconnect(account, false)).start();
1422 }
1423 }
1424 if (stop || activeAccounts == 0) {
1425 Log.d(Config.LOGTAG, "good bye");
1426 stopSelf();
1427 }
1428 }
1429
1430 private void schedulePostConnectivityChange() {
1431 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1432 if (alarmManager == null) {
1433 return;
1434 }
1435 final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1436 final Intent intent = new Intent(this, EventReceiver.class);
1437 intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1438 try {
1439 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, s()
1440 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1441 : PendingIntent.FLAG_UPDATE_CURRENT);
1442 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1443 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1444 } else {
1445 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1446 }
1447 } catch (RuntimeException e) {
1448 Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1449 }
1450 }
1451
1452 public void scheduleWakeUpCall(int seconds, int requestCode) {
1453 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000L;
1454 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1455 if (alarmManager == null) {
1456 return;
1457 }
1458 final Intent intent = new Intent(this, EventReceiver.class);
1459 intent.setAction("ping");
1460 try {
1461 final PendingIntent pendingIntent;
1462 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1463 pendingIntent =
1464 PendingIntent.getBroadcast(
1465 this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1466 } else {
1467 pendingIntent =
1468 PendingIntent.getBroadcast(
1469 this, requestCode, intent, 0);
1470 }
1471 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1472 } catch (RuntimeException e) {
1473 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1474 }
1475 }
1476
1477 @TargetApi(Build.VERSION_CODES.M)
1478 private void scheduleNextIdlePing() {
1479 final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1480 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1481 if (alarmManager == null) {
1482 return;
1483 }
1484 final Intent intent = new Intent(this, EventReceiver.class);
1485 intent.setAction(ACTION_IDLE_PING);
1486 try {
1487 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, s()
1488 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1489 : PendingIntent.FLAG_UPDATE_CURRENT);
1490 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1491 } catch (RuntimeException e) {
1492 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1493 }
1494 }
1495
1496 public XmppConnection createConnection(final Account account) {
1497 final XmppConnection connection = new XmppConnection(account, this);
1498 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1499 connection.setOnStatusChangedListener(this.statusListener);
1500 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1501 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1502 connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1503 connection.setOnBindListener(this.mOnBindListener);
1504 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1505 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1506 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1507 AxolotlService axolotlService = account.getAxolotlService();
1508 if (axolotlService != null) {
1509 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1510 }
1511 return connection;
1512 }
1513
1514 public void sendChatState(Conversation conversation) {
1515 if (sendChatStates()) {
1516 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1517 sendMessagePacket(conversation.getAccount(), packet);
1518 }
1519 }
1520
1521 private void sendFileMessage(final Message message, final boolean delay) {
1522 Log.d(Config.LOGTAG, "send file message");
1523 final Account account = message.getConversation().getAccount();
1524 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1525 || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1526 mHttpConnectionManager.createNewUploadConnection(message, delay);
1527 } else {
1528 mJingleConnectionManager.startJingleFileTransfer(message);
1529 }
1530 }
1531
1532 public void sendMessage(final Message message) {
1533 sendMessage(message, false, false);
1534 }
1535
1536 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1537 final Account account = message.getConversation().getAccount();
1538 if (account.setShowErrorNotification(true)) {
1539 databaseBackend.updateAccount(account);
1540 mNotificationService.updateErrorNotification();
1541 }
1542 final Conversation conversation = (Conversation) message.getConversation();
1543 account.deactivateGracePeriod();
1544
1545
1546 if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1547 final Contact contact = conversation.getContact();
1548 if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1549 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1550 createContact(contact, true);
1551 }
1552 }
1553
1554 MessagePacket packet = null;
1555 final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1556 || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1557 && !message.edited();
1558 boolean saveInDb = addToConversation;
1559 message.setStatus(Message.STATUS_WAITING);
1560
1561 if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1562 if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1563 databaseBackend.updateConversation(conversation);
1564 }
1565 }
1566
1567 final boolean inProgressJoin = isJoinInProgress(conversation);
1568
1569
1570 if (account.isOnlineAndConnected() && !inProgressJoin) {
1571 switch (message.getEncryption()) {
1572 case Message.ENCRYPTION_NONE:
1573 if (message.needsUploading()) {
1574 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1575 || conversation.getMode() == Conversation.MODE_MULTI
1576 || message.fixCounterpart()) {
1577 this.sendFileMessage(message, delay);
1578 } else {
1579 break;
1580 }
1581 } else {
1582 packet = mMessageGenerator.generateChat(message);
1583 }
1584 break;
1585 case Message.ENCRYPTION_PGP:
1586 case Message.ENCRYPTION_DECRYPTED:
1587 if (message.needsUploading()) {
1588 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1589 || conversation.getMode() == Conversation.MODE_MULTI
1590 || message.fixCounterpart()) {
1591 this.sendFileMessage(message, delay);
1592 } else {
1593 break;
1594 }
1595 } else {
1596 packet = mMessageGenerator.generatePgpChat(message);
1597 }
1598 break;
1599 case Message.ENCRYPTION_AXOLOTL:
1600 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1601 if (message.needsUploading()) {
1602 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1603 || conversation.getMode() == Conversation.MODE_MULTI
1604 || message.fixCounterpart()) {
1605 this.sendFileMessage(message, delay);
1606 } else {
1607 break;
1608 }
1609 } else {
1610 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1611 if (axolotlMessage == null) {
1612 account.getAxolotlService().preparePayloadMessage(message, delay);
1613 } else {
1614 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1615 }
1616 }
1617 break;
1618
1619 }
1620 if (packet != null) {
1621 if (account.getXmppConnection().getFeatures().sm()
1622 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1623 message.setStatus(Message.STATUS_UNSEND);
1624 } else {
1625 message.setStatus(Message.STATUS_SEND);
1626 }
1627 }
1628 } else {
1629 switch (message.getEncryption()) {
1630 case Message.ENCRYPTION_DECRYPTED:
1631 if (!message.needsUploading()) {
1632 String pgpBody = message.getEncryptedBody();
1633 String decryptedBody = message.getBody();
1634 message.setBody(pgpBody); //TODO might throw NPE
1635 message.setEncryption(Message.ENCRYPTION_PGP);
1636 if (message.edited()) {
1637 message.setBody(decryptedBody);
1638 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1639 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1640 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1641 }
1642 updateConversationUi();
1643 return;
1644 } else {
1645 databaseBackend.createMessage(message);
1646 saveInDb = false;
1647 message.setBody(decryptedBody);
1648 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1649 }
1650 }
1651 break;
1652 case Message.ENCRYPTION_AXOLOTL:
1653 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1654 break;
1655 }
1656 }
1657
1658
1659 boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1660 if (mucMessage) {
1661 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1662 }
1663
1664 if (resend) {
1665 if (packet != null && addToConversation) {
1666 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1667 markMessage(message, Message.STATUS_UNSEND);
1668 } else {
1669 markMessage(message, Message.STATUS_SEND);
1670 }
1671 }
1672 } else {
1673 if (addToConversation) {
1674 conversation.add(message);
1675 }
1676 if (saveInDb) {
1677 databaseBackend.createMessage(message);
1678 } else if (message.edited()) {
1679 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1680 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1681 }
1682 }
1683 updateConversationUi();
1684 }
1685 if (packet != null) {
1686 if (delay) {
1687 mMessageGenerator.addDelay(packet, message.getTimeSent());
1688 }
1689 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1690 if (this.sendChatStates()) {
1691 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1692 }
1693 }
1694 sendMessagePacket(account, packet);
1695 }
1696 }
1697
1698 private boolean isJoinInProgress(final Conversation conversation) {
1699 final Account account = conversation.getAccount();
1700 synchronized (account.inProgressConferenceJoins) {
1701 if (conversation.getMode() == Conversational.MODE_MULTI) {
1702 final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1703 final boolean pending = account.pendingConferenceJoins.contains(conversation);
1704 final boolean inProgressJoin = inProgress || pending;
1705 if (inProgressJoin) {
1706 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
1707 }
1708 return inProgressJoin;
1709 } else {
1710 return false;
1711 }
1712 }
1713 }
1714
1715 private void sendUnsentMessages(final Conversation conversation) {
1716 conversation.findWaitingMessages(message -> resendMessage(message, true));
1717 }
1718
1719 public void resendMessage(final Message message, final boolean delay) {
1720 sendMessage(message, true, delay);
1721 }
1722
1723 public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
1724 final XmppConnection connection = account.getXmppConnection();
1725 final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
1726 if (jid == null) {
1727 callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
1728 return;
1729 }
1730 final IqPacket request = new IqPacket(IqPacket.TYPE.SET);
1731 request.setTo(jid);
1732 final Element command = request.addChild("command", Namespace.COMMANDS);
1733 command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
1734 command.setAttribute("action", "execute");
1735 sendIqPacket(account, request, (a, response) -> {
1736 if (response.getType() == IqPacket.TYPE.RESULT) {
1737 final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
1738 final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
1739 if (x != null) {
1740 final Data data = Data.parse(x);
1741 final String uri = data.getValue("uri");
1742 final String landingUrl = data.getValue("landing-url");
1743 if (uri != null) {
1744 final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
1745 callback.inviteRequested(invite);
1746 return;
1747 }
1748 }
1749 callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
1750 Log.d(Config.LOGTAG, response.toString());
1751 } else if (response.getType() == IqPacket.TYPE.ERROR) {
1752 callback.inviteRequestFailed(IqParser.errorMessage(response));
1753 } else {
1754 callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
1755 }
1756 });
1757
1758 }
1759
1760 public void fetchRosterFromServer(final Account account) {
1761 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1762 if (!"".equals(account.getRosterVersion())) {
1763 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1764 + ": fetching roster version " + account.getRosterVersion());
1765 } else {
1766 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1767 }
1768 iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1769 sendIqPacket(account, iqPacket, mIqParser);
1770 }
1771
1772 public void fetchBookmarks(final Account account) {
1773 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1774 final Element query = iqPacket.query("jabber:iq:private");
1775 query.addChild("storage", Namespace.BOOKMARKS);
1776 final OnIqPacketReceived callback = (a, response) -> {
1777 if (response.getType() == IqPacket.TYPE.RESULT) {
1778 final Element query1 = response.query();
1779 final Element storage = query1.findChild("storage", "storage:bookmarks");
1780 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
1781 processBookmarksInitial(a, bookmarks, false);
1782 } else {
1783 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1784 }
1785 };
1786 sendIqPacket(account, iqPacket, callback);
1787 }
1788
1789 public void fetchBookmarks2(final Account account) {
1790 final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
1791 sendIqPacket(account, retrieve, new OnIqPacketReceived() {
1792 @Override
1793 public void onIqPacketReceived(final Account account, final IqPacket response) {
1794 if (response.getType() == IqPacket.TYPE.RESULT) {
1795 final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
1796 final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, account);
1797 processBookmarksInitial(account, bookmarks, true);
1798 }
1799 }
1800 });
1801 }
1802
1803 public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
1804 final Set<Jid> previousBookmarks = account.getBookmarkedJids();
1805 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1806 for (Bookmark bookmark : bookmarks.values()) {
1807 previousBookmarks.remove(bookmark.getJid().asBareJid());
1808 processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
1809 }
1810 if (pep && synchronizeWithBookmarks) {
1811 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
1812 for (Jid jid : previousBookmarks) {
1813 processDeletedBookmark(account, jid);
1814 }
1815 }
1816 account.setBookmarks(bookmarks);
1817 }
1818
1819 public void processDeletedBookmark(Account account, Jid jid) {
1820 final Conversation conversation = find(account, jid);
1821 if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
1822 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
1823 archiveConversation(conversation, false);
1824 }
1825 }
1826
1827 private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
1828 final Account account = bookmark.getAccount();
1829 Conversation conversation = find(bookmark);
1830 if (conversation != null) {
1831 if (conversation.getMode() != Conversation.MODE_MULTI) {
1832 return;
1833 }
1834 bookmark.setConversation(conversation);
1835 if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
1836 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
1837 archiveConversation(conversation, false);
1838 } else {
1839 final MucOptions mucOptions = conversation.getMucOptions();
1840 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
1841 final String current = mucOptions.getActualNick();
1842 final String proposed = mucOptions.getProposedNick();
1843 if (current != null && !current.equals(proposed)) {
1844 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
1845 joinMuc(conversation);
1846 }
1847 }
1848 }
1849 } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
1850 conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
1851 bookmark.setConversation(conversation);
1852 }
1853 }
1854
1855 public void processModifiedBookmark(Bookmark bookmark) {
1856 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1857 processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
1858 }
1859
1860 public void createBookmark(final Account account, final Bookmark bookmark) {
1861 account.putBookmark(bookmark);
1862 final XmppConnection connection = account.getXmppConnection();
1863 if (connection == null) {
1864 Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
1865 } else if (connection.getFeatures().bookmarks2()) {
1866 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
1867 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
1868 } else if (connection.getFeatures().bookmarksConversion()) {
1869 pushBookmarksPep(account);
1870 } else {
1871 pushBookmarksPrivateXml(account);
1872 }
1873 }
1874
1875 public void deleteBookmark(final Account account, final Bookmark bookmark) {
1876 if (bookmark.getJid().toString().equals("discuss@conference.soprani.ca")) {
1877 getPreferences().edit().putBoolean("cheogram_sopranica_bookmark_deleted", true).apply();
1878 }
1879 account.removeBookmark(bookmark);
1880 final XmppConnection connection = account.getXmppConnection();
1881 if (connection.getFeatures().bookmarks2()) {
1882 IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
1883 sendIqPacket(account, request, (a, response) -> {
1884 if (response.getType() == IqPacket.TYPE.ERROR) {
1885 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
1886 }
1887 });
1888 } else if (connection.getFeatures().bookmarksConversion()) {
1889 pushBookmarksPep(account);
1890 } else {
1891 pushBookmarksPrivateXml(account);
1892 }
1893 }
1894
1895 private void pushBookmarksPrivateXml(Account account) {
1896 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1897 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1898 Element query = iqPacket.query("jabber:iq:private");
1899 Element storage = query.addChild("storage", "storage:bookmarks");
1900 for (Bookmark bookmark : account.getBookmarks()) {
1901 storage.addChild(bookmark);
1902 }
1903 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1904 }
1905
1906 private void pushBookmarksPep(Account account) {
1907 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1908 Element storage = new Element("storage", "storage:bookmarks");
1909 for (Bookmark bookmark : account.getBookmarks()) {
1910 storage.addChild(bookmark);
1911 }
1912 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
1913
1914 }
1915
1916 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1917 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1918
1919 }
1920
1921 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1922 final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1923 sendIqPacket(account, packet, (a, response) -> {
1924 if (response.getType() == IqPacket.TYPE.RESULT) {
1925 return;
1926 }
1927 if (retry && PublishOptions.preconditionNotMet(response)) {
1928 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1929 @Override
1930 public void onPushSucceeded() {
1931 pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
1932 }
1933
1934 @Override
1935 public void onPushFailed() {
1936 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
1937 }
1938 });
1939 } else {
1940 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + retry + ") " + response);
1941 }
1942 });
1943 }
1944
1945 private void restoreFromDatabase() {
1946 synchronized (this.conversations) {
1947 final Map<String, Account> accountLookupTable = new Hashtable<>();
1948 for (Account account : this.accounts) {
1949 accountLookupTable.put(account.getUuid(), account);
1950 }
1951 Log.d(Config.LOGTAG, "restoring conversations...");
1952 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1953 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1954 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1955 Conversation conversation = iterator.next();
1956 Account account = accountLookupTable.get(conversation.getAccountUuid());
1957 if (account != null) {
1958 conversation.setAccount(account);
1959 } else {
1960 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1961 iterator.remove();
1962 }
1963 }
1964 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1965 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1966 Runnable runnable = () -> {
1967 if (DatabaseBackend.requiresMessageIndexRebuild()) {
1968 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
1969 }
1970 final long deletionDate = getAutomaticMessageDeletionDate();
1971 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1972 if (deletionDate > 0) {
1973 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1974 databaseBackend.expireOldMessages(deletionDate);
1975 }
1976 Log.d(Config.LOGTAG, "restoring roster...");
1977 for (Account account : accounts) {
1978 databaseBackend.readRoster(account.getRoster());
1979 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1980 }
1981 getBitmapCache().evictAll();
1982 loadPhoneContacts();
1983 Log.d(Config.LOGTAG, "restoring messages...");
1984 final long startMessageRestore = SystemClock.elapsedRealtime();
1985 final Conversation quickLoad = QuickLoader.get(this.conversations);
1986 if (quickLoad != null) {
1987 restoreMessages(quickLoad);
1988 updateConversationUi();
1989 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1990 Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
1991 }
1992 for (Conversation conversation : this.conversations) {
1993 if (quickLoad != conversation) {
1994 restoreMessages(conversation);
1995 }
1996 }
1997 mNotificationService.finishBacklog(false);
1998 restoredFromDatabaseLatch.countDown();
1999 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2000 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2001 updateConversationUi();
2002 };
2003 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2004 }
2005 }
2006
2007 private void restoreMessages(Conversation conversation) {
2008 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2009 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2010 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2011 }
2012
2013 public void loadPhoneContacts() {
2014 mContactMergerExecutor.execute(() -> {
2015 Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2016 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2017 for (Account account : accounts) {
2018 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2019 for (JabberIdContact jidContact : contacts.values()) {
2020 final Contact contact = account.getRoster().getContact(jidContact.getJid());
2021 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2022 if (needsCacheClean) {
2023 getAvatarService().clear(contact);
2024 }
2025 withSystemAccounts.remove(contact);
2026 }
2027 for (Contact contact : withSystemAccounts) {
2028 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2029 if (needsCacheClean) {
2030 getAvatarService().clear(contact);
2031 }
2032 }
2033 }
2034 Log.d(Config.LOGTAG, "finished merging phone contacts");
2035 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2036 updateRosterUi();
2037 mQuickConversationsService.considerSync();
2038 });
2039 }
2040
2041
2042 public void syncRoster(final Account account) {
2043 unregisterPhoneAccounts(account);
2044 mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
2045 }
2046
2047 public List<Conversation> getConversations() {
2048 return this.conversations;
2049 }
2050
2051 private void markFileDeleted(final File file) {
2052 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2053 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2054 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2055 return;
2056 }
2057 }
2058 final boolean isInternalFile = fileBackend.isInternalFile(file);
2059 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2060 Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2061 markUuidsAsDeletedFiles(uuids);
2062 }
2063
2064 private void markUuidsAsDeletedFiles(List<String> uuids) {
2065 boolean deleted = false;
2066 for (Conversation conversation : getConversations()) {
2067 deleted |= conversation.markAsDeleted(uuids);
2068 }
2069 for (final String uuid : uuids) {
2070 evictPreview(uuid);
2071 }
2072 if (deleted) {
2073 updateConversationUi();
2074 }
2075 }
2076
2077 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2078 boolean changed = false;
2079 for (Conversation conversation : getConversations()) {
2080 changed |= conversation.markAsChanged(infos);
2081 }
2082 if (changed) {
2083 updateConversationUi();
2084 }
2085 }
2086
2087 public void populateWithOrderedConversations(final List<Conversation> list) {
2088 populateWithOrderedConversations(list, true, true);
2089 }
2090
2091 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2092 populateWithOrderedConversations(list, includeNoFileUpload, true);
2093 }
2094
2095 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2096 final List<String> orderedUuids;
2097 if (sort) {
2098 orderedUuids = null;
2099 } else {
2100 orderedUuids = new ArrayList<>();
2101 for (Conversation conversation : list) {
2102 orderedUuids.add(conversation.getUuid());
2103 }
2104 }
2105 list.clear();
2106 if (includeNoFileUpload) {
2107 list.addAll(getConversations());
2108 } else {
2109 for (Conversation conversation : getConversations()) {
2110 if (conversation.getMode() == Conversation.MODE_SINGLE
2111 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2112 list.add(conversation);
2113 }
2114 }
2115 }
2116 try {
2117 if (orderedUuids != null) {
2118 Collections.sort(list, (a, b) -> {
2119 final int indexA = orderedUuids.indexOf(a.getUuid());
2120 final int indexB = orderedUuids.indexOf(b.getUuid());
2121 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2122 return a.compareTo(b);
2123 }
2124 return indexA - indexB;
2125 });
2126 } else {
2127 Collections.sort(list);
2128 }
2129 } catch (IllegalArgumentException e) {
2130 //ignore
2131 }
2132 }
2133
2134 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2135 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2136 return;
2137 } else if (timestamp == 0) {
2138 return;
2139 }
2140 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2141 final Runnable runnable = () -> {
2142 final Account account = conversation.getAccount();
2143 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2144 if (messages.size() > 0) {
2145 conversation.addAll(0, messages);
2146 callback.onMoreMessagesLoaded(messages.size(), conversation);
2147 } else if (conversation.hasMessagesLeftOnServer()
2148 && account.isOnlineAndConnected()
2149 && conversation.getLastClearHistory().getTimestamp() == 0) {
2150 final boolean mamAvailable;
2151 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2152 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2153 } else {
2154 mamAvailable = conversation.getMucOptions().mamSupport();
2155 }
2156 if (mamAvailable) {
2157 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2158 if (query != null) {
2159 query.setCallback(callback);
2160 callback.informUser(R.string.fetching_history_from_server);
2161 } else {
2162 callback.informUser(R.string.not_fetching_history_retention_period);
2163 }
2164
2165 }
2166 }
2167 };
2168 mDatabaseReaderExecutor.execute(runnable);
2169 }
2170
2171 public List<Account> getAccounts() {
2172 return this.accounts;
2173 }
2174
2175
2176 /**
2177 * 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)
2178 */
2179 public List<Conversation> findAllConferencesWith(Contact contact) {
2180 final ArrayList<Conversation> results = new ArrayList<>();
2181 for (final Conversation c : conversations) {
2182 if (c.getMode() != Conversation.MODE_MULTI) {
2183 continue;
2184 }
2185 final MucOptions mucOptions = c.getMucOptions();
2186 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2187 results.add(c);
2188 }
2189 }
2190 return results;
2191 }
2192
2193 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2194 for (final Conversation conversation : haystack) {
2195 if (conversation.getContact() == contact) {
2196 return conversation;
2197 }
2198 }
2199 return null;
2200 }
2201
2202 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2203 if (jid == null) {
2204 return null;
2205 }
2206 for (final Conversation conversation : haystack) {
2207 if ((account == null || conversation.getAccount() == account)
2208 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2209 return conversation;
2210 }
2211 }
2212 return null;
2213 }
2214
2215 public boolean isConversationsListEmpty(final Conversation ignore) {
2216 synchronized (this.conversations) {
2217 final int size = this.conversations.size();
2218 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2219 }
2220 }
2221
2222 public boolean isConversationStillOpen(final Conversation conversation) {
2223 synchronized (this.conversations) {
2224 for (Conversation current : this.conversations) {
2225 if (current == conversation) {
2226 return true;
2227 }
2228 }
2229 }
2230 return false;
2231 }
2232
2233 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2234 return this.findOrCreateConversation(account, jid, muc, false, async);
2235 }
2236
2237 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2238 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2239 }
2240
2241 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2242 synchronized (this.conversations) {
2243 Conversation conversation = find(account, jid);
2244 if (conversation != null) {
2245 return conversation;
2246 }
2247 conversation = databaseBackend.findConversation(account, jid);
2248 final boolean loadMessagesFromDb;
2249 if (conversation != null) {
2250 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2251 conversation.setAccount(account);
2252 if (muc) {
2253 conversation.setMode(Conversation.MODE_MULTI);
2254 conversation.setContactJid(jid);
2255 } else {
2256 conversation.setMode(Conversation.MODE_SINGLE);
2257 conversation.setContactJid(jid.asBareJid());
2258 }
2259 databaseBackend.updateConversation(conversation);
2260 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2261 } else {
2262 String conversationName;
2263 Contact contact = account.getRoster().getContact(jid);
2264 if (contact != null) {
2265 conversationName = contact.getDisplayName();
2266 } else {
2267 conversationName = jid.getLocal();
2268 }
2269 if (muc) {
2270 conversation = new Conversation(conversationName, account, jid,
2271 Conversation.MODE_MULTI);
2272 } else {
2273 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2274 Conversation.MODE_SINGLE);
2275 }
2276 this.databaseBackend.createConversation(conversation);
2277 loadMessagesFromDb = false;
2278 }
2279 final Conversation c = conversation;
2280 final Runnable runnable = () -> {
2281 if (loadMessagesFromDb) {
2282 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2283 updateConversationUi();
2284 c.messagesLoaded.set(true);
2285 }
2286 if (account.getXmppConnection() != null
2287 && !c.getContact().isBlocked()
2288 && account.getXmppConnection().getFeatures().mam()
2289 && !muc) {
2290 if (query == null) {
2291 mMessageArchiveService.query(c);
2292 } else {
2293 if (query.getConversation() == null) {
2294 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2295 }
2296 }
2297 }
2298 if (joinAfterCreate) {
2299 joinMuc(c);
2300 }
2301 };
2302 if (async) {
2303 mDatabaseReaderExecutor.execute(runnable);
2304 } else {
2305 runnable.run();
2306 }
2307 this.conversations.add(conversation);
2308 updateConversationUi();
2309 return conversation;
2310 }
2311 }
2312
2313 public void archiveConversation(Conversation conversation) {
2314 archiveConversation(conversation, true);
2315 }
2316
2317 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2318 getNotificationService().clear(conversation);
2319 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2320 conversation.setNextMessage(null);
2321 synchronized (this.conversations) {
2322 getMessageArchiveService().kill(conversation);
2323 if (conversation.getMode() == Conversation.MODE_MULTI) {
2324 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2325 final Bookmark bookmark = conversation.getBookmark();
2326 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2327 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2328 Account account = bookmark.getAccount();
2329 bookmark.setConversation(null);
2330 deleteBookmark(account, bookmark);
2331 } else if (bookmark.autojoin()) {
2332 bookmark.setAutojoin(false);
2333 createBookmark(bookmark.getAccount(), bookmark);
2334 }
2335 }
2336 }
2337 leaveMuc(conversation);
2338 } else {
2339 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2340 stopPresenceUpdatesTo(conversation.getContact());
2341 }
2342 }
2343 updateConversation(conversation);
2344 this.conversations.remove(conversation);
2345 updateConversationUi();
2346 }
2347 }
2348
2349 public void stopPresenceUpdatesTo(Contact contact) {
2350 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2351 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2352 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2353 }
2354
2355 public void createAccount(final Account account) {
2356 account.initAccountServices(this);
2357 databaseBackend.createAccount(account);
2358 this.accounts.add(account);
2359 this.reconnectAccountInBackground(account);
2360 updateAccountUi();
2361 syncEnabledAccountSetting();
2362 toggleForegroundService();
2363 }
2364
2365 private void syncEnabledAccountSetting() {
2366 final boolean hasEnabledAccounts = hasEnabledAccounts();
2367 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2368 toggleSetProfilePictureActivity(hasEnabledAccounts);
2369 }
2370
2371 private void toggleSetProfilePictureActivity(final boolean enabled) {
2372 try {
2373 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2374 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2375 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2376 } catch (IllegalStateException e) {
2377 Log.d(Config.LOGTAG, "unable to toggle profile picture actvitiy");
2378 }
2379 }
2380
2381 private void provisionAccount(final String address, final String password) {
2382 final Jid jid = Jid.ofEscaped(address);
2383 final Account account = new Account(jid, password);
2384 account.setOption(Account.OPTION_DISABLED, true);
2385 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2386 createAccount(account);
2387 }
2388
2389 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2390 new Thread(() -> {
2391 try {
2392 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2393 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2394 if (cert == null) {
2395 callback.informUser(R.string.unable_to_parse_certificate);
2396 return;
2397 }
2398 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2399 if (info == null) {
2400 callback.informUser(R.string.certificate_does_not_contain_jid);
2401 return;
2402 }
2403 if (findAccountByJid(info.first) == null) {
2404 final Account account = new Account(info.first, "");
2405 account.setPrivateKeyAlias(alias);
2406 account.setOption(Account.OPTION_DISABLED, true);
2407 account.setOption(Account.OPTION_FIXED_USERNAME, true);
2408 account.setDisplayName(info.second);
2409 createAccount(account);
2410 callback.onAccountCreated(account);
2411 if (Config.X509_VERIFICATION) {
2412 try {
2413 getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2414 } catch (CertificateException e) {
2415 callback.informUser(R.string.certificate_chain_is_not_trusted);
2416 }
2417 }
2418 } else {
2419 callback.informUser(R.string.account_already_exists);
2420 }
2421 } catch (Exception e) {
2422 callback.informUser(R.string.unable_to_parse_certificate);
2423 }
2424 }).start();
2425
2426 }
2427
2428 public void updateKeyInAccount(final Account account, final String alias) {
2429 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2430 try {
2431 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2432 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2433 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2434 if (info == null) {
2435 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2436 return;
2437 }
2438 if (account.getJid().asBareJid().equals(info.first)) {
2439 account.setPrivateKeyAlias(alias);
2440 account.setDisplayName(info.second);
2441 databaseBackend.updateAccount(account);
2442 if (Config.X509_VERIFICATION) {
2443 try {
2444 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2445 } catch (CertificateException e) {
2446 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2447 }
2448 account.getAxolotlService().regenerateKeys(true);
2449 }
2450 } else {
2451 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2452 }
2453 } catch (Exception e) {
2454 e.printStackTrace();
2455 }
2456 }
2457
2458 public boolean updateAccount(final Account account) {
2459 if (databaseBackend.updateAccount(account)) {
2460 account.setShowErrorNotification(true);
2461 this.statusListener.onStatusChanged(account);
2462 databaseBackend.updateAccount(account);
2463 reconnectAccountInBackground(account);
2464 updateAccountUi();
2465 getNotificationService().updateErrorNotification();
2466 toggleForegroundService();
2467 syncEnabledAccountSetting();
2468 mChannelDiscoveryService.cleanCache();
2469 return true;
2470 } else {
2471 return false;
2472 }
2473 }
2474
2475 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2476 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2477 sendIqPacket(account, iq, (a, packet) -> {
2478 if (packet.getType() == IqPacket.TYPE.RESULT) {
2479 a.setPassword(newPassword);
2480 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2481 databaseBackend.updateAccount(a);
2482 callback.onPasswordChangeSucceeded();
2483 } else {
2484 callback.onPasswordChangeFailed();
2485 }
2486 });
2487 }
2488
2489 public void deleteAccount(final Account account) {
2490 final boolean connected = account.getStatus() == Account.State.ONLINE;
2491 synchronized (this.conversations) {
2492 if (connected) {
2493 account.getAxolotlService().deleteOmemoIdentity();
2494 }
2495 for (final Conversation conversation : conversations) {
2496 if (conversation.getAccount() == account) {
2497 if (conversation.getMode() == Conversation.MODE_MULTI) {
2498 if (connected) {
2499 leaveMuc(conversation);
2500 }
2501 }
2502 conversations.remove(conversation);
2503 mNotificationService.clear(conversation);
2504 }
2505 }
2506 new Thread(() -> {
2507 for (final Contact contact : account.getRoster().getContacts()) {
2508 contact.unregisterAsPhoneAccount(this);
2509 }
2510 }).start();
2511 if (account.getXmppConnection() != null) {
2512 new Thread(() -> disconnect(account, !connected)).start();
2513 }
2514 final Runnable runnable = () -> {
2515 if (!databaseBackend.deleteAccount(account)) {
2516 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2517 }
2518 };
2519 mDatabaseWriterExecutor.execute(runnable);
2520 this.accounts.remove(account);
2521 this.mRosterSyncTaskManager.clear(account);
2522 updateAccountUi();
2523 mNotificationService.updateErrorNotification();
2524 syncEnabledAccountSetting();
2525 toggleForegroundService();
2526 }
2527 }
2528
2529 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2530 final boolean remainingListeners;
2531 synchronized (LISTENER_LOCK) {
2532 remainingListeners = checkListeners();
2533 if (!this.mOnConversationUpdates.add(listener)) {
2534 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2535 }
2536 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2537 }
2538 if (remainingListeners) {
2539 switchToForeground();
2540 }
2541 }
2542
2543 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2544 final boolean remainingListeners;
2545 synchronized (LISTENER_LOCK) {
2546 this.mOnConversationUpdates.remove(listener);
2547 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2548 remainingListeners = checkListeners();
2549 }
2550 if (remainingListeners) {
2551 switchToBackground();
2552 }
2553 }
2554
2555 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2556 final boolean remainingListeners;
2557 synchronized (LISTENER_LOCK) {
2558 remainingListeners = checkListeners();
2559 if (!this.mOnShowErrorToasts.add(listener)) {
2560 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2561 }
2562 }
2563 if (remainingListeners) {
2564 switchToForeground();
2565 }
2566 }
2567
2568 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2569 final boolean remainingListeners;
2570 synchronized (LISTENER_LOCK) {
2571 this.mOnShowErrorToasts.remove(onShowErrorToast);
2572 remainingListeners = checkListeners();
2573 }
2574 if (remainingListeners) {
2575 switchToBackground();
2576 }
2577 }
2578
2579 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2580 final boolean remainingListeners;
2581 synchronized (LISTENER_LOCK) {
2582 remainingListeners = checkListeners();
2583 if (!this.mOnAccountUpdates.add(listener)) {
2584 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2585 }
2586 }
2587 if (remainingListeners) {
2588 switchToForeground();
2589 }
2590 }
2591
2592 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2593 final boolean remainingListeners;
2594 synchronized (LISTENER_LOCK) {
2595 this.mOnAccountUpdates.remove(listener);
2596 remainingListeners = checkListeners();
2597 }
2598 if (remainingListeners) {
2599 switchToBackground();
2600 }
2601 }
2602
2603 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2604 final boolean remainingListeners;
2605 synchronized (LISTENER_LOCK) {
2606 remainingListeners = checkListeners();
2607 if (!this.mOnCaptchaRequested.add(listener)) {
2608 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2609 }
2610 }
2611 if (remainingListeners) {
2612 switchToForeground();
2613 }
2614 }
2615
2616 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2617 final boolean remainingListeners;
2618 synchronized (LISTENER_LOCK) {
2619 this.mOnCaptchaRequested.remove(listener);
2620 remainingListeners = checkListeners();
2621 }
2622 if (remainingListeners) {
2623 switchToBackground();
2624 }
2625 }
2626
2627 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2628 final boolean remainingListeners;
2629 synchronized (LISTENER_LOCK) {
2630 remainingListeners = checkListeners();
2631 if (!this.mOnRosterUpdates.add(listener)) {
2632 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2633 }
2634 }
2635 if (remainingListeners) {
2636 switchToForeground();
2637 }
2638 }
2639
2640 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2641 final boolean remainingListeners;
2642 synchronized (LISTENER_LOCK) {
2643 this.mOnRosterUpdates.remove(listener);
2644 remainingListeners = checkListeners();
2645 }
2646 if (remainingListeners) {
2647 switchToBackground();
2648 }
2649 }
2650
2651 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2652 final boolean remainingListeners;
2653 synchronized (LISTENER_LOCK) {
2654 remainingListeners = checkListeners();
2655 if (!this.mOnUpdateBlocklist.add(listener)) {
2656 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2657 }
2658 }
2659 if (remainingListeners) {
2660 switchToForeground();
2661 }
2662 }
2663
2664 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2665 final boolean remainingListeners;
2666 synchronized (LISTENER_LOCK) {
2667 this.mOnUpdateBlocklist.remove(listener);
2668 remainingListeners = checkListeners();
2669 }
2670 if (remainingListeners) {
2671 switchToBackground();
2672 }
2673 }
2674
2675 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2676 final boolean remainingListeners;
2677 synchronized (LISTENER_LOCK) {
2678 remainingListeners = checkListeners();
2679 if (!this.mOnKeyStatusUpdated.add(listener)) {
2680 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2681 }
2682 }
2683 if (remainingListeners) {
2684 switchToForeground();
2685 }
2686 }
2687
2688 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2689 final boolean remainingListeners;
2690 synchronized (LISTENER_LOCK) {
2691 this.mOnKeyStatusUpdated.remove(listener);
2692 remainingListeners = checkListeners();
2693 }
2694 if (remainingListeners) {
2695 switchToBackground();
2696 }
2697 }
2698
2699 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2700 final boolean remainingListeners;
2701 synchronized (LISTENER_LOCK) {
2702 remainingListeners = checkListeners();
2703 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
2704 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
2705 }
2706 }
2707 if (remainingListeners) {
2708 switchToForeground();
2709 }
2710 }
2711
2712 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2713 final boolean remainingListeners;
2714 synchronized (LISTENER_LOCK) {
2715 this.onJingleRtpConnectionUpdate.remove(listener);
2716 remainingListeners = checkListeners();
2717 }
2718 if (remainingListeners) {
2719 switchToBackground();
2720 }
2721 }
2722
2723 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2724 final boolean remainingListeners;
2725 synchronized (LISTENER_LOCK) {
2726 remainingListeners = checkListeners();
2727 if (!this.mOnMucRosterUpdate.add(listener)) {
2728 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2729 }
2730 }
2731 if (remainingListeners) {
2732 switchToForeground();
2733 }
2734 }
2735
2736 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2737 final boolean remainingListeners;
2738 synchronized (LISTENER_LOCK) {
2739 this.mOnMucRosterUpdate.remove(listener);
2740 remainingListeners = checkListeners();
2741 }
2742 if (remainingListeners) {
2743 switchToBackground();
2744 }
2745 }
2746
2747 public boolean checkListeners() {
2748 return (this.mOnAccountUpdates.size() == 0
2749 && this.mOnConversationUpdates.size() == 0
2750 && this.mOnRosterUpdates.size() == 0
2751 && this.mOnCaptchaRequested.size() == 0
2752 && this.mOnMucRosterUpdate.size() == 0
2753 && this.mOnUpdateBlocklist.size() == 0
2754 && this.mOnShowErrorToasts.size() == 0
2755 && this.onJingleRtpConnectionUpdate.size() == 0
2756 && this.mOnKeyStatusUpdated.size() == 0);
2757 }
2758
2759 private void switchToForeground() {
2760 final boolean broadcastLastActivity = broadcastLastActivity();
2761 for (Conversation conversation : getConversations()) {
2762 if (conversation.getMode() == Conversation.MODE_MULTI) {
2763 conversation.getMucOptions().resetChatState();
2764 } else {
2765 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
2766 }
2767 }
2768 for (Account account : getAccounts()) {
2769 if (account.getStatus() == Account.State.ONLINE) {
2770 account.deactivateGracePeriod();
2771 final XmppConnection connection = account.getXmppConnection();
2772 if (connection != null) {
2773 if (connection.getFeatures().csi()) {
2774 connection.sendActive();
2775 }
2776 if (broadcastLastActivity) {
2777 sendPresence(account, false); //send new presence but don't include idle because we are not
2778 }
2779 }
2780 }
2781 }
2782 Log.d(Config.LOGTAG, "app switched into foreground");
2783 }
2784
2785 private void switchToBackground() {
2786 final boolean broadcastLastActivity = broadcastLastActivity();
2787 if (broadcastLastActivity) {
2788 mLastActivity = System.currentTimeMillis();
2789 final SharedPreferences.Editor editor = getPreferences().edit();
2790 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2791 editor.apply();
2792 }
2793 for (Account account : getAccounts()) {
2794 if (account.getStatus() == Account.State.ONLINE) {
2795 XmppConnection connection = account.getXmppConnection();
2796 if (connection != null) {
2797 if (broadcastLastActivity) {
2798 sendPresence(account, true);
2799 }
2800 if (connection.getFeatures().csi()) {
2801 connection.sendInactive();
2802 }
2803 }
2804 }
2805 }
2806 this.mNotificationService.setIsInForeground(false);
2807 Log.d(Config.LOGTAG, "app switched into background");
2808 }
2809
2810 private void connectMultiModeConversations(Account account) {
2811 List<Conversation> conversations = getConversations();
2812 for (Conversation conversation : conversations) {
2813 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2814 joinMuc(conversation);
2815 }
2816 }
2817 }
2818
2819 public void mucSelfPingAndRejoin(final Conversation conversation) {
2820 final Account account = conversation.getAccount();
2821 synchronized (account.inProgressConferenceJoins) {
2822 if (account.inProgressConferenceJoins.contains(conversation)) {
2823 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2824 return;
2825 }
2826 }
2827 synchronized (account.inProgressConferencePings) {
2828 if (!account.inProgressConferencePings.add(conversation)) {
2829 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
2830 return;
2831 }
2832 }
2833 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2834 final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2835 ping.setTo(self);
2836 ping.addChild("ping", Namespace.PING);
2837 sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2838 if (response.getType() == IqPacket.TYPE.ERROR) {
2839 Element error = response.findChild("error");
2840 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2841 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
2842 } else {
2843 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
2844 joinMuc(conversation);
2845 }
2846 } else if (response.getType() == IqPacket.TYPE.RESULT) {
2847 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
2848 }
2849 synchronized (account.inProgressConferencePings) {
2850 account.inProgressConferencePings.remove(conversation);
2851 }
2852 });
2853 }
2854
2855 public void joinMuc(Conversation conversation) {
2856 joinMuc(conversation, null, false);
2857 }
2858
2859 public void joinMuc(Conversation conversation, boolean followedInvite) {
2860 joinMuc(conversation, null, followedInvite);
2861 }
2862
2863 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2864 joinMuc(conversation, onConferenceJoined, false);
2865 }
2866
2867 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2868 final Account account = conversation.getAccount();
2869 synchronized (account.pendingConferenceJoins) {
2870 account.pendingConferenceJoins.remove(conversation);
2871 }
2872 synchronized (account.pendingConferenceLeaves) {
2873 account.pendingConferenceLeaves.remove(conversation);
2874 }
2875 if (account.getStatus() == Account.State.ONLINE) {
2876 synchronized (account.inProgressConferenceJoins) {
2877 account.inProgressConferenceJoins.add(conversation);
2878 }
2879 if (Config.MUC_LEAVE_BEFORE_JOIN) {
2880 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2881 }
2882 conversation.resetMucOptions();
2883 if (onConferenceJoined != null) {
2884 conversation.getMucOptions().flagNoAutoPushConfiguration();
2885 }
2886 conversation.setHasMessagesLeftOnServer(false);
2887 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2888
2889 private void join(Conversation conversation) {
2890 Account account = conversation.getAccount();
2891 final MucOptions mucOptions = conversation.getMucOptions();
2892
2893 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2894 synchronized (account.inProgressConferenceJoins) {
2895 account.inProgressConferenceJoins.remove(conversation);
2896 }
2897 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2898 updateConversationUi();
2899 if (onConferenceJoined != null) {
2900 onConferenceJoined.onConferenceJoined(conversation);
2901 }
2902 return;
2903 }
2904
2905 final Jid joinJid = mucOptions.getSelf().getFullJid();
2906 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2907 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2908 packet.setTo(joinJid);
2909 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2910 if (conversation.getMucOptions().getPassword() != null) {
2911 x.addChild("password").setContent(mucOptions.getPassword());
2912 }
2913
2914 if (mucOptions.mamSupport()) {
2915 // Use MAM instead of the limited muc history to get history
2916 x.addChild("history").setAttribute("maxchars", "0");
2917 } else {
2918 // Fallback to muc history
2919 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2920 }
2921 sendPresencePacket(account, packet);
2922 if (onConferenceJoined != null) {
2923 onConferenceJoined.onConferenceJoined(conversation);
2924 }
2925 if (!joinJid.equals(conversation.getJid())) {
2926 conversation.setContactJid(joinJid);
2927 databaseBackend.updateConversation(conversation);
2928 }
2929
2930 if (mucOptions.mamSupport()) {
2931 getMessageArchiveService().catchupMUC(conversation);
2932 }
2933 if (mucOptions.isPrivateAndNonAnonymous()) {
2934 fetchConferenceMembers(conversation);
2935
2936 if (followedInvite) {
2937 final Bookmark bookmark = conversation.getBookmark();
2938 if (bookmark != null) {
2939 if (!bookmark.autojoin()) {
2940 bookmark.setAutojoin(true);
2941 createBookmark(account, bookmark);
2942 }
2943 } else {
2944 saveConversationAsBookmark(conversation, null);
2945 }
2946 }
2947 }
2948 synchronized (account.inProgressConferenceJoins) {
2949 account.inProgressConferenceJoins.remove(conversation);
2950 sendUnsentMessages(conversation);
2951 }
2952 }
2953
2954 @Override
2955 public void onConferenceConfigurationFetched(Conversation conversation) {
2956 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2957 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2958 return;
2959 }
2960 join(conversation);
2961 }
2962
2963 @Override
2964 public void onFetchFailed(final Conversation conversation, final String errorCondition) {
2965 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2966 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2967 return;
2968 }
2969 if ("remote-server-not-found".equals(errorCondition)) {
2970 synchronized (account.inProgressConferenceJoins) {
2971 account.inProgressConferenceJoins.remove(conversation);
2972 }
2973 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2974 updateConversationUi();
2975 } else {
2976 join(conversation);
2977 fetchConferenceConfiguration(conversation);
2978 }
2979 }
2980 });
2981 updateConversationUi();
2982 } else {
2983 synchronized (account.pendingConferenceJoins) {
2984 account.pendingConferenceJoins.add(conversation);
2985 }
2986 conversation.resetMucOptions();
2987 conversation.setHasMessagesLeftOnServer(false);
2988 updateConversationUi();
2989 }
2990 }
2991
2992 private void fetchConferenceMembers(final Conversation conversation) {
2993 final Account account = conversation.getAccount();
2994 final AxolotlService axolotlService = account.getAxolotlService();
2995 final String[] affiliations = {"member", "admin", "owner"};
2996 OnIqPacketReceived callback = new OnIqPacketReceived() {
2997
2998 private int i = 0;
2999 private boolean success = true;
3000
3001 @Override
3002 public void onIqPacketReceived(Account account, IqPacket packet) {
3003 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3004 Element query = packet.query("http://jabber.org/protocol/muc#admin");
3005 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
3006 for (Element child : query.getChildren()) {
3007 if ("item".equals(child.getName())) {
3008 MucOptions.User user = AbstractParser.parseItem(conversation, child);
3009 if (!user.realJidMatchesAccount()) {
3010 boolean isNew = conversation.getMucOptions().updateUser(user);
3011 Contact contact = user.getContact();
3012 if (omemoEnabled
3013 && isNew
3014 && user.getRealJid() != null
3015 && (contact == null || !contact.mutualPresenceSubscription())
3016 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3017 axolotlService.fetchDeviceIds(user.getRealJid());
3018 }
3019 }
3020 }
3021 }
3022 } else {
3023 success = false;
3024 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
3025 }
3026 ++i;
3027 if (i >= affiliations.length) {
3028 List<Jid> members = conversation.getMucOptions().getMembers(true);
3029 if (success) {
3030 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3031 boolean changed = false;
3032 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3033 Jid jid = iterator.next();
3034 if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3035 iterator.remove();
3036 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3037 changed = true;
3038 }
3039 }
3040 if (changed) {
3041 conversation.setAcceptedCryptoTargets(cryptoTargets);
3042 updateConversation(conversation);
3043 }
3044 }
3045 getAvatarService().clear(conversation);
3046 updateMucRosterUi();
3047 updateConversationUi();
3048 }
3049 }
3050 };
3051 for (String affiliation : affiliations) {
3052 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3053 }
3054 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3055 }
3056
3057 public void providePasswordForMuc(Conversation conversation, String password) {
3058 if (conversation.getMode() == Conversation.MODE_MULTI) {
3059 conversation.getMucOptions().setPassword(password);
3060 if (conversation.getBookmark() != null) {
3061 final Bookmark bookmark = conversation.getBookmark();
3062 if (synchronizeWithBookmarks()) {
3063 bookmark.setAutojoin(true);
3064 }
3065 createBookmark(conversation.getAccount(), bookmark);
3066 }
3067 updateConversation(conversation);
3068 joinMuc(conversation);
3069 }
3070 }
3071
3072 private boolean hasEnabledAccounts() {
3073 if (this.accounts == null) {
3074 return false;
3075 }
3076 for (Account account : this.accounts) {
3077 if (account.isEnabled()) {
3078 return true;
3079 }
3080 }
3081 return false;
3082 }
3083
3084
3085 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3086 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3087 }
3088
3089 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3090 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3091 }
3092
3093
3094 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3095 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3096 }
3097
3098 public void persistSelfNick(MucOptions.User self) {
3099 final Conversation conversation = self.getConversation();
3100 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3101 Jid full = self.getFullJid();
3102 if (!full.equals(conversation.getJid())) {
3103 Log.d(Config.LOGTAG, "nick changed. updating");
3104 conversation.setContactJid(full);
3105 databaseBackend.updateConversation(conversation);
3106 }
3107
3108 final Bookmark bookmark = conversation.getBookmark();
3109 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3110 if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
3111 final Account account = conversation.getAccount();
3112 final String defaultNick = MucOptions.defaultNick(account);
3113 if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3114 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
3115 return;
3116 }
3117 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
3118 bookmark.setNick(full.getResource());
3119 createBookmark(bookmark.getAccount(), bookmark);
3120 }
3121 }
3122
3123 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3124 final MucOptions options = conversation.getMucOptions();
3125 final Jid joinJid = options.createJoinJid(nick);
3126 if (joinJid == null) {
3127 return false;
3128 }
3129 if (options.online()) {
3130 Account account = conversation.getAccount();
3131 options.setOnRenameListener(new OnRenameListener() {
3132
3133 @Override
3134 public void onSuccess() {
3135 callback.success(conversation);
3136 }
3137
3138 @Override
3139 public void onFailure() {
3140 callback.error(R.string.nick_in_use, conversation);
3141 }
3142 });
3143
3144 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
3145 packet.setTo(joinJid);
3146 sendPresencePacket(account, packet);
3147 } else {
3148 conversation.setContactJid(joinJid);
3149 databaseBackend.updateConversation(conversation);
3150 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3151 Bookmark bookmark = conversation.getBookmark();
3152 if (bookmark != null) {
3153 bookmark.setNick(nick);
3154 createBookmark(bookmark.getAccount(), bookmark);
3155 }
3156 joinMuc(conversation);
3157 }
3158 }
3159 return true;
3160 }
3161
3162 public void leaveMuc(Conversation conversation) {
3163 leaveMuc(conversation, false);
3164 }
3165
3166 private void leaveMuc(Conversation conversation, boolean now) {
3167 final Account account = conversation.getAccount();
3168 synchronized (account.pendingConferenceJoins) {
3169 account.pendingConferenceJoins.remove(conversation);
3170 }
3171 synchronized (account.pendingConferenceLeaves) {
3172 account.pendingConferenceLeaves.remove(conversation);
3173 }
3174 if (account.getStatus() == Account.State.ONLINE || now) {
3175 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3176 conversation.getMucOptions().setOffline();
3177 Bookmark bookmark = conversation.getBookmark();
3178 if (bookmark != null) {
3179 bookmark.setConversation(null);
3180 }
3181 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3182 } else {
3183 synchronized (account.pendingConferenceLeaves) {
3184 account.pendingConferenceLeaves.add(conversation);
3185 }
3186 }
3187 }
3188
3189 public String findConferenceServer(final Account account) {
3190 String server;
3191 if (account.getXmppConnection() != null) {
3192 server = account.getXmppConnection().getMucServer();
3193 if (server != null) {
3194 return server;
3195 }
3196 }
3197 for (Account other : getAccounts()) {
3198 if (other != account && other.getXmppConnection() != null) {
3199 server = other.getXmppConnection().getMucServer();
3200 if (server != null) {
3201 return server;
3202 }
3203 }
3204 }
3205 return null;
3206 }
3207
3208
3209 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3210 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3211 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3212 if (!TextUtils.isEmpty(name)) {
3213 configuration.putString("muc#roomconfig_roomname", name);
3214 }
3215 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3216 @Override
3217 public void onPushSucceeded() {
3218 saveConversationAsBookmark(conversation, name);
3219 callback.success(conversation);
3220 }
3221
3222 @Override
3223 public void onPushFailed() {
3224 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3225 callback.error(R.string.unable_to_set_channel_configuration, conversation);
3226 } else {
3227 callback.error(R.string.joined_an_existing_channel, conversation);
3228 }
3229 }
3230 });
3231 });
3232 }
3233
3234 public boolean createAdhocConference(final Account account,
3235 final String name,
3236 final Iterable<Jid> jids,
3237 final UiCallback<Conversation> callback) {
3238 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3239 if (account.getStatus() == Account.State.ONLINE) {
3240 try {
3241 String server = findConferenceServer(account);
3242 if (server == null) {
3243 if (callback != null) {
3244 callback.error(R.string.no_conference_server_found, null);
3245 }
3246 return false;
3247 }
3248 final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
3249 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3250 joinMuc(conversation, new OnConferenceJoined() {
3251 @Override
3252 public void onConferenceJoined(final Conversation conversation) {
3253 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3254 if (!TextUtils.isEmpty(name)) {
3255 configuration.putString("muc#roomconfig_roomname", name);
3256 }
3257 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3258 @Override
3259 public void onPushSucceeded() {
3260 for (Jid invite : jids) {
3261 invite(conversation, invite);
3262 }
3263 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3264 Jid other = account.getJid().withResource(resource);
3265 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3266 directInvite(conversation, other);
3267 }
3268 saveConversationAsBookmark(conversation, name);
3269 if (callback != null) {
3270 callback.success(conversation);
3271 }
3272 }
3273
3274 @Override
3275 public void onPushFailed() {
3276 archiveConversation(conversation);
3277 if (callback != null) {
3278 callback.error(R.string.conference_creation_failed, conversation);
3279 }
3280 }
3281 });
3282 }
3283 });
3284 return true;
3285 } catch (IllegalArgumentException e) {
3286 if (callback != null) {
3287 callback.error(R.string.conference_creation_failed, null);
3288 }
3289 return false;
3290 }
3291 } else {
3292 if (callback != null) {
3293 callback.error(R.string.not_connected_try_again, null);
3294 }
3295 return false;
3296 }
3297 }
3298
3299 public void fetchConferenceConfiguration(final Conversation conversation) {
3300 fetchConferenceConfiguration(conversation, null);
3301 }
3302
3303 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3304 IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3305 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3306 @Override
3307 public void onIqPacketReceived(Account account, IqPacket packet) {
3308 if (packet.getType() == IqPacket.TYPE.RESULT) {
3309 final MucOptions mucOptions = conversation.getMucOptions();
3310 final Bookmark bookmark = conversation.getBookmark();
3311 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3312
3313 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3314 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3315 updateConversation(conversation);
3316 }
3317
3318 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3319 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3320 createBookmark(account, bookmark);
3321 }
3322 }
3323
3324
3325 if (callback != null) {
3326 callback.onConferenceConfigurationFetched(conversation);
3327 }
3328
3329
3330 updateConversationUi();
3331 } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3332 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3333 } else {
3334 if (callback != null) {
3335 callback.onFetchFailed(conversation, packet.getErrorCondition());
3336 }
3337 }
3338 }
3339 });
3340 }
3341
3342 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3343 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3344 }
3345
3346 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3347 Log.d(Config.LOGTAG, "pushing node configuration");
3348 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3349 @Override
3350 public void onIqPacketReceived(Account account, IqPacket packet) {
3351 if (packet.getType() == IqPacket.TYPE.RESULT) {
3352 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3353 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3354 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3355 if (x != null) {
3356 Data data = Data.parse(x);
3357 data.submit(options);
3358 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3359 @Override
3360 public void onIqPacketReceived(Account account, IqPacket packet) {
3361 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3362 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3363 callback.onPushSucceeded();
3364 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3365 callback.onPushFailed();
3366 }
3367 }
3368 });
3369 } else if (callback != null) {
3370 callback.onPushFailed();
3371 }
3372 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3373 callback.onPushFailed();
3374 }
3375 }
3376 });
3377 }
3378
3379 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3380 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3381 conversation.setAttribute("accept_non_anonymous", true);
3382 updateConversation(conversation);
3383 }
3384 if (options.containsKey("muc#roomconfig_moderatedroom")) {
3385 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3386 options.putString("members_by_default", moderated ? "0" : "1");
3387 }
3388 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3389 request.setTo(conversation.getJid().asBareJid());
3390 request.query("http://jabber.org/protocol/muc#owner");
3391 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3392 @Override
3393 public void onIqPacketReceived(Account account, IqPacket packet) {
3394 if (packet.getType() == IqPacket.TYPE.RESULT) {
3395 final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3396 data.submit(options);
3397 final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3398 set.setTo(conversation.getJid().asBareJid());
3399 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3400 sendIqPacket(account, set, new OnIqPacketReceived() {
3401 @Override
3402 public void onIqPacketReceived(Account account, IqPacket packet) {
3403 if (callback != null) {
3404 if (packet.getType() == IqPacket.TYPE.RESULT) {
3405 callback.onPushSucceeded();
3406 } else {
3407 callback.onPushFailed();
3408 }
3409 }
3410 }
3411 });
3412 } else {
3413 if (callback != null) {
3414 callback.onPushFailed();
3415 }
3416 }
3417 }
3418 });
3419 }
3420
3421 public void pushSubjectToConference(final Conversation conference, final String subject) {
3422 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3423 this.sendMessagePacket(conference.getAccount(), packet);
3424 }
3425
3426 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3427 final Jid jid = user.asBareJid();
3428 final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3429 sendIqPacket(conference.getAccount(), request, (account, response) -> {
3430 if (response.getType() == IqPacket.TYPE.RESULT) {
3431 conference.getMucOptions().changeAffiliation(jid, affiliation);
3432 getAvatarService().clear(conference);
3433 if (callback != null) {
3434 callback.onAffiliationChangedSuccessful(jid);
3435 } else {
3436 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3437 }
3438 } else if (callback != null) {
3439 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3440 } else {
3441 Log.d(Config.LOGTAG, "unable to change affiliation");
3442 }
3443 });
3444 }
3445
3446 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3447 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3448 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3449 if (packet.getType() != IqPacket.TYPE.RESULT) {
3450 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3451 }
3452 });
3453 }
3454
3455 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3456 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3457 request.setTo(conversation.getJid().asBareJid());
3458 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3459 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3460 @Override
3461 public void onIqPacketReceived(Account account, IqPacket packet) {
3462 if (packet.getType() == IqPacket.TYPE.RESULT) {
3463 if (callback != null) {
3464 callback.onRoomDestroySucceeded();
3465 }
3466 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3467 if (callback != null) {
3468 callback.onRoomDestroyFailed();
3469 }
3470 }
3471 }
3472 });
3473 }
3474
3475 private void disconnect(Account account, boolean force) {
3476 if ((account.getStatus() == Account.State.ONLINE)
3477 || (account.getStatus() == Account.State.DISABLED)) {
3478 final XmppConnection connection = account.getXmppConnection();
3479 if (!force) {
3480 List<Conversation> conversations = getConversations();
3481 for (Conversation conversation : conversations) {
3482 if (conversation.getAccount() == account) {
3483 if (conversation.getMode() == Conversation.MODE_MULTI) {
3484 leaveMuc(conversation, true);
3485 }
3486 }
3487 }
3488 sendOfflinePresence(account);
3489 }
3490 connection.disconnect(force);
3491 }
3492 }
3493
3494 @Override
3495 public IBinder onBind(Intent intent) {
3496 return mBinder;
3497 }
3498
3499 public void updateMessage(Message message) {
3500 updateMessage(message, true);
3501 }
3502
3503 public void updateMessage(Message message, boolean includeBody) {
3504 databaseBackend.updateMessage(message, includeBody);
3505 updateConversationUi();
3506 }
3507
3508 public void createMessageAsync(final Message message) {
3509 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3510 }
3511
3512 public void updateMessage(Message message, String uuid) {
3513 if (!databaseBackend.updateMessage(message, uuid)) {
3514 Log.e(Config.LOGTAG, "error updated message in DB after edit");
3515 }
3516 updateConversationUi();
3517 }
3518
3519 protected void syncDirtyContacts(Account account) {
3520 for (Contact contact : account.getRoster().getContacts()) {
3521 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3522 pushContactToServer(contact);
3523 }
3524 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3525 deleteContactOnServer(contact);
3526 }
3527 }
3528 }
3529
3530 protected void unregisterPhoneAccounts(final Account account) {
3531 for (final Contact contact : account.getRoster().getContacts()) {
3532 if (!contact.showInRoster()) {
3533 contact.unregisterAsPhoneAccount(this);
3534 }
3535 }
3536 }
3537
3538 public void createContact(final Contact contact, final boolean autoGrant) {
3539 createContact(contact, autoGrant, null);
3540 }
3541
3542 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3543 if (autoGrant) {
3544 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3545 contact.setOption(Contact.Options.ASKING);
3546 }
3547 pushContactToServer(contact, preAuth);
3548 }
3549
3550 public void pushContactToServer(final Contact contact) {
3551 pushContactToServer(contact, null);
3552 }
3553
3554 private void pushContactToServer(final Contact contact, final String preAuth) {
3555 contact.resetOption(Contact.Options.DIRTY_DELETE);
3556 contact.setOption(Contact.Options.DIRTY_PUSH);
3557 final Account account = contact.getAccount();
3558 if (account.getStatus() == Account.State.ONLINE) {
3559 final boolean ask = contact.getOption(Contact.Options.ASKING);
3560 final boolean sendUpdates = contact
3561 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3562 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3563 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3564 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3565 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3566 if (sendUpdates) {
3567 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3568 }
3569 if (ask) {
3570 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3571 }
3572 } else {
3573 syncRoster(contact.getAccount());
3574 }
3575 }
3576
3577 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3578 new Thread(() -> {
3579 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3580 final int size = Config.AVATAR_SIZE;
3581 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3582 if (avatar != null) {
3583 if (!getFileBackend().save(avatar)) {
3584 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3585 return;
3586 }
3587 avatar.owner = conversation.getJid().asBareJid();
3588 publishMucAvatar(conversation, avatar, callback);
3589 } else {
3590 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3591 }
3592 }).start();
3593 }
3594
3595 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3596 new Thread(() -> {
3597 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3598 final int size = Config.AVATAR_SIZE;
3599 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3600 if (avatar != null) {
3601 if (!getFileBackend().save(avatar)) {
3602 Log.d(Config.LOGTAG, "unable to save vcard");
3603 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3604 return;
3605 }
3606 publishAvatar(account, avatar, callback);
3607 } else {
3608 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3609 }
3610 }).start();
3611
3612 }
3613
3614 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3615 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3616 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3617 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3618 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3619 Element vcard = response.findChild("vCard", "vcard-temp");
3620 if (vcard == null) {
3621 vcard = new Element("vCard", "vcard-temp");
3622 }
3623 Element photo = vcard.findChild("PHOTO");
3624 if (photo == null) {
3625 photo = vcard.addChild("PHOTO");
3626 }
3627 photo.clearChildren();
3628 photo.addChild("TYPE").setContent(avatar.type);
3629 photo.addChild("BINVAL").setContent(avatar.image);
3630 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3631 publication.setTo(conversation.getJid().asBareJid());
3632 publication.addChild(vcard);
3633 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3634 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3635 callback.onAvatarPublicationSucceeded();
3636 } else {
3637 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3638 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3639 }
3640 });
3641 } else {
3642 Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3643 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3644 }
3645 });
3646 }
3647
3648 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3649 final Bundle options;
3650 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3651 options = PublishOptions.openAccess();
3652 } else {
3653 options = null;
3654 }
3655 publishAvatar(account, avatar, options, true, callback);
3656 }
3657
3658 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3659 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3660 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3661 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3662
3663 @Override
3664 public void onIqPacketReceived(Account account, IqPacket result) {
3665 if (result.getType() == IqPacket.TYPE.RESULT) {
3666 publishAvatarMetadata(account, avatar, options, true, callback);
3667 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3668 pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3669 @Override
3670 public void onPushSucceeded() {
3671 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3672 publishAvatar(account, avatar, options, false, callback);
3673 }
3674
3675 @Override
3676 public void onPushFailed() {
3677 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3678 publishAvatar(account, avatar, null, false, callback);
3679 }
3680 });
3681 } else {
3682 Element error = result.findChild("error");
3683 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3684 if (callback != null) {
3685 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3686 }
3687 }
3688 }
3689 });
3690 }
3691
3692 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3693 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3694 sendIqPacket(account, packet, new OnIqPacketReceived() {
3695 @Override
3696 public void onIqPacketReceived(Account account, IqPacket result) {
3697 if (result.getType() == IqPacket.TYPE.RESULT) {
3698 if (account.setAvatar(avatar.getFilename())) {
3699 getAvatarService().clear(account);
3700 databaseBackend.updateAccount(account);
3701 notifyAccountAvatarHasChanged(account);
3702 }
3703 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3704 if (callback != null) {
3705 callback.onAvatarPublicationSucceeded();
3706 }
3707 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3708 pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3709 @Override
3710 public void onPushSucceeded() {
3711 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3712 publishAvatarMetadata(account, avatar, options, false, callback);
3713 }
3714
3715 @Override
3716 public void onPushFailed() {
3717 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3718 publishAvatarMetadata(account, avatar, null, false, callback);
3719 }
3720 });
3721 } else {
3722 if (callback != null) {
3723 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3724 }
3725 }
3726 }
3727 });
3728 }
3729
3730 public void republishAvatarIfNeeded(Account account) {
3731 if (account.getAxolotlService().isPepBroken()) {
3732 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3733 return;
3734 }
3735 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3736 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3737
3738 private Avatar parseAvatar(IqPacket packet) {
3739 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3740 if (pubsub != null) {
3741 Element items = pubsub.findChild("items");
3742 if (items != null) {
3743 return Avatar.parseMetadata(items);
3744 }
3745 }
3746 return null;
3747 }
3748
3749 private boolean errorIsItemNotFound(IqPacket packet) {
3750 Element error = packet.findChild("error");
3751 return packet.getType() == IqPacket.TYPE.ERROR
3752 && error != null
3753 && error.hasChild("item-not-found");
3754 }
3755
3756 @Override
3757 public void onIqPacketReceived(Account account, IqPacket packet) {
3758 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3759 Avatar serverAvatar = parseAvatar(packet);
3760 if (serverAvatar == null && account.getAvatar() != null) {
3761 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3762 if (avatar != null) {
3763 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3764 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3765 } else {
3766 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3767 }
3768 }
3769 }
3770 }
3771 });
3772 }
3773
3774 public void fetchAvatar(Account account, Avatar avatar) {
3775 fetchAvatar(account, avatar, null);
3776 }
3777
3778 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3779 final String KEY = generateFetchKey(account, avatar);
3780 synchronized (this.mInProgressAvatarFetches) {
3781 if (mInProgressAvatarFetches.add(KEY)) {
3782 switch (avatar.origin) {
3783 case PEP:
3784 this.mInProgressAvatarFetches.add(KEY);
3785 fetchAvatarPep(account, avatar, callback);
3786 break;
3787 case VCARD:
3788 this.mInProgressAvatarFetches.add(KEY);
3789 fetchAvatarVcard(account, avatar, callback);
3790 break;
3791 }
3792 } else if (avatar.origin == Avatar.Origin.PEP) {
3793 mOmittedPepAvatarFetches.add(KEY);
3794 } else {
3795 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
3796 }
3797 }
3798 }
3799
3800 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3801 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3802 sendIqPacket(account, packet, (a, result) -> {
3803 synchronized (mInProgressAvatarFetches) {
3804 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3805 }
3806 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3807 if (result.getType() == IqPacket.TYPE.RESULT) {
3808 avatar.image = mIqParser.avatarData(result);
3809 if (avatar.image != null) {
3810 if (getFileBackend().save(avatar)) {
3811 if (a.getJid().asBareJid().equals(avatar.owner)) {
3812 if (a.setAvatar(avatar.getFilename())) {
3813 databaseBackend.updateAccount(a);
3814 }
3815 getAvatarService().clear(a);
3816 updateConversationUi();
3817 updateAccountUi();
3818 } else {
3819 final Contact contact = a.getRoster().getContact(avatar.owner);
3820 contact.setAvatar(avatar);
3821 syncRoster(account);
3822 getAvatarService().clear(contact);
3823 updateConversationUi();
3824 updateRosterUi();
3825 }
3826 if (callback != null) {
3827 callback.success(avatar);
3828 }
3829 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
3830 return;
3831 }
3832 } else {
3833
3834 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3835 }
3836 } else {
3837 Element error = result.findChild("error");
3838 if (error == null) {
3839 Log.d(Config.LOGTAG, ERROR + "(server error)");
3840 } else {
3841 Log.d(Config.LOGTAG, ERROR + error.toString());
3842 }
3843 }
3844 if (callback != null) {
3845 callback.error(0, null);
3846 }
3847
3848 });
3849 }
3850
3851 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3852 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3853 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3854 @Override
3855 public void onIqPacketReceived(Account account, IqPacket packet) {
3856 final boolean previouslyOmittedPepFetch;
3857 synchronized (mInProgressAvatarFetches) {
3858 final String KEY = generateFetchKey(account, avatar);
3859 mInProgressAvatarFetches.remove(KEY);
3860 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3861 }
3862 if (packet.getType() == IqPacket.TYPE.RESULT) {
3863 Element vCard = packet.findChild("vCard", "vcard-temp");
3864 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3865 String image = photo != null ? photo.findChildContent("BINVAL") : null;
3866 if (image != null) {
3867 avatar.image = image;
3868 if (getFileBackend().save(avatar)) {
3869 Log.d(Config.LOGTAG, account.getJid().asBareJid()
3870 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
3871 if (avatar.owner.isBareJid()) {
3872 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3873 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3874 account.setAvatar(avatar.getFilename());
3875 databaseBackend.updateAccount(account);
3876 getAvatarService().clear(account);
3877 updateAccountUi();
3878 } else {
3879 final Contact contact = account.getRoster().getContact(avatar.owner);
3880 contact.setAvatar(avatar, previouslyOmittedPepFetch);
3881 syncRoster(account);
3882 getAvatarService().clear(contact);
3883 updateRosterUi();
3884 }
3885 updateConversationUi();
3886 } else {
3887 Conversation conversation = find(account, avatar.owner.asBareJid());
3888 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3889 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3890 if (user != null) {
3891 if (user.setAvatar(avatar)) {
3892 getAvatarService().clear(user);
3893 updateConversationUi();
3894 updateMucRosterUi();
3895 }
3896 if (user.getRealJid() != null) {
3897 Contact contact = account.getRoster().getContact(user.getRealJid());
3898 contact.setAvatar(avatar);
3899 syncRoster(account);
3900 getAvatarService().clear(contact);
3901 updateRosterUi();
3902 }
3903 }
3904 }
3905 }
3906 }
3907 }
3908 }
3909 }
3910 });
3911 }
3912
3913 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3914 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3915 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3916
3917 @Override
3918 public void onIqPacketReceived(Account account, IqPacket packet) {
3919 if (packet.getType() == IqPacket.TYPE.RESULT) {
3920 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3921 if (pubsub != null) {
3922 Element items = pubsub.findChild("items");
3923 if (items != null) {
3924 Avatar avatar = Avatar.parseMetadata(items);
3925 if (avatar != null) {
3926 avatar.owner = account.getJid().asBareJid();
3927 if (fileBackend.isAvatarCached(avatar)) {
3928 if (account.setAvatar(avatar.getFilename())) {
3929 databaseBackend.updateAccount(account);
3930 }
3931 getAvatarService().clear(account);
3932 callback.success(avatar);
3933 } else {
3934 fetchAvatarPep(account, avatar, callback);
3935 }
3936 return;
3937 }
3938 }
3939 }
3940 }
3941 callback.error(0, null);
3942 }
3943 });
3944 }
3945
3946 public void notifyAccountAvatarHasChanged(final Account account) {
3947 final XmppConnection connection = account.getXmppConnection();
3948 if (connection != null && connection.getFeatures().bookmarksConversion()) {
3949 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
3950 for (Conversation conversation : conversations) {
3951 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3952 final MucOptions mucOptions = conversation.getMucOptions();
3953 if (mucOptions.online()) {
3954 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3955 packet.setTo(mucOptions.getSelf().getFullJid());
3956 connection.sendPresencePacket(packet);
3957 }
3958 }
3959 }
3960 }
3961 }
3962
3963 public void deleteContactOnServer(Contact contact) {
3964 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3965 contact.resetOption(Contact.Options.DIRTY_PUSH);
3966 contact.setOption(Contact.Options.DIRTY_DELETE);
3967 Account account = contact.getAccount();
3968 if (account.getStatus() == Account.State.ONLINE) {
3969 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3970 Element item = iq.query(Namespace.ROSTER).addChild("item");
3971 item.setAttribute("jid", contact.getJid());
3972 item.setAttribute("subscription", "remove");
3973 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3974 }
3975 }
3976
3977 public void updateConversation(final Conversation conversation) {
3978 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3979 }
3980
3981 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3982 synchronized (account) {
3983 XmppConnection connection = account.getXmppConnection();
3984 if (connection == null) {
3985 connection = createConnection(account);
3986 account.setXmppConnection(connection);
3987 }
3988 boolean hasInternet = hasInternetConnection();
3989 if (account.isEnabled() && hasInternet) {
3990 if (!force) {
3991 disconnect(account, false);
3992 }
3993 Thread thread = new Thread(connection);
3994 connection.setInteractive(interactive);
3995 connection.prepareNewConnection();
3996 connection.interrupt();
3997 thread.start();
3998 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3999 } else {
4000 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4001 account.getRoster().clearPresences();
4002 connection.resetEverything();
4003 final AxolotlService axolotlService = account.getAxolotlService();
4004 if (axolotlService != null) {
4005 axolotlService.resetBrokenness();
4006 }
4007 if (!hasInternet) {
4008 account.setStatus(Account.State.NO_INTERNET);
4009 }
4010 }
4011 }
4012 }
4013
4014 public void reconnectAccountInBackground(final Account account) {
4015 new Thread(() -> reconnectAccount(account, false, true)).start();
4016 }
4017
4018 public void invite(final Conversation conversation, final Jid contact) {
4019 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4020 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4021 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4022 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4023 }
4024 final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4025 sendMessagePacket(conversation.getAccount(), packet);
4026 }
4027
4028 public void directInvite(Conversation conversation, Jid jid) {
4029 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4030 sendMessagePacket(conversation.getAccount(), packet);
4031 }
4032
4033 public void resetSendingToWaiting(Account account) {
4034 for (Conversation conversation : getConversations()) {
4035 if (conversation.getAccount() == account) {
4036 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4037 }
4038 }
4039 }
4040
4041 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4042 return markMessage(account, recipient, uuid, status, null);
4043 }
4044
4045 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4046 if (uuid == null) {
4047 return null;
4048 }
4049 for (Conversation conversation : getConversations()) {
4050 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4051 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4052 if (message != null) {
4053 markMessage(message, status, errorMessage);
4054 }
4055 return message;
4056 }
4057 }
4058 return null;
4059 }
4060
4061 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4062 return markMessage(conversation, uuid, status, serverMessageId, null);
4063 }
4064
4065 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4066 if (uuid == null) {
4067 return false;
4068 } else {
4069 final Message message = conversation.findSentMessageWithUuid(uuid);
4070 if (message != null) {
4071 if (message.getServerMsgId() == null) {
4072 message.setServerMsgId(serverMessageId);
4073 }
4074 if (message.getEncryption() == Message.ENCRYPTION_NONE
4075 && message.isTypeText()
4076 && isBodyModified(message, body)) {
4077 message.setBody(body.content);
4078 if (body.count > 1) {
4079 message.setBodyLanguage(body.language);
4080 }
4081 markMessage(message, status, null, true);
4082 } else {
4083 markMessage(message, status);
4084 }
4085 return true;
4086 } else {
4087 return false;
4088 }
4089 }
4090 }
4091
4092 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4093 if (body == null || body.content == null) {
4094 return false;
4095 }
4096 return !body.content.equals(message.getBody());
4097 }
4098
4099 public void markMessage(Message message, int status) {
4100 markMessage(message, status, null);
4101 }
4102
4103
4104 public void markMessage(final Message message, final int status, final String errorMessage) {
4105 markMessage(message, status, errorMessage, false);
4106 }
4107
4108 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4109 final int oldStatus = message.getStatus();
4110 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4111 return;
4112 }
4113 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4114 return;
4115 }
4116 message.setErrorMessage(errorMessage);
4117 message.setStatus(status);
4118 databaseBackend.updateMessage(message, includeBody);
4119 updateConversationUi();
4120 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4121 mNotificationService.pushFailedDelivery(message);
4122 }
4123 }
4124
4125 private SharedPreferences getPreferences() {
4126 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4127 }
4128
4129 public long getAutomaticMessageDeletionDate() {
4130 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4131 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4132 }
4133
4134 public long getLongPreference(String name, @IntegerRes int res) {
4135 long defaultValue = getResources().getInteger(res);
4136 try {
4137 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4138 } catch (NumberFormatException e) {
4139 return defaultValue;
4140 }
4141 }
4142
4143 public boolean getBooleanPreference(String name, @BoolRes int res) {
4144 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4145 }
4146
4147 public boolean confirmMessages() {
4148 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4149 }
4150
4151 public boolean allowMessageCorrection() {
4152 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4153 }
4154
4155 public boolean sendChatStates() {
4156 return getBooleanPreference("chat_states", R.bool.chat_states);
4157 }
4158
4159 private boolean synchronizeWithBookmarks() {
4160 return getBooleanPreference("autojoin", R.bool.autojoin);
4161 }
4162
4163 public boolean useTorToConnect() {
4164 return getBooleanPreference("use_tor", R.bool.use_tor);
4165 }
4166
4167 public boolean showExtendedConnectionOptions() {
4168 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4169 }
4170
4171 public boolean broadcastLastActivity() {
4172 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4173 }
4174
4175 public int unreadCount() {
4176 int count = 0;
4177 for (Conversation conversation : getConversations()) {
4178 count += conversation.unreadCount();
4179 }
4180 return count;
4181 }
4182
4183
4184 private <T> List<T> threadSafeList(Set<T> set) {
4185 synchronized (LISTENER_LOCK) {
4186 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4187 }
4188 }
4189
4190 public void showErrorToastInUi(int resId) {
4191 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4192 listener.onShowErrorToast(resId);
4193 }
4194 }
4195
4196 public void updateConversationUi() {
4197 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4198 listener.onConversationUpdate();
4199 }
4200 }
4201
4202 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4203 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4204 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4205 }
4206 }
4207
4208 public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4209 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4210 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4211 }
4212 }
4213
4214 public void updateAccountUi() {
4215 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4216 listener.onAccountUpdate();
4217 }
4218 }
4219
4220 public void updateRosterUi() {
4221 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4222 listener.onRosterUpdate();
4223 }
4224 }
4225
4226 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4227 if (mOnCaptchaRequested.size() > 0) {
4228 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4229 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4230 (int) (captcha.getHeight() * metrics.scaledDensity), false);
4231 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4232 listener.onCaptchaRequested(account, id, data, scaled);
4233 }
4234 return true;
4235 }
4236 return false;
4237 }
4238
4239 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4240 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4241 listener.OnUpdateBlocklist(status);
4242 }
4243 }
4244
4245 public void updateMucRosterUi() {
4246 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4247 listener.onMucRosterUpdate();
4248 }
4249 }
4250
4251 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4252 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4253 listener.onKeyStatusUpdated(report);
4254 }
4255 }
4256
4257 public Account findAccountByJid(final Jid jid) {
4258 for (final Account account : this.accounts) {
4259 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4260 return account;
4261 }
4262 }
4263 return null;
4264 }
4265
4266 public Account findAccountByUuid(final String uuid) {
4267 for (Account account : this.accounts) {
4268 if (account.getUuid().equals(uuid)) {
4269 return account;
4270 }
4271 }
4272 return null;
4273 }
4274
4275 public Conversation findConversationByUuid(String uuid) {
4276 for (Conversation conversation : getConversations()) {
4277 if (conversation.getUuid().equals(uuid)) {
4278 return conversation;
4279 }
4280 }
4281 return null;
4282 }
4283
4284 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4285 List<Conversation> findings = new ArrayList<>();
4286 for (Conversation c : getConversations()) {
4287 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4288 findings.add(c);
4289 }
4290 }
4291 return findings.size() == 1 ? findings.get(0) : null;
4292 }
4293
4294 public boolean markRead(final Conversation conversation, boolean dismiss) {
4295 return markRead(conversation, null, dismiss).size() > 0;
4296 }
4297
4298 public void markRead(final Conversation conversation) {
4299 markRead(conversation, null, true);
4300 }
4301
4302 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4303 if (dismiss) {
4304 mNotificationService.clear(conversation);
4305 }
4306 final List<Message> readMessages = conversation.markRead(upToUuid);
4307 if (readMessages.size() > 0) {
4308 Runnable runnable = () -> {
4309 for (Message message : readMessages) {
4310 databaseBackend.updateMessage(message, false);
4311 }
4312 };
4313 mDatabaseWriterExecutor.execute(runnable);
4314 updateConversationUi();
4315 updateUnreadCountBadge();
4316 return readMessages;
4317 } else {
4318 return readMessages;
4319 }
4320 }
4321
4322 public synchronized void updateUnreadCountBadge() {
4323 int count = unreadCount();
4324 if (unreadCount != count) {
4325 Log.d(Config.LOGTAG, "update unread count to " + count);
4326 if (count > 0) {
4327 ShortcutBadger.applyCount(getApplicationContext(), count);
4328 } else {
4329 ShortcutBadger.removeCount(getApplicationContext());
4330 }
4331 unreadCount = count;
4332 }
4333 }
4334
4335 public void sendReadMarker(final Conversation conversation, String upToUuid) {
4336 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4337 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4338 if (readMessages.size() > 0) {
4339 updateConversationUi();
4340 }
4341 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4342 if (confirmMessages()
4343 && markable != null
4344 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4345 && markable.getRemoteMsgId() != null) {
4346 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4347 final Account account = conversation.getAccount();
4348 final MessagePacket packet = mMessageGenerator.confirm(markable);
4349 this.sendMessagePacket(account, packet);
4350 }
4351 }
4352
4353 public SecureRandom getRNG() {
4354 return this.mRandom;
4355 }
4356
4357 public MemorizingTrustManager getMemorizingTrustManager() {
4358 return this.mMemorizingTrustManager;
4359 }
4360
4361 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4362 this.mMemorizingTrustManager = trustManager;
4363 }
4364
4365 public void updateMemorizingTrustmanager() {
4366 final MemorizingTrustManager tm;
4367 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4368 if (dontTrustSystemCAs) {
4369 tm = new MemorizingTrustManager(getApplicationContext(), null);
4370 } else {
4371 tm = new MemorizingTrustManager(getApplicationContext());
4372 }
4373 setMemorizingTrustManager(tm);
4374 }
4375
4376 public LruCache<String, Bitmap> getBitmapCache() {
4377 return this.mBitmapCache;
4378 }
4379
4380 public LruCache<String, Drawable> getDrawableCache() {
4381 return this.mDrawableCache;
4382 }
4383
4384 public Collection<String> getKnownHosts() {
4385 final Set<String> hosts = new HashSet<>();
4386 for (final Account account : getAccounts()) {
4387 hosts.add(account.getServer());
4388 for (final Contact contact : account.getRoster().getContacts()) {
4389 if (contact.showInRoster()) {
4390 final String server = contact.getServer();
4391 if (server != null) {
4392 hosts.add(server);
4393 }
4394 }
4395 }
4396 }
4397 if (Config.QUICKSY_DOMAIN != null) {
4398 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4399 }
4400 if (Config.DOMAIN_LOCK != null) {
4401 hosts.add(Config.DOMAIN_LOCK);
4402 }
4403 if (Config.MAGIC_CREATE_DOMAIN != null) {
4404 hosts.add(Config.MAGIC_CREATE_DOMAIN);
4405 }
4406 return hosts;
4407 }
4408
4409 public Collection<String> getKnownConferenceHosts() {
4410 final Set<String> mucServers = new HashSet<>();
4411 for (final Account account : accounts) {
4412 if (account.getXmppConnection() != null) {
4413 mucServers.addAll(account.getXmppConnection().getMucServers());
4414 for (Bookmark bookmark : account.getBookmarks()) {
4415 final Jid jid = bookmark.getJid();
4416 final String s = jid == null ? null : jid.getDomain().toEscapedString();
4417 if (s != null) {
4418 mucServers.add(s);
4419 }
4420 }
4421 }
4422 }
4423 return mucServers;
4424 }
4425
4426 public void sendMessagePacket(Account account, MessagePacket packet) {
4427 final XmppConnection connection = account.getXmppConnection();
4428 if (connection != null) {
4429 connection.sendMessagePacket(packet);
4430 }
4431 }
4432
4433 public void sendPresencePacket(Account account, PresencePacket packet) {
4434 XmppConnection connection = account.getXmppConnection();
4435 if (connection != null) {
4436 connection.sendPresencePacket(packet);
4437 }
4438 }
4439
4440 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4441 final XmppConnection connection = account.getXmppConnection();
4442 if (connection != null) {
4443 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4444 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4445 }
4446 }
4447
4448 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4449 final XmppConnection connection = account.getXmppConnection();
4450 if (connection != null) {
4451 connection.sendIqPacket(packet, callback);
4452 } else if (callback != null) {
4453 callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4454 }
4455 }
4456
4457 public void sendPresence(final Account account) {
4458 sendPresence(account, checkListeners() && broadcastLastActivity());
4459 }
4460
4461 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4462 final Presence.Status status;
4463 if (manuallyChangePresence()) {
4464 status = account.getPresenceStatus();
4465 } else {
4466 status = getTargetPresence();
4467 }
4468 final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4469 if (mLastActivity > 0 && includeIdleTimestamp) {
4470 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4471 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4472 }
4473 sendPresencePacket(account, packet);
4474 }
4475
4476 private void deactivateGracePeriod() {
4477 for (Account account : getAccounts()) {
4478 account.deactivateGracePeriod();
4479 }
4480 }
4481
4482 public void refreshAllPresences() {
4483 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4484 for (Account account : getAccounts()) {
4485 if (account.isEnabled()) {
4486 sendPresence(account, includeIdleTimestamp);
4487 }
4488 }
4489 }
4490
4491 private void refreshAllFcmTokens() {
4492 for (Account account : getAccounts()) {
4493 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4494 mPushManagementService.registerPushTokenOnServer(account);
4495 //TODO renew mucs
4496 }
4497 }
4498 }
4499
4500 private void sendOfflinePresence(final Account account) {
4501 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4502 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4503 }
4504
4505 public MessageGenerator getMessageGenerator() {
4506 return this.mMessageGenerator;
4507 }
4508
4509 public PresenceGenerator getPresenceGenerator() {
4510 return this.mPresenceGenerator;
4511 }
4512
4513 public IqGenerator getIqGenerator() {
4514 return this.mIqGenerator;
4515 }
4516
4517 public IqParser getIqParser() {
4518 return this.mIqParser;
4519 }
4520
4521 public JingleConnectionManager getJingleConnectionManager() {
4522 return this.mJingleConnectionManager;
4523 }
4524
4525 public MessageArchiveService getMessageArchiveService() {
4526 return this.mMessageArchiveService;
4527 }
4528
4529 public QuickConversationsService getQuickConversationsService() {
4530 return this.mQuickConversationsService;
4531 }
4532
4533 public List<Contact> findContacts(Jid jid, String accountJid) {
4534 ArrayList<Contact> contacts = new ArrayList<>();
4535 for (Account account : getAccounts()) {
4536 if ((account.isEnabled() || accountJid != null)
4537 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4538 Contact contact = account.getRoster().getContactFromContactList(jid);
4539 if (contact != null) {
4540 contacts.add(contact);
4541 }
4542 }
4543 }
4544 return contacts;
4545 }
4546
4547 public Conversation findFirstMuc(Jid jid) {
4548 for (Conversation conversation : getConversations()) {
4549 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4550 return conversation;
4551 }
4552 }
4553 return null;
4554 }
4555
4556 public NotificationService getNotificationService() {
4557 return this.mNotificationService;
4558 }
4559
4560 public HttpConnectionManager getHttpConnectionManager() {
4561 return this.mHttpConnectionManager;
4562 }
4563
4564 public void resendFailedMessages(final Message message) {
4565 final Collection<Message> messages = new ArrayList<>();
4566 Message current = message;
4567 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4568 messages.add(current);
4569 if (current.mergeable(current.next())) {
4570 current = current.next();
4571 } else {
4572 break;
4573 }
4574 }
4575 for (final Message msg : messages) {
4576 msg.setTime(System.currentTimeMillis());
4577 markMessage(msg, Message.STATUS_WAITING);
4578 this.resendMessage(msg, false);
4579 }
4580 if (message.getConversation() instanceof Conversation) {
4581 ((Conversation) message.getConversation()).sort();
4582 }
4583 updateConversationUi();
4584 }
4585
4586 public void clearConversationHistory(final Conversation conversation) {
4587 final long clearDate;
4588 final String reference;
4589 if (conversation.countMessages() > 0) {
4590 Message latestMessage = conversation.getLatestMessage();
4591 clearDate = latestMessage.getTimeSent() + 1000;
4592 reference = latestMessage.getServerMsgId();
4593 } else {
4594 clearDate = System.currentTimeMillis();
4595 reference = null;
4596 }
4597 conversation.clearMessages();
4598 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4599 conversation.setLastClearHistory(clearDate, reference);
4600 Runnable runnable = () -> {
4601 databaseBackend.deleteMessagesInConversation(conversation);
4602 databaseBackend.updateConversation(conversation);
4603 };
4604 mDatabaseWriterExecutor.execute(runnable);
4605 }
4606
4607 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4608 if (blockable != null && blockable.getBlockedJid() != null) {
4609 final Jid jid = blockable.getBlockedJid();
4610 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4611 if (response.getType() == IqPacket.TYPE.RESULT) {
4612 a.getBlocklist().add(jid);
4613 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4614 }
4615 });
4616 if (blockable.getBlockedJid().isFullJid()) {
4617 return false;
4618 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4619 updateConversationUi();
4620 return true;
4621 } else {
4622 return false;
4623 }
4624 } else {
4625 return false;
4626 }
4627 }
4628
4629 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4630 boolean removed = false;
4631 synchronized (this.conversations) {
4632 boolean domainJid = blockedJid.getLocal() == null;
4633 for (Conversation conversation : this.conversations) {
4634 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4635 || blockedJid.equals(conversation.getJid().asBareJid());
4636 if (conversation.getAccount() == account
4637 && conversation.getMode() == Conversation.MODE_SINGLE
4638 && jidMatches) {
4639 this.conversations.remove(conversation);
4640 markRead(conversation);
4641 conversation.setStatus(Conversation.STATUS_ARCHIVED);
4642 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4643 updateConversation(conversation);
4644 removed = true;
4645 }
4646 }
4647 }
4648 return removed;
4649 }
4650
4651 public void sendUnblockRequest(final Blockable blockable) {
4652 if (blockable != null && blockable.getJid() != null) {
4653 final Jid jid = blockable.getBlockedJid();
4654 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4655 @Override
4656 public void onIqPacketReceived(final Account account, final IqPacket packet) {
4657 if (packet.getType() == IqPacket.TYPE.RESULT) {
4658 account.getBlocklist().remove(jid);
4659 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4660 }
4661 }
4662 });
4663 }
4664 }
4665
4666 public void publishDisplayName(Account account) {
4667 String displayName = account.getDisplayName();
4668 final IqPacket request;
4669 if (TextUtils.isEmpty(displayName)) {
4670 request = mIqGenerator.deleteNode(Namespace.NICK);
4671 } else {
4672 request = mIqGenerator.publishNick(displayName);
4673 }
4674 mAvatarService.clear(account);
4675 sendIqPacket(account, request, (account1, packet) -> {
4676 if (packet.getType() == IqPacket.TYPE.ERROR) {
4677 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet.toString());
4678 }
4679 });
4680 }
4681
4682 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4683 ServiceDiscoveryResult result = discoCache.get(key);
4684 if (result != null) {
4685 return result;
4686 } else {
4687 if (key.first == null || key.second == null) return null;
4688 result = databaseBackend.findDiscoveryResult(key.first, key.second);
4689 if (result != null) {
4690 discoCache.put(key, result);
4691 }
4692 return result;
4693 }
4694 }
4695
4696 public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
4697 IqPacket request = new IqPacket(input == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
4698 request.setTo(jid);
4699 Element query = request.query("jabber:iq:gateway");
4700 if (input != null) {
4701 Element prompt = query.addChild("prompt");
4702 prompt.setContent(input);
4703 }
4704 sendIqPacket(account, request, (Account acct, IqPacket packet) -> {
4705 if (packet.getType() == IqPacket.TYPE.RESULT) {
4706 callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
4707 } else {
4708 Element error = packet.findChild("error");
4709 callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
4710 }
4711 });
4712 }
4713
4714 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4715 fetchCaps(account, jid, presence, null);
4716 }
4717
4718 public void fetchCaps(Account account, final Jid jid, final Presence presence, Runnable cb) {
4719 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4720 final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4721
4722 if (disco != null) {
4723 presence.setServiceDiscoveryResult(disco);
4724 final Contact contact = account.getRoster().getContact(jid);
4725 if (contact.refreshRtpCapability()) {
4726 syncRoster(account);
4727 }
4728 if (disco.hasIdentity("gateway", "pstn")) {
4729 contact.registerAsPhoneAccount(this);
4730 mQuickConversationsService.considerSyncBackground(false);
4731 }
4732 } else {
4733 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4734 request.setTo(jid);
4735 final String node = presence.getNode();
4736 final String ver = presence.getVer();
4737 final Element query = request.query(Namespace.DISCO_INFO);
4738 if (node != null && ver != null) {
4739 query.setAttribute("node", node + "#" + ver);
4740 }
4741 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4742 sendIqPacket(account, request, (a, response) -> {
4743 if (response.getType() == IqPacket.TYPE.RESULT) {
4744 final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4745 if (presence.getVer() == null || presence.getVer().equals(discoveryResult.getVer())) {
4746 databaseBackend.insertDiscoveryResult(discoveryResult);
4747 injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), jid.getResource(), discoveryResult);
4748 if (discoveryResult.hasIdentity("gateway", "pstn")) {
4749 final Contact contact = account.getRoster().getContact(jid);
4750 contact.registerAsPhoneAccount(this);
4751 mQuickConversationsService.considerSyncBackground(false);
4752 }
4753 if (cb != null) cb.run();
4754 } else {
4755 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4756 }
4757 } else {
4758 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
4759 }
4760 });
4761 }
4762 }
4763
4764 public void fetchCommands(Account account, final Jid jid, OnIqPacketReceived callback) {
4765 final IqPacket request = mIqGenerator.queryDiscoItems(jid, "http://jabber.org/protocol/commands");
4766 sendIqPacket(account, request, callback);
4767 }
4768
4769 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, String resource, ServiceDiscoveryResult disco) {
4770 boolean rosterNeedsSync = false;
4771 for (final Contact contact : roster.getContacts()) {
4772 boolean serviceDiscoverySet = false;
4773 Presence onePresence = contact.getPresences().get(resource == null ? "" : resource);
4774 if (onePresence != null) {
4775 onePresence.setServiceDiscoveryResult(disco);
4776 serviceDiscoverySet = true;
4777 }
4778 if (hash != null && ver != null) {
4779 for (final Presence presence : contact.getPresences().getPresences()) {
4780 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4781 presence.setServiceDiscoveryResult(disco);
4782 serviceDiscoverySet = true;
4783 }
4784 }
4785 }
4786 if (serviceDiscoverySet) {
4787 rosterNeedsSync |= contact.refreshRtpCapability();
4788 }
4789 }
4790 if (rosterNeedsSync) {
4791 syncRoster(roster.getAccount());
4792 }
4793 }
4794
4795 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4796 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4797 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4798 request.addChild("prefs", version.namespace);
4799 sendIqPacket(account, request, (account1, packet) -> {
4800 Element prefs = packet.findChild("prefs", version.namespace);
4801 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4802 callback.onPreferencesFetched(prefs);
4803 } else {
4804 callback.onPreferencesFetchFailed();
4805 }
4806 });
4807 }
4808
4809 public PushManagementService getPushManagementService() {
4810 return mPushManagementService;
4811 }
4812
4813 public void changeStatus(Account account, PresenceTemplate template, String signature) {
4814 if (!template.getStatusMessage().isEmpty()) {
4815 databaseBackend.insertPresenceTemplate(template);
4816 }
4817 account.setPgpSignature(signature);
4818 account.setPresenceStatus(template.getStatus());
4819 account.setPresenceStatusMessage(template.getStatusMessage());
4820 databaseBackend.updateAccount(account);
4821 sendPresence(account);
4822 }
4823
4824 public List<PresenceTemplate> getPresenceTemplates(Account account) {
4825 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4826 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4827 if (!templates.contains(template)) {
4828 templates.add(0, template);
4829 }
4830 }
4831 return templates;
4832 }
4833
4834 public void saveConversationAsBookmark(Conversation conversation, String name) {
4835 final Account account = conversation.getAccount();
4836 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4837 final String nick = conversation.getJid().getResource();
4838 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4839 bookmark.setNick(nick);
4840 }
4841 if (!TextUtils.isEmpty(name)) {
4842 bookmark.setBookmarkName(name);
4843 }
4844 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4845 createBookmark(account, bookmark);
4846 bookmark.setConversation(conversation);
4847 }
4848
4849 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4850 boolean performedVerification = false;
4851 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4852 for (XmppUri.Fingerprint fp : fingerprints) {
4853 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4854 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4855 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4856 if (fingerprintStatus != null) {
4857 if (!fingerprintStatus.isVerified()) {
4858 performedVerification = true;
4859 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4860 }
4861 } else {
4862 axolotlService.preVerifyFingerprint(contact, fingerprint);
4863 }
4864 }
4865 }
4866 return performedVerification;
4867 }
4868
4869 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4870 final AxolotlService axolotlService = account.getAxolotlService();
4871 boolean verifiedSomething = false;
4872 for (XmppUri.Fingerprint fp : fingerprints) {
4873 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4874 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4875 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4876 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4877 if (fingerprintStatus != null) {
4878 if (!fingerprintStatus.isVerified()) {
4879 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4880 verifiedSomething = true;
4881 }
4882 } else {
4883 axolotlService.preVerifyFingerprint(account, fingerprint);
4884 verifiedSomething = true;
4885 }
4886 }
4887 }
4888 return verifiedSomething;
4889 }
4890
4891 public boolean blindTrustBeforeVerification() {
4892 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4893 }
4894
4895 public ShortcutService getShortcutService() {
4896 return mShortcutService;
4897 }
4898
4899 public void pushMamPreferences(Account account, Element prefs) {
4900 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4901 set.addChild(prefs);
4902 sendIqPacket(account, set, null);
4903 }
4904
4905 public void evictPreview(String uuid) {
4906 if (mBitmapCache.remove(uuid) != null) {
4907 Log.d(Config.LOGTAG, "deleted cached preview");
4908 }
4909 }
4910
4911 public interface OnMamPreferencesFetched {
4912 void onPreferencesFetched(Element prefs);
4913
4914 void onPreferencesFetchFailed();
4915 }
4916
4917 public interface OnAccountCreated {
4918 void onAccountCreated(Account account);
4919
4920 void informUser(int r);
4921 }
4922
4923 public interface OnMoreMessagesLoaded {
4924 void onMoreMessagesLoaded(int count, Conversation conversation);
4925
4926 void informUser(int r);
4927 }
4928
4929 public interface OnAccountPasswordChanged {
4930 void onPasswordChangeSucceeded();
4931
4932 void onPasswordChangeFailed();
4933 }
4934
4935 public interface OnRoomDestroy {
4936 void onRoomDestroySucceeded();
4937
4938 void onRoomDestroyFailed();
4939 }
4940
4941 public interface OnAffiliationChanged {
4942 void onAffiliationChangedSuccessful(Jid jid);
4943
4944 void onAffiliationChangeFailed(Jid jid, int resId);
4945 }
4946
4947 public interface OnConversationUpdate {
4948 void onConversationUpdate();
4949 }
4950
4951 public interface OnJingleRtpConnectionUpdate {
4952 void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
4953
4954 void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
4955 }
4956
4957 public interface OnAccountUpdate {
4958 void onAccountUpdate();
4959 }
4960
4961 public interface OnCaptchaRequested {
4962 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4963 }
4964
4965 public interface OnRosterUpdate {
4966 void onRosterUpdate();
4967 }
4968
4969 public interface OnMucRosterUpdate {
4970 void onMucRosterUpdate();
4971 }
4972
4973 public interface OnConferenceConfigurationFetched {
4974 void onConferenceConfigurationFetched(Conversation conversation);
4975
4976 void onFetchFailed(Conversation conversation, String errorCondition);
4977 }
4978
4979 public interface OnConferenceJoined {
4980 void onConferenceJoined(Conversation conversation);
4981 }
4982
4983 public interface OnConfigurationPushed {
4984 void onPushSucceeded();
4985
4986 void onPushFailed();
4987 }
4988
4989 public interface OnShowErrorToast {
4990 void onShowErrorToast(int resId);
4991 }
4992
4993 public class XmppConnectionBinder extends Binder {
4994 public XmppConnectionService getService() {
4995 return XmppConnectionService.this;
4996 }
4997 }
4998
4999 private class InternalEventReceiver extends BroadcastReceiver {
5000
5001 @Override
5002 public void onReceive(Context context, Intent intent) {
5003 onStartCommand(intent, 0, 0);
5004 }
5005 }
5006
5007 public static class OngoingCall {
5008 public final AbstractJingleConnection.Id id;
5009 public final Set<Media> media;
5010 public final boolean reconnecting;
5011
5012 public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5013 this.id = id;
5014 this.media = media;
5015 this.reconnecting = reconnecting;
5016 }
5017
5018 @Override
5019 public boolean equals(Object o) {
5020 if (this == o) return true;
5021 if (o == null || getClass() != o.getClass()) return false;
5022 OngoingCall that = (OngoingCall) o;
5023 return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
5024 }
5025
5026 @Override
5027 public int hashCode() {
5028 return Objects.hashCode(id, media, reconnecting);
5029 }
5030 }
5031}