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