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