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);
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 void 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 (options.online()) {
2355 Account account = conversation.getAccount();
2356 options.setOnRenameListener(new OnRenameListener() {
2357
2358 @Override
2359 public void onSuccess() {
2360 conversation.setContactJid(joinJid);
2361 databaseBackend.updateConversation(conversation);
2362 Bookmark bookmark = conversation.getBookmark();
2363 if (bookmark != null) {
2364 bookmark.setNick(nick);
2365 pushBookmarks(bookmark.getAccount());
2366 }
2367 callback.success(conversation);
2368 }
2369
2370 @Override
2371 public void onFailure() {
2372 callback.error(R.string.nick_in_use, conversation);
2373 }
2374 });
2375
2376 PresencePacket packet = new PresencePacket();
2377 packet.setTo(joinJid);
2378 packet.setFrom(conversation.getAccount().getJid());
2379
2380 String sig = account.getPgpSignature();
2381 if (sig != null) {
2382 packet.addChild("status").setContent("online");
2383 packet.addChild("x", "jabber:x:signed").setContent(sig);
2384 }
2385 sendPresencePacket(account, packet);
2386 } else {
2387 conversation.setContactJid(joinJid);
2388 databaseBackend.updateConversation(conversation);
2389 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2390 Bookmark bookmark = conversation.getBookmark();
2391 if (bookmark != null) {
2392 bookmark.setNick(nick);
2393 pushBookmarks(bookmark.getAccount());
2394 }
2395 joinMuc(conversation);
2396 }
2397 }
2398 }
2399
2400 public void leaveMuc(Conversation conversation) {
2401 leaveMuc(conversation, false);
2402 }
2403
2404 private void leaveMuc(Conversation conversation, boolean now) {
2405 Account account = conversation.getAccount();
2406 account.pendingConferenceJoins.remove(conversation);
2407 account.pendingConferenceLeaves.remove(conversation);
2408 if (account.getStatus() == Account.State.ONLINE || now) {
2409 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2410 conversation.getMucOptions().setOffline();
2411 conversation.deregisterWithBookmark();
2412 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": leaving muc " + conversation.getJid());
2413 } else {
2414 account.pendingConferenceLeaves.add(conversation);
2415 }
2416 }
2417
2418 public String findConferenceServer(final Account account) {
2419 String server;
2420 if (account.getXmppConnection() != null) {
2421 server = account.getXmppConnection().getMucServer();
2422 if (server != null) {
2423 return server;
2424 }
2425 }
2426 for (Account other : getAccounts()) {
2427 if (other != account && other.getXmppConnection() != null) {
2428 server = other.getXmppConnection().getMucServer();
2429 if (server != null) {
2430 return server;
2431 }
2432 }
2433 }
2434 return null;
2435 }
2436
2437 public boolean createAdhocConference(final Account account,
2438 final String subject,
2439 final Iterable<Jid> jids,
2440 final UiCallback<Conversation> callback) {
2441 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2442 if (account.getStatus() == Account.State.ONLINE) {
2443 try {
2444 String server = findConferenceServer(account);
2445 if (server == null) {
2446 if (callback != null) {
2447 callback.error(R.string.no_conference_server_found, null);
2448 }
2449 return false;
2450 }
2451 final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2452 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2453 joinMuc(conversation, new OnConferenceJoined() {
2454 @Override
2455 public void onConferenceJoined(final Conversation conversation) {
2456 pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConfigurationPushed() {
2457 @Override
2458 public void onPushSucceeded() {
2459 if (subject != null && !subject.trim().isEmpty()) {
2460 pushSubjectToConference(conversation, subject.trim());
2461 }
2462 for (Jid invite : jids) {
2463 invite(conversation, invite);
2464 }
2465 if (account.countPresences() > 1) {
2466 directInvite(conversation, account.getJid().toBareJid());
2467 }
2468 saveConversationAsBookmark(conversation, subject);
2469 if (callback != null) {
2470 callback.success(conversation);
2471 }
2472 }
2473
2474 @Override
2475 public void onPushFailed() {
2476 archiveConversation(conversation);
2477 if (callback != null) {
2478 callback.error(R.string.conference_creation_failed, conversation);
2479 }
2480 }
2481 });
2482 }
2483 });
2484 return true;
2485 } catch (InvalidJidException e) {
2486 if (callback != null) {
2487 callback.error(R.string.conference_creation_failed, null);
2488 }
2489 return false;
2490 }
2491 } else {
2492 if (callback != null) {
2493 callback.error(R.string.not_connected_try_again, null);
2494 }
2495 return false;
2496 }
2497 }
2498
2499 public void fetchConferenceConfiguration(final Conversation conversation) {
2500 fetchConferenceConfiguration(conversation, null);
2501 }
2502
2503 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2504 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2505 request.setTo(conversation.getJid().toBareJid());
2506 request.query("http://jabber.org/protocol/disco#info");
2507 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2508 @Override
2509 public void onIqPacketReceived(Account account, IqPacket packet) {
2510 Element query = packet.findChild("query", "http://jabber.org/protocol/disco#info");
2511 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2512 ArrayList<String> features = new ArrayList<>();
2513 for (Element child : query.getChildren()) {
2514 if (child != null && child.getName().equals("feature")) {
2515 String var = child.getAttribute("var");
2516 if (var != null) {
2517 features.add(var);
2518 }
2519 }
2520 }
2521 Element form = query.findChild("x", "jabber:x:data");
2522 if (form != null) {
2523 conversation.getMucOptions().updateFormData(Data.parse(form));
2524 }
2525 conversation.getMucOptions().updateFeatures(features);
2526 if (callback != null) {
2527 callback.onConferenceConfigurationFetched(conversation);
2528 }
2529 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetched muc configuration for " + conversation.getJid().toBareJid() + " - " + features.toString());
2530 updateConversationUi();
2531 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2532 if (callback != null) {
2533 callback.onFetchFailed(conversation, packet.getError());
2534 }
2535 }
2536 }
2537 });
2538 }
2539
2540 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2541 pushNodeConfiguration(account, account.getJid().toBareJid(), node, options, callback);
2542 }
2543
2544 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2545 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2546 @Override
2547 public void onIqPacketReceived(Account account, IqPacket packet) {
2548 if (packet.getType() == IqPacket.TYPE.RESULT) {
2549 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2550 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2551 Element x = configuration == null ? null : configuration.findChild("x", "jabber:x:data");
2552 if (x != null) {
2553 Data data = Data.parse(x);
2554 data.submit(options);
2555 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2556 @Override
2557 public void onIqPacketReceived(Account account, IqPacket packet) {
2558 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2559 callback.onPushSucceeded();
2560 } else {
2561 Log.d(Config.LOGTAG, packet.toString());
2562 }
2563 }
2564 });
2565 } else if (callback != null) {
2566 callback.onPushFailed();
2567 }
2568 } else if (callback != null) {
2569 callback.onPushFailed();
2570 }
2571 }
2572 });
2573 }
2574
2575 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2576 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2577 request.setTo(conversation.getJid().toBareJid());
2578 request.query("http://jabber.org/protocol/muc#owner");
2579 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2580 @Override
2581 public void onIqPacketReceived(Account account, IqPacket packet) {
2582 if (packet.getType() == IqPacket.TYPE.RESULT) {
2583 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2584 data.submit(options);
2585 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2586 set.setTo(conversation.getJid().toBareJid());
2587 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2588 sendIqPacket(account, set, new OnIqPacketReceived() {
2589 @Override
2590 public void onIqPacketReceived(Account account, IqPacket packet) {
2591 if (callback != null) {
2592 if (packet.getType() == IqPacket.TYPE.RESULT) {
2593 callback.onPushSucceeded();
2594 } else {
2595 callback.onPushFailed();
2596 }
2597 }
2598 }
2599 });
2600 } else {
2601 if (callback != null) {
2602 callback.onPushFailed();
2603 }
2604 }
2605 }
2606 });
2607 }
2608
2609 public void pushSubjectToConference(final Conversation conference, final String subject) {
2610 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2611 this.sendMessagePacket(conference.getAccount(), packet);
2612 final MucOptions mucOptions = conference.getMucOptions();
2613 final MucOptions.User self = mucOptions.getSelf();
2614 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2615 Bundle options = new Bundle();
2616 options.putString("muc#roomconfig_persistentroom", "1");
2617 this.pushConferenceConfiguration(conference, options, null);
2618 }
2619 }
2620
2621 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2622 final Jid jid = user.toBareJid();
2623 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2624 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2625 @Override
2626 public void onIqPacketReceived(Account account, IqPacket packet) {
2627 if (packet.getType() == IqPacket.TYPE.RESULT) {
2628 conference.getMucOptions().changeAffiliation(jid, affiliation);
2629 getAvatarService().clear(conference);
2630 callback.onAffiliationChangedSuccessful(jid);
2631 } else {
2632 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2633 }
2634 }
2635 });
2636 }
2637
2638 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2639 List<Jid> jids = new ArrayList<>();
2640 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2641 if (user.getAffiliation() == before && user.getRealJid() != null) {
2642 jids.add(user.getRealJid());
2643 }
2644 }
2645 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2646 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2647 }
2648
2649 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2650 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2651 Log.d(Config.LOGTAG, request.toString());
2652 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2653 @Override
2654 public void onIqPacketReceived(Account account, IqPacket packet) {
2655 Log.d(Config.LOGTAG, packet.toString());
2656 if (packet.getType() == IqPacket.TYPE.RESULT) {
2657 callback.onRoleChangedSuccessful(nick);
2658 } else {
2659 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2660 }
2661 }
2662 });
2663 }
2664
2665 private void disconnect(Account account, boolean force) {
2666 if ((account.getStatus() == Account.State.ONLINE)
2667 || (account.getStatus() == Account.State.DISABLED)) {
2668 final XmppConnection connection = account.getXmppConnection();
2669 if (!force) {
2670 List<Conversation> conversations = getConversations();
2671 for (Conversation conversation : conversations) {
2672 if (conversation.getAccount() == account) {
2673 if (conversation.getMode() == Conversation.MODE_MULTI) {
2674 leaveMuc(conversation, true);
2675 } else {
2676 if (conversation.endOtrIfNeeded()) {
2677 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2678 + ": ended otr session with "
2679 + conversation.getJid());
2680 }
2681 }
2682 }
2683 }
2684 sendOfflinePresence(account);
2685 }
2686 connection.disconnect(force);
2687 }
2688 }
2689
2690 @Override
2691 public IBinder onBind(Intent intent) {
2692 return mBinder;
2693 }
2694
2695 public void updateMessage(Message message) {
2696 databaseBackend.updateMessage(message);
2697 updateConversationUi();
2698 }
2699
2700 public void updateMessage(Message message, String uuid) {
2701 databaseBackend.updateMessage(message, uuid);
2702 updateConversationUi();
2703 }
2704
2705 protected void syncDirtyContacts(Account account) {
2706 for (Contact contact : account.getRoster().getContacts()) {
2707 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2708 pushContactToServer(contact);
2709 }
2710 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2711 deleteContactOnServer(contact);
2712 }
2713 }
2714 }
2715
2716 public void createContact(Contact contact) {
2717 boolean autoGrant = getBooleanPreference("grant_new_contacts", R.bool.grant_new_contacts);
2718 if (autoGrant) {
2719 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2720 contact.setOption(Contact.Options.ASKING);
2721 }
2722 pushContactToServer(contact);
2723 }
2724
2725 public void onOtrSessionEstablished(Conversation conversation) {
2726 final Account account = conversation.getAccount();
2727 final Session otrSession = conversation.getOtrSession();
2728 Log.d(Config.LOGTAG,
2729 account.getJid().toBareJid() + " otr session established with "
2730 + conversation.getJid() + "/"
2731 + otrSession.getSessionID().getUserID());
2732 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2733
2734 @Override
2735 public void onMessageFound(Message message) {
2736 SessionID id = otrSession.getSessionID();
2737 try {
2738 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2739 } catch (InvalidJidException e) {
2740 return;
2741 }
2742 if (message.needsUploading()) {
2743 mJingleConnectionManager.createNewConnection(message);
2744 } else {
2745 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2746 if (outPacket != null) {
2747 mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2748 message.setStatus(Message.STATUS_SEND);
2749 databaseBackend.updateMessage(message);
2750 sendMessagePacket(account, outPacket);
2751 }
2752 }
2753 updateConversationUi();
2754 }
2755 });
2756 }
2757
2758 public boolean renewSymmetricKey(Conversation conversation) {
2759 Account account = conversation.getAccount();
2760 byte[] symmetricKey = new byte[32];
2761 this.mRandom.nextBytes(symmetricKey);
2762 Session otrSession = conversation.getOtrSession();
2763 if (otrSession != null) {
2764 MessagePacket packet = new MessagePacket();
2765 packet.setType(MessagePacket.TYPE_CHAT);
2766 packet.setFrom(account.getJid());
2767 MessageGenerator.addMessageHints(packet);
2768 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2769 + otrSession.getSessionID().getUserID());
2770 try {
2771 packet.setBody(otrSession
2772 .transformSending(CryptoHelper.FILETRANSFER
2773 + CryptoHelper.bytesToHex(symmetricKey))[0]);
2774 sendMessagePacket(account, packet);
2775 conversation.setSymmetricKey(symmetricKey);
2776 return true;
2777 } catch (OtrException e) {
2778 return false;
2779 }
2780 }
2781 return false;
2782 }
2783
2784 public void pushContactToServer(final Contact contact) {
2785 contact.resetOption(Contact.Options.DIRTY_DELETE);
2786 contact.setOption(Contact.Options.DIRTY_PUSH);
2787 final Account account = contact.getAccount();
2788 if (account.getStatus() == Account.State.ONLINE) {
2789 final boolean ask = contact.getOption(Contact.Options.ASKING);
2790 final boolean sendUpdates = contact
2791 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2792 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2793 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2794 iq.query(Namespace.ROSTER).addChild(contact.asElement());
2795 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2796 if (sendUpdates) {
2797 sendPresencePacket(account,
2798 mPresenceGenerator.sendPresenceUpdatesTo(contact));
2799 }
2800 if (ask) {
2801 sendPresencePacket(account,
2802 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2803 }
2804 }
2805 }
2806
2807 public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2808 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2809 final int size = Config.AVATAR_SIZE;
2810 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2811 if (avatar != null) {
2812 avatar.height = size;
2813 avatar.width = size;
2814 if (format.equals(Bitmap.CompressFormat.WEBP)) {
2815 avatar.type = "image/webp";
2816 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2817 avatar.type = "image/jpeg";
2818 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
2819 avatar.type = "image/png";
2820 }
2821 if (!getFileBackend().save(avatar)) {
2822 callback.error(R.string.error_saving_avatar, avatar);
2823 return;
2824 }
2825 publishAvatar(account, avatar, callback);
2826 } else {
2827 callback.error(R.string.error_publish_avatar_converting, null);
2828 }
2829 }
2830
2831 public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2832 IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2833 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2834
2835 @Override
2836 public void onIqPacketReceived(Account account, IqPacket result) {
2837 if (result.getType() == IqPacket.TYPE.RESULT) {
2838 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2839 sendIqPacket(account, packet, new OnIqPacketReceived() {
2840 @Override
2841 public void onIqPacketReceived(Account account, IqPacket result) {
2842 if (result.getType() == IqPacket.TYPE.RESULT) {
2843 if (account.setAvatar(avatar.getFilename())) {
2844 getAvatarService().clear(account);
2845 databaseBackend.updateAccount(account);
2846 }
2847 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2848 if (callback != null) {
2849 callback.success(avatar);
2850 }
2851 } else {
2852 if (callback != null) {
2853 callback.error(R.string.error_publish_avatar_server_reject, avatar);
2854 }
2855 }
2856 }
2857 });
2858 } else {
2859 Element error = result.findChild("error");
2860 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2861 if (callback != null) {
2862 callback.error(R.string.error_publish_avatar_server_reject, avatar);
2863 }
2864 }
2865 }
2866 });
2867 }
2868
2869 public void republishAvatarIfNeeded(Account account) {
2870 if (account.getAxolotlService().isPepBroken()) {
2871 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": skipping republication of avatar because pep is broken");
2872 return;
2873 }
2874 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2875 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2876
2877 private Avatar parseAvatar(IqPacket packet) {
2878 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2879 if (pubsub != null) {
2880 Element items = pubsub.findChild("items");
2881 if (items != null) {
2882 return Avatar.parseMetadata(items);
2883 }
2884 }
2885 return null;
2886 }
2887
2888 private boolean errorIsItemNotFound(IqPacket packet) {
2889 Element error = packet.findChild("error");
2890 return packet.getType() == IqPacket.TYPE.ERROR
2891 && error != null
2892 && error.hasChild("item-not-found");
2893 }
2894
2895 @Override
2896 public void onIqPacketReceived(Account account, IqPacket packet) {
2897 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2898 Avatar serverAvatar = parseAvatar(packet);
2899 if (serverAvatar == null && account.getAvatar() != null) {
2900 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2901 if (avatar != null) {
2902 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": avatar on server was null. republishing");
2903 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2904 } else {
2905 Log.e(Config.LOGTAG, account.getJid().toBareJid() + ": error rereading avatar");
2906 }
2907 }
2908 }
2909 }
2910 });
2911 }
2912
2913 public void fetchAvatar(Account account, Avatar avatar) {
2914 fetchAvatar(account, avatar, null);
2915 }
2916
2917 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2918 final String KEY = generateFetchKey(account, avatar);
2919 synchronized (this.mInProgressAvatarFetches) {
2920 if (!this.mInProgressAvatarFetches.contains(KEY)) {
2921 switch (avatar.origin) {
2922 case PEP:
2923 this.mInProgressAvatarFetches.add(KEY);
2924 fetchAvatarPep(account, avatar, callback);
2925 break;
2926 case VCARD:
2927 this.mInProgressAvatarFetches.add(KEY);
2928 fetchAvatarVcard(account, avatar, callback);
2929 break;
2930 }
2931 }
2932 }
2933 }
2934
2935 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2936 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2937 sendIqPacket(account, packet, new OnIqPacketReceived() {
2938
2939 @Override
2940 public void onIqPacketReceived(Account account, IqPacket result) {
2941 synchronized (mInProgressAvatarFetches) {
2942 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2943 }
2944 final String ERROR = account.getJid().toBareJid()
2945 + ": fetching avatar for " + avatar.owner + " failed ";
2946 if (result.getType() == IqPacket.TYPE.RESULT) {
2947 avatar.image = mIqParser.avatarData(result);
2948 if (avatar.image != null) {
2949 if (getFileBackend().save(avatar)) {
2950 if (account.getJid().toBareJid().equals(avatar.owner)) {
2951 if (account.setAvatar(avatar.getFilename())) {
2952 databaseBackend.updateAccount(account);
2953 }
2954 getAvatarService().clear(account);
2955 updateConversationUi();
2956 updateAccountUi();
2957 } else {
2958 Contact contact = account.getRoster()
2959 .getContact(avatar.owner);
2960 contact.setAvatar(avatar);
2961 getAvatarService().clear(contact);
2962 updateConversationUi();
2963 updateRosterUi();
2964 }
2965 if (callback != null) {
2966 callback.success(avatar);
2967 }
2968 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2969 + ": successfully fetched pep avatar for " + avatar.owner);
2970 return;
2971 }
2972 } else {
2973
2974 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2975 }
2976 } else {
2977 Element error = result.findChild("error");
2978 if (error == null) {
2979 Log.d(Config.LOGTAG, ERROR + "(server error)");
2980 } else {
2981 Log.d(Config.LOGTAG, ERROR + error.toString());
2982 }
2983 }
2984 if (callback != null) {
2985 callback.error(0, null);
2986 }
2987
2988 }
2989 });
2990 }
2991
2992 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2993 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2994 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2995 @Override
2996 public void onIqPacketReceived(Account account, IqPacket packet) {
2997 synchronized (mInProgressAvatarFetches) {
2998 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2999 }
3000 if (packet.getType() == IqPacket.TYPE.RESULT) {
3001 Element vCard = packet.findChild("vCard", "vcard-temp");
3002 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3003 String image = photo != null ? photo.findChildContent("BINVAL") : null;
3004 if (image != null) {
3005 avatar.image = image;
3006 if (getFileBackend().save(avatar)) {
3007 Log.d(Config.LOGTAG, account.getJid().toBareJid()
3008 + ": successfully fetched vCard avatar for " + avatar.owner);
3009 if (avatar.owner.isBareJid()) {
3010 if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3011 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": had no avatar. replacing with vcard");
3012 account.setAvatar(avatar.getFilename());
3013 databaseBackend.updateAccount(account);
3014 getAvatarService().clear(account);
3015 updateAccountUi();
3016 } else {
3017 Contact contact = account.getRoster().getContact(avatar.owner);
3018 contact.setAvatar(avatar);
3019 getAvatarService().clear(contact);
3020 updateRosterUi();
3021 }
3022 updateConversationUi();
3023 } else {
3024 Conversation conversation = find(account, avatar.owner.toBareJid());
3025 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3026 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3027 if (user != null) {
3028 if (user.setAvatar(avatar)) {
3029 getAvatarService().clear(user);
3030 updateConversationUi();
3031 updateMucRosterUi();
3032 }
3033 }
3034 }
3035 }
3036 }
3037 }
3038 }
3039 }
3040 });
3041 }
3042
3043 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3044 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3045 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3046
3047 @Override
3048 public void onIqPacketReceived(Account account, IqPacket packet) {
3049 if (packet.getType() == IqPacket.TYPE.RESULT) {
3050 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3051 if (pubsub != null) {
3052 Element items = pubsub.findChild("items");
3053 if (items != null) {
3054 Avatar avatar = Avatar.parseMetadata(items);
3055 if (avatar != null) {
3056 avatar.owner = account.getJid().toBareJid();
3057 if (fileBackend.isAvatarCached(avatar)) {
3058 if (account.setAvatar(avatar.getFilename())) {
3059 databaseBackend.updateAccount(account);
3060 }
3061 getAvatarService().clear(account);
3062 callback.success(avatar);
3063 } else {
3064 fetchAvatarPep(account, avatar, callback);
3065 }
3066 return;
3067 }
3068 }
3069 }
3070 }
3071 callback.error(0, null);
3072 }
3073 });
3074 }
3075
3076 public void deleteContactOnServer(Contact contact) {
3077 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3078 contact.resetOption(Contact.Options.DIRTY_PUSH);
3079 contact.setOption(Contact.Options.DIRTY_DELETE);
3080 Account account = contact.getAccount();
3081 if (account.getStatus() == Account.State.ONLINE) {
3082 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3083 Element item = iq.query(Namespace.ROSTER).addChild("item");
3084 item.setAttribute("jid", contact.getJid().toString());
3085 item.setAttribute("subscription", "remove");
3086 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3087 }
3088 }
3089
3090 public void updateConversation(final Conversation conversation) {
3091 mDatabaseWriterExecutor.execute(new Runnable() {
3092 @Override
3093 public void run() {
3094 databaseBackend.updateConversation(conversation);
3095 }
3096 });
3097 }
3098
3099 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3100 synchronized (account) {
3101 XmppConnection connection = account.getXmppConnection();
3102 if (connection == null) {
3103 connection = createConnection(account);
3104 account.setXmppConnection(connection);
3105 }
3106 boolean hasInternet = hasInternetConnection();
3107 if (account.isEnabled() && hasInternet) {
3108 if (!force) {
3109 disconnect(account, false);
3110 }
3111 Thread thread = new Thread(connection);
3112 connection.setInteractive(interactive);
3113 connection.prepareNewConnection();
3114 connection.interrupt();
3115 thread.start();
3116 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3117 } else {
3118 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3119 account.getRoster().clearPresences();
3120 connection.resetEverything();
3121 final AxolotlService axolotlService = account.getAxolotlService();
3122 if (axolotlService != null) {
3123 axolotlService.resetBrokenness();
3124 }
3125 if (!hasInternet) {
3126 account.setStatus(Account.State.NO_INTERNET);
3127 }
3128 }
3129 }
3130 }
3131
3132 public void reconnectAccountInBackground(final Account account) {
3133 new Thread(new Runnable() {
3134 @Override
3135 public void run() {
3136 reconnectAccount(account, false, true);
3137 }
3138 }).start();
3139 }
3140
3141 public void invite(Conversation conversation, Jid contact) {
3142 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
3143 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3144 sendMessagePacket(conversation.getAccount(), packet);
3145 }
3146
3147 public void directInvite(Conversation conversation, Jid jid) {
3148 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3149 sendMessagePacket(conversation.getAccount(), packet);
3150 }
3151
3152 public void resetSendingToWaiting(Account account) {
3153 for (Conversation conversation : getConversations()) {
3154 if (conversation.getAccount() == account) {
3155 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3156
3157 @Override
3158 public void onMessageFound(Message message) {
3159 markMessage(message, Message.STATUS_WAITING);
3160 }
3161 });
3162 }
3163 }
3164 }
3165
3166 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3167 return markMessage(account, recipient, uuid, status, null);
3168 }
3169
3170 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3171 if (uuid == null) {
3172 return null;
3173 }
3174 for (Conversation conversation : getConversations()) {
3175 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
3176 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3177 if (message != null) {
3178 markMessage(message, status, errorMessage);
3179 }
3180 return message;
3181 }
3182 }
3183 return null;
3184 }
3185
3186 public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3187 if (uuid == null) {
3188 return false;
3189 } else {
3190 Message message = conversation.findSentMessageWithUuid(uuid);
3191 if (message != null) {
3192 if (message.getServerMsgId() == null) {
3193 message.setServerMsgId(serverMessageId);
3194 }
3195 markMessage(message, status);
3196 return true;
3197 } else {
3198 return false;
3199 }
3200 }
3201 }
3202
3203 public void markMessage(Message message, int status) {
3204 markMessage(message, status, null);
3205 }
3206
3207
3208 public void markMessage(Message message, int status, String errorMessage) {
3209 if (status == Message.STATUS_SEND_FAILED
3210 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
3211 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
3212 return;
3213 }
3214 message.setErrorMessage(errorMessage);
3215 message.setStatus(status);
3216 databaseBackend.updateMessage(message);
3217 updateConversationUi();
3218 }
3219
3220 private SharedPreferences getPreferences() {
3221 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3222 }
3223
3224 public long getAutomaticMessageDeletionDate() {
3225 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3226 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3227 }
3228
3229 public long getLongPreference(String name, @IntegerRes int res) {
3230 long defaultValue = getResources().getInteger(res);
3231 try {
3232 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3233 } catch (NumberFormatException e) {
3234 return defaultValue;
3235 }
3236 }
3237
3238 public boolean getBooleanPreference(String name, @BoolRes int res) {
3239 return getPreferences().getBoolean(name, getResources().getBoolean(res));
3240 }
3241
3242 public boolean confirmMessages() {
3243 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3244 }
3245
3246 public boolean allowMessageCorrection() {
3247 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3248 }
3249
3250 public boolean sendChatStates() {
3251 return getBooleanPreference("chat_states", R.bool.chat_states);
3252 }
3253
3254 private boolean respectAutojoin() {
3255 return getBooleanPreference("autojoin", R.bool.autojoin);
3256 }
3257
3258 public boolean indicateReceived() {
3259 return getBooleanPreference("indicate_received", R.bool.indicate_received);
3260 }
3261
3262 public boolean useTorToConnect() {
3263 return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3264 }
3265
3266 public boolean showExtendedConnectionOptions() {
3267 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3268 }
3269
3270 public boolean broadcastLastActivity() {
3271 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3272 }
3273
3274 public int unreadCount() {
3275 int count = 0;
3276 for (Conversation conversation : getConversations()) {
3277 count += conversation.unreadCount();
3278 }
3279 return count;
3280 }
3281
3282
3283 public void showErrorToastInUi(int resId) {
3284 if (mOnShowErrorToast != null) {
3285 mOnShowErrorToast.onShowErrorToast(resId);
3286 }
3287 }
3288
3289 public void updateConversationUi() {
3290 if (mOnConversationUpdate != null) {
3291 mOnConversationUpdate.onConversationUpdate();
3292 }
3293 }
3294
3295 public void updateAccountUi() {
3296 if (mOnAccountUpdate != null) {
3297 mOnAccountUpdate.onAccountUpdate();
3298 }
3299 }
3300
3301 public void updateRosterUi() {
3302 if (mOnRosterUpdate != null) {
3303 mOnRosterUpdate.onRosterUpdate();
3304 }
3305 }
3306
3307 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3308 if (mOnCaptchaRequested != null) {
3309 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3310 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3311 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3312
3313 mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3314 return true;
3315 }
3316 return false;
3317 }
3318
3319 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3320 if (mOnUpdateBlocklist != null) {
3321 mOnUpdateBlocklist.OnUpdateBlocklist(status);
3322 }
3323 }
3324
3325 public void updateMucRosterUi() {
3326 if (mOnMucRosterUpdate != null) {
3327 mOnMucRosterUpdate.onMucRosterUpdate();
3328 }
3329 }
3330
3331 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3332 if (mOnKeyStatusUpdated != null) {
3333 mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3334 }
3335 }
3336
3337 public Account findAccountByJid(final Jid accountJid) {
3338 for (Account account : this.accounts) {
3339 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3340 return account;
3341 }
3342 }
3343 return null;
3344 }
3345
3346 public Conversation findConversationByUuid(String uuid) {
3347 for (Conversation conversation : getConversations()) {
3348 if (conversation.getUuid().equals(uuid)) {
3349 return conversation;
3350 }
3351 }
3352 return null;
3353 }
3354
3355 public boolean markRead(final Conversation conversation) {
3356 return markRead(conversation, true);
3357 }
3358
3359 public boolean markRead(final Conversation conversation, boolean clear) {
3360 if (clear) {
3361 mNotificationService.clear(conversation);
3362 }
3363 final List<Message> readMessages = conversation.markRead();
3364 if (readMessages.size() > 0) {
3365 Runnable runnable = new Runnable() {
3366 @Override
3367 public void run() {
3368 for (Message message : readMessages) {
3369 databaseBackend.updateMessage(message);
3370 }
3371 }
3372 };
3373 mDatabaseWriterExecutor.execute(runnable);
3374 updateUnreadCountBadge();
3375 return true;
3376 } else {
3377 return false;
3378 }
3379 }
3380
3381 public synchronized void updateUnreadCountBadge() {
3382 int count = unreadCount();
3383 if (unreadCount != count) {
3384 Log.d(Config.LOGTAG, "update unread count to " + count);
3385 if (count > 0) {
3386 ShortcutBadger.applyCount(getApplicationContext(), count);
3387 } else {
3388 ShortcutBadger.removeCount(getApplicationContext());
3389 }
3390 unreadCount = count;
3391 }
3392 }
3393
3394 public void sendReadMarker(final Conversation conversation) {
3395 final Message markable = conversation.getLatestMarkableMessage();
3396 if (this.markRead(conversation)) {
3397 updateConversationUi();
3398 }
3399 if (confirmMessages()
3400 && markable != null
3401 && markable.trusted()
3402 && markable.getRemoteMsgId() != null
3403 && markable.getType() != Message.TYPE_PRIVATE) {
3404 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3405 Account account = conversation.getAccount();
3406 final Jid to = markable.getCounterpart();
3407 final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3408 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3409 this.sendMessagePacket(conversation.getAccount(), packet);
3410 }
3411 }
3412
3413 public SecureRandom getRNG() {
3414 return this.mRandom;
3415 }
3416
3417 public MemorizingTrustManager getMemorizingTrustManager() {
3418 return this.mMemorizingTrustManager;
3419 }
3420
3421 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3422 this.mMemorizingTrustManager = trustManager;
3423 }
3424
3425 public void updateMemorizingTrustmanager() {
3426 final MemorizingTrustManager tm;
3427 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3428 if (dontTrustSystemCAs) {
3429 tm = new MemorizingTrustManager(getApplicationContext(), null);
3430 } else {
3431 tm = new MemorizingTrustManager(getApplicationContext());
3432 }
3433 setMemorizingTrustManager(tm);
3434 }
3435
3436 public PowerManager getPowerManager() {
3437 return this.pm;
3438 }
3439
3440 public LruCache<String, Bitmap> getBitmapCache() {
3441 return this.mBitmapCache;
3442 }
3443
3444 public void syncRosterToDisk(final Account account) {
3445 Runnable runnable = new Runnable() {
3446
3447 @Override
3448 public void run() {
3449 databaseBackend.writeRoster(account.getRoster());
3450 }
3451 };
3452 mDatabaseWriterExecutor.execute(runnable);
3453
3454 }
3455
3456 public List<String> getKnownHosts() {
3457 final List<String> hosts = new ArrayList<>();
3458 for (final Account account : getAccounts()) {
3459 if (!hosts.contains(account.getServer().toString())) {
3460 hosts.add(account.getServer().toString());
3461 }
3462 for (final Contact contact : account.getRoster().getContacts()) {
3463 if (contact.showInRoster()) {
3464 final String server = contact.getServer().toString();
3465 if (server != null && !hosts.contains(server)) {
3466 hosts.add(server);
3467 }
3468 }
3469 }
3470 }
3471 if (Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3472 hosts.add(Config.DOMAIN_LOCK);
3473 }
3474 if (Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3475 hosts.add(Config.MAGIC_CREATE_DOMAIN);
3476 }
3477 return hosts;
3478 }
3479
3480 public List<String> getKnownConferenceHosts() {
3481 final ArrayList<String> mucServers = new ArrayList<>();
3482 for (final Account account : accounts) {
3483 if (account.getXmppConnection() != null) {
3484 final String server = account.getXmppConnection().getMucServer();
3485 if (server != null && !mucServers.contains(server)) {
3486 mucServers.add(server);
3487 }
3488 for (Bookmark bookmark : account.getBookmarks()) {
3489 final Jid jid = bookmark.getJid();
3490 final String s = jid == null ? null : jid.getDomainpart();
3491 if (s != null && !mucServers.contains(s)) {
3492 mucServers.add(s);
3493 }
3494 }
3495 }
3496 }
3497 return mucServers;
3498 }
3499
3500 public void sendMessagePacket(Account account, MessagePacket packet) {
3501 XmppConnection connection = account.getXmppConnection();
3502 if (connection != null) {
3503 connection.sendMessagePacket(packet);
3504 }
3505 }
3506
3507 public void sendPresencePacket(Account account, PresencePacket packet) {
3508 XmppConnection connection = account.getXmppConnection();
3509 if (connection != null) {
3510 connection.sendPresencePacket(packet);
3511 }
3512 }
3513
3514 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3515 final XmppConnection connection = account.getXmppConnection();
3516 if (connection != null) {
3517 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3518 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3519 }
3520 }
3521
3522 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3523 final XmppConnection connection = account.getXmppConnection();
3524 if (connection != null) {
3525 connection.sendIqPacket(packet, callback);
3526 }
3527 }
3528
3529 public void sendPresence(final Account account) {
3530 sendPresence(account, checkListeners() && broadcastLastActivity());
3531 }
3532
3533 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3534 PresencePacket packet;
3535 if (manuallyChangePresence()) {
3536 packet = mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3537 String message = account.getPresenceStatusMessage();
3538 if (message != null && !message.isEmpty()) {
3539 packet.addChild(new Element("status").setContent(message));
3540 }
3541 } else {
3542 packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3543 }
3544 if (mLastActivity > 0 && includeIdleTimestamp) {
3545 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3546 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3547 }
3548 sendPresencePacket(account, packet);
3549 }
3550
3551 private void deactivateGracePeriod() {
3552 for (Account account : getAccounts()) {
3553 account.deactivateGracePeriod();
3554 }
3555 }
3556
3557 public void refreshAllPresences() {
3558 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3559 for (Account account : getAccounts()) {
3560 if (account.isEnabled()) {
3561 sendPresence(account, includeIdleTimestamp);
3562 }
3563 }
3564 }
3565
3566 private void refreshAllGcmTokens() {
3567 for (Account account : getAccounts()) {
3568 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3569 mPushManagementService.registerPushTokenOnServer(account);
3570 }
3571 }
3572 }
3573
3574 private void sendOfflinePresence(final Account account) {
3575 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending offline presence");
3576 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3577 }
3578
3579 public MessageGenerator getMessageGenerator() {
3580 return this.mMessageGenerator;
3581 }
3582
3583 public PresenceGenerator getPresenceGenerator() {
3584 return this.mPresenceGenerator;
3585 }
3586
3587 public IqGenerator getIqGenerator() {
3588 return this.mIqGenerator;
3589 }
3590
3591 public IqParser getIqParser() {
3592 return this.mIqParser;
3593 }
3594
3595 public JingleConnectionManager getJingleConnectionManager() {
3596 return this.mJingleConnectionManager;
3597 }
3598
3599 public MessageArchiveService getMessageArchiveService() {
3600 return this.mMessageArchiveService;
3601 }
3602
3603 public List<Contact> findContacts(Jid jid, String accountJid) {
3604 ArrayList<Contact> contacts = new ArrayList<>();
3605 for (Account account : getAccounts()) {
3606 if ((account.isEnabled() || accountJid != null)
3607 && (accountJid == null || accountJid.equals(account.getJid().toBareJid().toString()))) {
3608 Contact contact = account.getRoster().getContactFromRoster(jid);
3609 if (contact != null) {
3610 contacts.add(contact);
3611 }
3612 }
3613 }
3614 return contacts;
3615 }
3616
3617 public Conversation findFirstMuc(Jid jid) {
3618 for (Conversation conversation : getConversations()) {
3619 if (conversation.getAccount().isEnabled() && conversation.getJid().toBareJid().equals(jid.toBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3620 return conversation;
3621 }
3622 }
3623 return null;
3624 }
3625
3626 public NotificationService getNotificationService() {
3627 return this.mNotificationService;
3628 }
3629
3630 public HttpConnectionManager getHttpConnectionManager() {
3631 return this.mHttpConnectionManager;
3632 }
3633
3634 public void resendFailedMessages(final Message message) {
3635 final Collection<Message> messages = new ArrayList<>();
3636 Message current = message;
3637 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3638 messages.add(current);
3639 if (current.mergeable(current.next())) {
3640 current = current.next();
3641 } else {
3642 break;
3643 }
3644 }
3645 for (final Message msg : messages) {
3646 msg.setTime(System.currentTimeMillis());
3647 markMessage(msg, Message.STATUS_WAITING);
3648 this.resendMessage(msg, false);
3649 }
3650 }
3651
3652 public void clearConversationHistory(final Conversation conversation) {
3653 final long clearDate;
3654 final String reference;
3655 if (conversation.countMessages() > 0) {
3656 Message latestMessage = conversation.getLatestMessage();
3657 clearDate = latestMessage.getTimeSent() + 1000;
3658 reference = latestMessage.getServerMsgId();
3659 } else {
3660 clearDate = System.currentTimeMillis();
3661 reference = null;
3662 }
3663 conversation.clearMessages();
3664 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3665 conversation.setLastClearHistory(clearDate, reference);
3666 Runnable runnable = new Runnable() {
3667 @Override
3668 public void run() {
3669 databaseBackend.deleteMessagesInConversation(conversation);
3670 databaseBackend.updateConversation(conversation);
3671 }
3672 };
3673 mDatabaseWriterExecutor.execute(runnable);
3674 }
3675
3676 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3677 if (blockable != null && blockable.getBlockedJid() != null) {
3678 final Jid jid = blockable.getBlockedJid();
3679 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3680
3681 @Override
3682 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3683 if (packet.getType() == IqPacket.TYPE.RESULT) {
3684 account.getBlocklist().add(jid);
3685 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3686 }
3687 }
3688 });
3689 if (removeBlockedConversations(blockable.getAccount(), jid)) {
3690 updateConversationUi();
3691 return true;
3692 } else {
3693 return false;
3694 }
3695 } else {
3696 return false;
3697 }
3698 }
3699
3700 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3701 boolean removed = false;
3702 synchronized (this.conversations) {
3703 boolean domainJid = blockedJid.isDomainJid();
3704 for (Conversation conversation : this.conversations) {
3705 boolean jidMatches = (domainJid && blockedJid.getDomainpart().equals(conversation.getJid().getDomainpart()))
3706 || blockedJid.equals(conversation.getJid().toBareJid());
3707 if (conversation.getAccount() == account
3708 && conversation.getMode() == Conversation.MODE_SINGLE
3709 && jidMatches) {
3710 this.conversations.remove(conversation);
3711 markRead(conversation);
3712 conversation.setStatus(Conversation.STATUS_ARCHIVED);
3713 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": archiving conversation " + conversation.getJid().toBareJid() + " because jid was blocked");
3714 updateConversation(conversation);
3715 removed = true;
3716 }
3717 }
3718 }
3719 return removed;
3720 }
3721
3722 public void sendUnblockRequest(final Blockable blockable) {
3723 if (blockable != null && blockable.getJid() != null) {
3724 final Jid jid = blockable.getBlockedJid();
3725 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3726 @Override
3727 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3728 if (packet.getType() == IqPacket.TYPE.RESULT) {
3729 account.getBlocklist().remove(jid);
3730 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3731 }
3732 }
3733 });
3734 }
3735 }
3736
3737 public void publishDisplayName(Account account) {
3738 String displayName = account.getDisplayName();
3739 if (displayName != null && !displayName.isEmpty()) {
3740 IqPacket publish = mIqGenerator.publishNick(displayName);
3741 sendIqPacket(account, publish, new OnIqPacketReceived() {
3742 @Override
3743 public void onIqPacketReceived(Account account, IqPacket packet) {
3744 if (packet.getType() == IqPacket.TYPE.ERROR) {
3745 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3746 }
3747 }
3748 });
3749 }
3750 }
3751
3752 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3753 ServiceDiscoveryResult result = discoCache.get(key);
3754 if (result != null) {
3755 return result;
3756 } else {
3757 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3758 if (result != null) {
3759 discoCache.put(key, result);
3760 }
3761 return result;
3762 }
3763 }
3764
3765 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3766 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3767 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3768 if (disco != null) {
3769 presence.setServiceDiscoveryResult(disco);
3770 } else {
3771 if (!account.inProgressDiscoFetches.contains(key)) {
3772 account.inProgressDiscoFetches.add(key);
3773 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3774 request.setTo(jid);
3775 request.query("http://jabber.org/protocol/disco#info");
3776 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": making disco request for " + key.second + " to " + jid);
3777 sendIqPacket(account, request, new OnIqPacketReceived() {
3778 @Override
3779 public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3780 if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3781 ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3782 if (presence.getVer().equals(disco.getVer())) {
3783 databaseBackend.insertDiscoveryResult(disco);
3784 injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3785 } else {
3786 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3787 }
3788 }
3789 account.inProgressDiscoFetches.remove(key);
3790 }
3791 });
3792 }
3793 }
3794 }
3795
3796 private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3797 for (Contact contact : roster.getContacts()) {
3798 for (Presence presence : contact.getPresences().getPresences().values()) {
3799 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3800 presence.setServiceDiscoveryResult(disco);
3801 }
3802 }
3803 }
3804 }
3805
3806 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3807 final boolean legacy = account.getXmppConnection().getFeatures().mamLegacy();
3808 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3809 request.addChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3810 sendIqPacket(account, request, new OnIqPacketReceived() {
3811 @Override
3812 public void onIqPacketReceived(Account account, IqPacket packet) {
3813 Element prefs = packet.findChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3814 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3815 callback.onPreferencesFetched(prefs);
3816 } else {
3817 callback.onPreferencesFetchFailed();
3818 }
3819 }
3820 });
3821 }
3822
3823 public PushManagementService getPushManagementService() {
3824 return mPushManagementService;
3825 }
3826
3827 public Account getPendingAccount() {
3828 Account pending = null;
3829 for (Account account : getAccounts()) {
3830 if (account.isOptionSet(Account.OPTION_REGISTER)) {
3831 pending = account;
3832 } else {
3833 return null;
3834 }
3835 }
3836 return pending;
3837 }
3838
3839 public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3840 if (!statusMessage.isEmpty()) {
3841 databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3842 }
3843 changeStatusReal(account, status, statusMessage, send);
3844 }
3845
3846 private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3847 account.setPresenceStatus(status);
3848 account.setPresenceStatusMessage(statusMessage);
3849 databaseBackend.updateAccount(account);
3850 if (account.isEnabled() && send) {
3851 sendPresence(account);
3852 }
3853 }
3854
3855 public void changeStatus(Presence.Status status, String statusMessage) {
3856 if (!statusMessage.isEmpty()) {
3857 databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3858 }
3859 for (Account account : getAccounts()) {
3860 changeStatusReal(account, status, statusMessage, true);
3861 }
3862 }
3863
3864 public List<PresenceTemplate> getPresenceTemplates(Account account) {
3865 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3866 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3867 if (!templates.contains(template)) {
3868 templates.add(0, template);
3869 }
3870 }
3871 return templates;
3872 }
3873
3874 public void saveConversationAsBookmark(Conversation conversation, String name) {
3875 Account account = conversation.getAccount();
3876 Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3877 if (!conversation.getJid().isBareJid()) {
3878 bookmark.setNick(conversation.getJid().getResourcepart());
3879 }
3880 if (name != null && !name.trim().isEmpty()) {
3881 bookmark.setBookmarkName(name.trim());
3882 }
3883 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3884 account.getBookmarks().add(bookmark);
3885 pushBookmarks(account);
3886 conversation.setBookmark(bookmark);
3887 }
3888
3889 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3890 boolean needsRosterWrite = false;
3891 boolean performedVerification = false;
3892 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3893 for (XmppUri.Fingerprint fp : fingerprints) {
3894 if (fp.type == XmppUri.FingerprintType.OTR) {
3895 performedVerification |= contact.addOtrFingerprint(fp.fingerprint);
3896 needsRosterWrite |= performedVerification;
3897 } else if (fp.type == XmppUri.FingerprintType.OMEMO) {
3898 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3899 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3900 if (fingerprintStatus != null) {
3901 if (!fingerprintStatus.isVerified()) {
3902 performedVerification = true;
3903 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3904 }
3905 } else {
3906 axolotlService.preVerifyFingerprint(contact, fingerprint);
3907 }
3908 }
3909 }
3910 if (needsRosterWrite) {
3911 syncRosterToDisk(contact.getAccount());
3912 }
3913 return performedVerification;
3914 }
3915
3916 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3917 final AxolotlService axolotlService = account.getAxolotlService();
3918 boolean verifiedSomething = false;
3919 for (XmppUri.Fingerprint fp : fingerprints) {
3920 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3921 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3922 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3923 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3924 if (fingerprintStatus != null) {
3925 if (!fingerprintStatus.isVerified()) {
3926 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3927 verifiedSomething = true;
3928 }
3929 } else {
3930 axolotlService.preVerifyFingerprint(account, fingerprint);
3931 verifiedSomething = true;
3932 }
3933 }
3934 }
3935 return verifiedSomething;
3936 }
3937
3938 public boolean blindTrustBeforeVerification() {
3939 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
3940 }
3941
3942 public ShortcutService getShortcutService() {
3943 return mShortcutService;
3944 }
3945
3946 public interface OnMamPreferencesFetched {
3947 void onPreferencesFetched(Element prefs);
3948
3949 void onPreferencesFetchFailed();
3950 }
3951
3952 public void pushMamPreferences(Account account, Element prefs) {
3953 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3954 set.addChild(prefs);
3955 sendIqPacket(account, set, null);
3956 }
3957
3958 public interface OnAccountCreated {
3959 void onAccountCreated(Account account);
3960
3961 void informUser(int r);
3962 }
3963
3964 public interface OnMoreMessagesLoaded {
3965 void onMoreMessagesLoaded(int count, Conversation conversation);
3966
3967 void informUser(int r);
3968 }
3969
3970 public interface OnAccountPasswordChanged {
3971 void onPasswordChangeSucceeded();
3972
3973 void onPasswordChangeFailed();
3974 }
3975
3976 public interface OnAffiliationChanged {
3977 void onAffiliationChangedSuccessful(Jid jid);
3978
3979 void onAffiliationChangeFailed(Jid jid, int resId);
3980 }
3981
3982 public interface OnRoleChanged {
3983 void onRoleChangedSuccessful(String nick);
3984
3985 void onRoleChangeFailed(String nick, int resid);
3986 }
3987
3988 public interface OnConversationUpdate {
3989 void onConversationUpdate();
3990 }
3991
3992 public interface OnAccountUpdate {
3993 void onAccountUpdate();
3994 }
3995
3996 public interface OnCaptchaRequested {
3997 void onCaptchaRequested(Account account,
3998 String id,
3999 Data data,
4000 Bitmap captcha);
4001 }
4002
4003 public interface OnRosterUpdate {
4004 void onRosterUpdate();
4005 }
4006
4007 public interface OnMucRosterUpdate {
4008 void onMucRosterUpdate();
4009 }
4010
4011 public interface OnConferenceConfigurationFetched {
4012 void onConferenceConfigurationFetched(Conversation conversation);
4013
4014 void onFetchFailed(Conversation conversation, Element error);
4015 }
4016
4017 public interface OnConferenceJoined {
4018 void onConferenceJoined(Conversation conversation);
4019 }
4020
4021 public interface OnConfigurationPushed {
4022 void onPushSucceeded();
4023
4024 void onPushFailed();
4025 }
4026
4027 public interface OnShowErrorToast {
4028 void onShowErrorToast(int resId);
4029 }
4030
4031 public class XmppConnectionBinder extends Binder {
4032 public XmppConnectionService getService() {
4033 return XmppConnectionService.this;
4034 }
4035 }
4036}