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