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