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