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