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