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