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