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