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