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