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