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