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