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 ArrayList<Conversation> results = new ArrayList<>();
1964 for (final Conversation c : conversations) {
1965 if (c.getMode() == Conversation.MODE_MULTI && (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || c.getMucOptions().isContactInRoom(contact))) {
1966 results.add(c);
1967 }
1968 }
1969 return results;
1970 }
1971
1972 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1973 for (final Conversation conversation : haystack) {
1974 if (conversation.getContact() == contact) {
1975 return conversation;
1976 }
1977 }
1978 return null;
1979 }
1980
1981 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1982 if (jid == null) {
1983 return null;
1984 }
1985 for (final Conversation conversation : haystack) {
1986 if ((account == null || conversation.getAccount() == account)
1987 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
1988 return conversation;
1989 }
1990 }
1991 return null;
1992 }
1993
1994 public boolean isConversationsListEmpty(final Conversation ignore) {
1995 synchronized (this.conversations) {
1996 final int size = this.conversations.size();
1997 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
1998 }
1999 }
2000
2001 public boolean isConversationStillOpen(final Conversation conversation) {
2002 synchronized (this.conversations) {
2003 for (Conversation current : this.conversations) {
2004 if (current == conversation) {
2005 return true;
2006 }
2007 }
2008 }
2009 return false;
2010 }
2011
2012 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2013 return this.findOrCreateConversation(account, jid, muc, false, async);
2014 }
2015
2016 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2017 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2018 }
2019
2020 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2021 synchronized (this.conversations) {
2022 Conversation conversation = find(account, jid);
2023 if (conversation != null) {
2024 return conversation;
2025 }
2026 conversation = databaseBackend.findConversation(account, jid);
2027 final boolean loadMessagesFromDb;
2028 if (conversation != null) {
2029 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2030 conversation.setAccount(account);
2031 if (muc) {
2032 conversation.setMode(Conversation.MODE_MULTI);
2033 conversation.setContactJid(jid);
2034 } else {
2035 conversation.setMode(Conversation.MODE_SINGLE);
2036 conversation.setContactJid(jid.asBareJid());
2037 }
2038 databaseBackend.updateConversation(conversation);
2039 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2040 } else {
2041 String conversationName;
2042 Contact contact = account.getRoster().getContact(jid);
2043 if (contact != null) {
2044 conversationName = contact.getDisplayName();
2045 } else {
2046 conversationName = jid.getLocal();
2047 }
2048 if (muc) {
2049 conversation = new Conversation(conversationName, account, jid,
2050 Conversation.MODE_MULTI);
2051 } else {
2052 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2053 Conversation.MODE_SINGLE);
2054 }
2055 this.databaseBackend.createConversation(conversation);
2056 loadMessagesFromDb = false;
2057 }
2058 final Conversation c = conversation;
2059 final Runnable runnable = () -> {
2060 if (loadMessagesFromDb) {
2061 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2062 updateConversationUi();
2063 c.messagesLoaded.set(true);
2064 }
2065 if (account.getXmppConnection() != null
2066 && !c.getContact().isBlocked()
2067 && account.getXmppConnection().getFeatures().mam()
2068 && !muc) {
2069 if (query == null) {
2070 mMessageArchiveService.query(c);
2071 } else {
2072 if (query.getConversation() == null) {
2073 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2074 }
2075 }
2076 }
2077 if (joinAfterCreate) {
2078 joinMuc(c);
2079 }
2080 };
2081 if (async) {
2082 mDatabaseReaderExecutor.execute(runnable);
2083 } else {
2084 runnable.run();
2085 }
2086 this.conversations.add(conversation);
2087 updateConversationUi();
2088 return conversation;
2089 }
2090 }
2091
2092 public void archiveConversation(Conversation conversation) {
2093 archiveConversation(conversation, true);
2094 }
2095
2096 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2097 getNotificationService().clear(conversation);
2098 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2099 conversation.setNextMessage(null);
2100 synchronized (this.conversations) {
2101 getMessageArchiveService().kill(conversation);
2102 if (conversation.getMode() == Conversation.MODE_MULTI) {
2103 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2104 final Bookmark bookmark = conversation.getBookmark();
2105 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2106 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2107 Account account = bookmark.getAccount();
2108 bookmark.setConversation(null);
2109 deleteBookmark(account, bookmark);
2110 } else if (bookmark.autojoin()) {
2111 bookmark.setAutojoin(false);
2112 createBookmark(bookmark.getAccount(), bookmark);
2113 }
2114 }
2115 }
2116 if (conversation.getMucOptions().push()) {
2117 disableDirectMucPush(conversation);
2118 mPushManagementService.disablePushOnServer(conversation);
2119 }
2120 leaveMuc(conversation);
2121 } else {
2122 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2123 stopPresenceUpdatesTo(conversation.getContact());
2124 }
2125 }
2126 updateConversation(conversation);
2127 this.conversations.remove(conversation);
2128 updateConversationUi();
2129 }
2130 }
2131
2132 public void stopPresenceUpdatesTo(Contact contact) {
2133 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2134 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2135 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2136 }
2137
2138 public void createAccount(final Account account) {
2139 account.initAccountServices(this);
2140 databaseBackend.createAccount(account);
2141 this.accounts.add(account);
2142 this.reconnectAccountInBackground(account);
2143 updateAccountUi();
2144 syncEnabledAccountSetting();
2145 toggleForegroundService();
2146 }
2147
2148 private void syncEnabledAccountSetting() {
2149 final boolean hasEnabledAccounts = hasEnabledAccounts();
2150 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2151 toggleSetProfilePictureActivity(hasEnabledAccounts);
2152 }
2153
2154 private void toggleSetProfilePictureActivity(final boolean enabled) {
2155 try {
2156 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2157 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2158 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2159 } catch (IllegalStateException e) {
2160 Log.d(Config.LOGTAG, "unable to toggle profile picture actvitiy");
2161 }
2162 }
2163
2164 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2165 new Thread(() -> {
2166 try {
2167 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2168 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2169 if (cert == null) {
2170 callback.informUser(R.string.unable_to_parse_certificate);
2171 return;
2172 }
2173 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2174 if (info == null) {
2175 callback.informUser(R.string.certificate_does_not_contain_jid);
2176 return;
2177 }
2178 if (findAccountByJid(info.first) == null) {
2179 Account account = new Account(info.first, "");
2180 account.setPrivateKeyAlias(alias);
2181 account.setOption(Account.OPTION_DISABLED, true);
2182 account.setDisplayName(info.second);
2183 createAccount(account);
2184 callback.onAccountCreated(account);
2185 if (Config.X509_VERIFICATION) {
2186 try {
2187 getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
2188 } catch (CertificateException e) {
2189 callback.informUser(R.string.certificate_chain_is_not_trusted);
2190 }
2191 }
2192 } else {
2193 callback.informUser(R.string.account_already_exists);
2194 }
2195 } catch (Exception e) {
2196 e.printStackTrace();
2197 callback.informUser(R.string.unable_to_parse_certificate);
2198 }
2199 }).start();
2200
2201 }
2202
2203 public void updateKeyInAccount(final Account account, final String alias) {
2204 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2205 try {
2206 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2207 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2208 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2209 if (info == null) {
2210 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2211 return;
2212 }
2213 if (account.getJid().asBareJid().equals(info.first)) {
2214 account.setPrivateKeyAlias(alias);
2215 account.setDisplayName(info.second);
2216 databaseBackend.updateAccount(account);
2217 if (Config.X509_VERIFICATION) {
2218 try {
2219 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2220 } catch (CertificateException e) {
2221 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2222 }
2223 account.getAxolotlService().regenerateKeys(true);
2224 }
2225 } else {
2226 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2227 }
2228 } catch (Exception e) {
2229 e.printStackTrace();
2230 }
2231 }
2232
2233 public boolean updateAccount(final Account account) {
2234 if (databaseBackend.updateAccount(account)) {
2235 account.setShowErrorNotification(true);
2236 this.statusListener.onStatusChanged(account);
2237 databaseBackend.updateAccount(account);
2238 reconnectAccountInBackground(account);
2239 updateAccountUi();
2240 getNotificationService().updateErrorNotification();
2241 toggleForegroundService();
2242 syncEnabledAccountSetting();
2243 return true;
2244 } else {
2245 return false;
2246 }
2247 }
2248
2249 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2250 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2251 sendIqPacket(account, iq, (a, packet) -> {
2252 if (packet.getType() == IqPacket.TYPE.RESULT) {
2253 a.setPassword(newPassword);
2254 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2255 databaseBackend.updateAccount(a);
2256 callback.onPasswordChangeSucceeded();
2257 } else {
2258 callback.onPasswordChangeFailed();
2259 }
2260 });
2261 }
2262
2263 public void deleteAccount(final Account account) {
2264 final boolean connected = account.getStatus() == Account.State.ONLINE;
2265 synchronized (this.conversations) {
2266 if (connected) {
2267 account.getAxolotlService().deleteOmemoIdentity();
2268 }
2269 for (final Conversation conversation : conversations) {
2270 if (conversation.getAccount() == account) {
2271 if (conversation.getMode() == Conversation.MODE_MULTI) {
2272 if (connected) {
2273 leaveMuc(conversation);
2274 }
2275 }
2276 conversations.remove(conversation);
2277 mNotificationService.clear(conversation);
2278 }
2279 }
2280 if (account.getXmppConnection() != null) {
2281 new Thread(() -> disconnect(account, !connected)).start();
2282 }
2283 final Runnable runnable = () -> {
2284 if (!databaseBackend.deleteAccount(account)) {
2285 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2286 }
2287 };
2288 mDatabaseWriterExecutor.execute(runnable);
2289 this.accounts.remove(account);
2290 this.mRosterSyncTaskManager.clear(account);
2291 updateAccountUi();
2292 mNotificationService.updateErrorNotification();
2293 syncEnabledAccountSetting();
2294 toggleForegroundService();
2295 }
2296 }
2297
2298 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2299 final boolean remainingListeners;
2300 synchronized (LISTENER_LOCK) {
2301 remainingListeners = checkListeners();
2302 if (!this.mOnConversationUpdates.add(listener)) {
2303 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2304 }
2305 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2306 }
2307 if (remainingListeners) {
2308 switchToForeground();
2309 }
2310 }
2311
2312 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2313 final boolean remainingListeners;
2314 synchronized (LISTENER_LOCK) {
2315 this.mOnConversationUpdates.remove(listener);
2316 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2317 remainingListeners = checkListeners();
2318 }
2319 if (remainingListeners) {
2320 switchToBackground();
2321 }
2322 }
2323
2324 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2325 final boolean remainingListeners;
2326 synchronized (LISTENER_LOCK) {
2327 remainingListeners = checkListeners();
2328 if (!this.mOnShowErrorToasts.add(listener)) {
2329 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2330 }
2331 }
2332 if (remainingListeners) {
2333 switchToForeground();
2334 }
2335 }
2336
2337 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2338 final boolean remainingListeners;
2339 synchronized (LISTENER_LOCK) {
2340 this.mOnShowErrorToasts.remove(onShowErrorToast);
2341 remainingListeners = checkListeners();
2342 }
2343 if (remainingListeners) {
2344 switchToBackground();
2345 }
2346 }
2347
2348 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2349 final boolean remainingListeners;
2350 synchronized (LISTENER_LOCK) {
2351 remainingListeners = checkListeners();
2352 if (!this.mOnAccountUpdates.add(listener)) {
2353 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2354 }
2355 }
2356 if (remainingListeners) {
2357 switchToForeground();
2358 }
2359 }
2360
2361 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2362 final boolean remainingListeners;
2363 synchronized (LISTENER_LOCK) {
2364 this.mOnAccountUpdates.remove(listener);
2365 remainingListeners = checkListeners();
2366 }
2367 if (remainingListeners) {
2368 switchToBackground();
2369 }
2370 }
2371
2372 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2373 final boolean remainingListeners;
2374 synchronized (LISTENER_LOCK) {
2375 remainingListeners = checkListeners();
2376 if (!this.mOnCaptchaRequested.add(listener)) {
2377 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2378 }
2379 }
2380 if (remainingListeners) {
2381 switchToForeground();
2382 }
2383 }
2384
2385 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2386 final boolean remainingListeners;
2387 synchronized (LISTENER_LOCK) {
2388 this.mOnCaptchaRequested.remove(listener);
2389 remainingListeners = checkListeners();
2390 }
2391 if (remainingListeners) {
2392 switchToBackground();
2393 }
2394 }
2395
2396 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2397 final boolean remainingListeners;
2398 synchronized (LISTENER_LOCK) {
2399 remainingListeners = checkListeners();
2400 if (!this.mOnRosterUpdates.add(listener)) {
2401 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2402 }
2403 }
2404 if (remainingListeners) {
2405 switchToForeground();
2406 }
2407 }
2408
2409 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2410 final boolean remainingListeners;
2411 synchronized (LISTENER_LOCK) {
2412 this.mOnRosterUpdates.remove(listener);
2413 remainingListeners = checkListeners();
2414 }
2415 if (remainingListeners) {
2416 switchToBackground();
2417 }
2418 }
2419
2420 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2421 final boolean remainingListeners;
2422 synchronized (LISTENER_LOCK) {
2423 remainingListeners = checkListeners();
2424 if (!this.mOnUpdateBlocklist.add(listener)) {
2425 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2426 }
2427 }
2428 if (remainingListeners) {
2429 switchToForeground();
2430 }
2431 }
2432
2433 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2434 final boolean remainingListeners;
2435 synchronized (LISTENER_LOCK) {
2436 this.mOnUpdateBlocklist.remove(listener);
2437 remainingListeners = checkListeners();
2438 }
2439 if (remainingListeners) {
2440 switchToBackground();
2441 }
2442 }
2443
2444 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2445 final boolean remainingListeners;
2446 synchronized (LISTENER_LOCK) {
2447 remainingListeners = checkListeners();
2448 if (!this.mOnKeyStatusUpdated.add(listener)) {
2449 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2450 }
2451 }
2452 if (remainingListeners) {
2453 switchToForeground();
2454 }
2455 }
2456
2457 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2458 final boolean remainingListeners;
2459 synchronized (LISTENER_LOCK) {
2460 this.mOnKeyStatusUpdated.remove(listener);
2461 remainingListeners = checkListeners();
2462 }
2463 if (remainingListeners) {
2464 switchToBackground();
2465 }
2466 }
2467
2468 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2469 final boolean remainingListeners;
2470 synchronized (LISTENER_LOCK) {
2471 remainingListeners = checkListeners();
2472 if (!this.mOnMucRosterUpdate.add(listener)) {
2473 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2474 }
2475 }
2476 if (remainingListeners) {
2477 switchToForeground();
2478 }
2479 }
2480
2481 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2482 final boolean remainingListeners;
2483 synchronized (LISTENER_LOCK) {
2484 this.mOnMucRosterUpdate.remove(listener);
2485 remainingListeners = checkListeners();
2486 }
2487 if (remainingListeners) {
2488 switchToBackground();
2489 }
2490 }
2491
2492 public boolean checkListeners() {
2493 return (this.mOnAccountUpdates.size() == 0
2494 && this.mOnConversationUpdates.size() == 0
2495 && this.mOnRosterUpdates.size() == 0
2496 && this.mOnCaptchaRequested.size() == 0
2497 && this.mOnMucRosterUpdate.size() == 0
2498 && this.mOnUpdateBlocklist.size() == 0
2499 && this.mOnShowErrorToasts.size() == 0
2500 && this.mOnKeyStatusUpdated.size() == 0);
2501 }
2502
2503 private void switchToForeground() {
2504 final boolean broadcastLastActivity = broadcastLastActivity();
2505 for (Conversation conversation : getConversations()) {
2506 if (conversation.getMode() == Conversation.MODE_MULTI) {
2507 conversation.getMucOptions().resetChatState();
2508 } else {
2509 conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2510 }
2511 }
2512 for (Account account : getAccounts()) {
2513 if (account.getStatus() == Account.State.ONLINE) {
2514 account.deactivateGracePeriod();
2515 final XmppConnection connection = account.getXmppConnection();
2516 if (connection != null) {
2517 if (connection.getFeatures().csi()) {
2518 connection.sendActive();
2519 }
2520 if (broadcastLastActivity) {
2521 sendPresence(account, false); //send new presence but don't include idle because we are not
2522 }
2523 }
2524 }
2525 }
2526 Log.d(Config.LOGTAG, "app switched into foreground");
2527 }
2528
2529 private void switchToBackground() {
2530 final boolean broadcastLastActivity = broadcastLastActivity();
2531 if (broadcastLastActivity) {
2532 mLastActivity = System.currentTimeMillis();
2533 final SharedPreferences.Editor editor = getPreferences().edit();
2534 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2535 editor.apply();
2536 }
2537 for (Account account : getAccounts()) {
2538 if (account.getStatus() == Account.State.ONLINE) {
2539 XmppConnection connection = account.getXmppConnection();
2540 if (connection != null) {
2541 if (broadcastLastActivity) {
2542 sendPresence(account, true);
2543 }
2544 if (connection.getFeatures().csi()) {
2545 connection.sendInactive();
2546 }
2547 }
2548 }
2549 }
2550 this.mNotificationService.setIsInForeground(false);
2551 Log.d(Config.LOGTAG, "app switched into background");
2552 }
2553
2554 private void connectMultiModeConversations(Account account) {
2555 List<Conversation> conversations = getConversations();
2556 for (Conversation conversation : conversations) {
2557 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2558 joinMuc(conversation);
2559 }
2560 }
2561 }
2562
2563 public void mucSelfPingAndRejoin(final Conversation conversation) {
2564 final Account account = conversation.getAccount();
2565 synchronized (account.inProgressConferenceJoins) {
2566 if (account.inProgressConferenceJoins.contains(conversation)) {
2567 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2568 return;
2569 }
2570 }
2571 synchronized (account.inProgressConferencePings) {
2572 if (!account.inProgressConferencePings.add(conversation)) {
2573 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
2574 return;
2575 }
2576 }
2577 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2578 final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2579 ping.setTo(self);
2580 ping.addChild("ping", Namespace.PING);
2581 sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2582 if (response.getType() == IqPacket.TYPE.ERROR) {
2583 Element error = response.findChild("error");
2584 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2585 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
2586 } else {
2587 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
2588 joinMuc(conversation);
2589 }
2590 } else if (response.getType() == IqPacket.TYPE.RESULT) {
2591 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
2592 }
2593 synchronized (account.inProgressConferencePings) {
2594 account.inProgressConferencePings.remove(conversation);
2595 }
2596 });
2597 }
2598
2599 public void joinMuc(Conversation conversation) {
2600 joinMuc(conversation, null, false);
2601 }
2602
2603 public void joinMuc(Conversation conversation, boolean followedInvite) {
2604 joinMuc(conversation, null, followedInvite);
2605 }
2606
2607 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2608 joinMuc(conversation, onConferenceJoined, false);
2609 }
2610
2611 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2612 final Account account = conversation.getAccount();
2613 synchronized (account.pendingConferenceJoins) {
2614 account.pendingConferenceJoins.remove(conversation);
2615 }
2616 synchronized (account.pendingConferenceLeaves) {
2617 account.pendingConferenceLeaves.remove(conversation);
2618 }
2619 if (account.getStatus() == Account.State.ONLINE) {
2620 synchronized (account.inProgressConferenceJoins) {
2621 account.inProgressConferenceJoins.add(conversation);
2622 }
2623 if (Config.MUC_LEAVE_BEFORE_JOIN) {
2624 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2625 }
2626 conversation.resetMucOptions();
2627 if (onConferenceJoined != null) {
2628 conversation.getMucOptions().flagNoAutoPushConfiguration();
2629 }
2630 conversation.setHasMessagesLeftOnServer(false);
2631 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2632
2633 private void join(Conversation conversation) {
2634 Account account = conversation.getAccount();
2635 final MucOptions mucOptions = conversation.getMucOptions();
2636
2637 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2638 synchronized (account.inProgressConferenceJoins) {
2639 account.inProgressConferenceJoins.remove(conversation);
2640 }
2641 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2642 updateConversationUi();
2643 if (onConferenceJoined != null) {
2644 onConferenceJoined.onConferenceJoined(conversation);
2645 }
2646 return;
2647 }
2648
2649 final Jid joinJid = mucOptions.getSelf().getFullJid();
2650 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2651 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2652 packet.setTo(joinJid);
2653 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2654 if (conversation.getMucOptions().getPassword() != null) {
2655 x.addChild("password").setContent(mucOptions.getPassword());
2656 }
2657
2658 if (mucOptions.mamSupport()) {
2659 // Use MAM instead of the limited muc history to get history
2660 x.addChild("history").setAttribute("maxchars", "0");
2661 } else {
2662 // Fallback to muc history
2663 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2664 }
2665 sendPresencePacket(account, packet);
2666 if (onConferenceJoined != null) {
2667 onConferenceJoined.onConferenceJoined(conversation);
2668 }
2669 if (!joinJid.equals(conversation.getJid())) {
2670 conversation.setContactJid(joinJid);
2671 databaseBackend.updateConversation(conversation);
2672 }
2673
2674 if (mucOptions.mamSupport()) {
2675 getMessageArchiveService().catchupMUC(conversation);
2676 }
2677 if (mucOptions.isPrivateAndNonAnonymous()) {
2678 fetchConferenceMembers(conversation);
2679
2680 if (followedInvite) {
2681 final Bookmark bookmark = conversation.getBookmark();
2682 if (bookmark != null) {
2683 if (!bookmark.autojoin()) {
2684 bookmark.setAutojoin(true);
2685 createBookmark(account, bookmark);
2686 }
2687 } else {
2688 saveConversationAsBookmark(conversation, null);
2689 }
2690 }
2691 }
2692 if (mucOptions.push()) {
2693 enableMucPush(conversation);
2694 }
2695 synchronized (account.inProgressConferenceJoins) {
2696 account.inProgressConferenceJoins.remove(conversation);
2697 sendUnsentMessages(conversation);
2698 }
2699 }
2700
2701 @Override
2702 public void onConferenceConfigurationFetched(Conversation conversation) {
2703 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2704 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2705 return;
2706 }
2707 join(conversation);
2708 }
2709
2710 @Override
2711 public void onFetchFailed(final Conversation conversation, Element error) {
2712 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2713 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2714
2715 return;
2716 }
2717 if (error != null && "remote-server-not-found".equals(error.getName())) {
2718 synchronized (account.inProgressConferenceJoins) {
2719 account.inProgressConferenceJoins.remove(conversation);
2720 }
2721 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2722 updateConversationUi();
2723 } else {
2724 join(conversation);
2725 fetchConferenceConfiguration(conversation);
2726 }
2727 }
2728 });
2729 updateConversationUi();
2730 } else {
2731 synchronized (account.pendingConferenceJoins) {
2732 account.pendingConferenceJoins.add(conversation);
2733 }
2734 conversation.resetMucOptions();
2735 conversation.setHasMessagesLeftOnServer(false);
2736 updateConversationUi();
2737 }
2738 }
2739
2740 private void enableDirectMucPush(final Conversation conversation) {
2741 final Account account = conversation.getAccount();
2742 final Jid room = conversation.getJid().asBareJid();
2743 final IqPacket enable = mIqGenerator.enablePush(conversation.getAccount().getJid(), conversation.getUuid(), null);
2744 enable.setTo(room);
2745 sendIqPacket(account, enable, (a, response) -> {
2746 if (response.getType() == IqPacket.TYPE.RESULT) {
2747 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": enabled direct push for muc " + room);
2748 } else if (response.getType() == IqPacket.TYPE.ERROR) {
2749 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to enable direct push for muc " + room + " " + response.getError());
2750 }
2751 });
2752 }
2753
2754 private void enableMucPush(final Conversation conversation) {
2755 enableDirectMucPush(conversation);
2756 mPushManagementService.registerPushTokenOnServer(conversation);
2757 }
2758
2759 private void disableDirectMucPush(final Conversation conversation) {
2760 final Account account = conversation.getAccount();
2761 final Jid room = conversation.getJid().asBareJid();
2762 final IqPacket disable = mIqGenerator.disablePush(conversation.getAccount().getJid(), conversation.getUuid());
2763 disable.setTo(room);
2764 sendIqPacket(account, disable, (a, response) -> {
2765 if (response.getType() == IqPacket.TYPE.RESULT) {
2766 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": disabled direct push for muc " + room);
2767 } else if (response.getType() == IqPacket.TYPE.ERROR) {
2768 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to disable direct push for muc " + room + " " + response.getError());
2769 }
2770 });
2771 }
2772
2773 private void fetchConferenceMembers(final Conversation conversation) {
2774 final Account account = conversation.getAccount();
2775 final AxolotlService axolotlService = account.getAxolotlService();
2776 final String[] affiliations = {"member", "admin", "owner"};
2777 OnIqPacketReceived callback = new OnIqPacketReceived() {
2778
2779 private int i = 0;
2780 private boolean success = true;
2781
2782 @Override
2783 public void onIqPacketReceived(Account account, IqPacket packet) {
2784 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2785 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2786 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2787 for (Element child : query.getChildren()) {
2788 if ("item".equals(child.getName())) {
2789 MucOptions.User user = AbstractParser.parseItem(conversation, child);
2790 if (!user.realJidMatchesAccount()) {
2791 boolean isNew = conversation.getMucOptions().updateUser(user);
2792 Contact contact = user.getContact();
2793 if (omemoEnabled
2794 && isNew
2795 && user.getRealJid() != null
2796 && (contact == null || !contact.mutualPresenceSubscription())
2797 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2798 axolotlService.fetchDeviceIds(user.getRealJid());
2799 }
2800 }
2801 }
2802 }
2803 } else {
2804 success = false;
2805 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2806 }
2807 ++i;
2808 if (i >= affiliations.length) {
2809 List<Jid> members = conversation.getMucOptions().getMembers(true);
2810 if (success) {
2811 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2812 boolean changed = false;
2813 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2814 Jid jid = iterator.next();
2815 if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
2816 iterator.remove();
2817 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2818 changed = true;
2819 }
2820 }
2821 if (changed) {
2822 conversation.setAcceptedCryptoTargets(cryptoTargets);
2823 updateConversation(conversation);
2824 }
2825 }
2826 getAvatarService().clear(conversation);
2827 updateMucRosterUi();
2828 updateConversationUi();
2829 }
2830 }
2831 };
2832 for (String affiliation : affiliations) {
2833 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2834 }
2835 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2836 }
2837
2838 public void providePasswordForMuc(Conversation conversation, String password) {
2839 if (conversation.getMode() == Conversation.MODE_MULTI) {
2840 conversation.getMucOptions().setPassword(password);
2841 if (conversation.getBookmark() != null) {
2842 final Bookmark bookmark = conversation.getBookmark();
2843 if (synchronizeWithBookmarks()) {
2844 bookmark.setAutojoin(true);
2845 }
2846 createBookmark(conversation.getAccount(), bookmark);
2847 }
2848 updateConversation(conversation);
2849 joinMuc(conversation);
2850 }
2851 }
2852
2853 private boolean hasEnabledAccounts() {
2854 if (this.accounts == null) {
2855 return false;
2856 }
2857 for (Account account : this.accounts) {
2858 if (account.isEnabled()) {
2859 return true;
2860 }
2861 }
2862 return false;
2863 }
2864
2865
2866 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2867 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2868 }
2869
2870 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2871 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
2872 }
2873
2874
2875 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2876 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2877 }
2878
2879 public void persistSelfNick(MucOptions.User self) {
2880 final Conversation conversation = self.getConversation();
2881 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
2882 Jid full = self.getFullJid();
2883 if (!full.equals(conversation.getJid())) {
2884 Log.d(Config.LOGTAG, "nick changed. updating");
2885 conversation.setContactJid(full);
2886 databaseBackend.updateConversation(conversation);
2887 }
2888
2889 final Bookmark bookmark = conversation.getBookmark();
2890 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
2891 if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
2892 final Account account = conversation.getAccount();
2893 final String defaultNick = MucOptions.defaultNick(account);
2894 if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
2895 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
2896 return;
2897 }
2898 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
2899 bookmark.setNick(full.getResource());
2900 createBookmark(bookmark.getAccount(), bookmark);
2901 }
2902 }
2903
2904 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2905 final MucOptions options = conversation.getMucOptions();
2906 final Jid joinJid = options.createJoinJid(nick);
2907 if (joinJid == null) {
2908 return false;
2909 }
2910 if (options.online()) {
2911 Account account = conversation.getAccount();
2912 options.setOnRenameListener(new OnRenameListener() {
2913
2914 @Override
2915 public void onSuccess() {
2916 callback.success(conversation);
2917 }
2918
2919 @Override
2920 public void onFailure() {
2921 callback.error(R.string.nick_in_use, conversation);
2922 }
2923 });
2924
2925 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
2926 packet.setTo(joinJid);
2927 sendPresencePacket(account, packet);
2928 } else {
2929 conversation.setContactJid(joinJid);
2930 databaseBackend.updateConversation(conversation);
2931 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2932 Bookmark bookmark = conversation.getBookmark();
2933 if (bookmark != null) {
2934 bookmark.setNick(nick);
2935 createBookmark(bookmark.getAccount(), bookmark);
2936 }
2937 joinMuc(conversation);
2938 }
2939 }
2940 return true;
2941 }
2942
2943 public void leaveMuc(Conversation conversation) {
2944 leaveMuc(conversation, false);
2945 }
2946
2947 private void leaveMuc(Conversation conversation, boolean now) {
2948 final Account account = conversation.getAccount();
2949 synchronized (account.pendingConferenceJoins) {
2950 account.pendingConferenceJoins.remove(conversation);
2951 }
2952 synchronized (account.pendingConferenceLeaves) {
2953 account.pendingConferenceLeaves.remove(conversation);
2954 }
2955 if (account.getStatus() == Account.State.ONLINE || now) {
2956 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2957 conversation.getMucOptions().setOffline();
2958 Bookmark bookmark = conversation.getBookmark();
2959 if (bookmark != null) {
2960 bookmark.setConversation(null);
2961 }
2962 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2963 } else {
2964 synchronized (account.pendingConferenceLeaves) {
2965 account.pendingConferenceLeaves.add(conversation);
2966 }
2967 }
2968 }
2969
2970 public String findConferenceServer(final Account account) {
2971 String server;
2972 if (account.getXmppConnection() != null) {
2973 server = account.getXmppConnection().getMucServer();
2974 if (server != null) {
2975 return server;
2976 }
2977 }
2978 for (Account other : getAccounts()) {
2979 if (other != account && other.getXmppConnection() != null) {
2980 server = other.getXmppConnection().getMucServer();
2981 if (server != null) {
2982 return server;
2983 }
2984 }
2985 }
2986 return null;
2987 }
2988
2989
2990 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
2991 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
2992 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
2993 if (!TextUtils.isEmpty(name)) {
2994 configuration.putString("muc#roomconfig_roomname", name);
2995 }
2996 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2997 @Override
2998 public void onPushSucceeded() {
2999 saveConversationAsBookmark(conversation, name);
3000 callback.success(conversation);
3001 }
3002
3003 @Override
3004 public void onPushFailed() {
3005 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3006 callback.error(R.string.unable_to_set_channel_configuration, conversation);
3007 } else {
3008 callback.error(R.string.joined_an_existing_channel, conversation);
3009 }
3010 }
3011 });
3012 });
3013 }
3014
3015 public boolean createAdhocConference(final Account account,
3016 final String name,
3017 final Iterable<Jid> jids,
3018 final UiCallback<Conversation> callback) {
3019 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3020 if (account.getStatus() == Account.State.ONLINE) {
3021 try {
3022 String server = findConferenceServer(account);
3023 if (server == null) {
3024 if (callback != null) {
3025 callback.error(R.string.no_conference_server_found, null);
3026 }
3027 return false;
3028 }
3029 final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
3030 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3031 joinMuc(conversation, new OnConferenceJoined() {
3032 @Override
3033 public void onConferenceJoined(final Conversation conversation) {
3034 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3035 if (!TextUtils.isEmpty(name)) {
3036 configuration.putString("muc#roomconfig_roomname", name);
3037 }
3038 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3039 @Override
3040 public void onPushSucceeded() {
3041 for (Jid invite : jids) {
3042 invite(conversation, invite);
3043 }
3044 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3045 Jid other = account.getJid().withResource(resource);
3046 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3047 directInvite(conversation, other);
3048 }
3049 saveConversationAsBookmark(conversation, name);
3050 if (callback != null) {
3051 callback.success(conversation);
3052 }
3053 }
3054
3055 @Override
3056 public void onPushFailed() {
3057 archiveConversation(conversation);
3058 if (callback != null) {
3059 callback.error(R.string.conference_creation_failed, conversation);
3060 }
3061 }
3062 });
3063 }
3064 });
3065 return true;
3066 } catch (IllegalArgumentException e) {
3067 if (callback != null) {
3068 callback.error(R.string.conference_creation_failed, null);
3069 }
3070 return false;
3071 }
3072 } else {
3073 if (callback != null) {
3074 callback.error(R.string.not_connected_try_again, null);
3075 }
3076 return false;
3077 }
3078 }
3079
3080 public void fetchConferenceConfiguration(final Conversation conversation) {
3081 fetchConferenceConfiguration(conversation, null);
3082 }
3083
3084 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3085 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3086 request.setTo(conversation.getJid().asBareJid());
3087 request.query("http://jabber.org/protocol/disco#info");
3088 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3089 @Override
3090 public void onIqPacketReceived(Account account, IqPacket packet) {
3091 if (packet.getType() == IqPacket.TYPE.RESULT) {
3092 final MucOptions mucOptions = conversation.getMucOptions();
3093 final Bookmark bookmark = conversation.getBookmark();
3094 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3095
3096 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3097 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3098 updateConversation(conversation);
3099 }
3100
3101 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3102 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3103 createBookmark(account, bookmark);
3104 }
3105 }
3106
3107
3108 if (callback != null) {
3109 callback.onConferenceConfigurationFetched(conversation);
3110 }
3111
3112
3113 updateConversationUi();
3114 } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3115 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3116 } else {
3117 if (callback != null) {
3118 callback.onFetchFailed(conversation, packet.getError());
3119 }
3120 }
3121 }
3122 });
3123 }
3124
3125 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3126 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3127 }
3128
3129 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3130 Log.d(Config.LOGTAG, "pushing node configuration");
3131 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3132 @Override
3133 public void onIqPacketReceived(Account account, IqPacket packet) {
3134 if (packet.getType() == IqPacket.TYPE.RESULT) {
3135 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3136 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3137 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3138 if (x != null) {
3139 Data data = Data.parse(x);
3140 data.submit(options);
3141 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3142 @Override
3143 public void onIqPacketReceived(Account account, IqPacket packet) {
3144 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3145 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3146 callback.onPushSucceeded();
3147 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3148 callback.onPushFailed();
3149 }
3150 }
3151 });
3152 } else if (callback != null) {
3153 callback.onPushFailed();
3154 }
3155 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3156 callback.onPushFailed();
3157 }
3158 }
3159 });
3160 }
3161
3162 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3163 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3164 conversation.setAttribute("accept_non_anonymous", true);
3165 updateConversation(conversation);
3166 }
3167 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3168 request.setTo(conversation.getJid().asBareJid());
3169 request.query("http://jabber.org/protocol/muc#owner");
3170 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3171 @Override
3172 public void onIqPacketReceived(Account account, IqPacket packet) {
3173 if (packet.getType() == IqPacket.TYPE.RESULT) {
3174 Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3175 data.submit(options);
3176 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3177 set.setTo(conversation.getJid().asBareJid());
3178 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3179 sendIqPacket(account, set, new OnIqPacketReceived() {
3180 @Override
3181 public void onIqPacketReceived(Account account, IqPacket packet) {
3182 if (callback != null) {
3183 if (packet.getType() == IqPacket.TYPE.RESULT) {
3184 callback.onPushSucceeded();
3185 } else {
3186 callback.onPushFailed();
3187 }
3188 }
3189 }
3190 });
3191 } else {
3192 if (callback != null) {
3193 callback.onPushFailed();
3194 }
3195 }
3196 }
3197 });
3198 }
3199
3200 public void pushSubjectToConference(final Conversation conference, final String subject) {
3201 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3202 this.sendMessagePacket(conference.getAccount(), packet);
3203 }
3204
3205 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3206 final Jid jid = user.asBareJid();
3207 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3208 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
3209 @Override
3210 public void onIqPacketReceived(Account account, IqPacket packet) {
3211 if (packet.getType() == IqPacket.TYPE.RESULT) {
3212 conference.getMucOptions().changeAffiliation(jid, affiliation);
3213 getAvatarService().clear(conference);
3214 callback.onAffiliationChangedSuccessful(jid);
3215 } else {
3216 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3217 }
3218 }
3219 });
3220 }
3221
3222 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
3223 List<Jid> jids = new ArrayList<>();
3224 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
3225 if (user.getAffiliation() == before && user.getRealJid() != null) {
3226 jids.add(user.getRealJid());
3227 }
3228 }
3229 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
3230 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
3231 }
3232
3233 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3234 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3235 Log.d(Config.LOGTAG, request.toString());
3236 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3237 if (packet.getType() != IqPacket.TYPE.RESULT) {
3238 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3239 }
3240 });
3241 }
3242
3243 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3244 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3245 request.setTo(conversation.getJid().asBareJid());
3246 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3247 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3248 @Override
3249 public void onIqPacketReceived(Account account, IqPacket packet) {
3250 if (packet.getType() == IqPacket.TYPE.RESULT) {
3251 if (callback != null) {
3252 callback.onRoomDestroySucceeded();
3253 }
3254 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3255 if (callback != null) {
3256 callback.onRoomDestroyFailed();
3257 }
3258 }
3259 }
3260 });
3261 }
3262
3263 private void disconnect(Account account, boolean force) {
3264 if ((account.getStatus() == Account.State.ONLINE)
3265 || (account.getStatus() == Account.State.DISABLED)) {
3266 final XmppConnection connection = account.getXmppConnection();
3267 if (!force) {
3268 List<Conversation> conversations = getConversations();
3269 for (Conversation conversation : conversations) {
3270 if (conversation.getAccount() == account) {
3271 if (conversation.getMode() == Conversation.MODE_MULTI) {
3272 leaveMuc(conversation, true);
3273 }
3274 }
3275 }
3276 sendOfflinePresence(account);
3277 }
3278 connection.disconnect(force);
3279 }
3280 }
3281
3282 @Override
3283 public IBinder onBind(Intent intent) {
3284 return mBinder;
3285 }
3286
3287 public void updateMessage(Message message) {
3288 updateMessage(message, true);
3289 }
3290
3291 public void updateMessage(Message message, boolean includeBody) {
3292 databaseBackend.updateMessage(message, includeBody);
3293 updateConversationUi();
3294 }
3295
3296 public void updateMessage(Message message, String uuid) {
3297 if (!databaseBackend.updateMessage(message, uuid)) {
3298 Log.e(Config.LOGTAG, "error updated message in DB after edit");
3299 }
3300 updateConversationUi();
3301 }
3302
3303 protected void syncDirtyContacts(Account account) {
3304 for (Contact contact : account.getRoster().getContacts()) {
3305 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3306 pushContactToServer(contact);
3307 }
3308 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3309 deleteContactOnServer(contact);
3310 }
3311 }
3312 }
3313
3314 public void createContact(Contact contact, boolean autoGrant) {
3315 if (autoGrant) {
3316 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3317 contact.setOption(Contact.Options.ASKING);
3318 }
3319 pushContactToServer(contact);
3320 }
3321
3322 public void pushContactToServer(final Contact contact) {
3323 contact.resetOption(Contact.Options.DIRTY_DELETE);
3324 contact.setOption(Contact.Options.DIRTY_PUSH);
3325 final Account account = contact.getAccount();
3326 if (account.getStatus() == Account.State.ONLINE) {
3327 final boolean ask = contact.getOption(Contact.Options.ASKING);
3328 final boolean sendUpdates = contact
3329 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3330 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3331 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3332 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3333 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3334 if (sendUpdates) {
3335 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3336 }
3337 if (ask) {
3338 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
3339 }
3340 } else {
3341 syncRoster(contact.getAccount());
3342 }
3343 }
3344
3345 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3346 new Thread(() -> {
3347 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3348 final int size = Config.AVATAR_SIZE;
3349 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3350 if (avatar != null) {
3351 if (!getFileBackend().save(avatar)) {
3352 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3353 return;
3354 }
3355 avatar.owner = conversation.getJid().asBareJid();
3356 publishMucAvatar(conversation, avatar, callback);
3357 } else {
3358 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3359 }
3360 }).start();
3361 }
3362
3363 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3364 new Thread(() -> {
3365 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3366 final int size = Config.AVATAR_SIZE;
3367 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3368 if (avatar != null) {
3369 if (!getFileBackend().save(avatar)) {
3370 Log.d(Config.LOGTAG, "unable to save vcard");
3371 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3372 return;
3373 }
3374 publishAvatar(account, avatar, callback);
3375 } else {
3376 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3377 }
3378 }).start();
3379
3380 }
3381
3382 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3383 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3384 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3385 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3386 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3387 Element vcard = response.findChild("vCard", "vcard-temp");
3388 if (vcard == null) {
3389 vcard = new Element("vCard", "vcard-temp");
3390 }
3391 Element photo = vcard.findChild("PHOTO");
3392 if (photo == null) {
3393 photo = vcard.addChild("PHOTO");
3394 }
3395 photo.clearChildren();
3396 photo.addChild("TYPE").setContent(avatar.type);
3397 photo.addChild("BINVAL").setContent(avatar.image);
3398 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3399 publication.setTo(conversation.getJid().asBareJid());
3400 publication.addChild(vcard);
3401 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3402 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3403 callback.onAvatarPublicationSucceeded();
3404 } else {
3405 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
3406 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3407 }
3408 });
3409 } else {
3410 Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3411 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3412 }
3413 });
3414 }
3415
3416 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3417 final Bundle options;
3418 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3419 options = PublishOptions.openAccess();
3420 } else {
3421 options = null;
3422 }
3423 publishAvatar(account, avatar, options, true, callback);
3424 }
3425
3426 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3427 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3428 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3429 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3430
3431 @Override
3432 public void onIqPacketReceived(Account account, IqPacket result) {
3433 if (result.getType() == IqPacket.TYPE.RESULT) {
3434 publishAvatarMetadata(account, avatar, options, true, callback);
3435 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3436 pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3437 @Override
3438 public void onPushSucceeded() {
3439 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3440 publishAvatar(account, avatar, options, false, callback);
3441 }
3442
3443 @Override
3444 public void onPushFailed() {
3445 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3446 publishAvatar(account, avatar, null, false, callback);
3447 }
3448 });
3449 } else {
3450 Element error = result.findChild("error");
3451 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3452 if (callback != null) {
3453 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3454 }
3455 }
3456 }
3457 });
3458 }
3459
3460 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3461 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3462 sendIqPacket(account, packet, new OnIqPacketReceived() {
3463 @Override
3464 public void onIqPacketReceived(Account account, IqPacket result) {
3465 if (result.getType() == IqPacket.TYPE.RESULT) {
3466 if (account.setAvatar(avatar.getFilename())) {
3467 getAvatarService().clear(account);
3468 databaseBackend.updateAccount(account);
3469 notifyAccountAvatarHasChanged(account);
3470 }
3471 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3472 if (callback != null) {
3473 callback.onAvatarPublicationSucceeded();
3474 }
3475 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3476 pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3477 @Override
3478 public void onPushSucceeded() {
3479 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3480 publishAvatarMetadata(account, avatar, options, false, callback);
3481 }
3482
3483 @Override
3484 public void onPushFailed() {
3485 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3486 publishAvatarMetadata(account, avatar, null, false, callback);
3487 }
3488 });
3489 } else {
3490 if (callback != null) {
3491 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3492 }
3493 }
3494 }
3495 });
3496 }
3497
3498 public void republishAvatarIfNeeded(Account account) {
3499 if (account.getAxolotlService().isPepBroken()) {
3500 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3501 return;
3502 }
3503 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3504 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3505
3506 private Avatar parseAvatar(IqPacket packet) {
3507 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3508 if (pubsub != null) {
3509 Element items = pubsub.findChild("items");
3510 if (items != null) {
3511 return Avatar.parseMetadata(items);
3512 }
3513 }
3514 return null;
3515 }
3516
3517 private boolean errorIsItemNotFound(IqPacket packet) {
3518 Element error = packet.findChild("error");
3519 return packet.getType() == IqPacket.TYPE.ERROR
3520 && error != null
3521 && error.hasChild("item-not-found");
3522 }
3523
3524 @Override
3525 public void onIqPacketReceived(Account account, IqPacket packet) {
3526 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3527 Avatar serverAvatar = parseAvatar(packet);
3528 if (serverAvatar == null && account.getAvatar() != null) {
3529 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3530 if (avatar != null) {
3531 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3532 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3533 } else {
3534 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3535 }
3536 }
3537 }
3538 }
3539 });
3540 }
3541
3542 public void fetchAvatar(Account account, Avatar avatar) {
3543 fetchAvatar(account, avatar, null);
3544 }
3545
3546 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3547 final String KEY = generateFetchKey(account, avatar);
3548 synchronized (this.mInProgressAvatarFetches) {
3549 if (mInProgressAvatarFetches.add(KEY)) {
3550 switch (avatar.origin) {
3551 case PEP:
3552 this.mInProgressAvatarFetches.add(KEY);
3553 fetchAvatarPep(account, avatar, callback);
3554 break;
3555 case VCARD:
3556 this.mInProgressAvatarFetches.add(KEY);
3557 fetchAvatarVcard(account, avatar, callback);
3558 break;
3559 }
3560 } else if (avatar.origin == Avatar.Origin.PEP) {
3561 mOmittedPepAvatarFetches.add(KEY);
3562 } else {
3563 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
3564 }
3565 }
3566 }
3567
3568 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3569 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3570 sendIqPacket(account, packet, (a, result) -> {
3571 synchronized (mInProgressAvatarFetches) {
3572 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3573 }
3574 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3575 if (result.getType() == IqPacket.TYPE.RESULT) {
3576 avatar.image = mIqParser.avatarData(result);
3577 if (avatar.image != null) {
3578 if (getFileBackend().save(avatar)) {
3579 if (a.getJid().asBareJid().equals(avatar.owner)) {
3580 if (a.setAvatar(avatar.getFilename())) {
3581 databaseBackend.updateAccount(a);
3582 }
3583 getAvatarService().clear(a);
3584 updateConversationUi();
3585 updateAccountUi();
3586 } else {
3587 Contact contact = a.getRoster().getContact(avatar.owner);
3588 if (contact.setAvatar(avatar)) {
3589 syncRoster(account);
3590 getAvatarService().clear(contact);
3591 updateConversationUi();
3592 updateRosterUi();
3593 }
3594 }
3595 if (callback != null) {
3596 callback.success(avatar);
3597 }
3598 Log.d(Config.LOGTAG, a.getJid().asBareJid()
3599 + ": successfully fetched pep avatar for " + avatar.owner);
3600 return;
3601 }
3602 } else {
3603
3604 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3605 }
3606 } else {
3607 Element error = result.findChild("error");
3608 if (error == null) {
3609 Log.d(Config.LOGTAG, ERROR + "(server error)");
3610 } else {
3611 Log.d(Config.LOGTAG, ERROR + error.toString());
3612 }
3613 }
3614 if (callback != null) {
3615 callback.error(0, null);
3616 }
3617
3618 });
3619 }
3620
3621 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3622 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3623 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3624 @Override
3625 public void onIqPacketReceived(Account account, IqPacket packet) {
3626 final boolean previouslyOmittedPepFetch;
3627 synchronized (mInProgressAvatarFetches) {
3628 final String KEY = generateFetchKey(account, avatar);
3629 mInProgressAvatarFetches.remove(KEY);
3630 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3631 }
3632 if (packet.getType() == IqPacket.TYPE.RESULT) {
3633 Element vCard = packet.findChild("vCard", "vcard-temp");
3634 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3635 String image = photo != null ? photo.findChildContent("BINVAL") : null;
3636 if (image != null) {
3637 avatar.image = image;
3638 if (getFileBackend().save(avatar)) {
3639 Log.d(Config.LOGTAG, account.getJid().asBareJid()
3640 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
3641 if (avatar.owner.isBareJid()) {
3642 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3643 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3644 account.setAvatar(avatar.getFilename());
3645 databaseBackend.updateAccount(account);
3646 getAvatarService().clear(account);
3647 updateAccountUi();
3648 } else {
3649 Contact contact = account.getRoster().getContact(avatar.owner);
3650 if (contact.setAvatar(avatar, previouslyOmittedPepFetch)) {
3651 syncRoster(account);
3652 getAvatarService().clear(contact);
3653 updateRosterUi();
3654 }
3655 }
3656 updateConversationUi();
3657 } else {
3658 Conversation conversation = find(account, avatar.owner.asBareJid());
3659 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3660 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3661 if (user != null) {
3662 if (user.setAvatar(avatar)) {
3663 getAvatarService().clear(user);
3664 updateConversationUi();
3665 updateMucRosterUi();
3666 }
3667 if (user.getRealJid() != null) {
3668 Contact contact = account.getRoster().getContact(user.getRealJid());
3669 if (contact.setAvatar(avatar)) {
3670 syncRoster(account);
3671 getAvatarService().clear(contact);
3672 updateRosterUi();
3673 }
3674 }
3675 }
3676 }
3677 }
3678 }
3679 }
3680 }
3681 }
3682 });
3683 }
3684
3685 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3686 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3687 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3688
3689 @Override
3690 public void onIqPacketReceived(Account account, IqPacket packet) {
3691 if (packet.getType() == IqPacket.TYPE.RESULT) {
3692 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3693 if (pubsub != null) {
3694 Element items = pubsub.findChild("items");
3695 if (items != null) {
3696 Avatar avatar = Avatar.parseMetadata(items);
3697 if (avatar != null) {
3698 avatar.owner = account.getJid().asBareJid();
3699 if (fileBackend.isAvatarCached(avatar)) {
3700 if (account.setAvatar(avatar.getFilename())) {
3701 databaseBackend.updateAccount(account);
3702 }
3703 getAvatarService().clear(account);
3704 callback.success(avatar);
3705 } else {
3706 fetchAvatarPep(account, avatar, callback);
3707 }
3708 return;
3709 }
3710 }
3711 }
3712 }
3713 callback.error(0, null);
3714 }
3715 });
3716 }
3717
3718 public void notifyAccountAvatarHasChanged(final Account account) {
3719 final XmppConnection connection = account.getXmppConnection();
3720 if (connection != null && connection.getFeatures().bookmarksConversion()) {
3721 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
3722 for (Conversation conversation : conversations) {
3723 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3724 final MucOptions mucOptions = conversation.getMucOptions();
3725 if (mucOptions.online()) {
3726 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3727 packet.setTo(mucOptions.getSelf().getFullJid());
3728 connection.sendPresencePacket(packet);
3729 }
3730 }
3731 }
3732 }
3733 }
3734
3735 public void deleteContactOnServer(Contact contact) {
3736 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3737 contact.resetOption(Contact.Options.DIRTY_PUSH);
3738 contact.setOption(Contact.Options.DIRTY_DELETE);
3739 Account account = contact.getAccount();
3740 if (account.getStatus() == Account.State.ONLINE) {
3741 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3742 Element item = iq.query(Namespace.ROSTER).addChild("item");
3743 item.setAttribute("jid", contact.getJid().toString());
3744 item.setAttribute("subscription", "remove");
3745 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3746 }
3747 }
3748
3749 public void updateConversation(final Conversation conversation) {
3750 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3751 }
3752
3753 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3754 synchronized (account) {
3755 XmppConnection connection = account.getXmppConnection();
3756 if (connection == null) {
3757 connection = createConnection(account);
3758 account.setXmppConnection(connection);
3759 }
3760 boolean hasInternet = hasInternetConnection();
3761 if (account.isEnabled() && hasInternet) {
3762 if (!force) {
3763 disconnect(account, false);
3764 }
3765 Thread thread = new Thread(connection);
3766 connection.setInteractive(interactive);
3767 connection.prepareNewConnection();
3768 connection.interrupt();
3769 thread.start();
3770 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3771 } else {
3772 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3773 account.getRoster().clearPresences();
3774 connection.resetEverything();
3775 final AxolotlService axolotlService = account.getAxolotlService();
3776 if (axolotlService != null) {
3777 axolotlService.resetBrokenness();
3778 }
3779 if (!hasInternet) {
3780 account.setStatus(Account.State.NO_INTERNET);
3781 }
3782 }
3783 }
3784 }
3785
3786 public void reconnectAccountInBackground(final Account account) {
3787 new Thread(() -> reconnectAccount(account, false, true)).start();
3788 }
3789
3790 public void invite(Conversation conversation, Jid contact) {
3791 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3792 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3793 sendMessagePacket(conversation.getAccount(), packet);
3794 }
3795
3796 public void directInvite(Conversation conversation, Jid jid) {
3797 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3798 sendMessagePacket(conversation.getAccount(), packet);
3799 }
3800
3801 public void resetSendingToWaiting(Account account) {
3802 for (Conversation conversation : getConversations()) {
3803 if (conversation.getAccount() == account) {
3804 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3805 }
3806 }
3807 }
3808
3809 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3810 return markMessage(account, recipient, uuid, status, null);
3811 }
3812
3813 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3814 if (uuid == null) {
3815 return null;
3816 }
3817 for (Conversation conversation : getConversations()) {
3818 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3819 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3820 if (message != null) {
3821 markMessage(message, status, errorMessage);
3822 }
3823 return message;
3824 }
3825 }
3826 return null;
3827 }
3828
3829 public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3830 if (uuid == null) {
3831 return false;
3832 } else {
3833 Message message = conversation.findSentMessageWithUuid(uuid);
3834 if (message != null) {
3835 if (message.getServerMsgId() == null) {
3836 message.setServerMsgId(serverMessageId);
3837 }
3838 markMessage(message, status);
3839 return true;
3840 } else {
3841 return false;
3842 }
3843 }
3844 }
3845
3846 public void markMessage(Message message, int status) {
3847 markMessage(message, status, null);
3848 }
3849
3850
3851 public void markMessage(Message message, int status, String errorMessage) {
3852 final int oldStatus = message.getStatus();
3853 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
3854 return;
3855 }
3856 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
3857 return;
3858 }
3859 message.setErrorMessage(errorMessage);
3860 message.setStatus(status);
3861 databaseBackend.updateMessage(message, false);
3862 updateConversationUi();
3863 }
3864
3865 private SharedPreferences getPreferences() {
3866 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3867 }
3868
3869 public long getAutomaticMessageDeletionDate() {
3870 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3871 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3872 }
3873
3874 public long getLongPreference(String name, @IntegerRes int res) {
3875 long defaultValue = getResources().getInteger(res);
3876 try {
3877 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3878 } catch (NumberFormatException e) {
3879 return defaultValue;
3880 }
3881 }
3882
3883 public boolean getBooleanPreference(String name, @BoolRes int res) {
3884 return getPreferences().getBoolean(name, getResources().getBoolean(res));
3885 }
3886
3887 public boolean confirmMessages() {
3888 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3889 }
3890
3891 public boolean allowMessageCorrection() {
3892 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3893 }
3894
3895 public boolean sendChatStates() {
3896 return getBooleanPreference("chat_states", R.bool.chat_states);
3897 }
3898
3899 private boolean synchronizeWithBookmarks() {
3900 return getBooleanPreference("autojoin", R.bool.autojoin);
3901 }
3902
3903 public boolean indicateReceived() {
3904 return getBooleanPreference("indicate_received", R.bool.indicate_received);
3905 }
3906
3907 public boolean useTorToConnect() {
3908 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
3909 }
3910
3911 public boolean showExtendedConnectionOptions() {
3912 return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3913 }
3914
3915 public boolean broadcastLastActivity() {
3916 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3917 }
3918
3919 public int unreadCount() {
3920 int count = 0;
3921 for (Conversation conversation : getConversations()) {
3922 count += conversation.unreadCount();
3923 }
3924 return count;
3925 }
3926
3927
3928 private <T> List<T> threadSafeList(Set<T> set) {
3929 synchronized (LISTENER_LOCK) {
3930 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3931 }
3932 }
3933
3934 public void showErrorToastInUi(int resId) {
3935 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3936 listener.onShowErrorToast(resId);
3937 }
3938 }
3939
3940 public void updateConversationUi() {
3941 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3942 listener.onConversationUpdate();
3943 }
3944 }
3945
3946 public void updateAccountUi() {
3947 for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3948 listener.onAccountUpdate();
3949 }
3950 }
3951
3952 public void updateRosterUi() {
3953 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3954 listener.onRosterUpdate();
3955 }
3956 }
3957
3958 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3959 if (mOnCaptchaRequested.size() > 0) {
3960 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3961 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3962 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3963 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3964 listener.onCaptchaRequested(account, id, data, scaled);
3965 }
3966 return true;
3967 }
3968 return false;
3969 }
3970
3971 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3972 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3973 listener.OnUpdateBlocklist(status);
3974 }
3975 }
3976
3977 public void updateMucRosterUi() {
3978 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3979 listener.onMucRosterUpdate();
3980 }
3981 }
3982
3983 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3984 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3985 listener.onKeyStatusUpdated(report);
3986 }
3987 }
3988
3989 public Account findAccountByJid(final Jid accountJid) {
3990 for (Account account : this.accounts) {
3991 if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3992 return account;
3993 }
3994 }
3995 return null;
3996 }
3997
3998 public Account findAccountByUuid(final String uuid) {
3999 for (Account account : this.accounts) {
4000 if (account.getUuid().equals(uuid)) {
4001 return account;
4002 }
4003 }
4004 return null;
4005 }
4006
4007 public Conversation findConversationByUuid(String uuid) {
4008 for (Conversation conversation : getConversations()) {
4009 if (conversation.getUuid().equals(uuid)) {
4010 return conversation;
4011 }
4012 }
4013 return null;
4014 }
4015
4016 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4017 List<Conversation> findings = new ArrayList<>();
4018 for (Conversation c : getConversations()) {
4019 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4020 findings.add(c);
4021 }
4022 }
4023 return findings.size() == 1 ? findings.get(0) : null;
4024 }
4025
4026 public boolean markRead(final Conversation conversation, boolean dismiss) {
4027 return markRead(conversation, null, dismiss).size() > 0;
4028 }
4029
4030 public void markRead(final Conversation conversation) {
4031 markRead(conversation, null, true);
4032 }
4033
4034 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4035 if (dismiss) {
4036 mNotificationService.clear(conversation);
4037 }
4038 final List<Message> readMessages = conversation.markRead(upToUuid);
4039 if (readMessages.size() > 0) {
4040 Runnable runnable = () -> {
4041 for (Message message : readMessages) {
4042 databaseBackend.updateMessage(message, false);
4043 }
4044 };
4045 mDatabaseWriterExecutor.execute(runnable);
4046 updateUnreadCountBadge();
4047 return readMessages;
4048 } else {
4049 return readMessages;
4050 }
4051 }
4052
4053 public synchronized void updateUnreadCountBadge() {
4054 int count = unreadCount();
4055 if (unreadCount != count) {
4056 Log.d(Config.LOGTAG, "update unread count to " + count);
4057 if (count > 0) {
4058 ShortcutBadger.applyCount(getApplicationContext(), count);
4059 } else {
4060 ShortcutBadger.removeCount(getApplicationContext());
4061 }
4062 unreadCount = count;
4063 }
4064 }
4065
4066 public void sendReadMarker(final Conversation conversation, String upToUuid) {
4067 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4068 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4069 if (readMessages.size() > 0) {
4070 updateConversationUi();
4071 }
4072 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4073 if (confirmMessages()
4074 && markable != null
4075 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4076 && markable.getRemoteMsgId() != null) {
4077 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4078 Account account = conversation.getAccount();
4079 final Jid to = markable.getCounterpart();
4080 final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
4081 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
4082 this.sendMessagePacket(conversation.getAccount(), packet);
4083 }
4084 }
4085
4086 public SecureRandom getRNG() {
4087 return this.mRandom;
4088 }
4089
4090 public MemorizingTrustManager getMemorizingTrustManager() {
4091 return this.mMemorizingTrustManager;
4092 }
4093
4094 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4095 this.mMemorizingTrustManager = trustManager;
4096 }
4097
4098 public void updateMemorizingTrustmanager() {
4099 final MemorizingTrustManager tm;
4100 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4101 if (dontTrustSystemCAs) {
4102 tm = new MemorizingTrustManager(getApplicationContext(), null);
4103 } else {
4104 tm = new MemorizingTrustManager(getApplicationContext());
4105 }
4106 setMemorizingTrustManager(tm);
4107 }
4108
4109 public LruCache<String, Bitmap> getBitmapCache() {
4110 return this.mBitmapCache;
4111 }
4112
4113 public Collection<String> getKnownHosts() {
4114 final Set<String> hosts = new HashSet<>();
4115 for (final Account account : getAccounts()) {
4116 hosts.add(account.getServer());
4117 for (final Contact contact : account.getRoster().getContacts()) {
4118 if (contact.showInRoster()) {
4119 final String server = contact.getServer();
4120 if (server != null) {
4121 hosts.add(server);
4122 }
4123 }
4124 }
4125 }
4126 if (Config.QUICKSY_DOMAIN != null) {
4127 hosts.remove(Config.QUICKSY_DOMAIN); //we only want to show this when we type a e164 number
4128 }
4129 if (Config.DOMAIN_LOCK != null) {
4130 hosts.add(Config.DOMAIN_LOCK);
4131 }
4132 if (Config.MAGIC_CREATE_DOMAIN != null) {
4133 hosts.add(Config.MAGIC_CREATE_DOMAIN);
4134 }
4135 return hosts;
4136 }
4137
4138 public Collection<String> getKnownConferenceHosts() {
4139 final Set<String> mucServers = new HashSet<>();
4140 for (final Account account : accounts) {
4141 if (account.getXmppConnection() != null) {
4142 mucServers.addAll(account.getXmppConnection().getMucServers());
4143 for (Bookmark bookmark : account.getBookmarks()) {
4144 final Jid jid = bookmark.getJid();
4145 final String s = jid == null ? null : jid.getDomain();
4146 if (s != null) {
4147 mucServers.add(s);
4148 }
4149 }
4150 }
4151 }
4152 return mucServers;
4153 }
4154
4155 public void sendMessagePacket(Account account, MessagePacket packet) {
4156 XmppConnection connection = account.getXmppConnection();
4157 if (connection != null) {
4158 connection.sendMessagePacket(packet);
4159 }
4160 }
4161
4162 public void sendPresencePacket(Account account, PresencePacket packet) {
4163 XmppConnection connection = account.getXmppConnection();
4164 if (connection != null) {
4165 connection.sendPresencePacket(packet);
4166 }
4167 }
4168
4169 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4170 final XmppConnection connection = account.getXmppConnection();
4171 if (connection != null) {
4172 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4173 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4174 }
4175 }
4176
4177 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4178 final XmppConnection connection = account.getXmppConnection();
4179 if (connection != null) {
4180 connection.sendIqPacket(packet, callback);
4181 } else if (callback != null) {
4182 callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4183 }
4184 }
4185
4186 public void sendPresence(final Account account) {
4187 sendPresence(account, checkListeners() && broadcastLastActivity());
4188 }
4189
4190 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4191 Presence.Status status;
4192 if (manuallyChangePresence()) {
4193 status = account.getPresenceStatus();
4194 } else {
4195 status = getTargetPresence();
4196 }
4197 final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4198 if (mLastActivity > 0 && includeIdleTimestamp) {
4199 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4200 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4201 }
4202 sendPresencePacket(account, packet);
4203 }
4204
4205 private void deactivateGracePeriod() {
4206 for (Account account : getAccounts()) {
4207 account.deactivateGracePeriod();
4208 }
4209 }
4210
4211 public void refreshAllPresences() {
4212 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4213 for (Account account : getAccounts()) {
4214 if (account.isEnabled()) {
4215 sendPresence(account, includeIdleTimestamp);
4216 }
4217 }
4218 }
4219
4220 private void refreshAllFcmTokens() {
4221 for (Account account : getAccounts()) {
4222 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4223 mPushManagementService.registerPushTokenOnServer(account);
4224 //TODO renew mucs
4225 }
4226 }
4227 }
4228
4229 private void sendOfflinePresence(final Account account) {
4230 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4231 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4232 }
4233
4234 public MessageGenerator getMessageGenerator() {
4235 return this.mMessageGenerator;
4236 }
4237
4238 public PresenceGenerator getPresenceGenerator() {
4239 return this.mPresenceGenerator;
4240 }
4241
4242 public IqGenerator getIqGenerator() {
4243 return this.mIqGenerator;
4244 }
4245
4246 public IqParser getIqParser() {
4247 return this.mIqParser;
4248 }
4249
4250 public JingleConnectionManager getJingleConnectionManager() {
4251 return this.mJingleConnectionManager;
4252 }
4253
4254 public MessageArchiveService getMessageArchiveService() {
4255 return this.mMessageArchiveService;
4256 }
4257
4258 public QuickConversationsService getQuickConversationsService() {
4259 return this.mQuickConversationsService;
4260 }
4261
4262 public List<Contact> findContacts(Jid jid, String accountJid) {
4263 ArrayList<Contact> contacts = new ArrayList<>();
4264 for (Account account : getAccounts()) {
4265 if ((account.isEnabled() || accountJid != null)
4266 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4267 Contact contact = account.getRoster().getContactFromContactList(jid);
4268 if (contact != null) {
4269 contacts.add(contact);
4270 }
4271 }
4272 }
4273 return contacts;
4274 }
4275
4276 public Conversation findFirstMuc(Jid jid) {
4277 for (Conversation conversation : getConversations()) {
4278 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4279 return conversation;
4280 }
4281 }
4282 return null;
4283 }
4284
4285 public NotificationService getNotificationService() {
4286 return this.mNotificationService;
4287 }
4288
4289 public HttpConnectionManager getHttpConnectionManager() {
4290 return this.mHttpConnectionManager;
4291 }
4292
4293 public void resendFailedMessages(final Message message) {
4294 final Collection<Message> messages = new ArrayList<>();
4295 Message current = message;
4296 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4297 messages.add(current);
4298 if (current.mergeable(current.next())) {
4299 current = current.next();
4300 } else {
4301 break;
4302 }
4303 }
4304 for (final Message msg : messages) {
4305 msg.setTime(System.currentTimeMillis());
4306 markMessage(msg, Message.STATUS_WAITING);
4307 this.resendMessage(msg, false);
4308 }
4309 if (message.getConversation() instanceof Conversation) {
4310 ((Conversation) message.getConversation()).sort();
4311 }
4312 updateConversationUi();
4313 }
4314
4315 public void clearConversationHistory(final Conversation conversation) {
4316 final long clearDate;
4317 final String reference;
4318 if (conversation.countMessages() > 0) {
4319 Message latestMessage = conversation.getLatestMessage();
4320 clearDate = latestMessage.getTimeSent() + 1000;
4321 reference = latestMessage.getServerMsgId();
4322 } else {
4323 clearDate = System.currentTimeMillis();
4324 reference = null;
4325 }
4326 conversation.clearMessages();
4327 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4328 conversation.setLastClearHistory(clearDate, reference);
4329 Runnable runnable = () -> {
4330 databaseBackend.deleteMessagesInConversation(conversation);
4331 databaseBackend.updateConversation(conversation);
4332 };
4333 mDatabaseWriterExecutor.execute(runnable);
4334 }
4335
4336 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4337 if (blockable != null && blockable.getBlockedJid() != null) {
4338 final Jid jid = blockable.getBlockedJid();
4339 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4340 if (response.getType() == IqPacket.TYPE.RESULT) {
4341 a.getBlocklist().add(jid);
4342 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4343 }
4344 });
4345 if (blockable.getBlockedJid().isFullJid()) {
4346 return false;
4347 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4348 updateConversationUi();
4349 return true;
4350 } else {
4351 return false;
4352 }
4353 } else {
4354 return false;
4355 }
4356 }
4357
4358 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4359 boolean removed = false;
4360 synchronized (this.conversations) {
4361 boolean domainJid = blockedJid.getLocal() == null;
4362 for (Conversation conversation : this.conversations) {
4363 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4364 || blockedJid.equals(conversation.getJid().asBareJid());
4365 if (conversation.getAccount() == account
4366 && conversation.getMode() == Conversation.MODE_SINGLE
4367 && jidMatches) {
4368 this.conversations.remove(conversation);
4369 markRead(conversation);
4370 conversation.setStatus(Conversation.STATUS_ARCHIVED);
4371 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4372 updateConversation(conversation);
4373 removed = true;
4374 }
4375 }
4376 }
4377 return removed;
4378 }
4379
4380 public void sendUnblockRequest(final Blockable blockable) {
4381 if (blockable != null && blockable.getJid() != null) {
4382 final Jid jid = blockable.getBlockedJid();
4383 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4384 @Override
4385 public void onIqPacketReceived(final Account account, final IqPacket packet) {
4386 if (packet.getType() == IqPacket.TYPE.RESULT) {
4387 account.getBlocklist().remove(jid);
4388 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4389 }
4390 }
4391 });
4392 }
4393 }
4394
4395 public void publishDisplayName(Account account) {
4396 String displayName = account.getDisplayName();
4397 final IqPacket request;
4398 if (TextUtils.isEmpty(displayName)) {
4399 request = mIqGenerator.deleteNode(Namespace.NICK);
4400 } else {
4401 request = mIqGenerator.publishNick(displayName);
4402 }
4403 mAvatarService.clear(account);
4404 sendIqPacket(account, request, (account1, packet) -> {
4405 if (packet.getType() == IqPacket.TYPE.ERROR) {
4406 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet.toString());
4407 }
4408 });
4409 }
4410
4411 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4412 ServiceDiscoveryResult result = discoCache.get(key);
4413 if (result != null) {
4414 return result;
4415 } else {
4416 result = databaseBackend.findDiscoveryResult(key.first, key.second);
4417 if (result != null) {
4418 discoCache.put(key, result);
4419 }
4420 return result;
4421 }
4422 }
4423
4424 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4425 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4426 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4427 if (disco != null) {
4428 presence.setServiceDiscoveryResult(disco);
4429 } else {
4430 if (!account.inProgressDiscoFetches.contains(key)) {
4431 account.inProgressDiscoFetches.add(key);
4432 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4433 request.setTo(jid);
4434 final String node = presence.getNode();
4435 final String ver = presence.getVer();
4436 final Element query = request.query("http://jabber.org/protocol/disco#info");
4437 if (node != null && ver != null) {
4438 query.setAttribute("node", node + "#" + ver);
4439 }
4440 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4441 sendIqPacket(account, request, (a, response) -> {
4442 if (response.getType() == IqPacket.TYPE.RESULT) {
4443 ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4444 if (presence.getVer().equals(discoveryResult.getVer())) {
4445 databaseBackend.insertDiscoveryResult(discoveryResult);
4446 injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4447 } else {
4448 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4449 }
4450 }
4451 a.inProgressDiscoFetches.remove(key);
4452 });
4453 }
4454 }
4455 }
4456
4457 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4458 for (Contact contact : roster.getContacts()) {
4459 for (Presence presence : contact.getPresences().getPresences().values()) {
4460 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4461 presence.setServiceDiscoveryResult(disco);
4462 }
4463 }
4464 }
4465 }
4466
4467 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4468 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4469 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4470 request.addChild("prefs", version.namespace);
4471 sendIqPacket(account, request, (account1, packet) -> {
4472 Element prefs = packet.findChild("prefs", version.namespace);
4473 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4474 callback.onPreferencesFetched(prefs);
4475 } else {
4476 callback.onPreferencesFetchFailed();
4477 }
4478 });
4479 }
4480
4481 public PushManagementService getPushManagementService() {
4482 return mPushManagementService;
4483 }
4484
4485 public void changeStatus(Account account, PresenceTemplate template, String signature) {
4486 if (!template.getStatusMessage().isEmpty()) {
4487 databaseBackend.insertPresenceTemplate(template);
4488 }
4489 account.setPgpSignature(signature);
4490 account.setPresenceStatus(template.getStatus());
4491 account.setPresenceStatusMessage(template.getStatusMessage());
4492 databaseBackend.updateAccount(account);
4493 sendPresence(account);
4494 }
4495
4496 public List<PresenceTemplate> getPresenceTemplates(Account account) {
4497 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4498 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4499 if (!templates.contains(template)) {
4500 templates.add(0, template);
4501 }
4502 }
4503 return templates;
4504 }
4505
4506 public void saveConversationAsBookmark(Conversation conversation, String name) {
4507 final Account account = conversation.getAccount();
4508 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4509 final String nick = conversation.getJid().getResource();
4510 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4511 bookmark.setNick(nick);
4512 }
4513 if (!TextUtils.isEmpty(name)) {
4514 bookmark.setBookmarkName(name);
4515 }
4516 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4517 createBookmark(account, bookmark);
4518 bookmark.setConversation(conversation);
4519 }
4520
4521 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4522 boolean performedVerification = false;
4523 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4524 for (XmppUri.Fingerprint fp : fingerprints) {
4525 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4526 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4527 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4528 if (fingerprintStatus != null) {
4529 if (!fingerprintStatus.isVerified()) {
4530 performedVerification = true;
4531 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4532 }
4533 } else {
4534 axolotlService.preVerifyFingerprint(contact, fingerprint);
4535 }
4536 }
4537 }
4538 return performedVerification;
4539 }
4540
4541 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4542 final AxolotlService axolotlService = account.getAxolotlService();
4543 boolean verifiedSomething = false;
4544 for (XmppUri.Fingerprint fp : fingerprints) {
4545 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4546 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4547 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4548 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4549 if (fingerprintStatus != null) {
4550 if (!fingerprintStatus.isVerified()) {
4551 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4552 verifiedSomething = true;
4553 }
4554 } else {
4555 axolotlService.preVerifyFingerprint(account, fingerprint);
4556 verifiedSomething = true;
4557 }
4558 }
4559 }
4560 return verifiedSomething;
4561 }
4562
4563 public boolean blindTrustBeforeVerification() {
4564 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4565 }
4566
4567 public ShortcutService getShortcutService() {
4568 return mShortcutService;
4569 }
4570
4571 public void pushMamPreferences(Account account, Element prefs) {
4572 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4573 set.addChild(prefs);
4574 sendIqPacket(account, set, null);
4575 }
4576
4577 public interface OnMamPreferencesFetched {
4578 void onPreferencesFetched(Element prefs);
4579
4580 void onPreferencesFetchFailed();
4581 }
4582
4583 public interface OnAccountCreated {
4584 void onAccountCreated(Account account);
4585
4586 void informUser(int r);
4587 }
4588
4589 public interface OnMoreMessagesLoaded {
4590 void onMoreMessagesLoaded(int count, Conversation conversation);
4591
4592 void informUser(int r);
4593 }
4594
4595 public interface OnAccountPasswordChanged {
4596 void onPasswordChangeSucceeded();
4597
4598 void onPasswordChangeFailed();
4599 }
4600
4601 public interface OnRoomDestroy {
4602 void onRoomDestroySucceeded();
4603
4604 void onRoomDestroyFailed();
4605 }
4606
4607 public interface OnAffiliationChanged {
4608 void onAffiliationChangedSuccessful(Jid jid);
4609
4610 void onAffiliationChangeFailed(Jid jid, int resId);
4611 }
4612
4613 public interface OnConversationUpdate {
4614 void onConversationUpdate();
4615 }
4616
4617 public interface OnAccountUpdate {
4618 void onAccountUpdate();
4619 }
4620
4621 public interface OnCaptchaRequested {
4622 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4623 }
4624
4625 public interface OnRosterUpdate {
4626 void onRosterUpdate();
4627 }
4628
4629 public interface OnMucRosterUpdate {
4630 void onMucRosterUpdate();
4631 }
4632
4633 public interface OnConferenceConfigurationFetched {
4634 void onConferenceConfigurationFetched(Conversation conversation);
4635
4636 void onFetchFailed(Conversation conversation, Element error);
4637 }
4638
4639 public interface OnConferenceJoined {
4640 void onConferenceJoined(Conversation conversation);
4641 }
4642
4643 public interface OnConfigurationPushed {
4644 void onPushSucceeded();
4645
4646 void onPushFailed();
4647 }
4648
4649 public interface OnShowErrorToast {
4650 void onShowErrorToast(int resId);
4651 }
4652
4653 public class XmppConnectionBinder extends Binder {
4654 public XmppConnectionService getService() {
4655 return XmppConnectionService.this;
4656 }
4657 }
4658
4659 private class InternalEventReceiver extends BroadcastReceiver {
4660
4661 @Override
4662 public void onReceive(Context context, Intent intent) {
4663 onStartCommand(intent, 0, 0);
4664 }
4665 }
4666}