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