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, 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 boolean isOnboarding() {
1998 return getAccounts().size() == 1 && getAccounts().get(0).getJid().getDomain().equals(Config.ONBOARDING_DOMAIN);
1999 }
2000
2001 public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
2002 final XmppConnection connection = account.getXmppConnection();
2003 final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
2004 if (jid == null) {
2005 callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
2006 return;
2007 }
2008 final IqPacket request = new IqPacket(IqPacket.TYPE.SET);
2009 request.setTo(jid);
2010 final Element command = request.addChild("command", Namespace.COMMANDS);
2011 command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
2012 command.setAttribute("action", "execute");
2013 sendIqPacket(account, request, (a, response) -> {
2014 if (response.getType() == IqPacket.TYPE.RESULT) {
2015 final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
2016 final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
2017 if (x != null) {
2018 final Data data = Data.parse(x);
2019 final String uri = data.getValue("uri");
2020 final String landingUrl = data.getValue("landing-url");
2021 if (uri != null) {
2022 final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
2023 callback.inviteRequested(invite);
2024 return;
2025 }
2026 }
2027 callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
2028 Log.d(Config.LOGTAG, response.toString());
2029 } else if (response.getType() == IqPacket.TYPE.ERROR) {
2030 callback.inviteRequestFailed(IqParser.errorMessage(response));
2031 } else {
2032 callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
2033 }
2034 });
2035
2036 }
2037
2038 public void fetchRosterFromServer(final Account account) {
2039 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
2040 if (!"".equals(account.getRosterVersion())) {
2041 Log.d(Config.LOGTAG, account.getJid().asBareJid()
2042 + ": fetching roster version " + account.getRosterVersion());
2043 } else {
2044 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
2045 }
2046 iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
2047 sendIqPacket(account, iqPacket, mIqParser);
2048 }
2049
2050 public void fetchBookmarks(final Account account) {
2051 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
2052 final Element query = iqPacket.query("jabber:iq:private");
2053 query.addChild("storage", Namespace.BOOKMARKS);
2054 final OnIqPacketReceived callback = (a, response) -> {
2055 if (response.getType() == IqPacket.TYPE.RESULT) {
2056 final Element query1 = response.query();
2057 final Element storage = query1.findChild("storage", "storage:bookmarks");
2058 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
2059 processBookmarksInitial(a, bookmarks, false);
2060 } else {
2061 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
2062 }
2063 };
2064 sendIqPacket(account, iqPacket, callback);
2065 }
2066
2067 public void fetchBookmarks2(final Account account) {
2068 final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
2069 sendIqPacket(account, retrieve, new OnIqPacketReceived() {
2070 @Override
2071 public void onIqPacketReceived(final Account account, final IqPacket response) {
2072 if (response.getType() == IqPacket.TYPE.RESULT) {
2073 final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
2074 final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, account);
2075 processBookmarksInitial(account, bookmarks, true);
2076 }
2077 }
2078 });
2079 }
2080
2081 public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
2082 final Set<Jid> previousBookmarks = account.getBookmarkedJids();
2083 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
2084 for (Bookmark bookmark : bookmarks.values()) {
2085 previousBookmarks.remove(bookmark.getJid().asBareJid());
2086 processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
2087 }
2088 if (pep && synchronizeWithBookmarks) {
2089 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
2090 for (Jid jid : previousBookmarks) {
2091 processDeletedBookmark(account, jid);
2092 }
2093 }
2094 account.setBookmarks(bookmarks);
2095 }
2096
2097 public void processDeletedBookmark(Account account, Jid jid) {
2098 final Conversation conversation = find(account, jid);
2099 if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2100 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
2101 archiveConversation(conversation, false);
2102 }
2103 }
2104
2105 private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
2106 final Account account = bookmark.getAccount();
2107 Conversation conversation = find(bookmark);
2108 if (conversation != null) {
2109 if (conversation.getMode() != Conversation.MODE_MULTI) {
2110 return;
2111 }
2112 bookmark.setConversation(conversation);
2113 if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
2114 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
2115 archiveConversation(conversation, false);
2116 } else {
2117 final MucOptions mucOptions = conversation.getMucOptions();
2118 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
2119 final String current = mucOptions.getActualNick();
2120 final String proposed = mucOptions.getProposedNick();
2121 if (current != null && !current.equals(proposed)) {
2122 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
2123 joinMuc(conversation);
2124 }
2125 }
2126 }
2127 } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
2128 conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
2129 bookmark.setConversation(conversation);
2130 }
2131 }
2132
2133 public void processModifiedBookmark(Bookmark bookmark) {
2134 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
2135 processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
2136 }
2137
2138 public void createBookmark(final Account account, final Bookmark bookmark) {
2139 account.putBookmark(bookmark);
2140 final XmppConnection connection = account.getXmppConnection();
2141 if (connection == null) {
2142 Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
2143 } else if (connection.getFeatures().bookmarks2()) {
2144 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
2145 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
2146 } else if (connection.getFeatures().bookmarksConversion()) {
2147 pushBookmarksPep(account);
2148 } else {
2149 pushBookmarksPrivateXml(account);
2150 }
2151 }
2152
2153 public void deleteBookmark(final Account account, final Bookmark bookmark) {
2154 if (bookmark.getJid().toString().equals("discuss@conference.soprani.ca")) {
2155 getPreferences().edit().putBoolean("cheogram_sopranica_bookmark_deleted", true).apply();
2156 }
2157 account.removeBookmark(bookmark);
2158 final XmppConnection connection = account.getXmppConnection();
2159 if (connection == null) return;
2160
2161 if (connection.getFeatures().bookmarks2()) {
2162 IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
2163 sendIqPacket(account, request, (a, response) -> {
2164 if (response.getType() == IqPacket.TYPE.ERROR) {
2165 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
2166 }
2167 });
2168 } else if (connection.getFeatures().bookmarksConversion()) {
2169 pushBookmarksPep(account);
2170 } else {
2171 pushBookmarksPrivateXml(account);
2172 }
2173 }
2174
2175 private void pushBookmarksPrivateXml(Account account) {
2176 if (!account.areBookmarksLoaded()) return;
2177
2178 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
2179 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2180 Element query = iqPacket.query("jabber:iq:private");
2181 Element storage = query.addChild("storage", "storage:bookmarks");
2182 for (final Bookmark bookmark : account.getBookmarks()) {
2183 storage.addChild(bookmark);
2184 }
2185 sendIqPacket(account, iqPacket, mDefaultIqHandler);
2186 }
2187
2188 private void pushBookmarksPep(Account account) {
2189 if (!account.areBookmarksLoaded()) return;
2190
2191 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
2192 final Element storage = new Element("storage", "storage:bookmarks");
2193 for (final Bookmark bookmark : account.getBookmarks()) {
2194 storage.addChild(bookmark);
2195 }
2196 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
2197
2198 }
2199
2200 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
2201 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2202
2203 }
2204
2205 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
2206 final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
2207 sendIqPacket(account, packet, (a, response) -> {
2208 if (response.getType() == IqPacket.TYPE.RESULT) {
2209 return;
2210 }
2211 if (retry && PublishOptions.preconditionNotMet(response)) {
2212 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
2213 @Override
2214 public void onPushSucceeded() {
2215 pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
2216 }
2217
2218 @Override
2219 public void onPushFailed() {
2220 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
2221 }
2222 });
2223 } else {
2224 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + retry + ") " + response);
2225 }
2226 });
2227 }
2228
2229 private void restoreFromDatabase() {
2230 synchronized (this.conversations) {
2231 final Map<String, Account> accountLookupTable = new Hashtable<>();
2232 for (Account account : this.accounts) {
2233 accountLookupTable.put(account.getUuid(), account);
2234 }
2235 Log.d(Config.LOGTAG, "restoring conversations...");
2236 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2237 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2238 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
2239 Conversation conversation = iterator.next();
2240 Account account = accountLookupTable.get(conversation.getAccountUuid());
2241 if (account != null) {
2242 conversation.setAccount(account);
2243 } else {
2244 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
2245 iterator.remove();
2246 }
2247 }
2248 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2249 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
2250 Runnable runnable = () -> {
2251 if (DatabaseBackend.requiresMessageIndexRebuild()) {
2252 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2253 }
2254 final long deletionDate = getAutomaticMessageDeletionDate();
2255 mLastExpiryRun.set(SystemClock.elapsedRealtime());
2256 if (deletionDate > 0) {
2257 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
2258 databaseBackend.expireOldMessages(deletionDate);
2259 }
2260 Log.d(Config.LOGTAG, "restoring roster...");
2261 for (final Account account : accounts) {
2262 databaseBackend.readRoster(account.getRoster());
2263 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
2264 }
2265 getDrawableCache().evictAll();
2266 loadPhoneContacts();
2267 Log.d(Config.LOGTAG, "restoring messages...");
2268 final long startMessageRestore = SystemClock.elapsedRealtime();
2269 final Conversation quickLoad = QuickLoader.get(this.conversations);
2270 if (quickLoad != null) {
2271 restoreMessages(quickLoad);
2272 updateConversationUi();
2273 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2274 Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
2275 }
2276 for (Conversation conversation : this.conversations) {
2277 if (quickLoad != conversation) {
2278 restoreMessages(conversation);
2279 }
2280 }
2281 mNotificationService.finishBacklog();
2282 restoredFromDatabaseLatch.countDown();
2283 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2284 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2285 updateConversationUi();
2286 };
2287 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2288 }
2289 }
2290
2291 private void restoreMessages(Conversation conversation) {
2292 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2293 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2294 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2295 }
2296
2297 public void loadPhoneContacts() {
2298 mContactMergerExecutor.execute(() -> {
2299 final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2300 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2301 for (final Account account : accounts) {
2302 final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2303 for (final JabberIdContact jidContact : contacts.values()) {
2304 final Contact contact = account.getRoster().getContact(jidContact.getJid());
2305 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2306 if (needsCacheClean) {
2307 getAvatarService().clear(contact);
2308 }
2309 withSystemAccounts.remove(contact);
2310 }
2311 for (final Contact contact : withSystemAccounts) {
2312 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2313 if (needsCacheClean) {
2314 getAvatarService().clear(contact);
2315 }
2316 }
2317 }
2318 Log.d(Config.LOGTAG, "finished merging phone contacts");
2319 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2320 updateRosterUi();
2321 mQuickConversationsService.considerSync();
2322 });
2323 }
2324
2325
2326 public void syncRoster(final Account account) {
2327 mRosterSyncTaskManager.execute(account, () -> {
2328 unregisterPhoneAccounts(account);
2329 databaseBackend.writeRoster(account.getRoster());
2330 try { Thread.sleep(500); } catch (InterruptedException e) { }
2331 });
2332 }
2333
2334 public List<Conversation> getConversations() {
2335 return this.conversations;
2336 }
2337
2338 private void markFileDeleted(final File file) {
2339 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2340 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2341 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2342 return;
2343 }
2344 }
2345 final boolean isInternalFile = fileBackend.isInternalFile(file);
2346 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2347 Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2348 markUuidsAsDeletedFiles(uuids);
2349 }
2350
2351 private void markUuidsAsDeletedFiles(List<String> uuids) {
2352 boolean deleted = false;
2353 for (Conversation conversation : getConversations()) {
2354 deleted |= conversation.markAsDeleted(uuids);
2355 }
2356 for (final String uuid : uuids) {
2357 evictPreview(uuid);
2358 }
2359 if (deleted) {
2360 updateConversationUi();
2361 }
2362 }
2363
2364 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2365 boolean changed = false;
2366 for (Conversation conversation : getConversations()) {
2367 changed |= conversation.markAsChanged(infos);
2368 }
2369 if (changed) {
2370 updateConversationUi();
2371 }
2372 }
2373
2374 public void populateWithOrderedConversations(final List<Conversation> list) {
2375 populateWithOrderedConversations(list, true, true);
2376 }
2377
2378 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2379 populateWithOrderedConversations(list, includeNoFileUpload, true);
2380 }
2381
2382 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2383 final List<String> orderedUuids;
2384 if (sort) {
2385 orderedUuids = null;
2386 } else {
2387 orderedUuids = new ArrayList<>();
2388 for (Conversation conversation : list) {
2389 orderedUuids.add(conversation.getUuid());
2390 }
2391 }
2392 list.clear();
2393 if (includeNoFileUpload) {
2394 list.addAll(getConversations());
2395 } else {
2396 for (Conversation conversation : getConversations()) {
2397 if (conversation.getMode() == Conversation.MODE_SINGLE
2398 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2399 list.add(conversation);
2400 }
2401 }
2402 }
2403 try {
2404 if (orderedUuids != null) {
2405 Collections.sort(list, (a, b) -> {
2406 final int indexA = orderedUuids.indexOf(a.getUuid());
2407 final int indexB = orderedUuids.indexOf(b.getUuid());
2408 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2409 return a.compareTo(b);
2410 }
2411 return indexA - indexB;
2412 });
2413 } else {
2414 Collections.sort(list);
2415 }
2416 } catch (IllegalArgumentException e) {
2417 //ignore
2418 }
2419 }
2420
2421 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2422 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2423 return;
2424 } else if (timestamp == 0) {
2425 return;
2426 }
2427 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2428 final Runnable runnable = () -> {
2429 final Account account = conversation.getAccount();
2430 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2431 if (messages.size() > 0) {
2432 conversation.addAll(0, messages);
2433 callback.onMoreMessagesLoaded(messages.size(), conversation);
2434 } else if (conversation.hasMessagesLeftOnServer()
2435 && account.isOnlineAndConnected()
2436 && conversation.getLastClearHistory().getTimestamp() == 0) {
2437 final boolean mamAvailable;
2438 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2439 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2440 } else {
2441 mamAvailable = conversation.getMucOptions().mamSupport();
2442 }
2443 if (mamAvailable) {
2444 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2445 if (query != null) {
2446 query.setCallback(callback);
2447 callback.informUser(R.string.fetching_history_from_server);
2448 } else {
2449 callback.informUser(R.string.not_fetching_history_retention_period);
2450 }
2451
2452 }
2453 }
2454 };
2455 mDatabaseReaderExecutor.execute(runnable);
2456 }
2457
2458 public List<Account> getAccounts() {
2459 return this.accounts;
2460 }
2461
2462
2463 /**
2464 * 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)
2465 */
2466 public List<Conversation> findAllConferencesWith(Contact contact) {
2467 final ArrayList<Conversation> results = new ArrayList<>();
2468 for (final Conversation c : conversations) {
2469 if (c.getMode() != Conversation.MODE_MULTI) {
2470 continue;
2471 }
2472 final MucOptions mucOptions = c.getMucOptions();
2473 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2474 results.add(c);
2475 }
2476 }
2477 return results;
2478 }
2479
2480 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2481 for (final Conversation conversation : haystack) {
2482 if (conversation.getContact() == contact) {
2483 return conversation;
2484 }
2485 }
2486 return null;
2487 }
2488
2489 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2490 if (jid == null) {
2491 return null;
2492 }
2493 for (final Conversation conversation : haystack) {
2494 if ((account == null || conversation.getAccount() == account)
2495 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2496 return conversation;
2497 }
2498 }
2499 return null;
2500 }
2501
2502 public boolean isConversationsListEmpty(final Conversation ignore) {
2503 synchronized (this.conversations) {
2504 final int size = this.conversations.size();
2505 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2506 }
2507 }
2508
2509 public boolean isConversationStillOpen(final Conversation conversation) {
2510 synchronized (this.conversations) {
2511 for (Conversation current : this.conversations) {
2512 if (current == conversation) {
2513 return true;
2514 }
2515 }
2516 }
2517 return false;
2518 }
2519
2520 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2521 return this.findOrCreateConversation(account, jid, muc, false, async);
2522 }
2523
2524 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2525 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2526 }
2527
2528 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2529 synchronized (this.conversations) {
2530 Conversation conversation = find(account, jid);
2531 if (conversation != null) {
2532 return conversation;
2533 }
2534 conversation = databaseBackend.findConversation(account, jid);
2535 final boolean loadMessagesFromDb;
2536 if (conversation != null) {
2537 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2538 conversation.setAccount(account);
2539 if (muc) {
2540 conversation.setMode(Conversation.MODE_MULTI);
2541 conversation.setContactJid(jid);
2542 } else {
2543 conversation.setMode(Conversation.MODE_SINGLE);
2544 conversation.setContactJid(jid.asBareJid());
2545 }
2546 databaseBackend.updateConversation(conversation);
2547 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2548 } else {
2549 String conversationName;
2550 Contact contact = account.getRoster().getContact(jid);
2551 if (contact != null) {
2552 conversationName = contact.getDisplayName();
2553 } else {
2554 conversationName = jid.getLocal();
2555 }
2556 if (muc) {
2557 conversation = new Conversation(conversationName, account, jid,
2558 Conversation.MODE_MULTI);
2559 } else {
2560 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2561 Conversation.MODE_SINGLE);
2562 }
2563 this.databaseBackend.createConversation(conversation);
2564 loadMessagesFromDb = false;
2565 }
2566 final Conversation c = conversation;
2567 final Runnable runnable = () -> {
2568 if (loadMessagesFromDb) {
2569 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2570 updateConversationUi();
2571 c.messagesLoaded.set(true);
2572 }
2573 if (account.getXmppConnection() != null
2574 && !c.getContact().isBlocked()
2575 && account.getXmppConnection().getFeatures().mam()
2576 && !muc) {
2577 if (query == null) {
2578 mMessageArchiveService.query(c);
2579 } else {
2580 if (query.getConversation() == null) {
2581 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2582 }
2583 }
2584 }
2585 if (joinAfterCreate) {
2586 joinMuc(c);
2587 }
2588 };
2589 if (async) {
2590 mDatabaseReaderExecutor.execute(runnable);
2591 } else {
2592 runnable.run();
2593 }
2594 this.conversations.add(conversation);
2595 updateConversationUi();
2596 return conversation;
2597 }
2598 }
2599
2600 public void archiveConversation(Conversation conversation) {
2601 archiveConversation(conversation, true);
2602 }
2603
2604 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2605 if (isOnboarding()) return;
2606
2607 getNotificationService().clear(conversation);
2608 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2609 conversation.setNextMessage(null);
2610 synchronized (this.conversations) {
2611 getMessageArchiveService().kill(conversation);
2612 if (conversation.getMode() == Conversation.MODE_MULTI) {
2613 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2614 final Bookmark bookmark = conversation.getBookmark();
2615 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2616 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2617 Account account = bookmark.getAccount();
2618 bookmark.setConversation(null);
2619 deleteBookmark(account, bookmark);
2620 } else if (bookmark.autojoin()) {
2621 bookmark.setAutojoin(false);
2622 createBookmark(bookmark.getAccount(), bookmark);
2623 }
2624 }
2625 }
2626 leaveMuc(conversation);
2627 } else {
2628 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2629 stopPresenceUpdatesTo(conversation.getContact());
2630 }
2631 }
2632 updateConversation(conversation);
2633 this.conversations.remove(conversation);
2634 updateConversationUi();
2635 }
2636 }
2637
2638 public void stopPresenceUpdatesTo(Contact contact) {
2639 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2640 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2641 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2642 }
2643
2644 public void createAccount(final Account account) {
2645 account.initAccountServices(this);
2646 databaseBackend.createAccount(account);
2647 this.accounts.add(account);
2648 this.reconnectAccountInBackground(account);
2649 updateAccountUi();
2650 syncEnabledAccountSetting();
2651 toggleForegroundService();
2652 }
2653
2654 private void syncEnabledAccountSetting() {
2655 final boolean hasEnabledAccounts = hasEnabledAccounts();
2656 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2657 toggleSetProfilePictureActivity(hasEnabledAccounts);
2658 }
2659
2660 private void toggleSetProfilePictureActivity(final boolean enabled) {
2661 try {
2662 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2663 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2664 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2665 } catch (IllegalStateException e) {
2666 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
2667 }
2668 }
2669
2670 public boolean reconfigurePushDistributor() {
2671 return this.unifiedPushBroker.reconfigurePushDistributor();
2672 }
2673
2674 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
2675 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
2676 }
2677
2678 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
2679 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
2680 }
2681
2682 private void provisionAccount(final String address, final String password) {
2683 final Jid jid = Jid.ofEscaped(address);
2684 final Account account = new Account(jid, password);
2685 account.setOption(Account.OPTION_DISABLED, true);
2686 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2687 createAccount(account);
2688 }
2689
2690 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2691 new Thread(() -> {
2692 try {
2693 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2694 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2695 if (cert == null) {
2696 callback.informUser(R.string.unable_to_parse_certificate);
2697 return;
2698 }
2699 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2700 if (info == null) {
2701 callback.informUser(R.string.certificate_does_not_contain_jid);
2702 return;
2703 }
2704 if (findAccountByJid(info.first) == null) {
2705 final Account account = new Account(info.first, "");
2706 account.setPrivateKeyAlias(alias);
2707 account.setOption(Account.OPTION_DISABLED, true);
2708 account.setOption(Account.OPTION_FIXED_USERNAME, true);
2709 account.setDisplayName(info.second);
2710 createAccount(account);
2711 callback.onAccountCreated(account);
2712 if (Config.X509_VERIFICATION) {
2713 try {
2714 getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2715 } catch (CertificateException e) {
2716 callback.informUser(R.string.certificate_chain_is_not_trusted);
2717 }
2718 }
2719 } else {
2720 callback.informUser(R.string.account_already_exists);
2721 }
2722 } catch (Exception e) {
2723 callback.informUser(R.string.unable_to_parse_certificate);
2724 }
2725 }).start();
2726
2727 }
2728
2729 public void updateKeyInAccount(final Account account, final String alias) {
2730 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2731 try {
2732 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2733 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2734 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2735 if (info == null) {
2736 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2737 return;
2738 }
2739 if (account.getJid().asBareJid().equals(info.first)) {
2740 account.setPrivateKeyAlias(alias);
2741 account.setDisplayName(info.second);
2742 databaseBackend.updateAccount(account);
2743 if (Config.X509_VERIFICATION) {
2744 try {
2745 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2746 } catch (CertificateException e) {
2747 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2748 }
2749 account.getAxolotlService().regenerateKeys(true);
2750 }
2751 } else {
2752 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2753 }
2754 } catch (Exception e) {
2755 e.printStackTrace();
2756 }
2757 }
2758
2759 public boolean updateAccount(final Account account) {
2760 if (databaseBackend.updateAccount(account)) {
2761 Integer color = account.getColorToSave();
2762 if (color == null) {
2763 getPreferences().edit().remove("account_color:" + account.getUuid()).commit();
2764 } else {
2765 getPreferences().edit().putInt("account_color:" + account.getUuid(), color.intValue()).commit();
2766 }
2767 account.setShowErrorNotification(true);
2768 this.statusListener.onStatusChanged(account);
2769 databaseBackend.updateAccount(account);
2770 reconnectAccountInBackground(account);
2771 updateAccountUi();
2772 getNotificationService().updateErrorNotification();
2773 toggleForegroundService();
2774 syncEnabledAccountSetting();
2775 mChannelDiscoveryService.cleanCache();
2776 return true;
2777 } else {
2778 return false;
2779 }
2780 }
2781
2782 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2783 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2784 sendIqPacket(account, iq, (a, packet) -> {
2785 if (packet.getType() == IqPacket.TYPE.RESULT) {
2786 a.setPassword(newPassword);
2787 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2788 databaseBackend.updateAccount(a);
2789 callback.onPasswordChangeSucceeded();
2790 } else {
2791 callback.onPasswordChangeFailed();
2792 }
2793 });
2794 }
2795
2796 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
2797 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2798 final Element query = iqPacket.addChild("query",Namespace.REGISTER);
2799 query.addChild("remove");
2800 sendIqPacket(account, iqPacket, (a, response) -> {
2801 if (response.getType() == IqPacket.TYPE.RESULT) {
2802 deleteAccount(a);
2803 callback.accept(true);
2804 } else {
2805 callback.accept(false);
2806 }
2807 });
2808 }
2809
2810 public void deleteAccount(final Account account) {
2811 getPreferences().edit().remove("onboarding_continued").commit();
2812 final boolean connected = account.getStatus() == Account.State.ONLINE;
2813 synchronized (this.conversations) {
2814 if (connected) {
2815 account.getAxolotlService().deleteOmemoIdentity();
2816 }
2817 for (final Conversation conversation : conversations) {
2818 if (conversation.getAccount() == account) {
2819 if (conversation.getMode() == Conversation.MODE_MULTI) {
2820 if (connected) {
2821 leaveMuc(conversation);
2822 }
2823 }
2824 conversations.remove(conversation);
2825 mNotificationService.clear(conversation);
2826 }
2827 }
2828 new Thread(() -> {
2829 for (final Contact contact : account.getRoster().getContacts()) {
2830 contact.unregisterAsPhoneAccount(this);
2831 }
2832 }).start();
2833 if (account.getXmppConnection() != null) {
2834 new Thread(() -> disconnect(account, !connected)).start();
2835 }
2836 final Runnable runnable = () -> {
2837 if (!databaseBackend.deleteAccount(account)) {
2838 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2839 }
2840 };
2841 mDatabaseWriterExecutor.execute(runnable);
2842 this.accounts.remove(account);
2843 this.mRosterSyncTaskManager.clear(account);
2844 updateAccountUi();
2845 mNotificationService.updateErrorNotification();
2846 syncEnabledAccountSetting();
2847 toggleForegroundService();
2848 }
2849 }
2850
2851 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2852 final boolean remainingListeners;
2853 synchronized (LISTENER_LOCK) {
2854 remainingListeners = checkListeners();
2855 if (!this.mOnConversationUpdates.add(listener)) {
2856 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2857 }
2858 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2859 }
2860 if (remainingListeners) {
2861 switchToForeground();
2862 }
2863 }
2864
2865 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2866 final boolean remainingListeners;
2867 synchronized (LISTENER_LOCK) {
2868 this.mOnConversationUpdates.remove(listener);
2869 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2870 remainingListeners = checkListeners();
2871 }
2872 if (remainingListeners) {
2873 switchToBackground();
2874 }
2875 }
2876
2877 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2878 final boolean remainingListeners;
2879 synchronized (LISTENER_LOCK) {
2880 remainingListeners = checkListeners();
2881 if (!this.mOnShowErrorToasts.add(listener)) {
2882 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2883 }
2884 }
2885 if (remainingListeners) {
2886 switchToForeground();
2887 }
2888 }
2889
2890 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2891 final boolean remainingListeners;
2892 synchronized (LISTENER_LOCK) {
2893 this.mOnShowErrorToasts.remove(onShowErrorToast);
2894 remainingListeners = checkListeners();
2895 }
2896 if (remainingListeners) {
2897 switchToBackground();
2898 }
2899 }
2900
2901 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2902 final boolean remainingListeners;
2903 synchronized (LISTENER_LOCK) {
2904 remainingListeners = checkListeners();
2905 if (!this.mOnAccountUpdates.add(listener)) {
2906 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2907 }
2908 }
2909 if (remainingListeners) {
2910 switchToForeground();
2911 }
2912 }
2913
2914 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2915 final boolean remainingListeners;
2916 synchronized (LISTENER_LOCK) {
2917 this.mOnAccountUpdates.remove(listener);
2918 remainingListeners = checkListeners();
2919 }
2920 if (remainingListeners) {
2921 switchToBackground();
2922 }
2923 }
2924
2925 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2926 final boolean remainingListeners;
2927 synchronized (LISTENER_LOCK) {
2928 remainingListeners = checkListeners();
2929 if (!this.mOnCaptchaRequested.add(listener)) {
2930 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2931 }
2932 }
2933 if (remainingListeners) {
2934 switchToForeground();
2935 }
2936 }
2937
2938 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2939 final boolean remainingListeners;
2940 synchronized (LISTENER_LOCK) {
2941 this.mOnCaptchaRequested.remove(listener);
2942 remainingListeners = checkListeners();
2943 }
2944 if (remainingListeners) {
2945 switchToBackground();
2946 }
2947 }
2948
2949 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2950 final boolean remainingListeners;
2951 synchronized (LISTENER_LOCK) {
2952 remainingListeners = checkListeners();
2953 if (!this.mOnRosterUpdates.add(listener)) {
2954 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2955 }
2956 }
2957 if (remainingListeners) {
2958 switchToForeground();
2959 }
2960 }
2961
2962 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2963 final boolean remainingListeners;
2964 synchronized (LISTENER_LOCK) {
2965 this.mOnRosterUpdates.remove(listener);
2966 remainingListeners = checkListeners();
2967 }
2968 if (remainingListeners) {
2969 switchToBackground();
2970 }
2971 }
2972
2973 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2974 final boolean remainingListeners;
2975 synchronized (LISTENER_LOCK) {
2976 remainingListeners = checkListeners();
2977 if (!this.mOnUpdateBlocklist.add(listener)) {
2978 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2979 }
2980 }
2981 if (remainingListeners) {
2982 switchToForeground();
2983 }
2984 }
2985
2986 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2987 final boolean remainingListeners;
2988 synchronized (LISTENER_LOCK) {
2989 this.mOnUpdateBlocklist.remove(listener);
2990 remainingListeners = checkListeners();
2991 }
2992 if (remainingListeners) {
2993 switchToBackground();
2994 }
2995 }
2996
2997 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2998 final boolean remainingListeners;
2999 synchronized (LISTENER_LOCK) {
3000 remainingListeners = checkListeners();
3001 if (!this.mOnKeyStatusUpdated.add(listener)) {
3002 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
3003 }
3004 }
3005 if (remainingListeners) {
3006 switchToForeground();
3007 }
3008 }
3009
3010 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
3011 final boolean remainingListeners;
3012 synchronized (LISTENER_LOCK) {
3013 this.mOnKeyStatusUpdated.remove(listener);
3014 remainingListeners = checkListeners();
3015 }
3016 if (remainingListeners) {
3017 switchToBackground();
3018 }
3019 }
3020
3021 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3022 final boolean remainingListeners;
3023 synchronized (LISTENER_LOCK) {
3024 remainingListeners = checkListeners();
3025 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
3026 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
3027 }
3028 }
3029 if (remainingListeners) {
3030 switchToForeground();
3031 }
3032 }
3033
3034 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3035 final boolean remainingListeners;
3036 synchronized (LISTENER_LOCK) {
3037 this.onJingleRtpConnectionUpdate.remove(listener);
3038 remainingListeners = checkListeners();
3039 }
3040 if (remainingListeners) {
3041 switchToBackground();
3042 }
3043 }
3044
3045 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
3046 final boolean remainingListeners;
3047 synchronized (LISTENER_LOCK) {
3048 remainingListeners = checkListeners();
3049 if (!this.mOnMucRosterUpdate.add(listener)) {
3050 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
3051 }
3052 }
3053 if (remainingListeners) {
3054 switchToForeground();
3055 }
3056 }
3057
3058 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
3059 final boolean remainingListeners;
3060 synchronized (LISTENER_LOCK) {
3061 this.mOnMucRosterUpdate.remove(listener);
3062 remainingListeners = checkListeners();
3063 }
3064 if (remainingListeners) {
3065 switchToBackground();
3066 }
3067 }
3068
3069 public boolean checkListeners() {
3070 return (this.mOnAccountUpdates.size() == 0
3071 && this.mOnConversationUpdates.size() == 0
3072 && this.mOnRosterUpdates.size() == 0
3073 && this.mOnCaptchaRequested.size() == 0
3074 && this.mOnMucRosterUpdate.size() == 0
3075 && this.mOnUpdateBlocklist.size() == 0
3076 && this.mOnShowErrorToasts.size() == 0
3077 && this.onJingleRtpConnectionUpdate.size() == 0
3078 && this.mOnKeyStatusUpdated.size() == 0);
3079 }
3080
3081 private void switchToForeground() {
3082 final boolean broadcastLastActivity = broadcastLastActivity();
3083 for (Conversation conversation : getConversations()) {
3084 if (conversation.getMode() == Conversation.MODE_MULTI) {
3085 conversation.getMucOptions().resetChatState();
3086 } else {
3087 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
3088 }
3089 }
3090 for (Account account : getAccounts()) {
3091 if (account.getStatus() == Account.State.ONLINE) {
3092 account.deactivateGracePeriod();
3093 final XmppConnection connection = account.getXmppConnection();
3094 if (connection != null) {
3095 if (connection.getFeatures().csi()) {
3096 connection.sendActive();
3097 }
3098 if (broadcastLastActivity) {
3099 sendPresence(account, false); //send new presence but don't include idle because we are not
3100 }
3101 }
3102 }
3103 }
3104 Log.d(Config.LOGTAG, "app switched into foreground");
3105 }
3106
3107 private void switchToBackground() {
3108 final boolean broadcastLastActivity = broadcastLastActivity();
3109 if (broadcastLastActivity) {
3110 mLastActivity = System.currentTimeMillis();
3111 final SharedPreferences.Editor editor = getPreferences().edit();
3112 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3113 editor.apply();
3114 }
3115 for (Account account : getAccounts()) {
3116 if (account.getStatus() == Account.State.ONLINE) {
3117 XmppConnection connection = account.getXmppConnection();
3118 if (connection != null) {
3119 if (broadcastLastActivity) {
3120 sendPresence(account, true);
3121 }
3122 if (connection.getFeatures().csi()) {
3123 connection.sendInactive();
3124 }
3125 }
3126 }
3127 }
3128 this.mNotificationService.setIsInForeground(false);
3129 Log.d(Config.LOGTAG, "app switched into background");
3130 }
3131
3132 private void connectMultiModeConversations(Account account) {
3133 List<Conversation> conversations = getConversations();
3134 for (Conversation conversation : conversations) {
3135 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
3136 joinMuc(conversation);
3137 }
3138 }
3139 }
3140
3141 public void mucSelfPingAndRejoin(final Conversation conversation) {
3142 final Account account = conversation.getAccount();
3143 synchronized (account.inProgressConferenceJoins) {
3144 if (account.inProgressConferenceJoins.contains(conversation)) {
3145 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
3146 return;
3147 }
3148 }
3149 synchronized (account.inProgressConferencePings) {
3150 if (!account.inProgressConferencePings.add(conversation)) {
3151 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
3152 return;
3153 }
3154 }
3155 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3156 final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
3157 ping.setTo(self);
3158 ping.addChild("ping", Namespace.PING);
3159 sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
3160 if (response.getType() == IqPacket.TYPE.ERROR) {
3161 Element error = response.findChild("error");
3162 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
3163 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
3164 } else {
3165 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
3166 joinMuc(conversation);
3167 }
3168 } else if (response.getType() == IqPacket.TYPE.RESULT) {
3169 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
3170 }
3171 synchronized (account.inProgressConferencePings) {
3172 account.inProgressConferencePings.remove(conversation);
3173 }
3174 });
3175 }
3176 public void joinMuc(Conversation conversation) {
3177 joinMuc(conversation, null, false);
3178 }
3179
3180 public void joinMuc(Conversation conversation, boolean followedInvite) {
3181 joinMuc(conversation, null, followedInvite);
3182 }
3183
3184 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3185 joinMuc(conversation, onConferenceJoined, false);
3186 }
3187
3188 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
3189 final Account account = conversation.getAccount();
3190 synchronized (account.pendingConferenceJoins) {
3191 account.pendingConferenceJoins.remove(conversation);
3192 }
3193 synchronized (account.pendingConferenceLeaves) {
3194 account.pendingConferenceLeaves.remove(conversation);
3195 }
3196 if (account.getStatus() == Account.State.ONLINE) {
3197 synchronized (account.inProgressConferenceJoins) {
3198 account.inProgressConferenceJoins.add(conversation);
3199 }
3200 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3201 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3202 }
3203 conversation.resetMucOptions();
3204 if (onConferenceJoined != null) {
3205 conversation.getMucOptions().flagNoAutoPushConfiguration();
3206 }
3207 conversation.setHasMessagesLeftOnServer(false);
3208 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
3209
3210 private void join(Conversation conversation) {
3211 Account account = conversation.getAccount();
3212 final MucOptions mucOptions = conversation.getMucOptions();
3213
3214 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
3215 synchronized (account.inProgressConferenceJoins) {
3216 account.inProgressConferenceJoins.remove(conversation);
3217 }
3218 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3219 updateConversationUi();
3220 if (onConferenceJoined != null) {
3221 onConferenceJoined.onConferenceJoined(conversation);
3222 }
3223 return;
3224 }
3225
3226 final Jid joinJid = mucOptions.getSelf().getFullJid();
3227 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
3228 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null, mucOptions.getSelf().getNick());
3229 packet.setTo(joinJid);
3230 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3231 if (conversation.getMucOptions().getPassword() != null) {
3232 x.addChild("password").setContent(mucOptions.getPassword());
3233 }
3234
3235 if (mucOptions.mamSupport()) {
3236 // Use MAM instead of the limited muc history to get history
3237 x.addChild("history").setAttribute("maxchars", "0");
3238 } else {
3239 // Fallback to muc history
3240 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
3241 }
3242 sendPresencePacket(account, packet);
3243 if (onConferenceJoined != null) {
3244 onConferenceJoined.onConferenceJoined(conversation);
3245 }
3246 if (!joinJid.equals(conversation.getJid())) {
3247 conversation.setContactJid(joinJid);
3248 databaseBackend.updateConversation(conversation);
3249 }
3250
3251 if (mucOptions.mamSupport()) {
3252 getMessageArchiveService().catchupMUC(conversation);
3253 }
3254 if (mucOptions.isPrivateAndNonAnonymous()) {
3255 fetchConferenceMembers(conversation);
3256
3257 if (followedInvite) {
3258 final Bookmark bookmark = conversation.getBookmark();
3259 if (bookmark != null) {
3260 if (!bookmark.autojoin()) {
3261 bookmark.setAutojoin(true);
3262 createBookmark(account, bookmark);
3263 }
3264 } else {
3265 saveConversationAsBookmark(conversation, null);
3266 }
3267 }
3268 }
3269 synchronized (account.inProgressConferenceJoins) {
3270 account.inProgressConferenceJoins.remove(conversation);
3271 sendUnsentMessages(conversation);
3272 }
3273 }
3274
3275 @Override
3276 public void onConferenceConfigurationFetched(Conversation conversation) {
3277 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3278 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3279 return;
3280 }
3281 join(conversation);
3282 }
3283
3284 @Override
3285 public void onFetchFailed(final Conversation conversation, final String errorCondition) {
3286 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3287 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3288 return;
3289 }
3290 if ("remote-server-not-found".equals(errorCondition)) {
3291 synchronized (account.inProgressConferenceJoins) {
3292 account.inProgressConferenceJoins.remove(conversation);
3293 }
3294 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
3295 updateConversationUi();
3296 } else {
3297 join(conversation);
3298 fetchConferenceConfiguration(conversation);
3299 }
3300 }
3301 });
3302 updateConversationUi();
3303 } else {
3304 synchronized (account.pendingConferenceJoins) {
3305 account.pendingConferenceJoins.add(conversation);
3306 }
3307 conversation.resetMucOptions();
3308 conversation.setHasMessagesLeftOnServer(false);
3309 updateConversationUi();
3310 }
3311 }
3312
3313 private void fetchConferenceMembers(final Conversation conversation) {
3314 final Account account = conversation.getAccount();
3315 final AxolotlService axolotlService = account.getAxolotlService();
3316 final String[] affiliations = {"member", "admin", "owner"};
3317 OnIqPacketReceived callback = new OnIqPacketReceived() {
3318
3319 private int i = 0;
3320 private boolean success = true;
3321
3322 @Override
3323 public void onIqPacketReceived(Account account, IqPacket packet) {
3324 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3325 Element query = packet.query("http://jabber.org/protocol/muc#admin");
3326 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
3327 for (Element child : query.getChildren()) {
3328 if ("item".equals(child.getName())) {
3329 MucOptions.User user = AbstractParser.parseItem(conversation, child);
3330 if (!user.realJidMatchesAccount()) {
3331 boolean isNew = conversation.getMucOptions().updateUser(user);
3332 Contact contact = user.getContact();
3333 if (omemoEnabled
3334 && isNew
3335 && user.getRealJid() != null
3336 && (contact == null || !contact.mutualPresenceSubscription())
3337 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3338 axolotlService.fetchDeviceIds(user.getRealJid());
3339 }
3340 }
3341 }
3342 }
3343 } else {
3344 success = false;
3345 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
3346 }
3347 ++i;
3348 if (i >= affiliations.length) {
3349 List<Jid> members = conversation.getMucOptions().getMembers(true);
3350 if (success) {
3351 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3352 boolean changed = false;
3353 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3354 Jid jid = iterator.next();
3355 if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3356 iterator.remove();
3357 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3358 changed = true;
3359 }
3360 }
3361 if (changed) {
3362 conversation.setAcceptedCryptoTargets(cryptoTargets);
3363 updateConversation(conversation);
3364 }
3365 }
3366 getAvatarService().clear(conversation);
3367 updateMucRosterUi();
3368 updateConversationUi();
3369 }
3370 }
3371 };
3372 for (String affiliation : affiliations) {
3373 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3374 }
3375 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3376 }
3377
3378 public void providePasswordForMuc(Conversation conversation, String password) {
3379 if (conversation.getMode() == Conversation.MODE_MULTI) {
3380 conversation.getMucOptions().setPassword(password);
3381 if (conversation.getBookmark() != null) {
3382 final Bookmark bookmark = conversation.getBookmark();
3383 if (synchronizeWithBookmarks()) {
3384 bookmark.setAutojoin(true);
3385 }
3386 createBookmark(conversation.getAccount(), bookmark);
3387 }
3388 updateConversation(conversation);
3389 joinMuc(conversation);
3390 }
3391 }
3392
3393 public void deleteAvatar(final Account account) {
3394 final AtomicBoolean executed = new AtomicBoolean(false);
3395 final Runnable onDeleted =
3396 () -> {
3397 if (executed.compareAndSet(false, true)) {
3398 account.setAvatar(null);
3399 databaseBackend.updateAccount(account);
3400 getAvatarService().clear(account);
3401 updateAccountUi();
3402 }
3403 };
3404 deleteVcardAvatar(account, onDeleted);
3405 deletePepNode(account, Namespace.AVATAR_DATA);
3406 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3407 }
3408
3409 public void deletePepNode(final Account account, final String node) {
3410 deletePepNode(account, node, null);
3411 }
3412
3413 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3414 final IqPacket request = mIqGenerator.deleteNode(node);
3415 sendIqPacket(account, request, (a, packet) -> {
3416 if (packet.getType() == IqPacket.TYPE.RESULT) {
3417 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": successfully deleted pep node "+node);
3418 if (runnable != null) {
3419 runnable.run();
3420 }
3421 } else {
3422 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": failed to delete "+ packet);
3423 }
3424 });
3425 }
3426
3427 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3428 final IqPacket retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3429 sendIqPacket(account, retrieveVcard, (a, response) -> {
3430 if (response.getType() != IqPacket.TYPE.RESULT) {
3431 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3432 return;
3433 }
3434 final Element vcard = response.findChild("vCard", "vcard-temp");
3435 if (vcard == null) {
3436 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3437 return;
3438 }
3439 Element photo = vcard.findChild("PHOTO");
3440 if (photo == null) {
3441 photo = vcard.addChild("PHOTO");
3442 }
3443 photo.clearChildren();
3444 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3445 publication.setTo(a.getJid().asBareJid());
3446 publication.addChild(vcard);
3447 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3448 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3449 Log.d(Config.LOGTAG,a1.getJid().asBareJid()+": successfully deleted vcard avatar");
3450 runnable.run();
3451 } else {
3452 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3453 }
3454 });
3455 });
3456 }
3457
3458 private boolean hasEnabledAccounts() {
3459 if (this.accounts == null) {
3460 return false;
3461 }
3462 for (Account account : this.accounts) {
3463 if (account.isEnabled()) {
3464 return true;
3465 }
3466 }
3467 return false;
3468 }
3469
3470
3471 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3472 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3473 }
3474
3475 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3476 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3477 }
3478
3479
3480 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3481 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3482 }
3483
3484 public void persistSelfNick(MucOptions.User self) {
3485 final Conversation conversation = self.getConversation();
3486 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3487 Jid full = self.getFullJid();
3488 if (!full.equals(conversation.getJid())) {
3489 Log.d(Config.LOGTAG, "nick changed. updating");
3490 conversation.setContactJid(full);
3491 databaseBackend.updateConversation(conversation);
3492 }
3493
3494 final String nick = self.getNick();
3495 final Bookmark bookmark = conversation.getBookmark();
3496 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3497 if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !nick.equals(bookmarkedNick)) {
3498 final Account account = conversation.getAccount();
3499 final String defaultNick = MucOptions.defaultNick(account);
3500 if (TextUtils.isEmpty(bookmarkedNick) && nick.equals(defaultNick)) {
3501 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
3502 return;
3503 }
3504 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + nick + "' into bookmark for " + conversation.getJid().asBareJid());
3505 bookmark.setNick(nick);
3506 createBookmark(bookmark.getAccount(), bookmark);
3507 }
3508 }
3509
3510 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3511 final MucOptions options = conversation.getMucOptions();
3512 final Jid joinJid = options.createJoinJid(nick);
3513 if (joinJid == null) {
3514 return false;
3515 }
3516 if (options.online()) {
3517 Account account = conversation.getAccount();
3518 options.setOnRenameListener(new OnRenameListener() {
3519
3520 @Override
3521 public void onSuccess() {
3522 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3523 packet.setTo(joinJid);
3524 sendPresencePacket(account, packet);
3525 callback.success(conversation);
3526 }
3527
3528 @Override
3529 public void onFailure() {
3530 callback.error(R.string.nick_in_use, conversation);
3531 }
3532 });
3533
3534 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3535 packet.setTo(joinJid);
3536 sendPresencePacket(account, packet);
3537 } else {
3538 conversation.setContactJid(joinJid);
3539 databaseBackend.updateConversation(conversation);
3540 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3541 Bookmark bookmark = conversation.getBookmark();
3542 if (bookmark != null) {
3543 bookmark.setNick(nick);
3544 createBookmark(bookmark.getAccount(), bookmark);
3545 }
3546 joinMuc(conversation);
3547 }
3548 }
3549 return true;
3550 }
3551
3552 public void leaveMuc(Conversation conversation) {
3553 leaveMuc(conversation, false);
3554 }
3555
3556 private void leaveMuc(Conversation conversation, boolean now) {
3557 final Account account = conversation.getAccount();
3558 synchronized (account.pendingConferenceJoins) {
3559 account.pendingConferenceJoins.remove(conversation);
3560 }
3561 synchronized (account.pendingConferenceLeaves) {
3562 account.pendingConferenceLeaves.remove(conversation);
3563 }
3564 if (account.getStatus() == Account.State.ONLINE || now) {
3565 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3566 conversation.getMucOptions().setOffline();
3567 Bookmark bookmark = conversation.getBookmark();
3568 if (bookmark != null) {
3569 bookmark.setConversation(null);
3570 }
3571 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3572 } else {
3573 synchronized (account.pendingConferenceLeaves) {
3574 account.pendingConferenceLeaves.add(conversation);
3575 }
3576 }
3577 }
3578
3579 public String findConferenceServer(final Account account) {
3580 String server;
3581 if (account.getXmppConnection() != null) {
3582 server = account.getXmppConnection().getMucServer();
3583 if (server != null) {
3584 return server;
3585 }
3586 }
3587 for (Account other : getAccounts()) {
3588 if (other != account && other.getXmppConnection() != null) {
3589 server = other.getXmppConnection().getMucServer();
3590 if (server != null) {
3591 return server;
3592 }
3593 }
3594 }
3595 return null;
3596 }
3597
3598
3599 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3600 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3601 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3602 if (!TextUtils.isEmpty(name)) {
3603 configuration.putString("muc#roomconfig_roomname", name);
3604 }
3605 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3606 @Override
3607 public void onPushSucceeded() {
3608 saveConversationAsBookmark(conversation, name);
3609 callback.success(conversation);
3610 }
3611
3612 @Override
3613 public void onPushFailed() {
3614 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3615 callback.error(R.string.unable_to_set_channel_configuration, conversation);
3616 } else {
3617 callback.error(R.string.joined_an_existing_channel, conversation);
3618 }
3619 }
3620 });
3621 });
3622 }
3623
3624 public boolean createAdhocConference(final Account account,
3625 final String name,
3626 final Iterable<Jid> jids,
3627 final UiCallback<Conversation> callback) {
3628 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3629 if (account.getStatus() == Account.State.ONLINE) {
3630 try {
3631 String server = findConferenceServer(account);
3632 if (server == null) {
3633 if (callback != null) {
3634 callback.error(R.string.no_conference_server_found, null);
3635 }
3636 return false;
3637 }
3638 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
3639 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3640 joinMuc(conversation, new OnConferenceJoined() {
3641 @Override
3642 public void onConferenceJoined(final Conversation conversation) {
3643 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3644 if (!TextUtils.isEmpty(name)) {
3645 configuration.putString("muc#roomconfig_roomname", name);
3646 }
3647 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3648 @Override
3649 public void onPushSucceeded() {
3650 for (Jid invite : jids) {
3651 invite(conversation, invite);
3652 }
3653 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3654 if (resource == null || "".equals(resource)) continue;
3655 Jid other = account.getJid().withResource(resource);
3656 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3657 directInvite(conversation, other);
3658 }
3659 saveConversationAsBookmark(conversation, name);
3660 if (callback != null) {
3661 callback.success(conversation);
3662 }
3663 }
3664
3665 @Override
3666 public void onPushFailed() {
3667 archiveConversation(conversation);
3668 if (callback != null) {
3669 callback.error(R.string.conference_creation_failed, conversation);
3670 }
3671 }
3672 });
3673 }
3674 });
3675 return true;
3676 } catch (IllegalArgumentException e) {
3677 if (callback != null) {
3678 callback.error(R.string.conference_creation_failed, null);
3679 }
3680 return false;
3681 }
3682 } else {
3683 if (callback != null) {
3684 callback.error(R.string.not_connected_try_again, null);
3685 }
3686 return false;
3687 }
3688 }
3689
3690 public void checkIfMuc(final Account account, final Jid jid, Consumer<Boolean> cb) {
3691 if (jid.isDomainJid()) {
3692 // Spec basically says MUC needs to have a node
3693 // And also specifies that MUC and MUC service should have the same identity...
3694 cb.accept(false);
3695 return;
3696 }
3697
3698 IqPacket request = mIqGenerator.queryDiscoInfo(jid.asBareJid());
3699 sendIqPacket(account, request, (acct, reply) -> {
3700 ServiceDiscoveryResult result = new ServiceDiscoveryResult(reply);
3701 cb.accept(
3702 result.getFeatures().contains("http://jabber.org/protocol/muc") &&
3703 result.hasIdentity("conference", null)
3704 );
3705 });
3706 }
3707
3708 public void fetchConferenceConfiguration(final Conversation conversation) {
3709 fetchConferenceConfiguration(conversation, null);
3710 }
3711
3712 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3713 IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3714 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3715 @Override
3716 public void onIqPacketReceived(Account account, IqPacket packet) {
3717 if (packet.getType() == IqPacket.TYPE.RESULT) {
3718 final MucOptions mucOptions = conversation.getMucOptions();
3719 final Bookmark bookmark = conversation.getBookmark();
3720 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3721
3722 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3723 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3724 updateConversation(conversation);
3725 }
3726
3727 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3728 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3729 createBookmark(account, bookmark);
3730 }
3731 }
3732
3733
3734 if (callback != null) {
3735 callback.onConferenceConfigurationFetched(conversation);
3736 }
3737
3738
3739 updateConversationUi();
3740 } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3741 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3742 } else {
3743 if (callback != null) {
3744 callback.onFetchFailed(conversation, packet.getErrorCondition());
3745 }
3746 }
3747 }
3748 });
3749 }
3750
3751 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3752 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3753 }
3754
3755 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3756 Log.d(Config.LOGTAG, "pushing node configuration");
3757 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3758 @Override
3759 public void onIqPacketReceived(Account account, IqPacket packet) {
3760 if (packet.getType() == IqPacket.TYPE.RESULT) {
3761 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3762 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3763 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3764 if (x != null) {
3765 Data data = Data.parse(x);
3766 data.submit(options);
3767 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3768 @Override
3769 public void onIqPacketReceived(Account account, IqPacket packet) {
3770 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3771 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3772 callback.onPushSucceeded();
3773 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3774 callback.onPushFailed();
3775 }
3776 }
3777 });
3778 } else if (callback != null) {
3779 callback.onPushFailed();
3780 }
3781 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3782 callback.onPushFailed();
3783 }
3784 }
3785 });
3786 }
3787
3788 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3789 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3790 conversation.setAttribute("accept_non_anonymous", true);
3791 updateConversation(conversation);
3792 }
3793 if (options.containsKey("muc#roomconfig_moderatedroom")) {
3794 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3795 options.putString("members_by_default", moderated ? "0" : "1");
3796 }
3797 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3798 request.setTo(conversation.getJid().asBareJid());
3799 request.query("http://jabber.org/protocol/muc#owner");
3800 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3801 @Override
3802 public void onIqPacketReceived(Account account, IqPacket packet) {
3803 if (packet.getType() == IqPacket.TYPE.RESULT) {
3804 final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3805 data.submit(options);
3806 final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3807 set.setTo(conversation.getJid().asBareJid());
3808 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3809 sendIqPacket(account, set, new OnIqPacketReceived() {
3810 @Override
3811 public void onIqPacketReceived(Account account, IqPacket packet) {
3812 if (callback != null) {
3813 if (packet.getType() == IqPacket.TYPE.RESULT) {
3814 callback.onPushSucceeded();
3815 } else {
3816 callback.onPushFailed();
3817 }
3818 }
3819 }
3820 });
3821 } else {
3822 if (callback != null) {
3823 callback.onPushFailed();
3824 }
3825 }
3826 }
3827 });
3828 }
3829
3830 public void pushSubjectToConference(final Conversation conference, final String subject) {
3831 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3832 this.sendMessagePacket(conference.getAccount(), packet);
3833 }
3834
3835 public void requestVoice(final Account account, final Jid jid) {
3836 MessagePacket packet = this.getMessageGenerator().requestVoice(jid);
3837 this.sendMessagePacket(account, packet);
3838 }
3839
3840 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3841 final Jid jid = user.asBareJid();
3842 final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3843 sendIqPacket(conference.getAccount(), request, (account, response) -> {
3844 if (response.getType() == IqPacket.TYPE.RESULT) {
3845 conference.getMucOptions().changeAffiliation(jid, affiliation);
3846 getAvatarService().clear(conference);
3847 if (callback != null) {
3848 callback.onAffiliationChangedSuccessful(jid);
3849 } else {
3850 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3851 }
3852 } else if (callback != null) {
3853 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3854 } else {
3855 Log.d(Config.LOGTAG, "unable to change affiliation");
3856 }
3857 });
3858 }
3859
3860 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3861 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3862 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3863 if (packet.getType() != IqPacket.TYPE.RESULT) {
3864 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3865 }
3866 });
3867 }
3868
3869 public void moderateMessage(final Account account, final Message m, final String reason) {
3870 IqPacket request = this.mIqGenerator.moderateMessage(account, m, reason);
3871 sendIqPacket(account, request, (a, packet) -> {
3872 if (packet.getType() != IqPacket.TYPE.RESULT) {
3873 showErrorToastInUi(R.string.unable_to_moderate);
3874 Log.d(Config.LOGTAG, a.getJid().asBareJid() + " unable to moderate: " + packet);
3875 }
3876 });
3877 }
3878
3879 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3880 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3881 request.setTo(conversation.getJid().asBareJid());
3882 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3883 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3884 @Override
3885 public void onIqPacketReceived(Account account, IqPacket packet) {
3886 if (packet.getType() == IqPacket.TYPE.RESULT) {
3887 if (callback != null) {
3888 callback.onRoomDestroySucceeded();
3889 }
3890 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3891 if (callback != null) {
3892 callback.onRoomDestroyFailed();
3893 }
3894 }
3895 }
3896 });
3897 }
3898
3899 private void disconnect(Account account, boolean force) {
3900 if ((account.getStatus() == Account.State.ONLINE)
3901 || (account.getStatus() == Account.State.DISABLED)) {
3902 final XmppConnection connection = account.getXmppConnection();
3903 if (!force) {
3904 List<Conversation> conversations = getConversations();
3905 for (Conversation conversation : conversations) {
3906 if (conversation.getAccount() == account) {
3907 if (conversation.getMode() == Conversation.MODE_MULTI) {
3908 leaveMuc(conversation, true);
3909 }
3910 }
3911 }
3912 sendOfflinePresence(account);
3913 }
3914 connection.disconnect(force);
3915 }
3916 }
3917
3918 @Override
3919 public IBinder onBind(Intent intent) {
3920 return mBinder;
3921 }
3922
3923 public void updateMessage(Message message) {
3924 updateMessage(message, true);
3925 }
3926
3927 public void updateMessage(Message message, boolean includeBody) {
3928 databaseBackend.updateMessage(message, includeBody);
3929 updateConversationUi();
3930 }
3931
3932 public void createMessageAsync(final Message message) {
3933 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3934 }
3935
3936 public void updateMessage(Message message, String uuid) {
3937 if (!databaseBackend.updateMessage(message, uuid)) {
3938 Log.e(Config.LOGTAG, "error updated message in DB after edit");
3939 }
3940 updateConversationUi();
3941 }
3942
3943 protected void syncDirtyContacts(Account account) {
3944 for (Contact contact : account.getRoster().getContacts()) {
3945 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3946 pushContactToServer(contact);
3947 }
3948 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3949 deleteContactOnServer(contact);
3950 }
3951 }
3952 }
3953
3954 protected void unregisterPhoneAccounts(final Account account) {
3955 for (final Contact contact : account.getRoster().getContacts()) {
3956 if (!contact.showInRoster()) {
3957 contact.unregisterAsPhoneAccount(this);
3958 }
3959 }
3960 }
3961
3962 public void createContact(final Contact contact, final boolean autoGrant) {
3963 createContact(contact, autoGrant, null);
3964 }
3965
3966 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3967 if (autoGrant) {
3968 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3969 contact.setOption(Contact.Options.ASKING);
3970 }
3971 pushContactToServer(contact, preAuth);
3972 }
3973
3974 public void pushContactToServer(final Contact contact) {
3975 pushContactToServer(contact, null);
3976 }
3977
3978 private void pushContactToServer(final Contact contact, final String preAuth) {
3979 contact.resetOption(Contact.Options.DIRTY_DELETE);
3980 contact.setOption(Contact.Options.DIRTY_PUSH);
3981 final Account account = contact.getAccount();
3982 if (account.getStatus() == Account.State.ONLINE) {
3983 final boolean ask = contact.getOption(Contact.Options.ASKING);
3984 final boolean sendUpdates = contact
3985 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3986 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3987 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3988 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3989 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3990 if (sendUpdates) {
3991 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3992 }
3993 if (ask) {
3994 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3995 }
3996 } else {
3997 syncRoster(contact.getAccount());
3998 }
3999 }
4000
4001 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4002 new Thread(() -> {
4003 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4004 final int size = Config.AVATAR_SIZE;
4005 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4006 if (avatar != null) {
4007 if (!getFileBackend().save(avatar)) {
4008 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4009 return;
4010 }
4011 avatar.owner = conversation.getJid().asBareJid();
4012 publishMucAvatar(conversation, avatar, callback);
4013 } else {
4014 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4015 }
4016 }).start();
4017 }
4018
4019 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
4020 new Thread(() -> {
4021 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4022 final int size = Config.AVATAR_SIZE;
4023 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4024 if (avatar != null) {
4025 if (!getFileBackend().save(avatar)) {
4026 Log.d(Config.LOGTAG, "unable to save vcard");
4027 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4028 return;
4029 }
4030 publishAvatar(account, avatar, callback);
4031 } else {
4032 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4033 }
4034 }).start();
4035
4036 }
4037
4038 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4039 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4040 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
4041 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
4042 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
4043 Element vcard = response.findChild("vCard", "vcard-temp");
4044 if (vcard == null) {
4045 vcard = new Element("vCard", "vcard-temp");
4046 }
4047 Element photo = vcard.findChild("PHOTO");
4048 if (photo == null) {
4049 photo = vcard.addChild("PHOTO");
4050 }
4051 photo.clearChildren();
4052 photo.addChild("TYPE").setContent(avatar.type);
4053 photo.addChild("BINVAL").setContent(avatar.image);
4054 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
4055 publication.setTo(conversation.getJid().asBareJid());
4056 publication.addChild(vcard);
4057 sendIqPacket(account, publication, (a1, publicationResponse) -> {
4058 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
4059 callback.onAvatarPublicationSucceeded();
4060 } else {
4061 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
4062 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4063 }
4064 });
4065 } else {
4066 Log.d(Config.LOGTAG, "failed to request vcard " + response);
4067 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
4068 }
4069 });
4070 }
4071
4072 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
4073 final Bundle options;
4074 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4075 options = PublishOptions.openAccess();
4076 } else {
4077 options = null;
4078 }
4079 publishAvatar(account, avatar, options, true, callback);
4080 }
4081
4082 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4083 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4084 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
4085 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4086
4087 @Override
4088 public void onIqPacketReceived(Account account, IqPacket result) {
4089 if (result.getType() == IqPacket.TYPE.RESULT) {
4090 publishAvatarMetadata(account, avatar, options, true, callback);
4091 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4092 pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
4093 @Override
4094 public void onPushSucceeded() {
4095 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
4096 publishAvatar(account, avatar, options, false, callback);
4097 }
4098
4099 @Override
4100 public void onPushFailed() {
4101 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
4102 publishAvatar(account, avatar, null, false, callback);
4103 }
4104 });
4105 } else {
4106 Element error = result.findChild("error");
4107 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
4108 if (callback != null) {
4109 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4110 }
4111 }
4112 }
4113 });
4114 }
4115
4116 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4117 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4118 sendIqPacket(account, packet, new OnIqPacketReceived() {
4119 @Override
4120 public void onIqPacketReceived(Account account, IqPacket result) {
4121 if (result.getType() == IqPacket.TYPE.RESULT) {
4122 if (account.setAvatar(avatar.getFilename())) {
4123 getAvatarService().clear(account);
4124 databaseBackend.updateAccount(account);
4125 notifyAccountAvatarHasChanged(account);
4126 }
4127 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
4128 if (callback != null) {
4129 callback.onAvatarPublicationSucceeded();
4130 }
4131 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4132 pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
4133 @Override
4134 public void onPushSucceeded() {
4135 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
4136 publishAvatarMetadata(account, avatar, options, false, callback);
4137 }
4138
4139 @Override
4140 public void onPushFailed() {
4141 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
4142 publishAvatarMetadata(account, avatar, null, false, callback);
4143 }
4144 });
4145 } else {
4146 if (callback != null) {
4147 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4148 }
4149 }
4150 }
4151 });
4152 }
4153
4154 public void republishAvatarIfNeeded(Account account) {
4155 if (account.getAxolotlService().isPepBroken()) {
4156 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
4157 return;
4158 }
4159 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4160 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4161
4162 private Avatar parseAvatar(IqPacket packet) {
4163 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4164 if (pubsub != null) {
4165 Element items = pubsub.findChild("items");
4166 if (items != null) {
4167 return Avatar.parseMetadata(items);
4168 }
4169 }
4170 return null;
4171 }
4172
4173 private boolean errorIsItemNotFound(IqPacket packet) {
4174 Element error = packet.findChild("error");
4175 return packet.getType() == IqPacket.TYPE.ERROR
4176 && error != null
4177 && error.hasChild("item-not-found");
4178 }
4179
4180 @Override
4181 public void onIqPacketReceived(Account account, IqPacket packet) {
4182 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
4183 Avatar serverAvatar = parseAvatar(packet);
4184 if (serverAvatar == null && account.getAvatar() != null) {
4185 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4186 if (avatar != null) {
4187 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
4188 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
4189 } else {
4190 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
4191 }
4192 }
4193 }
4194 }
4195 });
4196 }
4197
4198 public void fetchAvatar(Account account, Avatar avatar) {
4199 fetchAvatar(account, avatar, null);
4200 }
4201
4202 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4203 if (databaseBackend.isBlockedMedia(avatar.cid())) {
4204 if (callback != null) callback.error(0, null);
4205 return;
4206 }
4207
4208 final String KEY = generateFetchKey(account, avatar);
4209 synchronized (this.mInProgressAvatarFetches) {
4210 if (mInProgressAvatarFetches.add(KEY)) {
4211 switch (avatar.origin) {
4212 case PEP:
4213 this.mInProgressAvatarFetches.add(KEY);
4214 fetchAvatarPep(account, avatar, callback);
4215 break;
4216 case VCARD:
4217 this.mInProgressAvatarFetches.add(KEY);
4218 fetchAvatarVcard(account, avatar, callback);
4219 break;
4220 }
4221 } else if (avatar.origin == Avatar.Origin.PEP) {
4222 mOmittedPepAvatarFetches.add(KEY);
4223 } else {
4224 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
4225 }
4226 }
4227 }
4228
4229 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4230 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
4231 sendIqPacket(account, packet, (a, result) -> {
4232 synchronized (mInProgressAvatarFetches) {
4233 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
4234 }
4235 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
4236 if (result.getType() == IqPacket.TYPE.RESULT) {
4237 avatar.image = mIqParser.avatarData(result);
4238 if (avatar.image != null) {
4239 if (getFileBackend().save(avatar)) {
4240 if (a.getJid().asBareJid().equals(avatar.owner)) {
4241 if (a.setAvatar(avatar.getFilename())) {
4242 databaseBackend.updateAccount(a);
4243 }
4244 getAvatarService().clear(a);
4245 updateConversationUi();
4246 updateAccountUi();
4247 } else {
4248 final Contact contact = a.getRoster().getContact(avatar.owner);
4249 contact.setAvatar(avatar);
4250 syncRoster(account);
4251 getAvatarService().clear(contact);
4252 updateConversationUi();
4253 updateRosterUi();
4254 }
4255 if (callback != null) {
4256 callback.success(avatar);
4257 }
4258 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
4259 return;
4260 }
4261 } else {
4262
4263 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4264 }
4265 } else {
4266 Element error = result.findChild("error");
4267 if (error == null) {
4268 Log.d(Config.LOGTAG, ERROR + "(server error)");
4269 } else {
4270 Log.d(Config.LOGTAG, ERROR + error.toString());
4271 }
4272 }
4273 if (callback != null) {
4274 callback.error(0, null);
4275 }
4276
4277 });
4278 }
4279
4280 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4281 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4282 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4283 @Override
4284 public void onIqPacketReceived(Account account, IqPacket packet) {
4285 final boolean previouslyOmittedPepFetch;
4286 synchronized (mInProgressAvatarFetches) {
4287 final String KEY = generateFetchKey(account, avatar);
4288 mInProgressAvatarFetches.remove(KEY);
4289 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4290 }
4291 if (packet.getType() == IqPacket.TYPE.RESULT) {
4292 Element vCard = packet.findChild("vCard", "vcard-temp");
4293 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4294 String image = photo != null ? photo.findChildContent("BINVAL") : null;
4295 if (image != null) {
4296 avatar.image = image;
4297 if (getFileBackend().save(avatar)) {
4298 Log.d(Config.LOGTAG, account.getJid().asBareJid()
4299 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4300 if (avatar.owner.isBareJid()) {
4301 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4302 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4303 account.setAvatar(avatar.getFilename());
4304 databaseBackend.updateAccount(account);
4305 getAvatarService().clear(account);
4306 updateAccountUi();
4307 } else {
4308 final Contact contact = account.getRoster().getContact(avatar.owner);
4309 contact.setAvatar(avatar, previouslyOmittedPepFetch);
4310 syncRoster(account);
4311 getAvatarService().clear(contact);
4312 updateRosterUi();
4313 }
4314 updateConversationUi();
4315 } else {
4316 Conversation conversation = find(account, avatar.owner.asBareJid());
4317 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4318 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4319 if (user != null) {
4320 if (user.setAvatar(avatar)) {
4321 getAvatarService().clear(user);
4322 updateConversationUi();
4323 updateMucRosterUi();
4324 }
4325 if (user.getRealJid() != null) {
4326 Contact contact = account.getRoster().getContact(user.getRealJid());
4327 contact.setAvatar(avatar);
4328 syncRoster(account);
4329 getAvatarService().clear(contact);
4330 updateRosterUi();
4331 }
4332 }
4333 }
4334 }
4335 }
4336 }
4337 }
4338 }
4339 });
4340 }
4341
4342 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
4343 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4344 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4345
4346 @Override
4347 public void onIqPacketReceived(Account account, IqPacket packet) {
4348 if (packet.getType() == IqPacket.TYPE.RESULT) {
4349 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4350 if (pubsub != null) {
4351 Element items = pubsub.findChild("items");
4352 if (items != null) {
4353 Avatar avatar = Avatar.parseMetadata(items);
4354 if (avatar != null) {
4355 avatar.owner = account.getJid().asBareJid();
4356 if (fileBackend.isAvatarCached(avatar)) {
4357 if (account.setAvatar(avatar.getFilename())) {
4358 databaseBackend.updateAccount(account);
4359 }
4360 getAvatarService().clear(account);
4361 callback.success(avatar);
4362 } else {
4363 fetchAvatarPep(account, avatar, callback);
4364 }
4365 return;
4366 }
4367 }
4368 }
4369 }
4370 callback.error(0, null);
4371 }
4372 });
4373 }
4374
4375 public void notifyAccountAvatarHasChanged(final Account account) {
4376 final XmppConnection connection = account.getXmppConnection();
4377 if (connection != null && connection.getFeatures().bookmarksConversion()) {
4378 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4379 for (Conversation conversation : conversations) {
4380 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4381 final MucOptions mucOptions = conversation.getMucOptions();
4382 if (mucOptions.online()) {
4383 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous(), mucOptions.getSelf().getNick());
4384 packet.setTo(mucOptions.getSelf().getFullJid());
4385 connection.sendPresencePacket(packet);
4386 }
4387 }
4388 }
4389 }
4390 }
4391
4392 public void fetchVcard4(Account account, final Contact contact, final Consumer<Element> callback) {
4393 IqPacket packet = this.mIqGenerator.retrieveVcard4(contact.getJid());
4394 sendIqPacket(account, packet, (a, result) -> {
4395 if (result.getType() == IqPacket.TYPE.RESULT) {
4396 final Element item = mIqParser.getItem(result);
4397 if (item != null) {
4398 final Element vcard4 = item.findChild("vcard", Namespace.VCARD4);
4399 if (vcard4 != null) {
4400 if (callback != null) {
4401 callback.accept(vcard4);
4402 }
4403 return;
4404 }
4405 }
4406 } else {
4407 Element error = result.findChild("error");
4408 if (error == null) {
4409 Log.d(Config.LOGTAG, "fetchVcard4 (server error)");
4410 } else {
4411 Log.d(Config.LOGTAG, "fetchVcard4 " + error.toString());
4412 }
4413 }
4414 if (callback != null) {
4415 callback.accept(null);
4416 }
4417
4418 });
4419 }
4420
4421 public void deleteContactOnServer(Contact contact) {
4422 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4423 contact.resetOption(Contact.Options.DIRTY_PUSH);
4424 contact.setOption(Contact.Options.DIRTY_DELETE);
4425 Account account = contact.getAccount();
4426 if (account.getStatus() == Account.State.ONLINE) {
4427 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4428 Element item = iq.query(Namespace.ROSTER).addChild("item");
4429 item.setAttribute("jid", contact.getJid());
4430 item.setAttribute("subscription", "remove");
4431 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4432 }
4433 }
4434
4435 public void updateConversation(final Conversation conversation) {
4436 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4437 }
4438
4439 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4440 synchronized (account) {
4441 XmppConnection connection = account.getXmppConnection();
4442 if (connection == null) {
4443 connection = createConnection(account);
4444 account.setXmppConnection(connection);
4445 }
4446 boolean hasInternet = hasInternetConnection();
4447 if (account.isEnabled() && hasInternet) {
4448 if (!force) {
4449 disconnect(account, false);
4450 }
4451 Thread thread = new Thread(connection);
4452 connection.setInteractive(interactive);
4453 connection.prepareNewConnection();
4454 connection.interrupt();
4455 thread.start();
4456 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4457 } else {
4458 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4459 account.getRoster().clearPresences();
4460 connection.resetEverything();
4461 final AxolotlService axolotlService = account.getAxolotlService();
4462 if (axolotlService != null) {
4463 axolotlService.resetBrokenness();
4464 }
4465 if (!hasInternet) {
4466 account.setStatus(Account.State.NO_INTERNET);
4467 }
4468 }
4469 }
4470 }
4471
4472 public void reconnectAccountInBackground(final Account account) {
4473 new Thread(() -> reconnectAccount(account, false, true)).start();
4474 }
4475
4476 public void invite(final Conversation conversation, final Jid contact) {
4477 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4478 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4479 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4480 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4481 }
4482 final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4483 sendMessagePacket(conversation.getAccount(), packet);
4484 }
4485
4486 public void directInvite(Conversation conversation, Jid jid) {
4487 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4488 sendMessagePacket(conversation.getAccount(), packet);
4489 }
4490
4491 public void resetSendingToWaiting(Account account) {
4492 for (Conversation conversation : getConversations()) {
4493 if (conversation.getAccount() == account) {
4494 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4495 }
4496 }
4497 }
4498
4499 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4500 return markMessage(account, recipient, uuid, status, null);
4501 }
4502
4503 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4504 if (uuid == null) {
4505 return null;
4506 }
4507 for (Conversation conversation : getConversations()) {
4508 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4509 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4510 if (message != null) {
4511 markMessage(message, status, errorMessage);
4512 }
4513 return message;
4514 }
4515 }
4516 return null;
4517 }
4518
4519 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4520 return markMessage(conversation, uuid, status, serverMessageId, null);
4521 }
4522
4523 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4524 if (uuid == null) {
4525 return false;
4526 } else {
4527 final Message message = conversation.findSentMessageWithUuid(uuid);
4528 if (message != null) {
4529 if (message.getServerMsgId() == null) {
4530 message.setServerMsgId(serverMessageId);
4531 }
4532 if (message.getEncryption() == Message.ENCRYPTION_NONE
4533 && message.isTypeText()
4534 && isBodyModified(message, body)) {
4535 message.setBody(body.content);
4536 if (body.count > 1) {
4537 message.setBodyLanguage(body.language);
4538 }
4539 markMessage(message, status, null, true);
4540 } else {
4541 markMessage(message, status);
4542 }
4543 return true;
4544 } else {
4545 return false;
4546 }
4547 }
4548 }
4549
4550 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4551 if (body == null || body.content == null) {
4552 return false;
4553 }
4554 return !body.content.equals(message.getBody());
4555 }
4556
4557 public void markMessage(Message message, int status) {
4558 markMessage(message, status, null);
4559 }
4560
4561
4562 public void markMessage(final Message message, final int status, final String errorMessage) {
4563 markMessage(message, status, errorMessage, false);
4564 }
4565
4566 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4567 final int oldStatus = message.getStatus();
4568 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4569 return;
4570 }
4571 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4572 return;
4573 }
4574 message.setErrorMessage(errorMessage);
4575 message.setStatus(status);
4576 databaseBackend.updateMessage(message, includeBody);
4577 updateConversationUi();
4578 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4579 mNotificationService.pushFailedDelivery(message);
4580 }
4581 }
4582
4583 public SharedPreferences getPreferences() {
4584 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4585 }
4586
4587 public long getAutomaticMessageDeletionDate() {
4588 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4589 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4590 }
4591
4592 public long getLongPreference(String name, @IntegerRes int res) {
4593 long defaultValue = getResources().getInteger(res);
4594 try {
4595 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4596 } catch (NumberFormatException e) {
4597 return defaultValue;
4598 }
4599 }
4600
4601 public boolean getBooleanPreference(String name, @BoolRes int res) {
4602 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4603 }
4604
4605 public boolean confirmMessages() {
4606 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4607 }
4608
4609 public boolean allowMessageCorrection() {
4610 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4611 }
4612
4613 public boolean sendChatStates() {
4614 return getBooleanPreference("chat_states", R.bool.chat_states);
4615 }
4616
4617 private boolean synchronizeWithBookmarks() {
4618 return getBooleanPreference("autojoin", R.bool.autojoin);
4619 }
4620
4621 public boolean useTorToConnect() {
4622 return getBooleanPreference("use_tor", R.bool.use_tor);
4623 }
4624
4625 public boolean showExtendedConnectionOptions() {
4626 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4627 }
4628
4629 public boolean broadcastLastActivity() {
4630 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4631 }
4632
4633 public int unreadCount() {
4634 int count = 0;
4635 for (Conversation conversation : getConversations()) {
4636 count += conversation.unreadCount();
4637 }
4638 return count;
4639 }
4640
4641
4642 private <T> List<T> threadSafeList(Set<T> set) {
4643 synchronized (LISTENER_LOCK) {
4644 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4645 }
4646 }
4647
4648 public void showErrorToastInUi(int resId) {
4649 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4650 listener.onShowErrorToast(resId);
4651 }
4652 }
4653
4654 public void updateConversationUi() {
4655 updateConversationUi(false);
4656 }
4657
4658 public void updateConversationUi(boolean newCaps) {
4659 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4660 listener.onConversationUpdate(newCaps);
4661 }
4662 }
4663
4664 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4665 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4666 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4667 }
4668 }
4669
4670 public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4671 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4672 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4673 }
4674 }
4675
4676 public void updateAccountUi() {
4677 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4678 listener.onAccountUpdate();
4679 }
4680 }
4681
4682 public void updateRosterUi() {
4683 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4684 listener.onRosterUpdate();
4685 }
4686 }
4687
4688 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4689 if (mOnCaptchaRequested.size() > 0) {
4690 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4691 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4692 (int) (captcha.getHeight() * metrics.scaledDensity), false);
4693 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4694 listener.onCaptchaRequested(account, id, data, scaled);
4695 }
4696 return true;
4697 }
4698 return false;
4699 }
4700
4701 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4702 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4703 listener.OnUpdateBlocklist(status);
4704 }
4705 }
4706
4707 public void updateMucRosterUi() {
4708 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4709 listener.onMucRosterUpdate();
4710 }
4711 }
4712
4713 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4714 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4715 listener.onKeyStatusUpdated(report);
4716 }
4717 }
4718
4719 public Account findAccountByJid(final Jid jid) {
4720 for (final Account account : this.accounts) {
4721 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4722 return account;
4723 }
4724 }
4725 return null;
4726 }
4727
4728 public Account findAccountByUuid(final String uuid) {
4729 for (Account account : this.accounts) {
4730 if (account.getUuid().equals(uuid)) {
4731 return account;
4732 }
4733 }
4734 return null;
4735 }
4736
4737 public Conversation findConversationByUuid(String uuid) {
4738 for (Conversation conversation : getConversations()) {
4739 if (conversation.getUuid().equals(uuid)) {
4740 return conversation;
4741 }
4742 }
4743 return null;
4744 }
4745
4746 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4747 List<Conversation> findings = new ArrayList<>();
4748 for (Conversation c : getConversations()) {
4749 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid().asBareJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4750 findings.add(c);
4751 }
4752 }
4753 return findings.size() == 1 ? findings.get(0) : null;
4754 }
4755
4756 public boolean markRead(final Conversation conversation, boolean dismiss) {
4757 return markRead(conversation, null, dismiss).size() > 0;
4758 }
4759
4760 public void markRead(final Conversation conversation) {
4761 markRead(conversation, null, true);
4762 }
4763
4764 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4765 if (dismiss) {
4766 mNotificationService.clear(conversation);
4767 }
4768 final List<Message> readMessages = conversation.markRead(upToUuid);
4769 if (readMessages.size() > 0) {
4770 Runnable runnable = () -> {
4771 for (Message message : readMessages) {
4772 databaseBackend.updateMessage(message, false);
4773 }
4774 };
4775 mDatabaseWriterExecutor.execute(runnable);
4776 updateConversationUi();
4777 updateUnreadCountBadge();
4778 return readMessages;
4779 } else {
4780 return readMessages;
4781 }
4782 }
4783
4784 public synchronized void updateUnreadCountBadge() {
4785 int count = unreadCount();
4786 if (unreadCount != count) {
4787 Log.d(Config.LOGTAG, "update unread count to " + count);
4788 if (count > 0) {
4789 ShortcutBadger.applyCount(getApplicationContext(), count);
4790 } else {
4791 ShortcutBadger.removeCount(getApplicationContext());
4792 }
4793 unreadCount = count;
4794 }
4795 }
4796
4797 public void sendReadMarker(final Conversation conversation, String upToUuid) {
4798 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4799 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4800 if (readMessages.size() > 0) {
4801 updateConversationUi();
4802 }
4803 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4804 if (confirmMessages()
4805 && markable != null
4806 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4807 && markable.getRemoteMsgId() != null) {
4808 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4809 final Account account = conversation.getAccount();
4810 final MessagePacket packet = mMessageGenerator.confirm(markable);
4811 this.sendMessagePacket(account, packet);
4812 }
4813 }
4814
4815 public MemorizingTrustManager getMemorizingTrustManager() {
4816 return this.mMemorizingTrustManager;
4817 }
4818
4819 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4820 this.mMemorizingTrustManager = trustManager;
4821 }
4822
4823 public void updateMemorizingTrustmanager() {
4824 final MemorizingTrustManager tm;
4825 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4826 if (dontTrustSystemCAs) {
4827 tm = new MemorizingTrustManager(getApplicationContext(), null);
4828 } else {
4829 tm = new MemorizingTrustManager(getApplicationContext());
4830 }
4831 setMemorizingTrustManager(tm);
4832 }
4833
4834 public LruCache<String, Drawable> getDrawableCache() {
4835 return this.mDrawableCache;
4836 }
4837
4838 public Collection<String> getKnownHosts() {
4839 final Set<String> hosts = new HashSet<>();
4840 for (final Account account : getAccounts()) {
4841 hosts.add(account.getServer());
4842 for (final Contact contact : account.getRoster().getContacts()) {
4843 if (contact.showInRoster()) {
4844 final String server = contact.getServer();
4845 if (server != null) {
4846 hosts.add(server);
4847 }
4848 }
4849 }
4850 }
4851 if (Config.QUICKSY_DOMAIN != null) {
4852 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4853 }
4854 if (Config.DOMAIN_LOCK != null) {
4855 hosts.add(Config.DOMAIN_LOCK);
4856 }
4857 if (Config.MAGIC_CREATE_DOMAIN != null) {
4858 hosts.add(Config.MAGIC_CREATE_DOMAIN);
4859 }
4860 hosts.add("chat.above.im");
4861 return hosts;
4862 }
4863
4864 public Collection<String> getKnownConferenceHosts() {
4865 final Set<String> mucServers = new HashSet<>();
4866 for (final Account account : accounts) {
4867 if (account.getXmppConnection() != null) {
4868 mucServers.addAll(account.getXmppConnection().getMucServers());
4869 for (final Bookmark bookmark : account.getBookmarks()) {
4870 final Jid jid = bookmark.getJid();
4871 final String s = jid == null ? null : jid.getDomain().toEscapedString();
4872 if (s != null) {
4873 mucServers.add(s);
4874 }
4875 }
4876 }
4877 }
4878 return mucServers;
4879 }
4880
4881 public void sendMessagePacket(Account account, MessagePacket packet) {
4882 final XmppConnection connection = account.getXmppConnection();
4883 if (connection != null) {
4884 connection.sendMessagePacket(packet);
4885 }
4886 }
4887
4888 public void sendPresencePacket(Account account, PresencePacket packet) {
4889 XmppConnection connection = account.getXmppConnection();
4890 if (connection != null) {
4891 connection.sendPresencePacket(packet);
4892 }
4893 }
4894
4895 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4896 final XmppConnection connection = account.getXmppConnection();
4897 if (connection != null) {
4898 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4899 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4900 }
4901 }
4902
4903 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4904 sendIqPacket(account, packet, callback, null);
4905 }
4906
4907 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback, Long timeout) {
4908 final XmppConnection connection = account.getXmppConnection();
4909 if (connection != null) {
4910 connection.sendIqPacket(packet, callback, timeout);
4911 } else if (callback != null) {
4912 callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4913 }
4914 }
4915
4916 public void sendPresence(final Account account) {
4917 sendPresence(account, checkListeners() && broadcastLastActivity());
4918 }
4919
4920 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4921 final Presence.Status status;
4922 if (manuallyChangePresence()) {
4923 status = account.getPresenceStatus();
4924 } else {
4925 status = getTargetPresence();
4926 }
4927 final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4928 if (mLastActivity > 0 && includeIdleTimestamp) {
4929 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4930 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4931 }
4932 sendPresencePacket(account, packet);
4933 }
4934
4935 private void deactivateGracePeriod() {
4936 for (Account account : getAccounts()) {
4937 account.deactivateGracePeriod();
4938 }
4939 }
4940
4941 public void refreshAllPresences() {
4942 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4943 for (Account account : getAccounts()) {
4944 if (account.isEnabled()) {
4945 sendPresence(account, includeIdleTimestamp);
4946 }
4947 }
4948 }
4949
4950 private void refreshAllFcmTokens() {
4951 for (Account account : getAccounts()) {
4952 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4953 mPushManagementService.registerPushTokenOnServer(account);
4954 }
4955 }
4956 }
4957
4958
4959
4960 private void sendOfflinePresence(final Account account) {
4961 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4962 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4963 }
4964
4965 public MessageGenerator getMessageGenerator() {
4966 return this.mMessageGenerator;
4967 }
4968
4969 public PresenceGenerator getPresenceGenerator() {
4970 return this.mPresenceGenerator;
4971 }
4972
4973 public IqGenerator getIqGenerator() {
4974 return this.mIqGenerator;
4975 }
4976
4977 public IqParser getIqParser() {
4978 return this.mIqParser;
4979 }
4980
4981 public JingleConnectionManager getJingleConnectionManager() {
4982 return this.mJingleConnectionManager;
4983 }
4984
4985 public MessageArchiveService getMessageArchiveService() {
4986 return this.mMessageArchiveService;
4987 }
4988
4989 public QuickConversationsService getQuickConversationsService() {
4990 return this.mQuickConversationsService;
4991 }
4992
4993 public List<Contact> findContacts(Jid jid, String accountJid) {
4994 ArrayList<Contact> contacts = new ArrayList<>();
4995 for (Account account : getAccounts()) {
4996 if ((account.isEnabled() || accountJid != null)
4997 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4998 Contact contact = account.getRoster().getContactFromContactList(jid);
4999 if (contact != null) {
5000 contacts.add(contact);
5001 }
5002 }
5003 }
5004 return contacts;
5005 }
5006
5007 public Conversation findFirstMuc(Jid jid) {
5008 for (Conversation conversation : getConversations()) {
5009 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
5010 return conversation;
5011 }
5012 }
5013 return null;
5014 }
5015
5016 public NotificationService getNotificationService() {
5017 return this.mNotificationService;
5018 }
5019
5020 public HttpConnectionManager getHttpConnectionManager() {
5021 return this.mHttpConnectionManager;
5022 }
5023
5024 public void resendFailedMessages(final Message message) {
5025 final Collection<Message> messages = new ArrayList<>();
5026 Message current = message;
5027 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
5028 messages.add(current);
5029 if (current.mergeable(current.next())) {
5030 current = current.next();
5031 } else {
5032 break;
5033 }
5034 }
5035 for (final Message msg : messages) {
5036 msg.setTime(System.currentTimeMillis());
5037 markMessage(msg, Message.STATUS_WAITING);
5038 this.resendMessage(msg, false);
5039 }
5040 if (message.getConversation() instanceof Conversation) {
5041 ((Conversation) message.getConversation()).sort();
5042 }
5043 updateConversationUi();
5044 }
5045
5046 public void clearConversationHistory(final Conversation conversation) {
5047 final long clearDate;
5048 final String reference;
5049 if (conversation.countMessages() > 0) {
5050 Message latestMessage = conversation.getLatestMessage();
5051 clearDate = latestMessage.getTimeSent() + 1000;
5052 reference = latestMessage.getServerMsgId();
5053 } else {
5054 clearDate = System.currentTimeMillis();
5055 reference = null;
5056 }
5057 conversation.clearMessages();
5058 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
5059 conversation.setLastClearHistory(clearDate, reference);
5060 Runnable runnable = () -> {
5061 databaseBackend.deleteMessagesInConversation(conversation);
5062 databaseBackend.updateConversation(conversation);
5063 };
5064 mDatabaseWriterExecutor.execute(runnable);
5065 }
5066
5067 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
5068 if (blockable != null && blockable.getBlockedJid() != null) {
5069 final Jid jid = blockable.getBlockedJid();
5070 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
5071 if (response.getType() == IqPacket.TYPE.RESULT) {
5072 a.getBlocklist().add(jid);
5073 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
5074 }
5075 });
5076 if (blockable.getBlockedJid().isFullJid()) {
5077 return false;
5078 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
5079 updateConversationUi();
5080 return true;
5081 } else {
5082 return false;
5083 }
5084 } else {
5085 return false;
5086 }
5087 }
5088
5089 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
5090 boolean removed = false;
5091 synchronized (this.conversations) {
5092 boolean domainJid = blockedJid.getLocal() == null;
5093 for (Conversation conversation : this.conversations) {
5094 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
5095 || blockedJid.equals(conversation.getJid().asBareJid());
5096 if (conversation.getAccount() == account
5097 && conversation.getMode() == Conversation.MODE_SINGLE
5098 && jidMatches) {
5099 this.conversations.remove(conversation);
5100 markRead(conversation);
5101 conversation.setStatus(Conversation.STATUS_ARCHIVED);
5102 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
5103 updateConversation(conversation);
5104 removed = true;
5105 }
5106 }
5107 }
5108 return removed;
5109 }
5110
5111 public void sendUnblockRequest(final Blockable blockable) {
5112 if (blockable != null && blockable.getJid() != null) {
5113 final Jid jid = blockable.getBlockedJid();
5114 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
5115 @Override
5116 public void onIqPacketReceived(final Account account, final IqPacket packet) {
5117 if (packet.getType() == IqPacket.TYPE.RESULT) {
5118 account.getBlocklist().remove(jid);
5119 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
5120 }
5121 }
5122 });
5123 }
5124 }
5125
5126 public void publishDisplayName(Account account) {
5127 String displayName = account.getDisplayName();
5128 final IqPacket request;
5129 if (TextUtils.isEmpty(displayName)) {
5130 request = mIqGenerator.deleteNode(Namespace.NICK);
5131 } else {
5132 request = mIqGenerator.publishNick(displayName);
5133 }
5134 mAvatarService.clear(account);
5135 sendIqPacket(account, request, (account1, packet) -> {
5136 if (packet.getType() == IqPacket.TYPE.ERROR) {
5137 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet);
5138 }
5139 });
5140 }
5141
5142 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
5143 ServiceDiscoveryResult result = discoCache.get(key);
5144 if (result != null) {
5145 return result;
5146 } else {
5147 if (key.first == null || key.second == null) return null;
5148 result = databaseBackend.findDiscoveryResult(key.first, key.second);
5149 if (result != null) {
5150 discoCache.put(key, result);
5151 }
5152 return result;
5153 }
5154 }
5155
5156 public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
5157 IqPacket request = new IqPacket(input == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
5158 request.setTo(jid);
5159 Element query = request.query("jabber:iq:gateway");
5160 if (input != null) {
5161 Element prompt = query.addChild("prompt");
5162 prompt.setContent(input);
5163 }
5164 sendIqPacket(account, request, (Account acct, IqPacket packet) -> {
5165 if (packet.getType() == IqPacket.TYPE.RESULT) {
5166 callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
5167 } else {
5168 Element error = packet.findChild("error");
5169 callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
5170 }
5171 });
5172 }
5173
5174 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
5175 fetchCaps(account, jid, presence, null);
5176 }
5177
5178 public void fetchCaps(Account account, final Jid jid, final Presence presence, Runnable cb) {
5179 final Pair<String, String> key = presence == null ? null : new Pair<>(presence.getHash(), presence.getVer());
5180 final ServiceDiscoveryResult disco = key == null ? null : getCachedServiceDiscoveryResult(key);
5181
5182 if (disco != null) {
5183 presence.setServiceDiscoveryResult(disco);
5184 final Contact contact = account.getRoster().getContact(jid);
5185 if (contact.refreshRtpCapability()) {
5186 syncRoster(account);
5187 }
5188 if (disco.hasIdentity("gateway", "pstn")) {
5189 contact.registerAsPhoneAccount(this);
5190 mQuickConversationsService.considerSyncBackground(false);
5191 }
5192 updateConversationUi(true);
5193 } else {
5194 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5195 request.setTo(jid);
5196 final String node = presence == null ? null : presence.getNode();
5197 final String ver = presence == null ? null : presence.getVer();
5198 final Element query = request.query(Namespace.DISCO_INFO);
5199 if (node != null && ver != null) {
5200 query.setAttribute("node", node + "#" + ver);
5201 }
5202 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + (key == null ? "" : key.second) + " to " + jid);
5203 sendIqPacket(account, request, (a, response) -> {
5204 if (response.getType() == IqPacket.TYPE.RESULT) {
5205 final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
5206 if (presence == null || presence.getVer() == null || presence.getVer().equals(discoveryResult.getVer())) {
5207 databaseBackend.insertDiscoveryResult(discoveryResult);
5208 injectServiceDiscoveryResult(a.getRoster(), presence == null ? null : presence.getHash(), presence == null ? null : presence.getVer(), jid.getResource(), discoveryResult);
5209 if (discoveryResult.hasIdentity("gateway", "pstn")) {
5210 final Contact contact = account.getRoster().getContact(jid);
5211 contact.registerAsPhoneAccount(this);
5212 mQuickConversationsService.considerSyncBackground(false);
5213 }
5214 updateConversationUi(true);
5215 if (cb != null) cb.run();
5216 } else {
5217 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
5218 }
5219 } else {
5220 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
5221 }
5222 });
5223 }
5224 }
5225
5226 public void fetchCommands(Account account, final Jid jid, OnIqPacketReceived callback) {
5227 final IqPacket request = mIqGenerator.queryDiscoItems(jid, "http://jabber.org/protocol/commands");
5228 sendIqPacket(account, request, callback);
5229 }
5230
5231 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, String resource, ServiceDiscoveryResult disco) {
5232 boolean rosterNeedsSync = false;
5233 for (final Contact contact : roster.getContacts()) {
5234 boolean serviceDiscoverySet = false;
5235 Presence onePresence = contact.getPresences().get(resource == null ? "" : resource);
5236 if (onePresence != null) {
5237 onePresence.setServiceDiscoveryResult(disco);
5238 serviceDiscoverySet = true;
5239 } else if (resource == null && hash == null && ver == null) {
5240 Presence p = new Presence(Presence.Status.OFFLINE, null, null, null, "");
5241 p.setServiceDiscoveryResult(disco);
5242 contact.updatePresence("", p);
5243 serviceDiscoverySet = true;
5244 }
5245 if (hash != null && ver != null) {
5246 for (final Presence presence : contact.getPresences().getPresences()) {
5247 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
5248 presence.setServiceDiscoveryResult(disco);
5249 serviceDiscoverySet = true;
5250 }
5251 }
5252 }
5253 if (serviceDiscoverySet) {
5254 rosterNeedsSync |= contact.refreshRtpCapability();
5255 }
5256 }
5257 if (rosterNeedsSync) {
5258 syncRoster(roster.getAccount());
5259 }
5260 }
5261
5262 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
5263 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5264 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5265 request.addChild("prefs", version.namespace);
5266 sendIqPacket(account, request, (account1, packet) -> {
5267 Element prefs = packet.findChild("prefs", version.namespace);
5268 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
5269 callback.onPreferencesFetched(prefs);
5270 } else {
5271 callback.onPreferencesFetchFailed();
5272 }
5273 });
5274 }
5275
5276 public PushManagementService getPushManagementService() {
5277 return mPushManagementService;
5278 }
5279
5280 public void changeStatus(Account account, PresenceTemplate template, String signature) {
5281 if (!template.getStatusMessage().isEmpty()) {
5282 databaseBackend.insertPresenceTemplate(template);
5283 }
5284 account.setPgpSignature(signature);
5285 account.setPresenceStatus(template.getStatus());
5286 account.setPresenceStatusMessage(template.getStatusMessage());
5287 databaseBackend.updateAccount(account);
5288 sendPresence(account);
5289 }
5290
5291 public List<PresenceTemplate> getPresenceTemplates(Account account) {
5292 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5293 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5294 if (!templates.contains(template)) {
5295 templates.add(0, template);
5296 }
5297 }
5298 return templates;
5299 }
5300
5301 public void saveConversationAsBookmark(Conversation conversation, String name) {
5302 final Account account = conversation.getAccount();
5303 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5304 String nick = conversation.getMucOptions().getActualNick();
5305 if (nick == null) nick = conversation.getJid().getResource();
5306 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5307 bookmark.setNick(nick);
5308 }
5309 if (!TextUtils.isEmpty(name)) {
5310 bookmark.setBookmarkName(name);
5311 }
5312 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
5313 createBookmark(account, bookmark);
5314 bookmark.setConversation(conversation);
5315 }
5316
5317 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5318 boolean performedVerification = false;
5319 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5320 for (XmppUri.Fingerprint fp : fingerprints) {
5321 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5322 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5323 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5324 if (fingerprintStatus != null) {
5325 if (!fingerprintStatus.isVerified()) {
5326 performedVerification = true;
5327 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5328 }
5329 } else {
5330 axolotlService.preVerifyFingerprint(contact, fingerprint);
5331 }
5332 }
5333 }
5334 return performedVerification;
5335 }
5336
5337 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5338 final AxolotlService axolotlService = account.getAxolotlService();
5339 boolean verifiedSomething = false;
5340 for (XmppUri.Fingerprint fp : fingerprints) {
5341 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5342 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5343 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5344 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5345 if (fingerprintStatus != null) {
5346 if (!fingerprintStatus.isVerified()) {
5347 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5348 verifiedSomething = true;
5349 }
5350 } else {
5351 axolotlService.preVerifyFingerprint(account, fingerprint);
5352 verifiedSomething = true;
5353 }
5354 }
5355 }
5356 return verifiedSomething;
5357 }
5358
5359 public boolean blindTrustBeforeVerification() {
5360 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
5361 }
5362
5363 public ShortcutService getShortcutService() {
5364 return mShortcutService;
5365 }
5366
5367 public void pushMamPreferences(Account account, Element prefs) {
5368 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
5369 set.addChild(prefs);
5370 sendIqPacket(account, set, null);
5371 }
5372
5373 public void evictPreview(File f) {
5374 if (mDrawableCache.remove(f.getAbsolutePath()) != null) {
5375 Log.d(Config.LOGTAG, "deleted cached preview");
5376 }
5377 }
5378
5379 public void evictPreview(String uuid) {
5380 if (mDrawableCache.remove(uuid) != null) {
5381 Log.d(Config.LOGTAG, "deleted cached preview");
5382 }
5383 }
5384
5385 public interface OnMamPreferencesFetched {
5386 void onPreferencesFetched(Element prefs);
5387
5388 void onPreferencesFetchFailed();
5389 }
5390
5391 public interface OnAccountCreated {
5392 void onAccountCreated(Account account);
5393
5394 void informUser(int r);
5395 }
5396
5397 public interface OnMoreMessagesLoaded {
5398 void onMoreMessagesLoaded(int count, Conversation conversation);
5399
5400 void informUser(int r);
5401 }
5402
5403 public interface OnAccountPasswordChanged {
5404 void onPasswordChangeSucceeded();
5405
5406 void onPasswordChangeFailed();
5407 }
5408
5409 public interface OnRoomDestroy {
5410 void onRoomDestroySucceeded();
5411
5412 void onRoomDestroyFailed();
5413 }
5414
5415 public interface OnAffiliationChanged {
5416 void onAffiliationChangedSuccessful(Jid jid);
5417
5418 void onAffiliationChangeFailed(Jid jid, int resId);
5419 }
5420
5421 public interface OnConversationUpdate {
5422 default void onConversationUpdate() { onConversationUpdate(false); }
5423 default void onConversationUpdate(boolean newCaps) { onConversationUpdate(); }
5424 }
5425
5426 public interface OnJingleRtpConnectionUpdate {
5427 void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5428
5429 void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
5430 }
5431
5432 public interface OnAccountUpdate {
5433 void onAccountUpdate();
5434 }
5435
5436 public interface OnCaptchaRequested {
5437 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5438 }
5439
5440 public interface OnRosterUpdate {
5441 void onRosterUpdate();
5442 }
5443
5444 public interface OnMucRosterUpdate {
5445 void onMucRosterUpdate();
5446 }
5447
5448 public interface OnConferenceConfigurationFetched {
5449 void onConferenceConfigurationFetched(Conversation conversation);
5450
5451 void onFetchFailed(Conversation conversation, String errorCondition);
5452 }
5453
5454 public interface OnConferenceJoined {
5455 void onConferenceJoined(Conversation conversation);
5456 }
5457
5458 public interface OnConfigurationPushed {
5459 void onPushSucceeded();
5460
5461 void onPushFailed();
5462 }
5463
5464 public interface OnShowErrorToast {
5465 void onShowErrorToast(int resId);
5466 }
5467
5468 public class XmppConnectionBinder extends Binder {
5469 public XmppConnectionService getService() {
5470 return XmppConnectionService.this;
5471 }
5472 }
5473
5474 private class InternalEventReceiver extends BroadcastReceiver {
5475
5476 @Override
5477 public void onReceive(Context context, Intent intent) {
5478 onStartCommand(intent, 0, 0);
5479 }
5480 }
5481
5482 public static class OngoingCall {
5483 public final AbstractJingleConnection.Id id;
5484 public final Set<Media> media;
5485 public final boolean reconnecting;
5486
5487 public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5488 this.id = id;
5489 this.media = media;
5490 this.reconnecting = reconnecting;
5491 }
5492
5493 @Override
5494 public boolean equals(Object o) {
5495 if (this == o) return true;
5496 if (o == null || getClass() != o.getClass()) return false;
5497 OngoingCall that = (OngoingCall) o;
5498 return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
5499 }
5500
5501 @Override
5502 public int hashCode() {
5503 return Objects.hashCode(id, media, reconnecting);
5504 }
5505 }
5506
5507 public static class BlockedMediaException extends Exception { }
5508}