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