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