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