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