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