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