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