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