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