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