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