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