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