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