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