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