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