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