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