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