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