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