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