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