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