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