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