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