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