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