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