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