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 requestVoice(final Account account, final Jid jid) {
3671 MessagePacket packet = this.getMessageGenerator().requestVoice(jid);
3672 this.sendMessagePacket(account, packet);
3673 }
3674
3675 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3676 final Jid jid = user.asBareJid();
3677 final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3678 sendIqPacket(conference.getAccount(), request, (account, response) -> {
3679 if (response.getType() == IqPacket.TYPE.RESULT) {
3680 conference.getMucOptions().changeAffiliation(jid, affiliation);
3681 getAvatarService().clear(conference);
3682 if (callback != null) {
3683 callback.onAffiliationChangedSuccessful(jid);
3684 } else {
3685 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3686 }
3687 } else if (callback != null) {
3688 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3689 } else {
3690 Log.d(Config.LOGTAG, "unable to change affiliation");
3691 }
3692 });
3693 }
3694
3695 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3696 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3697 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3698 if (packet.getType() != IqPacket.TYPE.RESULT) {
3699 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3700 }
3701 });
3702 }
3703
3704 public void moderateMessage(final Account account, final Message m, final String reason) {
3705 IqPacket request = this.mIqGenerator.moderateMessage(account, m, reason);
3706 sendIqPacket(account, request, (a, packet) -> {
3707 if (packet.getType() != IqPacket.TYPE.RESULT) {
3708 showErrorToastInUi(R.string.unable_to_moderate);
3709 Log.d(Config.LOGTAG, a.getJid().asBareJid() + " unable to moderate: " + packet);
3710 }
3711 });
3712 }
3713
3714 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3715 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3716 request.setTo(conversation.getJid().asBareJid());
3717 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3718 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3719 @Override
3720 public void onIqPacketReceived(Account account, IqPacket packet) {
3721 if (packet.getType() == IqPacket.TYPE.RESULT) {
3722 if (callback != null) {
3723 callback.onRoomDestroySucceeded();
3724 }
3725 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3726 if (callback != null) {
3727 callback.onRoomDestroyFailed();
3728 }
3729 }
3730 }
3731 });
3732 }
3733
3734 private void disconnect(Account account, boolean force) {
3735 if ((account.getStatus() == Account.State.ONLINE)
3736 || (account.getStatus() == Account.State.DISABLED)) {
3737 final XmppConnection connection = account.getXmppConnection();
3738 if (!force) {
3739 List<Conversation> conversations = getConversations();
3740 for (Conversation conversation : conversations) {
3741 if (conversation.getAccount() == account) {
3742 if (conversation.getMode() == Conversation.MODE_MULTI) {
3743 leaveMuc(conversation, true);
3744 }
3745 }
3746 }
3747 sendOfflinePresence(account);
3748 }
3749 connection.disconnect(force);
3750 }
3751 }
3752
3753 @Override
3754 public IBinder onBind(Intent intent) {
3755 return mBinder;
3756 }
3757
3758 public void updateMessage(Message message) {
3759 updateMessage(message, true);
3760 }
3761
3762 public void updateMessage(Message message, boolean includeBody) {
3763 databaseBackend.updateMessage(message, includeBody);
3764 updateConversationUi();
3765 }
3766
3767 public void createMessageAsync(final Message message) {
3768 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3769 }
3770
3771 public void updateMessage(Message message, String uuid) {
3772 if (!databaseBackend.updateMessage(message, uuid)) {
3773 Log.e(Config.LOGTAG, "error updated message in DB after edit");
3774 }
3775 updateConversationUi();
3776 }
3777
3778 protected void syncDirtyContacts(Account account) {
3779 for (Contact contact : account.getRoster().getContacts()) {
3780 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3781 pushContactToServer(contact);
3782 }
3783 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3784 deleteContactOnServer(contact);
3785 }
3786 }
3787 }
3788
3789 protected void unregisterPhoneAccounts(final Account account) {
3790 for (final Contact contact : account.getRoster().getContacts()) {
3791 if (!contact.showInRoster()) {
3792 contact.unregisterAsPhoneAccount(this);
3793 }
3794 }
3795 }
3796
3797 public void createContact(final Contact contact, final boolean autoGrant) {
3798 createContact(contact, autoGrant, null);
3799 }
3800
3801 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3802 if (autoGrant) {
3803 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3804 contact.setOption(Contact.Options.ASKING);
3805 }
3806 pushContactToServer(contact, preAuth);
3807 }
3808
3809 public void pushContactToServer(final Contact contact) {
3810 pushContactToServer(contact, null);
3811 }
3812
3813 private void pushContactToServer(final Contact contact, final String preAuth) {
3814 contact.resetOption(Contact.Options.DIRTY_DELETE);
3815 contact.setOption(Contact.Options.DIRTY_PUSH);
3816 final Account account = contact.getAccount();
3817 if (account.getStatus() == Account.State.ONLINE) {
3818 final boolean ask = contact.getOption(Contact.Options.ASKING);
3819 final boolean sendUpdates = contact
3820 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3821 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3822 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3823 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3824 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3825 if (sendUpdates) {
3826 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3827 }
3828 if (ask) {
3829 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3830 }
3831 } else {
3832 syncRoster(contact.getAccount());
3833 }
3834 }
3835
3836 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3837 new Thread(() -> {
3838 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3839 final int size = Config.AVATAR_SIZE;
3840 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3841 if (avatar != null) {
3842 if (!getFileBackend().save(avatar)) {
3843 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3844 return;
3845 }
3846 avatar.owner = conversation.getJid().asBareJid();
3847 publishMucAvatar(conversation, avatar, callback);
3848 } else {
3849 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3850 }
3851 }).start();
3852 }
3853
3854 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3855 new Thread(() -> {
3856 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3857 final int size = Config.AVATAR_SIZE;
3858 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3859 if (avatar != null) {
3860 if (!getFileBackend().save(avatar)) {
3861 Log.d(Config.LOGTAG, "unable to save vcard");
3862 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3863 return;
3864 }
3865 publishAvatar(account, avatar, callback);
3866 } else {
3867 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3868 }
3869 }).start();
3870
3871 }
3872
3873 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3874 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3875 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3876 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3877 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3878 Element vcard = response.findChild("vCard", "vcard-temp");
3879 if (vcard == null) {
3880 vcard = new Element("vCard", "vcard-temp");
3881 }
3882 Element photo = vcard.findChild("PHOTO");
3883 if (photo == null) {
3884 photo = vcard.addChild("PHOTO");
3885 }
3886 photo.clearChildren();
3887 photo.addChild("TYPE").setContent(avatar.type);
3888 photo.addChild("BINVAL").setContent(avatar.image);
3889 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3890 publication.setTo(conversation.getJid().asBareJid());
3891 publication.addChild(vcard);
3892 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3893 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3894 callback.onAvatarPublicationSucceeded();
3895 } else {
3896 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3897 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3898 }
3899 });
3900 } else {
3901 Log.d(Config.LOGTAG, "failed to request vcard " + response);
3902 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3903 }
3904 });
3905 }
3906
3907 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3908 final Bundle options;
3909 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3910 options = PublishOptions.openAccess();
3911 } else {
3912 options = null;
3913 }
3914 publishAvatar(account, avatar, options, true, callback);
3915 }
3916
3917 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3918 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3919 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3920 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3921
3922 @Override
3923 public void onIqPacketReceived(Account account, IqPacket result) {
3924 if (result.getType() == IqPacket.TYPE.RESULT) {
3925 publishAvatarMetadata(account, avatar, options, true, callback);
3926 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3927 pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
3928 @Override
3929 public void onPushSucceeded() {
3930 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3931 publishAvatar(account, avatar, options, false, callback);
3932 }
3933
3934 @Override
3935 public void onPushFailed() {
3936 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3937 publishAvatar(account, avatar, null, false, callback);
3938 }
3939 });
3940 } else {
3941 Element error = result.findChild("error");
3942 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3943 if (callback != null) {
3944 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3945 }
3946 }
3947 }
3948 });
3949 }
3950
3951 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3952 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3953 sendIqPacket(account, packet, new OnIqPacketReceived() {
3954 @Override
3955 public void onIqPacketReceived(Account account, IqPacket result) {
3956 if (result.getType() == IqPacket.TYPE.RESULT) {
3957 if (account.setAvatar(avatar.getFilename())) {
3958 getAvatarService().clear(account);
3959 databaseBackend.updateAccount(account);
3960 notifyAccountAvatarHasChanged(account);
3961 }
3962 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3963 if (callback != null) {
3964 callback.onAvatarPublicationSucceeded();
3965 }
3966 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3967 pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
3968 @Override
3969 public void onPushSucceeded() {
3970 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3971 publishAvatarMetadata(account, avatar, options, false, callback);
3972 }
3973
3974 @Override
3975 public void onPushFailed() {
3976 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3977 publishAvatarMetadata(account, avatar, null, false, callback);
3978 }
3979 });
3980 } else {
3981 if (callback != null) {
3982 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3983 }
3984 }
3985 }
3986 });
3987 }
3988
3989 public void republishAvatarIfNeeded(Account account) {
3990 if (account.getAxolotlService().isPepBroken()) {
3991 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3992 return;
3993 }
3994 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3995 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3996
3997 private Avatar parseAvatar(IqPacket packet) {
3998 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3999 if (pubsub != null) {
4000 Element items = pubsub.findChild("items");
4001 if (items != null) {
4002 return Avatar.parseMetadata(items);
4003 }
4004 }
4005 return null;
4006 }
4007
4008 private boolean errorIsItemNotFound(IqPacket packet) {
4009 Element error = packet.findChild("error");
4010 return packet.getType() == IqPacket.TYPE.ERROR
4011 && error != null
4012 && error.hasChild("item-not-found");
4013 }
4014
4015 @Override
4016 public void onIqPacketReceived(Account account, IqPacket packet) {
4017 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
4018 Avatar serverAvatar = parseAvatar(packet);
4019 if (serverAvatar == null && account.getAvatar() != null) {
4020 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4021 if (avatar != null) {
4022 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
4023 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
4024 } else {
4025 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
4026 }
4027 }
4028 }
4029 }
4030 });
4031 }
4032
4033 public void fetchAvatar(Account account, Avatar avatar) {
4034 fetchAvatar(account, avatar, null);
4035 }
4036
4037 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4038 if (databaseBackend.isBlockedMedia(avatar.cid())) {
4039 if (callback != null) callback.error(0, null);
4040 return;
4041 }
4042
4043 final String KEY = generateFetchKey(account, avatar);
4044 synchronized (this.mInProgressAvatarFetches) {
4045 if (mInProgressAvatarFetches.add(KEY)) {
4046 switch (avatar.origin) {
4047 case PEP:
4048 this.mInProgressAvatarFetches.add(KEY);
4049 fetchAvatarPep(account, avatar, callback);
4050 break;
4051 case VCARD:
4052 this.mInProgressAvatarFetches.add(KEY);
4053 fetchAvatarVcard(account, avatar, callback);
4054 break;
4055 }
4056 } else if (avatar.origin == Avatar.Origin.PEP) {
4057 mOmittedPepAvatarFetches.add(KEY);
4058 } else {
4059 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
4060 }
4061 }
4062 }
4063
4064 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4065 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
4066 sendIqPacket(account, packet, (a, result) -> {
4067 synchronized (mInProgressAvatarFetches) {
4068 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
4069 }
4070 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
4071 if (result.getType() == IqPacket.TYPE.RESULT) {
4072 avatar.image = mIqParser.avatarData(result);
4073 if (avatar.image != null) {
4074 if (getFileBackend().save(avatar)) {
4075 if (a.getJid().asBareJid().equals(avatar.owner)) {
4076 if (a.setAvatar(avatar.getFilename())) {
4077 databaseBackend.updateAccount(a);
4078 }
4079 getAvatarService().clear(a);
4080 updateConversationUi();
4081 updateAccountUi();
4082 } else {
4083 final Contact contact = a.getRoster().getContact(avatar.owner);
4084 contact.setAvatar(avatar);
4085 syncRoster(account);
4086 getAvatarService().clear(contact);
4087 updateConversationUi();
4088 updateRosterUi();
4089 }
4090 if (callback != null) {
4091 callback.success(avatar);
4092 }
4093 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
4094 return;
4095 }
4096 } else {
4097
4098 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4099 }
4100 } else {
4101 Element error = result.findChild("error");
4102 if (error == null) {
4103 Log.d(Config.LOGTAG, ERROR + "(server error)");
4104 } else {
4105 Log.d(Config.LOGTAG, ERROR + error.toString());
4106 }
4107 }
4108 if (callback != null) {
4109 callback.error(0, null);
4110 }
4111
4112 });
4113 }
4114
4115 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4116 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4117 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4118 @Override
4119 public void onIqPacketReceived(Account account, IqPacket packet) {
4120 final boolean previouslyOmittedPepFetch;
4121 synchronized (mInProgressAvatarFetches) {
4122 final String KEY = generateFetchKey(account, avatar);
4123 mInProgressAvatarFetches.remove(KEY);
4124 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4125 }
4126 if (packet.getType() == IqPacket.TYPE.RESULT) {
4127 Element vCard = packet.findChild("vCard", "vcard-temp");
4128 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4129 String image = photo != null ? photo.findChildContent("BINVAL") : null;
4130 if (image != null) {
4131 avatar.image = image;
4132 if (getFileBackend().save(avatar)) {
4133 Log.d(Config.LOGTAG, account.getJid().asBareJid()
4134 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4135 if (avatar.owner.isBareJid()) {
4136 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4137 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4138 account.setAvatar(avatar.getFilename());
4139 databaseBackend.updateAccount(account);
4140 getAvatarService().clear(account);
4141 updateAccountUi();
4142 } else {
4143 final Contact contact = account.getRoster().getContact(avatar.owner);
4144 contact.setAvatar(avatar, previouslyOmittedPepFetch);
4145 syncRoster(account);
4146 getAvatarService().clear(contact);
4147 updateRosterUi();
4148 }
4149 updateConversationUi();
4150 } else {
4151 Conversation conversation = find(account, avatar.owner.asBareJid());
4152 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4153 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4154 if (user != null) {
4155 if (user.setAvatar(avatar)) {
4156 getAvatarService().clear(user);
4157 updateConversationUi();
4158 updateMucRosterUi();
4159 }
4160 if (user.getRealJid() != null) {
4161 Contact contact = account.getRoster().getContact(user.getRealJid());
4162 contact.setAvatar(avatar);
4163 syncRoster(account);
4164 getAvatarService().clear(contact);
4165 updateRosterUi();
4166 }
4167 }
4168 }
4169 }
4170 }
4171 }
4172 }
4173 }
4174 });
4175 }
4176
4177 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
4178 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4179 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4180
4181 @Override
4182 public void onIqPacketReceived(Account account, IqPacket packet) {
4183 if (packet.getType() == IqPacket.TYPE.RESULT) {
4184 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4185 if (pubsub != null) {
4186 Element items = pubsub.findChild("items");
4187 if (items != null) {
4188 Avatar avatar = Avatar.parseMetadata(items);
4189 if (avatar != null) {
4190 avatar.owner = account.getJid().asBareJid();
4191 if (fileBackend.isAvatarCached(avatar)) {
4192 if (account.setAvatar(avatar.getFilename())) {
4193 databaseBackend.updateAccount(account);
4194 }
4195 getAvatarService().clear(account);
4196 callback.success(avatar);
4197 } else {
4198 fetchAvatarPep(account, avatar, callback);
4199 }
4200 return;
4201 }
4202 }
4203 }
4204 }
4205 callback.error(0, null);
4206 }
4207 });
4208 }
4209
4210 public void notifyAccountAvatarHasChanged(final Account account) {
4211 final XmppConnection connection = account.getXmppConnection();
4212 if (connection != null && connection.getFeatures().bookmarksConversion()) {
4213 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4214 for (Conversation conversation : conversations) {
4215 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4216 final MucOptions mucOptions = conversation.getMucOptions();
4217 if (mucOptions.online()) {
4218 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous(), mucOptions.getSelf().getNick());
4219 packet.setTo(mucOptions.getSelf().getFullJid());
4220 connection.sendPresencePacket(packet);
4221 }
4222 }
4223 }
4224 }
4225 }
4226
4227 public void fetchVcard4(Account account, final Contact contact, final Consumer<Element> callback) {
4228 IqPacket packet = this.mIqGenerator.retrieveVcard4(contact.getJid());
4229 sendIqPacket(account, packet, (a, result) -> {
4230 if (result.getType() == IqPacket.TYPE.RESULT) {
4231 final Element item = mIqParser.getItem(result);
4232 if (item != null) {
4233 final Element vcard4 = item.findChild("vcard", Namespace.VCARD4);
4234 if (vcard4 != null) {
4235 if (callback != null) {
4236 callback.accept(vcard4);
4237 }
4238 return;
4239 }
4240 }
4241 } else {
4242 Element error = result.findChild("error");
4243 if (error == null) {
4244 Log.d(Config.LOGTAG, "fetchVcard4 (server error)");
4245 } else {
4246 Log.d(Config.LOGTAG, "fetchVcard4 " + error.toString());
4247 }
4248 }
4249 if (callback != null) {
4250 callback.accept(null);
4251 }
4252
4253 });
4254 }
4255
4256 public void deleteContactOnServer(Contact contact) {
4257 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4258 contact.resetOption(Contact.Options.DIRTY_PUSH);
4259 contact.setOption(Contact.Options.DIRTY_DELETE);
4260 Account account = contact.getAccount();
4261 if (account.getStatus() == Account.State.ONLINE) {
4262 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4263 Element item = iq.query(Namespace.ROSTER).addChild("item");
4264 item.setAttribute("jid", contact.getJid());
4265 item.setAttribute("subscription", "remove");
4266 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4267 }
4268 }
4269
4270 public void updateConversation(final Conversation conversation) {
4271 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4272 }
4273
4274 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4275 synchronized (account) {
4276 XmppConnection connection = account.getXmppConnection();
4277 if (connection == null) {
4278 connection = createConnection(account);
4279 account.setXmppConnection(connection);
4280 }
4281 boolean hasInternet = hasInternetConnection();
4282 if (account.isEnabled() && hasInternet) {
4283 if (!force) {
4284 disconnect(account, false);
4285 }
4286 Thread thread = new Thread(connection);
4287 connection.setInteractive(interactive);
4288 connection.prepareNewConnection();
4289 connection.interrupt();
4290 thread.start();
4291 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4292 } else {
4293 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4294 account.getRoster().clearPresences();
4295 connection.resetEverything();
4296 final AxolotlService axolotlService = account.getAxolotlService();
4297 if (axolotlService != null) {
4298 axolotlService.resetBrokenness();
4299 }
4300 if (!hasInternet) {
4301 account.setStatus(Account.State.NO_INTERNET);
4302 }
4303 }
4304 }
4305 }
4306
4307 public void reconnectAccountInBackground(final Account account) {
4308 new Thread(() -> reconnectAccount(account, false, true)).start();
4309 }
4310
4311 public void invite(final Conversation conversation, final Jid contact) {
4312 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4313 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4314 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4315 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4316 }
4317 final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4318 sendMessagePacket(conversation.getAccount(), packet);
4319 }
4320
4321 public void directInvite(Conversation conversation, Jid jid) {
4322 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4323 sendMessagePacket(conversation.getAccount(), packet);
4324 }
4325
4326 public void resetSendingToWaiting(Account account) {
4327 for (Conversation conversation : getConversations()) {
4328 if (conversation.getAccount() == account) {
4329 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4330 }
4331 }
4332 }
4333
4334 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4335 return markMessage(account, recipient, uuid, status, null);
4336 }
4337
4338 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4339 if (uuid == null) {
4340 return null;
4341 }
4342 for (Conversation conversation : getConversations()) {
4343 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4344 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4345 if (message != null) {
4346 markMessage(message, status, errorMessage);
4347 }
4348 return message;
4349 }
4350 }
4351 return null;
4352 }
4353
4354 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4355 return markMessage(conversation, uuid, status, serverMessageId, null);
4356 }
4357
4358 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4359 if (uuid == null) {
4360 return false;
4361 } else {
4362 final Message message = conversation.findSentMessageWithUuid(uuid);
4363 if (message != null) {
4364 if (message.getServerMsgId() == null) {
4365 message.setServerMsgId(serverMessageId);
4366 }
4367 if (message.getEncryption() == Message.ENCRYPTION_NONE
4368 && message.isTypeText()
4369 && isBodyModified(message, body)) {
4370 message.setBody(body.content);
4371 if (body.count > 1) {
4372 message.setBodyLanguage(body.language);
4373 }
4374 markMessage(message, status, null, true);
4375 } else {
4376 markMessage(message, status);
4377 }
4378 return true;
4379 } else {
4380 return false;
4381 }
4382 }
4383 }
4384
4385 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4386 if (body == null || body.content == null) {
4387 return false;
4388 }
4389 return !body.content.equals(message.getBody());
4390 }
4391
4392 public void markMessage(Message message, int status) {
4393 markMessage(message, status, null);
4394 }
4395
4396
4397 public void markMessage(final Message message, final int status, final String errorMessage) {
4398 markMessage(message, status, errorMessage, false);
4399 }
4400
4401 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4402 final int oldStatus = message.getStatus();
4403 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4404 return;
4405 }
4406 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4407 return;
4408 }
4409 message.setErrorMessage(errorMessage);
4410 message.setStatus(status);
4411 databaseBackend.updateMessage(message, includeBody);
4412 updateConversationUi();
4413 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4414 mNotificationService.pushFailedDelivery(message);
4415 }
4416 }
4417
4418 public SharedPreferences getPreferences() {
4419 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4420 }
4421
4422 public long getAutomaticMessageDeletionDate() {
4423 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4424 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4425 }
4426
4427 public long getLongPreference(String name, @IntegerRes int res) {
4428 long defaultValue = getResources().getInteger(res);
4429 try {
4430 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4431 } catch (NumberFormatException e) {
4432 return defaultValue;
4433 }
4434 }
4435
4436 public boolean getBooleanPreference(String name, @BoolRes int res) {
4437 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4438 }
4439
4440 public boolean confirmMessages() {
4441 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4442 }
4443
4444 public boolean allowMessageCorrection() {
4445 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4446 }
4447
4448 public boolean sendChatStates() {
4449 return getBooleanPreference("chat_states", R.bool.chat_states);
4450 }
4451
4452 private boolean synchronizeWithBookmarks() {
4453 return getBooleanPreference("autojoin", R.bool.autojoin);
4454 }
4455
4456 public boolean useTorToConnect() {
4457 return getBooleanPreference("use_tor", R.bool.use_tor);
4458 }
4459
4460 public boolean showExtendedConnectionOptions() {
4461 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4462 }
4463
4464 public boolean broadcastLastActivity() {
4465 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4466 }
4467
4468 public int unreadCount() {
4469 int count = 0;
4470 for (Conversation conversation : getConversations()) {
4471 count += conversation.unreadCount();
4472 }
4473 return count;
4474 }
4475
4476
4477 private <T> List<T> threadSafeList(Set<T> set) {
4478 synchronized (LISTENER_LOCK) {
4479 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4480 }
4481 }
4482
4483 public void showErrorToastInUi(int resId) {
4484 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4485 listener.onShowErrorToast(resId);
4486 }
4487 }
4488
4489 public void updateConversationUi() {
4490 updateConversationUi(false);
4491 }
4492
4493 public void updateConversationUi(boolean newCaps) {
4494 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4495 listener.onConversationUpdate(newCaps);
4496 }
4497 }
4498
4499 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4500 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4501 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4502 }
4503 }
4504
4505 public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4506 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4507 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4508 }
4509 }
4510
4511 public void updateAccountUi() {
4512 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4513 listener.onAccountUpdate();
4514 }
4515 }
4516
4517 public void updateRosterUi() {
4518 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4519 listener.onRosterUpdate();
4520 }
4521 }
4522
4523 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4524 if (mOnCaptchaRequested.size() > 0) {
4525 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4526 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4527 (int) (captcha.getHeight() * metrics.scaledDensity), false);
4528 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4529 listener.onCaptchaRequested(account, id, data, scaled);
4530 }
4531 return true;
4532 }
4533 return false;
4534 }
4535
4536 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4537 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4538 listener.OnUpdateBlocklist(status);
4539 }
4540 }
4541
4542 public void updateMucRosterUi() {
4543 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4544 listener.onMucRosterUpdate();
4545 }
4546 }
4547
4548 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4549 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4550 listener.onKeyStatusUpdated(report);
4551 }
4552 }
4553
4554 public Account findAccountByJid(final Jid jid) {
4555 for (final Account account : this.accounts) {
4556 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4557 return account;
4558 }
4559 }
4560 return null;
4561 }
4562
4563 public Account findAccountByUuid(final String uuid) {
4564 for (Account account : this.accounts) {
4565 if (account.getUuid().equals(uuid)) {
4566 return account;
4567 }
4568 }
4569 return null;
4570 }
4571
4572 public Conversation findConversationByUuid(String uuid) {
4573 for (Conversation conversation : getConversations()) {
4574 if (conversation.getUuid().equals(uuid)) {
4575 return conversation;
4576 }
4577 }
4578 return null;
4579 }
4580
4581 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4582 List<Conversation> findings = new ArrayList<>();
4583 for (Conversation c : getConversations()) {
4584 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid().asBareJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4585 findings.add(c);
4586 }
4587 }
4588 return findings.size() == 1 ? findings.get(0) : null;
4589 }
4590
4591 public boolean markRead(final Conversation conversation, boolean dismiss) {
4592 return markRead(conversation, null, dismiss).size() > 0;
4593 }
4594
4595 public void markRead(final Conversation conversation) {
4596 markRead(conversation, null, true);
4597 }
4598
4599 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4600 if (dismiss) {
4601 mNotificationService.clear(conversation);
4602 }
4603 final List<Message> readMessages = conversation.markRead(upToUuid);
4604 if (readMessages.size() > 0) {
4605 Runnable runnable = () -> {
4606 for (Message message : readMessages) {
4607 databaseBackend.updateMessage(message, false);
4608 }
4609 };
4610 mDatabaseWriterExecutor.execute(runnable);
4611 updateConversationUi();
4612 updateUnreadCountBadge();
4613 return readMessages;
4614 } else {
4615 return readMessages;
4616 }
4617 }
4618
4619 public synchronized void updateUnreadCountBadge() {
4620 int count = unreadCount();
4621 if (unreadCount != count) {
4622 Log.d(Config.LOGTAG, "update unread count to " + count);
4623 if (count > 0) {
4624 ShortcutBadger.applyCount(getApplicationContext(), count);
4625 } else {
4626 ShortcutBadger.removeCount(getApplicationContext());
4627 }
4628 unreadCount = count;
4629 }
4630 }
4631
4632 public void sendReadMarker(final Conversation conversation, String upToUuid) {
4633 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4634 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4635 if (readMessages.size() > 0) {
4636 updateConversationUi();
4637 }
4638 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4639 if (confirmMessages()
4640 && markable != null
4641 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4642 && markable.getRemoteMsgId() != null) {
4643 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4644 final Account account = conversation.getAccount();
4645 final MessagePacket packet = mMessageGenerator.confirm(markable);
4646 this.sendMessagePacket(account, packet);
4647 }
4648 }
4649
4650 public MemorizingTrustManager getMemorizingTrustManager() {
4651 return this.mMemorizingTrustManager;
4652 }
4653
4654 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4655 this.mMemorizingTrustManager = trustManager;
4656 }
4657
4658 public void updateMemorizingTrustmanager() {
4659 final MemorizingTrustManager tm;
4660 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4661 if (dontTrustSystemCAs) {
4662 tm = new MemorizingTrustManager(getApplicationContext(), null);
4663 } else {
4664 tm = new MemorizingTrustManager(getApplicationContext());
4665 }
4666 setMemorizingTrustManager(tm);
4667 }
4668
4669 public LruCache<String, Drawable> getDrawableCache() {
4670 return this.mDrawableCache;
4671 }
4672
4673 public Collection<String> getKnownHosts() {
4674 final Set<String> hosts = new HashSet<>();
4675 for (final Account account : getAccounts()) {
4676 hosts.add(account.getServer());
4677 for (final Contact contact : account.getRoster().getContacts()) {
4678 if (contact.showInRoster()) {
4679 final String server = contact.getServer();
4680 if (server != null) {
4681 hosts.add(server);
4682 }
4683 }
4684 }
4685 }
4686 if (Config.QUICKSY_DOMAIN != null) {
4687 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4688 }
4689 if (Config.DOMAIN_LOCK != null) {
4690 hosts.add(Config.DOMAIN_LOCK);
4691 }
4692 if (Config.MAGIC_CREATE_DOMAIN != null) {
4693 hosts.add(Config.MAGIC_CREATE_DOMAIN);
4694 }
4695 hosts.add("chat.above.im");
4696 return hosts;
4697 }
4698
4699 public Collection<String> getKnownConferenceHosts() {
4700 final Set<String> mucServers = new HashSet<>();
4701 for (final Account account : accounts) {
4702 if (account.getXmppConnection() != null) {
4703 mucServers.addAll(account.getXmppConnection().getMucServers());
4704 for (final Bookmark bookmark : account.getBookmarks()) {
4705 final Jid jid = bookmark.getJid();
4706 final String s = jid == null ? null : jid.getDomain().toEscapedString();
4707 if (s != null) {
4708 mucServers.add(s);
4709 }
4710 }
4711 }
4712 }
4713 return mucServers;
4714 }
4715
4716 public void sendMessagePacket(Account account, MessagePacket packet) {
4717 final XmppConnection connection = account.getXmppConnection();
4718 if (connection != null) {
4719 connection.sendMessagePacket(packet);
4720 }
4721 }
4722
4723 public void sendPresencePacket(Account account, PresencePacket packet) {
4724 XmppConnection connection = account.getXmppConnection();
4725 if (connection != null) {
4726 connection.sendPresencePacket(packet);
4727 }
4728 }
4729
4730 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4731 final XmppConnection connection = account.getXmppConnection();
4732 if (connection != null) {
4733 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4734 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4735 }
4736 }
4737
4738 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4739 sendIqPacket(account, packet, callback, null);
4740 }
4741
4742 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback, Long timeout) {
4743 final XmppConnection connection = account.getXmppConnection();
4744 if (connection != null) {
4745 connection.sendIqPacket(packet, callback, timeout);
4746 } else if (callback != null) {
4747 callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4748 }
4749 }
4750
4751 public void sendPresence(final Account account) {
4752 sendPresence(account, checkListeners() && broadcastLastActivity());
4753 }
4754
4755 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4756 final Presence.Status status;
4757 if (manuallyChangePresence()) {
4758 status = account.getPresenceStatus();
4759 } else {
4760 status = getTargetPresence();
4761 }
4762 final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4763 if (mLastActivity > 0 && includeIdleTimestamp) {
4764 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4765 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4766 }
4767 sendPresencePacket(account, packet);
4768 }
4769
4770 private void deactivateGracePeriod() {
4771 for (Account account : getAccounts()) {
4772 account.deactivateGracePeriod();
4773 }
4774 }
4775
4776 public void refreshAllPresences() {
4777 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4778 for (Account account : getAccounts()) {
4779 if (account.isEnabled()) {
4780 sendPresence(account, includeIdleTimestamp);
4781 }
4782 }
4783 }
4784
4785 private void refreshAllFcmTokens() {
4786 for (Account account : getAccounts()) {
4787 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4788 mPushManagementService.registerPushTokenOnServer(account);
4789 }
4790 }
4791 }
4792
4793
4794
4795 private void sendOfflinePresence(final Account account) {
4796 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4797 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4798 }
4799
4800 public MessageGenerator getMessageGenerator() {
4801 return this.mMessageGenerator;
4802 }
4803
4804 public PresenceGenerator getPresenceGenerator() {
4805 return this.mPresenceGenerator;
4806 }
4807
4808 public IqGenerator getIqGenerator() {
4809 return this.mIqGenerator;
4810 }
4811
4812 public IqParser getIqParser() {
4813 return this.mIqParser;
4814 }
4815
4816 public JingleConnectionManager getJingleConnectionManager() {
4817 return this.mJingleConnectionManager;
4818 }
4819
4820 public MessageArchiveService getMessageArchiveService() {
4821 return this.mMessageArchiveService;
4822 }
4823
4824 public QuickConversationsService getQuickConversationsService() {
4825 return this.mQuickConversationsService;
4826 }
4827
4828 public List<Contact> findContacts(Jid jid, String accountJid) {
4829 ArrayList<Contact> contacts = new ArrayList<>();
4830 for (Account account : getAccounts()) {
4831 if ((account.isEnabled() || accountJid != null)
4832 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4833 Contact contact = account.getRoster().getContactFromContactList(jid);
4834 if (contact != null) {
4835 contacts.add(contact);
4836 }
4837 }
4838 }
4839 return contacts;
4840 }
4841
4842 public Conversation findFirstMuc(Jid jid) {
4843 for (Conversation conversation : getConversations()) {
4844 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4845 return conversation;
4846 }
4847 }
4848 return null;
4849 }
4850
4851 public NotificationService getNotificationService() {
4852 return this.mNotificationService;
4853 }
4854
4855 public HttpConnectionManager getHttpConnectionManager() {
4856 return this.mHttpConnectionManager;
4857 }
4858
4859 public void resendFailedMessages(final Message message) {
4860 final Collection<Message> messages = new ArrayList<>();
4861 Message current = message;
4862 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4863 messages.add(current);
4864 if (current.mergeable(current.next())) {
4865 current = current.next();
4866 } else {
4867 break;
4868 }
4869 }
4870 for (final Message msg : messages) {
4871 msg.setTime(System.currentTimeMillis());
4872 markMessage(msg, Message.STATUS_WAITING);
4873 this.resendMessage(msg, false);
4874 }
4875 if (message.getConversation() instanceof Conversation) {
4876 ((Conversation) message.getConversation()).sort();
4877 }
4878 updateConversationUi();
4879 }
4880
4881 public void clearConversationHistory(final Conversation conversation) {
4882 final long clearDate;
4883 final String reference;
4884 if (conversation.countMessages() > 0) {
4885 Message latestMessage = conversation.getLatestMessage();
4886 clearDate = latestMessage.getTimeSent() + 1000;
4887 reference = latestMessage.getServerMsgId();
4888 } else {
4889 clearDate = System.currentTimeMillis();
4890 reference = null;
4891 }
4892 conversation.clearMessages();
4893 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4894 conversation.setLastClearHistory(clearDate, reference);
4895 Runnable runnable = () -> {
4896 databaseBackend.deleteMessagesInConversation(conversation);
4897 databaseBackend.updateConversation(conversation);
4898 };
4899 mDatabaseWriterExecutor.execute(runnable);
4900 }
4901
4902 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4903 if (blockable != null && blockable.getBlockedJid() != null) {
4904 final Jid jid = blockable.getBlockedJid();
4905 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4906 if (response.getType() == IqPacket.TYPE.RESULT) {
4907 a.getBlocklist().add(jid);
4908 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4909 }
4910 });
4911 if (blockable.getBlockedJid().isFullJid()) {
4912 return false;
4913 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4914 updateConversationUi();
4915 return true;
4916 } else {
4917 return false;
4918 }
4919 } else {
4920 return false;
4921 }
4922 }
4923
4924 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4925 boolean removed = false;
4926 synchronized (this.conversations) {
4927 boolean domainJid = blockedJid.getLocal() == null;
4928 for (Conversation conversation : this.conversations) {
4929 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4930 || blockedJid.equals(conversation.getJid().asBareJid());
4931 if (conversation.getAccount() == account
4932 && conversation.getMode() == Conversation.MODE_SINGLE
4933 && jidMatches) {
4934 this.conversations.remove(conversation);
4935 markRead(conversation);
4936 conversation.setStatus(Conversation.STATUS_ARCHIVED);
4937 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4938 updateConversation(conversation);
4939 removed = true;
4940 }
4941 }
4942 }
4943 return removed;
4944 }
4945
4946 public void sendUnblockRequest(final Blockable blockable) {
4947 if (blockable != null && blockable.getJid() != null) {
4948 final Jid jid = blockable.getBlockedJid();
4949 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4950 @Override
4951 public void onIqPacketReceived(final Account account, final IqPacket packet) {
4952 if (packet.getType() == IqPacket.TYPE.RESULT) {
4953 account.getBlocklist().remove(jid);
4954 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4955 }
4956 }
4957 });
4958 }
4959 }
4960
4961 public void publishDisplayName(Account account) {
4962 String displayName = account.getDisplayName();
4963 final IqPacket request;
4964 if (TextUtils.isEmpty(displayName)) {
4965 request = mIqGenerator.deleteNode(Namespace.NICK);
4966 } else {
4967 request = mIqGenerator.publishNick(displayName);
4968 }
4969 mAvatarService.clear(account);
4970 sendIqPacket(account, request, (account1, packet) -> {
4971 if (packet.getType() == IqPacket.TYPE.ERROR) {
4972 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet);
4973 }
4974 });
4975 }
4976
4977 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4978 ServiceDiscoveryResult result = discoCache.get(key);
4979 if (result != null) {
4980 return result;
4981 } else {
4982 if (key.first == null || key.second == null) return null;
4983 result = databaseBackend.findDiscoveryResult(key.first, key.second);
4984 if (result != null) {
4985 discoCache.put(key, result);
4986 }
4987 return result;
4988 }
4989 }
4990
4991 public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
4992 IqPacket request = new IqPacket(input == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
4993 request.setTo(jid);
4994 Element query = request.query("jabber:iq:gateway");
4995 if (input != null) {
4996 Element prompt = query.addChild("prompt");
4997 prompt.setContent(input);
4998 }
4999 sendIqPacket(account, request, (Account acct, IqPacket packet) -> {
5000 if (packet.getType() == IqPacket.TYPE.RESULT) {
5001 callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
5002 } else {
5003 Element error = packet.findChild("error");
5004 callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
5005 }
5006 });
5007 }
5008
5009 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
5010 fetchCaps(account, jid, presence, null);
5011 }
5012
5013 public void fetchCaps(Account account, final Jid jid, final Presence presence, Runnable cb) {
5014 final Pair<String, String> key = presence == null ? null : new Pair<>(presence.getHash(), presence.getVer());
5015 final ServiceDiscoveryResult disco = key == null ? null : getCachedServiceDiscoveryResult(key);
5016
5017 if (disco != null) {
5018 presence.setServiceDiscoveryResult(disco);
5019 final Contact contact = account.getRoster().getContact(jid);
5020 if (contact.refreshRtpCapability()) {
5021 syncRoster(account);
5022 }
5023 if (disco.hasIdentity("gateway", "pstn")) {
5024 contact.registerAsPhoneAccount(this);
5025 mQuickConversationsService.considerSyncBackground(false);
5026 }
5027 updateConversationUi(true);
5028 } else {
5029 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5030 request.setTo(jid);
5031 final String node = presence == null ? null : presence.getNode();
5032 final String ver = presence == null ? null : presence.getVer();
5033 final Element query = request.query(Namespace.DISCO_INFO);
5034 if (node != null && ver != null) {
5035 query.setAttribute("node", node + "#" + ver);
5036 }
5037 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + (key == null ? "" : key.second) + " to " + jid);
5038 sendIqPacket(account, request, (a, response) -> {
5039 if (response.getType() == IqPacket.TYPE.RESULT) {
5040 final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
5041 if (presence == null || presence.getVer() == null || presence.getVer().equals(discoveryResult.getVer())) {
5042 databaseBackend.insertDiscoveryResult(discoveryResult);
5043 injectServiceDiscoveryResult(a.getRoster(), presence == null ? null : presence.getHash(), presence == null ? null : presence.getVer(), jid.getResource(), discoveryResult);
5044 if (discoveryResult.hasIdentity("gateway", "pstn")) {
5045 final Contact contact = account.getRoster().getContact(jid);
5046 contact.registerAsPhoneAccount(this);
5047 mQuickConversationsService.considerSyncBackground(false);
5048 }
5049 updateConversationUi(true);
5050 if (cb != null) cb.run();
5051 } else {
5052 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
5053 }
5054 } else {
5055 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
5056 }
5057 });
5058 }
5059 }
5060
5061 public void fetchCommands(Account account, final Jid jid, OnIqPacketReceived callback) {
5062 final IqPacket request = mIqGenerator.queryDiscoItems(jid, "http://jabber.org/protocol/commands");
5063 sendIqPacket(account, request, callback);
5064 }
5065
5066 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, String resource, ServiceDiscoveryResult disco) {
5067 boolean rosterNeedsSync = false;
5068 for (final Contact contact : roster.getContacts()) {
5069 boolean serviceDiscoverySet = false;
5070 Presence onePresence = contact.getPresences().get(resource == null ? "" : resource);
5071 if (onePresence != null) {
5072 onePresence.setServiceDiscoveryResult(disco);
5073 serviceDiscoverySet = true;
5074 } else if (resource == null && hash == null && ver == null) {
5075 Presence p = new Presence(Presence.Status.OFFLINE, null, null, null, "");
5076 p.setServiceDiscoveryResult(disco);
5077 contact.updatePresence("", p);
5078 serviceDiscoverySet = true;
5079 }
5080 if (hash != null && ver != null) {
5081 for (final Presence presence : contact.getPresences().getPresences()) {
5082 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
5083 presence.setServiceDiscoveryResult(disco);
5084 serviceDiscoverySet = true;
5085 }
5086 }
5087 }
5088 if (serviceDiscoverySet) {
5089 rosterNeedsSync |= contact.refreshRtpCapability();
5090 }
5091 }
5092 if (rosterNeedsSync) {
5093 syncRoster(roster.getAccount());
5094 }
5095 }
5096
5097 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
5098 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5099 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5100 request.addChild("prefs", version.namespace);
5101 sendIqPacket(account, request, (account1, packet) -> {
5102 Element prefs = packet.findChild("prefs", version.namespace);
5103 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
5104 callback.onPreferencesFetched(prefs);
5105 } else {
5106 callback.onPreferencesFetchFailed();
5107 }
5108 });
5109 }
5110
5111 public PushManagementService getPushManagementService() {
5112 return mPushManagementService;
5113 }
5114
5115 public void changeStatus(Account account, PresenceTemplate template, String signature) {
5116 if (!template.getStatusMessage().isEmpty()) {
5117 databaseBackend.insertPresenceTemplate(template);
5118 }
5119 account.setPgpSignature(signature);
5120 account.setPresenceStatus(template.getStatus());
5121 account.setPresenceStatusMessage(template.getStatusMessage());
5122 databaseBackend.updateAccount(account);
5123 sendPresence(account);
5124 }
5125
5126 public List<PresenceTemplate> getPresenceTemplates(Account account) {
5127 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5128 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5129 if (!templates.contains(template)) {
5130 templates.add(0, template);
5131 }
5132 }
5133 return templates;
5134 }
5135
5136 public void saveConversationAsBookmark(Conversation conversation, String name) {
5137 final Account account = conversation.getAccount();
5138 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5139 String nick = conversation.getMucOptions().getActualNick();
5140 if (nick == null) nick = conversation.getJid().getResource();
5141 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5142 bookmark.setNick(nick);
5143 }
5144 if (!TextUtils.isEmpty(name)) {
5145 bookmark.setBookmarkName(name);
5146 }
5147 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
5148 createBookmark(account, bookmark);
5149 bookmark.setConversation(conversation);
5150 }
5151
5152 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5153 boolean performedVerification = false;
5154 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5155 for (XmppUri.Fingerprint fp : fingerprints) {
5156 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5157 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5158 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5159 if (fingerprintStatus != null) {
5160 if (!fingerprintStatus.isVerified()) {
5161 performedVerification = true;
5162 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5163 }
5164 } else {
5165 axolotlService.preVerifyFingerprint(contact, fingerprint);
5166 }
5167 }
5168 }
5169 return performedVerification;
5170 }
5171
5172 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5173 final AxolotlService axolotlService = account.getAxolotlService();
5174 boolean verifiedSomething = false;
5175 for (XmppUri.Fingerprint fp : fingerprints) {
5176 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5177 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5178 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5179 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5180 if (fingerprintStatus != null) {
5181 if (!fingerprintStatus.isVerified()) {
5182 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5183 verifiedSomething = true;
5184 }
5185 } else {
5186 axolotlService.preVerifyFingerprint(account, fingerprint);
5187 verifiedSomething = true;
5188 }
5189 }
5190 }
5191 return verifiedSomething;
5192 }
5193
5194 public boolean blindTrustBeforeVerification() {
5195 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
5196 }
5197
5198 public ShortcutService getShortcutService() {
5199 return mShortcutService;
5200 }
5201
5202 public void pushMamPreferences(Account account, Element prefs) {
5203 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
5204 set.addChild(prefs);
5205 sendIqPacket(account, set, null);
5206 }
5207
5208 public void evictPreview(File f) {
5209 if (mDrawableCache.remove(f.getAbsolutePath()) != null) {
5210 Log.d(Config.LOGTAG, "deleted cached preview");
5211 }
5212 }
5213
5214 public void evictPreview(String uuid) {
5215 if (mDrawableCache.remove(uuid) != null) {
5216 Log.d(Config.LOGTAG, "deleted cached preview");
5217 }
5218 }
5219
5220 public interface OnMamPreferencesFetched {
5221 void onPreferencesFetched(Element prefs);
5222
5223 void onPreferencesFetchFailed();
5224 }
5225
5226 public interface OnAccountCreated {
5227 void onAccountCreated(Account account);
5228
5229 void informUser(int r);
5230 }
5231
5232 public interface OnMoreMessagesLoaded {
5233 void onMoreMessagesLoaded(int count, Conversation conversation);
5234
5235 void informUser(int r);
5236 }
5237
5238 public interface OnAccountPasswordChanged {
5239 void onPasswordChangeSucceeded();
5240
5241 void onPasswordChangeFailed();
5242 }
5243
5244 public interface OnRoomDestroy {
5245 void onRoomDestroySucceeded();
5246
5247 void onRoomDestroyFailed();
5248 }
5249
5250 public interface OnAffiliationChanged {
5251 void onAffiliationChangedSuccessful(Jid jid);
5252
5253 void onAffiliationChangeFailed(Jid jid, int resId);
5254 }
5255
5256 public interface OnConversationUpdate {
5257 default void onConversationUpdate() { onConversationUpdate(false); }
5258 default void onConversationUpdate(boolean newCaps) { onConversationUpdate(); }
5259 }
5260
5261 public interface OnJingleRtpConnectionUpdate {
5262 void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5263
5264 void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
5265 }
5266
5267 public interface OnAccountUpdate {
5268 void onAccountUpdate();
5269 }
5270
5271 public interface OnCaptchaRequested {
5272 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5273 }
5274
5275 public interface OnRosterUpdate {
5276 void onRosterUpdate();
5277 }
5278
5279 public interface OnMucRosterUpdate {
5280 void onMucRosterUpdate();
5281 }
5282
5283 public interface OnConferenceConfigurationFetched {
5284 void onConferenceConfigurationFetched(Conversation conversation);
5285
5286 void onFetchFailed(Conversation conversation, String errorCondition);
5287 }
5288
5289 public interface OnConferenceJoined {
5290 void onConferenceJoined(Conversation conversation);
5291 }
5292
5293 public interface OnConfigurationPushed {
5294 void onPushSucceeded();
5295
5296 void onPushFailed();
5297 }
5298
5299 public interface OnShowErrorToast {
5300 void onShowErrorToast(int resId);
5301 }
5302
5303 public class XmppConnectionBinder extends Binder {
5304 public XmppConnectionService getService() {
5305 return XmppConnectionService.this;
5306 }
5307 }
5308
5309 private class InternalEventReceiver extends BroadcastReceiver {
5310
5311 @Override
5312 public void onReceive(Context context, Intent intent) {
5313 onStartCommand(intent, 0, 0);
5314 }
5315 }
5316
5317 public static class OngoingCall {
5318 public final AbstractJingleConnection.Id id;
5319 public final Set<Media> media;
5320 public final boolean reconnecting;
5321
5322 public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5323 this.id = id;
5324 this.media = media;
5325 this.reconnecting = reconnecting;
5326 }
5327
5328 @Override
5329 public boolean equals(Object o) {
5330 if (this == o) return true;
5331 if (o == null || getClass() != o.getClass()) return false;
5332 OngoingCall that = (OngoingCall) o;
5333 return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
5334 }
5335
5336 @Override
5337 public int hashCode() {
5338 return Objects.hashCode(id, media, reconnecting);
5339 }
5340 }
5341
5342 public static class BlockedMediaException extends Exception { }
5343}