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