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